diff --git "a/071.jsonl" "b/071.jsonl" new file mode 100644--- /dev/null +++ "b/071.jsonl" @@ -0,0 +1,456 @@ +{"seq_id":"17113956884","text":"# -*- coding: utf-8 -*-\n\"\"\"\n tests/api/promo_codes_endpoints_test\n ~~~~~\n\n PromoCodes API endpoints tests\n\"\"\"\nfrom hamcrest import *\nimport mock\n\nimport json\n\nfrom tests.conftest import mock_jwt_required\nfrom videona_platform.promo_codes import models as promo_codes_models\nfrom videona_platform.api.promo_codes import validate_promo_code\nfrom videona_platform.promo_codes.promo_codes_service import PromoCodeValidationError\n\n\nclass TestPromoCodesEndpoints(object):\n @mock.patch('videona_platform.api.promo_codes.jsonify', mock.Mock())\n @mock.patch('flask_jwt._jwt_required', mock.Mock(side_effect=mock_jwt_required))\n @mock.patch('videona_platform.api.promo_codes.current_identity')\n @mock.patch('videona_platform.promo_codes.promo_codes_service.promo_codes_service.validate_code')\n def test_validate_calls_service(self, validate_code, current_identity, push_context):\n\n validate_promo_code('kode')\n\n validate_code.assert_called_once_with('kode', current_identity)\n\n @mock.patch('flask_jwt._jwt_required', mock.Mock(side_effect=mock_jwt_required))\n @mock.patch('videona_platform.promo_codes.promo_codes_service.promo_codes_service.first')\n def test_validate_returns_error_if_no_code(self, first, api_app):\n with api_app.test_request_context():\n first.return_value = None\n\n response, status_code = validate_promo_code('notfoundcode')\n\n assert_that(status_code, is_(404))\n assert_that(json.loads(response.data), is_({'valid_code': False, 'campaign': '', 'error': PromoCodeValidationError.MSG_CODE_NOT_FOUND}))\n\n @mock.patch('flask_jwt._jwt_required', mock.Mock(side_effect=mock_jwt_required))\n @mock.patch('videona_platform.api.promo_codes.current_identity', None)\n @mock.patch('videona_platform.promo_codes.promo_codes_service.promo_codes_service.first')\n def test_validate_returns_valid_code_response_if_code_validates(self, first, session, api_app):\n with api_app.test_request_context():\n code = promo_codes_models.PromoCode(code='code', campaign='wolder')\n first.return_value = code\n\n response, status_code = validate_promo_code(code_string='code')\n\n assert_that(status_code, is_(200))\n assert_that(json.loads(response.data), is_({'valid_code': True, 'campaign': 'wolder'}))\n","repo_name":"IAgof/VideonaPlatform","sub_path":"tests/api/promo_codes_endpoints_test.py","file_name":"promo_codes_endpoints_test.py","file_ext":"py","file_size_in_byte":2350,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"23097576742","text":"import pandas as pd\n#from html.parser import HTMLParser\n#from collections import defaultdict\n#import urllib.request\nimport tempfile\nimport pickle\nimport requests\nfrom lxml import etree\nimport shutil\nimport os.path as osp\nfrom pprint import pprint\nimport datetime\nimport re\nimport os\n\nclass Parser(object):\n def __init__(self,queries=('חיפה',)):\n\n #self.debug = True\n self.debug = False\n if type(queries) is str:\n queries = (queries,)\n self.queries = queries\n self.addr_prefix = 'https://www.gov.il/he/departments/news/'\n\n save_dir = './' #\n s_queries = '_'.join(queries)\n self.tar_fname = osp.join(save_dir,'govil_parse_{}_{}'.format(datetime.datetime.now().strftime('%d%m%y_%Hh'),s_queries))\n self.tar_fname_recent = osp.join(save_dir,'govil_parse_{}_{}'.format('recent', s_queries))\n print('target file name: {}'.format(self.tar_fname))\n self.res_data = None\n def get_addresses(self):\n start_date = datetime.datetime(day=1,month=3,year=2020)\n end_date = datetime.datetime.now()\n delta = datetime.timedelta(days=1)\n cur = start_date\n err_msg = 'לא מצאנו את מה שחיפשת.'\n #addresses = []\n html = None\n while cur <= end_date:\n dd = cur.day\n mm = cur.month\n yyyy = cur.year\n for num in range(1,100): # no more than 100 updates per day\n url = '{}{:02d}{:02d}{:04d}_{:02d}'.format(self.addr_prefix, dd,mm,yyyy, num)\n success = False\n seek_next_page = False\n for tries in range(3):\n try:\n print('try {}, checking {}...'.format(tries, url))\n html = requests.get(url).text\n if err_msg in html:\n print('no page')\n seek_next_page = True\n pass\n else:\n success = True\n break\n except Exception as e:\n print(e)\n if success:\n yield html, url\n #addresses.append(url)\n if seek_next_page:\n break\n\n cur += delta\n #return addresses\n\n def parse_details(self,s=None,url='',patient=-1):\n date = re.findall('\\d\\d\\.\\d\\d\\.\\d\\d\\d\\d',s)\n hours = re.findall('\\d\\d:\\d\\d',s)\n return dict(date=date,hours=hours,text=s,url=url,patient=patient)\n\n def read_page(self, html=None, addr='https://www.gov.il/he/departments/news/20032020_04'):\n if html is None:\n html = requests.get(addr).text\n debug=True\n else:\n debug=False\n dom = etree.HTML(html)\n text = dom.xpath('//div[@id=\"NewsContent\"]/p/node()')\n dat = []\n cur_patient=-1\n for line in text:\n if type(line) is not etree._Element: # i.e. string with details\n if any([q in line for q in self.queries]):\n di = self.parse_details(line,addr,patient=cur_patient)\n print('patient: {}, date: {}, times: {}, all: {}'.format(di['patient'], di['date'], di['hours'], di['text']))\n\n dat.append(di)\n else: # element\n try:\n cur_patient = re.findall('{} (\\d+)'.format('חולה מספר'),line.text)[0]\n except:\n pass\n # cur_patient = -1\n return dat\n def read_pages(self):\n data = []\n for html, url in self.get_addresses():\n data.extend(self.read_page(html=html, addr=url))\n self.res_data = data\n def save_parsed_data(self):\n data = self.res_data\n df = pd.DataFrame(data)\n df['text'] = df['text'].apply(str.strip)\n df['url'] = df['url'].apply(lambda x: '{}'.format(x,x))\n df = df.iloc[::-1] # reverse\n open(self.tar_fname+'.html','w').writelines(df.to_html(escape=False))\n open(self.tar_fname+'.md', 'w').writelines(df.to_markdown())\n print('written HTML to {}'.format(self.tar_fname+'.html'))\n print('written MD to {}'.format(self.tar_fname+'.md'))\n shutil.copy(self.tar_fname+'.md',self.tar_fname_recent+'.md')\n os.system('xdg-open {}'.format(self.tar_fname+'.html'))\n\ndef someplot():\n import numpy as np\n import matplotlib.pyplot as plt\n x = np.cumsum(np.random.randn(1000))\n print(x)\n plt.plot(x)\n plt.show()\n exit(0)\nif __name__ == '__main__':\n #someplot()\n parser = Parser(queries='חיפה')\n #parser = Parser(queries=['חיפה','קרית ים','קריית ים','אתא','מוצקין','קרית חיים','קריית חיים','ביאליק','הקריות'])\n # parser = Parser(queries='סטוק')\n # parser = Parser(queries='כנסת')\n # parser = Parser(queries=['יקנעם','יוקנעם'])\n # parser.read_page()\n parser.read_pages()\n parser.save_parsed_data()\n","repo_name":"IdoZach/govil_corona_parse","sub_path":"govil_corona_parser.py","file_name":"govil_corona_parser.py","file_ext":"py","file_size_in_byte":5115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"23670248084","text":"'''\nGiven n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that \nthe two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container\ncontains the most water.\n\nNote: You may not slant the container and n is at least 2.\n'''\nclass Solution(object):\n def maxArea(self, height):\n \"\"\"\n :type height: List[int]\n :rtype: int\n \"\"\"\n first = 0\n last = len(height) - 1\n area = 0\n while first < last :\n A = min(height[first],height[last]) * (last - first)\n if area < A :\n area = A\n if height[first] < height[last]:\n first += 1\n else:\n last -= 1\n return area\n","repo_name":"bmegha98/Python-Practice","sub_path":"LeetCode/Container With Most Water.py","file_name":"Container With Most Water.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"76"} +{"seq_id":"26064200135","text":"from django import template\nfrom django.conf import settings\nfrom django.utils.html import conditional_escape\nfrom django.utils.safestring import mark_safe\nfrom archives.models import LEVEL_STATUS_CHOICES\n\nregister = template.Library()\n\n\n@register.filter(name=\"whitehat_tag\", need_autoescape=True)\ndef whitehat_level_tag_filter(name, autoescape=True):\n colors = dict((_[1][1], _[2]) for _ in settings.USER_LEVEL_RANGE)\n if autoescape:\n name = conditional_escape(name)\n return mark_safe('{value}'.format(color=colors[name], value=name))\n\n\n@register.filter(name=\"post_tag\", need_autoescape=True)\ndef post_level_tag_filter(value, autoescape=True):\n levels = (_[1] for _ in LEVEL_STATUS_CHOICES)\n colors = dict(zip(levels, ('secondary', 'primary', 'warning', 'danger')))\n\n if autoescape:\n value = conditional_escape(value)\n return mark_safe('{value}'.format(color=colors[value], value=value))\n\n\n@register.filter(name=\"post_tag_color\", is_safe=True)\ndef post_level_tag_color_filter(value):\n levels = (_[0] for _ in LEVEL_STATUS_CHOICES)\n colors = dict(zip(levels, ('secondary', 'primary', 'warning', 'danger')))\n\n return colors[value]\n\n\n@register.filter(name=\"css\", is_safe=True)\ndef css_filter(form, css):\n if 'class' in form.field.widget.attrs:\n form.field.widget.attrs['class'] += \" %s\" % css\n else:\n form.field.widget.attrs['class'] = css\n\n return form\n\n\n@register.filter(name=\"placeholder\", is_safe=True)\ndef placeholder_filter(form, default=\"\"):\n text = default if default else form.label\n if 'placeholder' not in form.field.widget.attrs:\n form.field.widget.attrs['placeholder'] = text\n\n return form\n\n\n@register.filter(name=\"first_error\", is_safe=True)\ndef first_error_filter(errors):\n if not errors:\n return errors\n\n if 'captcha' in errors:\n data = errors['captcha'].as_text()\n else:\n data = errors.get(tuple(errors)[0]).as_text()\n\n return data\n\n\n@register.filter\ndef level_progress_bar(rank):\n total = rank\n for index, level in enumerate(settings.USER_LEVEL_RANGE):\n if level[0][0] <= rank < level[0][1] and index < len(settings.USER_LEVEL_RANGE) - 1:\n total = level[0][1]\n break\n\n return rank / total * 100","repo_name":"phith0n/mooder","sub_path":"archives/templatetags/template_helper.py","file_name":"template_helper.py","file_ext":"py","file_size_in_byte":2358,"program_lang":"python","lang":"en","doc_type":"code","stars":746,"dataset":"github-code","pt":"76"} +{"seq_id":"45567854073","text":"from __future__ import print_function\nimport sys\nimport os\nimport tempfile\nimport time\nimport multiprocessing as mp\nimport unittest\nimport random\nimport mxnet as mx\nimport numpy as np\nimport unittest\nimport math\nfrom nose.tools import assert_raises\nfrom mxnet.test_utils import check_consistency, set_default_context, assert_almost_equal\nfrom mxnet.base import MXNetError\nfrom mxnet import autograd\nfrom numpy.testing import assert_allclose\nfrom mxnet.test_utils import rand_ndarray\n\n\ncurr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))\nsys.path.insert(0, os.path.join(curr_path, '../unittest'))\nfrom common import setup_module, with_seed, teardown, assert_raises_cudnn_not_satisfied\nfrom test_gluon import *\nfrom test_loss import *\nfrom test_gluon_rnn import *\n\nset_default_context(mx.gpu(0))\n\ndef check_rnn_layer(layer):\n layer.collect_params().initialize(ctx=[mx.cpu(0), mx.gpu(0)])\n with mx.gpu(0):\n x = mx.nd.ones((10, 16, 30))\n states = layer.begin_state(16)\n go, gs = layer(x, states)\n\n with mx.cpu(0):\n x = mx.nd.ones((10, 16, 30))\n states = layer.begin_state(16)\n co, cs = layer(x, states)\n\n # atol of 1e-6 required, as exposed by seed 2124685726\n assert_almost_equal(go.asnumpy(), co.asnumpy(), rtol=1e-2, atol=1e-6)\n for g, c in zip(gs, cs):\n assert_almost_equal(g.asnumpy(), c.asnumpy(), rtol=1e-2, atol=1e-6)\n\n@with_seed()\ndef check_rnn_layer_w_rand_inputs(layer):\n layer.collect_params().initialize(ctx=[mx.cpu(0), mx.gpu(0)])\n x = mx.nd.uniform(shape=(10, 16, 30))\n with mx.gpu(0):\n x = x.copyto(mx.gpu(0))\n states = layer.begin_state(16)\n go, gs = layer(x, states)\n\n with mx.cpu(0):\n x = x.copyto(mx.cpu(0))\n states = layer.begin_state(16)\n co, cs = layer(x, states)\n\n assert_almost_equal(go.asnumpy(), co.asnumpy(), rtol=1e-2, atol=1e-6)\n for g, c in zip(gs, cs):\n assert_almost_equal(g.asnumpy(), c.asnumpy(), rtol=1e-2, atol=1e-6)\n\n\n@with_seed()\n@assert_raises_cudnn_not_satisfied(min_version='7.2.1')\ndef test_lstmp():\n hidden_size, projection_size = 3, 2\n rtol, atol = 1e-2, 1e-2\n batch_size, seq_len = 7, 11\n input_size = 5\n lstm_input = mx.nd.uniform(shape=(seq_len, batch_size, input_size), ctx=mx.gpu(0))\n shapes = {'i2h_weight': (hidden_size*4, input_size),\n 'h2h_weight': (hidden_size*4, projection_size),\n 'i2h_bias': (hidden_size*4,),\n 'h2h_bias': (hidden_size*4,),\n 'h2r_weight': (projection_size, hidden_size)}\n weights = {k: rand_ndarray(v) for k, v in shapes.items()}\n lstm_layer = gluon.rnn.LSTM(hidden_size, projection_size=projection_size,\n input_size=input_size, prefix='lstm0_')\n lstm_cell = gluon.contrib.rnn.LSTMPCell(hidden_size=hidden_size,\n projection_size=projection_size,\n input_size=input_size,\n prefix='lstm0_l0_')\n lstm_layer.initialize(ctx=mx.gpu(0))\n lstm_cell.initialize(ctx=mx.gpu(0))\n layer_params = lstm_layer.collect_params()\n cell_params = lstm_cell.collect_params()\n for k, v in weights.items():\n layer_params['lstm0_l0_'+k].set_data(v.copy())\n cell_params['lstm0_l0_'+k].set_data(v.copy())\n with autograd.record():\n layer_output = lstm_layer(lstm_input.copy())\n cell_output = lstm_cell.unroll(seq_len, lstm_input.copy(), layout='TNC',\n merge_outputs=True)[0]\n assert_almost_equal(layer_output.asnumpy(), cell_output.asnumpy(), rtol=rtol, atol=atol)\n layer_output.backward()\n cell_output.backward()\n for k, v in weights.items():\n layer_grad = layer_params['lstm0_l0_'+k].grad()\n cell_grad = cell_params['lstm0_l0_'+k].grad()\n print('checking gradient for {}'.format('lstm0_l0_'+k))\n assert_almost_equal(layer_grad.asnumpy(), cell_grad.asnumpy(),\n rtol=rtol, atol=atol)\n check_rnn_layer_forward(gluon.rnn.LSTM(10, 2, projection_size=5), mx.nd.ones((8, 3, 20)))\n check_rnn_layer_forward(gluon.rnn.LSTM(10, 2, projection_size=5, bidirectional=True), mx.nd.ones((8, 3, 20)), [mx.nd.ones((4, 3, 5)), mx.nd.ones((4, 3, 10))])\n\n check_rnn_layer_forward(gluon.rnn.LSTM(10, 2, dropout=0.5, projection_size=5), mx.nd.ones((8, 3, 20)),\n run_only=True)\n check_rnn_layer_forward(gluon.rnn.LSTM(10, 2, bidirectional=True, dropout=0.5, projection_size=5),\n mx.nd.ones((8, 3, 20)),\n [mx.nd.ones((4, 3, 5)), mx.nd.ones((4, 3, 10))], run_only=True)\n\n\n@with_seed()\n@assert_raises_cudnn_not_satisfied(min_version='7.2.1')\ndef test_lstm_clip():\n hidden_size, projection_size = 4096, 2048\n batch_size, seq_len = 32, 80\n input_size = 50\n clip_min, clip_max, clip_nan = -5, 5, True\n lstm_input = mx.nd.uniform(shape=(seq_len, batch_size, input_size), ctx=mx.gpu(0))\n lstm_states = [mx.nd.uniform(shape=(2, batch_size, projection_size), ctx=mx.gpu(0)),\n mx.nd.uniform(shape=(2, batch_size, hidden_size), ctx=mx.gpu(0))]\n lstm_layer = gluon.rnn.LSTM(hidden_size, projection_size=projection_size,\n input_size=input_size, prefix='lstm0_',\n bidirectional=True,\n state_clip_min=clip_min,\n state_clip_max=clip_max,\n state_clip_nan=clip_nan)\n lstm_layer.initialize(ctx=mx.gpu(0))\n with autograd.record():\n _, layer_output_states = lstm_layer(lstm_input, lstm_states)\n cell_states = layer_output_states[0].asnumpy()\n assert (cell_states >= clip_min).all() and (cell_states <= clip_max).all()\n assert not np.isnan(cell_states).any()\n\n\n@with_seed()\n@assert_raises_cudnn_not_satisfied(min_version='5.1.10')\ndef test_rnn_layer():\n check_rnn_layer(gluon.rnn.RNN(100, num_layers=3))\n check_rnn_layer(gluon.rnn.RNN(100, activation='tanh', num_layers=3))\n check_rnn_layer(gluon.rnn.LSTM(100, num_layers=3))\n check_rnn_layer(gluon.rnn.GRU(100, num_layers=3))\n\n check_rnn_layer(gluon.rnn.LSTM(100, num_layers=3, bidirectional=True))\n check_rnn_layer_w_rand_inputs(gluon.rnn.LSTM(100, num_layers=3, bidirectional=True))\n\n\ndef check_layer_bidirectional(size, in_size, proj_size):\n class RefBiLSTM(gluon.Block):\n def __init__(self, size, proj_size, **kwargs):\n super(RefBiLSTM, self).__init__(**kwargs)\n with self.name_scope():\n self._lstm_fwd = gluon.rnn.LSTM(size, projection_size=proj_size, bidirectional=False, prefix='l0')\n self._lstm_bwd = gluon.rnn.LSTM(size, projection_size=proj_size, bidirectional=False, prefix='r0')\n\n def forward(self, inpt):\n fwd = self._lstm_fwd(inpt)\n bwd_inpt = nd.flip(inpt, 0)\n bwd = self._lstm_bwd(bwd_inpt)\n bwd = nd.flip(bwd, 0)\n return nd.concat(fwd, bwd, dim=2)\n weights = {}\n for d in ['l', 'r']:\n weights['lstm_{}0_i2h_weight'.format(d)] = mx.random.uniform(shape=(size*4, in_size))\n if proj_size:\n weights['lstm_{}0_h2h_weight'.format(d)] = mx.random.uniform(shape=(size*4, proj_size))\n weights['lstm_{}0_h2r_weight'.format(d)] = mx.random.uniform(shape=(proj_size, size))\n else:\n weights['lstm_{}0_h2h_weight'.format(d)] = mx.random.uniform(shape=(size*4, size))\n weights['lstm_{}0_i2h_bias'.format(d)] = mx.random.uniform(shape=(size*4,))\n weights['lstm_{}0_h2h_bias'.format(d)] = mx.random.uniform(shape=(size*4,))\n\n net = gluon.rnn.LSTM(size, projection_size=proj_size, bidirectional=True, prefix='lstm_')\n ref_net = RefBiLSTM(size, proj_size, prefix='lstm_')\n net.initialize()\n ref_net.initialize()\n net_params = net.collect_params()\n ref_net_params = ref_net.collect_params()\n for k in weights:\n net_params[k].set_data(weights[k])\n ref_net_params[k.replace('l0', 'l0l0').replace('r0', 'r0l0')].set_data(weights[k])\n\n data = mx.random.uniform(shape=(11, 10, in_size))\n assert_allclose(net(data).asnumpy(), ref_net(data).asnumpy())\n\n@with_seed()\n@assert_raises_cudnn_not_satisfied(min_version='5.1.10')\ndef test_layer_bidirectional():\n check_layer_bidirectional(7, 5, 0)\n\n@with_seed()\n@assert_raises_cudnn_not_satisfied(min_version='7.2.1')\ndef test_layer_bidirectional_proj():\n check_layer_bidirectional(7, 5, 3)\n\n\n@with_seed()\n@assert_raises_cudnn_not_satisfied(min_version='5.1.10')\ndef test_rnn_layer_begin_state_type():\n fake_data = nd.random.uniform(shape=(3, 5, 7), dtype='float16')\n modeling_layer = gluon.rnn.LSTM(hidden_size=11, num_layers=2, dropout=0.2, bidirectional=True)\n modeling_layer.cast('float16')\n modeling_layer.initialize()\n modeling_layer(fake_data)\n\n\ndef test_gluon_ctc_consistency():\n loss = mx.gluon.loss.CTCLoss()\n data = mx.nd.arange(0, 4, repeat=40, ctx=mx.gpu(0)).reshape((2,20,4)).flip(axis=0)\n cpu_label = mx.nd.array([[2,1,-1,-1],[3,2,2,-1]], ctx=mx.cpu(0))\n gpu_label = mx.nd.array([[2,1,-1,-1],[3,2,2,-1]], ctx=mx.gpu(0))\n\n cpu_data = data.copy().as_in_context(mx.cpu(0))\n cpu_data.attach_grad()\n with mx.autograd.record():\n l_cpu = loss(cpu_data, cpu_label)\n l_cpu.backward()\n\n gpu_data = data.copyto(mx.gpu(0))\n gpu_data.attach_grad()\n with mx.autograd.record():\n l_gpu = loss(gpu_data, gpu_label)\n l_gpu.backward()\n\n assert_almost_equal(cpu_data.grad.asnumpy(), gpu_data.grad.asnumpy(), atol=1e-3, rtol=1e-3)\n\n\n@with_seed()\ndef test_global_norm_clip_multi_device():\n for check_isfinite in [True, False]:\n x1 = mx.nd.ones((3,3), ctx=mx.gpu(0))\n x2 = mx.nd.ones((4,4), ctx=mx.cpu(0))\n norm = gluon.utils.clip_global_norm([x1, x2], 1.0, check_isfinite=check_isfinite)\n if check_isfinite:\n assert norm == 5.0\n else:\n assert norm.asscalar() == 5.0\n assert_almost_equal(x1.asnumpy(), np.ones((3, 3)) / 5)\n assert_almost_equal(x2.asnumpy(), np.ones((4, 4)) / 5)\n\n\ndef _check_batchnorm_result(input, num_devices=1, cuda=False):\n from mxnet.gluon.utils import split_and_load\n def _find_bn(module):\n if isinstance(module, (mx.gluon.nn.BatchNorm, mx.gluon.contrib.nn.SyncBatchNorm)):\n return module\n elif isinstance(module.module, (mx.gluon.nn.BatchNorm, mx.gluon.contrib.nn.SyncBatchNorm)):\n return module.module\n\n raise RuntimeError('BN not found')\n\n def _syncParameters(bn1, bn2, ctx):\n ctx = input.context\n bn2.gamma.set_data(bn1.gamma.data(ctx))\n bn2.beta.set_data(bn1.beta.data(ctx))\n bn2.running_mean.set_data(bn1.running_mean.data(ctx))\n bn2.running_var.set_data(bn1.running_var.data(ctx))\n\n input1 = input.copy()\n input2 = input.copy()\n\n if cuda:\n input1 = input.as_in_context(mx.gpu(0))\n ctx_list = [mx.gpu(i) for i in range(num_devices)]\n else:\n ctx_list = [mx.cpu(0) for _ in range(num_devices)]\n\n nch = input.shape[1]\n bn1 = mx.gluon.nn.BatchNorm(in_channels=nch)\n bn2 = mx.gluon.contrib.nn.SyncBatchNorm(in_channels=nch, num_devices=num_devices)\n\n bn1.initialize(ctx=ctx_list[0])\n bn2.initialize(ctx=ctx_list)\n\n # using the same values for gamma and beta\n #_syncParameters(_find_bn(bn1), _find_bn(bn2), ctx_list[0])\n\n input1.attach_grad()\n inputs2 = split_and_load(input2, ctx_list, batch_axis=0)\n for xi in inputs2:\n xi.attach_grad()\n\n with mx.autograd.record():\n output1 = bn1(input1)\n output2 = [bn2(xi) for xi in inputs2]\n loss1 = (output1 ** 2).sum()\n loss2 = [(output ** 2).sum() for output in output2]\n mx.autograd.backward(loss1)\n mx.autograd.backward(loss2)\n\n output2 = mx.nd.concat(*[output.as_in_context(input.context) for output in output2], dim=0)\n # assert forwarding\n assert_almost_equal(input1.asnumpy(), input2.asnumpy(), atol=1e-3, rtol=1e-3)\n assert_almost_equal(output1.asnumpy(), output2.asnumpy(), atol=1e-3, rtol=1e-3)\n assert_almost_equal(_find_bn(bn1).running_mean.data(ctx_list[0]).asnumpy(),\n _find_bn(bn2).running_mean.data(ctx_list[0]).asnumpy(),\n atol=1e-3, rtol=1e-3)\n assert_almost_equal(_find_bn(bn1).running_var.data(ctx_list[0]).asnumpy(),\n _find_bn(bn2).running_var.data(ctx_list[0]).asnumpy(),\n atol=1e-3, rtol=1e-3)\n input2grad = mx.nd.concat(*[output.grad.as_in_context(input.context) for output in inputs2], dim=0)\n assert_almost_equal(input1.grad.asnumpy(), input2grad.asnumpy(), atol=1e-3, rtol=1e-3)\n\n@with_seed()\ndef test_sync_batchnorm():\n def get_num_devices():\n for i in range(100):\n try:\n mx.nd.zeros((1,), ctx=mx.gpu(i))\n except:\n return i\n # no need to use SyncBN with 1 gpu\n if get_num_devices() < 2:\n return\n ndev = 2\n # check with unsync version\n for i in range(10):\n _check_batchnorm_result(mx.nd.random.uniform(shape=(4, 1, 4, 4)),\n num_devices=ndev, cuda=True)\n\n\n@with_seed()\ndef test_symbol_block_fp16():\n # Test case to verify if initializing the SymbolBlock from a model with params\n # other than fp32 param dtype.\n\n # 1. Load a resnet model, cast it to fp16 and export\n tmp = tempfile.mkdtemp()\n tmpfile = os.path.join(tmp, 'resnet34_fp16')\n ctx = mx.gpu(0)\n\n net_fp32 = mx.gluon.model_zoo.vision.resnet34_v2(pretrained=True, ctx=ctx, root=tmp)\n net_fp32.cast('float16')\n net_fp32.hybridize()\n data = mx.nd.zeros((1,3,224,224), dtype='float16', ctx=ctx)\n net_fp32.forward(data)\n net_fp32.export(tmpfile, 0)\n\n # 2. Load the saved model and verify if all the params are loaded correctly.\n # and choose one of the param to verify the type if fp16.\n sm = mx.sym.load(tmpfile + '-symbol.json')\n inputs = mx.sym.var('data', dtype='float16')\n net_fp16 = mx.gluon.SymbolBlock(sm, inputs)\n net_fp16.collect_params().load(tmpfile + '-0000.params', ctx=ctx)\n # 3. Get a conv layer's weight parameter name. Conv layer's weight param is\n # expected to be of dtype casted, fp16.\n for param_name in net_fp16.params.keys():\n if 'conv' in param_name and 'weight' in param_name:\n break\n assert np.dtype(net_fp16.params[param_name].dtype) == np.dtype(np.float16)\n\n\n@with_seed()\ndef test_large_models():\n ctx = default_context()\n # Create model\n net = gluon.nn.HybridSequential()\n\n largest_num_features = 256\n with net.name_scope():\n net.add(nn.Conv2D(largest_num_features, 3))\n\n net.hybridize()\n net.initialize(mx.init.Normal(sigma=0.01), ctx=ctx)\n\n # Compute the height (=width) of the square tensor of the given size in bytes\n def tensor_size(big_tensor_bytes):\n bytes_per_float = 4\n sz = int(math.sqrt(big_tensor_bytes / largest_num_features / bytes_per_float))\n return (sz // 100) * 100\n\n # The idea is to create models with large tensors of (say) 20% of the total memory.\n # This in the past has given cudnnFind() trouble when it needed to allocate similar I/O's\n # from the area carved out by the MXNET_GPU_MEM_POOL_RESERVE setting (by default 5%).\n (free_mem_bytes, total_mem_bytes) = mx.context.gpu_memory_info(ctx.device_id)\n start_size = tensor_size(0.20 * total_mem_bytes)\n num_trials = 10\n sys.stderr.write(' testing global memory of size {} ... '.format(total_mem_bytes))\n sys.stderr.flush()\n for i in range(num_trials):\n sz = start_size - 10 * i\n (height, width) = (sz,sz)\n sys.stderr.write(\" {}x{} \".format(height,width))\n sys.stderr.flush()\n data_in = nd.random_uniform(low=0, high=255, shape=(1, 3, height, width),\n ctx=ctx, dtype=\"float32\")\n # Evaluate model\n net(data_in).asnumpy()\n\n\nif __name__ == '__main__':\n import nose\n nose.runmodule()\n","repo_name":"researchmm/tasn","sub_path":"tasn-mxnet/tests/python/gpu/test_gluon_gpu.py","file_name":"test_gluon_gpu.py","file_ext":"py","file_size_in_byte":16168,"program_lang":"python","lang":"en","doc_type":"code","stars":216,"dataset":"github-code","pt":"76"} +{"seq_id":"6955537648","text":"# 2013.11.15 11:27:21 EST\n# Embedded file name: scripts/client/tutorial/control/lobby/context.py\nimport BigWorld\nfrom AccountCommands import RES_TUTORIAL_DISABLED, RES_SUCCESS\nimport dossiers2\nfrom tutorial.control import context\nfrom tutorial.logger import LOG_DEBUG, LOG_ERROR\n\nclass LobbyStartReqs(context.StartReqs):\n\n def isEnabled(self):\n return not self._ctx.cache.isFinished() or self._ctx.restart\n\n def process(self):\n BigWorld.player().stats.get('tutorialsCompleted', self.__cb_onGetTutorialsCompleted)\n\n def __cb_onGetTutorialsCompleted(self, resultID, completed):\n ctx = self._ctx\n loader = self._loader\n if resultID < RES_SUCCESS:\n LOG_ERROR('Server return error on request tutorialsCompleted', resultID, completed)\n loader._clear()\n self._clear()\n return\n ctx.bonusCompleted = completed\n cache = ctx.cache\n if loader.tutorial._descriptor.areAllBonusesReceived(completed):\n cache.setFinished(True).write()\n loader._clear()\n self._clear()\n return\n if cache.isRefused():\n self._clear()\n if ctx.restart and not ctx.isInPrebattle:\n loader.tutorial.restart(ctx)\n else:\n loader.tutorial.pause(ctx)\n return\n if cache.isEmpty() and not completed:\n BigWorld.player().stats.get('dossier', self.__cb_onGetDossier)\n else:\n self._clear()\n if not cache.isAfterBattle():\n cache.setAfterBattle(loader.isAfterBattle)\n loader._doRun(ctx)\n\n def __cb_onGetDossier(self, resultID, dossierCD):\n loader, ctx = self._flush()\n if resultID < RES_SUCCESS:\n LOG_ERROR('Server return error on request dossier', resultID, dossierCD)\n loader._clear()\n return\n dossierDescr = dossiers2.getAccountDossierDescr(dossierCD)\n if not dossierDescr['a15x15']['battlesCount']:\n loader._doRun(ctx)\n else:\n ctx.cache.setFinished(True).write()\n loader._clear()\n\n\nclass LobbyBonusesRequester(context.BonusesRequester):\n\n def __init__(self, completed):\n super(LobbyBonusesRequester, self).__init__(completed)\n self._isReceived = True\n\n def isStillRunning(self):\n return not self._isReceived\n\n def request(self, chapterID = None):\n chapter = self.getChapter(chapterID=chapterID)\n if chapter is None:\n LOG_ERROR('Chapter not found', chapterID)\n return\n elif not chapter.hasBonus():\n LOG_ERROR('Chapter has not bonus.')\n return\n elif chapter.isBonusReceived(self._completed):\n LOG_ERROR('Bonus already received.')\n return\n else:\n bonusID = chapter.getBonusID()\n self._isReceived = False\n waitingID = chapter.getBonusMessage()\n if not len(waitingID):\n waitingID = 'request-bonus'\n self._gui.showWaiting(waitingID)\n LOG_DEBUG('completeTutorial', bonusID)\n BigWorld.player().completeTutorial(bonusID, lambda resultID: self.__cb_onCompleteTutorial(bonusID, waitingID, resultID))\n return\n\n def __cb_onCompleteTutorial(self, bonusID, waitingID, resultID):\n if self._tutorial is not None and not self._tutorial._tutorialStopped:\n self._gui.hideWaiting(waitingID)\n self._isReceived = True\n if resultID < 0:\n LOG_ERROR('Server return error on request completeTutorial', resultID, bonusID)\n if resultID == RES_TUTORIAL_DISABLED:\n errorKey = '#tutorial:messages/tutorial-disabled'\n else:\n errorKey = '#tutorial:messages/request-bonus-failed'\n if self._tutorial is not None and not self._tutorial._tutorialStopped:\n self._gui.showI18nMessage(errorKey, msgType='Error')\n self._gui.hideWaiting()\n self._tutorial.stop()\n return\n else:\n LOG_DEBUG('Received bonus', bonusID)\n self._completed |= 1 << bonusID\n return\n# okay decompyling res/scripts/client/tutorial/control/lobby/context.pyc \n# decompiled 1 files: 1 okay, 0 failed, 0 verify failed\n# 2013.11.15 11:27:21 EST\n","repo_name":"Omegaice/WOTDecompiled","sub_path":"res/scripts/client/tutorial/control/lobby/context.py","file_name":"context.py","file_ext":"py","file_size_in_byte":4369,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"76"} +{"seq_id":"19120828623","text":"import sys\n\nfrom mastodon import Mastodon\n\nfrom oabot.post import create_replies\nfrom oabot.extract import EMAIL\n\n\nif __name__ == \"__main__\":\n if EMAIL is None:\n raise TypeError(\n \"Set the EMAIL environment variable to your email \"\n \"address for polite usage of the APIs.\"\n )\n if len(sys.argv) != 2:\n raise ValueError(\"Need to provide a Mastodon status ID\")\n try:\n status_id = int(sys.argv[1])\n except ValueError:\n raise ValueError(\"Mastodon status ID must be an integer\")\n m = Mastodon(api_base_url=\"https://neuromatch.social\")\n replies = create_replies(m.status(status_id).content)\n if not replies:\n print(\"No replies to be made\")\n else:\n for line in replies:\n print(line)\n","repo_name":"mstimberg/openaccess_mastodon_bot","sub_path":"run_mastodon.py","file_name":"run_mastodon.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"16243973154","text":"with open(\"day8.txt\") as f:\n lines = f.readlines()\n\nprint(\"Number of lines:\", len(lines))\nfor j in range(len(lines)):\n if lines[j].startswith(\"jmp\"):\n lines[j] = lines[j].replace(\"jmp\", \"nop\")\n elif lines[j].startswith(\"nop\"):\n lines[j] = lines[j].replace(\"nop\", \"jmp\")\n else:\n continue\n acc = 0\n i = 0\n visited = set()\n while True:\n visited.add(i)\n command, amount = lines[i].split(\" \")\n if command == \"nop\":\n i += 1\n elif command == \"acc\":\n acc += int(amount.strip(\"\\n\"))\n i += 1\n elif command == \"jmp\":\n i += int(amount.strip(\"\\n\"))\n if i in visited:\n print(i, \"already visited\")\n print(acc)\n break\n if i == len(lines)-1:\n print(\"Last instruction, acc:\", acc)\n print(\"Line\", j, \"changed\")\n break\n\n if lines[j].startswith(\"jmp\"):\n lines[j] = lines[j].replace(\"jmp\", \"nop\")\n elif lines[j].startswith(\"nop\"):\n lines[j] = lines[j].replace(\"nop\", \"jmp\")\n","repo_name":"wplohrmann/projects","sub_path":"aoc_2020/day8.py","file_name":"day8.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"31489233491","text":"import os\nimport glob\nimport re\nimport multiprocessing as mp\nimport numpy as np\nimport scipy.io.wavfile\nimport pandas as pd\nimport tqdm\n\nfrom magnolia.utils.bss_eval import bss_eval_sources\n\n\ndef evaluate(input_path, output_csv_file, target_stype=None, eval_sr=8000, num_sources=2):\n print('starting evaluation on directory {}'.format(input_path))\n \n mix_glob_pattern = 'mix_*_snr_*.wav'\n mix_regex = r\"mix_(?P[0-9]+)_snr_(?P[0-9\\-\\.]+).wav\"\n original_source_glob_format = 'mix_{}_original_source_*.wav'\n original_regex = r\"mix_(?P[0-9]+)_original_source_(?P[0-9]+).wav\"\n separated_source_glob_format = 'mix_{}_separated_source_*.wav'\n extended_separated_source_glob_format = 'mix_{}_*_separated_source_*.wav'\n separated_regex = r\"mix_(?P[0-9]+)_separated_source_(?P[0-9]+).wav\"\n extended_separated_regex = r\"mix_(?P[0-9]+)_(?P[a-zA-Z]*)_separated_source_(?P[0-9]+).wav\"\n\n mix_info = {'snr': [],\n 'mix_number': [],\n 'mix_file_location': []}\n for source_num in range(num_sources):\n mix_info['original_source_{}_file_location'.format(source_num + 1)] = []\n mix_info['separated_source_{}_file_location'.format(source_num + 1)] = []\n mix_info['source_{}_original_sdr'.format(source_num + 1)] = []\n mix_info['separated_source_{}_output_sdr'.format(source_num + 1)] = []\n\n mixes_list = glob.glob(os.path.join(input_path, mix_glob_pattern))\n for filename in tqdm.tqdm(mixes_list):\n dirname = os.path.dirname(os.path.normpath(filename))\n basename = os.path.basename(os.path.normpath(filename))\n m = re.match(mix_regex, basename)\n mix_num = int(m.group('mix_number'))\n mix_info['mix_number'].append(mix_num)\n mix_info['snr'].append(float(m.group('snr')))\n mix_info['mix_file_location'].append(filename)\n\n mix_input = []\n mix_y = scipy.io.wavfile.read(filename)[1]\n for i in range(num_sources):\n mix_input.append(mix_y)\n mix_input = np.stack(mix_input)\n\n original_input = []\n original_input_order = []\n original_source_glob = original_source_glob_format.format(mix_num)\n for original_filename in glob.glob(os.path.join(input_path, original_source_glob)):\n original_basename = os.path.basename(os.path.normpath(original_filename))\n m = re.match(original_regex, original_basename)\n source_num = int(m.group('source_number'))\n original_input_order.append(source_num)\n mix_info['original_source_{}_file_location'.format(source_num)].append(original_filename)\n original_y = scipy.io.wavfile.read(original_filename)[1]\n original_input.append(original_y)\n\n original_input = np.stack(original_input)[np.argsort(original_input_order)]\n\n separated_input = []\n separated_input_order = []\n separated_source_glob = separated_source_glob_format.format(mix_num)\n extended_separated_source_glob = extended_separated_source_glob_format.format(mix_num)\n is_extended = False\n gg = None\n if glob.glob(os.path.join(input_path, separated_source_glob)):\n gg = glob.glob(os.path.join(input_path, separated_source_glob))\n elif glob.glob(os.path.join(input_path, extended_separated_source_glob)):\n gg = glob.glob(os.path.join(input_path, extended_separated_source_glob))\n is_extended = True\n for separated_filename in gg:\n separated_basename = os.path.basename(os.path.normpath(separated_filename))\n m = None\n if not is_extended:\n m = re.match(separated_regex, separated_basename)\n else:\n m = re.match(extended_separated_regex, separated_basename)\n if m.group('stype') != target_stype:\n continue\n source_num = int(m.group('source_number'))\n separated_input_order.append(source_num)\n mix_info['separated_source_{}_file_location'.format(source_num)].append(separated_filename)\n separated_y = scipy.io.wavfile.read(separated_filename)[1]\n separated_input.append(separated_y)\n\n separated_input = np.stack(separated_input)[np.argsort(separated_input_order)]\n\n starting_sdr, starting_sir, starting_sar, starting_perm = bss_eval_sources(original_input, mix_input)\n final_sdr, final_sir, final_sar, final_perm = bss_eval_sources(original_input, separated_input)\n\n for i in range(num_sources):\n mix_info['source_{}_original_sdr'.format(i + 1)].append(starting_sdr[i])\n mix_info['separated_source_{}_output_sdr'.format(i + 1)].append(final_sdr[final_perm][i])\n\n print('writing output CSV file to {}'.format(output_csv_file))\n pd.DataFrame(mix_info).to_csv(output_csv_file, index=False, index_label='mix_number')\n\n\n\nif __name__ == '__main__':\n args = [\n ['/local_data/magnolia/experiment_data/date_2017_09_28_time_13_14/aux/evaluations/lab41/in_sample_test',\n '/local_data/magnolia/experiment_data/date_2017_09_28_time_13_14/aux/evaluations/bss/lab41/in_sample_test.csv'],\n ['/local_data/magnolia/experiment_data/date_2017_09_28_time_13_14/aux/evaluations/lab41/out_of_sample_test',\n '/local_data/magnolia/experiment_data/date_2017_09_28_time_13_14/aux/evaluations/bss/lab41/out_of_sample_test.csv'],\n ['/local_data/magnolia/experiment_data/date_2017_09_28_time_13_14/aux/evaluations/large_lab41/in_sample_test',\n '/local_data/magnolia/experiment_data/date_2017_09_28_time_13_14/aux/evaluations/bss/large_lab41/in_sample_test.csv'],\n ['/local_data/magnolia/experiment_data/date_2017_09_28_time_13_14/aux/evaluations/large_lab41/out_of_sample_test',\n '/local_data/magnolia/experiment_data/date_2017_09_28_time_13_14/aux/evaluations/bss/large_lab41/out_of_sample_test.csv'],\n ['/local_data/magnolia/experiment_data/date_2017_09_28_time_13_14/aux/evaluations/chimera/in_sample_test',\n '/local_data/magnolia/experiment_data/date_2017_09_28_time_13_14/aux/evaluations/bss/chimera/mi_in_sample_test.csv',\n 'mi'],\n ['/local_data/magnolia/experiment_data/date_2017_09_28_time_13_14/aux/evaluations/chimera/out_of_sample_test',\n '/local_data/magnolia/experiment_data/date_2017_09_28_time_13_14/aux/evaluations/bss/chimera/mi_out_of_sample_test.csv',\n 'mi'],\n ['/local_data/magnolia/experiment_data/date_2017_09_28_time_13_14/aux/evaluations/chimera/in_sample_test',\n '/local_data/magnolia/experiment_data/date_2017_09_28_time_13_14/aux/evaluations/bss/chimera/dc_in_sample_test.csv',\n 'dc'],\n ['/local_data/magnolia/experiment_data/date_2017_09_28_time_13_14/aux/evaluations/chimera/out_of_sample_test',\n '/local_data/magnolia/experiment_data/date_2017_09_28_time_13_14/aux/evaluations/bss/chimera/dc_out_of_sample_test.csv',\n 'dc'],\n ['/local_data/magnolia/experiment_data/date_2017_09_28_time_13_14/aux/evaluations/snmf/in_sample_test',\n '/local_data/magnolia/experiment_data/date_2017_09_28_time_13_14/aux/evaluations/bss/snmf/in_sample_test.csv'],\n ['/local_data/magnolia/experiment_data/date_2017_09_28_time_13_14/aux/evaluations/snmf/out_of_sample_test',\n '/local_data/magnolia/experiment_data/date_2017_09_28_time_13_14/aux/evaluations/bss/snmf/out_of_sample_test.csv']\n ]\n \n args = args[8:]\n \n # Parallel\n #processes = []\n #for arg in args:\n # processes.append(mp.Process(target=evaluate, args=arg))\n # processes[-1].start()\n # \n #for process in processes:\n # process.join()\n \n # Parallel\n #pool = mp.Pool(processes=min(len(args), os.cpu_count() - 1))\n pool = mp.Pool(processes=2)\n pool.starmap(evaluate, args)\n \n # Sequential\n #for arg in args:\n # evaluate(*arg)\n","repo_name":"Lab41/Magnolia","sub_path":"magnolia/python/analysis/bss_evaluate.py","file_name":"bss_evaluate.py","file_ext":"py","file_size_in_byte":7999,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"76"} +{"seq_id":"19742261591","text":"\"\"\"Functions that handle alignment, padding, widths, etc.\"\"\"\n\nimport unicodedata\n\n\ndef string_width(string):\n \"\"\"Get the visible width of a unicode string.\n\n Some CJK unicode characters are more than one byte unlike ASCII and latin unicode characters.\n\n From: https://github.com/Robpol86/terminaltables/pull/9\n\n :param str string: String to measure.\n\n :return: String's width.\n :rtype: int\n \"\"\"\n # Colorclass instance.\n if hasattr(string, 'value_no_colors'):\n string = string.value_no_colors\n\n # Convert to unicode.\n try:\n decoded = string.decode('u8')\n except (AttributeError, UnicodeEncodeError):\n decoded = string\n\n width = 0\n for char in decoded:\n if unicodedata.east_asian_width(char) in ('F', 'W'):\n width += 2\n else:\n width += 1\n\n return width\n\n\ndef align_and_pad_cell(string, align, size_dims):\n \"\"\"Align a string with center/rjust/ljust and adds additional padding.\n\n :param str string: Input string to operate on.\n :param str align: 'left', 'right', or 'center'.\n :param iter size_dims: Size and dimensions. A 4-item tuple of integers representing width, height, lpad, and rpad.\n\n :return: Modified string.\n :rtype: str\n \"\"\"\n width, height, lpad, rpad = size_dims\n\n # Handle trailing newlines or empty strings, str.splitlines() does not satisfy.\n lines = string.splitlines() or ['']\n if string.endswith('\\n'):\n lines.append('')\n\n # Align.\n if align == 'center':\n method = 'center'\n elif align == 'right':\n method = 'rjust'\n else:\n method = 'ljust'\n aligned = '\\n'.join(getattr(l, method)(width + len(l) - string_width(l)) for l in lines)\n\n # Pad.\n padded = '\\n'.join((' ' * lpad) + l + (' ' * rpad) for l in aligned.splitlines() or [''])\n\n # Increase height.\n additional_padding = height - 1 - padded.count('\\n')\n if additional_padding > 0:\n padded += ('\\n{0}'.format(' ' * (width + lpad + rpad))) * additional_padding\n\n return padded\n\n\ndef column_widths(table_data):\n \"\"\"Get maximum widths of each column in the table.\n\n :param iter table_data: List of list of strings. The unpadded table data.\n\n :return: Column widths.\n :rtype: list\n \"\"\"\n if not table_data:\n return list()\n\n number_of_columns = max(len(r) for r in table_data)\n widths = [0] * number_of_columns\n\n for row in table_data:\n for i in range(len(row)):\n if not row[i]:\n continue\n widths[i] = max(widths[i], string_width(max(row[i].splitlines(), key=len)))\n\n return widths\n","repo_name":"meetbill/zabbix_manager","sub_path":"ZabbixTool/lib_zabbix/w_lib/terminaltables/width_and_alignment.py","file_name":"width_and_alignment.py","file_ext":"py","file_size_in_byte":2629,"program_lang":"python","lang":"en","doc_type":"code","stars":209,"dataset":"github-code","pt":"76"} +{"seq_id":"2766064405","text":"from PyQt5 import QtWidgets\r\nfrom PyQt5.QtCore import Qt\r\nfrom PyQt5.QtWidgets import *\r\nfrom board import Board\r\n\r\nD = False\r\nclass QuoridorGame(QWidget):\r\n\r\n def __init__(self):\r\n super().__init__()\r\n self.setGeometry(400, 500, 800, 500) # 조절해야함 4k 기준\r\n # init Layout\r\n quoridorLayout = QGridLayout()\r\n quoridorLayout.setSpacing(4)\r\n self.setLayout(quoridorLayout)\r\n quoridorLayout.setContentsMargins(15, 15, 15, 15)\r\n # init board_button\r\n self.board_button = []\r\n for y in range(17):\r\n tmp_board = []\r\n for x in range(17):\r\n tmp_button = QPushButton()\r\n tmp_button.setMaximumSize(25,25) #boxsize 제한 34가 ui그리드에 딱 맞는 크기 \r\n tmp_button.clicked.connect(self.btnclick)\r\n if y%2 or x%2:\r\n tmp_button.setStyleSheet(\"background-color: gray\")\r\n else:\r\n tmp_button.setStyleSheet(\"background-color: white\")\r\n \r\n quoridorLayout.addWidget(tmp_button, y, x)\r\n tmp_board.append(tmp_button)\r\n self.board_button.append(tmp_board)\r\n \r\n # Display widget for current status\r\n self.player1block = QLineEdit()\r\n self.player1block.setReadOnly(True)\r\n self.player1block.setMaximumSize(300,25)\r\n quoridorLayout.addWidget(self.player1block, 0, 18)\r\n \r\n self.statusText = QLineEdit()\r\n self.statusText.setReadOnly(True)\r\n self.statusText.setMaximumSize(300,25)\r\n quoridorLayout.addWidget(self.statusText, 6, 18)\r\n \r\n self.change_btn = QToolButton()\r\n self.change_btn.setText(\"가로\")\r\n self.change_btn.clicked.connect(self.change_dir)\r\n self.change_btn.setMaximumSize(300,25)\r\n quoridorLayout.addWidget(self.change_btn, 8, 18)\r\n \r\n self.currentturn = QLineEdit()\r\n quoridorLayout.addWidget(self.currentturn, 10, 18)\r\n self.currentturn.setMaximumSize(300,25)\r\n\r\n\r\n self.player2block = QLineEdit()\r\n self.player2block.setReadOnly(True)\r\n self.player2block.setMaximumSize(300,25)\r\n quoridorLayout.addWidget(self.player2block, 16, 18)\r\n quoridorLayout.setSizeConstraint(QLayout.SetFixedSize)\r\n self.startGame()\r\n \r\n self.setMouseTracking(True) #mouse 현재 위치 픽셀 계산\r\n\r\n def mouseMoveEvent(self, pos):\r\n \r\n self.mouseXpos = 0\r\n self.mouseYpos = 0\r\n x = pos.x() - 12\r\n y = pos.y() - 12\r\n self.mouseXpos = (x//29) #43을 조절해야함\r\n self.mouseYpos = (y//29) #43을 조절해야함 지금은 4k 기준 \r\n if self.mouseXpos<=16 and self.mouseYpos<=16:\r\n self.wallcheker(self.mouseXpos,self.mouseYpos)\r\n if D:\r\n text = f\"x: {x}, y: {y}, gridx: {self.mouseXpos}, gridy: {self.mouseYpos}\"\r\n print(text)\r\n\r\n def startGame(self):\r\n self.board = Board()\r\n self.turn = 2 # player1\r\n self.board.whereCanMove(self.turn)\r\n self.color_4()\r\n\r\n self.wall_count = [10,10]\r\n self.player1block.setText(\"player1 은 벽 개수 : \"+str(self.wall_count[0]))\r\n self.player2block.setText(\"player2 남은 벽 개수 : \"+str(self.wall_count[1]))\r\n \r\n self.currentturn.setText(\"Red turn\")\r\n self.currentturn.setStyleSheet(\"color : Red\")\r\n\r\n self.board_button[0][8].setStyleSheet(\"background-color : red\")\r\n self.board_button[16][8].setStyleSheet(\"background-color : blue\")\r\n \r\n def change_dir(self):\r\n btn = self.sender()\r\n btn.setText(\"가로\" if btn.text() == \"세로\" else \"세로\")\r\n self.board.set_direction(0 if btn.text() == \"가로\" else 1)\r\n\r\n def btnclick(self):\r\n (y, x) = self.find_btn(self.sender())\r\n if D:\r\n print(f\"mouse clicked x: {x}, y: {y} \")\r\n if y % 2 or x % 2: # 벽 세우는 곳임\r\n if self.wall_count[self.turn - 2] <= 0:\r\n self.statusText.setText(\"벽이 부족합니다!\")\r\n # 벽이 없습니다\r\n return \r\n if self.board.wall_clicked(y, x):\r\n # 설치 & status 변경\r\n for tmp in [0, -1, 1]:\r\n yy = y + tmp*self.board.direction\r\n xx = x + tmp*(1 - self.board.direction)\r\n self.board.status[yy][xx] = 1\r\n self.board_button[yy][xx].setStyleSheet(\"background-color : brown\")\r\n # 벽 개수 감소\r\n self.wall_count[self.turn - 2] -= 1\r\n # 턴 종료\r\n self.next_turn()\r\n else:\r\n self.statusText.setText(\"설치 불가능한 지역입니다!\")\r\n else: # 말이 움직이는 곳임\r\n if self.board.player_clicked(y, x):\r\n #말 이동\r\n (i,j) = self.board.find_board(self.turn)\r\n self.board.status[y][x] = self.turn\r\n self.board.status[i][j] = 0\r\n self.board_button[y][x].setStyleSheet(\"background-color : \" + (\"red \" if self.turn == 2 else \"blue\"))\r\n self.board_button[i][j].setStyleSheet(\"background-color : white\")\r\n self.next_turn()\r\n \r\n \r\n def wallcheker(self,x,y): \r\n for i in range(17):\r\n for j in range(17):\r\n if (i%2 or j%2) and self.board.status[i][j] == 0: \r\n self.board_button[i][j].setStyleSheet(\"background-color : gray\")\r\n \r\n if y % 2 or x % 2: \r\n if self.board.wall_check(y, x): \r\n for tmp in [0, -1, 1]:\r\n yy = y + tmp*self.board.direction\r\n xx = x + tmp*(1 - self.board.direction)\r\n self.board_button[yy][xx].setStyleSheet(\"background-color : yellow\")\r\n\r\n def find_btn(self, btn):\r\n for i in range(17):\r\n for j in range(17):\r\n if self.board_button[i][j] == btn:\r\n return (i,j)\r\n\r\n def next_turn(self):\r\n (y, x) = self.board.find_board(self.turn)\r\n if (3 - self.turn) * 16 == y:\r\n self.statusText.setStyleSheet(\"color : \" + (\"red \" if self.turn == 2 else \"blue\"))\r\n self.statusText.setText((\"Red \" if self.turn == 2 else \"Blue\") + \"의 승리!\")\r\n self.erase_4()\r\n return\r\n #erase 하기\r\n\r\n self.turn = 5 - self.turn\r\n self.erase_4()\r\n self.board.whereCanMove(self.turn)\r\n self.color_4()\r\n \r\n self.player1block.setText(\"1번 플레이어 남은 벽 개수 : \" + str(self.wall_count[0]))\r\n self.player2block.setText(\"2번 플레이어 남은 벽 개수 : \" + str(self.wall_count[1]))\r\n \r\n self.statusText.setText(\"\")\r\n if self.turn == 2:\r\n self.currentturn.setText(\"Red turn\")\r\n self.currentturn.setStyleSheet(\"color : Red\")\r\n else:\r\n self.currentturn.setText(\"Blue turn\")\r\n self.currentturn.setStyleSheet(\"color : Blue\")\r\n pass\r\n\r\n def erase_4(self):\r\n for i in range(17):\r\n for j in range(17):\r\n if self.board.status[i][j] == 4:\r\n self.board.status[i][j] = 0\r\n self.board_button[i][j].setStyleSheet(\"background-color : white\")\r\n\r\n \r\n def color_4(self):\r\n for i in range(17):\r\n for j in range(17):\r\n if self.board.status[i][j] == 4:\r\n self.board_button[i][j].setStyleSheet(\"background-color : green\")\r\n\r\n\r\nif __name__ == '__main__':\r\n import sys\r\n app = QApplication(sys.argv)\r\n game = QuoridorGame()\r\n game.show()\r\n sys.exit(app.exec_())\r\n","repo_name":"Rkda8071/PyQt_Quoridor","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":7852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"17125018016","text":"# -*- coding: utf-8 -*-\n# @Author : Virace\n# @Email : Virace@aliyun.com\n# @Site : x-item.com\n# @Software: Pycharm\n# @Create : 2022/8/26 14:11\n# @Update : 2023/3/9 17:11\n# @Detail : 描述\n\nimport gc\nimport json\nimport os\nimport re\nimport sys\nfrom collections import defaultdict\nfrom typing import Dict, List\n\nimport lol_voice\nfrom loguru import logger\nfrom lol_voice.formats import BIN, StringHash, WAD\n\nfrom Data.Manifest import GameData\nfrom Utils.common import de_duplication, makedirs, tree\nfrom config import GAME_CHAMPION_PATH, GAME_MAPS_PATH, GAME_REGION, HASH_PATH, LOG_PATH\n\nEVENT_HASH_PATH = os.path.join(HASH_PATH, 'event')\nE2A_HASH_PATH = os.path.join(HASH_PATH, 'event2audio')\nmakedirs(EVENT_HASH_PATH)\nmakedirs(E2A_HASH_PATH)\n\n# 游戏数据相关\ngame_data = GameData()\ngame_data_default = GameData('en_us')\n\n\ndef file_classify(b, region) -> tree:\n \"\"\"\n 分类, 区分事件和资源文件\n :param b: 好几层的dict\n :param region:\n :return:\n \"\"\"\n\n def check_path(paths):\n for p in paths:\n p = p.lower()\n if '_sfx_' in p:\n return 'SFX'\n elif '_vo_' in p:\n return 'VO'\n elif 'mus_' in p:\n return 'MUSIC'\n return 'SFX'\n\n region = region.lower()\n\n for kind in b:\n for name in b[kind]:\n for skin in b[kind][name]:\n items = b[kind][name][skin]\n this = defaultdict(list)\n for item in items:\n if len(item) == 1:\n continue\n _type = check_path(item)\n\n events = ''\n audio = []\n for path in item:\n # 哈希表的路径是无所谓大小写(因为最后计算还是按小写+)\n path = path.lower().replace('en_us', region)\n if 'events' in path:\n events = path\n elif 'audio' in path:\n audio.append(path)\n this[_type].append({'events': events, 'audio': audio})\n b[kind][name][skin] = this\n return b\n\n\ndef get_bin_hashes(update=False) -> Dict:\n \"\"\"\n 穷举皮肤ID, 0~100, 取出bin哈希表\n 这个哈希表是用来从wad中提取bin文件用的。\n 所以 就算 实际皮肤ID不存在也无所谓。\n :param update: 强制更新\n :return:\n \"\"\"\n target = os.path.join(HASH_PATH, 'bin.json')\n if os.path.exists(target) and not update:\n return json.load(open(target, encoding='utf-8'))\n\n # map是整理好的, 几乎没见过更新位置, 所以写死了\n # 如果有新的就直接调用以下 WAD.get_hash(小写路径) 就行了\n result = {\n \"characters\": {},\n \"maps\": {\n \"common\": {\n \"15714053217970310635\": \"data/maps/shipping/common/common.bin\"\n },\n \"map11\": {\"4648248922051545971\": \"data/maps/shipping/map11/map11.bin\"},\n \"map12\": {\"10561014283630087560\": \"data/maps/shipping/map12/map12.bin\"},\n \"map21\": {\"15820477637625025279\": \"data/maps/shipping/map21/map21.bin\"},\n \"map22\": {\"2513799657867357310\": \"data/maps/shipping/map22/map22.bin\"}\n }}\n champion_list = game_data.get_champions_name()\n tpl = 'data/characters/{}/skins/skin{}.bin'\n\n for item in champion_list.keys():\n if item == 'none':\n continue\n\n # 循环0 到100, 是skin的编号\n result['characters'].update(\n {item: {WAD.get_hash(tpl.format(item, i)): tpl.format(item, i) for i in range(101)}})\n\n with open(target, 'w+') as f:\n json.dump(result, f)\n return result\n\n\ndef get_bnk_hashes(update=False) -> tree:\n \"\"\"\n 从bin文件中取出实际调用的音频文件列表\n regin不需要实际安装,比如获取其他语言的哈希表,不需要实际安装外服\n\n :param update: 是否强制更新所有已知哈希表\n :return: 一个tree结构, 就是一个分好类的json\n \"\"\"\n\n target = os.path.join(HASH_PATH, f'bnk.{GAME_REGION}.json')\n if os.path.exists(target) and not update:\n res = json.load(open(target, encoding='utf-8'))\n else:\n bin_hash = get_bin_hashes(update)\n\n res = tree()\n for kind, parts in bin_hash.items():\n # companions为云顶小英雄特效音, 英雄的bin文件中没有事件信息,应该在其他bin里面\n # 但是音频音效都是重复的,也没多大关系,这里就跳过了\n if kind == 'companions':\n continue\n for name, bins in parts.items():\n\n if kind == 'characters':\n wad_file = os.path.join(GAME_CHAMPION_PATH, f'{name.capitalize()}.wad.client')\n elif kind == 'maps':\n wad_file = os.path.join(GAME_MAPS_PATH, f'{name.capitalize()}.wad.client')\n else:\n wad_file = os.path.join(GAME_MAPS_PATH, 'Map22.wad.client')\n\n bin_paths = list(bins.values())\n ids = [os.path.splitext(os.path.basename(item))[0] for item in bin_paths]\n # extract 函数使用 list[path]作为参数, 可保证返回顺序\n raw_bins = WAD(wad_file).extract(bin_paths, raw=True)\n\n bs = []\n temp = set()\n for _id, raw in zip(ids, raw_bins):\n if not raw:\n continue\n # 解析Bin文件\n b = BIN(raw)\n # 音频文件列表\n p = b.audio_files\n # 去重\n temp, fs = de_duplication(temp, p)\n if fs:\n bs.append(b)\n res[kind][name][_id] = list(fs)\n else:\n if p:\n bs.append(b)\n del raw_bins\n if bs:\n get_event_hashes(kind, name, bs, True)\n\n # 这里其实不返回值也可以, 浅拷贝修改\n res = file_classify(res, GAME_REGION)\n with open(target, 'w+', encoding='utf-8') as f:\n json.dump(res, f)\n return res\n\n\ndef get_event_hashes(kind, name, bin_datas: List[BIN] = None, update=False) -> List:\n \"\"\"\n 根据bin文件获取事件哈希表\n :param kind:\n :param name:\n :param bin_datas: BIN对象列表,\n :param update:\n :return:\n \"\"\"\n target = os.path.join(HASH_PATH, 'event', kind, f'{name}.json')\n if os.path.exists(target) and not update:\n res = BIN.load_hash_table(target)\n else:\n res = set()\n for bin_data in bin_datas:\n if len(bin_data.hash_tables) == 0:\n continue\n t = bin_data.hash_tables\n res.update(t)\n\n res = list(res)\n if res:\n makedirs(os.path.dirname(target))\n with open(target, 'w+', encoding='utf-8') as f:\n json.dump(res, f, cls=StringHash.dump_cls())\n del bin_datas\n return res\n\n\ndef get_audio_hashes(items, wad_file, event_hashes, _type, kind, name, skin, update=False) -> None:\n \"\"\"\n 根据提供的信息生成事件ID与音频ID的哈希表\n :param items: 由bin_to_data返回的数据, 格式如下\n {\n \"events\":\n \"assets/sounds/wwise2016/vo/zh_cn/characters/aatrox/skins/base/aatrox_base_vo_events.bnk\",\n \"audio\":\n [\"assets/sounds/wwise2016/vo/zh_cn/characters/aatrox/skins/base/aatrox_base_vo_audio.bnk\",\n \"assets/sounds/wwise2016/vo/zh_cn/characters/aatrox/skins/base/aatrox_base_vo_audio.wpk\"]\n }\n :param wad_file: wad文件\n :param event_hashes: get_event_hashes 返回\n :param _type: 音频类型, VO/SFX/MUSIC\n :param kind: 音频类型, characters/companions/maps\n :param name: 英雄或地图名字\n :param skin: 皮肤或地图\n :param update: 是否强制更新\n :return:\n \"\"\"\n func_name = sys._getframe().f_code.co_name\n _log_file = os.path.join(LOG_PATH, f'{func_name}.{GAME_REGION}.log')\n warn_item = []\n\n def tt(value):\n temp = False\n if isinstance(value, list):\n for t in value:\n temp = temp or t\n return bool(temp)\n return bool(value)\n\n region = re.compile(r'\\w{2}_\\w{2}').search(wad_file)\n if region:\n region = region.group()\n else:\n region = 'Default'\n target = os.path.join(HASH_PATH, 'event2audio', region, _type, kind, name,\n f'{skin}.json')\n if os.path.exists(target) and not update:\n # 可以直接pass 这里json加载用来校验文件是否正常\n # d = json.load(open(target, encoding='utf-8'))\n # del d\n # gc.collect()\n pass\n\n else:\n res = tree()\n relative_wad_path = 'Game' + wad_file.split('Game')[-1].replace('\\\\', '/')\n for item in items:\n if not item['events']:\n logger.info(f'无事件文件: {kind}, {name}, {skin}, {_type}')\n return\n\n files = [item['events'], *item['audio']]\n data_raw = WAD(wad_file).extract(files, raw=True)\n if not tt(data_raw):\n warn_item.append((wad_file, item[\"events\"]))\n logger.trace(f'WAD无文件解包: {wad_file}, {name}, {skin}, {_type}, {item[\"events\"]}')\n continue\n\n # 事件就一个,音频可能有多个,一般是两个\n event_raw, *audio_raw = data_raw\n try:\n event_hash = lol_voice.get_event_hashtable(event_hashes, event_raw)\n except KeyError:\n # characters, zyra, skin2, SFX, 这个bnk文件events和audio是相反的\n if len(audio_raw) > 1:\n raise ValueError(f'未知错误, {kind}, {name}, {skin}, {_type}')\n event_hash = lol_voice.get_event_hashtable(event_hashes, audio_raw[0])\n audio_raw = [event_raw]\n\n for raw in audio_raw:\n audio_hash = lol_voice.get_audio_hashtable(event_hash, raw)\n if audio_hash:\n # log.info(f'to_audio_hashtable, {kind}, {name}, {skin}, {_type}')\n res['data'][item['audio'][audio_raw.index(raw)]] = audio_hash\n del event_raw\n del data_raw\n del audio_raw\n\n if res:\n path = os.path.dirname(target)\n\n makedirs(path)\n res['info'] = {\n 'kind': kind,\n 'name': name,\n 'detail': skin,\n 'type': _type,\n 'wad': relative_wad_path\n }\n with open(target, 'w+', encoding='utf-8') as f:\n json.dump(res, f)\n del res\n gc.collect()\n # log.info(f'to_audio_hashtable: {kind}, {name}, {skin}, {_type}')\n\n with open(_log_file, 'a+', encoding='utf-8') as f:\n for item in warn_item:\n f.write(f'{item}\\n')\n\n","repo_name":"Virace/lol_extract_voice","sub_path":"Hashes/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":11122,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"76"} +{"seq_id":"11182192010","text":"from discord.ext import commands\nfrom DaveBOT import checks\n\n\nclass Admin:\n \"\"\"Admin-only commands.\"\"\"\n def __init__(self, bot):\n self.client = bot\n\n @commands.command(hidden=True)\n @checks.adminonly()\n async def load(self, *, module: str):\n \"\"\"Load a module.\"\"\"\n try:\n self.client.load_extension(module)\n except Exception as e:\n await self.client.say(f\"{type(e).__name__}: {e}\")\n else:\n await self.client.say(\"Module loaded.\")\n\n @commands.command(hidden=True)\n @checks.adminonly()\n async def unload(self, *, module: str):\n \"\"\"Unload a module.\"\"\"\n try:\n self.client.unload_extension(module)\n except Exception as e:\n await self.client.say(f\"{type(e).__name__}: {e}\")\n else:\n await self.client.say(\"Module unloaded.\")\n\n @commands.command(hidden=True)\n @checks.adminonly()\n async def reload(self, *, module: str):\n \"\"\"Reload a module.\"\"\"\n try:\n self.client.unload_extension(module)\n self.client.load_extension(module)\n except Exception as e:\n await self.client.say(f\"{type(e).__name__}: {e}\")\n else:\n await self.client.say(\"Module reloaded.\")\n\n\ndef setup(bot):\n bot.add_cog(Admin(bot))\n","repo_name":"fisherthewol/Dave-BOT","sub_path":"DaveBOT/cogs/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"3557260584","text":"import json\n\nfrom django.shortcuts import render\n\n# Create your views here.\nfrom django.http import HttpResponse\n\nfrom myapp.models import Class, Student\n\n\ndef index(request):\n return HttpResponse(\"cy is good man\")\n\n\ndef detail(request, **kwargs):\n return HttpResponse(\"detail {0}, {1}\".format(kwargs['num'], kwargs['num2']))\n\n\ndef myapp_class(request, **kwargs):\n # 去模型中取数据\n class_list = Class.objects.all()\n # 将数据传递给模板,,,模板渲染页面 然后 返回给浏览器\n return render(request, 'myapp/class.html', {'Class': class_list})\n\n\ndef student_info(request, **kwargs):\n print(kwargs)\n # user_id = int(kwargs['user_id'])\n user_id = kwargs['user_id']\n\n # user_id = int(user_id)\n one_student_info = Student.objects.get(id=user_id)\n print(one_student_info)\n print(type(one_student_info))\n return render(request, 'myapp/student_info.html', {'student_info': one_student_info})\n\n\ndef myapp_student(request):\n student_list = Student.objects.all()\n return render(request, 'myapp/student.html', {'student': student_list})\n\n\ndef class_student(request, class_id):\n one_class = Student.objects.filter(sclass_id=class_id)\n # one_class_student = one_class.student_set.all()\n return render(request, 'myapp/class_and_student.html', {'student': one_class})\n\n\ndef view_delete_student(request):\n student = Student.driver.all()\n return render(request, 'myapp/view_delete_student.html', {'delete_student': student})\n\n\ndef add_student(request):\n from faker import Faker\n f = Faker(locale='zh_CN')\n name = f.name()\n sex = f.boolean()\n import random\n age = random.randint(18, 26)\n contend = f.sentences()\n all_class_id = Class.objects.all()\n class_id = random.choice(all_class_id)\n # from myapp.models import create_student # 是用的方法 对应第三种写法\n # student = create_student(name, sex, age, contend, class_id) # 对应第三种写法\n # student = Student().create_student(name, sex, age, contend, class_id) # 对应 models 的第二种写法\n # student = Student.create_student(name, sex, age, contend, class_id) # 对应第一种写法\n student = Student.driver.create_student(name, sex, age, contend, class_id) # 对应第四种写法\n student.save()\n return HttpResponse(\"学生 {0}添加成功,关联在{1}\".format(name, class_id))\n\n\ndef student_page(request, page):\n page = int(page)\n limit = 5\n student = Student.objects.all()[(page - 1) * limit: page * limit]\n return render(request, 'myapp/student.html', {'student': student})\n\n\ndef hello_world(request):\n print(type(request))\n print(request)\n print('get:', request.GET)\n\n if request.GET.get('num', False) :\n resp = {'code': 1000, 'detail': 'success! hello'}\n else:\n resp = {'code': 2100, 'detail': 'fail'}\n\n return HttpResponse(json.dumps(resp), content_type=\"application/json\")\n\n\ndef attribute(request):\n \"\"\"查看他们的属性\"\"\"\n print(\"path:\", request.path)\n print('method:', request.method)\n print('encoding:', request.encoding)\n print('get:', request.GET)\n print('post:', request.POST)\n print('cookies:', request.COOKIES)\n print('session:', request.session)\n print('files:', request.FILES)\n return HttpResponse('attribute')\n\n\ndef attribute_get1(request):\n \"\"\"查看他们的属性\"\"\"\n a = request.GET['a']\n b = request.GET.get('b')\n c = request.GET['c']\n print(\"path:\", request.path)\n print('method:', request.method)\n print('encoding:', request.encoding)\n print('get:', request.GET)\n print('post:', request.POST)\n print('cookies:', request.COOKIES)\n print('session:', request.session)\n print('files:', request.FILES)\n return HttpResponse(\"a:{a}\\nb:{b}\\nc:{c}\".format(a=a, b=b, c=c))\n\n\ndef attribute_get2(request):\n \"\"\"查看他们的属性\"\"\"\n a = request.GET.getlist('a')\n b = request.GET.getlist('b')\n c = request.GET.getlist('c')\n print(\"path:\", request.path)\n print('method:', request.method)\n print('encoding:', request.encoding)\n print('get:', request.GET)\n print('post:', request.POST)\n print('cookies:', request.COOKIES)\n print('session:', request.session)\n print('files:', request.FILES)\n return HttpResponse(\"a:{a}\\nb:{b}\\nc:{c}\".format(a=a, b=b, c=c))\n\n\ndef show_register(request):\n return render(request, 'myapp/register.html')\n\n\ndef register(request):\n name = request.POST['name']\n age = request.POST['age']\n sex = request.POST['sex']\n bobby = request.POST.getlist('bobby')\n info = {\n 'name': name,\n 'age': age,\n 'sex': sex,\n 'hobby': bobby,\n 'code': 1000\n }\n return HttpResponse(json.dumps(info), content_type='application/json')\n\n\ndef show_response(request):\n result = HttpResponse()\n result.content = b'good'\n print(result.charset)\n print(result.content)\n print(result.status_code)\n return result\n\n\ndef show_cookie(request):\n \"\"\"设置cookie\"\"\"\n res = HttpResponse()\n # cookie = request.COOKIES\n # res.write(\"

{}

\".format(cookie['sid']))\n res.delete_cookie('sid') # 删除 cookie\n # res.set_cookie('sid', 'WSEGSLIF87665DFWS0j')\n return res\n\n\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import redirect\n\n\n# 重定向\ndef show_redirect1(request):\n \"\"\"url 配置 这个 但是 跳转到下面的一个\"\"\"\n return HttpResponseRedirect('/show_redirect2')\n # return redirect('/show_redirect2')\n\n\ndef show_redirect2(request):\n data = {\n 'code': 1000,\n 'status': 1\n }\n return HttpResponse(json.dumps(data))\n","repo_name":"SirCYong/LearningTogetherDjango","sub_path":"myapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"18881017879","text":"from typing import Tuple\n\nimport numpy as np\n\nfrom ...utils import exclude_list_from_list\n\n\nclass Walker(object):\n def __init__(self, coord: Tuple[int, int], main_step_prob: float = 1.0):\n self.start_coord = coord\n self.main_step_prob = main_step_prob\n self.coord = list(coord)\n\n def random_step(self, real_step, possible_actions):\n if len(possible_actions) == 1:\n return real_step\n\n if np.random.binomial(n=2, p=self.main_step_prob):\n return real_step\n else:\n return np.random.choice(\n exclude_list_from_list(possible_actions, [real_step])\n )\n\n def get_coord_from_action(self, action, cur_coord):\n x, y = cur_coord\n if action == \"left\":\n y -= 1\n elif action == \"right\":\n y += 1\n elif action == \"up\":\n x -= 1\n elif action == \"down\":\n x += 1\n return x, y\n\n def step(self, direction, possible_actions, do_step=True):\n if direction not in possible_actions:\n raise RuntimeError(\"direction should be in possible_actions\")\n\n direction = self.random_step(direction, possible_actions)\n new_x, new_y = self.get_coord_from_action(direction, tuple(self.coord))\n self.coord[0] = new_x\n self.coord[1] = new_y\n\n def reset_coord(self):\n self.coord = list(self.start_coord)\n","repo_name":"VSydorskyy/iasa_multiagent","sub_path":"matk/reinforcment/agents/walker.py","file_name":"walker.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"12832480184","text":"# Given an m x n matrix, return true if the matrix is Toeplitz. Otherwise, return false.\r\n#\r\n# A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements.\r\n#\r\n#\r\n#\r\n# Example 1:\r\n# Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]\r\n# Output: true\r\n# Explanation:\r\n# In the above grid, the diagonals are:\r\n# \"[9]\", \"[5, 5]\", \"[1, 1, 1]\", \"[2, 2, 2]\", \"[3, 3]\", \"[4]\".\r\n# In each diagonal all elements are the same, so the answer is True.\r\n\r\nclass Solution(object):\r\n def isToeplitzMatrix(self, matrix):\r\n\r\n # enumerate matrix to have both the indexes and rows\r\n for i, row in enumerate(matrix):\r\n # look at the numbers in each row\r\n for num in range(len(row) - 1):\r\n # make sure that we don't get an index error, so make sure the index is 1 less than the len of\r\n # the matrix\r\n if i < len(matrix) -1:\r\n # compare the numbers to their diagonals\r\n if row[num] != matrix[i + 1][num + 1]:\r\n return False\r\n return True\r\n","repo_name":"logan-lampton/neetcode","sub_path":"leetcode/766_toeplitz_matrix.py","file_name":"766_toeplitz_matrix.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"35635217506","text":"# ami_creation.py\n\nfrom datetime import datetime, timedelta\nimport aws_utils as awsutils\nimport os\nimport boto3\n\nREGION = os.environ['AWS_REGION']\nRETENTION = os.getenv('RETENTION', 1)\n\ndef get_instance_name(fid):\n # When given an instance ID as str e.g. 'i-1234567', return the instance 'Name' from the name tag.\n ec2 = boto3.resource('ec2')\n ec2instance = ec2.Instance(fid)\n instancename = ''\n for tags in ec2instance.tags:\n if tags[\"Key\"] == 'Name':\n instancename = tags[\"Value\"]\n return instancename\n\ndef backup(region_id=REGION):\n '''This function searches for all EC2 instances with a tag of BackUp\n and creates a AMI for them and tags the images with a\n RemoveOn tag of a YYYYMMDD value of days in UTC mentioned in RETENTION variable from today\n '''\n created_on = datetime.utcnow().strftime('%Y%m%d')\n remove_on = (datetime.utcnow() + timedelta(days=RETENTION)).strftime('%Y%m%d')\n session = awsutils.get_session(region_id)\n \n client = session.client('ec2')\n resource = session.resource('ec2')\n \n reservations = client.describe_instances(Filters=[{'Name': 'tag-key', 'Values': ['BackUp']}])\n \n for reservation in reservations['Reservations']:\n for instance_description in reservation['Instances']:\n instance_id = instance_description['InstanceId']\n name_tag = get_instance_name(instance_id)\n name = f\"{name_tag}_InstanceId({instance_id})_CreatedOn({created_on})\"\n print(f\"Creating Backup: {name}\")\n image_description = client.create_image(InstanceId=instance_id, Name=name, NoReboot=True)\n images = []\n images.append(image_description['ImageId'])\n image = resource.Image(image_description['ImageId'])\n image.create_tags(Tags=[{'Key': 'RemoveOn', 'Value': remove_on}, {'Key': 'Name', 'Value': name}])\n\nif __name__ == '__main__':\n backup(REGION)","repo_name":"pawarrchetan/aws-utilities","sub_path":"aws-ami-management/ami_creation.py","file_name":"ami_creation.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"75120198324","text":"\"\"\"\nThanks to A_n_g_e_l_a for the cookies!\n\nITV\nAuthor: stabbedbybrick\n\nInfo:\nITV L3 is 720p, AAC 2.0 max\n\n\"\"\"\nfrom __future__ import annotations\n\nimport base64\nimport subprocess\nimport json\nimport shutil\nimport sys\n\nfrom collections import Counter\nfrom pathlib import Path\n\nimport click\nimport requests\nimport yaml\n\nfrom bs4 import BeautifulSoup\n\nfrom utils.utilities import (\n info,\n error,\n is_url,\n string_cleaning,\n set_save_path,\n set_filename,\n add_subtitles,\n construct_pssh,\n get_wvd,\n geo_error,\n premium_error,\n)\nfrom utils.titles import Episode, Series, Movie, Movies\nfrom utils.options import get_downloads\nfrom utils.args import get_args\nfrom utils.info import print_info\nfrom utils.config import Config\nfrom utils.cdm import LocalCDM\n\n\nclass ITV(Config):\n def __init__(self, config, srvc_api, srvc_config, **kwargs):\n super().__init__(config, srvc_api, srvc_config, **kwargs)\n\n with open(self.srvc_api, \"r\") as f:\n self.config.update(yaml.safe_load(f))\n\n self.get_options()\n\n def get_license(self, challenge: bytes, lic_url: str) -> bytes:\n r = self.client.post(url=lic_url, data=challenge)\n if not r.is_success:\n error(f\"License request failed: {r.status_code}\")\n exit(1)\n return r.content\n\n def get_keys(self, pssh: str, lic_url: str) -> bytes:\n wvd = get_wvd(Path.cwd())\n with self.console.status(\"Getting decryption keys...\"):\n widevine = LocalCDM(wvd)\n challenge = widevine.challenge(pssh)\n response = self.get_license(challenge, lic_url)\n return widevine.parse(response)\n\n def get_data(self, url: str) -> dict:\n soup = BeautifulSoup(self.client.get(url), \"html.parser\")\n props = soup.select_one(\"#__NEXT_DATA__\").text\n data = json.loads(props)\n return data[\"props\"][\"pageProps\"]\n\n def get_series(self, url: str) -> Series:\n data = self.get_data(url)\n\n return Series(\n [\n Episode(\n id_=None,\n service=\"ITV\",\n title=data[\"programme\"][\"title\"],\n season=episode.get(\"series\") or 0,\n number=episode.get(\"episode\") or 0,\n name=episode[\"episodeTitle\"],\n year=None,\n data=episode[\"playlistUrl\"],\n description=episode.get(\"description\"),\n )\n for series in data[\"seriesList\"]\n if \"Latest episodes\" not in series[\"seriesLabel\"]\n for episode in series[\"titles\"]\n ]\n )\n\n def get_movies(self, url: str) -> Movies:\n data = self.get_data(url)\n\n return Movies(\n [\n Movie(\n id_=None,\n service=\"ITV\",\n title=data[\"programme\"][\"title\"],\n year=movie.get(\"productionYear\"),\n name=data[\"programme\"][\"title\"],\n data=movie[\"playlistUrl\"],\n synopsis=movie.get(\"description\"),\n )\n for movies in data[\"seriesList\"]\n for movie in movies[\"titles\"]\n ]\n )\n\n def get_playlist(self, playlist: str) -> tuple:\n featureset = {\n k: (\"mpeg-dash\", \"widevine\", \"outband-webvtt\", \"hd\", \"single-track\")\n for k in (\"min\", \"max\")\n }\n payload = {\n \"client\": {\"id\": \"browser\"},\n \"variantAvailability\": {\"featureset\": featureset, \"platformTag\": \"dotcom\"},\n }\n\n r = self.client.post(playlist, json=payload)\n if not r.is_success:\n premium_error(\n r.status_code\n ) if \"UserTokenValidationFailed\" in r.text else geo_error(\n r.status_code, None, location=\"UK\"\n )\n\n data = r.json()\n\n video = data[\"Playlist\"][\"Video\"]\n media = video[\"MediaFiles\"]\n mpd_url = f\"{video.get('Base')}{media[0].get('Href')}\"\n lic_url = f\"{media[0].get('KeyServiceUrl')}\"\n subtitle = video.get(\"Subtitles\")\n subtitle = f\"{subtitle[0].get('Href')}\" if subtitle else None\n\n return mpd_url, lic_url, subtitle\n\n\n def get_mediainfo(self, manifest: str, quality: str, subtitle: str) -> str:\n r = requests.get(manifest)\n if not r.ok:\n click.echo(f\"\\n\\nError! {r.status_code}\\n{r.content}\")\n sys.exit(1)\n\n self.soup = BeautifulSoup(r.content, \"xml\")\n elements = self.soup.find_all(\"Representation\")\n heights = sorted(\n [int(x.attrs[\"height\"]) for x in elements if x.attrs.get(\"height\")],\n reverse=True,\n )\n\n new_base, params = manifest.split(\".mpd\")\n new_base += \"dash/\"\n self.soup.select_one(\"BaseURL\").string = new_base\n\n segments = self.soup.find_all(\"SegmentTemplate\")\n for segment in segments:\n segment[\"media\"] += params\n segment[\"initialization\"] += params\n\n if subtitle is not None:\n self.soup = add_subtitles(self.soup, subtitle)\n\n with open(self.tmp / \"manifest.mpd\", \"w\") as f:\n f.write(str(self.soup.prettify()))\n\n if quality is not None:\n if int(quality) in heights:\n return quality\n else:\n closest_match = min(heights, key=lambda x: abs(int(x) - int(quality)))\n return closest_match\n\n return heights[0]\n\n def get_content(self, url: str) -> object:\n if self.movie:\n with self.console.status(\"Fetching titles...\"):\n content = self.get_movies(self.url)\n title = string_cleaning(str(content))\n\n info(f\"{str(content)}\\n\")\n\n else:\n with self.console.status(\"Fetching titles...\"):\n content = self.get_series(url)\n\n title = string_cleaning(str(content))\n seasons = Counter(x.season for x in content)\n num_seasons = len(seasons)\n num_episodes = sum(seasons.values())\n\n info(\n f\"{str(content)}: {num_seasons} Season(s), {num_episodes} Episode(s)\\n\"\n )\n\n return content, title\n\n def get_episode_from_url(self, url: str):\n data = self.get_data(url)\n\n episode = Series(\n [\n Episode(\n id_=None,\n service=\"ITV\",\n title=data[\"programme\"][\"title\"],\n season=data[\"episode\"].get(\"series\") or 0,\n number=data[\"episode\"].get(\"episode\") or 0,\n name=data[\"episode\"][\"episodeTitle\"],\n year=None,\n data=data[\"episode\"][\"playlistUrl\"],\n description=data[\"episode\"].get(\"description\"),\n )\n ]\n )\n\n title = string_cleaning(str(episode))\n\n return [episode[0]], title\n\n def get_options(self) -> None:\n downloads, title = get_downloads(self)\n\n for download in downloads:\n self.download(download, title)\n\n def download(self, stream: object, title: str) -> None:\n with self.console.status(\"Getting media info...\"):\n manifest, lic_url, subtitle = self.get_playlist(stream.data)\n self.res = self.get_mediainfo(manifest, self.quality, subtitle)\n pssh = construct_pssh(self.soup)\n\n keys = self.get_keys(pssh, lic_url)\n with open(self.tmp / \"keys.txt\", \"w\") as file:\n file.write(\"\\n\".join(keys))\n\n if self.info:\n print_info(self, stream, keys)\n\n self.filename = set_filename(self, stream, self.res, audio=\"AAC2.0\")\n self.save_path = set_save_path(stream, self, title)\n self.manifest = self.tmp / \"manifest.mpd\"\n self.key_file = self.tmp / \"keys.txt\"\n self.sub_path = None\n\n info(f\"{str(stream)}\")\n for key in keys:\n info(f\"{key}\")\n click.echo(\"\")\n\n args, file_path = get_args(self)\n\n if not file_path.exists():\n try:\n subprocess.run(args, check=True)\n except Exception as e:\n raise ValueError(f\"{e}\")\n else:\n info(f\"{self.filename} already exist. Skipping download\\n\")\n self.sub_path.unlink() if self.sub_path else None\n pass\n","repo_name":"stabbedbybrick/freevine","sub_path":"services/itv/itv.py","file_name":"itv.py","file_ext":"py","file_size_in_byte":8492,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"76"} +{"seq_id":"8315104074","text":"from django.urls import path\nfrom . import views\n\napp_name = 'contacts'\n\nurlpatterns = [\n path('add/', views.add, name=\"add\"),\n path('contacts/', views.ContactList.as_view()),\n path('finance/', views.FinanceList.as_view()),\n]","repo_name":"rsgilbert/contactsAPI","sub_path":"contacts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"10865815870","text":"# -*- coding:utf-8 -*-\n\"\"\"\n@author: chengbo\n@software: PyCharm\n@file: basic_make_uncased_model_cased.py\n@time: 2022/6/29 15:12\n\"\"\"\nfrom __future__ import print_function\n\nimport os\n\nos.environ.setdefault(\"TF_KERAS\", \"1\")\nfrom bert4keras.models import build_transformer_model\nfrom bert4keras.tokenizers import Tokenizer, load_vocab\nfrom bert4keras.snippets import to_array\nimport numpy as np\n\n# bert配置\nbert_dir = \"E:\\\\working\\\\huada_bgi\\\\data\\\\pretrained_model\\\\bert\\\\chinese_roberta_wwm_ext_L-12_H-768_A-12\\\\\"\nconfig_path = os.path.join(bert_dir, \"bert_config.json\")\ncheckpoint_path = os.path.join(bert_dir, \"bert_model.ckpt\")\ndict_path = os.path.join(bert_dir, \"vocab.txt\")\n\ntoken_dict = load_vocab(dict_path)\nnew_token_dict = token_dict.copy()\ncompound_tokens = []\n\nfor t, i in sorted(token_dict.items(), key=lambda s: s[1]):\n tokens = []\n if t.isalpha():\n tokens.extend([t[:1].upper() + t[1:], t.upper()])\n elif t[:2] == \"##\" and t[2:].isalpha():\n tokens.append(t.upper())\n for token in tokens:\n if token not in new_token_dict:\n compound_tokens.append([i])\n new_token_dict[token] = len(new_token_dict)\n\ntokenizer = Tokenizer(new_token_dict, do_lower_case=False)\n\nmodel = build_transformer_model(\n config_path, checkpoint_path, compound_tokens=compound_tokens\n)\n\ntext = \"Welcome to BEIJING.\"\ntokens = tokenizer.tokenize(text)\n\nprint(tokens)\n\ntoken_ids, segment_ids = tokenizer.encode(text)\ntoken_ids, segment_ids = to_array([token_ids], [segment_ids])\nprint(model.predict([token_ids, segment_ids]))\n","repo_name":"chongzicbo/NLP-Learning","sub_path":"bert4keras_examples/examples/basic_make_uncased_model_cased.py","file_name":"basic_make_uncased_model_cased.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"9504274989","text":"# Observer notifies about events happening in other objects they observe without coupling to their classes. \n\n# Use case. Each time I need to add the subscription mechanism to let an object subscribe to/ unsubscribe from notifications on the events happening with a specific publisher class, I use the Observer pattern. \n\n# A good example is a simple subscription to news from any online magazine, frequently with the option to choose your sphere of interest (science, digital technology, etc.). Alternatively, the button “Notify me when it’s in stock” for e-commerce platforms is another example.\n\n# ➕ You haven’t to change the publisher’s code to add subscribers’ classes.\n\n# ➖ Subscribers get notifications in random order. \n\n\nfrom __future__ import annotations\nfrom abc import ABC, abstractmethod\nfrom random import randrange\nfrom typing import List\n\nclass Subject(ABC):\n\n @abstractmethod\n def attach(self, observer:Observer):\n ...\n\n @abstractmethod\n def detach(self, observer: Observer):\n raise NotImplementedError\n \n @abstractmethod\n def notify(self):\n pass\n\nclass ConcreteSubject(Subject):\n _state :int = None\n _observers: List[Observer] = []\n\n def attach(self, observer: Observer):\n print(\"subject attached an observer\")\n self._observers.append(observer)\n\n def detach(self, observer: Observer):\n self._observers.remove(observer)\n\n def notify(self):\n print(\"Subject notifying observers...\")\n for observer in self._observers:\n observer.update(self)\n\n def some_business_logic(self):\n print(\"subject im doing something important\")\n self._state = randrange(0,10)\n print(f'subject: my state has just changed to {self._state}')\n self.notify()\n\n\n\n\nclass Observer(ABC):\n @abstractmethod\n def update(self, subject: Subject):\n pass\n\nclass ConcreteObserverA(Observer):\n def update(self, subject: Subject):\n if subject._state < 3:\n print(\"concreteObserverA: Reacted to event\")\n\nclass ConcreteObserverB(Observer):\n def update(self, subject: Subject):\n if subject._state == 0 or subject._state >= 2:\n print(\"Concreate observerB : reacted to event\") \n\nif __name__ == \"__main__\":\n subject = ConcreteSubject()\n\n observer_a = ConcreteObserverA()\n subject.attach(observer_a)\n\n observer_b = ConcreteObserverB()\n subject.attach(observer_b)\n\n subject.some_business_logic()\n subject.some_business_logic()\n\n subject.detach(observer_a)\n\n subject.some_business_logic()\n\n\n# $ python observer.py \n# subject attached an observer\n# subject attached an observer\n# subject im doing something important\n# subject: my state has just changed to 7\n# Subject notifying observers...\n# Concreate observerB : reacted to event\n# subject im doing something important\n# subject: my state has just changed to 6\n# Subject notifying observers...\n# Concreate observerB : reacted to event\n# subject im doing something important\n# subject: my state has just changed to 9\n# Subject notifying observers...\n# Concreate observerB : reacted to event\n","repo_name":"BNSBNS/pyplaygrd","sub_path":"python_pattern/behavior/observer.py","file_name":"observer.py","file_ext":"py","file_size_in_byte":3135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"73847999924","text":"from tkinter import *\nimport turtle\n\n\ndef area(b, h):\n area = b * h\n return area\n\ndef tiempo(a, v):\n tiempo = a/v\n return tiempo\n\ndef calculado_todo():\n print(u'El roomba va a una velocidad de 0.1 m²/s')\n vel = 1000 #cm²/s\n area1 = area(500, 150)\n tiempo1 = tiempo(area1, vel)\n area2 = area(101, 480)\n tiempo2 = tiempo(area2, vel)\n area3 = area(309, 480)\n tiempo3 = tiempo(area3, vel)\n area4 = area(90, 220)\n tiempo4 = tiempo(area4, vel)\n\n print('El tiempo que tarda en limpiar cada zona es de:\\nZona 1: {} min\\nZona 2: {} min\\nZona 3: {} min\\nZona 4: {} min'.format(tiempo1/60, round(tiempo2/60,2), round(tiempo3/60,2), tiempo4/60))\n tiempoT = tiempo1 + tiempo2 + tiempo3 + tiempo4\n print('El roomba tardara ' + str(round(tiempoT/60,2)) + ' minutos')","repo_name":"MiguelGG03/Primera_Practica_PPD","sub_path":"calculos.py","file_name":"calculos.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"3933771806","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jun 30 12:51:34 2021\r\n\r\n@author: anton\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\r\nfrom sklearn import decomposition, ensemble\r\n\r\ntweet_df = pd.read_csv(r'ready_to_go_1020_220726.csv')\r\n\r\n# transforming data \r\n #train test split\r\n#lda_train_x, lda_test_x, lda_train_y, lda_test_y = model_selection.train_test_split(dense_dfND['tweet'],dense_dfND['vaccine_type'])\r\n\r\n #feature engineering\r\ncv_lda = TfidfVectorizer(stop_words='english',ngram_range=(1,2))\r\n\r\n\r\nlda_text = cv_lda.fit_transform(tweet_df.tweet)\r\n\r\n\r\n\r\n\r\n\r\n#model\r\nlda_model = decomposition.LatentDirichletAllocation(n_components = 4 , verbose=1, max_iter=20)\r\n#mode fit/transform\r\nX_topics = lda_model.fit_transform(lda_text)\r\ntopic_word = lda_model.components_\r\nvocab = cv_lda.get_feature_names()\r\n\r\n\r\nn_top_words = 10\r\ntopic_summaries = []\r\nfor topic_dist in topic_word:\r\n topic_words = np.array(vocab)[np.argsort(topic_dist)][:-(n_top_words+1):-1]\r\n topic_summaries.append(','.join(topic_words))","repo_name":"AntonG-89/vaccine_se_twitter","sub_path":"LDA.py","file_name":"LDA.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"20973248771","text":"import json\nimport torch\nimport logging\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport torch.nn.functional as F\n\nfrom PIL import Image\nfrom torch import nn\nfrom torchvision import models\nfrom argparse import ArgumentParser\n\nlogging.basicConfig(level=logging.DEBUG,\n format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',\n datefmt='%m-%d %H:%M')\n\nlogger = logging.getLogger(__file__)\n\nparser = ArgumentParser(description='Process solution arguments.')\nparser.add_argument('--device', type=str, default='cpu', help='Device used for training (cuda or cpu)')\nparser.add_argument('--image-path', type=str, help='Path to image')\nparser.add_argument('--class-file-path', type=str, help='Path to file mapping classes to names',\n default='cat_to_name.json')\nparser.add_argument('--model-path', type=str, help='Path to model checkpoint')\nparser.add_argument('--k', type=int, help='Number of elements to be used by top-k', default=1)\n\n\ndef get_cat_to_name(path='cat_to_name.json'):\n cat_to_name = None\n try:\n path_list = path.split('.')\n if len(path_list) == 0:\n raise ValueError('Invalid path')\n elif len(path_list) > 0 and path_list[-1] != 'json':\n raise ValueError('Invalid file format. Json type should be selected')\n else:\n with open(path, 'r') as f:\n cat_to_name = json.load(f)\n except FileNotFoundError:\n return cat_to_name\n\n return cat_to_name\n\n\nclass DeepFeedForwardNet(nn.Module):\n def __init__(self, input_shape, layers=2, units=128, dropout=0.5):\n super(DeepFeedForwardNet, self).__init__()\n self.input_shape = input_shape\n self.input = nn.Linear(input_shape, units)\n self.out = nn.Linear(units, 102)\n if dropout is not None:\n self.dropout = nn.Dropout(dropout)\n else:\n self.dropout = dropout\n\n self.layers = list()\n for i in range(layers):\n self.layers.append(nn.Linear(units, units))\n\n self.layers = nn.ModuleList(self.layers)\n\n def forward(self, x):\n if self.dropout is not None:\n y = F.relu(self.dropout(self.input(x)))\n\n for layer in self.layers:\n y = F.relu(self.dropout(layer(y)))\n else:\n y = F.relu(self.input(x))\n\n for layer in self.layers:\n y = F.relu(layer(y))\n\n out = self.out(y)\n\n return out\n\n\ndef load_model_checkpoint_only(model_path_, device_='cpu'):\n logger.info('Loading checkpoint located at: {}'.format(model_path_))\n\n parameters = model_path_.split('/')\n\n if len(parameters) == 0:\n raise ValueError('Wrong model dir format')\n\n parameters = parameters[-1].split('-')\n\n name = parameters[0] # Pretrained model name.\n layers = int(parameters[1].replace('dnn', '')) # Number of layers in the checkpoint name.\n hidden_units = int(parameters[2].split('_')[0])\n\n # checkpoint = torch.load(model_dir_)\n checkpoint = torch.load(model_path_, map_location=lambda storage, loc: storage)\n model_checkpoint = checkpoint['model']\n net = models.__dict__[name](pretrained=True)\n\n if 'vgg' in name:\n input_features = 25088 # VGG input\n elif 'resnet' in name:\n input_features = 512 # Resnet input\n else:\n input_features = 9216 # Alexnet input\n\n dff_net = DeepFeedForwardNet(input_features, layers, hidden_units)\n # dff_net = dff_net.to(device_)\n\n for p in net.parameters():\n p.requires_grad = False\n\n if 'resnet' in name:\n net.fc = dff_net\n else:\n net.classifier = dff_net\n\n net = net.to(device_)\n net.load_state_dict(model_checkpoint)\n net.class_to_index = checkpoint['classes']\n\n logger.info('Model loaded')\n\n return net\n\n\ndef resize_and_keep_ar(pil_image, smaller_side):\n w, h = pil_image.size\n\n if w < h:\n new_w = smaller_side\n w_ratio = (new_w / float(pil_image.size[0]))\n new_h = int((float(pil_image.size[1]) * float(w_ratio)))\n else:\n new_h = smaller_side\n h_ratio = (new_h / float(pil_image.size[1]))\n new_w = int((float(pil_image.size[0]) * float(h_ratio)))\n\n return pil_image.resize((new_w, new_h))\n\n\ndef center_square_crop(pil_image, size):\n width, height = pil_image.size\n\n left = (width - size) / 2\n top = (height - size) / 2\n right = (width + size) / 2\n bottom = (height + size) / 2\n\n return pil_image.crop((left, top, right, bottom))\n\n\ndef normalize_image(pil_image):\n image_as_array = np.array(pil_image)\n img = torch.from_numpy(image_as_array.transpose((2, 0, 1)))\n\n if isinstance(img, torch.ByteTensor):\n img = img.float().div(255)\n\n for t, m, s in zip(img, [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]):\n t.sub_(m).div_(s)\n\n return img.numpy()\n\n\ndef process_image(image):\n ''' Scales, crops, and normalizes a PIL image for a PyTorch model,\n returns an Numpy array\n '''\n _CROP_DIM = 224\n _RESIZE_SIZE = 256\n\n im = Image.fromarray(np.array(image))\n\n resized = resize_and_keep_ar(im, _RESIZE_SIZE)\n cropped = center_square_crop(resized, _CROP_DIM)\n normalized = normalize_image(cropped)\n\n return normalized\n\n\ndef imshow(image, ax=None, title=None):\n \"\"\"Imshow for Tensor.\"\"\"\n if ax is None:\n fig, ax = plt.subplots()\n\n # PyTorch tensors assume the color channel is the first dimension\n # but matplotlib assumes is the third dimension\n image = image.numpy().transpose((1, 2, 0))\n\n # Undo preprocessing\n mean = np.array([0.485, 0.456, 0.406])\n std = np.array([0.229, 0.224, 0.225])\n image = std * image + mean\n\n # Image needs to be clipped between 0 and 1 or it looks like noise when displayed\n image = np.clip(image, 0, 1)\n\n if title is not None:\n ax.set_title(title)\n else:\n ax.set_title(\"Flower Species\")\n\n ax.imshow(image)\n\n return ax\n\n\ndef predict(image_path_, model_, device_='cpu', topk=5, class_mapping_file=None):\n ''' Predict the class (or classes) of an image using a trained deep learning model.\n '''\n\n logger.info(\"Starting prediction mode with top-{}\".format(topk))\n\n image_as_tensor = torch.Tensor(process_image(Image.open(image_path_))).reshape([1, 3, 224, 224])\n reverse = {k: v for v, k in model_.class_to_index.items()}\n\n # Switch the model to eval mode\n model_.eval()\n model_ = model_.to(device_)\n image_as_tensor = image_as_tensor.to(device_) # Switching input to same device as model.\n\n class_labels = get_cat_to_name(class_mapping_file if class_mapping_file is not None else \"cat_to_name.json\")\n\n # Predict input\n predicted_ = F.softmax(model_(image_as_tensor), dim=1)\n preds = predicted_.topk(topk)\n\n probs = [float(prob) for prob in preds[0][0]]\n classes = [class_labels[str(reverse[int(cls)])] for cls in preds[1][0]]\n\n return probs, classes\n\n\ndef plot_charts(tensor_image, true_label, pred_classes, pred_probas):\n ''' Auxiliar function used to create and plot charts given an image and some required information.\n '''\n\n fig, (ax1, ax2) = plt.subplots(2, figsize=(5, 10))\n\n cat_to_name = get_cat_to_name()\n\n y_pos = np.arange(len(pred_classes))\n performance = np.asarray(pred_probas)\n classes = (cat_to_name[class_] for class_ in pred_classes)\n\n ax2.barh(y_pos, performance, align='center', color='blue', ecolor='black')\n ax2.set_yticks(y_pos)\n ax2.set_yticklabels(classes)\n ax2.invert_yaxis()\n ax2.set_xlabel('Probability')\n ax2.set_title('Predicted classes')\n\n fig.subplots_adjust(hspace=0.3)\n\n imshow(tensor_image, ax=ax1, title=cat_to_name[true_label])\n\n plt.show()\n\n\ndef sanity_check(image_path_, model_, topk=5):\n prb_, cls_ = predict(image_path_, model_, topk)\n\n tensor_image = torch.Tensor(process_image(Image.open(image_path)))\n true_label = image_path.split('/')[2]\n\n plot_charts(tensor_image, true_label, cls_, prb_)\n\n\nif __name__ == '__main__':\n\n args = parser.parse_args()\n\n image_path = args.image_path\n model_path = args.model_path\n class_file = args.class_file_path\n k = args.k\n\n if args.device == 'cuda':\n if not torch.cuda.is_available():\n device = 'cpu'\n logger.warning('Cuda is not available on this machine, setting device to cpu')\n else:\n device = args.device\n else:\n device = args.device\n\n logger.info('Device mode set to {}'.format(device))\n\n model = load_model_checkpoint_only(model_path, device)\n probs, classes = predict(image_path, model, device_=device, topk=1, class_mapping_file=class_file)\n logger.info(list(zip(probs, classes)))\n\n top_k_probs, top_k_classes = predict(image_path, model, device_=device, topk=k, class_mapping_file=class_file)\n logger.info(list(zip(top_k_probs, top_k_classes)))\n","repo_name":"pcastanha/image","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":8875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"23454682168","text":"#!/usr/bin/python\n\nfrom bcc import BPF\nfrom bcc.utils import printb\nimport ctypes as ct\n\n# Adjust to your liking\nnvidia_dkms = \"/usr/src/nvidia-510.54\"\n\n# load BPF program\nb = BPF(src_file=\"uvm.c\", cflags=[f\"-I{nvidia_dkms}/common/inc\", f\"-I{nvidia_dkms}\"])\n\nb.attach_kprobe(event=\"uvm_perf_event_notify\", fn_name=\"uvm_perf_event_notify\")\n\ndef transfer_mode(m):\n if m == 1:\n return \"Move\"\n elif m == 2:\n return \"Copy\"\n else:\n return \"Unknown\"\n\n\ndef cause(c):\n if c == 0:\n return \"Replayable Fault\"\n elif c == 1:\n return \"Non Replayable Fault\"\n elif c == 2:\n return \"Access Counter\"\n elif c == 3:\n return \"Prefetch\"\n elif c == 4:\n return \"Eviction\"\n elif c == 5:\n return \"API Tools\"\n elif c == 6:\n return \"API Migrate\"\n elif c == 7:\n return \"API Set Range Group\"\n elif c == 8:\n return \"API Hint\"\n else:\n return \"Unknown\"\n\n# define output data structure in Python\nclass Migration(ct.Structure):\n _fields_ = [\n (\"dst\", ct.c_uint32),\n (\"src\", ct.c_uint32),\n (\"address\", ct.c_uint64),\n (\"bytes\", ct.c_uint64),\n (\"transfer_mode\", ct.c_int),\n (\"cause\", ct.c_int)]\n\n\ndef print_migration(cpu, data, size):\n m = ct.cast(data, ct.POINTER(Migration)).contents\n printb(\n b\"Migration from proc %-6d to %-6d (va: 0x%x, %d bytes, mode: %b, cause: %b)\"\n % (m.src, m.dst, m.address, m.bytes, transfer_mode(m.transfer_mode).encode(), cause(m.cause).encode())\n )\n\ndef print_gpu_fault(cpu, data, size):\n fault = b[\"gpu_faults\"].event(data)\n if fault.is_duplicated or fault.filtered:\n printb(\n b\"Duplicated GPU fault on proc %-6d (va: 0x%x)\"\n % (fault.proc_id, fault.fault_va)\n )\n else:\n printb(\n b\"GPU fault on proc %-6d (va: 0x%x)\"\n % (fault.proc_id, fault.fault_va)\n )\n\ndef print_cpu_fault(cpu, data, size):\n fault = b[\"cpu_faults\"].event(data)\n printb(\n b\"CPU fault on proc %-6d (write: %r, va: 0x%x, pc: 0x%x)\"\n % (fault.proc_id, bool(fault.is_write), fault.fault_va, fault.pc)\n )\n\nprint(\"Tracing... Hit Ctrl-C to end.\")\n# loop with callback to print_event\nb[\"migrations\"].open_perf_buffer(print_migration)\nb[\"gpu_faults\"].open_perf_buffer(print_gpu_fault)\nb[\"cpu_faults\"].open_perf_buffer(print_cpu_fault)\n# b[\"revocations\"].open_perf_buffer(print_revocations)\nwhile 1:\n try:\n b.perf_buffer_poll()\n except KeyboardInterrupt:\n exit()\n","repo_name":"vchuravy/bpf_uvm","sub_path":"uvm.py","file_name":"uvm.py","file_ext":"py","file_size_in_byte":2539,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"76"} +{"seq_id":"3188814111","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport curses\nimport sys\nimport time\n\nimport options\nfrom life import Life\n\n\ndef main(args):\n curses.wrapper(CLI(options.parse(args)).run)\n\n\nclass CLI:\n outputs = {0: \"∙\", 1: \"█\"}\n\n def __init__(self, options):\n self.options = options\n\n def run(self, stdscr):\n CLIRunner.load(self.options, stdscr).run()\n\n\nclass CLIRunner:\n @staticmethod\n def load(app_options, stdscr):\n if app_options.input_file:\n life = Life.from_file(app_options.input_file)\n else:\n height, width = stdscr.getmaxyx()\n width = width\n height = height\n life = Life.random(height - 1, width - 1)\n return CLIRunner(app_options.style, stdscr, life)\n\n def __init__(self, style, stdscr, life):\n self.style = style\n self.stdscr = stdscr\n self.life = life\n self.width = life.width\n self.height = life.height\n self.marker = (int(self.width / 2), int(self.height / 2))\n self.show_marker = False\n\n def run(self):\n curses.noecho()\n curses.cbreak()\n curses.start_color()\n curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)\n curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_WHITE)\n\n mode = self.live\n try:\n while True:\n next_mode = mode()\n if next_mode:\n mode = next_mode\n except (Quit, KeyboardInterrupt):\n pass\n\n def live(self):\n self.stdscr.nodelay(True)\n self.show_marker = False\n\n self.display()\n self.life = self.life.step(self.style)\n time.sleep(0.1)\n\n if self.read() == \" \":\n return self.pause\n\n def pause(self):\n self.stdscr.nodelay(False)\n\n self.show_marker = True\n self.display()\n\n ch = self.read()\n if ch == \" \":\n return self.live\n elif ch == \"KEY_UP\":\n self.marker = (\n self.marker[0] % self.width,\n (self.marker[1] - 1) % self.height,\n )\n elif ch == \"KEY_DOWN\":\n self.marker = (\n self.marker[0] % self.width,\n (self.marker[1] + 1) % self.height,\n )\n elif ch == \"KEY_LEFT\":\n self.marker = (\n (self.marker[0] - 1) % self.width,\n self.marker[1] % self.height,\n )\n elif ch == \"KEY_RIGHT\":\n self.marker = (\n (self.marker[0] + 1) % self.width,\n self.marker[1] % self.height,\n )\n\n def read(self):\n try:\n ch = self.stdscr.getkey()\n except curses.error:\n return\n\n if ch == \"q\":\n raise Quit()\n else:\n return ch\n\n def display(self):\n self.stdscr.clear()\n for i, line in enumerate(self.life.matrix.tolist()):\n self.stdscr.addstr(\n i, 0, \"\".join(CLI.outputs[n] for n in line), curses.color_pair(1)\n )\n if self.show_marker:\n self.stdscr.addstr(\n self.marker[1], self.marker[0], \" \", curses.color_pair(2)\n )\n self.stdscr.move(self.height - 1, 0)\n self.stdscr.refresh()\n\n\nclass Quit(Exception):\n pass\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","repo_name":"SamirTalwar/predestination","sub_path":"src/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":3390,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"76"} +{"seq_id":"19886712042","text":"#!/usr/bin/python3\n\n\"\"\"\nModule 2-square\nDefines clas square with private attribute size\n\n\"\"\"\n\n\nclass Square:\n \"\"\"\n Class square defines a square by size\n Args:\n size: size of the side\n \"\"\"\n def __init__(self, size = 0):\n \"\"\"\n initialises size with default 0 \n checks if size has the correct type and value\n \n Attributes:\n __size: size of the side in square\n \"\"\"\n if type(size) is not int:\n raise TypeError(\"Size must be an integer\")\n elif size < 0:\n raise ValueError(\"Size must be >= 0\")\n else:\n self.__size = size\n","repo_name":"Soft-Mahmood/alx-higher_level_programming","sub_path":"0x06-python-classes/2-square.py","file_name":"2-square.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"39673843627","text":"#!/usr/bin/python3\n\"\"\"this module contains a function to divide a matrix.\n\"\"\"\n\n\ndef matrix_divided(matrix, div):\n \"\"\"this function divides a matrix\n\n Args:\n matrix (list): a list of lists of floats or ints\n div (int or float): number to divide everything by\n\n Raises:\n TypeError: if matrix is not a list\n TypeError: if each member of matrix is not a list\n TypeError: if the lists are of different sizes\n TypeError: if the members of each sublist are not ints/floats\n TypeError: if div is not a number\n ZeroDivisionError: if div is zero\n\n Returns:\n _type_: _description_\n \"\"\"\n if type(matrix) != list:\n raise TypeError(\"matrix must be a matrix (list of lists) of \\\nintegers/floats\")\n for member in matrix:\n if type(member) != list:\n raise TypeError(\"matrix must be a matrix (list of lists) \\\nof integers/floats\")\n if len(member) != len(matrix[0]):\n raise TypeError(\"Each row of the matrix must have the same size\")\n for i in member:\n if type(i) != int and type(i) != float:\n raise TypeError(\"matrix must be a matrix (list of lists) \\\nof integers/floats\")\n if type(div) != int and type(div) != float:\n raise TypeError(\"div must be a number\")\n if div == 0:\n raise ZeroDivisionError(\"division by zero\")\n newmatrix = [x[:] for x in matrix]\n for newmember in newmatrix:\n for newi in range(len(newmember)):\n newmember[newi] = round(newmember[newi] / div, 2)\n return newmatrix\n","repo_name":"wdmd2022/holbertonschool-higher_level_programming","sub_path":"0x07-python-test_driven_development/2-matrix_divided.py","file_name":"2-matrix_divided.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"8554618835","text":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Flatten, Dense\nfrom tensorflow.keras.datasets import fashion_mnist\nfrom tensorflow.keras.callbacks import EarlyStopping\n\n\ndef load_fashion_mnist():\n \"\"\"\n Loads the fashion MNIST dataset into memory. It also normalizes the input\n data to lie between 0 and 1.\n\n Returns:\n x_train -- (60000,28,28) numpy array, 60000 28x28 grayscale images\n y_train -- (60000,) numpy array, 60000 0-9 integer labels\n x_valid -- (10000, 28,28) numpy array, 10000 28x28 grayscale images\n y_valid -- (10000,), 10000 0-9 integer labels\n \"\"\"\n (x_train, y_train), (x_valid, y_valid) = fashion_mnist.load_data()\n return x_train/255, y_train, x_valid/255, y_valid\n\n\ndef nn_model():\n \"\"\"\n Defines a NN model to learn the fashion MNIST dataset\n\n Returns:\n model -- keras model object, containing the model\n \"\"\"\n model = Sequential()\n model.add(Flatten(input_shape=(28,28)))\n model.add(Dense(512, activation='relu'))\n model.add(Dense(256, activation='relu'))\n model.add(Dense(10, activation='softmax'))\n return model\n\n\ndef compile_fit(model, x_train, y_train, x_valid, y_valid):\n \"\"\"\n Compiles and fits the model to the training data. Validates on the\n validation data passed in to the function\n\n Args:\n model: keras sequential object -- containing the model\n x_train: numpy array (60000,28,28) -- 60000 training 28x28 images\n y_train: numpy array (60000,) -- 60000 training labels\n x_valid: numpy array (10000,28,28) -- 10000 validation 28x28 images\n y_valid: numpy array (10000,) -- 10000 validation labels\n\n Returns:\n history -- History object -- containing the history of model trianing\n \"\"\"\n # compiling the model\n model.compile(optimizer='adam', loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])\n\n # callbacks to stop training earlier than planned\n early_stop = EarlyStopping(monitor='val_accuracy', min_delta=0.001,\n patience=5, mode='max', verbose=1)\n\n # fitting the model to the training data. Validating on the validation set\n history = model.fit(x_train, y_train, epochs=50, validation_data=(\n x_valid, y_valid), callbacks=[early_stop])\n\n return history\n\n\ndef run():\n x_train, y_train, x_valid, y_valid = load_fashion_mnist()\n model = nn_model()\n history = compile_fit(model, x_train, y_train, x_valid, y_valid)\n\n return model, history\n\n\nif __name__ == '__main__':\n model, history = run()\n","repo_name":"connected-ftarlan/tf-specialization","sub_path":"C1/W2/Fashion_MNIST.py","file_name":"Fashion_MNIST.py","file_ext":"py","file_size_in_byte":2601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"15650871189","text":"'''\nCreated on Sep 29, 2022\n\n@author: estudiante\n'''\n#Realizar un programa que lea un carácter y dos números enteros por\n#teclado. Si el carácter leído es un operador aritmético, calcular la operación\n#correspondiente, si es cualquier otro debe mostrar un error.\n\nnumero1 = int(input(\"Introduce el número 1: \"))\nnumero2 = int(input(\"Introduce el número 2: \"))\noperador = input(\"Introduce la operacion +, -, *, /: \")\n\nif operador == \"+\":\n suma = numero1 + numero2\n print(\"La suma de los número introducidos es: %s\"(suma))\nelif operador == \"-\":\n resta = numero1 - numero2\n print(\"La resta de los número introducidos es: %s\"(resta))\nelif operador == \"*\":\n multiplicacion = numero1 * numero2\n print(\"La multi`plicacion de los número introducidos es: %s\"(multiplicacion))\nelif operador == \"/\":\n division = numero1 / numero2\n print(\"La division de los número introducidos es: %s\"(division))\n \nelse:\n print(\"Los valores introducidos no son válidos\")\n","repo_name":"iivansaanchez/Programming-Python-","sub_path":"Boletín3-Estructuras condicionales/ejercicio10.py","file_name":"ejercicio10.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"72395760887","text":"import os \nfrom gppylib.gplog import get_default_logger\nfrom .base import Command, LOCAL, REMOTE\n\nlogger = get_default_logger()\n\n# NOTE THIS IS A CHECK FOR 1040 or later appliance\ndef is_dca_appliance():\n try:\n if os.path.isfile('/opt/dca/bin/dca_gpdb_initialized'):\n return True\n except:\n pass\n\n return False\n\n#-----------------------------------------------\nclass DcaGpdbInitialized(Command):\n def __init__(self, name, ctxt=LOCAL, remoteHost=None):\n self.cmdStr=\"/opt/dca/bin/dca_gpdb_initialized\"\n Command.__init__(self, name, self.cmdStr, ctxt, remoteHost)\n\n @staticmethod\n def local():\n try:\n cmd=DcaGpdbInitialized('dcainit')\n cmd.run(validateAfter=True)\n except Exception as e:\n logger.error(e.__str__())\n logger.error(\"Exception running dca initialization\")\n except:\n logger.error(\"Exception running dca initialization\")\n\n#-----------------------------------------------\nclass DcaGpdbStopped(Command):\n def __init__(self, name, ctxt=LOCAL, remoteHost=None):\n self.cmdStr=\"/opt/dca/bin/dca_gpdb_stopped\"\n Command.__init__(self, name, self.cmdStr, ctxt, remoteHost)\n\n @staticmethod\n def local():\n try:\n cmd=DcaGpdbStopped('dcastop')\n cmd.run(validateAfter=True)\n except Exception as e:\n logger.error(e.__str__())\n logger.error(\"Exception running dca de-initialization\")\n except:\n logger.error(\"Exception running dca de-initialization\")\n\n","repo_name":"greenplum-db/gpdb","sub_path":"gpMgmt/bin/gppylib/commands/dca.py","file_name":"dca.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","stars":6032,"dataset":"github-code","pt":"76"} +{"seq_id":"11884099093","text":"from os.path import dirname, join\nimport os\nimport pandas as pd\nfrom bokeh.io import curdoc\nfrom bokeh.layouts import row, column\nfrom bokeh.models import Button, Slider, Toggle, FactorRange, Div, ColumnDataSource, LabelSet, Select,Legend, LegendItem, DataTable, TableColumn, HoverTool, Slope\nfrom bokeh.plotting import figure\nfrom bokeh.events import ButtonClick\nfrom classes import parameters, moments, var\nfrom data_funcs import compute_rough_jacobian,rough_dyn_fixed_point_solver\nimport numpy as np\nimport itertools\nfrom bokeh.palettes import Category10, Dark2\nCategory18 = Category10[10]+Dark2[8]\nimport time\nimport warnings\nwarnings.simplefilter('ignore', np.RankWarning)\n# warnings.simplefilter('ignore', np.RuntimeWarning)\nwarnings.filterwarnings('ignore')\n\nstart = time.perf_counter()\n\ndef load(path, data_path=None, \n dir_path = None, context = 'calibration'):\n # p = parameters(data_path=data_path)\n p = parameters()\n # p.load_data(path)\n p.load_run(path,dir_path=dir_path)\n sol = var.var_from_vector(p.guess, p, compute=True, context = context)\n sol.scale_P(p)\n sol.compute_price_indices(p)\n sol.compute_non_solver_quantities(p)\n m = moments()\n # m.load_data(data_path)\n m.load_run(path,dir_path=dir_path)\n m.compute_moments(sol, p)\n m.compute_moments_deviations()\n return p,m,sol\n\ndef init_dic_of_dataframes_with_baseline(p_baseline,m_baseline,sol_baseline,list_of_moments):\n dic_df_param = {}\n dic_df_mom = {}\n dic_df_sol = {}\n params = p_baseline.calib_parameters\n params.append('kappa')\n params.append('r_hjort')\n if 'theta' not in params:\n params.append('theta')\n params.append('theta')\n # params.append('d*fe')\n # params.append('nu/deltaUS')\n df_scalar_params = pd.DataFrame(columns = ['baseline'])\n df_scalar_params.index.name='x'\n \n for param in params:\n if hasattr(p_baseline,param):\n if len(getattr(p_baseline,param)[p_baseline.mask[param]]) == 1:\n if param == 'k':\n df_scalar_params.loc[param,'baseline'] = float(getattr(p_baseline,param)[p_baseline.mask[param]])-1\n else:\n df_scalar_params.loc[param,'baseline'] = float(getattr(p_baseline,param)[p_baseline.mask[param]])\n if param in ['eta','delta']:\n df = pd.DataFrame(index = p_baseline.countries, columns = ['baseline'], data = getattr(p_baseline,param)[...,1])\n df.index.name='x'\n dic_df_param[param] = df\n if param in ['r_hjort']:\n df = pd.DataFrame(index = p_baseline.countries, columns = ['baseline'], data = getattr(p_baseline,param))\n df.index.name='x'\n dic_df_param[param] = df\n if param in ['T']:\n df = pd.DataFrame(index = p_baseline.countries, columns = ['baseline'], data = getattr(p_baseline,param)[...,0])\n df.index.name='x'\n dic_df_param[param+' non patent sector'] = df\n df = pd.DataFrame(index = p_baseline.countries, columns = ['baseline'], data = getattr(p_baseline,param)[...,1])\n df.index.name='x'\n dic_df_param[param+' patent sector'] = df\n elif param == 'd*fe':\n df_scalar_params.loc[param,'baseline'] = float(getattr(p_baseline,'d')[p_baseline.mask['d']])*float(getattr(p_baseline,'fe')[p_baseline.mask['fe']])\n elif param == 'nu/deltaUS':\n df_scalar_params.loc[param,'baseline'] = float(getattr(p_baseline,'nu')[1])/float(getattr(p_baseline,'delta')[0,1])\n dic_df_param['scalars'] = df_scalar_params\n \n df_scalar_moments = pd.DataFrame(columns = ['target','baseline'])\n df_scalar_moments.index.name='x'\n for mom in list_of_moments:\n if mom != 'objective':\n if len(m_baseline.idx[mom]) == 1:\n if mom != 'OUT':\n try:\n df_scalar_moments.loc[mom,'target'] = float(getattr(m_baseline,mom+'_target'))\n df_scalar_moments.loc[mom,'baseline'] = float(getattr(m_baseline,mom))\n except:\n pass\n else:\n try:\n df = pd.DataFrame(index = m_baseline.idx[mom], \n columns = ['target','baseline'], \n # data = np.array([getattr(m_baseline,mom+'_target').ravel(), getattr(m_baseline,mom).ravel()])\n )\n df.index.name='x'\n df['target'] = getattr(m_baseline,mom+'_target').ravel()\n df['baseline'] = getattr(m_baseline,mom).ravel()\n dic_df_mom[mom] = df\n except:\n pass\n \n for sol_qty in ['semi_elast_patenting_delta','DT','psi_o_star']:\n df = pd.DataFrame(index = p_baseline.countries, \n columns = ['baseline'], \n )\n df.index.name='x'\n df['baseline'] = getattr(sol_baseline,sol_qty)[...,1]\n dic_df_sol[sol_qty] = df\n \n for sol_qty in ['l_R']:\n df = pd.DataFrame(index = p_baseline.countries, \n columns = ['baseline'], \n )\n df.index.name='x'\n df['baseline'] = getattr(sol_baseline,sol_qty)[...,1]/p_baseline.labor\n dic_df_sol[sol_qty] = df\n \n for sol_qty in ['min_psi_m_star_inward']:\n df = pd.DataFrame(index = p_baseline.countries, \n columns = ['baseline'], \n )\n df.index.name='x'\n df['baseline'] = getattr(sol_baseline,'psi_m_star')[:,:,1].min(axis=1)\n dic_df_sol[sol_qty] = df\n \n for sol_qty in ['min_psi_m_star_outward']:\n df = pd.DataFrame(index = p_baseline.countries, \n columns = ['baseline'], \n )\n df.index.name='x'\n df['baseline'] = getattr(sol_baseline,'psi_m_star')[:,:,1].min(axis=0)\n dic_df_sol[sol_qty] = df\n \n df_scalar_moments.loc['objective','target'] = 0.01\n df_scalar_moments.loc['objective','baseline'] = m_baseline.objective_function()*28\n dic_df_mom['scalars'] = df_scalar_moments\n return dic_df_param, dic_df_mom, dic_df_sol\n\ndef append_dic_of_dataframes_with_variation(dic_df_param, dic_df_mom, dic_df_sol, p, m, sol, run_name):\n for k in dic_df_param.keys():\n if k == 'scalars':\n for i in dic_df_param[k].index:\n if i == 'k':\n dic_df_param[k].loc[i,run_name] = float(getattr(p,i)[p.mask[i]])-1\n elif i == 'd*fe':\n dic_df_param[k].loc[i,run_name] = float(getattr(p,'d')[p.mask['d']])*float(getattr(p,'fe')[p.mask['fe']])\n elif i == 'nu/deltaUS':\n dic_df_param[k].loc[i,run_name] = float(getattr(p,'nu')[1])/float(getattr(p,'delta')[0,1])\n else:\n dic_df_param[k].loc[i,run_name] = float(getattr(p,i)[p.mask[i]])\n \n if k in ['eta','delta']:\n dic_df_param[k][run_name] = getattr(p,k)[...,1]\n if k in ['r_hjort']:\n dic_df_param[k][run_name] = getattr(p,k)\n if k == 'T non patent sector':\n dic_df_param[k][run_name] = getattr(p,'T')[...,0]\n if k == 'T patent sector':\n dic_df_param[k][run_name] = getattr(p,'T')[...,1]\n \n for k in dic_df_mom.keys():\n if k == 'scalars':\n for i in dic_df_mom[k].index:\n if i == 'objective':\n dic_df_mom[k].loc[i,run_name] = m.objective_function()*28\n else:\n dic_df_mom[k].loc[i,run_name] = float(getattr(m,i))\n if k == 'scalar deviations':\n for i in dic_df_mom[k].index:\n dic_df_mom[k].loc[i,run_name] = float(getattr(m,i+'_deviation'))/m.weights_dict[i]\n if k not in ['scalars','scalar deviations']:\n dic_df_mom[k][run_name] = getattr(m,k).ravel()\n \n for k in dic_df_sol.keys():\n if k in ['semi_elast_patenting_delta','DT','psi_o_star']:\n dic_df_sol[k][run_name] = getattr(sol,k)[...,1]\n if k in ['l_R']:\n dic_df_sol[k][run_name] = getattr(sol,k)[...,1]/p.labor\n if k in ['min_psi_m_star_outward']:\n dic_df_sol[k][run_name] = getattr(sol,'psi_m_star')[:,:,1].min(axis=0)\n if k in ['min_psi_m_star_inward']:\n dic_df_sol[k][run_name] = getattr(sol,'psi_m_star')[:,:,1].min(axis=1)\n \n return dic_df_param, dic_df_mom, dic_df_sol\n\n#%% path\ndir_path = dirname(__file__)+'/'\ndata_path = join(dirname(__file__), 'data/')\n# dir_path = './'\n# data_path = 'data/'\n# results_path = 'calibration_results_matched_economy/'\nresults_path = join(dirname(__file__), 'calibration_results_matched_economy/')\ncf_path = join(dirname(__file__), 'counterfactual_recaps/unilateral_patent_protection/')\naround_dyn_eq_path = join(dirname(__file__), 'counterfactual_recaps/')\nnash_eq_path = join(dirname(__file__), 'nash_eq_recaps/')\ncoop_eq_path = join(dirname(__file__), 'coop_eq_recaps/')\n\n\n#%% moments / parameters for variations\n\nlist_of_moments = ['GPDIFF','GROWTH','KM', 'OUT',\n 'RD', 'RP', 'SPFLOWDOM', 'SPFLOW','STFLOW','STFLOWSDOM',\n 'SRGDP','UUPCOST','SINNOVPATUS',\n 'TO','TE','DOMPATINUS','DOMPATUS',\n 'TWSPFLOW','TWSPFLOWDOM','SDOMTFLOW','objective']\n# list_of_moments = ['GPDIFF','GROWTH','KM', 'OUT',\n# 'RD', 'RP', 'SPFLOWDOM', 'SPFLOW','STFLOW','STFLOWSDOM',\n# 'SRDUS', 'SRGDP','UUPCOST', 'PCOST','PCOSTINTER','PCOSTNOAGG','PCOSTINTERNOAGG','SINNOVPATUS',\n# 'SINNOVPATEU', 'TO','TP',\n# 'DOMPATUS','DOMPATEU','DOMPATINUS','DOMPATINEU','TWSPFLOW','TWSPFLOWDOM','SDOMTFLOW','objective']\n\ncomments_dic = {}\n\ncomments_dic['403'] = {'baseline':'bsln:TO:0.0183',\n '1.0':'1.0: TO: 0.01',\n'1.1':'1.1: TO: 0.0105',\n'1.2':'1.2: TO: 0.011',\n'1.3':'1.3: TO: 0.0115',\n'1.4':'1.4: TO: 0.012',\n'1.5':'1.5: TO: 0.0125',\n'1.6':'1.6: TO: 0.013',\n'1.7':'1.7: TO: 0.0135',\n'1.8':'1.8: TO: 0.014',\n'1.9':'1.9: TO: 0.0145',\n'1.10':'1.10: TO: 0.015',\n'1.11':'1.11: TO: 0.0155',\n'1.12':'1.12: TO: 0.016',\n'1.13':'1.13: TO: 0.0165',\n'1.14':'1.14: TO: 0.017',\n'1.15':'1.15: TO: 0.0175',\n'1.16':'1.16: TO: 0.018',\n'1.17':'1.17: TO: 0.0185',\n'1.18':'1.18: TO: 0.019',\n'1.19':'1.19: TO: 0.0195',\n'1.20':'1.20: TO: 0.02',\n'1.21':'1.21: TO: 0.0205',\n'1.22':'1.22: TO: 0.021',\n'1.23':'1.23: TO: 0.0215',\n'1.24':'1.24: TO: 0.022',\n'1.25':'1.25: TO: 0.0225',\n'1.26':'1.26: TO: 0.023',\n'1.27':'1.27: TO: 0.0235',\n'1.28':'1.28: TO: 0.024',\n'1.29':'1.29: TO: 0.0245',\n'1.30':'1.30: TO: 0.025',\n'1.31':'1.31: TO: 0.0255',\n'1.32':'1.32: TO: 0.026',\n'1.33':'1.33: TO: 0.0265',\n'1.34':'1.34: TO: 0.027',\n'1.35':'1.35: TO: 0.0275',\n'1.36':'1.36: TO: 0.028',\n'1.37':'1.37: TO: 0.0285',\n'1.38':'1.38: TO: 0.029',\n'1.39':'1.39: TO: 0.0295',\n'1.40':'1.40: TO: 0.03'\n }\ncomments_dic['405'] = {'baseline':'bsln:TO:0.0183',\n '1.0':'1.0: TO: 0.01',\n'1.1':'1.1: TO: 0.0105',\n'1.2':'1.2: TO: 0.011',\n'1.3':'1.3: TO: 0.0115',\n'1.4':'1.4: TO: 0.012',\n'1.5':'1.5: TO: 0.0125',\n'1.6':'1.6: TO: 0.013',\n'1.7':'1.7: TO: 0.0135',\n'1.8':'1.8: TO: 0.014',\n'1.9':'1.9: TO: 0.0145',\n'1.10':'1.10: TO: 0.015',\n'1.11':'1.11: TO: 0.0155',\n'1.12':'1.12: TO: 0.016',\n'1.13':'1.13: TO: 0.0165',\n'1.14':'1.14: TO: 0.017',\n'1.15':'1.15: TO: 0.0175',\n'1.16':'1.16: TO: 0.018',\n'1.17':'1.17: TO: 0.0185',\n'1.18':'1.18: TO: 0.019',\n'1.19':'1.19: TO: 0.0195',\n'1.20':'1.20: TO: 0.02',\n'1.21':'1.21: TO: 0.0205',\n'1.22':'1.22: TO: 0.021',\n'1.23':'1.23: TO: 0.0215',\n'1.24':'1.24: TO: 0.022',\n'1.25':'1.25: TO: 0.0225',\n'1.26':'1.26: TO: 0.023',\n'1.27':'1.27: TO: 0.0235',\n'1.28':'1.28: TO: 0.024',\n'1.29':'1.29: TO: 0.0245',\n'1.30':'1.30: TO: 0.025',\n'1.31':'1.31: TO: 0.0255',\n'1.32':'1.32: TO: 0.026',\n'1.33':'1.33: TO: 0.0265',\n'1.34':'1.34: TO: 0.027',\n'1.35':'1.35: TO: 0.0275',\n'1.36':'1.36: TO: 0.028',\n'1.37':'1.37: TO: 0.0285',\n'1.38':'1.38: TO: 0.029',\n'1.39':'1.39: TO: 0.0295',\n'1.40':'1.40: TO: 0.03'\n }\n\ncomments_dic['404'] = {\n 'baseline':'baseline',\n '1.0':'1.0: SRDUS, UUPCOST, log loss',\n '1.1':'1.1: SRDUS, UUPCOST, ratio loss',\n '1.2':'1.2: SRDUS, PCOSTNOAGG, log loss',\n '1.3':'1.3: SRDUS, PCOSTNOAGG, ratio loss',\n '1.4':'1.4: no SRDUS, UUPCOST, log loss',\n '1.5':'1.5: no SRDUS, UUPCOST, ratio loss',\n '1.6':'1.6: no SRDUS, PCOSTNOAGG, log loss',\n '1.7':'1.7: no SRDUS, PCOSTNOAGG, ratio loss',\n '1.8':'1.8: no RD, UUPCOST, log loss',\n '1.9':'1.9: no RD, UUPCOST, ratio loss',\n '1.10':'1.10: no RD, PCOSTNOAGG, log loss',\n '1.11':'1.11: no RD, PCOSTNOAGG, ratio loss',\n '2.0':'2.0: sigma=2.7, SRDUS, UUPCOST',\n '2.1':'2.1: sigma=2.7, no SRDUS, UUPCOST',\n '2.2':'2.2: sigma=2.7, SRDUS, PCOSTNOAGG',\n '2.3':'2.3: sigma=2.7, no SRDUS, PCOSTNOAGG',\n }\n\ncomments_dic['501'] = {\n \"baseline\":\"baseline\",\n '1.0':'1.0: Higher growth weight',\n '2.0':'2.0: Hjort correc real GDP',\n '3.0':'3.0: No drop RD South',\n '4.0':'4.0: New data',\n '5.0':'5.0: New data v2',\n }\n\ncomments_dic['601'] = {\n \"baseline\":\"baseline : 2005\",\n \"1.0\" : \"1.0 : 1990\",\n \"1.1\" : \"1.1 : 1991\",\n \"1.2\" : \"1.2 : 1992\",\n \"1.3\" : \"1.3 : 1993\",\n \"1.4\" : \"1.4 : 1994\",\n \"1.5\" : \"1.5 : 1995\",\n \"1.6\" : \"1.6 : 1996\",\n \"1.7\" : \"1.7 : 1997\",\n \"1.8\" : \"1.8 : 1998\",\n \"1.9\" : \"1.9 : 1999\",\n \"1.10\" : \"1.10 : 2000\",\n \"1.11\" : \"1.11 : 2001\",\n \"1.12\" : \"1.12 : 2002\",\n \"1.13\" : \"1.13 : 2003\",\n \"1.14\" : \"1.14 : 2004\",\n \"1.15\" : \"1.15 : 2005\",\n \"1.16\" : \"1.16 : 2006\",\n \"1.17\" : \"1.17 : 2007\",\n \"1.18\" : \"1.18 : 2008\",\n \"1.19\" : \"1.19 : 2009\",\n \"1.20\" : \"1.20 : 2010\",\n \"1.21\" : \"1.21 : 2011\",\n \"1.22\" : \"1.22 : 2012\",\n \"1.23\" : \"1.23 : 2013\",\n \"1.24\" : \"1.24 : 2014\",\n \"1.25\" : \"1.25 : 2015\",\n \"1.26\" : \"1.26 : 2016\",\n \"1.27\" : \"1.27 : 2017\",\n \"1.28\" : \"1.28 : 2018\",\n}\n\ncomments_dic['602'] = comments_dic['601']\ncomments_dic['603'] = comments_dic['601']\n\ncomments_dic['606'] = {\n \"baseline\":\"baseline:SRGDP weight < RP weight\",\n \"2.0\" : \"2.0:SRGDP weight = RP weight\",\n \"3.0\" : \"3.0:SRGDP weight > RP weight\",\n}\ncomments_dic['607'] = comments_dic['601']\ncomments_dic['608'] = comments_dic['601']\ncomments_dic['609'] = comments_dic['601']\ncomments_dic['610'] = comments_dic['601']\ncomments_dic['614'] = comments_dic['601']\ncomments_dic['615'] = comments_dic['601']\ncomments_dic['616'] = comments_dic['601']\ncomments_dic['617'] = comments_dic['601']\ncomments_dic['620'] = comments_dic['601']\ncomments_dic['619'] = comments_dic['601']\n\n\ncomments_dic['611'] = {'baseline':'bsln:TO:0.0183',\n '1.0':'1.0: TO: 0.01',\n'1.1':'1.1: TO: 0.0105',\n'1.2':'1.2: TO: 0.011',\n'1.3':'1.3: TO: 0.0115',\n'1.4':'1.4: TO: 0.012',\n'1.5':'1.5: TO: 0.0125',\n'1.6':'1.6: TO: 0.013',\n'1.7':'1.7: TO: 0.0135',\n'1.8':'1.8: TO: 0.014',\n'1.9':'1.9: TO: 0.0145',\n'1.10':'1.10: TO: 0.015',\n'1.11':'1.11: TO: 0.0155',\n'1.12':'1.12: TO: 0.016',\n'1.13':'1.13: TO: 0.0165',\n'1.14':'1.14: TO: 0.017',\n'1.15':'1.15: TO: 0.0175',\n'1.16':'1.16: TO: 0.018',\n'1.17':'1.17: TO: 0.0185',\n'1.18':'1.18: TO: 0.019',\n'1.19':'1.19: TO: 0.0195',\n'1.20':'1.20: TO: 0.02',\n'1.21':'1.21: TO: 0.0205',\n'1.22':'1.22: TO: 0.021',\n'1.23':'1.23: TO: 0.0215',\n'1.24':'1.24: TO: 0.022',\n'1.25':'1.25: TO: 0.0225',\n'1.26':'1.26: TO: 0.023',\n'1.27':'1.27: TO: 0.0235',\n'1.28':'1.28: TO: 0.024',\n'1.29':'1.29: TO: 0.0245',\n'1.30':'1.30: TO: 0.025',\n'1.31':'1.31: TO: 0.0255',\n'1.32':'1.32: TO: 0.026',\n'1.33':'1.33: TO: 0.0265',\n'1.34':'1.34: TO: 0.027',\n'1.35':'1.35: TO: 0.0275',\n'1.36':'1.36: TO: 0.028',\n'1.37':'1.37: TO: 0.0285',\n'1.38':'1.38: TO: 0.029',\n'1.39':'1.39: TO: 0.0295',\n'1.40':'1.40: TO: 0.03'\n }\n\ncomments_dic['618'] = {\n 'baseline':'baseline',\n '1.0':'1.0:full calibration 2005',\n '1.1':'1.1:full calibration 1992',\n '2.0':'2.0:free f, target UUPCOST, 2005',\n '2.1':'2.1:free f, target UUPCOST, 1992',\n '3.0':'3.0:free f, target UUPCOST and TP, 2005',\n '3.1':'3.1:free f, target UUPCOST and TP, 1992',\n '4.0':'4.0:free f, target UUPCOST and inter_TP, 2005',\n '4.1':'4.1:free f, target UUPCOST and inter_TP, 1992',\n '5.0':'5.0:fixed f, target UUPCOST, 2005',\n '5.1':'5.1:fixed f, target UUPCOST, 1992',\n '6.0':'6.0:fixed f, target UUPCOST and TP, 2005',\n '6.1':'6.1:fixed f, target UUPCOST and TP, 1992',\n '7.0':'7.0:fixed f, target UUPCOST and inter_TP, 2005',\n '7.1':'7.1:fixed f, target UUPCOST and inter_TP, 1992',\n '8.0':'8.0:fixed f, drop UUPCOST, 2005',\n '8.1':'8.1:fixed f, drop UUPCOST, 1992',\n '9.0':'9.0:fixed f, drop UUPCOST, target TP, 2005',\n '9.1':'9.1:fixed f, drop UUPCOST, target TP, 1992',\n '10.0':'10.0:fixed f, drop UUPCOST,target inter_TP, 2005',\n '10.1':'10.1:fixed f, drop UUPCOST,target inter_TP, 1992',\n '11.0':'11.0:fixed f, target UUPCOST, drop SINNOV, 2005',\n '11.1':'11.1:fixed f, target UUPCOST, drop SINNOV, 1992',\n '12.0':'12.0:fixed f, target UUPCOST, inter_TP, drop SINNOV, 2005',\n '12.1':'12.1:fixed f, target UUPCOST, inter_TP, drop SINNOV, 1992',\n '13.0':'13.0:full calibration without SINNOV, 2005',\n '15.0':'15.0:nu=0.1, drop TO',\n '16.0':'16.0:fixed f, target UUPCOST and KM, drop SINNOV, 2005',\n '16.1':'16.1:fixed f, target UUPCOST and KM, drop SINNOV, 1992',\n '17.0':'17.0:fixed f, target UUPCOST and KM and inter_TP, drop SINNOV, 2005',\n '17.1':'17.1:fixed f, target UUPCOST and KM and inter_TP, drop SINNOV, 1992',\n '18.0':'18.0:fixed f, target UUPCOST and KM, 2005',\n '18.1':'18.1:fixed f, target UUPCOST and KM, 1992',\n '19.0':'19.0:fixed f, target UUPCOST and KM and inter_TP, 2005',\n '19.1':'19.1:fixed f, target UUPCOST and KM and inter_TP, 1992',\n '20.0':'20.0:fixed f, target UUPCOST and KM, drop SINNOVUS, 2005',\n '20.1':'20.1:fixed f, target UUPCOST and KM, drop SINNOVUS, 1992',\n '21.0':'21.0:fixed f, drop SINNOV, KM, UUPCOST, keep delta_north fixed 2005',\n '21.1':'21.1:fixed f, drop SINNOV, KM, UUPCOST, keep delta_north fixed 1992',\n '22.1':'22.1:full calibration 1992, scale up nbr of patents',\n }\n\ncomments_dic['701'] = {\n 'baseline':'baseline: same as 607/618 without SINNOVPATEU',\n '1.0':'1.0:full calibration 2005',\n '1.1':'1.1:full calibration 1992',\n '2.0':'2.0:[delta], [SPFLOW], deltaUS fixed',\n '2.1':'2.1:[delta], [SPFLOW], deltaUS fixed',\n '3.0':'3.0:[delta], [SPFLOW,DOMPATIN], deltaUS fixed',\n '3.1':'3.1:[delta], [SPFLOW,DOMPATIN], deltaUS fixed',\n '4.0':'4.0:[delta], [SPFLOW,DOMPATIN], deltaUS fixed',\n '4.1':'4.1:[delta], [SPFLOW,DOMPATIN], deltaUS_1995 = 1.17647 deltaUS_2005',\n '5.0':'5.0:[delta,T], [SPFLOW,DOMPATIN,OUT], deltaUS fixed',\n '5.1':'5.1:[delta,T], [SPFLOW,DOMPATIN,OUT], deltaUS fixed',\n '6.0':'6.0:[delta,T,eta], [SPFLOW,DOMPATIN,OUT,RD,RP,SRGDP], deltaUS fixed',\n '6.1':'6.1:[delta,T,eta], [SPFLOW,DOMPATIN,OUT,RD,RP,SRGDP], deltaUS fixed',\n '7.0':'7.0:[delta,T,eta], [SPFLOW,DOMPATIN,OUT,RD,RP,SRGDP], delta,etaUS fixed',\n '7.1':'7.1:[delta,T,eta], [SPFLOW,DOMPATIN,OUT,RD,RP,SRGDP], delta,etaUS fixed',\n '8.0':'8.0:[delta,T,eta], [SPFLOW,DOMPATIN,OUT,RD,RP,SRGDP,KM], deltaUS fixed',\n '8.1':'8.1:[delta,T,eta], [SPFLOW,DOMPATIN,OUT,RD,RP,SRGDP,KM], deltaUS fixed',\n '9.0':'9.0:[delta,T,eta], [SPFLOW,DOMPATIN,OUT,RD,RP,SRGDP,KM], deltaUS fixed, KM weight=10',\n '9.1':'9.1:[delta,T,eta], [SPFLOW,DOMPATIN,OUT,RD,RP,SRGDP,KM], deltaUS fixed, KM weight=10',\n }\n\ncomments_dic['702'] = {\n 'baseline':'baseline: same as 607/618 without SINNOVPATEU, DOMPATINEU',\n '1.0':'1.0:full calibration 2005',\n '1.1':'1.1:full calibration 1992',\n '2.0':'2.0:[delta], [SPFLOW], deltaUS fixed',\n '2.1':'2.1:[delta], [SPFLOW], deltaUS fixed',\n '3.0':'3.0:[delta], [SPFLOW,DOMPATINUS], deltaUS fixed',\n '3.1':'3.1:[delta], [SPFLOW,DOMPATINUS], deltaUS fixed',\n '4.0':'4.0:[delta], [SPFLOW,DOMPATINUS], deltaUS fixed',\n '4.1':'4.1:[delta], [SPFLOW,DOMPATINUS], deltaUS_1995 = 1.17647 deltaUS_2005',\n '5.0':'5.0:[delta,T], [SPFLOW,DOMPATINUS,OUT], deltaUS fixed',\n '5.1':'5.1:[delta,T], [SPFLOW,DOMPATINUS,OUT], deltaUS fixed',\n '6.0':'6.0:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP], deltaUS fixed',\n '6.1':'6.1:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP], deltaUS fixed',\n '7.0':'7.0:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP], delta,etaUS fixed',\n '7.1':'7.1:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP], delta,etaUS fixed',\n '8.0':'8.0:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,KM], deltaUS fixed',\n '8.1':'8.1:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,KM], deltaUS fixed',\n '9.0':'9.0:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,KM], deltaUS fixed, KM weight=10',\n '9.1':'9.1:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,KM], deltaUS fixed, KM weight=10',\n '10.0':'10.0:[delta,eta], [SPFLOW,DOMPATINUS], deltaUS fixed',\n '10.1':'10.1:[delta,eta], [SPFLOW,DOMPATINUS], deltaUS fixed',\n }\n\ncomments_dic['801'] = {\n 'baseline':'baseline',\n '0.0':'0.0',\n '0.1':'0.1',\n '0.2':'0.2',\n '0.3':'0.3',\n '0.4':'0.4',\n '0.5':'0.5',\n }\ncomments_dic['802'] = {\n 'baseline':'baseline,target RD US/EUR/JAP,theta=7',\n '1.0':'1.0: 1992',\n '2.0':'2.0: 2005 no Hjort correc',\n '3.0':'3.0: target RD US/EU/JP/CA/KR/RU/AU/MX',\n '4.0':'4.0: from now: target RD US/EU/JP/CA/KR/AU',\n '4.1':'4.1: drop SRDUS',\n '4.2':'4.2: drop SRDUS, higher weight on RD',\n '4.3':'4.3: drop SRDUS, higher weight on SPFLOW',\n '5.0':'5.0: lin loss',\n '5.1':'5.1: weight on large pflows lin loss',\n '5.2':'5.2: higher weight on large pflows lin loss',\n '6.0':'6.0: weight on large pflows log loss',\n '7.0':'7.0: higher weight on large pflows log loss',\n }\n\ncomments_dic['803'] = {\n 'baseline':'baseline: 802_7.0 with improved weights',\n '1.0':'1.0: calibrated theta',\n '1.1':'1.1: drop SRDUS',\n '1.2':'1.2: drop SINNOVPATEU',\n '1.3':'1.3: drop DOMPATINEU',\n '1.4':'1.4: drop SINNOVPATEU and DOMPATINEU',\n '1.5':'1.5: drop SRDUS, SINNOVPATEU and DOMPATINEU',\n '1.5.0':'1.5.0: sigma = 2',\n '1.5.1':'1.5.1: sigma = 2.25',\n '1.5.2':'1.5.2: sigma = 2.5',\n '1.5.3':'1.5.3: sigma = 2.75',\n '1.5.4':'1.5.4: sigma = 3',\n '1.5.5':'1.5.5: sigma = 3.5',\n '1.5.6':'1.5.6: sigma = 4.5',\n '1.6':'1.6: drop SINNOVPATUS',\n '1.7':'1.7: drop DOMPATINUS',\n '1.8':'1.8: drop SINNOVPATUS and DOMPATINUS',\n '1.9':'1.9: drop SRDUS, SINNOVPATUS and DOMPATINUS',\n }\n\ncomments_dic['804'] = {'baseline':'bsln:2005',\n '1.0':'1.0: TO: 0.01',\n'1.1':'1.1: TO: 0.0105',\n'1.2':'1.2: TO: 0.011',\n'1.3':'1.3: TO: 0.0115',\n'1.4':'1.4: TO: 0.012',\n'1.5':'1.5: TO: 0.0125',\n'1.6':'1.6: TO: 0.013',\n'1.7':'1.7: TO: 0.0135',\n'1.8':'1.8: TO: 0.014',\n'1.9':'1.9: TO: 0.0145',\n'1.10':'1.10: TO: 0.015',\n'1.11':'1.11: TO: 0.0155',\n'1.12':'1.12: TO: 0.016',\n'1.13':'1.13: TO: 0.0165',\n'1.14':'1.14: TO: 0.017',\n'1.15':'1.15: TO: 0.0175',\n'1.16':'1.16: TO: 0.018',\n'1.17':'1.17: TO: 0.0185',\n'1.18':'1.18: TO: 0.019',\n'1.19':'1.19: TO: 0.0195',\n'1.20':'1.20: TO: 0.02',\n'1.23':'1.23: TO: TO = 0.022',\n'1.24':'1.24: TO: TO = 0.024',\n'1.25':'1.25: TO: TO = 0.026',\n'1.26':'1.26: TO: TO = 0.028',\n'1.27':'1.27: TO: TO = 0.03',\n'1.40':'1.40: TO: 0.014603',\n'1.41':'1.41: TO: TO = 0.019661',\n }\n\ncomments_dic['805'] = {'baseline':'bsln:2015',\n '1.0':'1.0: TO: 0.01',\n'1.1':'1.1: TO: 0.0105',\n'1.2':'1.2: TO: 0.011',\n'1.3':'1.3: TO: 0.0115',\n'1.4':'1.4: TO: 0.012',\n'1.5':'1.5: TO: 0.0125',\n'1.6':'1.6: TO: 0.013',\n'1.7':'1.7: TO: 0.0135',\n'1.8':'1.8: TO: 0.014',\n'1.9':'1.9: TO: 0.0145',\n'1.10':'1.10: TO: 0.015',\n'1.11':'1.11: TO: 0.0155',\n'1.12':'1.12: TO: 0.016',\n'1.13':'1.13: TO: 0.0165',\n'1.14':'1.14: TO: 0.017',\n'1.15':'1.15: TO: 0.0175',\n'1.16':'1.16: TO: 0.018',\n'1.17':'1.17: TO: 0.0185',\n'1.18':'1.18: TO: 0.019',\n'1.19':'1.19: TO: 0.0195',\n'1.20':'1.20: TO: 0.02',\n'1.23':'1.23: TO: TO = 0.022',\n'1.24':'1.24: TO: TO = 0.024',\n'1.25':'1.25: TO: TO = 0.026',\n'1.26':'1.26: TO: TO = 0.028',\n'1.27':'1.27: TO: TO = 0.03',\n'1.40':'1.40: TO: 0.014603',\n'1.41':'1.41: TO: TO = 0.019661',\n }\n\ncomments_dic['806'] = {\n \"baseline\":\"baseline : 2015\",\n \"1.0\" : \"1.0 : 1990\",\n \"1.1\" : \"1.1 : 1991\",\n \"1.2\" : \"1.2 : 1992\",\n \"1.3\" : \"1.3 : 1993\",\n \"1.4\" : \"1.4 : 1994\",\n \"1.5\" : \"1.5 : 1995\",\n \"1.6\" : \"1.6 : 1996\",\n \"1.7\" : \"1.7 : 1997\",\n \"1.8\" : \"1.8 : 1998\",\n \"1.9\" : \"1.9 : 1999\",\n \"1.10\" : \"1.10 : 2000\",\n \"1.11\" : \"1.11 : 2001\",\n \"1.12\" : \"1.12 : 2002\",\n \"1.13\" : \"1.13 : 2003\",\n \"1.14\" : \"1.14 : 2004\",\n \"1.15\" : \"1.15 : 2005\",\n \"1.16\" : \"1.16 : 2006\",\n \"1.17\" : \"1.17 : 2007\",\n \"1.18\" : \"1.18 : 2008\",\n \"1.19\" : \"1.19 : 2009\",\n \"1.20\" : \"1.20 : 2010\",\n \"1.21\" : \"1.21 : 2011\",\n \"1.22\" : \"1.22 : 2012\",\n \"1.23\" : \"1.23 : 2013\",\n \"1.24\" : \"1.24 : 2014\",\n \"1.25\" : \"1.25 : 2015\",\n \"1.26\" : \"1.26 : 2016\",\n \"1.27\" : \"1.27 : 2017\",\n \"1.28\" : \"1.28 : 2018\",\n}\n\ncomments_dic['807'] = {\n \"baseline\":\"baseline : 2015\",\n \"0.1\" : \"0.1 : dont drop RD in South\",\n \"1.0\" : \"1.0 : ratio loss\",\n \"1.1\" : \"1.1 : ratio loss and dont drop RD in South\",\n \"2.0\" : \"2.0 : no weight on large flows\",\n \"3.0\" : \"3.0 : ratio loss and no weight on large flows\",\n}\n\ncomments_dic['808'] = {\n 'baseline':'baseline',\n '1.0':'1.0:full calibration 2015',\n '1.1':'1.1:full calibration 1992',\n '2.0':'2.0:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP]',\n '2.1':'2.1:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP]',\n '3.0':'3.0:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP], delta_US fixed',\n '3.1':'3.1:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP], delta_US fixed',\n '4.0':'4.0:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP], delta,eta_US fixed',\n '4.1':'4.1:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP], delta,eta_US fixed',\n '5.0':'5.0:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,KM]',\n '5.1':'5.1:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,KM]',\n '6.0':'6.0:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,SINNOVPATUS]',\n '6.1':'6.1:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,SINNOVPATUS]',\n '7.0':'7.0:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,GROWTH]',\n '7.1':'7.1:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,GROWTH]',\n '8.0':'8.0:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,UUPCOST]',\n '8.1':'8.1:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,UUPCOST]',\n '9.0':'9.0:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,TO]',\n '9.1':'9.1:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,TO]',\n '17.0':'17.0:[delta,T,eta,g_0], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,GROWTH]',\n '17.1':'17.1:[delta,T,eta,g_0], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,GROWTH]',\n '18.0':'18.0:[delta,T,eta,fe,fo], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,UUPCOST]',\n '18.1':'18.1:[delta,T,eta,fe,fo], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,UUPCOST]',\n '19.0':'19.0:[delta,T,eta,nu], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,TO]',\n '19.1':'19.1:[delta,T,eta,nu], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,TO]',\n }\n\ncomments_dic['901'] = {\n \"baseline\":\"baseline : 2015\",\n '1.0':'1.0:same as bsln',\n '2.0':'2.0:calibrated theta, new weights',\n '3.0':'3.0:more weights SPFLOW',\n '4.0':'4.0:more weights high SPFLOW',\n '5.0':'5.0:special weight on USA-EUR',\n '6.0':'6.0:more weight on high SPFLOW',\n '7.0':'7.0',\n '8.0':'8.0',\n '9.0':'9.0',\n '10.0':'10.0:doubling eta IDN',\n '11.0':'11.0',\n '12.0':'12.0',\n '13.0':'13.0',\n '14.0':'14.0',\n '15.0':'15.0:only TE, theta',\n '16.0':'16.0',\n '17.0':'17.0',\n '18.0':'18.0',\n '19.0':'19.0',\n '20.0':'20.0',\n '21.0':'21.0',\n }\n\ncomments_dic['902'] = {\n \"baseline\":\"baseline : 2015\",\n \"1.0\" : \"1.0 : 1990\",\n \"1.1\" : \"1.1 : 1991\",\n \"1.2\" : \"1.2 : 1992\",\n \"1.3\" : \"1.3 : 1993\",\n \"1.4\" : \"1.4 : 1994\",\n \"1.5\" : \"1.5 : 1995\",\n \"1.6\" : \"1.6 : 1996\",\n \"1.7\" : \"1.7 : 1997\",\n \"1.8\" : \"1.8 : 1998\",\n \"1.9\" : \"1.9 : 1999\",\n \"1.10\" : \"1.10 : 2000\",\n \"1.11\" : \"1.11 : 2001\",\n \"1.12\" : \"1.12 : 2002\",\n \"1.13\" : \"1.13 : 2003\",\n \"1.14\" : \"1.14 : 2004\",\n \"1.15\" : \"1.15 : 2005\",\n \"1.16\" : \"1.16 : 2006\",\n \"1.17\" : \"1.17 : 2007\",\n \"1.18\" : \"1.18 : 2008\",\n \"1.19\" : \"1.19 : 2009\",\n \"1.20\" : \"1.20 : 2010\",\n \"1.21\" : \"1.21 : 2011\",\n \"1.22\" : \"1.22 : 2012\",\n \"1.23\" : \"1.23 : 2013\",\n \"1.24\" : \"1.24 : 2014\",\n \"1.25\" : \"1.25 : 2015\",\n \"1.26\" : \"1.26 : 2016\",\n \"1.27\" : \"1.27 : 2017\",\n \"1.28\" : \"1.28 : 2018\",\n}\n\ncomments_dic['903'] = {\n \"baseline\":\"baseline : 2015\",\n \"1.0\" : \"1.0 : 1990 smooth 3y\",\n \"1.1\" : \"1.1 : 1991 smooth 3y\",\n \"1.2\" : \"1.2 : 1992 smooth 3y\",\n \"1.3\" : \"1.3 : 1993 smooth 3y\",\n \"1.4\" : \"1.4 : 1994 smooth 3y\",\n \"1.5\" : \"1.5 : 1995 smooth 3y\",\n \"1.6\" : \"1.6 : 1996 smooth 3y\",\n \"1.7\" : \"1.7 : 1997 smooth 3y\",\n \"1.8\" : \"1.8 : 1998 smooth 3y\",\n \"1.9\" : \"1.9 : 1999 smooth 3y\",\n \"1.10\" : \"1.10 : 2000 smooth 3y\",\n \"1.11\" : \"1.11 : 2001 smooth 3y\",\n \"1.12\" : \"1.12 : 2002 smooth 3y\",\n \"1.13\" : \"1.13 : 2003 smooth 3y\",\n \"1.14\" : \"1.14 : 2004 smooth 3y\",\n \"1.15\" : \"1.15 : 2005 smooth 3y\",\n \"1.16\" : \"1.16 : 2006 smooth 3y\",\n \"1.17\" : \"1.17 : 2007 smooth 3y\",\n \"1.18\" : \"1.18 : 2008 smooth 3y\",\n \"1.19\" : \"1.19 : 2009 smooth 3y\",\n \"1.20\" : \"1.20 : 2010 smooth 3y\",\n \"1.21\" : \"1.21 : 2011 smooth 3y\",\n \"1.22\" : \"1.22 : 2012 smooth 3y\",\n \"1.23\" : \"1.23 : 2013 smooth 3y\",\n \"1.24\" : \"1.24 : 2014 smooth 3y\",\n \"1.25\" : \"1.25 : 2015 smooth 3y\",\n \"1.26\" : \"1.26 : 2016 smooth 3y\",\n \"1.27\" : \"1.27 : 2017 smooth 3y\",\n \"1.28\" : \"1.28 : 2018 smooth 3y\",\n}\n\ncomments_dic['1001'] = {\n \"baseline\":\"baseline : 2015\",\n \"1.0\":\"1.0:same as bsln\",\n \"2.0\":\"2.0:less weights on big flows\",\n \"3.0\":\"3.0:1 weight on all moments\",\n \"4.0\":\"4.0:increase weight on SPFLOW\",\n \"5.0\":\"5.0:corect RD\",\n \"6.0\":\"6.0:no weight on high pflow\",\n}\n\ncomments_dic['1002'] = {\n \"baseline\":\"baseline : 2015\",\n \"1.0\" : \"1.0 : 1990 smooth 3y\",\n \"1.1\" : \"1.1 : 1991 smooth 3y\",\n \"1.2\" : \"1.2 : 1992 smooth 3y\",\n \"1.3\" : \"1.3 : 1993 smooth 3y\",\n \"1.4\" : \"1.4 : 1994 smooth 3y\",\n \"1.5\" : \"1.5 : 1995 smooth 3y\",\n \"1.6\" : \"1.6 : 1996 smooth 3y\",\n \"1.7\" : \"1.7 : 1997 smooth 3y\",\n \"1.8\" : \"1.8 : 1998 smooth 3y\",\n \"1.9\" : \"1.9 : 1999 smooth 3y\",\n \"1.10\" : \"1.10 : 2000 smooth 3y\",\n \"1.11\" : \"1.11 : 2001 smooth 3y\",\n \"1.12\" : \"1.12 : 2002 smooth 3y\",\n \"1.13\" : \"1.13 : 2003 smooth 3y\",\n \"1.14\" : \"1.14 : 2004 smooth 3y\",\n \"1.15\" : \"1.15 : 2005 smooth 3y\",\n \"1.16\" : \"1.16 : 2006 smooth 3y\",\n \"1.17\" : \"1.17 : 2007 smooth 3y\",\n \"1.18\" : \"1.18 : 2008 smooth 3y\",\n \"1.19\" : \"1.19 : 2009 smooth 3y\",\n \"1.20\" : \"1.20 : 2010 smooth 3y\",\n \"1.21\" : \"1.21 : 2011 smooth 3y\",\n \"1.22\" : \"1.22 : 2012 smooth 3y\",\n \"1.23\" : \"1.23 : 2013 smooth 3y\",\n \"1.24\" : \"1.24 : 2014 smooth 3y\",\n \"1.25\" : \"1.25 : 2015 smooth 3y\",\n \"1.26\" : \"1.26 : 2016 smooth 3y\",\n \"1.27\" : \"1.27 : 2017 smooth 3y\",\n \"1.28\" : \"1.28 : 2018 smooth 3y\",\n}\n\ncomments_dic['1005'] = comments_dic['1002']\ncomments_dic['1011'] = comments_dic['1002']\n\ncomments_dic['1003'] = {\n \"baseline\":\"baseline : 2015\",\n # '0.1':'0.1:better RD targeting',\n # '0.2':'0.2:better RD and GROWTH targeting',\n # '0.3':'0.3:better RD and GROWTH/TO/TE targeting',\n '0.4':'0.4:better RD targeting',\n '0.5':'0.5:0.4 with different UUPCOST/DOMPATINUS tension',\n '1.0':'1.0:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP],delta_US fixed',\n '1.1':'1.1:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP],delta_US fixed',\n '2.0':'2.0:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP]',\n '2.1':'2.1:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP]',\n '3.0':'3.0:full calibration',\n '3.1':'3.1:full calibration',\n '4.0':'4.0:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,TP]',\n '4.1':'4.1:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,TP]',\n '5.0':'5.0:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,inter-TP]',\n '5.1':'5.1:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,inter-TP]',\n }\n\ncomments_dic['1004'] = {\n \"baseline\":\"baseline : 2015, same as 1003_0.4\",\n '1.0':'1.0:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP],delta_US fixed',\n '1.1':'1.1:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP],delta_US fixed',\n '2.0':'2.0:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP]',\n '2.1':'2.1:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP]',\n '3.0':'3.0:full calibration',\n '3.1':'3.1:full calibration',\n '4.0':'4.0:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,TP]',\n '4.1':'4.1:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,TP]',\n '5.0':'5.0:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,inter-TP]',\n '5.1':'5.1:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,inter-TP]',\n '6.0':'6.0:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP],delta_North fixed',\n '6.1':'6.1:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP],delta_North fixed',\n '8.0':'8.0:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP],delta_US bertolotti',\n '8.1':'8.1:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP],delta_US bertolotti',\n '9.0':'9.0:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,UUPCOST]',\n '9.1':'9.1:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,UUPCOST]',\n '9.2':'9.2:1995',\n '10.0':'10.0:full calibration, delta_US fixed',\n '10.1':'10.1:full calibration, delta_US fixed',\n '11.0':'11.0:[delta,T,eta,nu], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,TO(updated)]',\n '11.1':'11.1:[delta,T,eta,nu], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,TO(updated)]',\n '12.0':'12.0:full calibration except delta_US fixed, KM and TO not targeted',\n '12.1':'12.1:full calibration except delta_US fixed, KM and TO not targeted',\n '13.0':'13.0:full calibration except delta_US and nu fixed, KM and TO not targeted',\n '13.1':'13.1:full calibration except delta_US and nu fixed, KM and TO not targeted',\n '14.0':'14.0:[delta,T,eta,fe,fo], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,UUPCOST], d_US fixed',\n '14.1':'14.1:[delta,T,eta,fe,fo], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,UUPCOST], d_US fixed',\n '15.0':'15.0:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,UUPCOST], d_US fixed',\n '15.1':'15.1:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,UUPCOST], d_US fixed',\n }\n\ncomments_dic['1006'] = {\n \"baseline\":\"baseline : 2015, same as 1004\",\n '1.0':'1.0:SPFLOWDOM instead of SPFLOW',\n '2.0':'2.0:DOMPATUS instead of DOMPATINUS',\n '2.1':'2.1:1992 partial calibration',\n '3.0':'3.0:DOMPATUS and DOMPATINUS',\n '3.1':'3.1:1992 partial calibration',\n '4.0':'4.0:2.0 with higher weight on DOMPATUS',\n '4.1':'4.1:1992 partial calibration',\n '5.0':'5.0:3.0 with higher weight on DOMPAT(IN)US',\n '5.1':'5.1:1992 partial calibration',\n }\n\ncomments_dic['1010'] = {\n \"baseline\":\"baseline : 2015, new correction US flows and new TO\",\n '2.0':'2.0:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP]',\n '2.1':'2.1:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP]',\n '3.0':'3.0:full calibration 2015',\n '3.1':'3.1:full calibration 1992',\n '9.0':'9.0:[delta,T,eta],[SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,UUPCOST] 2015',\n '9.1':'9.1:[delta,T,eta],[SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,UUPCOST] 1992',\n '9.2':'9.2:same conditions, 3-year smoothed out data 1992',\n '10.0':'10.0 corrected mistake denominator in the Gamma function',\n }\n\ncomments_dic['1020'] = {\n \"baseline\":\"baseline : 2015, with corrected term in Gamma function\",\n \"1.0\" : \"1.0 : 1990 smooth 3y\",\n \"1.1\" : \"1.1 : 1991 smooth 3y\",\n \"1.2\" : \"1.2 : 1992 smooth 3y\",\n \"1.3\" : \"1.3 : 1993 smooth 3y\",\n \"1.4\" : \"1.4 : 1994 smooth 3y\",\n \"1.5\" : \"1.5 : 1995 smooth 3y\",\n \"1.6\" : \"1.6 : 1996 smooth 3y\",\n \"1.7\" : \"1.7 : 1997 smooth 3y\",\n \"1.8\" : \"1.8 : 1998 smooth 3y\",\n \"1.9\" : \"1.9 : 1999 smooth 3y\",\n \"1.10\" : \"1.10 : 2000 smooth 3y\",\n \"1.11\" : \"1.11 : 2001 smooth 3y\",\n \"1.12\" : \"1.12 : 2002 smooth 3y\",\n \"1.13\" : \"1.13 : 2003 smooth 3y\",\n \"1.14\" : \"1.14 : 2004 smooth 3y\",\n \"1.15\" : \"1.15 : 2005 smooth 3y\",\n \"1.16\" : \"1.16 : 2006 smooth 3y\",\n \"1.17\" : \"1.17 : 2007 smooth 3y\",\n \"1.18\" : \"1.18 : 2008 smooth 3y\",\n \"1.19\" : \"1.19 : 2009 smooth 3y\",\n \"1.20\" : \"1.20 : 2010 smooth 3y\",\n \"1.21\" : \"1.21 : 2011 smooth 3y\",\n \"1.22\" : \"1.22 : 2012 smooth 3y\",\n \"1.23\" : \"1.23 : 2013 smooth 3y\",\n \"1.24\" : \"1.24 : 2014 smooth 3y\",\n \"1.25\" : \"1.25 : 2015 smooth 3y\",\n \"1.26\" : \"1.26 : 2016 smooth 3y\",\n \"1.27\" : \"1.27 : 2017 smooth 3y\",\n \"1.28\" : \"1.28 : 2018 smooth 3y\",\n '2.0':'2.0:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP]',\n '2.1':'2.1:[delta,T,eta], [SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP]',\n '3.0':'3.0:full calibration 2015',\n '3.1':'3.1:full calibration 1992',\n '9.0':'9.0:[delta,T,eta],[SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,UUPCOST] 2015',\n '9.1':'9.1:[delta,T,eta],[SPFLOW,DOMPATINUS,OUT,RD,RP,SRGDP,UUPCOST] 1992',\n '9.2':'9.2:same conditions, 3-year smoothed out data 1992',\n }\n\nbaselines_dic_param = {}\nbaselines_dic_mom = {}\nbaselines_dic_sol_qty = {}\n\n# baseline_list = ['311','312','401','402','403'] \n# baseline_list = ['402','403','404'] \n# baseline_list = ['403','404','405'] \n# baseline_list = ['501','607','608','609','610','614','615','616','617'] \n# baseline_list = ['618','701','702'] \n# baseline_list = ['901','803','806','808'] \nbaseline_list = ['1020'] \nbaseline_mom = '1020'\n\ndef section(s):\n return [int(_) for _ in s.split(\".\")]\n \nfor baseline_nbr in baseline_list:\n print(baseline_nbr)\n print(time.perf_counter() - start)\n baseline_path = results_path+baseline_nbr+'/'\n baseline_variations_path = results_path+'baseline_'+baseline_nbr+'_variations/'\n p_baseline,m_baseline,sol_baseline = load(baseline_path,data_path = data_path,\n dir_path=dir_path)\n # print(baseline_nbr)\n baselines_dic_param[baseline_nbr], baselines_dic_mom[baseline_nbr], baselines_dic_sol_qty[baseline_nbr]\\\n = init_dic_of_dataframes_with_baseline(p_baseline,m_baseline,sol_baseline,list_of_moments)\n try:\n files_in_dir = next(os.walk(baseline_variations_path))[1]\n run_list = [f for f in files_in_dir if f[0].isnumeric()]\n # lists = sorted([s.split('.') for s in run_list], key=lambda x:map(int, x)) \n # run_list#.sort()\n run_list = sorted(run_list, key=section)\n \n for run in run_list:\n if run not in ['2.1.9','99']:\n p_to_add,m_to_add,sol_to_add = load(baseline_variations_path+run+'/',\n data_path = data_path,\n dir_path=dir_path)\n a, b, c = append_dic_of_dataframes_with_variation(baselines_dic_param[baseline_nbr], \n baselines_dic_mom[baseline_nbr], \n baselines_dic_sol_qty[baseline_nbr],\n p_to_add, \n m_to_add, \n sol_to_add,\n run)\n baselines_dic_param[baseline_nbr] = a\n baselines_dic_mom[baseline_nbr] = b\n baselines_dic_sol_qty[baseline_nbr] = c\n except:\n pass\n\n# gather full list run\nfull_run_list = []\nfor baseline_nbr in baseline_list:\n baseline_path = results_path+baseline_nbr+'/'\n baseline_variations_path = results_path+'baseline_'+baseline_nbr+'_variations/'\n files_in_dir = next(os.walk(baseline_variations_path))[1]\n for f in files_in_dir:\n if f[0].isnumeric() and f not in full_run_list:\n full_run_list.append(f)\nfull_run_list = ['target','baseline']+sorted(full_run_list,key = section)\n#add empty columns to dfs\nfor baseline_nbr in baseline_list:\n for df_name in baselines_dic_mom[baseline_nbr].keys():\n baselines_dic_mom[baseline_nbr][df_name] = baselines_dic_mom[baseline_nbr][df_name].reindex(columns=full_run_list)\n for df_name in baselines_dic_param[baseline_nbr].keys():\n baselines_dic_param[baseline_nbr][df_name] = baselines_dic_param[baseline_nbr][df_name].reindex(columns=full_run_list[1:])\n for df_name in baselines_dic_sol_qty[baseline_nbr].keys():\n baselines_dic_sol_qty[baseline_nbr][df_name] = baselines_dic_sol_qty[baseline_nbr][df_name].reindex(columns=full_run_list[1:])\n\ncountries = p_baseline.countries\n\nTOOLS=\"pan,wheel_zoom,box_zoom,reset,save\"\n\n# baseline_mom = '101'\n# baseline_mom = '618'\n\nmom = 'SPFLOW'\n\nbaseline_mom_select = Select(value=baseline_mom, title='Baseline', options=sorted(baselines_dic_mom.keys()))\nmom_select = Select(value=mom, title='Quantity', options=sorted(baselines_dic_mom[baseline_mom].keys()))\nx_mom_select = Select(value='baseline', title='x-axis target', options=list(comments_dic[baseline_mom].keys()))\nlabels_mom_toggle = Toggle(label=\"Labels On/Off\",align='end')\n\ndef update_x_axis_mom_matching_options(attr, old, new):\n x_mom_select.options = list(comments_dic[new].keys())\n\nds_mom = ColumnDataSource(baselines_dic_mom[baseline_mom][mom])\np_mom = figure(title=\"Moment matching\", \n width = 1200,\n height = 875,\n x_axis_type=\"log\",\n y_axis_type=\"log\",\n x_axis_label='Target', \n y_axis_label='Model implied',\n tools = TOOLS)\nhover_tool_mom = HoverTool()\nhover_tool_mom.tooltips = [\n (\"index\", \"@x\"),\n (\"(target,value)\", \"($x,$y)\"),\n ]\nlabels_mom = LabelSet(x='target', y='baseline', text='x',\n x_offset=2, y_offset=2, source=ds_mom, text_font_size=\"7pt\")\np_mom.add_layout(labels_mom)\np_mom.add_tools(hover_tool_mom)\nslope1 = Slope(gradient=1, y_intercept=0,\n line_color='black', line_dash='dashed', line_width=1)\n# slope2 = Slope(gradient=1.4876, y_intercept=0,\n# line_color='black', line_dash='dashed', line_width=0.25)\n# slope3 = Slope(gradient=0.5124, y_intercept=0,\n# line_color='black', line_dash='dashed', line_width=0.25)\n# slope4 = Slope(gradient=0.756198, y_intercept=0,\n# line_color='black', line_dash='dashed', line_width=0.25)\n# slope5 = Slope(gradient=1.546, y_intercept=0,\n# line_color='black', line_dash='dashed', line_width=0.25)\n# slope6 = Slope(gradient=2.20, y_intercept=0,\n# line_color='black', line_dash='dashed', line_width=0.25)\n\nfor slope in [slope1]:\n# for slope in [slope1,slope2,slope3,slope4,slope5,slope6]:\n p_mom.add_layout(slope)\n \n# slope2.visible = False\n# slope3.visible = False\n# slope4.visible = False\n# slope5.visible = False\n# slope6.visible = False\n\ncolors_mom = itertools.cycle(Category18)\n\nlines_mom = {}\n# for i,col in enumerate(ds_mom.data.keys()):\nfor i,col in enumerate(ds_mom.data.keys()):\n if col not in ['x','target']:\n lines_mom[col] = p_mom.circle('target', col, \n source = ds_mom, \n size=5, color=next(colors_mom))\n if col != 'baseline':\n lines_mom[col].visible = False\n \nlegend_items_mom = [LegendItem(label=comments_dic[baseline_mom][col], renderers=[lin_mom]) \n for col, lin_mom in lines_mom.items() if col in comments_dic[baseline_mom]]\n# legend_items_mom = [LegendItem(label=comments_dic[baseline_mom][col], renderers=[lines_mom[i]]) for i,col in enumerate(ds_mom.data)]\nlegend_mom = Legend(items=legend_items_mom, click_policy=\"hide\", \n label_text_font_size=\"8pt\",\n spacing = 0)\np_mom.add_layout(legend_mom, 'right')\n\n# legend_mom_split_1 = Legend(items=legend_items_mom[:round((len(legend_items_mom)+1)/2)], click_policy=\"hide\", \n# label_text_font_size=\"8pt\",\n# spacing = 0, \n# # location=(10, -60)\n# )\n# legend_mom_split_2 = Legend(items=legend_items_mom[round((len(legend_items_mom)+1)/2):], click_policy=\"hide\", \n# label_text_font_size=\"8pt\",\n# spacing = 0\n# # , location=(10, -60)\n# )\n# p_mom.add_layout(legend_mom_split_1, 'right')\n# p_mom.add_layout(legend_mom_split_2, 'right')\n# columns_mom = [TableColumn(field=col) for col in list(ds_mom.data.keys())]\ncolumns_mom = [\n TableColumn(field=\"x\"),\n ]+[TableColumn(field=col) for col in ['target']+list(comments_dic[baseline_mom].keys())]\ndata_table_mom = DataTable(source=ds_mom, columns = columns_mom, width=1200, height=400)\n \ndef update_baseline_mom(attrname, old, new):\n mom = mom_select.value\n ds_mom.data = baselines_dic_mom[new][mom]\n \n # legend_items_mom = [LegendItem(label=comments_dic[new][col], \n # renderers=[lines_mom[i]]) for i,col in enumerate(ds_mom.data) if col not in ['x','target']]\n legend_items_mom = [LegendItem(label=comments_dic[new][col], renderers=[lines_mom[col]]) \n for col in ds_mom.data if col in comments_dic[new]]\n legend_mom.items = legend_items_mom\n # legend_mom_split_1.items = legend_items_mom[:round((len(legend_items_mom)+1)/2)]\n # legend_mom_split_2.items = legend_items_mom[round((1+len(legend_items_mom))/2):]\n data_table_mom.columns = [\n TableColumn(field=\"x\"),\n ]+[TableColumn(field=col) for col in ['target']+list(comments_dic[new].keys())]\n x_mom_select.value = 'baseline'\n \ndef update_mom(attrname, old, new):\n baseline_mom = baseline_mom_select.value\n ds_mom.data = baselines_dic_mom[baseline_mom][new]\n # if new == 'scalars':\n # slope2.visible = True\n # slope3.visible = True\n # slope4.visible = True\n # else:\n # slope2.visible = False\n # slope3.visible = False\n # slope4.visible = False\n x_mom_select.value = 'baseline'\n \ndef update_x_axis_target(attrname, old, new):\n baseline_mom = baseline_mom_select.value\n mom = mom_select.value\n df_temp = ds_mom.data.copy()\n if new == 'baseline':\n path_x_axis = results_path+baseline_mom+'/'\n else:\n path_x_axis = results_path+'baseline_'+baseline_mom+'_variations/'+new+'/'\n if mom != 'scalars':\n m_temp = moments()\n m_temp.load_run(path_x_axis,\n dir_path=dir_path)\n df_temp['target'] = getattr(m_temp,mom+'_target').ravel()\n # df_temp['target'] = pd.read_csv(path_x_axis+mom)['target']\n else:\n m_temp = moments()\n m_temp.load_run(path_x_axis,\n dir_path=dir_path)\n for i,x in enumerate(df_temp['x']):\n if x != 'objective':\n df_temp['target'][i] = float(getattr(m_temp,x+'_target'))\n ds_mom.data = df_temp\n \ndef toggle_labels(event):\n labels_mom.visible = not labels_mom.visible\n \ncontrols_mom = row(baseline_mom_select, mom_select, x_mom_select, labels_mom_toggle)\n\nbaseline_mom_select.on_change('value', update_baseline_mom)\nbaseline_mom_select.on_change('value', update_x_axis_mom_matching_options)\nlabels_mom_toggle.on_click(toggle_labels)\n\nmom_select.on_change('value', update_mom)\nx_mom_select.on_change('value', update_x_axis_target)\n\nbaseline_par = baseline_mom\npar = 'delta'\n\nbaseline_par_select = Select(value=baseline_par, title='Baseline', options=sorted(baselines_dic_param.keys()))\npar_select = Select(value=par, title='Quantity', options=sorted(baselines_dic_param[baseline_par].keys()))\n\ncountry_sort = {\n 'USA':\t1,\n 'JAP':\t2,\n 'CAN':\t3,\n 'AUS':\t13,\n 'EUR':\t5,\n 'KOR':\t6,\n 'MEX':\t7,\n 'RUS':\t8,\n 'BRA':\t9,\n 'ROW':\t10,\n 'CHN':\t11,\n 'IND':\t12,\n 'IDN':\t14\n }\n\nx_range = baselines_dic_param[baseline_par][par_select.value].index.to_list()\nx_range = sorted(x_range, key = country_sort.get)\nds_par = ColumnDataSource(baselines_dic_param[baseline_par][par].loc[x_range])\np_par = figure(title=\"Parameters\", \n width = 1200,\n height = 875,\n x_range = x_range,\n y_axis_label='Model implied',\n tools = TOOLS)\nhover_tool_par = HoverTool()\nhover_tool_par.tooltips = [\n (\"index\", \"@x\"),\n (\"value\", \"$y\")\n ]\n\np_par.add_tools(hover_tool_par)\ncolors_par = itertools.cycle(Category18)\nlines_par = {}\n\nfor col in baselines_dic_param[baseline_par][par].columns:\n lines_par[col] = p_par.line(x='x', y=col, source = ds_par, color=next(colors_par),\n line_width = 2)\n if col != 'baseline':\n lines_par[col].visible = False\n\nlegend_items_par = [LegendItem(label=comments_dic[baseline_par][col], renderers=[lin_par])\n for col, lin_par in lines_par.items() if col in comments_dic[baseline_par]]\nlegend_par = Legend(items=legend_items_par, click_policy=\"hide\", \n label_text_font_size=\"8pt\",\n spacing = 0, \n )\np_par.add_layout(legend_par, 'right')\n\n# legend_par_split_1 = Legend(items=legend_items_par[:round((len(legend_items_par)+1)/2)], click_policy=\"hide\", \n# label_text_font_size=\"8pt\",\n# spacing = 0, \n# )\n# legend_par_split_2 = Legend(items=legend_items_par[round((1+len(legend_items_par))/2):], click_policy=\"hide\", \n# label_text_font_size=\"8pt\",\n# spacing = 0\n# )\n# p_par.add_layout(legend_par_split_1, 'right')\n# p_par.add_layout(legend_par_split_2, 'right')\n\ncolumns_par = [\n TableColumn(field=\"x\"),\n ]+[TableColumn(field=col) for col in list(comments_dic[baseline_par].keys())]\n\ndata_table_par = DataTable(source=ds_par, columns = columns_par, width=1200, height=400)\n\ndef update_baseline_par(attrname, old, new):\n par = par_select.value\n x_range_factors = baselines_dic_param[new][par].index.to_list()\n if new != 'scalars':\n x_range_factors = sorted(x_range_factors, key = country_sort.get)\n ds_par.data = baselines_dic_param[new][par].loc[x_range_factors]\n legend_items_par = [LegendItem(label=comments_dic[new][col], renderers=[lines_par[col]])\n for col in ds_par.data if col in comments_dic[new]]\n legend_par.items = legend_items_par\n # legend_par_split_1.items = legend_items_par[:round((1+len(legend_items_par))/2)]\n # legend_par_split_2.items = legend_items_par[round((len(legend_items_par)+1)/2):]\n \n data_table_par.columns = [\n TableColumn(field=\"x\"),\n ]+[TableColumn(field=col) for col in list(comments_dic[new].keys())]\n\ndef update_par(attrname, old, new):\n baseline_par = baseline_par_select.value\n x_range_factors = baselines_dic_param[baseline_par][new].index.to_list()\n if new != 'scalars':\n x_range_factors = sorted(x_range_factors, key = country_sort.get)\n p_par.x_range.factors = x_range_factors\n ds_par.data = baselines_dic_param[baseline_par][new].loc[x_range_factors]\n\ncontrols_par = row(baseline_par_select, par_select)\n\nbaseline_par_select.on_change('value', update_baseline_par)\npar_select.on_change('value', update_par)\n\nbaseline_sol_qty = baseline_mom\nsol_qty = 'psi_o_star'\n\nbaseline_sol_qty_select = Select(value=baseline_sol_qty, title='Baseline', options=sorted(baselines_dic_sol_qty.keys()))\nsol_qty_select = Select(value=sol_qty, title='Quantity', options=sorted(baselines_dic_sol_qty[baseline_sol_qty].keys()))\nx_range_par = baselines_dic_sol_qty[baseline_sol_qty][sol_qty_select.value].index.to_list()\nx_range_par = sorted(x_range_par, key = country_sort.get)\nds_sol_qty = ColumnDataSource(baselines_dic_sol_qty[baseline_sol_qty][sol_qty].loc[x_range_par])\np_sol_qty = figure(title=\"Solution quantities\", \n width = 1200,\n height = 875,\n x_range = x_range,\n y_axis_label='Model implied',\n tools = TOOLS)\nhover_tool_sol_qty = HoverTool()\nhover_tool_sol_qty.tooltips = [\n (\"index\", \"@x\"),\n (\"value\", \"$y\")\n ]\n\np_sol_qty.add_tools(hover_tool_sol_qty)\ncolors_sol_qty = itertools.cycle(Category18)\nlines_sol_qty = {}\n\nfor col in baselines_dic_sol_qty[baseline_sol_qty][sol_qty].columns:\n lines_sol_qty[col] = p_sol_qty.line(x='x', y=col, source = ds_sol_qty, \n color=next(colors_sol_qty),\n line_width = 2)\n if col != 'baseline':\n lines_sol_qty[col].visible = False\n\nlegend_items_sol_qty = [LegendItem(label=comments_dic[baseline_sol_qty][col], renderers=[lin_sol_qty]) \n for col, lin_sol_qty in lines_sol_qty.items() if col in comments_dic[baseline_sol_qty]]\n\nlegend_sol_qty = Legend(items=legend_items_sol_qty, click_policy=\"hide\", \n label_text_font_size=\"8pt\",\n spacing = 0, \n )\np_sol_qty.add_layout(legend_sol_qty, 'right')\n\n# legend_sol_qty_split_1 = Legend(items=legend_items_sol_qty[:round((len(legend_items_sol_qty)+1)/2)], click_policy=\"hide\", \n# label_text_font_size=\"8pt\",\n# spacing = 0, \n# )\n# legend_sol_qty_split_2 = Legend(items=legend_items_sol_qty[round((len(legend_items_sol_qty)+1)/2):], click_policy=\"hide\", \n# label_text_font_size=\"8pt\",\n# spacing = 0\n# )\n# p_sol_qty.add_layout(legend_sol_qty_split_1, 'right')\n# p_sol_qty.add_layout(legend_sol_qty_split_2, 'right')\n\n\ncolumns_sol_qty = [\n TableColumn(field=\"x\"),\n ]+[TableColumn(field=col) for col in list(comments_dic[baseline_sol_qty].keys())]\n\ndata_table_sol_qty = DataTable(source=ds_sol_qty, columns = columns_sol_qty, width=1200, height=400)\n\ndef update_baseline_sol_qty(attrname, old, new):\n sol_qty = sol_qty_select.value\n x_range_factors = baselines_dic_sol_qty[new][sol_qty].index.to_list()\n if new != 'scalars':\n x_range_factors = sorted(x_range_factors, key = country_sort.get)\n ds_sol_qty.data = baselines_dic_sol_qty[new][sol_qty].loc[x_range_factors]\n legend_items_sol_qty = [LegendItem(label=comments_dic[new][col], renderers=[lines_sol_qty[col]]) \n for col in ds_sol_qty.data if col in comments_dic[new]]\n legend_sol_qty.items = legend_items_sol_qty\n # legend_sol_qty_split_1.items = legend_items_sol_qty[:round((len(legend_items_sol_qty)+1)/2)]\n # legend_sol_qty_split_2.items = legend_items_sol_qty[round((len(legend_items_sol_qty)+1)/2):]\n data_table_sol_qty.columns = [TableColumn(field=col) for col in list(comments_dic[new].keys())]\n \ndef update_sol_qty(attrname, old, new):\n baseline_sol_qty = baseline_sol_qty_select.value\n # p_sol_qty.x_range.factors = baselines_dic_sol_qty[baseline_sol_qty][new].index.to_list()\n ds_sol_qty.data = baselines_dic_sol_qty[baseline_sol_qty][new].loc[x_range_par]\n\ncontrols_sol_qty = row(baseline_sol_qty_select, sol_qty_select)\n\nbaseline_sol_qty_select.on_change('value', update_baseline_sol_qty)\nsol_qty_select.on_change('value', update_sol_qty)\n\nmoment_report = column(controls_mom,p_mom,data_table_mom)\nparam_report = column(controls_par, p_par, data_table_par)\nsol_qty_report = column(controls_sol_qty, p_sol_qty, data_table_sol_qty)\n\n#!!! first panel\nfirst_panel = row(moment_report,param_report,sol_qty_report)\n# first_panel = row(moment_report,param_report)\nprint(time.perf_counter() - start)\n\n#%% Time series\n\nbaseline_time = '1020'\n# baseline_time_list = ['607','608','609','610','614','615','616','617'] \n# baseline_time_list = ['607','806','903']\nbaseline_time_list = ['1020']\npar_time = 'delta'\npar_time_select = Select(value=par_time, title='Quantity', options=sorted(baselines_dic_param[baseline_time].keys()))\nbaseline_time_select = Select(value=baseline_time, title='Baseline', options=baseline_time_list)\n\n\nyears_time = [y for y in range(1990,2019)]\nruns_time = ['1.'+str(i) for i in range(29)]\n\ndef build_time_series(baseline_time,par_time):\n # df = baselines_dic_param[baseline_time][par_time].T.reindex(\n # columns=countries+baselines_dic_param[baseline_time]['scalars'].index.to_list()\n # )\n df = baselines_dic_param[baseline_time][par_time].copy()\n df = df[runs_time]\n # print(df)\n df.columns = years_time\n df = df.T\n df = df.reindex(\n columns=countries+baselines_dic_param[baseline_time]['scalars'].index.to_list()\n )\n df.index.name = 'year'\n return df\n\ndf_par_time = build_time_series(baseline_time,par_time)\nds_par_time = ColumnDataSource(df_par_time)\np_par_time = figure(title=\"Time series\", \n width = 1500,\n height = 850,\n y_axis_label='Parameter',\n tools = TOOLS)\nhover_tool_par_time = HoverTool()\nhover_tool_par_time.tooltips = [\n (\"Year\", \"@year\"),\n (\"value\", \"$y\")\n ]\n\np_par_time.add_tools(hover_tool_par_time)\ncolors_par_time = itertools.cycle(Category18)\nlines_par_time = {}\n\nfor col in df_par_time.columns:\n if col != 'kappa':\n lines_par_time[col] = p_par_time.line(x='year', y=col, \n source = ds_par_time, \n color=next(colors_par_time),\n line_width = 2,\n # legend_label=col\n )\n\nlegend_items_par_time = [LegendItem(label=col, renderers=[lines_par_time[col]]) \n for col in countries]\nlegend_par_time = Legend(items=legend_items_par_time, click_policy=\"hide\", \n label_text_font_size=\"10pt\",\n )\np_par_time.add_layout(legend_par_time , 'right')\n \ndef update_par_time(attrname, old, new):\n df_par_time = build_time_series(baseline_time_select.value,new)\n ds_par_time.data = df_par_time\n if new!='scalars':\n legend_items_par_time = [LegendItem(label=col, renderers=[lines_par_time[col]]) \n for col in countries]\n else:\n legend_items_par_time = [LegendItem(label=col, renderers=[lines_par_time[col]]) \n for col in baselines_dic_param[baseline_time]['scalars'].index.to_list() if col != 'kappa']\n legend_par_time.items = legend_items_par_time\n \ndef update_baseline_time(attrname, old, new):\n df_par_time = build_time_series(new,par_time_select.value)\n ds_par_time.data = df_par_time\n if new!='scalars':\n legend_items_par_time = [LegendItem(label=col, renderers=[lines_par_time[col]]) \n for col in countries]\n else:\n legend_items_par_time = [LegendItem(label=col, renderers=[lines_par_time[col]]) \n for col in baselines_dic_param[baseline_time]['scalars'].index.to_list() if col != 'kappa']\n legend_par_time.items = legend_items_par_time\n\ncontrols_par_time = row(baseline_time_select,par_time_select)\n\npar_time_select.on_change('value', update_par_time)\nbaseline_time_select.on_change('value', update_baseline_time)\n\npar_time_report = column(controls_par_time, p_par_time) \n\n# explication_calib_params = Div(text=\n# \"607 variations :
\\\n# calibrated parameters : eta,k,fe,T,zeta,g_0,delta,nu,fo,theta
\\\n# targeted moments : GPDIFF,GROWTH,KM,OUT,RD,RP,SRDUS,SRGDP,SINNOVPATUS,\\\n# TO,SPFLOW,UUPCOST,SINNOVPATEU,DOMPATINUS,DOMPATINEU,TE
\\\n# 608 variations :
\\\n# calibrated parameters : eta,fe,T,delta,fo
\\\n# targeted moments : OUT,RD,RP,SRGDP,SINNOVPATUS,\\\n# SPFLOW,UUPCOST,SINNOVPATEU,DOMPATINUS,DOMPATINEU
\\\n# 609 variations :
\\\n# calibrated parameters : eta,T,delta
\\\n# targeted moments : OUT,RD,RP,SRGDP,SINNOVPATUS,\\\n# SPFLOW,SINNOVPATEU,DOMPATINUS,DOMPATINEU
\\\n# 610 variations :
\\\n# calibrated parameters : eta,T,delta
\\\n# targeted moments : OUT,RD,RP,SRDUS,SRGDP,SINNOVPATUS,\\\n# SPFLOW,SINNOVPATEU,DOMPATINUS,DOMPATINEU
\\\n# \")\n\n#!!! second_panel\n# second_panel = row(par_time_report, explication_calib_params)\nsecond_panel = row(par_time_report)\n\n\n#%% counterfactuals\n\n# baseline_cf = '101'\nbaseline_cf = '1020'\ncountry_cf = 'USA'\n\ndef section_end(s):\n return [int(_) for _ in s.split(\"_\")[-1].split(\".\")]\n# cf_list = sorted([s for s in os.listdir(cf_path) \n# if s[9:].startswith('604') and s.startswith('baseline')], key=section_end)+\\\ncf_list = sorted([s for s in os.listdir(cf_path) \n if s[9:].startswith('1020') and s.startswith('baseline')], key=section_end)#+\\\n # sorted([s for s in os.listdir(cf_path) \n # if s[9:].startswith('803') and s.startswith('baseline')], key=section_end)+\\\n # sorted([s for s in os.listdir(cf_path) \n # if s[9:].startswith('804') and s.startswith('baseline')], key=section_end)+\\\n # sorted([s for s in os.listdir(cf_path) \n # if s[9:].startswith('805') and s.startswith('baseline')], key=section_end)#+\\\n # sorted([s for s in os.listdir(cf_path) \n # if s[9:].startswith('608') and s.startswith('baseline')], key=section_end)+\\\n # sorted([s for s in os.listdir(cf_path) \n # if s[9:].startswith('609') and s.startswith('baseline')], key=section_end)+\\\n # sorted([s for s in os.listdir(cf_path) \n # if s[9:].startswith('618') and s.startswith('baseline')], key=section_end)+\\\n # sorted([s for s in os.listdir(cf_path) \n # if s[9:].startswith('501') and s.startswith('baseline')], key=section_end)#+\\\n # sorted([s for s in os.listdir(cf_path) \n # if s[9:].startswith('601') and s.startswith('baseline')], key=section_end)+\\\n # sorted([s for s in os.listdir(cf_path) \n # if s[9:].startswith('602') and s.startswith('baseline')], key=section_end)+\\\n # sorted([s for s in os.listdir(cf_path) \n # if s[9:].startswith('603') and s.startswith('baseline')], key=section_end)+\\\n # sorted([s for s in os.listdir(cf_path) \n # if s[9:].startswith('404') and s.startswith('baseline')], key=section_end)#+\\\n # sorted([s for s in os.listdir(cf_path) \n # if s[9:].startswith('312') and s.startswith('baseline')], key=section_end)+\\\n # sorted([s for s in os.listdir(cf_path) \n # if s[9:].startswith('311') and s.startswith('baseline')], key=section_end)\n\nbaseline_cf_select = Select(value=baseline_cf, title='Baseline', options=[s[9:] for s in cf_list])\ncountry_cf_select = Select(value=country_cf, \n title='Country', \n options=countries+['World','Harmonizing','Upper_harmonizing',\n 'Uniform_delta','Upper_uniform_delta'])\n\ndef get_data_cf(baseline,country):\n df_cf = pd.read_csv(cf_path+'baseline_'+baseline+'/'+country+'.csv')\n if country != 'Harmonizing':\n df_cf['Growth rate'] = df_cf['growth']/df_cf.loc[np.argmin(np.abs(df_cf.delt-1))].growth\n if country == 'Harmonizing':\n df_cf['Growth rate'] = df_cf['growth']/df_cf.loc[np.argmin(np.abs(df_cf.delt))].growth\n df_cf.set_index('delt',inplace=True)\n return df_cf\n\ndef build_max(df_cf):\n df_max = pd.concat([df_cf.idxmax(),df_cf.max()],axis=1)\n df_max.index.name = 'label'\n df_max.columns = ['xmax','max'] \n df_max = df_max.loc[countries]\n df_max['colors'] = Category18[:len(df_max)]\n return df_max\n\ndf_cf = get_data_cf(baseline_cf,country_cf)\nds_cf = ColumnDataSource(df_cf)\ndf_cf_max = build_max(df_cf)\nds_cf_max = ColumnDataSource(df_cf_max)\n\ncolors_cf = itertools.cycle(Category18)\ncolors_cf_max = itertools.cycle(Category18)\n\np_cf = figure(title=\"Patent protection counterfactual\", \n width = 1200,\n height = 850,\n x_axis_label='Change in delta',\n y_axis_label='Normalized Consumption equivalent welfare / Growth rate',\n x_axis_type=\"log\",\n tools = TOOLS) \n\nfor col in df_cf.columns:\n if col not in [0,'delt','growth']:\n p_cf.line(x='delt', y=col, source = ds_cf, color=next(colors_cf),line_width = 2, legend_label=col)\n\np_cf.circle(x = 'xmax', y = 'max', source = ds_cf_max, size=4, color='colors')\n \np_cf.legend.click_policy=\"hide\"\np_cf.legend.label_text_font_size = '8pt'\np_cf.add_layout(p_cf.legend[0], 'right')\n\ndef update_baseline_cf(attrname, old, new):\n country_cf = country_cf_select.value\n ds_cf.data = get_data_cf(new,country_cf)\n df_cf = get_data_cf(new,country_cf)\n ds_cf.data = df_cf\n ds_cf_max.data = build_max(df_cf)\n \ndef update_country_cf(attrname, old, new):\n baseline_cf = baseline_cf_select.value\n df_cf = get_data_cf(baseline_cf,new)\n ds_cf.data = df_cf\n ds_cf_max.data = build_max(df_cf)\n \ncontrols_cf = row(baseline_cf_select, country_cf_select)\n\nbaseline_cf_select.on_change('value', update_baseline_cf)\ncountry_cf_select.on_change('value', update_country_cf)\n\ncounterfactuals_report = column(controls_cf,p_cf)\n\n#%% counterfactuals 805 TO target\n\n# country_to_cf = 'USA'\n# to_target = 0.0155\n# baseline_to_cf = '804'\n\n# # list_of_to_targets = np.linspace(0.01,0.03,41)\n# list_of_to_targets = np.array(np.linspace(0.01,0.02,21).tolist()\n# +[0.022,0.024,0.026,0.028,0.03])\n\n# def section_end(s):\n# return [int(_) for _ in s.split(\"_\")[-1].split(\".\")]\n# cf_to_list = {'804':sorted([s for s in os.listdir(cf_path) \n# if s[9:].startswith('804') and s.startswith('baseline')], key=section_end),\n# '805':sorted([s for s in os.listdir(cf_path) \n# if s[9:].startswith('805') and s.startswith('baseline')], key=section_end)}\n\n# def get_data_to_cf(to_target,country,baseline_to_cf):\n# idx_to_cf = np.argmin(np.abs(list_of_to_targets-to_target))\n# df_to_cf = pd.read_csv(cf_path+cf_to_list[baseline_to_cf][min(idx_to_cf,len(cf_to_list[baseline_to_cf])-1)]+'/'+country+'.csv')\n# if country == 'Harmonizing':\n# df_to_cf['Growth rate'] = df_to_cf['growth']/df_to_cf.loc[np.argmin(np.abs(df_to_cf.delt))].growth\n# elif country == 'Uniform_delta':\n# df_to_cf['Growth rate'] = np.nan\n# else:\n# df_to_cf['Growth rate'] = df_to_cf['growth']/df_to_cf.loc[np.argmin(np.abs(df_to_cf.delt-1))].growth\n# df_to_cf.set_index('delt',inplace=True)\n# return df_to_cf\n\n# def build_max(df_to_cf):\n# df_max = pd.concat([df_to_cf.idxmax(),df_to_cf.max()],axis=1)\n# df_max.index.name = 'label'\n# df_max.columns = ['xmax','max'] \n# df_max = df_max.loc[countries]\n# df_max['colors'] = Category18[:len(df_max)]\n# return df_max\n\n# baseline_to_cf_select = Select(value=baseline_to_cf, title='Baseline', options=['804','805'])\n# country_to_cf_select = Select(value=country_to_cf, \n# title='Country', \n# options=countries+['World','Harmonizing','Uniform_delta'])\n\n# df_to_cf = get_data_to_cf(to_target,country_to_cf,baseline_to_cf)\n# ds_to_cf = ColumnDataSource(df_to_cf)\n# df_to_cf_max = build_max(df_to_cf)\n# ds_to_cf_max = ColumnDataSource(df_to_cf_max)\n\n# colors_to_cf = itertools.cycle(Category18)\n# colors_to_cf_max = itertools.cycle(Category18)\n\n# p_to_cf = figure(title=\"Patent protection counterfactual as function of TO target, baselines 804(2005) and 805 (2015)\", \n# width = 1200,\n# height = 850,\n# x_axis_label='Change in delta',\n# y_axis_label='Normalized Consumption equivalent welfare / Growth rate',\n# x_axis_type=\"log\",\n# tools = TOOLS) \n\n# for col in df_to_cf.columns:\n# if col not in [0,'delt','growth']:\n# p_to_cf.line(x='delt', y=col, source = ds_to_cf, color=next(colors_to_cf),line_width = 2, legend_label=col)\n\n# p_to_cf.circle(x = 'xmax', y = 'max', source = ds_to_cf_max, size=4, color='colors')\n \n# p_to_cf.legend.click_policy=\"hide\"\n# p_to_cf.legend.label_text_font_size = '8pt'\n# p_to_cf.add_layout(p_to_cf.legend[0], 'right')\n\n# def update_target_to_cf(attrname, old, new):\n# country_to_cf = country_to_cf_select.value\n# baseline_to_cf = baseline_to_cf_select.value\n# df_to_cf = get_data_to_cf(new/100,country_to_cf,baseline_to_cf)\n# ds_to_cf.data = df_to_cf\n# ds_to_cf_max.data = build_max(df_to_cf)\n \n# def update_baseline_to_cf(attrname, old, new):\n# country_to_cf = country_to_cf_select.value\n# to_target = slider_to_cf.value/100\n# df_to_cf = get_data_to_cf(to_target,country_to_cf,new)\n# ds_to_cf.data = df_to_cf\n# ds_to_cf_max.data = build_max(df_to_cf)\n \n# def update_country_to_cf(attrname, old, new):\n# to_target = slider_to_cf.value/100\n# baseline_to_cf = baseline_to_cf_select.value\n# df_to_cf = get_data_to_cf(to_target,new,baseline_to_cf)\n# ds_to_cf.data = df_to_cf\n# ds_to_cf_max.data = build_max(df_to_cf)\n \n# slider_to_cf = Slider(start=1, end=3, value=1.55, step=0.05, title=\"Turnover target in %\") \n \n# controls_to_cf = row(baseline_to_cf_select, slider_to_cf, country_to_cf_select)\n# country_to_cf_select.on_change('value', update_country_to_cf)\n# slider_to_cf.on_change('value', update_target_to_cf)\n# baseline_to_cf_select.on_change('value', update_baseline_to_cf)\n\n# counterfactuals_to_report = column(controls_to_cf,p_to_cf)\n\n#%% dynamic counterfactuals\n\nbaseline_dyn_cf = '1020'\ncountry_dyn_cf = 'USA'\n\nbaseline_dyn_cf_select = Select(value=baseline_dyn_cf, title='Baseline', options=['1020'])\ncountry_dyn_cf_select = Select(value=country_dyn_cf, \n title='Country', \n options=countries+['World','Harmonizing','Upper_harmonizing',\n 'Uniform_delta','Upper_uniform_delta'])\n\ndef get_data_dyn_cf(baseline,country):\n df_dyn_cf = pd.read_csv(cf_path+'baseline_'+baseline+'/dyn_'+country+'.csv')\n df_dyn_cf.set_index('delt',inplace=True)\n return df_dyn_cf\n\ndef build_max(df_dyn_cf):\n df_max = pd.concat([df_dyn_cf.idxmax(),df_dyn_cf.max()],axis=1)\n df_max.index.name = 'label'\n df_max.columns = ['xmax','max'] \n df_max = df_max.loc[countries]\n df_max['colors'] = Category18[:len(df_max)]\n return df_max\n\ndf_dyn_cf = get_data_dyn_cf(baseline_dyn_cf,country_dyn_cf)\nds_dyn_cf = ColumnDataSource(df_dyn_cf)\ndf_dyn_cf_max = build_max(df_dyn_cf)\nds_dyn_cf_max = ColumnDataSource(df_dyn_cf_max)\n\ncolors_dyn_cf = itertools.cycle(Category18)\ncolors_dyn_cf_max = itertools.cycle(Category18)\n\np_dyn_cf = figure(title=\"With transitional dynamics patent protection counterfactual\", \n width = 1200,\n height = 850,\n x_axis_label='Change in delta',\n y_axis_label='Normalized Consumption equivalent welfare / Growth rate',\n x_axis_type=\"log\",\n tools = TOOLS) \n\nfor col in df_dyn_cf.columns:\n if col not in [0,'delt']:\n p_dyn_cf.line(x='delt', y=col, source = ds_dyn_cf, \n color=next(colors_dyn_cf),line_width = 2, legend_label=col)\n\np_dyn_cf.circle(x = 'xmax', y = 'max', source = ds_dyn_cf_max, size=4, color='colors')\n \np_dyn_cf.legend.click_policy=\"hide\"\np_dyn_cf.legend.label_text_font_size = '8pt'\np_dyn_cf.add_layout(p_dyn_cf.legend[0], 'right')\n\ndef update_baseline_dyn_cf(attrname, old, new):\n country_dyn_cf = country_dyn_cf_select.value\n ds_dyn_cf.data = get_data_dyn_cf(new,country_dyn_cf)\n df_dyn_cf = get_data_dyn_cf(new,country_dyn_cf)\n ds_dyn_cf.data = df_dyn_cf\n ds_dyn_cf_max.data = build_max(df_dyn_cf)\n \ndef update_country_dyn_cf(attrname, old, new):\n baseline_dyn_cf = baseline_dyn_cf_select.value\n df_dyn_cf = get_data_dyn_cf(baseline_dyn_cf,new)\n ds_dyn_cf.data = df_dyn_cf\n ds_dyn_cf_max.data = build_max(df_dyn_cf)\n \ncontrols_dyn_cf = row(baseline_dyn_cf_select, country_dyn_cf_select)\n\nbaseline_dyn_cf_select.on_change('value', update_baseline_dyn_cf)\ncountry_dyn_cf_select.on_change('value', update_country_dyn_cf)\n\ncounterfactuals_dyn_report = column(controls_dyn_cf,p_dyn_cf)\n\n#%% counterfactuals 405 TO target with dynamics\n\n# country_to_cf_dyn = 'USA'\n# to_target_dyn = 0.016\n\n# list_of_to_targets_dyn = np.linspace(0.01,0.03,41)\n\n# def section_end(s):\n# return [int(_) for _ in s.split(\"_\")[-1].split(\".\")]\n# cf_to_list = sorted([s for s in os.listdir(cf_path) \n# if s[9:].startswith('405') and s.startswith('baseline')], key=section_end)\n\n# def get_data_to_cf_dyn(to_target_dyn,country):\n# idx_to_cf_dyn = np.argmin(np.abs(list_of_to_targets_dyn-to_target_dyn))\n# df_to_cf_dyn = pd.read_csv(cf_path+cf_to_list[min(idx_to_cf_dyn,len(cf_to_list)-1)]+'/dyn_'+country+'.csv')\n# df_to_cf_dyn.set_index('delt',inplace=True)\n# if country not in ['World','Harmonizing']:\n# df_to_cf_dyn['static_for_main_country'] = pd.read_csv(\n# cf_path+cf_to_list[min(idx_to_cf_dyn,len(cf_to_list)-1)]+'/'+country+'.csv'\n# )[country].values\n# else:\n# df_to_cf_dyn['static_for_main_country'] = np.nan\n# return df_to_cf_dyn\n\n# def build_max(df_to_cf):\n# df_max = pd.concat([df_to_cf.idxmax(),df_to_cf.max()],axis=1)\n# df_max.index.name = 'label'\n# df_max.columns = ['xmax','max'] \n# df_max = df_max.loc[countries]\n# df_max['colors'] = Category18[:len(df_max)]\n# return df_max\n\n# country_to_cf_dyn_select = Select(value=country_to_cf_dyn, \n# title='Country', \n# options=countries+['World','Harmonizing'])\n\n# df_to_cf_dyn = get_data_to_cf_dyn(to_target_dyn,country_to_cf_dyn)\n# ds_to_cf_dyn = ColumnDataSource(df_to_cf_dyn)\n# df_to_cf_dyn_max = build_max(df_to_cf_dyn)\n# ds_to_cf_dyn_max = ColumnDataSource(df_to_cf_dyn_max)\n\n# colors_to_cf_dyn = itertools.cycle(Category18)\n# colors_to_cf_dyn_max = itertools.cycle(Category18)\n\n# p_to_cf_dyn = figure(title=\"With transitional dynamics patent protection counterfactual as function of TO target, baseline 405\", \n# width = 1200,\n# height = 850,\n# x_axis_label='Change in delta',\n# y_axis_label='Normalized Consumption equivalent welfare',\n# x_axis_type=\"log\",\n# tools = TOOLS) \n\n# for col in df_to_cf_dyn.columns:\n# if col not in [0,'delt','static_for_main_country']:\n# p_to_cf_dyn.line(x='delt', y=col, source = ds_to_cf_dyn, \n# color=next(colors_to_cf_dyn),line_width = 2, legend_label=col)\n# if col == 'static_for_main_country':\n# p_to_cf_dyn.line(x='delt', y=col, source = ds_to_cf_dyn, \n# color='grey',line_width = 2, legend_label=col, \n# line_dash = 'dashed')\n\n# p_to_cf_dyn.circle(x = 'xmax', y = 'max', source = ds_to_cf_dyn_max, size=4, color='colors')\n\n# p_to_cf_dyn.legend.click_policy=\"hide\"\n# p_to_cf_dyn.legend.label_text_font_size = '8pt'\n# p_to_cf_dyn.add_layout(p_to_cf_dyn.legend[0], 'right')\n\n# def update_baseline_to_cf_dyn(attrname, old, new):\n# country_to_cf_dyn = country_to_cf_dyn_select.value\n# df_to_cf_dyn = get_data_to_cf_dyn(new/100,country_to_cf_dyn)\n# ds_to_cf_dyn.data = df_to_cf_dyn\n# ds_to_cf_dyn_max.data = build_max(df_to_cf_dyn)\n \n# def update_country_to_cf_dyn(attrname, old, new):\n# to_target_dyn = slider_to_cf_dyn.value/100\n# df_to_cf_dyn = get_data_to_cf_dyn(to_target_dyn,new)\n# ds_to_cf_dyn.data = df_to_cf_dyn\n# ds_to_cf_dyn_max.data = build_max(df_to_cf_dyn)\n \n# slider_to_cf_dyn = Slider(start=1, end=3, value=1.85, step=0.05, title=\"Turnover target in %\") \n \n# controls_to_cf_dyn = row(slider_to_cf_dyn, country_to_cf_dyn_select)\n# country_to_cf_dyn_select.on_change('value', update_country_to_cf_dyn)\n# slider_to_cf_dyn.on_change('value', update_baseline_to_cf_dyn)\n\n# counterfactuals_to_dyn_report = column(controls_to_cf_dyn,p_to_cf_dyn)\n\n#!!! third panel\n# third_panel = row(counterfactuals_dyn_report, counterfactuals_to_dyn_report, dyn_report)\nthird_panel = row(counterfactuals_dyn_report,counterfactuals_report)\n\n#%% Dynamic Nash / coop equilibrium and deviations from it\n\nbaseline_dyn_nash_coop = '1020'\nvariation_dyn_nash_coop = 'baseline'\nequilibrium_type ='Nash'\n\nbaseline_dyn_nash_coop_select = Select(value=baseline_dyn_nash_coop, title='Baseline', options=[\n # '607','501'\n '1020'\n ])\ndic_of_possible_variations_dyn_nash_coop = {\n # '1003':['baseline','0.4'],\n '1020':['baseline'],\n # '607':['baseline'],\n # '501':['1.0','2.0']\n }\nvariation_dyn_nash_coop_select = Select(value=variation_dyn_nash_coop, \n title='Variation', \n options=dic_of_possible_variations_dyn_nash_coop[baseline_dyn_nash_coop])\nequilibrium_type_select = Select(value=equilibrium_type, title='Equilibrium', options=['Nash','Coop eq','Coop negishi'])\n\ndef get_dyn_eq_deltas_welfares(baseline_dyn_nash_coop,variation_dyn_nash_coop,equilibrium_type):\n if equilibrium_type == 'Nash':\n deltas = pd.read_csv(nash_eq_path+'dyn_deltas.csv'\n ,index_col=0\n ,dtype={'baseline':str,'variation':str}).drop_duplicates(['baseline','variation','method'],keep='last')\n eq_deltas = deltas.loc[\n (deltas.baseline == baseline_dyn_nash_coop)\n & (deltas.variation == variation_dyn_nash_coop)\n ][countries].values.squeeze()\n welfares = pd.read_csv(nash_eq_path+'dyn_cons_eq_welfares.csv'\n ,index_col=0\n ,dtype={'baseline':str,'variation':str}).drop_duplicates(['baseline','variation','method'],keep='last')\n eq_welfares = welfares.loc[\n (welfares.baseline == baseline_dyn_nash_coop)\n & (welfares.variation == variation_dyn_nash_coop)\n ][countries].values.squeeze()\n \n if equilibrium_type == 'Coop eq':\n deltas = pd.read_csv(coop_eq_path+'dyn_deltas.csv'\n ,index_col=0\n ,dtype={'baseline':str,'variation':str}).drop_duplicates(['baseline','variation','aggregation_method'],keep='last')\n eq_deltas = deltas.loc[\n (deltas.baseline == baseline_dyn_nash_coop)\n & (deltas.variation == variation_dyn_nash_coop)\n & (deltas.aggregation_method == 'pop_weighted')\n ][countries].values.squeeze()\n welfares = pd.read_csv(coop_eq_path+'dyn_cons_eq_welfares.csv'\n ,index_col=0\n ,dtype={'baseline':str,'variation':str}).drop_duplicates(['baseline','variation','aggregation_method'],keep='last')\n eq_welfares = welfares.loc[\n (welfares.baseline == baseline_dyn_nash_coop)\n & (welfares.variation == variation_dyn_nash_coop)\n & (welfares.aggregation_method == 'pop_weighted')\n ][countries].values.squeeze()\n \n if equilibrium_type == 'Coop negishi':\n deltas = pd.read_csv(coop_eq_path+'dyn_deltas.csv'\n ,index_col=0\n ,dtype={'baseline':str,'variation':str}).drop_duplicates(['baseline','variation','aggregation_method'],keep='last')\n eq_deltas = deltas.loc[\n (deltas.baseline == baseline_dyn_nash_coop)\n & (deltas.variation == variation_dyn_nash_coop)\n & (deltas.aggregation_method == 'negishi')\n ][countries].values.squeeze()\n welfares = pd.read_csv(coop_eq_path+'dyn_cons_eq_welfares.csv'\n ,index_col=0\n ,dtype={'baseline':str,'variation':str}).drop_duplicates(['baseline','variation','aggregation_method'],keep='last')\n eq_welfares = welfares.loc[\n (welfares.baseline == baseline_dyn_nash_coop)\n & (welfares.variation == variation_dyn_nash_coop)\n & (welfares.aggregation_method == 'negishi')\n ][countries].values.squeeze()\n \n df = pd.DataFrame(index = pd.Index(countries,name='country'))\n df['deltas'] = eq_deltas\n df['welfares'] = eq_welfares\n df['colors'] = Category18[:len(df)]\n \n return df\n\ndef get_dyn_deviation_recap(baseline_dyn_nash_coop,variation_dyn_nash_coop,equilibrium_type):\n if variation_dyn_nash_coop == 'baseline':\n temp_run = baseline_dyn_nash_coop\n else:\n temp_run = baseline_dyn_nash_coop+'_'+variation_dyn_nash_coop\n \n if equilibrium_type == 'Nash':\n dyn_deviation_recap = pd.read_csv(around_dyn_eq_path+f'around_dyn_nash_eq/baseline_{temp_run}/all_countries.csv')\n \n if equilibrium_type == 'Coop eq':\n dyn_deviation_recap = pd.read_csv(around_dyn_eq_path+f'around_dyn_coop_equal_eq/baseline_{temp_run}/all_countries.csv')\n \n if equilibrium_type == 'Coop negishi':\n dyn_deviation_recap = pd.read_csv(around_dyn_eq_path+f'around_dyn_coop_negishi_eq/baseline_{temp_run}/all_countries.csv')\n\n return dyn_deviation_recap\n \nds_dyn_eq = ColumnDataSource(get_dyn_eq_deltas_welfares(baseline_dyn_nash_coop,variation_dyn_nash_coop,equilibrium_type))\n# ds_dyn_eq_dev = ColumnDataSource(get_dyn_deviation_recap(baseline_dyn_nash_coop,variation_dyn_nash_coop,equilibrium_type))\n\ncolors_dyn_eq_dev = itertools.cycle(Category18)\n\np_dyn_eq_dev = figure(title=\"With transitional dynamics Equilibria and unilateral deviations from it\", \n width = 1200,\n height = 850,\n x_axis_label='Delta',\n y_axis_label='Normalized Consumption equivalent welfare change',\n x_axis_type=\"log\",\n tools = TOOLS) \n\n# for country_eq_dev in countries:\n# color = next(colors_dyn_eq_dev)\n# p_dyn_eq_dev.line(x=country_eq_dev+'_delta', \n# y=country_eq_dev+'_welfare', \n# source = ds_dyn_eq_dev, \n# color=color,\n# line_width = 2, \n# legend_label=country_eq_dev+'_welfare')\n# p_dyn_eq_dev.line(x=country_eq_dev+'_delta', \n# y=country_eq_dev+'_world_negishi', \n# source = ds_dyn_eq_dev, \n# color=color,\n# line_width = 2, \n# line_dash='dashed',\n# legend_label=country_eq_dev+'_world_negishi')\n# p_dyn_eq_dev.line(x=country_eq_dev+'_delta', \n# y=country_eq_dev+'_world_equal', \n# source = ds_dyn_eq_dev, \n# color=color,\n# line_width = 2, \n# line_dash='dotted',\n# legend_label=country_eq_dev+'_world_equal')\n\np_dyn_eq_dev.circle(x = 'deltas', y = 'welfares', source = ds_dyn_eq, size=4,color = 'colors')\n\n# p_dyn_eq_dev.legend.click_policy=\"hide\"\n# p_dyn_eq_dev.legend.label_text_font_size = '8pt'\n# p_dyn_eq_dev.add_layout(p_dyn_eq_dev.legend[0], 'right')\n\nhover_tool_eq = HoverTool()\nhover_tool_eq.tooltips = [\n (\"delta\", \"$x\"),\n (\"welfare\", \"$y\")\n ] \np_dyn_eq_dev.add_tools(hover_tool_eq)\n\n\nlabels_dyn_eq_dev = LabelSet(x='deltas', y='welfares', text='country',\n x_offset=2, y_offset=2, source=ds_dyn_eq, text_font_size=\"7pt\")\n\np_dyn_eq_dev.add_layout(labels_dyn_eq_dev)\n\n\ndef update_baseline_dyn_nash(attrname, old, new):\n variation_dyn_nash_coop_select.value = dic_of_possible_variations_dyn_nash_coop[new][0]\n variation_dyn_nash_coop_select.options = dic_of_possible_variations_dyn_nash_coop[new]\n ds_dyn_eq.data = get_dyn_eq_deltas_welfares(new,\n variation_dyn_nash_coop_select.value,\n equilibrium_type_select.value)\n # ds_dyn_eq_dev.data = get_dyn_deviation_recap(new,\n # variation_dyn_nash_coop_select.value,\n # equilibrium_type_select.value)\n \ndef update_variation_dyn_nash_coop(attrname, old, new):\n ds_dyn_eq.data = get_dyn_eq_deltas_welfares(baseline_dyn_nash_coop_select.value,\n new,\n equilibrium_type_select.value)\n # ds_dyn_eq_dev.data = get_dyn_deviation_recap(baseline_dyn_nash_coop_select.value,\n # new,\n # equilibrium_type_select.value)\n \ndef update_equilibrium_type(attrname, old, new):\n ds_dyn_eq.data = get_dyn_eq_deltas_welfares(baseline_dyn_nash_coop_select.value,\n variation_dyn_nash_coop_select.value,\n new)\n # ds_dyn_eq_dev.data = get_dyn_deviation_recap(baseline_dyn_nash_coop_select.value,\n # variation_dyn_nash_coop_select.value,\n # new)\n\ncontrols_dyn_eq_dev = row(baseline_dyn_nash_coop_select, variation_dyn_nash_coop_select, equilibrium_type_select)\n\nbaseline_dyn_nash_coop_select.on_change('value', update_baseline_dyn_nash)\nvariation_dyn_nash_coop_select.on_change('value', update_variation_dyn_nash_coop)\nequilibrium_type_select.on_change('value', update_equilibrium_type)\n\ndyn_eq_dev_report = column(controls_dyn_eq_dev,p_dyn_eq_dev)\n\n\n#%% Nash / coop equilibrium\ndef section_ser(s):\n return pd.Series([[int(_) for _ in s_e.split(\".\")] for s_e in s])\n\nbaseline_nash_coop = '1020'\n\ndic_change_labels_for_405 = {'405, '+k:comments_dic['403'][k] for k in comments_dic['405']}\n\ndef get_data_nash_coop(baseline_nash_number):\n\n welf_coop = pd.read_csv(coop_eq_path+'cons_eq_welfares.csv',index_col=0).drop_duplicates(['baseline', \n 'variation','aggregation_method'],keep='last').sort_values(['baseline','variation'])\n welf_nash = pd.read_csv(nash_eq_path+'cons_eq_welfares.csv',index_col=0).drop_duplicates(['baseline', \n 'variation'],keep='last').sort_values(['baseline','variation'])\n \n welf_coop['run'] = welf_coop['baseline'].astype('str')+', '+welf_coop['variation']\n welf_nash['run'] = welf_nash['baseline'].astype('str')+', '+welf_nash['variation']\n\n welf_coop['run'] = welf_coop['run'].replace(dic_change_labels_for_405)\n welf_nash['run'] = welf_nash['run'].replace(dic_change_labels_for_405)\n \n welf_coop['sorting'] = welf_coop['variation'].str.replace('baseline','0')#.astype(float)\n welf_nash['sorting'] = welf_nash['variation'].str.replace('baseline','0')#.astype(float)\n \n welf_coop = welf_coop.sort_values('sorting',key=section_ser)#.sort_values('baseline')\n welf_nash = welf_nash.sort_values('sorting',key=section_ser)#.sort_values('baseline')\n \n welf_coop = welf_coop[welf_coop['baseline'].isin([int(baseline_nash_number)])]\n welf_nash = welf_nash[welf_nash['baseline'].isin([int(baseline_nash_number)])]\n \n welf_negishi = welf_coop[welf_coop['aggregation_method'] == 'negishi']\n welf_pop_weighted = welf_coop[welf_coop['aggregation_method'] == 'pop_weighted']\n \n return welf_pop_weighted, welf_negishi, welf_nash\n\nbaseline_nash_coop_select = Select(value=baseline_nash_coop, title='Baseline', \n # options=['404','405','501','601'])\n # options=['501','607','618','619'])\n # options=['802','803','804','805','806'])\n options=['1020'])\n\nwelf_pop_weighted, welf_negishi, welf_nash = get_data_nash_coop(baseline_nash_coop)\n \nds_pop_weighted = ColumnDataSource(welf_pop_weighted)\nds_negishi = ColumnDataSource(welf_negishi)\nds_nash = ColumnDataSource(welf_nash)\n\ncolors_pop_weighted = itertools.cycle(Category18)\ncolors_negishi = itertools.cycle(Category18)\ncolors_nash = itertools.cycle(Category18)\n\nx_range_nash = welf_nash['run'].to_list()\n\np_eq = figure(title=\"Static cooperative and Nash equilibrium\", \n width = 1200,\n height = 900,\n x_range = x_range_nash,\n # x_axis_label='Run',\n y_axis_label='Consumption eqivalent welfare change',\n tools = TOOLS\n ) \np_eq.xaxis.major_label_orientation = 3.14/3\n\nlines_nash = {}\nfor col in p_baseline.countries+['Equal']+['Negishi']:\n lines_nash[col+' Nash'] = p_eq.line(x='run', y=col, source = ds_nash, color=next(colors_nash),line_width = 2, legend_label=col+' Nash')\n lines_nash[col+' coop equal'] = p_eq.line(x='run', y=col, source = ds_pop_weighted, color=next(colors_pop_weighted), line_dash='dashed', line_width = 2, legend_label=col+' coop equal')\n lines_nash[col+' coop negishi'] = p_eq.line(x='run', y=col, source = ds_negishi, color=next(colors_negishi), line_dash='dotted', line_width = 2, legend_label=col+' coop negishi')\n if col != 'Negishi' and col != 'Equal':\n lines_nash[col+' Nash'].visible = False\n lines_nash[col+' coop equal'].visible = False\n lines_nash[col+' coop negishi'].visible = False\n \n \np_eq.legend.click_policy=\"hide\"\np_eq.legend.label_text_font_size = '8pt'\np_eq.legend.spacing = 0\np_eq.add_layout(p_eq.legend[0], 'right') \n\nhover_tool_eq = HoverTool()\nhover_tool_eq.tooltips = [\n (\"run\", \"@run\"),\n (\"value\", \"$y\")\n ] \np_eq.add_tools(hover_tool_eq)\n\ncolumns = [\n TableColumn(field=\"runs\", title=\"Runs\"),\n TableColumn(field=\"comments\", title=\"Description\"),\n ]\n\nexplication = Div(text=\"In the legend, first is the quantity displayed and last\\\n is the quantity maximized
'Negishi coop equal' means that:
\\\n - we display the Change in cons equivalent of world welfare
according to Negishi weights aggregation
\\\n - we maximize according to the Change in cons equivalent of world welfare
according to equal weights aggregation\\\n \")\n\ndata_table_welfares = pd.concat([welf_nash.set_index('run'),\n welf_negishi.set_index('run'),\n welf_pop_weighted.set_index('run')],\n axis=0,\n keys=['Nash','Coop Negishi','Coop equal'],\n names=['type','run'],\n sort=False\n ).reset_index().sort_values('sorting',key=section_ser)[['run','type']+p_baseline.countries+['Equal']+['Negishi']]\n\nsource_table_welfares = ColumnDataSource(data_table_welfares)\ncolumns_welf = [TableColumn(field=col) for col in ['run','type']+p_baseline.countries+['Equal']+['Negishi']]\n\ntable_widget_welfares = DataTable(source=source_table_welfares, columns=columns_welf, width=1100, height=400,\n )\n\ndef get_delta_nash_coop(baseline_number):\n deltas_coop = pd.read_csv(coop_eq_path+'deltas.csv',index_col=0).drop_duplicates(['baseline', \n 'variation','aggregation_method'],keep='last').sort_values(['baseline','variation'])\n deltas_nash = pd.read_csv(nash_eq_path+'deltas.csv',index_col=0).drop_duplicates(['baseline', \n 'variation'],keep='last').sort_values(['baseline','variation'])\n \n deltas_coop['run'] = deltas_coop['baseline'].astype('str')+', '+deltas_coop['variation']\n deltas_nash['run'] = deltas_nash['baseline'].astype('str')+', '+deltas_nash['variation']\n \n deltas_coop['run'] = deltas_coop['run'].replace(dic_change_labels_for_405)\n deltas_nash['run'] = deltas_nash['run'].replace(dic_change_labels_for_405)\n \n deltas_coop['sorting'] = deltas_coop['variation'].str.replace('baseline','0')#.astype(float)\n deltas_nash['sorting'] = deltas_nash['variation'].str.replace('baseline','0')#.astype(float)\n \n deltas_coop = deltas_coop.sort_values('sorting',key=section_ser)#.sort_values('baseline')\n deltas_nash = deltas_nash.sort_values('sorting',key=section_ser)#.sort_values('baseline')\n \n deltas_coop = deltas_coop[deltas_coop['baseline'].isin([int(baseline_number)])]\n deltas_nash = deltas_nash[deltas_nash['baseline'].isin([int(baseline_number)])]\n \n deltas_negishi = deltas_coop[deltas_coop['aggregation_method'] == 'negishi']\n deltas_pop_weighted = deltas_coop[deltas_coop['aggregation_method'] == 'pop_weighted']\n \n return deltas_pop_weighted, deltas_negishi, deltas_nash\n\ndeltas_pop_weighted, deltas_negishi, deltas_nash = get_delta_nash_coop(baseline_nash_coop)\n\nds_deltas_negishi = ColumnDataSource(deltas_negishi)\nds_deltas_pop_weighted = ColumnDataSource(deltas_pop_weighted)\nds_deltas_nash = ColumnDataSource(deltas_nash)\n\ncolors_deltas_negishi = itertools.cycle(Category18)\ncolors_deltas_pop_weighted = itertools.cycle(Category18)\ncolors_deltas_nash = itertools.cycle(Category18)\n\np_deltas_eq = figure(title=\"Static cooperative and Nash equilibrium\", \n width = 1200,\n height = 900,\n x_range = x_range_nash,\n y_axis_type=\"log\",\n y_axis_label='Delta',\n tools = TOOLS\n ) \np_deltas_eq.xaxis.major_label_orientation = 3.14/3\n\nlines_delta={}\nfor col in p_baseline.countries:\n lines_delta[col+' Nash'] = p_deltas_eq.line(x='run', y=col, \n source = ds_deltas_nash, color=next(colors_deltas_nash),\n line_width = 2, legend_label=col+' Nash')\n lines_delta[col+' coop equal'] = p_deltas_eq.line(x='run', y=col, \n source = ds_deltas_pop_weighted, color=next(colors_deltas_pop_weighted), line_dash='dashed', \n line_width = 2, legend_label=col+' coop equal')\n lines_delta[col+' coop negishi'] = p_deltas_eq.line(x='run', y=col, \n source = ds_deltas_negishi, color=next(colors_deltas_negishi), line_dash='dotted', \n line_width = 2, legend_label=col+' coop negishi')\n lines_delta[col+' coop equal'].visible = False\n lines_delta[col+' coop negishi'].visible = False\n \np_deltas_eq.legend.click_policy=\"hide\"\np_deltas_eq.legend.label_text_font_size = '8pt'\np_deltas_eq.legend.spacing = 0\np_deltas_eq.add_layout(p_deltas_eq.legend[0], 'right') \nhover_tool_deltas_eq = HoverTool()\nhover_tool_deltas_eq.tooltips = [\n (\"run\", \"@run\"),\n (\"value\", \"$y\")\n ] \np_deltas_eq.add_tools(hover_tool_deltas_eq)\n\ndata_table_deltas = pd.concat([deltas_nash.set_index('run'),\n deltas_negishi.set_index('run'),\n deltas_pop_weighted.set_index('run')],\n axis=0,\n keys=['Nash','Coop Negishi','Coop equal'],\n names=['type','run'],\n sort=False\n ).reset_index().sort_values('sorting',key=section_ser)[['run','type']+p_baseline.countries]\n\nsource_table_deltas = ColumnDataSource(data_table_deltas)\ncolumns_deltas = [TableColumn(field=col) for col in ['run','type']+p_baseline.countries+['Equal']+['Negishi']]\n\ntable_widget_deltas = DataTable(source=source_table_deltas, columns=columns_deltas, width=1100, height=400,\n )\n\ndef update_baseline_nash(attrname, old, new):\n baseline_nash_number = new\n welf_pop_weighted, welf_negishi, welf_nash = get_data_nash_coop(baseline_nash_number)\n \n ds_pop_weighted.data = welf_pop_weighted\n ds_negishi.data = welf_negishi\n ds_nash.data = welf_nash\n \n deltas_pop_weighted, deltas_negishi, deltas_nash = get_delta_nash_coop(baseline_nash_number)\n\n ds_deltas_negishi.data = deltas_negishi\n ds_deltas_pop_weighted.data = deltas_pop_weighted\n ds_deltas_nash.data = deltas_nash\n \n p_eq.x_range.factors = welf_nash['run'].to_list()\n p_deltas_eq.x_range.factors = welf_nash['run'].to_list()\n\nbaseline_nash_coop_select.on_change('value', update_baseline_nash)\n\nnash_coop_welfare_report = column(baseline_nash_coop_select,p_eq,table_widget_welfares)\nnash_coop_deltas_report = column(p_deltas_eq,table_widget_deltas)\n\n#!!! fourth panel\nfourth_panel = row(dyn_eq_dev_report, nash_coop_welfare_report, nash_coop_deltas_report)\n# fourth_panel = row(nash_coop_welfare_report, nash_coop_deltas_report)\n\n#%% dynamic solver\n\nbaseline_dyn = '1020'\ncountry_dyn = 'USA'\nsector_dyn = 'Patent'\n\nbaseline_dyn_select = Select(value=baseline_dyn, title='Baseline', \n # options=['501','604','607','608','609','610']\n options=['1020']\n )\n\nbaseline_dyn_path = results_path+'baseline_'+baseline_dyn+'_variations/'\nfiles_in_dir = next(os.walk(baseline_dyn_path))[1]\nrun_list = [f for f in files_in_dir if f[0].isnumeric()]\nrun_list = sorted(run_list, key=section)\nvariation_dyn_select = Select(value='baseline', title='Variation', \n options=['baseline']+run_list)\n\ndef update_list_of_runs_dyn(attr, old, new):\n baseline_dyn_path = results_path+'baseline_'+new+'_variations/'\n files_in_dir = next(os.walk(baseline_dyn_path))[1]\n run_list = [f for f in files_in_dir if f[0].isnumeric()]\n run_list = sorted(run_list, key=section)\n variation_dyn_select.options = ['baseline']+run_list\n\ncountry_dyn_select = Select(value='USA', title='Country delta to change', options=['USA', 'EUR', 'JAP', 'CHN', 'BRA', \n 'IND','CAN','KOR','RUS','AUS',\n 'MEX', 'ROW','World'])\nslider_dyn = Slider(start=-1, end=0.5, value=0, step=0.01, title=\"Log change of delta\") \n\nstate_computation = Div(text=\"Done\")\n\ndef make_time_evolution_df(dyn_sol):\n qties = ['w','l_R','l_Ae','l_Ao','price_indices','Z','g','r','profit']\n df = pd.DataFrame(index = pd.Index(qties,name='Quantity'), \n columns = ['Initial jump mean','Initial jump median',\n 'Typical time of evolution\\nmean','Typical time of evolution\\nmedian'])\n for qty in qties:\n a = dyn_sol.get_jump(qty)\n df.loc[qty,'Initial jump mean'] = a[0].round(2)\n df.loc[qty,'Initial jump median'] = a[1].round(2)\n b = dyn_sol.get_typical_time_evolution(qty)\n df.loc[qty,'Typical time of evolution\\nmean'] = b[0].round(2)\n df.loc[qty,'Typical time of evolution\\nmedian'] = b[1].round(2)\n return df\n\ndef fit_and_eval(vec,dyn_sol):\n fit = np.polyval(np.polyfit(dyn_sol.t_real,\n vec,\n dyn_sol.Nt),np.linspace(0,dyn_sol.t_inf,2001))\n return fit\n\ndef create_column_data_source_from_dyn_sol(dyn_sol):\n data_dyn = {}\n data_dyn['time'] = np.linspace(0,dyn_sol.t_inf,2001)\n for agg_qty in ['g']:\n data_dyn[agg_qty] = fit_and_eval(getattr(dyn_sol,agg_qty),dyn_sol)\n for c_qty in ['Z','r','price_indices','w','nominal_final_consumption','ratios_of_consumption_levels_change_not_normalized',\n 'integrand_welfare','second_term_sum_welfare','integral_welfare']:\n for i,c in enumerate(dyn_sol.countries):\n data_dyn[c_qty+c] = fit_and_eval(getattr(dyn_sol,c_qty)[i,:].ravel(),dyn_sol)\n for c_s_qty in ['l_R','psi_o_star','PSI_CD','l_Ao']:\n for i,c in enumerate(dyn_sol.countries):\n if c_s_qty in ['PSI_CD']:\n data_dyn[c_s_qty+c] = fit_and_eval(\n (getattr(dyn_sol,c_s_qty)+getattr(dyn_sol,c_s_qty+'_0')[...,None])[i,1,:].ravel(),dyn_sol)\n else:\n data_dyn[c_s_qty+c] = fit_and_eval(\n getattr(dyn_sol,c_s_qty)[i,1,:].ravel(),dyn_sol)\n for c_c_s_qty in ['l_Ae','PSI_MPD','PSI_MPND','PSI_MNP','profit']:\n if c_c_s_qty in ['PSI_MPD','PSI_MPND','PSI_MNP']:\n temp_sum_n = (getattr(dyn_sol,c_c_s_qty)+getattr(dyn_sol,c_c_s_qty+'_0')[...,None]).sum(axis=0)\n temp_sum_i = (getattr(dyn_sol,c_c_s_qty)+getattr(dyn_sol,c_c_s_qty+'_0')[...,None]).sum(axis=1)\n else:\n temp_sum_n = getattr(dyn_sol,c_c_s_qty).sum(axis=0)\n temp_sum_i = getattr(dyn_sol,c_c_s_qty).sum(axis=1)\n for i,c in enumerate(dyn_sol.countries):\n data_dyn['sum_n_'+c_c_s_qty+c] = fit_and_eval(temp_sum_n[i,1,:].ravel(),dyn_sol)\n data_dyn['sum_i_'+c_c_s_qty+c] = fit_and_eval(temp_sum_i[i,1,:].ravel(),dyn_sol)\n for i,c in enumerate(dyn_sol.countries):\n data_dyn['real_final_consumption'+c] = fit_and_eval((getattr(dyn_sol,'nominal_final_consumption')[i,:]\n /getattr(dyn_sol,'price_indices')[i,:]).ravel(),dyn_sol)\n \n data_dyn_init = {}\n data_dyn_init['time'] = [0]\n for agg_qty in ['g']:\n data_dyn_init[agg_qty] = [getattr(dyn_sol.sol_init,agg_qty)]\n for c_qty in ['Z','price_indices','w','nominal_final_consumption']:\n for i,c in enumerate(dyn_sol.countries):\n data_dyn_init[c_qty+c] = [getattr(dyn_sol.sol_init,c_qty)[i]]\n for c_s_qty in ['l_R','psi_o_star','PSI_CD','l_Ao']:\n for i,c in enumerate(dyn_sol.countries):\n data_dyn_init[c_s_qty+c] = [getattr(dyn_sol.sol_init,c_s_qty)[i,1]]\n for c_c_s_qty in ['l_Ae','PSI_MPD','PSI_MPND','PSI_MNP','profit']:\n if c_c_s_qty == 'profit':\n temp_sum_n = (getattr(dyn_sol.sol_init,c_c_s_qty)*getattr(dyn_sol.sol_init,'w')[None,:,None]).sum(axis=0)[:,1]\n temp_sum_i = (getattr(dyn_sol.sol_init,c_c_s_qty)*getattr(dyn_sol.sol_init,'w')[None,:,None]).sum(axis=1)[:,1]\n else:\n temp_sum_n = getattr(dyn_sol.sol_init,c_c_s_qty).sum(axis=0)[:,1]\n temp_sum_i = getattr(dyn_sol.sol_init,c_c_s_qty).sum(axis=1)[:,1]\n for i,c in enumerate(dyn_sol.countries):\n data_dyn_init['sum_n_'+c_c_s_qty+c] = [temp_sum_n[i]]\n data_dyn_init['sum_i_'+c_c_s_qty+c] = [temp_sum_i[i]]\n for i,c in enumerate(dyn_sol.countries):\n data_dyn_init['real_final_consumption'+c] = [getattr(dyn_sol.sol_init,'nominal_final_consumption')[i]/getattr(dyn_sol.sol_init,'price_indices')[i]]\n data_dyn_init['r'+c] = [getattr(dyn_sol.sol_init,'r')]\n data_dyn_init['integrand_welfare'+c] = [None]\n data_dyn_init['integral_welfare'+c] = [None]\n data_dyn_init['second_term_sum_welfare'+c] = [None]\n data_dyn_init['ratios_of_consumption_levels_change_not_normalized'+c] = [None]\n \n data_dyn_fin = {}\n data_dyn_fin['time'] = [dyn_sol.t_inf]\n for agg_qty in ['g']:\n data_dyn_fin[agg_qty] = [getattr(dyn_sol.sol_fin,agg_qty)]\n for c_qty in ['Z','price_indices','w','nominal_final_consumption']:\n for i,c in enumerate(dyn_sol.countries):\n data_dyn_fin[c_qty+c] = [getattr(dyn_sol.sol_fin,c_qty)[i]]\n for c_s_qty in ['l_R','psi_o_star','PSI_CD','l_Ao']:\n for i,c in enumerate(dyn_sol.countries):\n data_dyn_fin[c_s_qty+c] = [getattr(dyn_sol.sol_fin,c_s_qty)[i,1]]\n for c_c_s_qty in ['l_Ae','PSI_MPD','PSI_MPND','PSI_MNP','profit']:\n if c_c_s_qty == 'profit':\n temp_sum_n = (getattr(dyn_sol.sol_fin,c_c_s_qty)*getattr(dyn_sol.sol_fin,'w')[None,:,None]).sum(axis=0)[:,1]\n temp_sum_i = (getattr(dyn_sol.sol_fin,c_c_s_qty)*getattr(dyn_sol.sol_fin,'w')[None,:,None]).sum(axis=1)[:,1]\n else:\n temp_sum_n = getattr(dyn_sol.sol_fin,c_c_s_qty).sum(axis=0)[:,1]\n temp_sum_i = getattr(dyn_sol.sol_fin,c_c_s_qty).sum(axis=1)[:,1]\n for i,c in enumerate(dyn_sol.countries):\n data_dyn_fin['sum_n_'+c_c_s_qty+c] = [temp_sum_n[i]]\n data_dyn_fin['sum_i_'+c_c_s_qty+c] = [temp_sum_i[i]]\n for i,c in enumerate(dyn_sol.countries):\n data_dyn_fin['real_final_consumption'+c] = [getattr(dyn_sol.sol_fin,'nominal_final_consumption')[i]/getattr(dyn_sol.sol_fin,'price_indices')[i]]\n data_dyn_fin['r'+c] = [getattr(dyn_sol.sol_fin,'r')]\n data_dyn_fin['integrand_welfare'+c] = [None]\n data_dyn_fin['integral_welfare'+c] = [None]\n data_dyn_fin['second_term_sum_welfare'+c] = [None]\n data_dyn_fin['ratios_of_consumption_levels_change_not_normalized'+c] = [None]\n \n return data_dyn, data_dyn_init, data_dyn_fin\n\ndef compute_dyn(event):\n if variation_dyn_select.value == 'baseline':\n path = results_path+baseline_dyn_select.value+'/'\n else:\n path = results_path+'baseline_'+baseline_dyn_select.value+'_variations/'+variation_dyn_select.value+'/'\n p_dyn, m_dyn, sol_dyn = load(path, data_path=data_path,\n dir_path=dir_path)\n p_dyn_cf = p_dyn.copy()\n if country_dyn_select.value != 'World':\n p_dyn_cf.delta[p_dyn.countries.index(country_dyn_select.value),1] = p_dyn_cf.delta[p_dyn.countries.index(country_dyn_select.value),1]*(10**slider_dyn.value)\n else:\n p_dyn_cf.delta[:,1] = p_dyn_cf.delta[:,1]*(10**slider_dyn.value)\n start = time.perf_counter()\n dyn_sol, sol_c, convergence = rough_dyn_fixed_point_solver(p_dyn_cf, sol_dyn, sol_fin = None,Nt=25,\n t_inf=500, x0=None, tol = 1e-14, max_count=1e6, safe_convergence=0.1,damping=50, damping_post_acceleration=10)\n end = time.perf_counter()\n if country_dyn_select.value == 'World':\n message = 'Done, computation for all deltas multiplied by a factor '+str(10**slider_dyn.value)+'
Convergence : '+str(convergence)+'
Computation time : '+str(end-start)\n else:\n message = 'Done, computation for delta '+country_dyn_select.value+' = '+str(p_dyn_cf.delta[p_dyn.countries.index(country_dyn_select.value),1])+'
Convergence : '+str(convergence)+'
Computation time : '+str(end-start)\n state_computation.text = message\n temp = create_column_data_source_from_dyn_sol(dyn_sol)\n ds_dyn.data = temp[0]\n ds_dyn_init.data = temp[1]\n ds_dyn_fin.data = temp[2]\n source_table_time_evol.data = make_time_evolution_df(dyn_sol)\n \nif variation_dyn_select.value == 'baseline':\n path = results_path+baseline_dyn_select.value+'/'\nelse:\n path = results_path+'baseline_'+baseline_dyn_select.value+'_variations/'+variation_dyn_select.value+'/'\np_dyn, m_dyn, sol_dyn = load(path, data_path=data_path,\n dir_path=dir_path)\np_dyn_cf = p_dyn.copy()\nif country_dyn_select.value != 'World':\n p_dyn_cf.delta[p_dyn.countries.index(country_dyn_select.value),1] = p_dyn_cf.delta[p_dyn.countries.index(country_dyn_select.value),1]*10**slider_dyn.value\nelse:\n p_dyn_cf.delta[:,1] = p_dyn_cf.delta[:,1]*slider_dyn.value\ndyn_sol, sol_c, convergence = rough_dyn_fixed_point_solver(p_dyn_cf, sol_dyn, sol_fin = None,Nt=25,\n t_inf=500, x0=None, tol = 1e-14, max_count=1e6, safe_convergence=0.1,damping=50, damping_post_acceleration=10)\n\nsource_table_time_evol = ColumnDataSource(make_time_evolution_df(dyn_sol))\ncolumns_time_evol = [TableColumn(field=col) for col in \n ['Quantity','Initial jump mean','Initial jump median',\n 'Typical time of evolution\\nmean','Typical time of evolution\\nmedian']]\ntable_widget_time_evol = DataTable(source=source_table_time_evol, columns=columns_time_evol, width=600, height=750)\n\nbutton_compute_dyn = Button(label=\"Compute\",align='end')\nbutton_compute_dyn.on_event(ButtonClick, compute_dyn)\n\nqty_dyn_display_select = Select(value='g', title='Quantity', options=['g','Z','r','price_indices','w','nominal_final_consumption',\n 'real_final_consumption','ratios_of_consumption_levels_change_not_normalized',\n 'l_R','l_Ao','psi_o_star',\n 'PSI_CD','integrand_welfare','integral_welfare','second_term_sum_welfare',\n 'sum_n_l_Ae','sum_n_PSI_MPD','sum_n_PSI_MPND','sum_n_PSI_MNP','sum_n_profit',\n 'sum_i_l_Ae','sum_i_PSI_MPD','sum_i_PSI_MPND','sum_i_PSI_MNP','sum_i_profit'])\ncountry_dyn_display_select = Select(value='USA', title='Country', options=['USA', 'EUR', 'JAP', 'CHN', 'BRA', \n 'IND','CAN','KOR','RUS','AUS',\n 'MEX', 'ROW'])\n\ntemp = create_column_data_source_from_dyn_sol(dyn_sol)\ndata_dyn_default = temp[0]\ndata_dyn_init_default = temp[1]\ndata_dyn_fin_default = temp[2]\nds_dyn = ColumnDataSource(data_dyn_default)\nds_dyn_init = ColumnDataSource(data_dyn_init_default)\nds_dyn_fin = ColumnDataSource(data_dyn_fin_default)\nup_max = max([max(ds_dyn.data['g']), max(ds_dyn_fin.data['g']), max(ds_dyn_init.data['g'])])\ndown_min = min([min(ds_dyn.data['g']), min(ds_dyn_fin.data['g']), min(ds_dyn_init.data['g'])])\ndelta = up_max-down_min\nif delta == 0:\n delta = 1\np_dyn_figure = figure(title=\"Dynamic solver\",\n width = 1200,\n height = 750,\n x_axis_label='Time',\n y_axis_label='Value',\n tools = TOOLS,\n x_range = (-20,dyn_sol.t_inf+20),\n y_range=(down_min-delta*0.1,up_max+delta*0.1)\n )\n\nhover_tool_eq = HoverTool()\nhover_tool_eq.tooltips = [\n (\"Time\", \"$x\"),\n (\"value\", \"$y\")\n ] \np_dyn_figure.add_tools(hover_tool_eq)\n\nlines_dyn = {}\nfor col in data_dyn_default.keys():\n if col != time:\n lines_dyn[col] = p_dyn_figure.line(x='time', y=col, source = ds_dyn)\n if col != 'g':\n lines_dyn[col].visible = False\n\ninit_dyn = {}\nfor col in data_dyn_init_default.keys():\n if col != time:\n init_dyn[col] = p_dyn_figure.circle(x='time', y=col, source = ds_dyn_init, color='red',size=8)\n if col != 'g':\n init_dyn[col].visible = False\n \nfin_dyn = {}\nfor col in data_dyn_fin_default.keys():\n if col != time:\n fin_dyn[col] = p_dyn_figure.circle(x='time', y=col, source = ds_dyn_fin, color='red',size=8)\n if col != 'g':\n fin_dyn[col].visible = False\n\ndef update_graph_dyn(event):\n if qty_dyn_display_select.value in ['g']:\n col = qty_dyn_display_select.value\n elif qty_dyn_display_select.value in ['Z','r','price_indices','w','nominal_final_consumption','real_final_consumption',\n 'ratios_of_consumption_levels_change_not_normalized',\n 'l_R','l_Ao','psi_o_star','PSI_CD','integrand_welfare','integral_welfare','second_term_sum_welfare',\n 'sum_n_l_Ae','sum_n_PSI_MPD','sum_n_PSI_MPND','sum_n_PSI_MNP','sum_n_profit',\n 'sum_i_l_Ae','sum_i_PSI_MPD','sum_i_PSI_MPND','sum_i_PSI_MNP','sum_i_profit']:\n col = qty_dyn_display_select.value+country_dyn_display_select.value\n lines_dyn[col].visible = True\n if qty_dyn_display_select.value not in ['integrand_welfare','integral_welfare',\n 'second_term_sum_welfare','ratios_of_consumption_levels_change_not_normalized']:\n init_dyn[col].visible = True\n fin_dyn[col].visible = True\n else:\n init_dyn[col].visible = False\n fin_dyn[col].visible = False\n\n for other_column in lines_dyn:\n if other_column != col:\n lines_dyn[other_column].visible = False\n init_dyn[other_column].visible = False\n fin_dyn[other_column].visible = False\n try:\n up_max = max([max(ds_dyn.data[col]), max(ds_dyn_fin.data[col]), max(ds_dyn_init.data[col])])\n down_min = min([min(ds_dyn.data[col]), min(ds_dyn_fin.data[col]), min(ds_dyn_init.data[col])])\n except:\n up_max = max(ds_dyn.data[col])\n down_min = min(ds_dyn.data[col])\n delta = up_max-down_min\n if delta == 0:\n delta = 1\n p_dyn_figure.y_range.start=down_min-delta*0.1\n p_dyn_figure.y_range.end=up_max+delta*0.1\n p_dyn_figure.x_range.start=-20\n p_dyn_figure.x_range.end=dyn_sol.t_inf+20\n \nbutton_display_dyn = Button(label=\"Display\",align='end')\nbutton_display_dyn.on_event(ButtonClick, update_graph_dyn)\n\ncontrols_dyn = row(baseline_dyn_select, variation_dyn_select, country_dyn_select, slider_dyn, button_compute_dyn, state_computation)\ncontrols_display_dyn = row(qty_dyn_display_select, \n country_dyn_display_select,\n button_display_dyn)\n\nbaseline_dyn_select.on_change('value', update_list_of_runs_dyn)\n\ndyn_report = column(controls_dyn,controls_display_dyn,p_dyn_figure)\n\n\n#!!! fifth_panel\n# fifth_panel = row(counterfactuals_report, counterfactuals_to_report)\nfifth_panel = row(dyn_report,table_widget_time_evol)\n\n#%% sensitivities\n\nbaselines_dic_sensi = {}\n\nfor baseline_nbr in ['1004']:\n baselines_dic_sensi[baseline_nbr] = {} \n baseline_sensi_path = results_path+'baseline_'+baseline_nbr+'_sensitivity_tables/'\n files_in_dir = os.listdir(baseline_sensi_path)\n files_in_dir = [ filename for filename in files_in_dir if filename.endswith('.csv') ]\n for f in files_in_dir:\n baselines_dic_sensi[baseline_nbr][f[:-4]] = pd.read_csv(baseline_sensi_path+f,index_col = 0)\n \nbaseline_sensi = '1004'\nqty_sensi = 'objective'\n\nbaseline_sensi_select = Select(value=baseline_sensi, title='Baseline', options=sorted(baselines_dic_sensi.keys()))\nqty_sensi_select = Select(value=qty_sensi, title='Quantity', options=sorted(baselines_dic_sensi[baseline_sensi].keys()))\n\nds_sensi = ColumnDataSource(baselines_dic_sensi[baseline_sensi][qty_sensi])\np_sensi = figure(title=\"Sensitivity\", \n width = 1200,\n height = 850,\n x_axis_label='Change in moment or parameter',\n y_axis_label='Value',\n tools = TOOLS)\n\ncolors_sensi = itertools.cycle(Category18)\n\nfor col in baselines_dic_sensi[baseline_sensi][qty_sensi].columns[1:]:\n if col!='zeta':\n p_sensi.line(x='Change', y=col, source = ds_sensi, color=next(colors_sensi),line_width = 2, legend_label=col)\n\np_sensi.legend.click_policy=\"hide\"\np_sensi.legend.label_text_font_size = '8pt'\np_sensi.add_layout(p_sensi.legend[0], 'right')\n\ndef update_baseline_sensi(attrname, old, new):\n qty_sensi = qty_sensi_select.value\n ds_sensi.data = baselines_dic_sensi[new][qty_sensi]\n \ndef update_qty_sensi(attrname, old, new):\n baseline_sensi = baseline_sensi_select.value\n ds_sensi.data = baselines_dic_sensi[baseline_sensi][new]\n\ncontrols_sensi = row(baseline_sensi_select, qty_sensi_select)\n\nbaseline_sensi_select.on_change('value', update_baseline_sensi)\nqty_sensi_select.on_change('value', update_qty_sensi)\n\nsensitivity_report = column(controls_sensi,p_sensi)\n\n# %% weights sensitivities\n\nbaselines_dic_sensi_weights = {}\n\n# for baseline_nbr in ['101','102','104']:\nfor baseline_nbr in ['802']:\n baselines_dic_sensi_weights[baseline_nbr] = {}\n baseline_sensi_weights_path = results_path+'baseline_'+baseline_nbr+'_sensitivity_weights_tables/'\n files_in_dir = os.listdir(baseline_sensi_weights_path)\n files_in_dir = [ filename for filename in files_in_dir if filename.endswith('.csv') ]\n for f in files_in_dir:\n # if f not in ['GPDIFF.csv','GROWTH.csv']:\n baselines_dic_sensi_weights[baseline_nbr][f[:-4]] = pd.read_csv(baseline_sensi_weights_path+f,index_col = 0)\n \nbaseline_sensi_weights = '802'\nqty_sensi_weights = 'objective'\n\nbaseline_sensi_weights_select = Select(value=baseline_sensi_weights, title='Baseline', options=sorted(baselines_dic_sensi_weights.keys()))\nqty_sensi_weights_select = Select(value=qty_sensi_weights, title='Quantity', options=sorted(baselines_dic_sensi_weights[baseline_sensi_weights].keys()))\n\nds_sensi_weights = ColumnDataSource(baselines_dic_sensi_weights[baseline_sensi_weights][qty_sensi_weights])\np_sensi_weights = figure(title=\"Sensitivity to the weights\", \n width = 1200,\n height = 850,\n x_axis_label='Change in weight',\n y_axis_label='Objective function or contribution to objective function: loss(moment,target)',\n y_axis_type=\"log\",\n tools = TOOLS)\n\ncolors_sensi_weights = itertools.cycle(Category18)\n\nfor col in baselines_dic_sensi_weights[baseline_sensi_weights][qty_sensi_weights].columns[1:]:\n # if col not in ['zeta','GPDIFF_weight','GROWTH_weight']:\n p_sensi_weights.line(x='Change', y=col, source = ds_sensi_weights, color=next(colors_sensi_weights),line_width = 2, \n legend_label=col)\n\np_sensi_weights.legend.click_policy=\"hide\"\np_sensi_weights.legend.label_text_font_size = '8pt'\np_sensi_weights.add_layout(p_sensi_weights.legend[0], 'right')\n\ndef update_baseline_sensi_weights(attrname, old, new):\n qty_sensi_weights = qty_sensi_weights_select.value\n ds_sensi_weights.data = baselines_dic_sensi_weights[new][qty_sensi_weights]\n \ndef update_qty_sensi_weights(attrname, old, new):\n baseline_sensi_weights = baseline_sensi_weights_select.value\n ds_sensi_weights.data = baselines_dic_sensi_weights[baseline_sensi_weights][new]\n\ncontrols_sensi_weights = row(baseline_sensi_weights_select, qty_sensi_weights_select)\n\nbaseline_sensi_weights_select.on_change('value', update_baseline_sensi_weights)\nqty_sensi_weights_select.on_change('value', update_qty_sensi_weights)\n\nsensitivity_weights_report = column(controls_sensi_weights,p_sensi_weights)\n\n#%% Jacobian panel\n\n# baseline_jac = '1010'\n# country_jac = 'USA'\n# sector_jac = 'Patent'\n\n# # baseline_jac_select = Select(value=baseline_jac, title='Baseline', options=['501','604','607','608','609','610'])\n# baseline_jac_select = Select(value=baseline_jac, title='Baseline', options=['1010'])\n\n# baseline_jac_path = results_path+'baseline_'+baseline_jac+'_variations/'\n# files_in_dir = next(os.walk(baseline_jac_path))[1]\n# run_list = [f for f in files_in_dir if f[0].isnumeric()]\n# run_list = sorted(run_list, key=section)\n# variation_jac_select = Select(value='baseline', title='Variation', \n# options=['baseline']+run_list)\n\n# def update_list_of_runs_jac(attr, old, new):\n# baseline_jac_path = results_path+'baseline_'+new+'_variations/'\n# files_in_dir = next(os.walk(baseline_jac_path))[1]\n# run_list = [f for f in files_in_dir if f[0].isnumeric()]\n# run_list = sorted(run_list, key=section)\n# variation_jac_select.options = ['baseline']+run_list\n\n# if variation_jac_select.value == 'baseline':\n# path = results_path+baseline_jac_select.value+'/'\n# else:\n# path = results_path+'baseline_'+baseline_jac_select.value+'_variations/'+variation_jac_select.value+'/'\n \n# p_jac, m_jac, sol_jac = load(path, data_path=data_path,\n# dir_path=dir_path)\n\n# qty_jac_select = Select(value='delta', title='Parameter', options=p_jac.calib_parameters)\n# country_jac_select = Select(value='USA', title='Country', options=p_jac.countries)\n# sector_jac_select = Select(value='Patent', title='Sector', options=p_jac.sectors)\n\n# if qty_jac_select.value in ['eta','T','delta','nu']:\n# idx_to_change_jac = p_jac.countries.index(country_jac_select.value),p_jac.sectors.index(sector_jac_select.value)\n# if qty_jac_select.value in ['fe','zeta','nu', 'fo']:\n# idx_to_change_jac = 0,p_jac.sectors.index(sector_jac_select.value)\n# if qty_jac_select.value in ['k','g_0']:\n# idx_to_change_jac = 0\n\n# qty_to_change_jac = qty_jac_select.value\n\n# x_jac = compute_rough_jacobian(p_jac, m_jac, qty_to_change_jac, idx_to_change_jac, \n# change_by = 0.25, tol = 1e-14, damping = 5,\n# max_count = 5e3)\n\n# p_jac_fig = figure(title=\"Rough jacobian computation\", \n# y_range=FactorRange(factors=m_jac.get_signature_list()),\n# width = 1500,\n# height = 1200,\n# x_axis_label='Change in contribution to objective function',\n# y_axis_label='Moment',\n# tools = TOOLS) \n\n# data_jac = pd.DataFrame(columns = ['Moment','Contribution'], data=np.array([np.array(m_jac.get_signature_list()),x_jac]).T)\n# src_jac = ColumnDataSource(data_jac)\n\n# p_jac_fig.hbar(y = 'Moment',right = 'Contribution', source = src_jac)\n\n# hover_tool_jac = HoverTool()\n# hover_tool_jac.tooltips = [\n# (\"(Moment)\", \"(@Moment)\"),\n# ]\n# p_jac_fig.add_tools(hover_tool_jac)\n\n\n# def update_jac(event):\n# if variation_jac_select.value == 'baseline':\n# path = results_path+baseline_jac_select.value+'/'\n# else:\n# path = results_path+'baseline_'+baseline_jac_select.value+'_variations/'+variation_jac_select.value+'/'\n# par_jac, m_jac, sol_jac = load(path, data_path=data_path,\n# dir_path=dir_path)\n# if qty_jac_select.value in ['eta','T','delta','nu']:\n# idx_to_change_jac = par_jac.countries.index(country_jac_select.value),par_jac.sectors.index(sector_jac_select.value)\n# if qty_jac_select.value in ['fe','zeta','nu', 'fo']:\n# idx_to_change_jac = par_jac.sectors.index(sector_jac_select.value)\n# if qty_jac_select.value in ['k','g_0']:\n# idx_to_change_jac = None\n# x_jac = compute_rough_jacobian(par_jac, m_jac, qty_jac_select.value, idx_to_change_jac, \n# change_by = 0.1, tol = 1e-14, damping = 5,\n# max_count = 5e3)\n# data_jac = pd.DataFrame(columns = ['Moment','Contribution'], data=np.array([np.array(m_jac.get_signature_list()),x_jac]).T)\n# src_jac.data = data_jac\n# p_jac_fig.y_range.factors = m_jac.get_signature_list()\n\n# button_jac = Button(label=\"Compute\")\n# button_jac.on_event(ButtonClick, update_jac)\n\n# controls_jac = row(baseline_jac_select, variation_jac_select, qty_jac_select, \n# country_jac_select, sector_jac_select, button_jac)\n\n# baseline_jac_select.on_change('value', update_list_of_runs_jac)\n\n# jac_report = column(controls_jac,p_jac_fig)\n\n#!!! sixth panel\n# sixth_panel = row(sensitivity_report,sensitivity_weights_report,jac_report)\nsixth_panel = row(sensitivity_report,sensitivity_weights_report)\n\n#%% Kogan paper\n\ncolors_kog = itertools.cycle(Category18)\n\ndf_kog = pd.read_csv(data_path+'koga_updated.csv')\nds_kog = ColumnDataSource(df_kog)\n\np_kog = figure(title=\"Kogan moment updated / extrapolated\", \n width = 1200,\n height = 850,\n x_axis_label='Issue Date',\n y_axis_type=\"log\",\n tools = TOOLS) \n\nl_kog = {}\n\nfor i,col in enumerate(df_kog.columns):\n if col not in ['issue_date']:\n l_kog[i] = p_kog.line(x='issue_date', y=col, \n source = ds_kog, \n line_width = 2, legend_label=col, color=next(colors_kog),\n name = col)\n\nhover_tool_kog = HoverTool(\n tooltips = [\n (\"Issue date\", \"$x\"),\n ('ValuePerPatent', '@ValuePerPatent'),\n ('CostPerPatent', '@CostPerPatent'),\n ('KM_article', '@KM_article'),\n ('ValuePerPatentUpdated', '@ValuePerPatentUpdated'),\n ('CostPerPatentExtrapolated', '@CostPerPatentExtrapolated'),\n ('KM_extrapolatedCost', '@KM_extrapolatedCost')\n ],\n mode='vline',\n renderers = [l_kog[4]]\n)\np_kog.add_tools(hover_tool_kog)\n\np_kog.legend.click_policy=\"hide\"\np_kog.legend.label_text_font_size = '8pt'\np_kog.add_layout(p_kog.legend[0], 'right')\n\n\n# colors_kog2 = itertools.cycle(Category18)\n\n# df_kog2 = pd.read_csv(data_path+'KM_prior.csv')\n# ds_kog2 = ColumnDataSource(df_kog2)\n\n# p_kog2 = figure(title=\"Kogan moment\", \n# width = 1200,\n# height = 850,\n# x_axis_label='Market Prior',\n# tools = TOOLS) \n\n# l_kog2 = {}\n\n# for i,col in enumerate(df_kog2.columns):\n# if col not in ['market prior']:\n# l_kog2[i] = p_kog2.line(x='market prior', y=col, \n# source = ds_kog2, \n# line_width = 2, legend_label=col, color=next(colors_kog2))\n\n# hover_tool_kog2 = HoverTool(\n# tooltips = [\n# (\"market prior\", \"$x\"),\n# ('1950 to 2007', '@from1950to2007'),\n# ('1980 to 2007', '@from1980to2007'),\n# ('1995 to 2007', '@from1995to2007'),\n# ('2002 to 2007', '@from2002to2007'),\n# ('1950 to 2020', '@from1950to2020'),\n# ('1980 to 2020', '@from1980to2020'),\n# ('1995 to 2020', '@from1995to2020'),\n# ('2002 to 2020', '@from2002to2020'),\n# ],\n# mode='vline',\n# renderers = [l_kog2[4]]\n# )\n\n# p_kog2.legend.click_policy=\"hide\"\n# p_kog2.legend.label_text_font_size = '8pt'\n# p_kog2.add_layout(p_kog2.legend[0], 'right')\n# p_kog2.add_tools(hover_tool_kog2)\n\n\ncolors_to_data = itertools.cycle(Category18)\n\ndf_to_data = pd.read_csv(data_path+'turnover_imports_weighted_11_countries.csv'\n )[['year','HS_digits','A3']].pivot(\n columns= 'HS_digits',\n index = 'year',\n values = 'A3'\n )[[6,8,10]]\ndf_to_data = df_to_data.rename(columns={6:'6',\n 8:'8',\n 10:'10'})\nds_to_data = ColumnDataSource(df_to_data)\n\np_to_data = figure(title=\"Turnover moment for rule A3, time window (y,y+5)\", \n width = 1200,\n height = 850,\n x_axis_label='Year',\n # y_axis_type=\"log\",\n tools = TOOLS) \n\nl_to_data = {}\n\nfor i,col in enumerate(['6','8','10']):\n if col not in ['year']:\n l_to_data[i] = p_to_data.line(x='year', y=col, \n source = ds_to_data, \n line_width = 2, legend_label=col, color=next(colors_to_data),\n name = col)\n\nhover_tool_to_data = HoverTool(\n tooltips = [\n (\"Year\", \"$x\"),\n ('HS6', '@6'),\n ('HS8', '@8'),\n ('HS10', '@10'),\n ],\n mode='vline',\n renderers = [l_to_data[1]]\n)\np_to_data.add_tools(hover_tool_to_data)\n\np_to_data.legend.click_policy=\"hide\"\np_to_data.legend.label_text_font_size = '8pt'\np_to_data.add_layout(p_to_data.legend[0], 'right')\n\n#!!! seventh_panel\n# seventh_panel = row(p_kog,p_kog2)\nseventh_panel = row(p_kog,p_to_data)\n\n#%% 7 countries comparison of patent flows data\n\n# # labels_leg_patstat = {\n# # 'baseline':'pre IN treatment',\n# # 'calibration data':'calibration data',\n# # 'WIPO data':'WIPO data',\n# # 'alternative 1':'alt 1 : no sector filtering',\n# # 'alternative 2':'alt 2 : first applicant only',\n# # 'alternative 3':'alt 3 : diff origin weight',\n# # 'alternative 4':'alt 4 : no domestic allocation',\n# # 'alternative 5':'alt 5 : only granted patents',\n# # 'alternative 6':'alt 6 : no ML predi for EPO',\n# # 'alternative 7':'alt 7 : with ML predi for WIPO',\n# # 'after IN treatment':'baseline',\n# # 'julian latest code':'julian latest code',\n# # }\n# # tot = pd.read_csv(join(dirname(__file__),'patstat_compar.csv')).set_index(\n# # ['destination_code','origin_code']\n# # ).sort_index(\n# # ).round()\n\n# # ds_patstat = ColumnDataSource(tot)\n# # # TOOLS=\"pan,wheel_zoom,box_zoom,reset,save\"\n# # p_patstat = figure(title=\"Patent flows\", \n# # width = 1200,\n# # height = 850,\n# # x_axis_type=\"log\",\n# # y_axis_type=\"log\",\n# # x_axis_label='Baseline', \n# # # y_axis_label='Model implied',\n# # tools = TOOLS)\n# # hover_tool = HoverTool()\n# # hover_tool.tooltips = [\n# # (\"index\", \"@x\"),\n# # (\"(baseline,alternative)\", \"($x,$y)\"),\n# # ]\n# # # labels_patstat = LabelSet(x='calibration data', y='baseline', text='x',\n# # labels_patstat = LabelSet(y='WIPO data', x='after IN treatment', text='x',\n# # x_offset=2, y_offset=2, source=ds_patstat, text_font_size=\"7pt\")\n# # p_patstat.add_layout(labels_patstat)\n# # p_patstat.add_tools(hover_tool)\n\n# # slope_patstat = Slope(gradient=1, y_intercept=0,\n# # line_color='black', line_dash='dashed', line_width=1)\n# # p_patstat.add_layout(slope_patstat)\n# # lines_patstat = {}\n# # colors_patstat = itertools.cycle(Category18)\n# # for i,col in enumerate(tot.columns):\n# # if col not in ['x','after IN treatment']:\n# # # lines_patstat[col] = p_patstat.circle('calibration data', col, \n# # lines_patstat[col] = p_patstat.circle('after IN treatment', col, \n# # source = ds_patstat, \n# # size=5, color=next(colors_patstat))\n# # if col != 'WIPO data':\n# # lines_patstat[col].visible = False\n \n# # legend_items = [LegendItem(label=labels_leg_patstat[col], renderers=[lin_par])\n# # for col, lin_par in lines_patstat.items() if col not in \n# # # ['x','calibration data']]\n# # ['x','after IN treatment']]\n\n# # legend = Legend(items=legend_items, click_policy=\"hide\", \n# # label_text_font_size=\"8pt\",\n# # spacing = 0, \n# # )\n# # p_patstat.add_layout(legend, 'right')\n\n# # columns_patstat = [\n# # TableColumn(field=\"x\"),\n# # ]+[TableColumn(field=col) for col in tot.columns]\n# # data_table_patstat = DataTable(source=ds_patstat, columns = columns_patstat, width=1200, height=400)\n\n# # #%% 13 countries comparison of patent flows data\n\n# # tot_13 = pd.read_csv(join(dirname(__file__),'patstat_compar_13.csv')).set_index(\n# # ['destination_code','origin_code']\n# # ).sort_index(\n# # ).round()\n\n# # ds_patstat_13 = ColumnDataSource(tot_13)\n# # # TOOLS=\"pan,wheel_zoom,box_zoom,reset,save\"\n# # p_patstat_13 = figure(title=\"Patent flows\", \n# # width = 1200,\n# # height = 850,\n# # x_axis_type=\"log\",\n# # y_axis_type=\"log\",\n# # x_axis_label='Baseline', \n# # # y_axis_label='Model implied',\n# # tools = TOOLS)\n# # hover_tool = HoverTool()\n# # hover_tool.tooltips = [\n# # (\"index\", \"@x\"),\n# # (\"(baseline,alternative)\", \"($x,$y)\"),\n# # ]\n# # # labels_patstat = LabelSet(x='calibration data', y='baseline', text='x',\n# # labels_patstat_13 = LabelSet(y='WIPO data', x='baseline', text='x',\n# # x_offset=2, y_offset=2, source=ds_patstat_13, text_font_size=\"7pt\")\n# # p_patstat_13.add_layout(labels_patstat_13)\n# # p_patstat_13.add_tools(hover_tool)\n\n# # slope_patstat_13 = Slope(gradient=1, y_intercept=0,\n# # line_color='black', line_dash='dashed', line_width=1)\n# # p_patstat_13.add_layout(slope_patstat_13)\n# # lines_patstat_13 = {}\n# # colors_patstat_13 = itertools.cycle(Category18)\n# # for i,col in enumerate(tot_13.columns):\n# # if col not in ['x','baseline']:\n# # # lines_patstat[col] = p_patstat.circle('calibration data', col, \n# # lines_patstat_13[col] = p_patstat_13.circle('baseline', col, \n# # source = ds_patstat_13, \n# # size=5, color=next(colors_patstat_13))\n# # legend_items_13 = [LegendItem(label=labels_leg_patstat[col], renderers=[lin_par])\n# # for col, lin_par in lines_patstat_13.items() if col not in \n# # # ['x','calibration data']]\n# # ['x','baseline']]\n\n# # legend_13 = Legend(items=legend_items_13, click_policy=\"hide\", \n# # label_text_font_size=\"8pt\",\n# # spacing = 0, \n# # )\n# # p_patstat_13.add_layout(legend_13, 'right')\n\n# # columns_patstat_13 = [\n# # TableColumn(field=\"x\"),\n# # ]+[TableColumn(field=col) for col in tot_13.columns]\n# # data_table_patstat_13 = DataTable(source=ds_patstat_13, columns = columns_patstat_13, width=1200, height=400)\n\n\n#!!! eigth_panel\n# # eigth_panel = row(column(p_patstat,data_table_patstat),\n# # column(p_patstat_13,data_table_patstat_13))\n\n#%% build curdoc\nprint(time.perf_counter() - start)\ncurdoc().add_root(column(\n first_panel, \n second_panel, \n third_panel, \n fourth_panel, \n fifth_panel, \n sixth_panel,\n seventh_panel,\n # eigth_panel\n )\n )\n","repo_name":"todortodor/pyTRIPS","sub_path":"bokeh-app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":133340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"71597706806","text":"import random\r\n\r\nimport vk_api\r\nfrom vk_api.longpoll import VkLongPoll, VkEventType\r\n\r\nimport secret_constants\r\nfrom cites import Lobby\r\nfrom cities_list import cities_list\r\n\r\nvk_session = vk_api.VkApi(token=secret_constants.TOKEN)\r\nlongpoll = VkLongPoll(vk_session)\r\n\r\n\r\ndef is_message(event):\r\n return event.type == VkEventType.MESSAGE_NEW and event.to_me\r\n\r\n\r\ndef send_message(user_id, message):\r\n vk_session.method('messages.send', {'user_id': user_id,\r\n 'message': message,\r\n 'random_id': 0})\r\n\r\n\r\ndef is_start_game(event):\r\n start_commands = ['game', 'Города', 'Игра', 'игра',\r\n 'Играть', 'Играть', 'города Играть', 'Играть в города', 'играть в города']\r\n return event.text.lower() in start_commands\r\n\r\n\r\ndef main():\r\n menuBot = ['commands:''\\nКак дела?', '\\nВ чём сила?', '\\nИграть в города']\r\n convertmenuBot = ' '.join(map(str, menuBot))\r\n players_queue = None\r\n lobbies = []\r\n users_in_game = []\r\n\r\n dela = ['дела по БОТовски', 'Питоновские , а у тебя?', 'print(normalno)',\r\n 'нормас(пивас)', 'дела словно dead inside... ', 'Нормально)']\r\n\r\n VoprosDela = ['Как дела', 'Как дела?', 'как дела', 'Чо каво?', 'как дела?', 'd', 'как дела клатчер',\r\n 'Как дела клатчер?']\r\n\r\n for event in longpoll.listen():\r\n if is_message(event):\r\n if event.text == 'привет':\r\n send_message(event.user_id, 'привет! Для функций бота напиши /menu')\r\n\r\n elif event.text == '/menu':\r\n send_message(event.user_id, convertmenuBot)\r\n\r\n elif event.text == 'в чём сила?':\r\n send_message(event.user_id, 'В правде ,кто прав тот и сильней.')\r\n\r\n elif event.text in VoprosDela:\r\n OtvetDela = random.choice(dela)\r\n send_message(event.user_id, OtvetDela)\r\n\r\n\r\n elif is_start_game(event):\r\n if players_queue is None:\r\n send_message(event.user_id, 'Ищем соперника!')\r\n players_queue = event.user_id\r\n elif event.user_id != players_queue:\r\n user1 = players_queue\r\n user2 = event.user_id\r\n lobbies.append(Lobby(user1, user2))\r\n users_in_game.extend((user1, user2))\r\n players_queue = None\r\n send_message(user1, 'Игра началась!')\r\n send_message(user2, 'Игра началась!')\r\n send_message(lobbies[-1].get_active_player(), 'Вы ходите первым.Назовите город на любую букву!')\r\n elif event.user_id in users_in_game:\r\n city = event.text.lower()\r\n lobby = find_lobby(lobbies, event.user_id)\r\n if city not in cities_list:\r\n send_message(event.user_id, 'Такого города нет, либо ��ыла опечатка. \\n'\r\n 'Ты проиграл. ')\r\n send_message(lobby.get_inactive_player_id(), 'вы победили')\r\n users_in_game.remove(event.user_id)\r\n users_in_game.remove(lobby.get_inactive_player_id())\r\n lobbies.remove(lobby)\r\n continue\r\n if not lobby.is_correct_letter(city[0].lower):\r\n send_message(event.user_id, 'Не та буква, географию рано, купи букварь!')\r\n continue\r\n if lobby.get_activez_player_id() != event.user_id:\r\n send_message(event.user_id, 'сейчас не твой ход!')\r\n continue\r\n\r\n lobby.change_last_letter(city)\r\n lobby.used_cities.append(city)\r\n lobby.change_current_turn()\r\n send_message(lobby.get_active_player(), f'вам на букву: {lobby.last_letter}.\\n'\r\n f'игрок назвал город:{city}')\r\n\r\n\r\ndef find_lobby(lobbies, user_id):\r\n for lobby in lobbies:\r\n if user_id in lobby.user_ids:\r\n return lobby\r\n\r\n\r\nmain()\r\n","repo_name":"KKholin/vk_bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4698,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"38728098813","text":"import sys\nfrom dataclasses import asdict\nfrom pathlib import Path\nfrom typing import List\n\nfrom pandas import DataFrame\n\nfrom src.car_racing import CustomRacing\nfrom src.ppo import PPONetwork, perform_ppo_learning, get_ppo_data, PPOMetadata\n\n# Initialize\nweights_path: Path = Path() / \"data\" / \"results\"\nweights_folder: Path = weights_path / sys.argv[1]\nweights_folder.mkdir(parents=True, exist_ok=True)\nmetadata_path: Path = Path() / \"data\" / \"metadata\"\nnetwork = PPONetwork(weights_folder)\nassert sys.argv[2] == \"-t\" or sys.argv[2] == \"-i\" or sys.argv[2] == \"-d\"\nepisode: int = int(sys.argv[3])\ncar_racing: CustomRacing = CustomRacing(episode)\n \n# Training Mode\nif sys.argv[2] == \"-t\":\n if episode > 0:\n network.load_model(episode)\n perform_ppo_learning(car_racing, network, True)\n \n# Inference Mode\nelif sys.argv[2] == \"-i\":\n network.load_model(episode)\n perform_ppo_learning(car_racing, network, False)\n \n# Collect Metadata Mode (for plots)\nelif sys.argv[2] == \"-d\":\n metadata: List[PPOMetadata] = get_ppo_data(car_racing, network)\n as_dataframe: DataFrame = DataFrame([asdict(data) for data in metadata])\n as_dataframe.to_csv(metadata_path / \"ppo.csv\")\n\n\n\n","repo_name":"linuslh1996/car-racing-unimore","sub_path":"train_ppo.py","file_name":"train_ppo.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"33692682293","text":"import sqlite3\n\n\ndef one_animal(itemid):\n with sqlite3.connect('animal.db') as connection:\n cursor = connection.cursor()\n query = \"\"\"\n SELECT new_animals_table.name_id, new_animals_table.name, animal_type.animal_type, breed.breed,\n colors.colors, new_animals_table.date_of_birth, outcome_type.outcome_type, outcome_month.outcome_month,\n outcome_year.outcome_year\n FROM new_animals_table\n JOIN animal_color ON animal_color.animals_id = new_animals_table.name_id\n JOIN colors ON colors.colors_id = animal_color.color_id\n INNER JOIN animal_type ON new_animals_table.animal_type_id = animal_type.animal_type_id\n INNER JOIN breed ON new_animals_table.breed_id = breed.breed_id\n INNER JOIN outcome_type ON new_animals_table.outcome_type_id = outcome_type.outcome_type_id\n INNER JOIN outcome_month ON new_animals_table.outcome_month_id = outcome_month.outcome_month_id\n INNER JOIN outcome_year ON new_animals_table.outcome_year_id = outcome_year.outcome_year_id\n WHERE new_animals_table.name_id = ?\n \"\"\"\n cursor.execute(query, (itemid,))\n executed_query = cursor.fetchall()\n results = executed_query\n\n if len(results) == 1:\n animal = {'name': results[0][1],\n 'animal_type': results[0][2],\n 'breed': results[0][3],\n 'color1': results[0][4],\n 'date_of_birth': results[0][5],\n 'outcome_type': results[0][6],\n 'outcome_mounth': results[0][7],\n 'outcome_year': results[0][8]\n }\n return animal\n else:\n\n animal = {'name': results[0][1],\n 'animal_type': results[0][2],\n 'breed': results[0][3],\n 'color1': results[0][4],\n 'color2': results[1][4],\n 'date_of_birth': results[0][5],\n 'outcome_type': results[0][6],\n 'outcome_mounth': results[0][7],\n 'outcome_year': results[0][8]\n }\n return animal\n\n\n\n","repo_name":"K-Maxim/hw15","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"72100990006","text":"import sys\nfrom wit import Wit\nimport os\n\naccess_token = os.environ.get('WIT_TOKEN')\n\n# Quickstart example\n# See https://wit.ai/ar7hur/Quickstart\n\ndef first_entity_value(entities, entity):\n if entity not in entities:\n return None\n val = entities[entity][0]['value']\n if not val:\n return None\n return val['value'] if isinstance(val, dict) else val\n\ndef send(request, response):\n print(response['text'])\n\ndef get_forecast(request):\n context = request['context']\n entities = request['entities']\n\n loc = first_entity_value(entities, 'location')\n if loc:\n context['forecast'] = 'sunny'\n else:\n context['missingLocation'] = True\n if context.get('forecast') is not None:\n del context['forecast']\n\n return context\n\nactions = {\n 'send': send,\n 'getForecast': get_forecast,\n}\n\nclient = Wit(access_token=access_token, actions=actions)\nclient.interactive()\n","repo_name":"BCCN-Prog/weather_2016","sub_path":"bot/weather_example.py","file_name":"weather_example.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"76"} +{"seq_id":"27421243262","text":"from ArgStrat.powerset import powerset\nimport random\nimport sys\n\n\n\nclass ClosureFunction:\t# Closure function object\n\n\trules = {}\n\n\tdef __init__(self,rules=[]):\n\t\tself.rules = {}\n\n\t\tfor r in rules:\n\t\t\tself.add_rule(r[0],r[1])\n\n\tdef __repr__(self):\n\t\treturn str(self.rules)\n\n\tdef add_rule(self,body,head):\n\t\t# incorporate rule into closure operator\n\t\tself.rules[tuple(set(body))] = set(head)\n\n\tdef all_inferences(self):\n\t\t# returns all possible inferences\n\t\tinf = set([])\n\t\tfor body in self.rules:\n\t\t\tinf |= self.rules[body]\n\t\treturn inf\n\n\tdef get(self,X):\n\t\t# get closure of X\n\t\tY = set(X)\n\t\tfor body in self.rules:\n\t\t\tif set(body).issubset(Y):\n\t\t\t\tY |= self.rules[body]\n\t\n\t\tif Y == X:\n\t\t\treturn X\n\t\telse:\n\t\t\treturn self.get(Y)\n\nclass Agent: \n\tK = set([])\n\tmu = ClosureFunction()\n\n\tdef __init__(self,K,mu=None):\n\t\tself.K = set(K)\n\t\tif mu:\n\t\t\tself.mu = mu\n\t\telse:\n\t\t\tself.mu = ClosureFunction()\n\n\tdef __repr__(self):\n\t\treturn str((list(self.K),self.mu))\n\n\tdef getClosure(self):\n\t\treturn self.mu\n\n\tdef getKnowledge(self):\n\t\treturn self.K\n\n\tdef getArgs(self):\n\t\treturn self.K\n\n\nclass OpponentModel:\n\tmodel = {}\n\tmodel_size = 0\n\tID = None\n\n\tdef __init__(self):\n\t\tself.model = {}\n\t\tself.size = 0\n\t\tself.ID = None\n\n\tdef __repr__(self):\n\t\treturn str(dict([(X,round(self.model[X],2)) for X in self.model]))\n\n\tdef addID(self,ID):\n\t\tself.ID = str(ID)\n\n\tdef get_seed(self):\n\t\treturn self.ID\n\n\tdef totalProbability(self):\n\t\ttotal_prob = 0\n\t\tfor Opp in self.model:\n\t\t\ttotal_prob += self.model[Opp]\n\t\treturn total_prob\n\n\n\tdef getArgs(self):\n\t\targs = set([])\n\t\tfor Opp in self.model:\n\t\t\tinf = Opp.getClosure().all_inferences()\n\t\t\targs |= Opp.getArgs()\n\t\t\targs |= inf\n\t\treturn args\n\n\tdef getID(self,Opp):\n\t\tif Opp not in self.model:\n\t\t\treturn 0\n\t\telse:\n\t\t\treturn self.model.keys().index(Opp)\n\n\n\tdef getModels(self):\n\t\treturn sorted(self.model.keys())\n\n\tdef __len__(self):\n\t\treturn self.model_size\n\n\tdef probability(self,Opp):\n\t\tif not Opp in self.model:\n\t\t\treturn 0\n\t\telse:\n\t\t\treturn self.model[Opp]\n\n\tdef add_model(self,Opp,p):\n\t\tif not Opp in self.model:\n\t\t\tself.model[Opp] = p\n\t\t\tself.model_size += 1\n\t\telse:\n\t\t\tself.model[Opp] = p\n\n\tdef standardise(self,accuracy=2):\n\t\t# make all probabilities integers\n\t\tself.normalise()\n\t\tfactor = 10**accuracy\n\n\t\tfor Opp in self.model:\n\t\t\tself.model[Opp] = int(round(self.model[Opp]*factor,0))\n\n\tdef normalise(self):\n\t\t# normalise total probability to 1\n\t\ttotal_prob = self.totalProbability()\n\n\t\tfor Opp in self.model:\n\t\t\tself.model[Opp] = float(self.model[Opp])/total_prob\n\n\n\n\ndef getUniformModel(Args,size,seed=None): # generates a random uniform opponent model of given size\n\tM = OpponentModel()\n\n\tall_models = powerset(Args)\n\n\t# get random seed:\n\tif not seed:\n\t\tseed = random.randint(0,sys.maxint)\n\n\tM.addID(seed)\n\trandom.seed(seed)\n\n\tif size > len(all_models) or size==None:\n\t\tselection = all_models\n\telse:\n\t\tselection = random.sample(all_models,size)\n\n\ti = 0\n\tfor K in selection:\n\t\tOpp = Agent(K)\n\t\tM.add_model(Opp,1)\n\t\ti += 1\n\n\t#M.normalise()\n\treturn M\n\n\ndef getUniformModelwithClosure(Args,size,seed=None,K_prop=[],closure_size=1): # generates a random uniform opponent model of given size\n\tM = OpponentModel()\n\n\tall_models = powerset(Args)\n\n\t# get random seed:\n\tif not seed:\n\t\tseed = random.randint(0,sys.maxint)\n\n\tM.addID(seed)\n\trandom.seed(seed)\n\n\tif size > len(all_models) or size==None:\n\t\tselection = all_models\n\telse:\n\t\tselection = random.sample(all_models,size)\n\n\tmu = getRandomClosure(K_prop,Args,size=closure_size)\n\ti = 0\n\tfor K in selection:\t\n\t\tOpp = Agent(K,mu)\n\t\tM.add_model(Opp,1)\n\t\ti += 1\n\n\t#M.normalise()\n\treturn M\n\n\ndef getRandomClosure(A,B,size=0):\n\trules = []\n\tfor i in range(size):\n\t\ttry:\n\t\t\tbody = [random.choice(A)]\n\t\t\thead = [random.choice(B)]\n\t\t\trules += [(body,head)]\n\t\texcept:\n\t\t\trules += []\n\n\treturn ClosureFunction(rules)\n","repo_name":"christopher-hampson/argstrat","sub_path":"ArgStrat/agent_models.py","file_name":"agent_models.py","file_ext":"py","file_size_in_byte":3780,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"1632291340","text":"import csv\nfrom flask import Flask\nfrom flask import abort\n# this is telling it to go to folder flask and import tool Flask\nfrom flask import render_template\napp = Flask(__name__)\n\ndef fetch_csv(csv_path):\n\tcsv_file = open(csv_path, \"rb\")\n\tcsv_obj = csv.DictReader(csv_file)\n\t\t# returns a dictionary (headers)\n\tcsv_list = list(csv_obj)\n\treturn csv_list\n\n\n@app.route(\"/\")\ndef index():\n\ttemplate = \"index.html\"\n\tobject_list = fetch_csv(\"./static/la-riots-deaths.csv\")\n\t\t#the list of data returned by the csv\n\treturn render_template(template, object_list=object_list)\n\n@app.route(\"//\")\ndef detail(row_id):\n\ttemplate = 'detail.html'\n\tobject_list = fetch_csv(\"./static/la-riots-deaths.csv\")\n\tfor row in object_list: \n\t\tif row['id'] == row_id:\n\t\t\treturn render_template(template, object=row)\n\tabort(404)\n\nif __name__ == \"__main__\":\n # Fire up the Flask test server\n app.run(debug=True, use_reloader=True)\n # If this thing is being booted up from the terminal, run this thing.\n # This will give us a barebones web server to work with.\n # The colon is super important!","repo_name":"amberjrivera/first-news-app","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"31700877167","text":"xmini = -10\nxmaxi = 10\nm_d_g = \"7*x + 2\"\nm_d_d =\" 6*x - 5\"\ndifference=10\nwhile abs(difference) > 0.00001:\n x0 = (xmaxi+xmini)/2\n x=x0\n d = eval(m_d_g) - eval(m_d_d)\n x = xmini\n d0 = eval(m_d_g) - eval(m_d_d)\n x=xmaxi\n d1 = eval(m_d_g) - eval(m_d_d)\n if d*d1<0:\n xmini = x0\n difference = (d+d1)/2\n print((x0+xmaxi)/2, difference)\n else:\n xmaxi = x0\n difference = (d+d0)/2\n print((x0+xmini)/2, difference)\n","repo_name":"oultetman/lycee","sub_path":"dicotomie.py","file_name":"dicotomie.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"34993480350","text":"#########################################################################################\n# gabrielgarza / openai-gym-policy-gradient \n# policy_gradient.py\n## Adolfo's Notes: Policy Update\n## R = discounted_episode_rewards_norm\n## H(logits, labels) = softmax_cross_entropy_with_logits(logits=logits, labels=labels)\n## H(logits, labels) = - summation{ labels * log(logits) }\n## loss = mean{ H(logits, labels) * R }\n### line 159\nwith tf.name_scope('loss'):\n neg_log_prob = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=labels)\n loss = tf.reduce_mean(neg_log_prob * self.discounted_episode_rewards_norm) # reward guided loss\n\nwith tf.name_scope('train'):\n self.train_op = tf.train.AdamOptimizer(self.lr).minimize(loss)\n\n#########################################################################################\n# dennybritz / reinforcement-learning / PolicyGradient\n# CliffWalk REINFORCE with Baseline Solution.ipynb\n## Adolfo's Notes: Policy Update\n## R = self.target\n## p(a) = probability of doing action a\n## loss = -log(p(a)) * R\n## Simplest out of three; No Baseline\n### window 9\nself.action_probs = tf.squeeze(tf.nn.softmax(self.output_layer))\nself.picked_action_prob = tf.gather(self.action_probs, self.action)\n\n# Loss and train op\nself.loss = -tf.log(self.picked_action_prob) * self.target\n\nself.optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)\nself.train_op = self.optimizer.minimize(\n self.loss, global_step=tf.contrib.framework.get_global_step())\n\n# Calculate the loss\nself.losses = tf.squared_difference(self.y_pl, self.action_predictions)\nself.loss = tf.reduce_mean(self.losses)\n\n# Optimizer Parameters from original paper\nself.optimizer = tf.train.RMSPropOptimizer(0.00025, 0.99, 0.0, 1e-6)\nself.train_op = self.optimizer.minimize(self.loss, global_step=tf.contrib.framework.get_global_step())\n\n########################################\n# window 10\nself.value_estimate = tf.squeeze(self.output_layer)\nself.loss = tf.squared_difference(self.value_estimate, self.target)\n\nself.optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)\nself.train_op = self.optimizer.minimize(\nself.loss, global_step=tf.contrib.framework.get_global_step())\n\n#########################################################################################\n# Ashboy64 / rl-reimplementations\n## Adolfo's Notes: Policy Update\n## advantage * e^(log(p(i)) + log(p(i-1)))\n## Uses a baseline to reduce variance; \n## Uses a past policy network similar to DQN\n## Uses ideas from http://rll.berkeley.edu/deeprlcoursesp17/docs/lec2.pdf\n## Specifically slides 17, 18\n### line 32\n# critic\nself.value = self.build_critic()\nself.advantage = self.dicounted_rewards_placeholder - self.value\nself.closs = tf.reduce_mean(tf.square(self.advantage))\nself.ctrain_op = tf.train.AdamOptimizer(self.c_lr).minimize(self.closs)\n\n# actor\npi, pi_params = self.build_policy('pi', trainable=True)\noldpi, oldpi_params = self.build_policy('oldpi', trainable=False)\nwith tf.variable_scope('sample_action'):\n self.sample_op = tf.squeeze(pi.sample(), axis=0)\nwith tf.variable_scope('update_oldpi'):\n self.update_oldpi_op = [oldp.assign(p) for p, oldp in zip(pi_params, oldpi_params)]\n\nwith tf.variable_scope('loss'):\n with tf.variable_scope('surrogate'):\n ratio = tf.exp(pi.logp(self.actions_placeholder) - oldpi.logp(self.actions_placeholder))\n surr = ratio * self.advantages_placeholder\n self.aloss = -tf.reduce_mean(surr)\n\nwith tf.variable_scope('atrain'):\n self.atrain_op = tf.train.AdamOptimizer(self.a_lr).minimize(self.aloss)","repo_name":"adolfogonzalez3/comparison_pg","sub_path":"building_training_op.py","file_name":"building_training_op.py","file_ext":"py","file_size_in_byte":3556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"2605345038","text":"from flask import Flask, jsonify\nfrom flask_restplus import Resource, Api\nfrom apis.fortify.FortifyPushFPR import fortify_push_fpr\n\napp = Flask(__name__)\n\napp.register_blueprint(fortify_push_fpr)\napi = Api(app)\n\n\n@api.route('/hello')\nclass HelloWorld(Resource):\n def get(self):\n return 'foritfy-app from dr-octopus'\n\n\nif __name__ == '__main__':\n app.run(debug = True, host = '0.0.0.0')\n","repo_name":"cihatyildiz/vm-scripts","sub_path":"dr-octo/dr-octo/fortify_app.py","file_name":"fortify_app.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"24939960360","text":"import fnmatch\nimport os\nfrom typing import Union, Tuple, List, Optional, MutableMapping, Any\nimport pygeoutils as geoutils\nimport async_retriever as ar\nimport py3dep\nfrom pydaymet import InvalidInputRange\nfrom pydaymet.core import Daymet, _check_requirements\nfrom pydaymet.pydaymet import _gridded_urls, _xarray_geomask\nfrom shapely.geometry import MultiPolygon, Polygon\nimport rasterio.features as rio_features\nimport io\nimport xarray as xr\nimport numpy as np\nimport pandas as pd\nfrom catchmentforcings.pet.pet4daymet import priestley_taylor, pm_fao56\nfrom catchmentforcings.utils.hydro_utils import t_range_days\n\nDEF_CRS = \"epsg:4326\"\n\n\ndef download_daymet_by_geom_bound(\n geometry: Union[Polygon, MultiPolygon, Tuple[float, float, float, float]],\n dates: Union[Tuple[str, str], Union[int, List[int]]],\n crs: str = DEF_CRS,\n variables: Optional[List[str]] = None,\n region: str = \"na\",\n time_scale: str = \"daily\",\n boundary: bool = True,\n) -> xr.Dataset:\n \"\"\"\n Get gridded data from the Daymet database at 1-km resolution in the boundary of the \"geometry\"\n\n if the error occurred: sqlite3.DatabaseError: database disk image is malformed,\n please delete the cache in the current directory of the performing script\n\n Parameters\n ----------\n geometry\n The geometry of the region of interest.\n dates\n Start and end dates as a tuple (start, end) or a list of years [2001, 2010, ...].\n crs\n The CRS of the input geometry, defaults to epsg:4326.\n variables\n List of variables to be downloaded. The acceptable variables are:\n ``tmin``, ``tmax``, ``prcp``, ``srad``, ``vp``, ``swe``, ``dayl``\n Descriptions can be found `here `__.\n region\n Region in the US, defaults to na. Acceptable values are:\n * na: Continental North America\n * hi: Hawaii\n * pr: Puerto Rico\n time_scale\n Data time scale which can be daily, monthly (monthly average),\n or annual (annual average). Defaults to daily.\n boundary\n if boundary is true, we will use the box of bounds as the geometry mask;\n otherwise, return downloaded data acccording to urls directly\n\n Returns\n -------\n xr.Dataset\n Daily climate data within a geometry's boundary\n\n Raises\n -------\n ValueError\n when downloading failed, raise a ValueError\n\n \"\"\"\n\n daymet = Daymet(variables, time_scale=time_scale, region=region)\n daymet.check_dates(dates)\n\n if isinstance(dates, tuple):\n dates_itr = daymet.dates_tolist(dates)\n else:\n dates_itr = daymet.years_tolist(dates)\n # transform the crs\n _geometry = geoutils.pygeoutils._geo2polygon(geometry, crs, DEF_CRS)\n\n if not _geometry.intersects(daymet.region_bbox[region]):\n raise InvalidInputRange(daymet.invalid_bbox_msg)\n\n urls, kwds = zip(\n *_gridded_urls(\n daymet.time_codes[time_scale],\n _geometry.bounds,\n daymet.region,\n daymet.variables,\n dates_itr,\n )\n )\n\n try:\n clm = xr.open_mfdataset(\n (\n io.BytesIO(r)\n for r in ar.retrieve(urls, \"binary\", request_kwds=kwds, max_workers=8)\n ),\n engine=\"scipy\",\n coords=\"minimal\",\n )\n except ValueError:\n msg = (\n \"The server did NOT process your request successfully. \"\n + \"Check your inputs and try again.\"\n )\n raise ValueError(msg)\n\n for k, v in daymet.units.items():\n if k in clm.variables:\n clm[k].attrs[\"units\"] = v\n\n clm = clm.drop_vars([\"lambert_conformal_conic\"])\n # daymet's crs comes from: https://daymet.ornl.gov/overview\n daymet_crs = \" \".join(\n [\n \"+proj=lcc\",\n \"+lat_1=25\",\n \"+lat_2=60\",\n \"+lat_0=42.5\",\n \"+lon_0=-100\",\n \"+x_0=0\",\n \"+y_0=0\",\n \"+ellps=WGS84\",\n \"+units=km\",\n \"+no_defs\",\n ]\n )\n clm.attrs[\"crs\"] = daymet_crs\n clm.attrs[\"nodatavals\"] = (0.0,)\n transform, _, _ = geoutils.pygeoutils._get_transform(clm, (\"y\", \"x\"))\n clm.attrs[\"transform\"] = transform\n clm.attrs[\"res\"] = (transform.a, transform.e)\n\n if isinstance(clm, xr.Dataset):\n for v in clm:\n clm[v].attrs[\"crs\"] = crs\n clm[v].attrs[\"nodatavals\"] = (0.0,)\n if boundary:\n return _xarray_geomask(clm, geometry.bounds, crs)\n else:\n return clm\n\n\ndef calculate_basin_grids_pet(\n clm_ds: xr.Dataset, pet_method: Union[str, list] = \"priestley_taylor\"\n) -> xr.Dataset:\n \"\"\"\n Compute Potential EvapoTranspiration using Daymet dataset.\n\n Parameters\n ----------\n clm_ds\n The dataset should include the following variables:\n `tmin``, ``tmax``, ``lat``, ``lon``, ``vp``, ``srad``, ``dayl``\n pet_method\n now support priestley_taylor and fao56\n\n Returns\n -------\n xr.Dataset\n The input dataset with an additional variable called ``pet``.\n\n \"\"\"\n\n if type(pet_method) is str:\n pet_method = [pet_method]\n assert np.sort(pet_method) in np.sort([\"priestley_taylor\", \"pm_fao56\"])\n\n keys = list(clm_ds.keys())\n reqs = [\"tmin\", \"tmax\", \"lat\", \"vp\", \"srad\", \"dayl\"]\n # units: °C, °C, °, Pa, W/m^2, seconds\n _check_requirements(reqs, keys)\n dtype = clm_ds.tmin.dtype\n dates = clm_ds[\"time\"]\n # km -> m\n res = clm_ds.res[0] * 1.0e3\n elev = py3dep.elevation_bygrid(clm_ds.x.values, clm_ds.y.values, clm_ds.crs, res)\n attrs = clm_ds.attrs\n clm_ds = xr.merge([clm_ds, elev], combine_attrs=\"override\")\n clm_ds.attrs = attrs\n clm_ds[\"elevation\"] = clm_ds.elevation.where(\n ~np.isnan(clm_ds.isel(time=0)[keys[0]]), drop=True\n ).T\n # Pa -> kPa\n clm_ds[\"vp\"] *= 1e-3\n # data -> day of year\n clm_ds[\"time\"] = pd.to_datetime(clm_ds.time.values).dayofyear.astype(dtype)\n\n t_min = clm_ds[\"tmin\"]\n t_max = clm_ds[\"tmax\"]\n # average over the daylight period of the day, W/m^2 -> average over the day, MJ m-2 day-1\n r_surf = clm_ds[\"srad\"] * clm_ds[\"dayl\"] * 1e-6\n lat = clm_ds.isel(time=0).lat\n # ° -> rad\n phi = lat * np.pi / 180.0\n elevation = clm_ds[\"elevation\"]\n doy = clm_ds[\"time\"]\n e_a = clm_ds[\"vp\"]\n\n for pet_name in pet_method:\n if pet_name == \"pm_fao56\":\n clm_ds[\"pet_fao56\"] = pm_fao56(\n t_min, t_max, r_surf, phi, elevation, doy, e_a=e_a\n )\n clm_ds[\"pet_fao56\"].attrs[\"units\"] = \"mm/day\"\n elif pet_name == \"priestley_taylor\":\n clm_ds[\"pet_pt\"] = priestley_taylor(\n t_min, t_max, r_surf, phi, elevation, doy, e_a=e_a\n )\n clm_ds[\"pet_pt\"].attrs[\"units\"] = \"mm/day\"\n\n # after calculation, recover the value of time and vp\n clm_ds[\"time\"] = dates\n clm_ds[\"vp\"] *= 1.0e3\n return clm_ds\n\n\ndef calculate_basin_mean(\n clm_ds: xr.Dataset,\n geometry: Union[Polygon, MultiPolygon, Tuple[float, float, float, float]],\n geo_crs: str = DEF_CRS,\n) -> xr.Dataset:\n \"\"\"\n Get gridded data from the Daymet database at 1-km resolution.\n\n Parameters\n ----------\n clm_ds\n gridded daymet Dataset of a basin.\n geometry\n The geometry of a basin.\n geo_crs\n The CRS of the input geometry, defaults to epsg:4326.\n Returns\n -------\n xr.Dataset\n Daily mean climate data of the basin\n\n \"\"\"\n\n clm = _xarray_geomask(clm_ds, geometry, geo_crs)\n ds = xr.Dataset({}, coords={\"time\": clm.time})\n for k in clm.data_vars:\n ds[k] = clm[k].mean(dim=(\"x\", \"y\"))\n return ds\n\n\ndef generate_boundary_dataset(\n clm_ds: xr.Dataset,\n geometry: Union[Polygon, MultiPolygon, Tuple[float, float, float, float]],\n geo_crs: str = DEF_CRS,\n) -> xr.Dataset:\n \"\"\"\n Generate an xarray dataset in the boundary of geometry, but the boundary belongs to clm_ds's array, not the geometry\n\n Parameters\n ----------\n clm_ds\n Downloaded gridded daymet Dataset of a basin.\n geometry\n The geometry of a basin.\n geo_crs\n The CRS of the input geometry, defaults to epsg:4326.\n\n Returns\n -------\n xr.Dataset\n an xarray dataset in the boundary of the geometry\n\n \"\"\"\n\n ds_dims = (\"y\", \"x\")\n transform, width, height = geoutils.pygeoutils._get_transform(clm_ds, ds_dims)\n _geometry = geoutils.pygeoutils._geo2polygon(geometry, geo_crs, clm_ds.crs)\n\n _mask = rio_features.geometry_mask(\n [_geometry], (height, width), transform, invert=True\n )\n # x - column, y - row\n y_idx, x_idx = np.where(_mask)\n y_idx_min = y_idx.min()\n y_idx_max = y_idx.max()\n x_idx_min = x_idx.min()\n x_idx_max = x_idx.max()\n _mask_bound = np.full(_mask.shape, False)\n _mask_bound[y_idx_min : y_idx_max + 1, x_idx_min : x_idx_max + 1] = True\n\n coords = {\n ds_dims[0]: clm_ds.coords[ds_dims[0]],\n ds_dims[1]: clm_ds.coords[ds_dims[1]],\n }\n mask_bound = xr.DataArray(_mask_bound, coords, dims=ds_dims)\n\n ds_bound_masked = clm_ds.where(mask_bound, drop=True)\n ds_bound_masked.attrs[\"transform\"] = transform\n return ds_bound_masked\n\n\ndef resample_nc(clm_ds: xr.Dataset, resample_size: Union[int, float]) -> xr.Dataset:\n \"\"\"\n Resample the dataset to the resample_size\n\n Because Daymet's resolution is 1km which means each grid is 1km * 1km in a x-y coordinate system,\n we think it's enough to use general regrid methods such as interpolate functions in scipy.\n\n Parameters\n ----------\n clm_ds\n the original xarray dataset\n resample_size\n the ratio of resampled dataset's resolution to the original dataset's\n\n Returns\n -------\n xr.Dataset\n the resampled dataset\n\n \"\"\"\n\n if resample_size > 1:\n # coarsen the original values\n ds = (\n clm_ds.coarsen(x=resample_size, boundary=\"pad\")\n .mean()\n .coarsen(y=resample_size, boundary=\"pad\")\n .mean()\n )\n else:\n ydim, xdim = (\"y\", \"x\")\n height, width = clm_ds.sizes[ydim], clm_ds.sizes[xdim]\n left, right = clm_ds[xdim].min().item(), clm_ds[xdim].max().item()\n bottom, top = clm_ds[ydim].min().item(), clm_ds[ydim].max().item()\n\n x_res = abs(left - right) / (width - 1)\n y_res = abs(top - bottom) / (height - 1)\n # interpolate the original values to the new resolution\n x_res_new = x_res * resample_size\n y_res_new = y_res * resample_size\n # the array is in a left-close-right-open range, so right + x_res\n new_x = np.arange(left, right + x_res, x_res_new)\n # the sequence of y is large -> small, for example, [941, 940, 939, ...]\n new_y = np.arange(bottom, top + y_res, y_res_new)[::-1]\n # we extrapolate some out-range values\n ds = clm_ds.interp(x=new_x, y=new_y, kwargs={\"fill_value\": \"extrapolate\"})\n return ds\n\n\ndef trans_daymet_to_camels_format(\n daymet_dir: str, output_dir: str, gage_dict: dict, region: str, year: int\n):\n \"\"\"\n Transform forcing data of daymet downloaded from GEE to the format in CAMELS.\n\n The GEE code used to generate the original data can be seen here:\n https://code.earthengine.google.com/e910596013b5b90cb9c800d17a54a2b3\n If you can read Chinese, and prefer Python code, you can see here:\n https://github.com/OuyangWenyu/hydroGIS/blob/master/GEE/4-geepy-gallery.ipynb\n\n Parameters\n ----------\n daymet_dir\n the original data's directory\n output_dir\n the transformed data's directory\n gage_dict\n a dict containing gage's ids and the correspond HUC02 ids\n region\n we named the file downloaded from GEE as daymet__mean_.csv,\n because we use GEE code to generate data for each year for each shape file (region) containing some basins.\n For example, if we use the basins' shpfile in CAMELS, the region is \"camels\".\n year\n we use GEE code to generate data for each year, so each year for each region has one data file.\n Returns\n -------\n None\n \"\"\"\n\n name_dataset = [\n \"gage_id\",\n \"time_start\",\n \"dayl\",\n \"prcp\",\n \"srad\",\n \"swe\",\n \"tmax\",\n \"tmin\",\n \"vp\",\n ]\n camels_index = [\n \"Year\",\n \"Mnth\",\n \"Day\",\n \"Hr\",\n \"dayl(s)\",\n \"prcp(mm/day)\",\n \"srad(W/m2)\",\n \"swe(mm)\",\n \"tmax(C)\",\n \"tmin(C)\",\n \"vp(Pa)\",\n ]\n\n if \"STAID\" in gage_dict:\n gage_id_key = \"STAID\"\n elif \"gauge_id\" in gage_dict:\n gage_id_key = \"gauge_id\"\n elif \"gage_id\" in gage_dict:\n gage_id_key = \"gage_id\"\n else:\n raise NotImplementedError(\"No such gage id name\")\n\n if \"HUC02\" in gage_dict:\n huc02_key = \"HUC02\"\n elif \"huc_02\" in gage_dict:\n huc02_key = \"huc_02\"\n else:\n raise NotImplementedError(\"No such huc02 id\")\n\n for f_name in os.listdir(daymet_dir):\n if fnmatch.fnmatch(f_name, f\"daymet_{region}_mean_{year}.csv\"):\n data_file = os.path.join(daymet_dir, f_name)\n # because this func only works for one region and one year, it means it only works for one file once\n # Hence, when we find the file and transform it, just finish\n break\n data_temp = pd.read_csv(data_file, sep=\",\", dtype={name_dataset[0]: str})\n for i_basin in range(len(gage_dict[gage_id_key])):\n # name csv\n # if type is not str, may not find the data\n assert type(gage_dict[gage_id_key][i_basin]) == str\n basin_data = data_temp[\n data_temp[name_dataset[0]] == gage_dict[gage_id_key][i_basin]\n ]\n if basin_data.shape[0] == 0:\n raise ArithmeticError(\"Such chosen basins have no data\")\n # get Year,Month,Day,Hour info\n csv_date = pd.to_datetime(basin_data[name_dataset[1]])\n # the hour is set to 12, as 12 is the average hour of a day\n year_month_day_hour = pd.DataFrame(\n [[dt.year, dt.month, dt.day, 12] for dt in csv_date],\n columns=camels_index[:4],\n )\n data_df = pd.DataFrame(basin_data.iloc[:, 2:].values, columns=camels_index[4:])\n # concat\n new_data_df = pd.concat([year_month_day_hour, data_df], axis=1)\n # output the result\n huc_id = gage_dict[huc02_key][i_basin]\n output_huc_dir = os.path.join(output_dir, huc_id)\n if not os.path.isdir(output_huc_dir):\n os.makedirs(output_huc_dir)\n output_file = os.path.join(\n output_huc_dir, gage_dict[gage_id_key][i_basin] + \"_lump_daymet_forcing.txt\"\n )\n print(\"output forcing data of\", gage_dict[gage_id_key][i_basin], \"year\", year)\n if os.path.isfile(output_file):\n data_old = pd.read_csv(output_file, sep=\" \")\n years = np.unique(data_old[camels_index[0]].values)\n if year in years:\n continue\n os.remove(output_file)\n new_data_df = pd.concat([data_old, new_data_df]).sort_values(\n by=camels_index[:3]\n )\n new_data_df.to_csv(\n output_file, header=True, index=False, sep=\" \", float_format=\"%.2f\"\n )\n\n\ndef insert_daymet_value_in_leap_year(data_dir: str, t_range: list = None):\n \"\"\"\n interpolation for the 12.31 data in leap year\n\n Parameters\n ----------\n data_dir\n the transformed but not inserted data's directory\n t_range\n the time range to insert, the default range is [\"1980-01-01\", \"2020-01-01\"]\n\n Returns\n -------\n None\n \"\"\"\n\n if t_range is None:\n t_range = [\"1980-01-01\", \"2020-01-01\"]\n subdir_str = os.listdir(data_dir)\n col_lst = [\n \"dayl(s)\",\n \"prcp(mm/day)\",\n \"srad(W/m2)\",\n \"swe(mm)\",\n \"tmax(C)\",\n \"tmin(C)\",\n \"vp(Pa)\",\n ]\n for i in range(len(subdir_str)):\n subdir = os.path.join(data_dir, subdir_str[i])\n path_list = os.listdir(subdir)\n path_list.sort()\n for filename in path_list:\n data_file = os.path.join(subdir, filename)\n is_leap_file_name = data_file[-8:]\n if \"leap\" in is_leap_file_name:\n continue\n print(\"reading\", data_file)\n data_temp = pd.read_csv(data_file, sep=r\"\\s+\")\n data_temp.rename(columns={\"Mnth\": \"Month\"}, inplace=True)\n df_date = data_temp[[\"Year\", \"Month\", \"Day\"]]\n date = pd.to_datetime(df_date).values.astype(\"datetime64[D]\")\n # daymet file not for leap year, there is no data in 12.31 in leap year\n assert all(x < y for x, y in zip(date, date[1:]))\n t_range_list = t_range_days(t_range)\n [c, ind1, ind2] = np.intersect1d(date, t_range_list, return_indices=True)\n # assert date[0] <= t_range_list[0] and date[-1] >= t_range_list[-1]\n nt = t_range_list.size\n out = np.full([nt, 7], np.nan)\n out[ind2, :] = data_temp[col_lst].values[ind1]\n x = pd.DataFrame(out, columns=col_lst)\n x_intepolate = x.interpolate(\n method=\"linear\", limit_direction=\"forward\", axis=0\n )\n csv_date = pd.to_datetime(t_range_list)\n year_month_day_hour = pd.DataFrame(\n [[dt.year, dt.month, dt.day, dt.hour] for dt in csv_date],\n columns=[\"Year\", \"Mnth\", \"Day\", \"Hr\"],\n )\n # concat\n new_data_df = pd.concat([year_month_day_hour, x_intepolate], axis=1)\n output_file = data_file[:-4] + \"_leap.txt\"\n new_data_df.to_csv(\n output_file, header=True, index=False, sep=\" \", float_format=\"%.2f\"\n )\n os.remove(data_file)\n","repo_name":"OuyangWenyu/CatchmentForcings","sub_path":"catchmentforcings/daymet4basins/basin_daymet_process.py","file_name":"basin_daymet_process.py","file_ext":"py","file_size_in_byte":17876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"2267163551","text":"clothes = [\"T-Shirt\", \"Sweater\"]\nchoice = [\"C\", \"R\", \"U\", \"D\"]\nLoop = True\nwhile Loop:\n CRUD = input(\"Welcome to our shop, what do you want {0}? \".format(choice))\n if CRUD == \"C\":\n new = input(\"Enter new item: \")\n clothes.append(new)\n elif CRUD == \"R\":\n pass\n elif CRUD == \"U\":\n new_po = int(input(\"Update position? \"))\n new = input(\"New item? \")\n clothes[new_po - 1] = new\n elif CRUD == \"D\":\n del_po = int(input(\"Delete position? \"))\n clothes.pop(del_po - 1)\n else:\n print(\"please only choose in {0}\".format(choice))\n break\n print(\"Our items:\", end =\" \")\n print(*clothes, sep =\", \")\n# else:\n# print()\n","repo_name":"KhauTu/C4E15---Khau-Tu","sub_path":"Fundamentals/session04/Homework/01_serious_CRUD.py","file_name":"01_serious_CRUD.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"36803600176","text":"# 2.6.6. Measuring objects properties: ndimage.measurements\n\nimport numpy as np\nfrom scipy import ndimage\nimport matplotlib.pyplot as plt\n\nnp.random.seed(1)\nn = 10\nl = 256\n\nim = np.zeros((l, l))\n\n# after creating im variable which holds 256*256 matrix of zeors is use to plot points in all matrix fields.\npoints = l*np.random.random((2, n**2))\n\n# made 1 at this point range\nim[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1\n\n# sigma is not only use to blure the image but also modify the outer circle of shape. like as in sigma provide a formula whcih use to show a multiple shapes in image but if you change this wiht random numbers you will get different shapes.\n# like change sigma value with sigma=5.2282277 then check or change with other value then chack again.\nim = ndimage.gaussian_filter(im, sigma=l/(4.*n))\n\nmask = im > im.mean()\n\n# this is use to set all 0 as background and rest of 1's are using to show the mask designing\nlabel_im, nb_labels = ndimage.label(mask)\n\nplt.figure(figsize=(9,3))\n\nplt.subplot(131)\nplt.imshow(im)\nplt.axis('off')\nplt.subplot(132)\nplt.imshow(mask, cmap=plt.cm.gray)\nplt.axis('off')\nplt.subplot(133)\nplt.imshow(label_im, cmap=plt.cm.nipy_spectral)\nplt.axis('off')\n\nplt.subplots_adjust(wspace=0.02, hspace=0.02, top=1, bottom=0, left=0, right=1)\nplt.show()","repo_name":"heysushil/python_image_processing","sub_path":"17.Measuring_objects_properties_using_ndimage_messering.py","file_name":"17.Measuring_objects_properties_using_ndimage_messering.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"76"} +{"seq_id":"18250710533","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\nimport jenkins.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Artifact',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('filename', models.CharField(max_length=255)),\n ('url', models.CharField(max_length=255)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Build',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('build_id', models.CharField(max_length=255)),\n ('number', models.IntegerField()),\n ('duration', models.IntegerField(null=True)),\n ('url', models.CharField(max_length=255)),\n ('phase', models.CharField(max_length=25)),\n ('status', models.CharField(max_length=255)),\n ('console_log', models.TextField(null=True, editable=False, blank=True)),\n ('parameters', jenkins.fields.JSONField(null=True, editable=False, blank=True)),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ],\n options={\n 'ordering': ['-number'],\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='JenkinsServer',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(unique=True, max_length=255)),\n ('url', models.CharField(unique=True, max_length=255)),\n ('username', models.CharField(max_length=255)),\n ('password', models.CharField(max_length=255)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Job',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=255)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='JobType',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=255)),\n ('description', models.TextField(null=True, blank=True)),\n ('config_xml', models.TextField()),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='job',\n name='jobtype',\n field=models.ForeignKey(to='jenkins.JobType'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='job',\n name='server',\n field=models.ForeignKey(to='jenkins.JenkinsServer'),\n preserve_default=True,\n ),\n migrations.AlterUniqueTogether(\n name='job',\n unique_together=set([('server', 'name')]),\n ),\n migrations.AddField(\n model_name='build',\n name='job',\n field=models.ForeignKey(to='jenkins.Job'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='build',\n name='requested_by',\n field=models.ForeignKey(blank=True, editable=False, to=settings.AUTH_USER_MODEL, null=True),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='artifact',\n name='build',\n field=models.ForeignKey(to='jenkins.Build'),\n preserve_default=True,\n ),\n ]\n","repo_name":"B-Rich/capomastro","sub_path":"jenkins/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":4238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"76"} +{"seq_id":"72355753524","text":"import sys\nimport math\nfrom pymavlink import mavutil\nfrom time import time, sleep\nfrom common import print_usage, init_mavlink, print_all_messages\nimport threading\n\n\ndef send_heartbeat(the_connection):\n base_mode = mavutil.mavlink.MAV_MODE_FLAG_MANUAL_INPUT_ENABLED + \\\n mavutil.mavlink.MAV_MODE_FLAG_STABILIZE_ENABLED + \\\n mavutil.mavlink.MAV_MODE_FLAG_CUSTOM_MODE_ENABLED\n custom_mode = 0\n system_status = mavutil.mavlink.MAV_STATE_ACTIVE if drone['active'] \\\n else mavutil.mavlink.MAV_STATE_STANDBY\n\n the_connection.mav.heartbeat_send(\n type=mavutil.mavlink.MAV_TYPE_QUADROTOR,\n autopilot=mavutil.mavlink.MAV_AUTOPILOT_ARDUPILOTMEGA,\n base_mode=base_mode,\n custom_mode=custom_mode,\n system_status=system_status)\n\n\ndef send_data_stream_position(the_connection):\n the_connection.mav.global_position_int_send(\n time_boot_ms=0,\n lat=int(drone['lat'] * 10**7), # Converts degrees into degreesE7\n lon=int(drone['lon'] * 10**7), # Converts degrees into degreesE7\n alt=int(drone['alt'] * 1000), # Converts m into mm\n relative_alt=int(drone['alt'] * 1000), # Converts m into mm\n vx=drone['vx'],\n vy=drone['vy'],\n vz=drone['vz'],\n hdg=65535)\n\n\ndef heartbeat_thread(connection, interval):\n while True:\n send_heartbeat(connection)\n sleep(interval)\n\n\ndef global_position_int_thread(connection):\n while True:\n send_data_stream_position(connection)\n sleep(1 / drone['request_data_stream_position']['req_message_rate'])\n\n\nif __name__ == '__main__':\n if len(sys.argv) != 2 and len(sys.argv) != 3:\n print_usage(\"\")\n\n connection_string = sys.argv[1]\n baud = sys.argv[2] if len(sys.argv) == 3 else None\n drone_system = 1 # MAVLINK system id for the drone. Id 1 is the same as the drone.\n drone_component = 1 # MAVLINK component id for the drone. Id 1 is the autopilot.\n the_connection_drone = init_mavlink(drone_system, drone_component, connection_string, baud)\n\n gcs_system = 255 # MAVLINK system id for the GCS. Id 255 is the usual for GCSs.\n gcs_component = 190 # MAVLINK component id for the GCS. Id 190 is used for the GCS.\n the_connection_gcs = init_mavlink(gcs_system, gcs_component, 'udpout:localhost:12345', baud)\n\n module_system = 1 # MAVLINK system id for the module. Id 1 is the same as the drone.\n module_component = 99 # MAVLINK component id for the module. Id 99 is for private user defined use.\n\n # Defining drone information\n drone = {\n 'lat': 63.1, # degrees\n 'lon': 12.0, # degrees\n 'alt': 50, # m\n 'vx': 20, # cm/s\n 'vy': 95, # cm/s\n 'vz': 0, # cm/s\n 'active': False,\n 'request_data_stream_position': {\n 'request_system': None, # What system to send gps information.\n 'request_component': None, # What component to send gps information.\n 'req_message_rate': None # How often to send gps information in hertz.\n }\n }\n\n last_sheep_rtt_seq = -1\n test_timeout = 5 # 5 sec timeout\n\n # Testing sending heartbeat\n print('\\n\\n1. ##############################################################################')\n print('Sending heartbeat to module.')\n send_heartbeat(the_connection_drone)\n print('Waiting for heartbeat from module...')\n msg = the_connection_drone.recv_match(type='HEARTBEAT', blocking=True, timeout=test_timeout)\n if msg is None:\n print('NOT OK! No heartbeat received from module.')\n the_connection_drone.close()\n the_connection_gcs.close()\n exit()\n print('OK! Received heartbeat from module.')\n\n # Starting heartbeat thread\n print('\\n\\n!. ##############################################################################')\n print('Starting heartbeat thread. Interval: 1s')\n t_heartbeat = threading.Thread(target=heartbeat_thread, args=(the_connection_drone, 1.0), daemon=True)\n t_heartbeat.start()\n\n print('\\n\\n!. ##############################################################################')\n print('Changing drone MAV_STATE to MAV_STATE_ACTIVE.')\n drone['active'] = True\n\n # Checking if module requests 'DATA_STREAM_POSITION'\n print('\\n\\n2. ##############################################################################')\n print(\"Checking if module requests 'DATA_STREAM_POSITION' with 'MAV_DATA_STREAM_POSITION\")\n\n msg = the_connection_drone.recv_match(type='REQUEST_DATA_STREAM', blocking=True, timeout=test_timeout)\n print(msg)\n if msg is None:\n print('NOT OK! No \\'REQUEST_DATA_STREAM\\' with \\'MAV_DATA_STREAM_POSITION\\'received from module.')\n the_connection_drone.close()\n the_connection_gcs.close()\n exit()\n elif msg.req_stream_id == mavutil.mavlink.MAV_DATA_STREAM_POSITION and \\\n msg.target_system == drone_system and \\\n msg.target_component in (drone_component, 0) and \\\n msg.start_stop == 1:\n print('OK! Received correct \\'REQUEST_DATA_STREAM\\' from module.')\n\n drone['request_data_stream_position'] = {\n 'request_system': the_connection_drone.target_system, # What system to send gps information.\n 'request_component': the_connection_drone.target_component, # What component to send gps information.\n 'req_message_rate': msg.req_message_rate # How often to send gps information in hertz.\n }\n else:\n print('NOT OK! Received \\'REQUEST_DATA_STREAM\\' is not correct. Received:')\n print(msg)\n the_connection_drone.close()\n the_connection_gcs.close()\n exit()\n\n # Starting global_position_int thread.\n print('\\n\\n!. ##############################################################################')\n print('Starting global_position_int thread. Target system: {}, Target component: {}, interval: {}'.format(\n drone['request_data_stream_position']['request_system'],\n drone['request_data_stream_position']['request_component'],\n drone['request_data_stream_position']['req_message_rate']))\n t_global_position_int = threading.Thread(target=global_position_int_thread, args=(the_connection_drone,), daemon=True)\n t_global_position_int.start()\n\n # Checking if module sends 'SHEEP_RTT_DATA'.\n print('\\n\\n3. ##############################################################################')\n print(\"Checking if module sends 'SHEEP_RTT_DATA' or encapsulated 'SHEEP_RTT_DATA'.\")\n\n msg = the_connection_drone.recv_match(type=['SHEEP_RTT_DATA', 'DATA64'], blocking=True, timeout=test_timeout*5)\n if msg is None:\n print('NOT OK! No SHEEP_RTT_DATA or encapsulated SHEEP_RTT_DATA received.')\n the_connection_drone.close()\n the_connection_drone.close()\n exit()\n elif msg.name == 'SHEEP_RTT_DATA':\n last_sheep_rtt_seq = msg.seq\n print('OK! SHEEP_RTT_DATA received.')\n\n # Send the sheepRTT ack packet directly.\n msg_ack = the_connection_gcs.mav.sheep_rtt_ack_encode(msg.seq)\n the_connection_drone.mav.send(msg_ack)\n print('Sending SHEEP_RTT_ACK to module.')\n elif msg.name == 'DATA64' and msg.type == 129:\n msg = the_connection_gcs.mav.parse_char(msg.data[0:msg.len]) # Unpack encapsulated sheepRTT data.\n last_sheep_rtt_seq = msg.seq\n print(msg)\n\n print('OK! Encapsulated SHEEP_RTT_DATA received.')\n\n # Pack sheepRTT ack packet inside a data16 packet and send it. With zero padding.\n sheep_rtt_ack_packet = the_connection_gcs.mav.sheep_rtt_ack_encode(msg.seq).pack(the_connection_gcs.mav) + b'\\x00\\x00\\x00'\n\n msg_ack = the_connection_gcs.mav.data16_encode(130, len(sheep_rtt_ack_packet) - 3, sheep_rtt_ack_packet)\n the_connection_drone.mav.send(msg_ack)\n print('Sending encapsulated SHEEP_RTT_ACK to module.')\n\n # Avoid errors from an earlier SHEEP_RTT_DATA\n for i in range(10):\n msg = the_connection_drone.recv_match(type=['SHEEP_RTT_DATA', 'DATA64'], blocking=True, timeout=0.2)\n\n # Checking if module sends encapsulated 'SHEEP_RTT_DATA'.\n print('\\n\\n4. ##############################################################################')\n print(\"Checking if module increments 'SHEEP_RTT_DATA' seq after ack.\")\n\n msg = the_connection_drone.recv_match(type=['SHEEP_RTT_DATA', 'DATA64'], blocking=True, timeout=test_timeout*5)\n if msg is None:\n print('NOT OK! No encapsulated SHEEP_RTT_DATA received.')\n the_connection_drone.close()\n the_connection_gcs.close()\n exit()\n elif msg.name == 'SHEEP_RTT_DATA':\n print('SHEEP_RTT_DATA received.')\n elif msg.name == 'DATA64' and msg.type == 129:\n msg = the_connection_gcs.mav.parse_char(msg.data[0:msg.len]) # Unpack encapsulated sheepRTT data.\n print('Encapsulated SHEEP_RTT_DATA received.')\n\n if msg.seq == last_sheep_rtt_seq + 1:\n print('OK! SHEEP_RTT_DATA seq incremented.')\n else:\n print('NOT OK! SHEEP_RTT_DATA seq incremented. Expected: {}, received: {}'.format(last_sheep_rtt_seq, msg.seq))\n the_connection_drone.close()\n the_connection_gcs.close()\n exit()\n\n param_count = None\n\n # Getting module parameter by id.\n print('\\n\\n5. ##############################################################################')\n print(\"Getting module parameter by id\")\n # Start parameter related testing\n for t in range(3):\n the_connection_drone.mav.param_request_read_send(1, 99, str.encode('1 vector weight'), -1) # Test get parameter by id\n msg = the_connection_drone.recv_match(type='PARAM_VALUE', blocking=True, timeout=test_timeout)\n if msg is not None:\n break\n\n if msg is None:\n print('NOT OK! PARAM_VALUE not received.')\n the_connection_drone.close()\n the_connection_gcs.close()\n exit()\n elif msg.param_id != '1 vector weight' or \\\n msg.param_value != 0.0 or \\\n msg.param_type != mavutil.mavlink.MAV_PARAM_TYPE_INT32 or \\\n msg.param_index != 1:\n print('NOT OK! PARAM_VALUE contains wrong values. Expected:\\n '\n 'PARAM_VALUE {param_id : 1 vector weight, param_value : 0.0, param_type : 6, param_count : ??, param_index : 1}\\n'\n 'Received:\\n', msg)\n the_connection_drone.close()\n the_connection_gcs.close()\n exit()\n print('OK! Correct PARAM_VALUE received.')\n param_count = msg.param_count\n\n # Getting module parameter by index.\n print('\\n\\n6. ##############################################################################')\n print(\"Getting module parameter by index\")\n\n for t in range(3):\n the_connection_drone.mav.param_request_read_send(1, 99, str.encode(''), 1) # Test get parameter by index\n msg = the_connection_drone.recv_match(type='PARAM_VALUE', blocking=True, timeout=test_timeout)\n if msg is not None:\n break\n\n if msg is None:\n print('NOT OK! PARAM_VALUE not received.')\n the_connection_drone.close()\n the_connection_gcs.close()\n exit()\n elif msg.param_id != '1 vector weight' or \\\n msg.param_value != 0.0 or \\\n msg.param_type != mavutil.mavlink.MAV_PARAM_TYPE_INT32 or \\\n msg.param_count != param_count or \\\n msg.param_index != 1:\n print('NOT OK! PARAM_VALUE contains wrong values. Expected:\\n '\n 'PARAM_VALUE {param_id : 1 vector weight, param_value : 0.0, param_type : 6, param_count : ', param_count, ', param_index : 1}\\n'\n 'Received:\\n', msg)\n\n the_connection_drone.close()\n the_connection_gcs.close()\n exit()\n print('OK! Correct PARAM_VALUE received.')\n\n # Getting all module parameters.\n print('\\n\\n7. ##############################################################################')\n print(\"Getting all module parameters.\")\n\n for t in range(3):\n the_connection_drone.mav.param_request_list_send(1, 99) # Test get all parameter\n msg = the_connection_drone.recv_match(type='PARAM_VALUE', blocking=True, timeout=test_timeout)\n if msg is not None:\n break\n\n if msg is None:\n print('NOT OK! PARAM_VALUE not received.')\n the_connection_drone.close()\n the_connection_gcs.close()\n exit()\n else:\n values_received = 1\n values_count = msg.param_count\n print(msg)\n\n for i in range(values_received, values_count):\n msg = the_connection_drone.recv_match(type='PARAM_VALUE', blocking=True, timeout=test_timeout)\n print(msg)\n values_received += 1\n sleep(0.02)\n\n if values_received != values_count:\n print('NOT OK! Received {} of {} values.'.format(values_received, values_count))\n the_connection_drone.close()\n the_connection_gcs.close()\n exit()\n\n print('OK! All PARAM_VALUEs received.')\n\n # Setting module parameter.\n print('\\n\\n8 .##############################################################################')\n print(\"Setting module parameter\")\n for t in range(3):\n the_connection_drone.mav.param_set_send(1, 99, str.encode('packet count'), 1, mavutil.mavlink.MAV_PARAM_TYPE_INT32) # Test set a single parameter\n msg = the_connection_drone.recv_match(type='PARAM_VALUE', blocking=True, timeout=test_timeout)\n if msg is not None:\n break\n\n if msg is None:\n print('NOT OK! PARAM_VALUE not received.')\n the_connection_drone.close()\n the_connection_gcs.close()\n exit()\n elif msg.param_id != 'packet count' or \\\n msg.param_value != 5.605193857299268e-45 or \\\n msg.param_type != mavutil.mavlink.MAV_PARAM_TYPE_INT32 or \\\n msg.param_count != param_count or \\\n msg.param_index != 13:\n print('NOT OK! PARAM_VALUE contains wrong values. Expected:\\n '\n 'PARAM_VALUE {param_id : packet count, param_value : 1.0, param_type : 6, param_count : ', param_count, ', param_index : 13}\\n'\n 'Received:\\n', msg)\n\n the_connection_drone.close()\n the_connection_gcs.close()\n exit()\n print('OK! Correct value set and PARAM_VALUE received.')\n","repo_name":"trygve55/sheep-2021-emulator","sub_path":"module_tests.py","file_name":"module_tests.py","file_ext":"py","file_size_in_byte":14305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"4466690403","text":"import json, os\nfrom functools import singledispatch\n\nimport torch\n\nfrom hydragnn.preprocess.load_data import dataset_loading_and_splitting\nfrom hydragnn.preprocess.utils import check_if_graph_size_constant\nfrom hydragnn.utils.distributed import setup_ddp\nfrom hydragnn.utils.model import load_existing_model\nfrom hydragnn.utils.time_utils import print_timers\nfrom hydragnn.utils.config_utils import (\n update_config_NN_outputs,\n normalize_output_config,\n get_log_name_config,\n)\nfrom hydragnn.utils.model import calculate_PNA_degree\nfrom hydragnn.models.create import create_model_config\nfrom hydragnn.train.train_validate_test import test\nfrom hydragnn.postprocess.postprocess import output_denormalize\n\n\n@singledispatch\ndef run_prediction(config):\n raise TypeError(\"Input must be filename string or configuration dictionary.\")\n\n\n@run_prediction.register\ndef _(config_file: str):\n\n config = {}\n with open(config_file, \"r\") as f:\n config = json.load(f)\n\n run_prediction(config)\n\n\n@run_prediction.register\ndef _(config: dict):\n\n try:\n os.environ[\"SERIALIZED_DATA_PATH\"]\n except:\n os.environ[\"SERIALIZED_DATA_PATH\"] = os.getcwd()\n\n world_size, world_rank = setup_ddp()\n\n verbosity = config[\"Verbosity\"][\"level\"]\n train_loader, val_loader, test_loader = dataset_loading_and_splitting(config=config)\n\n graph_size_variable = check_if_graph_size_constant(\n train_loader, val_loader, test_loader\n )\n config = update_config_NN_outputs(config, graph_size_variable)\n\n config = normalize_output_config(config)\n\n config[\"NeuralNetwork\"][\"Architecture\"][\"input_dim\"] = len(\n config[\"NeuralNetwork\"][\"Variables_of_interest\"][\"input_node_features\"]\n )\n max_neigh = config[\"NeuralNetwork\"][\"Architecture\"][\"max_neighbours\"]\n if config[\"NeuralNetwork\"][\"Architecture\"][\"model_type\"] == \"PNA\":\n deg = calculate_PNA_degree(train_loader.dataset, max_neigh)\n else:\n deg = None\n model = create_model_config(\n config=config[\"NeuralNetwork\"][\"Architecture\"],\n num_nodes=train_loader.dataset[0].num_nodes,\n max_neighbours=max_neigh,\n pna_deg=deg,\n verbosity=config[\"Verbosity\"][\"level\"],\n )\n\n log_name = get_log_name_config(config)\n load_existing_model(model, log_name)\n\n (\n error,\n error_rmse_task,\n true_values,\n predicted_values,\n ) = test(test_loader, model, config[\"Verbosity\"][\"level\"])\n\n ##output predictions with unit/not normalized\n if config[\"NeuralNetwork\"][\"Variables_of_interest\"][\"denormalize_output\"]:\n true_values, predicted_values = output_denormalize(\n config[\"NeuralNetwork\"][\"Variables_of_interest\"][\"y_minmax\"],\n true_values,\n predicted_values,\n )\n\n return error, error_rmse_task, true_values, predicted_values\n","repo_name":"jychoi-hpc/HydraGNN","sub_path":"hydragnn/run_prediction.py","file_name":"run_prediction.py","file_ext":"py","file_size_in_byte":2856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"76"} +{"seq_id":"41596529057","text":"#!/usr/bin/env python\n#\n# Scanner(Lexer) for Mini Triangle\n#\n# Author: Wilson Giese\n#\n\nimport cStringIO as StringIO\nimport string\n\n# Token Constants\nTK_IDENTIFIER = 0 # Function names, class names, variable names, etc...\nTK_INTLITERAL = 1\nTK_OPERATOR = 2 # + | - | * | / | < | > | = | \\\nTK_BEGIN = 3 # begin\nTK_CONST = 4 # const\nTK_DO = 5 # do\nTK_ELSE = 6 # else\nTK_END = 7 # end\nTK_IF = 8 # if\nTK_IN = 9 # in\nTK_LET = 10 # let\nTK_THEN = 11 # then\nTK_VAR = 12 # var\nTK_WHILE = 13 # while\nTK_SEMICOLON = 14 # ;\nTK_COLON = 15 # :\nTK_BECOMES = 16 # :=\nTK_IS = 17 # ~\nTK_LPAREN = 18 # (\nTK_RPAREN = 19 # )\nTK_EOT = 20 # end of text\nTK_FUNCDEF = 21 # func\nTK_RETURN = 22 # return\nTK_COMMA = 23 # ,\n\nTOKENS = {TK_IDENTIFIER: 'IDENTIFIER',\n TK_INTLITERAL: 'INTLITERAL',\n TK_OPERATOR: 'OPERATOR',\n TK_BEGIN: 'BEGIN',\n TK_CONST: 'CONST',\n TK_DO: 'DO',\n TK_ELSE: 'ELSE',\n TK_END: 'END',\n TK_IF: 'IF',\n TK_IN: 'IN',\n TK_LET: 'LET',\n TK_THEN: 'THEN',\n TK_VAR: 'VAR',\n TK_WHILE: 'WHILE',\n TK_SEMICOLON: 'SEMICOLON',\n TK_COLON: 'COLON',\n TK_BECOMES: 'BECOMES',\n TK_IS: 'IS',\n TK_LPAREN: 'LPAREN',\n TK_RPAREN: 'RPAREN',\n TK_EOT: 'EOT',\n TK_FUNCDEF: 'FUNCDEF',\n TK_RETURN: 'RETURN',\n TK_COMMA: 'COMMA'}\n\nKEYWORDS = {'begin': TK_BEGIN,\n 'const': TK_CONST,\n 'do': TK_DO,\n 'else': TK_ELSE,\n 'end': TK_END,\n 'if': TK_IF,\n 'in': TK_IN,\n 'let': TK_LET,\n 'then': TK_THEN,\n 'var': TK_VAR,\n 'while': TK_WHILE,\n 'func': TK_FUNCDEF,\n 'return': TK_RETURN}\n\nOPERATORS = ['+', '*', '-', '/', '<', '>', '=', '!=', '\\\\']\n\n\nclass Token(object):\n \"\"\" A simple Token structure.\n\n Contains the token type, value and position.\n \"\"\"\n def __init__(self, type, val, pos):\n self.type = type\n self.val = val\n self.pos = pos\n\n def __str__(self):\n return '(%s(%s) at %s)' % (TOKENS[self.type], self.val, self.pos)\n\n def __repr__(self):\n return self.__str__()\n\n\nclass ScannerError(Exception):\n \"\"\" Scanner error exception.\n\n pos: position in the input text where the error occurred.\n \"\"\"\n def __init__(self, pos, char):\n self.pos = pos\n self.char = char\n\n def __str__(self):\n return 'ScannerError at pos = %d, char = %s' % (self.pos, self.char)\n\n\nclass Scanner(object):\n \"\"\"Scanner for the following token grammar\n\n Token ::= Letter (Letter | Digit)* | Digit Digit* |\n '+' | '-' | '*' | '/' | '<' | '>' | '=' | '\\'\n ':' ('=' | ) | ';' | '~' | '(' | ')' | \n\n Separator ::= '!' Graphic* | | \n \"\"\"\n\n def __init__(self, input):\n # Use StringIO to treat input string like a file.\n self.inputstr = StringIO.StringIO(input)\n self.eot = False # Are we at the end of the input text?\n self.pos = 0 # Position in the input text\n self.char = '' # The current character from the input text\n self.char_take() # Fill self.char with the first character\n\n def scan(self):\n \"\"\"Main entry point to scanner object.\n\n Return a list of Tokens.\n \"\"\"\n\n self.tokens = []\n while 1:\n token = self.scan_token()\n self.tokens.append(token)\n\n if token.type == TK_EOT:\n break\n return self.tokens\n\n def scan_token(self):\n \"\"\"Scan a single token from input text.\n\n Return a Token.\n \"\"\"\n\n c = self.char_current()\n token = None\n\n while not self.char_eot():\n # Remove spaces\n if c.isspace():\n self.char_take()\n c = self.char_current()\n continue\n\n # Remove Comments\n if c == '!':\n while self.char_current() != '\\n' and not self.char_eot():\n self.char_take()\n c = self.char_current()\n continue\n\n if c.isdigit(): # Integer\n token = self.scan_int()\n break\n elif c.isalpha(): # Keyword/Identifier\n pos = self.char_pos()\n word = self.scan_keyword()\n\n # Get type from dictionary\n token_type = KEYWORDS.get(word)\n\n if token_type is None: # Not a keyword\n token = Token(TK_IDENTIFIER, word, pos)\n else: # Is a keyword\n token = Token(token_type, 0, pos)\n break\n elif c in OPERATORS:\n pos = self.char_pos()\n val = self.char_take()\n token = Token(TK_OPERATOR, val, pos)\n break\n elif c == ';':\n pos = self.char_pos()\n val = self.char_take()\n token = Token(TK_SEMICOLON, 0, pos)\n break\n elif c == ':':\n pos = self.char_pos()\n val = self.char_take()\n\n # Check for becomes(:=) token\n if(self.char_current() == '='):\n val += self.char_take()\n token = Token(TK_BECOMES, 0, pos)\n else:\n token = Token(TK_COLON, 0, pos)\n break\n elif c == '~':\n pos = self.char_pos()\n val = self.char_take()\n token = Token(TK_IS, 0, pos)\n break\n elif c == '(':\n pos = self.char_pos()\n val = self.char_take()\n token = Token(TK_LPAREN, 0, pos)\n break\n elif c == ')':\n pos = self.char_pos()\n val = self.char_take()\n token = Token(TK_RPAREN, 0, pos)\n break\n elif c == ',':\n pos = self.char_pos()\n val = self.char_take()\n token = Token(TK_COMMA, 0, pos)\n break\n else:\n raise ScannerError(self.char_pos(), self.char_current())\n\n # Finished building token\n if token is not None:\n return token\n\n if self.char_eot():\n return(Token(TK_EOT, 0, self.char_pos()))\n\n def scan_int(self):\n \"\"\"Int :== Digit (Digit*)\"\"\"\n\n pos = self.char_pos()\n numlist = [self.char_take()]\n\n while self.char_current().isdigit():\n numlist.append(self.char_take())\n\n return Token(TK_INTLITERAL, int(string.join(numlist, '')), pos)\n\n def scan_keyword(self):\n \"\"\"Scans and builds keyword. Terminates on any non-alpha or non-digit character\n\n Note: Keywords CANNOT start with digits. Those should all be considered ints\n \"\"\"\n word = self.char_take()\n\n while self.char_current().isalpha() or self.char_current().isdigit():\n word += self.char_take()\n\n return word\n\n def char_current(self):\n \"\"\"Return in the current input character.\"\"\"\n\n return self.char\n\n def char_take(self):\n \"\"\"Consume the current character and read the next character\n from the input text.\n\n Update self.char, self.eot, and self.pos\n \"\"\"\n\n char_prev = self.char\n\n self.char = self.inputstr.read(1)\n if self.char == '':\n self.eot = True\n\n self.pos += 1\n\n return char_prev\n\n def char_pos(self):\n \"\"\"Return the position of the *current* character in the input text.\"\"\"\n\n return self.pos - 1\n\n def char_eot(self):\n \"\"\"Determine if we are at the end of the input text.\"\"\"\n\n return self.eot\n","repo_name":"WilsonGiese/MiniTriangleLanguageImplementation","sub_path":"scanner.py","file_name":"scanner.py","file_ext":"py","file_size_in_byte":8152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"27223807945","text":"import json\n\nkk = {}\nwith open(\"assets/kk_full.json\", \"r\") as kkfile:\n kk = json.load(kkfile)\n\n\nfor song_no, song in kk.items():\n lyrics: list = song[\"Song\"].split(\"\\n\\n\")\n print(\"song \", song_no)\n if len(lyrics) == 1:\n ll = lyrics[0].split(\"\\n\")\n x = len(ll)\n n = 1\n for y in range(4, len(ll) // 2):\n if len(ll) % y == 0:\n n = y\n break\n lyrics = [\"\\n\".join(ll[i : i + n]) for i in range(0, len(ll), n)]\n kk[song_no][\"Song\"] = \"\\n\\n\".join(lyrics)\n if lyrics[0].count(\"\\n\") > lyrics[1].count(\"\\n\") and not lyrics[1].startswith(\"1\"):\n print(song_no)\n x = lyrics[1].count(\"\\n\") + 1\n chorus_lyrics = lyrics[0].split(\"\\n\")[x:]\n chorus = \"\\n\".join(chorus_lyrics)\n lyrics[0] = \"\\n\".join(lyrics[0].split(\"\\n\")[:x])\n lyrics.insert(0, chorus)\n kk[song_no][\"Song\"] = \"\\n\\n\".join(lyrics)\nwith open(\"updated_kk.json\", \"w\") as newkk:\n json.dump(kk, newkk, ensure_ascii=False)\n\nprint(\"NEW FILE\")\nwith open(\"updated_kk.json\", \"r\") as kkfile:\n kk = json.load(kkfile)\n\n\nfor song_no, song in kk.items():\n lyrics: list = song[\"Song\"].split(\"\\n\\n\")\n if lyrics[0].count(\"\\n\") > lyrics[1].count(\"\\n\"):\n print(song_no)\n","repo_name":"gijocode/Church_PPT_Utility","sub_path":"cleaner.py","file_name":"cleaner.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"35384253896","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n\n#\n# Complete the 'encryption' function below.\n#\n# The function is expected to return a STRING.\n# The function accepts STRING s as parameter.\n#\n\ndef encryption(s):\n\n L = s.replace(' ' , '')\n print(len(L))\n col = max(math.floor(math.sqrt(len(L))) , math.ceil(math.sqrt(len(L))))\n row = min(math.floor(math.sqrt(len(L))) , math.ceil(math.sqrt(len(L))))\n if abs(row*col - len(L)) >= 1:\n row = col\n res = []\n st = 0\n end = col\n print(L,row,col)\n for i in range(row):\n res.append(L[st:end])\n st = end\n end += col\n rest = \"\"\n print(res)\n for i in range(col):\n for j in res:\n try:\n rest += j[i]\n except:\n pass\n rest += ' '\n\n return rest\n\n\nif __name__ == '__main__':\n result = encryption(\"roqfqeylxuyxjfyqterizzkhgvngapvudnztsxeprfp\")\n print(result)\n","repo_name":"MdAbuZehadAntu/hackerrank","sub_path":"badges/problem_solving/algorithms/encryption.py","file_name":"encryption.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"41944034096","text":"import time\n\nfrom rest_framework.authentication import TokenAuthentication\nfrom rest_framework import exceptions\n\n\nclass DelayTokenAuthentication(TokenAuthentication):\n \"\"\"\n Simple token based authentication with configurable delay\n\n Clients should authenticate by passing the token key in the \"Authorization\"\n HTTP header, prepended with the string \"Token \". For example:\n\n Authorization: Token 401f7ac837da42b97f613d789819ff93537bee6a\n \"\"\"\n HARDCODED_TOKEN = '224a93060c0dd4fb931d05083b4cb7b6a8c27df8'\n DELAY = 0.00001\n\n def authenticate_credentials(self, key):\n if len(key) != len(self.HARDCODED_TOKEN):\n raise exceptions.AuthenticationFailed('Invalid token.')\n\n for i in xrange(len(key)):\n if key[i] == self.HARDCODED_TOKEN[i]:\n time.sleep(self.DELAY)\n else:\n raise exceptions.AuthenticationFailed('Invalid token.')\n","repo_name":"andresriancho/django-rest-framework-timing","sub_path":"timing/example/authentication/token.py","file_name":"token.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"2296056844","text":"from http.server import HTTPServer\nfrom webbrowser import open_new\nfrom http_server_handler import HTTPServerHandler\n\n\nclass TokenHandler:\n \"\"\"\n Class used to handle oAuth\n \"\"\"\n\n def __init__(self, client_id, client_secret, access_url, api, name_api):\n self._id = client_id\n self._secret = client_secret\n self._access_url = access_url\n self._api = api\n self.name_api = name_api\n\n def get_access_token(self):\n open_new(self._access_url)\n\n http_server = HTTPServer(('localhost', 8080),\n lambda request, address, server:\n HTTPServerHandler\n (request, address, server,\n self._id, self._secret,\n self._api, self.name_api))\n\n # This function will block until it receives a request\n http_server.socket.settimeout(40)\n http_server.handle_request()\n try:\n return http_server.access_token\n except AttributeError:\n return None, None, 'Connection error'\n","repo_name":"vakyym07/export_contacts","sub_path":"token_handler.py","file_name":"token_handler.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"4041428370","text":"# Phillip LeClair\n# CS 5001\n# Final Project\n# 12/10/2023\n# testApp.py executes a series of tests to ensure functionality of the project\n\n\n# import unittest to create the testing framework\nimport unittest\n\n# import os to check file size\nimport os\nfrom datetime import date\nfrom os.path import getsize\n\n# import Driver to execute the webdriver\nfrom driver import Driver\n\n# import DataService to send API requests to Google Sheets\nfrom dataService import DataService\n\nclass TestDriver(unittest.TestCase):\n ''' TestDriver class creates a series of tests\n Parameters: unnittest.TestCase\n '''\n def test_data_service(self):\n ''' test_data_service tests whether Google Sheets API is returning data\n Parameters: None\n Returns nothing\n '''\n spreadsheet_id='1ZbTHgQc5p61oDLcAHoj2iAWcfgYXJJibnCFMo9boShI'\n service = DataService(spreadsheet_id)\n data = service.getData()\n # check to see if the sheet has data\n self.assertTrue(len(data['values']) > 0, msg='Returned sheet is empty!')\n def test_driver(self):\n ''' test_driver tests whether the webdriver scrapes listings correctly & saves a valid screenshot\n Parameters: None\n Returns nothing\n '''\n driver = Driver()\n\n tenant = 'Aspen Valley Hospital'\n city_state = 'Aspen, CO'\n specialty = 'Medical'\n # title = 'Doctor' -- optional\n results = driver.drive(tenant, city_state, specialty)\n\n path = os.getcwd() + f'/images/{tenant}'\n today = str(date.today())\n img_path = f'{path}/3pack - {today}.png'\n img_size = getsize(img_path) / 1000\n height, width = results['screenshot_size']\n driver.quit()\n # check to see if listing dimensions are valid:\n self.assertTrue(results['width'] > 0 and results['height'] > 0, msg='Listing dimensions are invalid')\n # check to see if screenshot dimensions are valid:\n self.assertTrue(height > 0 and width > 0, msg='Screenshot dimensions are invalid')\n # check to see if screenshot image size is valid (greater than 100kb):\n self.assertTrue(img_size > 10, msg='Screenshot file size is invalid (<10kb)!')\n\n\ndef main():\n ''' Main function executes the tests\n Parameters: None\n Returns nothing\n '''\n unittest.main(verbosity=3)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"pjleclair/threePackTool","sub_path":"testApp.py","file_name":"testApp.py","file_ext":"py","file_size_in_byte":2378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"40506207496","text":"import openpyxl\n\nworkbook = openpyxl.load_workbook('cwd_file.xlxs')\n\n# a sinle xlxs file might contain multiple tabs and \n# or maybe you can call that a sheet\n# that little tab thingy in the left-bottom of your \n# excel file??? yeah, that's what it is... that's a sheet\n\n# you can select a sheet by\n\nsheet1 = workbook.get_sheet_by_name('sheet_name_i.e_sheet1')\n\n# get names of all sheets, no paras\n\nsheets = workbook.get_sheet_names()\n# print (sheets) will result in sheet1\n\n# let's suppose we get a sheet named sheet1, let's work with it\ncellOrColumnName = sheet1['firstColumnName']\n# [] bracket in sheet gets call objects\n# cell objects have value member variable\n# with all the contents of that cell. \n\nstore = str(cellOrColumnName.value)\n# cell() method retusn a Cell object from a sheet\n\n\n# EDITING EXCEL SPREADSHEETS\nwb = openpyxl.workbook()\n# create a workbook object\nwb.get_sheet_names()\n# ['Sheet'] -> default name prolly. \n# lets select this sheet and work with it\n\nsheet = wb.get_sheet_by_name('Sheet')\n\nsheet['A1'].value == None\n# returns true\n\nsheet['A1'] = 42\nsheet['A2'] = 'Hello'\n\n# save the sheet to some other directory. \n\nimport os\n\nos.chdir('c:\\\\Users\\\\UserName\\\\Documents')\nwb.save()\n\n# create another sheet\nsheet2 = wb.create_sheet()\nwb.get_sheet_names()\n\n# would returns 2 sheets now\n# [Sheet1, Sheet2]\n\nsheet2.title = 'New Sheet Of People Name'\nwb.get_sheet_names()\n\n# now it will return sheet1 and New Sheet of People Name\nwb.save('example.xlsx')\n# workbook saved\n\nwb.create_sheet(index=0, title='My Other Sheet')\nwb.save('Other Sheet.xlsx')\n# Now, this workbook would have first sheet named my other sheet\n# as you can see the first para index=0, represents first sheet index\n\n\n\n\n\n\n\n","repo_name":"mujeebishaque/AutomateTheBoringStuffWithPython","sub_path":"workingWithExcel.py","file_name":"workingWithExcel.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"76"} +{"seq_id":"6333074346","text":"import locale as L\nimport math as M\n\nimport skdecide.hub.domain.flight_planning.weather_interpolator.weather_tools.unit_conversion as U\n\ntry:\n from default_units import *\nexcept ImportError:\n default_area_units = \"ft**2\"\n default_power_units = \"hp\"\n default_speed_units = \"kt\"\n default_temp_units = \"C\"\n default_weight_units = \"lb\"\n default_press_units = \"in HG\"\n default_density_units = \"lb/ft**3\"\n default_length_units = \"ft\"\n default_alt_units = default_length_units\n default_avgas_units = \"lb\"\n\ntry:\n L.setlocale(L.LC_ALL, \"en_US\")\nexcept:\n pass\n\ng = 9.80665 # Acceleration of gravity at 45.542 deg latitude, m/s**s\nRd = 287.05307 # Gas constant for dry air, J/kg K\n\n# conditions starting at sea level, in a region with temperature gradient\n\nT0 = 288.15 # Temperature at sea level, degrees K\nL0 = -6.5 # Temperature lapse rate, at sea level deg K/km\nP0 = 29.9213 # Pressure at sea level, in HG\nRho0 = 1.2250 # Density at sea level, kg/m**3\n\n# conditions starting at 11 km, in an isothermal region\n\nT11 = T0 + 11 * L0 # Temperature at 11,000 m, degrees K\nPR11 = (T11 / T0) ** ((-1000 * g) / (Rd * L0)) # pressure ratio at 11,000 m\nP11 = PR11 * P0\nRho11 = (Rho0 * PR11) * (T0 / T11)\n\n# conditions starting at 20 km, in a region with temperature gradient\n\nT20 = T11\nPR20 = PR11 * M.exp(((-1000 * g) * (20 - 11)) / (Rd * T11))\nL20 = 1 # temperature lapse rate, starting at 20,000 m, deg K/km\nP20 = PR20 * P0\nRho20 = (Rho0 * PR20) * (T0 / T20)\n\n# conditions starting at 32 km, in a region with temperature gradient\n\nT32 = 228.65 # Temperature at 32 km, degrees K\nPR32 = PR20 * (T32 / T20) ** ((-1000 * g) / (Rd * L20))\n\n# PR32 = PR20 * M.exp((-1000 * g) * (32 - 20)/(R * T20))\n\nL32 = 2.8 # temperature lapse rate, starting at 32,000 m, deg K/km\nP32 = PR32 * P0\nRho32 = (Rho0 * PR32) * (T0 / T32)\n\n# conditions starting at 47 km, in an isothermal region\n\nT47 = 270.65\nPR47 = PR32 * (T47 / T32) ** ((-1000 * g) / (Rd * L32))\nP47 = PR47 * P0\nRho47 = (Rho0 * PR47) * (T0 / T47)\n\n# conditions starting at 51 km, in a region with temperature gradient\n\nT51 = 270.65 # Temperature at 51 km, degrees K\nPR51 = PR47 * M.exp(((-1000 * g) * (51 - 47)) / (Rd * T47))\nL51 = -2.8 # temperature lapse rate, starting at 51,000 m, deg K/km\nP51 = PR51 * P0\nRho51 = (Rho0 * PR51) * (T0 / T51)\n\n# conditions starting at 71 km, in a region with temperature gradient\n\nT71 = 214.65 # Temperature at 71 km, degrees K\nPR71 = PR51 * (T71 / T51) ** ((-1000 * g) / (Rd * L51))\nL71 = -2.0 # temperature lapse rate, starting at 71,000 m, deg K/km\nP71 = PR71 * P0\nRho71 = (Rho0 * PR71) * (T0 / T71)\n\n# temp_units_list = ['C', 'F', 'K', 'R']\n\n# #############################################################################\n#\n# Altitude to temperature\n#\n# #############################################################################\n\n\ndef alt2temp(H, alt_units=default_alt_units, temp_units=default_temp_units):\n \"\"\"Return the standard temperature for the specified altitude. Altitude\n units may be feet ('ft'), metres ('m'), statute miles, ('sm') or\n nautical miles ('nm'). Temperature units may be degrees C, F, K or R\n ('C', 'F', 'K' or 'R')\n\n If the units are not specified, the units in default_units.py are used.\n\n Examples:\n\n Calculate the standard temperature (in default temperature units) at\n 5,000 (default altitude units):\n >>> alt2temp(5000)\n 5.0939999999999941\n\n Calculate the standard temperature in deg F at sea level:\n >>> alt2temp(0, temp_units = 'F')\n 59.0\n\n Calculate the standard temperature in deg K at 11,000 m:\n >>> alt2temp(11000, alt_units = 'm', temp_units = 'K')\n 216.64999999999998\n\n Calculate the standard temperature at 11 statute miles in deg R:\n >>> alt2temp(11, alt_units = 'sm', temp_units = 'R')\n 389.96999999999997\n\n The input value may be an expression:\n >>> alt2temp(11 * 5280, temp_units = 'R')\n 389.96999999999997\n\n \"\"\"\n\n # Validated to 84000 m\n # uses meters and degrees K for the internal calculations\n\n # function tested in tests/test_std_atm.py\n\n H = U.len_conv(H, from_units=alt_units, to_units=\"km\")\n\n if H <= 11:\n temp = T0 + H * L0\n elif H <= 20:\n temp = T11\n elif H <= 32:\n temp = T20 + (H - 20) * L20\n elif H <= 47:\n temp = T32 + (H - 32) * L32\n elif H <= 51:\n temp = T47\n elif H <= 71:\n temp = T51 + (H - 51) * L51\n elif H <= 84.852:\n temp = T71 + (H - 71) * L71\n else:\n raise ValueError(\n \"This function is only implemented for altitudes of 84.852 km and below.\"\n )\n\n return U.temp_conv(temp, to_units=temp_units, from_units=\"K\")\n\n\ndef alt2temp_ratio(H, alt_units=default_alt_units):\n \"\"\"\n Return the temperature ratio (temperature / standard temperature for\n sea level). The altitude is specified in feet ('ft'), metres ('m'),\n statute miles, ('sm') or nautical miles ('nm').\n\n If the units are not specified, the units in default_units.py are used.\n\n Examples:\n\n Calculate the temperature ratio at 8,000 (default altitude units)\n >>> alt2temp_ratio(8000)\n 0.94499531494013533\n\n Calculate the temperature ratio at 8,000 m.\n >>> alt2temp_ratio(8000, alt_units = 'm')\n 0.81953843484296374\n \"\"\"\n\n # function tested in tests/test_std_atm.py\n\n return alt2temp(H, alt_units, temp_units=\"K\") / T0\n\n\n# #############################################################################\n#\n# ISA deviation to temperature\n#\n# #############################################################################\n\n\ndef isa2temp(\n ISA_dev,\n altitude,\n temp_units=default_temp_units,\n alt_units=default_alt_units,\n):\n \"\"\"\n Return the temperature that is a specified amount warmer or cooler\n than the standard temperature for the altitude.\n\n The temperature may be in deg C, F, K or R.\n\n The altitude may be in feet ('ft'), metres ('m'), kilometres ('km'),\n statute miles, ('sm') or nautical miles ('nm').\n\n If the units are not specified, the units in default_units.py are used.\n\n Examples:\n\n Determine the temperature that is 10 deg (default temperature units) warmer\n than the standard temperature at 8,000 (default altitude units):\n >>> isa2temp(10, 8000)\n 9.1503999999999905\n\n Determine the temperature that is 25 degrees K cooler than the standard\n temperature at 2000 m.\n >>> isa2temp(-25, 2000, temp_units = 'K', alt_units = 'm')\n 250.14999999999998\n \"\"\"\n\n # function tested in tests/test_std_atm.py\n\n temp = ISA_dev + alt2temp(altitude, alt_units, temp_units)\n\n return temp\n\n\n# #############################################################################\n#\n# temperature to ISA deviation\n#\n# #############################################################################\n\n\ndef temp2isa(\n temp,\n altitude,\n temp_units=default_temp_units,\n alt_units=default_alt_units,\n):\n \"\"\"\n Return the amount that the specified temperature is warmer or cooler\n than the standard temperature for the altitude.\n\n The temperature may be in deg C, F, K or R.\n\n The altitude may be in feet ('ft'), metres ('m'), kilometres ('km'),\n statute miles, ('sm') or nautical miles ('nm').\n\n If the units are not specified, the units in default_units.py are used.\n\n Examples:\n\n Determine the ISA deviation for a temperature of 30 deg (default\n temperature units) at an altitude of 2000 (default altitude units):\n >>> temp2isa(30, 2000)\n 18.962400000000002\n\n Determine the ISA deviation in degrees F for a temperature of 45 deg F\n at an altitude of 1000 m:\n >>> temp2isa(45, 1000, temp_units = 'F', alt_units = 'm')\n -2.2999999999999972\n \"\"\"\n\n # function tested in tests/test_std_atm.py\n\n std_temp = alt2temp(altitude, alt_units, temp_units)\n ISA_dev = temp - std_temp\n\n return ISA_dev\n\n\n# #############################################################################\n#\n# Altitude to pressure and pressure ratio\n#\n# #############################################################################\n\n\ndef _alt2press_ratio_gradient(\n H,\n Hb,\n Pb,\n Tb,\n L,\n):\n\n # eqn from USAF TPS PEC binder, page PS1-31\n\n return (Pb / P0) * (1 + (L / Tb) * (H - Hb)) ** ((-1000 * g) / (Rd * L))\n\n\ndef _alt2press_ratio_isothermal(\n H,\n Hb,\n Pb,\n Tb,\n):\n\n # eqn from USAF TPS PEC binder, page PS1-26\n\n return (Pb / P0) * M.exp((-1 * (H - Hb)) * ((1000 * g) / (Rd * Tb)))\n\n\ndef alt2press_ratio(H, alt_units=default_alt_units):\n \"\"\"\n Return the pressure ratio (atmospheric pressure / standard pressure\n for sea level). The altitude is specified in feet ('ft'), metres ('m'),\n statute miles, ('sm') or nautical miles ('nm').\n\n If the units are not specified, the units in default_units.py are used.\n\n Examples:\n\n Calculate the pressure ratio at 5000 (default altitude units):\n >>> alt2press_ratio(5000)\n 0.8320481158727735\n\n Calculate the pressure ratio at 1000 m:\n >>> alt2press_ratio(1000, alt_units = 'm')\n 0.88699304638887044\n\n The functions are only implemented at altitudes of 84.852 km and lower.\n >>> alt2press_ratio(90, alt_units = 'km')\n Traceback (most recent call last):\n File '', line 1, in ?\n File './std_atm.py', line 189, in alt2press_ratio\n if H <= 20:\n ValueError: This function is only implemented for altitudes of 84.852 km and below.\n \"\"\"\n\n # uses meters and degrees K for the internal calculations\n\n # function tested in tests/test_std_atm.py\n\n H = U.len_conv(H, from_units=alt_units, to_units=\"km\")\n\n if H <= 11:\n return _alt2press_ratio_gradient(H, 0, P0, T0, L0)\n if H <= 20:\n return _alt2press_ratio_isothermal(H, 11, P11, T11)\n if H <= 32:\n return _alt2press_ratio_gradient(H, 20, P20, T20, L20)\n if H <= 47:\n return _alt2press_ratio_gradient(H, 32, P32, T32, L32)\n if H <= 51:\n return _alt2press_ratio_isothermal(H, 47, P47, T47)\n if H <= 71:\n return _alt2press_ratio_gradient(H, 51, P51, T51, L51)\n if H <= 84.852:\n return _alt2press_ratio_gradient(H, 71, P71, T71, L71)\n else:\n raise ValueError(\n \"This function is only implemented for altitudes of 84.852 km and below.\"\n )\n\n\ndef alt2press(H, alt_units=default_alt_units, press_units=default_press_units):\n \"\"\"\n Return the atmospheric pressure for a given altitude, with the\n altitude in feet ('ft'), metres ('m'), statute miles, ('sm') or nautical\n miles ('nm'), and the pressure in inches of HG ('in HG'), mm of HG\n ('mm HG'), psi, lb per sq. ft ('psf'), pa, hpa or mb.\n\n If the units are not specified, the units in default_units.py are used.\n\n Examples:\n\n Calculate the pressure in inches of mercury at 5,000 (default altitude\n units):\n >>> alt2press(5000)\n 24.895961289464015\n\n Calculate the pressure in pounds per square foot at 10,000 (default\n altitude units):\n >>> alt2press(10000, press_units = 'psf')\n 1455.3301392981359\n\n Calculate the pressure in pascal at 20 km:\n >>> alt2press(20, press_units = 'pa', alt_units = 'km')\n 5474.8827144576408\n \"\"\"\n\n # uses meters, inches of HG and degrees K for the internal calculations\n\n # function tested in tests/test_std_atm.py\n\n H = U.len_conv(H, from_units=alt_units, to_units=\"m\")\n\n press = P0 * alt2press_ratio(H, alt_units=\"m\")\n press = U.press_conv(press, from_units=\"in HG\", to_units=press_units)\n\n return press\n\n\n# #############################################################################\n#\n# Pressure altitude from barometric altitude and altimeter setting\n#\n# #############################################################################\n\n\ndef pressure_alt(H, alt_setting, alt_units=default_alt_units):\n \"\"\"\n Return the pressure altitude, given the barometric altitude and the\n altimeter setting.\n\n Altimeter setting may have units of inches of HG, or hpa or mb. If the\n altimeter setting value is less than 35, the units are assumed to be\n in HG, otherwise they are assumed to be hpa. The altimeter setting must\n be in the range of 25 to 35 inches of mercury.\n\n The altitude may have units of feet ('ft'), metres ('m'), statute miles,\n ('sm') or nautical miles ('nm').\n\n If the units are not specified, the units in default_units.py are used.\n\n Examples:\n\n Calculate the pressure altitude for 1,000 (default altitude units)\n barometric altitude with altimeter setting of 30.92 in HG:\n >>> pressure_alt(1000, 30.92)\n 88.612734282205338\n\n Calculate the pressure altitude for 1,000 (default altitude units)\n barometric altitude with altimeter setting of 1008 mb:\n >>> pressure_alt(1000, 1008)\n 1143.6503495627171\n\n Calculate the pressure altitude in metres for 304.8 m barometric\n altitude with altimeter setting of 1008 mb:\n >>> pressure_alt(304.8, 1008, alt_units = 'm')\n 348.58462654671621\n \"\"\"\n\n H = U.len_conv(H, from_units=alt_units, to_units=\"ft\")\n if alt_setting > 35:\n alt_setting = U.press_conv(alt_setting, from_units=\"hpa\", to_units=\"in HG\")\n if alt_setting < 25 or alt_setting > 35:\n raise ValueError(\"Altimeter setting out of range.\")\n HP = H + 145442.2 * (1 - (alt_setting / P0) ** 0.190261)\n HP = U.len_conv(HP, from_units=\"ft\", to_units=alt_units)\n return HP\n\n\ndef QNH(\n HP,\n H,\n alt_units=default_alt_units,\n alt_setting_units=\"in HG\",\n):\n \"\"\"\n Return the altimeter setting, given the pressure altitude (HP) and the\n barometric altitude (H).\n \"\"\"\n\n HP = U.len_conv(HP, from_units=alt_units, to_units=\"ft\")\n H = U.len_conv(H, from_units=alt_units, to_units=\"ft\")\n QNH = P0 * (1 - (HP - H) / 145442.2) ** 5.255594\n QNH = U.press_conv(QNH, from_units=\"in HG\", to_units=alt_setting_units)\n\n return QNH\n\n\n# #############################################################################\n#\n# Altitude to density and density ratio\n#\n# #############################################################################\n\n\ndef alt2density_ratio(H, alt_units=default_alt_units):\n \"\"\"\n Return the density ratio (atmospheric density / standard density\n for sea level). The altitude is specified in feet ('ft'), metres ('m'),\n statute miles, ('sm') or nautical miles ('nm').\n\n If the units are not specified, the units in default_units.py are used.\n\n Examples:\n\n Calculate the density ratio at 7,500 (default altitude units):\n >>> alt2density_ratio(7500)\n 0.79825819881753035\n\n Calculate the density ratio at 2 km:\n >>> alt2density_ratio(2, alt_units = 'km')\n 0.8216246960994622\n \"\"\"\n\n # function tested in tests/test_std_atm.py\n\n return alt2press_ratio(H, alt_units) / alt2temp_ratio(H, alt_units)\n\n\ndef alt2density(H, alt_units=default_alt_units, density_units=default_density_units):\n \"\"\"\n Return the density given the pressure altitude. The altitude is\n specified in feet ('ft'), metres ('m'), statute miles, ('sm') or\n nautical miles ('nm').\n\n The desired density units are specified as 'lb/ft**3', 'slug/ft**3' or\n 'kg/m**3'.\n\n If the units are not specified, the units in default_units.py are used.\n\n Examples:\n\n Calculate the density in lb / ft cubed at 7,500 (default altitude units):\n >>> alt2density(7500)\n 0.061046199847730374\n\n Calculate the density in slugs / ft cubed at 5,000 (default altitude units):\n >>> alt2density(5000, density_units = 'slug/ft**3')\n 0.0020480982157718704\n\n Calculate the density in kg / m cubed at 0 (default altitude units:\n >>> alt2density(0, density_units = 'kg/m**3')\n 1.2250000000000001\n\n Calculate the density in kg / m cubed at 81,000 m:\n >>> alt2density(81000, density_units = 'kg/m**3', alt_units = 'm')\n 1.3320480184052337e-05\n \"\"\"\n\n # function tested in tests/test_std_atm.py\n\n # get density in kg/m**3\n\n density = Rho0 * alt2density_ratio(H, alt_units)\n return U.density_conv(density, from_units=\"kg/m**3\", to_units=density_units)\n\n\n# #############################################################################\n#\n# Density to altitude and density ratio to altitude\n#\n# #############################################################################\n\n\ndef _density2alt_gradient(\n Rho,\n Rhob,\n Hb,\n Tb,\n L,\n):\n\n return Hb + (Tb / L) * ((Rho / Rhob) ** (-1 / ((1000 * g) / (Rd * L) + 1)) - 1)\n\n\ndef _density2alt_isothermal(\n Rho,\n Rhob,\n Hb,\n Tb,\n):\n\n return Hb - ((Rd * Tb) * M.log(Rho / Rhob)) / (1000 * g)\n\n\ndef density2alt(Rho, density_units=default_density_units, alt_units=default_alt_units):\n \"\"\"\n Return the altitude corresponding to the specified density, with\n density in 'lb/ft**3', 'slug/ft**3' or 'kg/m**3'.\n\n The altitude is specified in feet ('ft'), metres ('m'), statute miles,\n ('sm') or nautical miles ('nm').\n\n If the units are not specified, the units in default_units.py are used.\n\n Examples:\n\n Calculate the altitude in default altitude units where the density is\n 0.056475 in default density units:\n >>> density2alt(.056475)\n 9999.8040934937271\n\n Calculate the altitude in metres where the density is 0.018012 kg / m\n cubed:\n >>> density2alt(.018012, alt_units = 'm', density_units = 'kg/m**3')\n 29999.978688508152\n \"\"\"\n\n # function tested in tests/test_std_atm.py\n\n Rho = U.density_conv(Rho, from_units=density_units, to_units=\"kg/m**3\")\n\n if Rho > Rho11:\n H = _density2alt_gradient(Rho, Rho0, 0, T0, L0)\n elif Rho > Rho20:\n H = _density2alt_isothermal(Rho, Rho11, 11, T11)\n elif Rho > Rho32:\n H = _density2alt_gradient(Rho, Rho20, 20, T20, L20)\n elif Rho > Rho47:\n H = _density2alt_gradient(Rho, Rho32, 32, T32, L32)\n elif Rho > Rho51:\n H = _density2alt_isothermal(Rho, Rho47, 47, T47)\n elif Rho > Rho71:\n H = _density2alt_gradient(Rho, Rho51, 51, T51, L51)\n else:\n H = _density2alt_gradient(Rho, Rho71, 71, T71, L71)\n\n if H > 84.852:\n raise ValueError(\n \"This function is only implemented for altitudes of 84.852 km and below.\"\n )\n\n return U.len_conv(H, from_units=\"km\", to_units=alt_units)\n\n\ndef density_ratio2alt(DR, alt_units=default_alt_units):\n \"\"\"\n Return the altitude for the specified density ratio. The altitude is in\n feet ('ft'), metres ('m'), statute miles, ('sm') or nautical miles\n ('nm').\n\n If the units are not specified, the units in default_units.py are used.\n\n Examples:\n\n Calculate the altitude in default altitude units where the density ratio is\n 1:\n >>> density_ratio2alt(1)\n 0.0\n\n Calculate the altitude in feet where the density ratio is 0.5:\n >>> density_ratio2alt(.5)\n 21859.50324995652\n\n Calculate the altitude in km where the density ratio is 0.1\n >>> density_ratio2alt(.1, alt_units = 'km')\n 17.9048674520646\n \"\"\"\n\n # function tested in tests/test_std_atm.py\n\n D = DR * Rho0\n return density2alt(D, alt_units=alt_units, density_units=\"kg/m**3\")\n\n\n# #############################################################################\n#\n# Density Altitude\n#\n# #############################################################################\n\n\ndef density_alt(\n H,\n T,\n alt_setting=P0,\n DP=\"FALSE\",\n RH=0.0,\n alt_units=default_alt_units,\n temp_units=default_temp_units,\n):\n \"\"\"\n Return density altitude, given the pressure altitude and the\n temperature with altitudes in units of feet ('ft'), metres ('m'),\n statute miles, ('sm') or nautical miles ('nm'), and temperature in units\n of deg C, F, K or R ('C', 'F', 'K' or 'R').\n\n Mandatory parametres:\n H = altitude\n T = temperature\n\n Optional parametres:\n alt_setting = altimeter setting (defaults to 29.9213 if not provided\n DP = dew point\n RH = relative humidity\n alt_units = units for the altitude. 'ft', 'm', or 'km'.\n temp_units = units for the temperature and dew point. 'C', 'F', 'K'\n or 'R'.\n\n The altimeter setting units are assumed to be inches of HG, unless the\n value is greater than 35. In this case the units are assumed to be mb.\n\n If the dew point or relative humidity are not specified, the air is\n assumed to be completely dry. If both the dew point and relative humidity\n are specified, the relative humidity value is ignored.\n\n If the units are not specified, the units in default_units.py are used.\n\n The method is from: http://wahiduddin.net/calc/density_altitude.htm\n\n Examples:\n\n Calculate the density altitude in default altitude units for a pressure\n altitude of 7000 default altitude units and a temperature of 15 deg\n (default temperature units). The altimeter setting is not specified, so it\n defaults to standard pressure of 29.9213 in HG or 1013.25 mb:\n >>> density_alt(7000, 15)\n 8595.3465863232504\n\n Calculate the density altitude in default altitude units for a pressure\n altitude of 7000 default altitude units and a temperature of 85 deg F.\n The altimeter setting is not specified, so it defaults to standard pressure\n of 29.9213 in HG or 1013.25 mb. The dew point and relative humidity are\n not specified, so the air is assumed to be dry:\n >>> density_alt(7000, 85, temp_units = 'F')\n 10159.10696106757\n\n Calculate the density altitude in default altitude units for a pressure\n altitude of 7000 default altitude units, an altimeter setting of 29.80 and\n a temperature of 85 deg F and a dew point of 55 deg F:\n >>> density_alt(7000, 85, 29.80, 55, temp_units = 'F')\n 10522.776013011618\n\n Calculate the density altitude in metres for a pressure altitude of\n 2000 m, an altimeter setting of 1010 mb, a temperature of 15 deg (default\n temperature units) and a relative humidity of 50%:\n >>> density_alt(2000, 15, 1010, alt_units = 'm', RH = 0.5)\n 2529.8230634449737\n\n The dew point may be specified in one of two ways: as the fourth\n argument on the command line, or via the keyword argument DP.\n >>> density_alt(2000, 15, 1010, alt_units = 'm', DP = 5)\n 2530.7528237990618\n\n The relative humidity must be in the range of 0 to 1:\n >>> density_alt(2000, 15, 1010, alt_units = 'm', RH = 1.1)\n Traceback (most recent call last):\n File '', line 1, in ?\n File 'std_atm.py', line 533, in density_alt\n raise ValueError, 'The relative humidity must be in the range of 0 to 1.'\n ValueError: The relative humidity must be in the range of 0 to 1.\n \"\"\"\n\n Rv = 461.495 # gas constant for water vapour\n\n # saturated vapour pressure\n\n if DP == \"FALSE\" and RH == 0:\n Pv = 0\n else:\n Pv = sat_press(T, DP, RH, temp_units, press_units=\"pa\")\n\n # dry air pressure\n\n Pd = dry_press(\n H, Pv, alt_setting=alt_setting, alt_units=alt_units, press_units=\"pa\"\n )\n\n T = U.temp_conv(T, from_units=temp_units, to_units=\"K\")\n D = Pd / (Rd * T) + Pv / (Rv * T)\n\n DR = D / Rho0\n\n return density_ratio2alt(DR, alt_units)\n\n\ndef _sat_press(T):\n \"\"\"\n Return the saturation pressure in mb of the water vapour, given\n temperature in deg C. Equation from:\n http://wahiduddin.net/calc/density_altitude.htm\n \"\"\"\n\n eso = 6.1078\n c0 = 0.99999683\n c1 = -0.90826951e-2\n c2 = 0.78736169e-4\n c3 = -0.61117958e-6\n c4 = 0.43884187e-8\n c5 = -0.29883885e-10\n c6 = 0.21874425e-12\n c7 = -0.17892321e-14\n c8 = 0.11112018e-16\n c9 = -0.30994571e-19\n\n p = c0 + T * (\n c1\n + T\n * (\n c2\n + T * (c3 + T * (c4 + T * (c5 + T * (c6 + T * (c7 + T * (c8 + T * c9))))))\n )\n )\n sat_press = eso / p**8\n return sat_press\n\n\ndef sat_press(\n T=\"FALSE\",\n DP=\"FALSE\",\n RH=0.0,\n temp_units=default_temp_units,\n press_units=default_press_units,\n):\n \"\"\"\n Return the saturated vapour pressure of water. Either the dew point, or\n the temperature and the relative humidity must be specified. If both the\n dew point and relative humidity are specified, the relative humidity value\n is ignored.\n\n If the temperature and dew point are both specified, the dew point cannot\n be greater than the temperature:\n\n If the units are not specified, the units in default_units.py are used.\n\n >>> sat_press(T=10, DP=11)\n Traceback (most recent call last):\n File '', line 1, in \n File 'std_atm.py', line 795, in sat_press\n raise ValueError, 'The dew point cannot be greater than the temperature.'\n ValueError: The dew point cannot be greater than the temperature.\n\n Dew point is 11 deg (default temperature units). Find the water vapour\n pressure in default pressure units:\n >>> sat_press(DP=11)\n 0.38741015927568667\n\n Dew point is 65 deg F. Find the water vapour pressure in default pressure units:\n >>> sat_press(DP=65, temp_units = 'F')\n 0.62207710701956165\n\n Dew point is 212 deg F (the boiling point of water at sea level).\n Find the water vapour pressure in lb per sq. inch:\n >>> sat_press(DP=212, temp_units = 'F', press_units = 'psi')\n 14.696764873564959\n\n Temperature is 30 deg C. Find the water vapour pressure in default pressure units:\n for 50% relative humidity:\n >>> sat_press(T=30, RH = 0.5)\n 0.62647666996057927\n \"\"\"\n\n if DP != \"FALSE\":\n\n # use dew point method\n\n if T != \"FALSE\":\n if DP > T:\n raise ValueError(\n \"The dew point cannot be greater than the temperature.\"\n )\n\n DP = U.temp_conv(DP, from_units=temp_units, to_units=\"C\")\n\n # calculate vapour pressure\n\n Pv = _sat_press(DP) * 100\n else:\n\n if RH == \"FALSE\":\n raise ValueError(\n \"Either DP (dew point) or RH (relative humidity) must be specified.\"\n )\n\n # relative humidity is specified\n # confirm relative humidity is in range\n\n if RH < 0 or RH > 1:\n raise ValueError(\"The relative humidity must be in the range of 0 to 1.\")\n\n if T == \"FALSE\":\n raise ValueError(\n \"If the relative humidity is specified, the temperature must also be specified.\"\n )\n\n T = U.temp_conv(T, from_units=temp_units, to_units=\"C\")\n\n Pv = _sat_press(T) * 100\n Pv *= RH\n\n Pv = U.press_conv(Pv, from_units=\"pa\", to_units=press_units)\n\n return Pv\n\n\ndef dry_press(\n H,\n Pv,\n alt_setting=P0,\n alt_units=default_alt_units,\n press_units=default_press_units,\n):\n \"\"\"\n Returns dry air pressure, i.e. the total air pressure, less the water\n vapour pressure.\n \"\"\"\n\n HP = pressure_alt(H, alt_setting, alt_units=alt_units)\n P = alt2press(HP, press_units=press_units, alt_units=alt_units)\n Pd = P - Pv\n\n return Pd\n\n\ndef density_alt2temp(\n density_alt_seek,\n press_alt,\n alt_units=default_alt_units,\n temp_units=default_temp_units,\n):\n \"\"\"\n Return temperature to achieve a desired density altitude.\n\n If the units are not specified, the units in default_units.py are used.\n \"\"\"\n\n low = -100 # initial lower guess\n high = 100 # initial upper guess\n\n # confirm initial low and high are OK:\n\n da_low = density_alt(press_alt, low, alt_units=alt_units)\n if da_low > density_alt_seek:\n raise ValueError(\"Initial low guess too high.\")\n\n da_high = density_alt(press_alt, high, alt_units=alt_units)\n if da_high < density_alt_seek:\n raise ValueError(\"Initial high guess too low.\")\n\n guess = (low + high) / 2.0\n da_guess = density_alt(press_alt, guess, alt_units=alt_units)\n\n # keep iterating until da is within 1 ft of desired value\n\n while M.fabs(da_guess - density_alt_seek) > 1:\n if da_guess > density_alt_seek:\n high = guess\n else:\n low = guess\n\n guess = (low + high) / 2.0\n da_guess = density_alt(press_alt, guess, alt_units=alt_units)\n\n guess = U.temp_conv(guess, from_units=\"C\", to_units=temp_units)\n\n return guess\n\n\ndef density_alt_table(\n density_alt_seek,\n alt_range=2000,\n alt_inc=100,\n alt_units=default_alt_units,\n temp_units=default_temp_units,\n multi_units=False,\n file=\"\",\n format=\"text\",\n):\n \"\"\"\n Return a text or html table of required temperature vs pressure altitude.\n\n If the units are not specified, the units in default_units.py are used.\n \"\"\"\n\n line_buffer = []\n if format == \"text\":\n line_buffer.append(\"Pressure altitudes and temperatures for a density \")\n line_buffer.append(\"altitude of \" + str(density_alt_seek) + \" \" + alt_units)\n line_buffer.append(\"(assuming dry air)\\n\")\n if multi_units:\n line_buffer.append(\" Pressure Temp Temp\")\n line_buffer.append(\" Altitude\")\n line_buffer.append(\" (\" + alt_units + \") (deg C) (deg F)\")\n else:\n line_buffer.append(\" Pressure Temp\")\n line_buffer.append(\" Altitude\")\n line_buffer.append(\" (\" + alt_units + \") (deg \" + temp_units + \")\")\n elif format == \"html\":\n print(\"creating html\")\n else:\n raise ValueError('Invalid format. Must be either \"text\" or \"html\"')\n\n if multi_units:\n for alt in range(\n max(density_alt_seek - alt_range / 2.0, 0),\n density_alt_seek + alt_range / 2.0 + alt_inc,\n alt_inc,\n ):\n temp_c = density_alt2temp(density_alt_seek, alt, alt_units=alt_units)\n temp_f = U.temp_conv(temp_c, from_units=\"C\", to_units=\"F\")\n alt_str = L.format(\"%.*f\", (0, alt), grouping=True)\n temp_c_str = \"%.1f\" % temp_c\n temp_f_str = \"%.1f\" % temp_f\n line_buffer.append(\n alt_str.rjust(6) + temp_c_str.rjust(11) + temp_f_str.rjust(10)\n )\n else:\n for alt in range(\n max(density_alt_seek - alt_range / 2.0, 0),\n density_alt_seek + alt_range / 2.0 + alt_inc,\n alt_inc,\n ):\n alt_str = L.format(\"%.*f\", (0, alt), grouping=True)\n temp_str = \"%.1f\" % density_alt2temp(\n density_alt_seek, alt, temp_units=temp_units, alt_units=alt_units\n )\n line_buffer.append(alt_str.rjust(6) + temp_str.rjust(11))\n\n if file != \"\":\n OUT = open(file, \"w\")\n for line in line_buffer:\n OUT.write(line + \"\\n\")\n\n print(\"file selected\")\n else:\n return \"\\n\".join(line_buffer)\n\n\n# #############################################################################\n#\n# Pressure to altitude and pressure ratio to altitude\n#\n# #############################################################################\n\n\ndef _press2alt_gradient(\n P,\n Pb,\n Hb,\n Tb,\n L,\n):\n\n return Hb + (Tb / L) * ((P / Pb) ** (((-1 * Rd) * L) / (1000 * g)) - 1)\n\n\ndef _press2alt_isothermal(\n P,\n Pb,\n Hb,\n Tb,\n):\n\n return Hb - ((Rd * Tb) * M.log(P / Pb)) / (1000 * g)\n\n\ndef press2alt(P, press_units=default_press_units, alt_units=default_alt_units):\n \"\"\"\n Return the altitude corresponding to the specified pressure, with\n pressure in inches of HG, mm of HG, psi, psf (lb per sq. ft), pa, hpa or\n mb.\n\n The altitude is in units of feet ('ft'), metres ('m'), statute miles,\n ('sm') or nautical miles ('nm')\n\n If the units are not specified, the units in default_units.py are used.\n\n Examples:\n\n Calculate the pressure altitude in feet for a pressure of 31.0185 inches\n of HG:\n >>> press2alt(31.0185)\n -999.98992888235091\n\n Calculate the pressure altitude in feet for a pressure of\n 1455.33 lb sq. ft:\n >>> press2alt(1455.33, press_units = 'psf')\n 10000.002466564831\n\n Calculate the pressure altitude in metres for a pressure of\n 90.3415 mm HG:\n >>> press2alt(90.3415, press_units = 'mm HG', alt_units = 'm')\n 15000.025465320754\n\n Calculate the pressure altitude in metres for a pressure of\n 1171.86 pascal:\n >>> press2alt(1171.86, press_units = 'pa', alt_units = 'm')\n 30000.029510365184\n \"\"\"\n\n # function tested in tests/test_std_atm.py\n\n P = U.press_conv(P, from_units=press_units, to_units=\"in HG\")\n\n if P > P11:\n H = _press2alt_gradient(P, P0, 0, T0, L0)\n elif P > P20:\n H = _press2alt_isothermal(P, P11, 11, T11)\n elif P > P32:\n H = _press2alt_gradient(P, P20, 20, T20, L20)\n elif P > P47:\n H = _press2alt_gradient(P, P32, 32, T32, L32)\n elif P > P51:\n H = _press2alt_isothermal(P, P47, 47, T47)\n elif P > P71:\n H = _press2alt_gradient(P, P51, 51, T51, L51)\n else:\n H = _press2alt_gradient(P, P71, 71, T71, L71)\n\n if H > 84.852:\n raise ValueError(\n \"This function is only implemented for altitudes of 84.852 km and below.\"\n )\n\n return U.len_conv(H, from_units=\"km\", to_units=alt_units)\n\n\ndef press_ratio2alt(PR, alt_units=default_alt_units):\n \"\"\"\n Return the pressure ratio for the specified altitude. The altitude is\n specified in feet ('ft'), metres ('m'), statute miles, ('sm') or\n nautical miles ('nm').\n\n If the units are not specified, the units in default_units.py are used.\n\n Examples:\n\n Calculate the altitude in feet where the pressure ratio is 0.5:\n >>> press_ratio2alt(.5)\n 17969.990746028907\n\n Calculate the altitude in metres where the pressure ratio is 0.1:\n >>> press_ratio2alt(.1, alt_units = 'm')\n 16096.249927559489\n \"\"\"\n\n # function tested in tests/test_std_atm.py\n\n P = PR * P0\n return press2alt(P, alt_units=alt_units)\n\n\n# #############################################################################\n#\n# Temperature to speed of sound\n#\n# #############################################################################\n\n\ndef temp2speed_of_sound(\n temp, temp_units=default_temp_units, speed_units=default_speed_units\n):\n \"\"\"\n Return the speed of sound, given the air temperature.\n\n The temperature units may be deg C, F, K or R ('C', 'F', 'K' or 'R').\n\n The speed units may be 'kt', 'mph', 'km/h', 'm/s' and 'ft/s'.\n\n If the units are not specified, the units in default_units.py are used.\n\n Examples:\n\n Determine speed of sound in knots at 15 deg (default temperature units):\n >>> temp2speed_of_sound(15)\n 661.47882487301808\n\n Determine speed of sound in mph at 120 deg F:\n >>> temp2speed_of_sound(120, speed_units = 'mph', temp_units = 'F')\n 804.73500154991291\n \"\"\"\n\n # function tested in tests/test_std_atm.py\n\n temp = U.temp_conv(temp, from_units=temp_units, to_units=\"K\")\n\n speed_of_sound = M.sqrt((1.4 * Rd) * temp)\n speed_of_sound = U.speed_conv(\n speed_of_sound, from_units=\"m/s\", to_units=speed_units\n )\n\n return speed_of_sound\n\n\nif __name__ == \"__main__\":\n\n # run doctest to check the validity of the examples in the doc strings.\n\n import doctest\n import sys\n\n doctest.testmod(sys.modules[__name__])\n","repo_name":"airbus/scikit-decide","sub_path":"skdecide/hub/domain/flight_planning/weather_interpolator/weather_tools/std_atm.py","file_name":"std_atm.py","file_ext":"py","file_size_in_byte":35015,"program_lang":"python","lang":"en","doc_type":"code","stars":107,"dataset":"github-code","pt":"76"} +{"seq_id":"9839462511","text":"import logging\n\nimport numpy as np\n\nfrom easyfl.simulation.mobile_ratio import MOBILE_RATIO\nfrom easyfl.datasets.simulation import equal_division\n\nlogger = logging.getLogger(__name__)\n\nSIMULATE_ISO = \"iso\" # isometric sleep time distribution among selected clients\nSIMULATE_DIR = \"dir\" # use symmetric dirichlet process to sample sleep time heterogenous\nSIMULATE_REAL = \"real\" # use real speed ratio of main stream smartphones to simulate sleep time heterogenous\n\n\ndef assign_value_to_group(groups, values):\n assert len(groups) == len(values)\n result = []\n for i in range(len(groups)):\n result.extend([values[i]] * len(groups[i]))\n return result\n\n\ndef sample_real_ratio(num_values):\n value_pool = list(MOBILE_RATIO.values())\n idxs = np.random.randint(0, len(value_pool), size=num_values)\n return np.array([value_pool[i] for i in idxs]).astype(float)\n\n\ndef resource_hetero_simulation(fraction, hetero_type, sleep_group_num, level, total_time, num_clients):\n \"\"\"Simulated resource heterogeneous by add sleeping time to clients.\n\n Args:\n fraction (float): The fraction of clients attending heterogeneous simulation.\n hetero_type (str): The type of heterogeneous simulation, options: iso, dir or real.\n sleep_group_num (int): The number of groups with different sleep time.\n level (int): The level of heterogeneous (0-5), 0 means no heterogeneous among clients.\n total_time (float): The total sleep time of all clients.\n num_clients (int): The total number of clients.\n\n Returns:\n list[float]: A list of sleep time with distribution according to heterogeneous type.\n \"\"\"\n sleep_clients = int(fraction * num_clients)\n unsleep_clients = [0] * (num_clients - sleep_clients)\n sleep_group_num = sleep_group_num\n if sleep_group_num > sleep_clients:\n logger.warning(\"sleep_group_num {} is more than sleep_clients number {}, \\\n so we set sleep_group_num to sleep_clients\".format(sleep_group_num, sleep_clients))\n sleep_group_num = sleep_clients\n groups, _ = equal_division(sleep_group_num, np.arange(sleep_clients))\n if level == 0:\n distribution = np.array([1] * sleep_clients)\n elif hetero_type == SIMULATE_DIR:\n alpha = 1 / (level * level)\n values = np.random.dirichlet(np.repeat(alpha, sleep_group_num))\n distribution = assign_value_to_group(groups, values)\n elif hetero_type == SIMULATE_ISO:\n if level > 5:\n raise ValueError(\"level cannot be more than 5\")\n begin = 0.5 - level * 0.1\n end = 0.5 + level * 0.1\n values = np.arange(begin, end, (end - begin) / sleep_group_num)\n distribution = assign_value_to_group(groups, values)\n elif hetero_type == SIMULATE_REAL:\n values = sample_real_ratio(sleep_group_num)\n distribution = assign_value_to_group(groups, values)\n else:\n raise ValueError(\"sleep type not supported, please use either dir or iso\")\n distribution += unsleep_clients\n np.random.shuffle(distribution)\n return distribution / sum(distribution) * total_time\n","repo_name":"EasyFL-AI/EasyFL","sub_path":"easyfl/simulation/system_hetero.py","file_name":"system_hetero.py","file_ext":"py","file_size_in_byte":3104,"program_lang":"python","lang":"en","doc_type":"code","stars":256,"dataset":"github-code","pt":"76"} +{"seq_id":"72921858804","text":"# 문제 링크: https://www.acmicpc.net/problem/1874\n\nimport sys\ninput = sys.stdin.readline\n\nn = int(input())\nnums = [int(input()) for _ in range(n)]\n\n\nstack, ops, index = [], [], 0\nfor i in range(1, n + 1):\n stack.append(i)\n ops.append('+')\n\n while stack and stack[-1] == nums[index]:\n stack.pop()\n ops.append('-')\n index += 1\n\n\nprint('\\n'.join(ops) if not stack else 'NO')","repo_name":"jamesujeon/coding-problem-solutions","sub_path":"baekjoon/python 3/1874.py","file_name":"1874.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"17866368713","text":"import os\nimport csv\nimport re\nimport nltk\nfrom nltk.corpus import stopwords\nimport pandas as pd\nfrom pandas import DataFrame\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.model_selection import train_test_split, cross_val_score\nfrom sklearn import metrics\nfrom sklearn.metrics import precision_score, recall_score\nfrom sklearn.preprocessing import MultiLabelBinarizer\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom nltk.stem import WordNetLemmatizer\nimport matplotlib.pyplot as plt\nfrom wordcloud import WordCloud\n\n\n#including DFKI\ndata1 = pd.read_csv(\"DFKI/P07_1001-50.csv\", sep=\"\\t\", index_col=False, encoding='latin-1', low_memory=False)\ndf1 = DataFrame(data1)\ndf1 = df1[df1.label != 'Neutral'] #removes rows with Netral label\nx1 = df1.data\ny1 = df1.label\n\ndata2 = pd.read_csv(\"DFKI/P08_1009-50.csv\", sep=\"\\t\", index_col=False, encoding='latin-1', low_memory=False)\ndf2 = DataFrame(data2)\ndf2 = df2[df2.label != 'Neutral']\nx2 = df2.data\ny2 = df2.label\n\ndata3 = pd.read_csv(\"DFKI/P08_2001-30.csv\", sep=\"\\t\", index_col=False, encoding='latin-1', low_memory=False)\ndf3 = DataFrame(data3)\ndf3 = df3[df3.label != 'Neutral']\nx3 = df3.data\ny3 = df3.label\n\n# including IMS\ndata4 = pd.read_csv(\"corpus2.csv\", sep=\",\", index_col=False, encoding='latin-1', low_memory=False)\ndf4 = DataFrame(data4)\nx4 = df4.data\ny4 = df4.label\n\nframes = [df1, df2, df3, df4]\ndf = pd.concat(frames, ignore_index=True)\n\n# hedging words to list\nwith open('hedges.csv', 'r') as f:\n reader = csv.reader(f)\n hedges = list(reader)\n# hedging (list of list) to list\nhedges_list = [item for sublist in hedges for item in sublist]\nparagraphs = df['data']\n\n# drawing wordcloud\ndef wordcloud_draw(data, color='white'):\n words = ' '.join(data)\n # cleaned_word = \" \".join([word for word in words.split()\n # if 'http' not in word\n # and not word.startswith('@')\n # and not word.startswith('#')\n # and word != 'RT'\n # ])\n wordcloud = WordCloud(background_color=color,\n width=2500,\n height=2000\n ).generate(words)\n plt.figure(1, figsize=(13, 13))\n plt.imshow(wordcloud)\n plt.axis('off')\n plt.show()\n #plt.savefig('word_cloud') #uncomment to save picture\n\n# uncomment next 2 lines to generate pic\n# print(\"Hedging Cues\")\n# wordcloud_draw(hedges_list)\n\n# preprocessing list of paragraphs\n# nltk.download('wordnet')\nlemmatizer = WordNetLemmatizer()\n\ndef lemmatize(word):\n lemmatizer = WordNetLemmatizer()\n return lemmatizer.lemmatize(word=word)\n\n# for sent in paragraphs:\nparagraphs = paragraphs.str.replace('[^a-zA-Z0-9-_*.]', ' ')\npre_para = [\" \".join([lemmatize(word) for word in sentence.split(\" \")]) for sentence in paragraphs]\n\n#replacing list of list to list\n\nlabel_list = df['label'].values.tolist()\n\n# joing lists\ncomplete_list = []\nfor sent1, sent2 in zip(pre_para, label_list):\n complete_list.append([sent1, sent2])\n\n# removing repeated things\ndef unique(seq):\n # order preserving\n checked = []\n for e in seq:\n if e not in checked:\n checked.append(e)\n return checked\n\nunique_list = unique(complete_list)\n\n# getting 179 positives and negatives\nlist_179 = []\nj = 0\nk = 0\nfor i in unique_list:\n if i[1] == 'Negative' and j < 179:\n list_179.append(i)\n j = j + 1\n if i[1] == 'Positive' and k < 179:\n list_179.append(i)\n k = k + 1\n# getting only sentences from list_179\nlist_358 = [item[0] for item in list_179]\n\n\n# implementing hedge cue detection\nhedges_bool = []\nfor word in hedges_list:\n for sent in list_358:\n found = False\n found_hedge_false = False\n # if word in sent:\n for i in hedges_bool:\n if i[0] == sent and i[1] == 'hedge_true': # checks if true is repeated\n found = True\n break\n if i[0] == sent and i[1] == 'hedge_false': # checks if false is repeated\n found_hedge_false = True\n if found is True: # if hedge_true\n break\n if sent.find(word) != -1 and found_hedge_false is True: # checks two idexes if same\n hedges_bool.remove([sent, 'hedge_false'])\n hedges_bool.append([sent, 'hedge_true'])\n if found_hedge_false is True: # it can become true in further steps\n continue\n else:\n hedges_bool.append([sent, 'hedge_false'])\n\n# x and y\nx_data = []\ny_data = []\nfor sent1, sent2 in zip(label_list, hedges_bool):\n x_data.append(sent2[0])\n y_data.append([sent1, sent2[1]])\n\n# classification\n\ndef labelEncoding(y_data):\n mlb = MultiLabelBinarizer()\n y_binarized = mlb.fit_transform(y_data)\n return y_binarized\n\n\ndef tfidfVectorizer(x_data):\n stopset = stopwords.words('english')\n vect = TfidfVectorizer(analyzer='word', encoding='utf-8', min_df = 0, ngram_range=(1, 2), lowercase = True, strip_accents='ascii', stop_words = stopset)\n X_vec = vect.fit_transform(x_data)\n return X_vec\n\n\nX_vec = tfidfVectorizer(x_data)\ny_encoded = labelEncoding(y_data)\n\n\ndef splitTestTrain(X_vec, y_encoded):\n X_train, X_test, y_train, y_test = train_test_split(X_vec, y_encoded,\ntest_size=0.2, random_state=0)\n return X_train, X_test, y_train, y_test\n\nX_train, X_test, y_train, y_test = splitTestTrain(X_vec, y_encoded)\n\ndef applyDecisionTreeClassifier(X_train, y_train, X_test, y_test):\n # Model Training: DecisionTreeClassifier\n DT_classifier = DecisionTreeClassifier(random_state=0)\n DT_classifier.fit(X_train, y_train)\n print(DT_classifier)\n model_accuracies = cross_val_score(estimator=DT_classifier,\n X=X_train, y=y_train, cv=10)\n print(\"Model Accuracies Mean\", model_accuracies.mean()*100)\n print(\"Model Accuracies Standard Devision\", model_accuracies.std()*100)\n # Model Testing: DTs\n y_pred = DT_classifier.predict(X_test)\n metrics.confusion_matrix(y_test.argmax(axis=1), y_pred.argmax(axis=1))\n test_accuracy = metrics.accuracy_score(y_test, y_pred)\n precision_DT = precision_score(y_test, y_pred, average='weighted')\n recall_DT = recall_score(y_test, y_pred, average='weighted')\n f_DT = 2*(precision_DT * recall_DT) / (precision_DT + recall_DT)\n print(\"Decision Tree Classifier Test Accuracy: \", test_accuracy*100)\n print(\"Decision Tree Classifier Test Precision: \", precision_DT*100)\n print(\"Decision Tree Classifier Test Recall: \", recall_DT*100)\n print(\"Decision Tree Classifier Test F measure: \", f_DT*100)\n return test_accuracy, precision_DT, recall_DT, f_DT\n\naccuracy, precision, recall, f1_score = applyDecisionTreeClassifier(X_train, y_train, X_test, y_test)\nprint(accuracy)\n\ndef applyKNeighborsClassifier(X_train, y_train, X_test, y_test):\n # Model Training: KNN\n knn_classifier = KNeighborsClassifier(n_neighbors=3)\n knn_classifier.fit(X_train, y_train)\n print(knn_classifier)\n model_accuracies = cross_val_score(estimator=knn_classifier,\n X=X_train, y=y_train, cv=10)\n print(\"Model Accuracies Mean\", model_accuracies.mean()*100)\n print(\"Model Accuracies Standard Devision\", model_accuracies.std()*100)\n # Model Testing: Knn\n y_pred = knn_classifier.predict(X_test)\n metrics.confusion_matrix(y_test.argmax(axis=1), y_pred.argmax(axis=1))\n test_accuracy = metrics.accuracy_score(y_test, y_pred)\n precision_KNN = precision_score(y_test, y_pred, average='weighted')\n recall_KNN = recall_score(y_test, y_pred, average='weighted')\n f_KNN = 2*(precision_KNN * recall_KNN) / (precision_KNN + recall_KNN)\n print(\"KNNs Test Accuracy: \", test_accuracy*100)\n print(\"KNNs Test Precision: \", precision_KNN*100)\n print(\"KNNs Test Recall: \", recall_KNN*100)\n print(\"KNNs Test F measure: \", f_KNN*100)\n return test_accuracy, precision_KNN, recall_KNN, f_KNN\n\naccuracy, precision, recall, f1_score = applyKNeighborsClassifier(X_train, y_train, X_test, y_test)\nprint(accuracy)","repo_name":"aatif1/Classification_of_Scientific_Citations","sub_path":"with_hedging.py","file_name":"with_hedging.py","file_ext":"py","file_size_in_byte":8123,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"25091197471","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('places', '0003_auto_20141203_1910'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='place',\n name='recommandTime',\n field=models.IntegerField(max_length=40, verbose_name=b'\\xe6\\x8e\\xa8\\xe8\\x8d\\x90\\xe6\\x97\\xb6\\xe9\\x95\\xbf'),\n preserve_default=True,\n ),\n ]\n","repo_name":"curlylrt/testsite","sub_path":"places/migrations/0004_auto_20141207_2007.py","file_name":"0004_auto_20141207_2007.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"39080496738","text":"from flask import Flask, request, send_from_directory\nfrom flask_restful import Api, Resource\nimport json\nimport os\nfrom flask_cors import CORS\nfrom models import db, Article\n\nbasedir = os.path.dirname(os.path.abspath(__file__))\nSQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db')\napp = Flask(__name__)\napp.config.update({\n 'SQLALCHEMY_TRACK_MODIFICATIONS': True,\n \"SQLALCHEMY_DATABASE_URI\": SQLALCHEMY_DATABASE_URI,\n})\napi = Api(app)\ncors = CORS(app)\ndb.init_app(app)\nIMAGE_PATH = os.path.join(basedir, 'image')\n\ndef serializer(l):\n ret = []\n for row in l:\n ret.append(json.loads(row.serialize()))\n return ret \n\nclass Picture(Resource):\n def get(self, name):\n return send_from_directory(IMAGE_PATH, name)\n\nclass ArticleList(Resource):\n def get_articles(self):\n articles = Article.query.all()\n return articles \n\n def get(self):\n articles = self.get_articles()\n return serializer(articles)\n\n def post(self):\n r_json = request.get_json() \n title = r_json['title']\n image = r_json['image']\n category = r_json['category']\n content = r_json['content']\n new_article = Article(title, image, category, content)\n db.session.add(new_article)\n db.session.commit()\n return \"write successfully\"\n\n def put(self):\n r_json = request.get_json()\n _id = r_json['id']\n title = r_json['title']\n image = r_json['image']\n category = r_json['category']\n content = r_json['content']\n article = Article.query.filter_by(id=_id).first()\n if not article:\n return \"article[:{}] is not exists\".format(_id)\n article.title = title\n article.image = image\n article.content = content\n db.session.commit()\n return \"update successfully\"\n\n def delete(self):\n r_json = request.get_json()\n _id = r_json['id']\n article = Article.query.filter_by(id=_id).first()\n if not article:\n return \"article[:{}] is not exists\".format(_id)\n db.session.delete(article)\n db.session.commit()\n return \"delete successfully\"\n\napi.add_resource(ArticleList, '/api/articles')\napi.add_resource(Picture, '/api/pictures/')\n\nif __name__ == '__main__':\n with app.app_context():\n db.create_all()\n app.run(host='0.0.0.0', port=5000, debug=True)\n\n","repo_name":"sisobus/WebStudio2019","sub_path":"projects/20151172/api/boilerplate.py","file_name":"boilerplate.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"76"} +{"seq_id":"21078244851","text":"import json\nimport random\nimport os\n\n\ndef read_jsonl(file_path, sample_rate=1.0):\n assert os.path.exists(file_path)\n with open(file_path) as r:\n for line in r:\n if random.random() <= sample_rate:\n yield json.loads(line)\n\n\ndef write_jsonl(records, file_path):\n with open(file_path, \"w\") as w:\n for r in records:\n w.write(json.dumps(r, ensure_ascii=False).strip() + \"\\n\")\n\n\ndef read_lines(file_path):\n lines = list()\n with open(file_path, \"r\") as r:\n for line in r:\n lines.append(line.strip())\n return lines\n","repo_name":"IlyaGusev/rudetox","sub_path":"rudetox/util/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"76"} +{"seq_id":"40570813369","text":"import altair_saver\nimport matplotlib.pyplot as plt\nimport os\nimport numpy as np\nimport pandas as pd\nimport glob\n\nfrom tools.paperv2.utils import *\n\nSCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))\n\nRESULTS_DIR = \"/sdb/paperv2_results/\"\n\n\ndef rand_jitter(arr):\n stdev = .005 * (max(arr) - min(arr))\n return arr + np.random.randn(len(arr)) * stdev\n\n\ndef filter(df, **kwargs):\n bool_index = None\n for key, value in kwargs.items():\n if isinstance(value, list):\n _bool_index = df[key].isin(value)\n else:\n _bool_index = df[key] == value\n if bool_index is None:\n bool_index = _bool_index\n else:\n bool_index = bool_index & _bool_index\n return df[bool_index]\n\n\ndef load_dlmc_df(subdir, nthreads=None, bcols=None):\n # assert nthreads or bcols\n\n if nthreads is not None and bcols is not None:\n return pd.read_csv(RESULTS_DIR + '/cache/' + subdir + f'/dlmc_bcols_{bcols}_nthreads_{nthreads}.csv')\n elif nthreads is not None:\n return pd.read_csv(RESULTS_DIR + '/cache/' + subdir + f'/dlmc_nthreads_{nthreads}.csv')\n elif bcols is not None:\n return pd.read_csv(RESULTS_DIR + '/cache/' + subdir + f'/dlmc_bcols_{bcols}.csv')\n else:\n all_files = glob.glob(os.path.join(RESULTS_DIR + 'cache/' + subdir, \"*_per_part.csv\" ))\n return pd.concat((pd.read_csv(f) for f in all_files), axis=0, ignore_index=True)\n\n\ndef create_chart_grid(charts, row_width):\n charts_merged = None\n charts_row = None\n\n col = 0\n for i in range(0, len(charts)):\n col = i % row_width\n if col == 0:\n charts_merged = charts_row if charts_merged is None else charts_merged & charts_row\n charts_row = None\n\n charts_row = charts[i] if charts_row is None else charts_row | charts[i]\n\n if col:\n charts_merged = charts_row if charts_merged is None else charts_merged & charts_row\n return charts_merged\n\n\ndef chart_save(chart, filename):\n filepath = PLOTS_DIR + filename\n filepath = filepath.replace(\".png\", \"\") + \".png\"\n os.makedirs(os.path.dirname(filepath), exist_ok=True)\n altair_saver.save(chart, filepath, fmt=\"png\", scale_fator=4)\n\n\ndef plot_save(filename):\n filepath = PLOTS_DIR + filename\n filepath = filepath.replace(\".pdf\", \"\") + \".pdf\"\n os.makedirs(os.path.dirname(filepath), exist_ok=True)\n plt.savefig(filepath)\n","repo_name":"SpRegTiling/sparse-register-tiling","sub_path":"tools/paperv2/plot_utils.py","file_name":"plot_utils.py","file_ext":"py","file_size_in_byte":2408,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"76"} +{"seq_id":"3296682972","text":"import tkinter as tk\n\ndef obtener_valores():\n nombre = entry_nombre.get()\n apellido = entry_apellido.get()\n mensaje = f\"¡Hola, {nombre} {apellido}!\"\n label_mensaje.config(text=mensaje)\n\n# Crear la ventana principal\nventana = tk.Tk()\nventana.title(\"Formulario\")\nventana.geometry(\"300x200\")\n\n# Crear etiquetas y campos de entrada\nlabel_nombre = tk.Label(ventana, text=\"Nombre:\")\nlabel_nombre.pack()\nentry_nombre = tk.Entry(ventana)\nentry_nombre.pack()\n\nlabel_apellido = tk.Label(ventana, text=\"Apellido:\")\nlabel_apellido.pack()\nentry_apellido = tk.Entry(ventana)\nentry_apellido.pack()\n\n# Botón para obtener los valores\nbtn_obtener_valores = tk.Button(ventana, text=\"Obtener Valores\", command=obtener_valores)\nbtn_obtener_valores.pack()\n\n# Etiqueta para mostrar el mensaje\nlabel_mensaje = tk.Label(ventana, text=\"\")\nlabel_mensaje.pack()\n\n# Iniciar el bucle de eventos\nventana.mainloop()\n","repo_name":"Trexpapu/python-interfaz","sub_path":"test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"39908882378","text":"import threading\nimport time\n\na = 1\n\ndef fun(chain):\n time.sleep(2)\n print(chain)\n\nprint(f\"Sync:{a}\")\n\n\n# async thread\ny = threading.Thread(target=fun, args=(f\"Async:{a}\",))\ny.start()\n\n\n# async daemon thread (run in background)\nx = threading.Thread(target=fun, args=(f\"Daemon:{a}\",), daemon=True)\nx.start()\nx.join() # needed to wait for the daemon\n\na = 10\n\nprint(f\"Sync:{a}\")","repo_name":"carlosjimz87/PyClean","sub_path":"BasicThreads.py","file_name":"BasicThreads.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"8010754635","text":"# Calcula salario de funcionario com base nas horas trabalhadas\r\n\r\nnum = int(input())\r\nhoras = int(input())\r\nvalorhora = float(input())\r\n\r\nsalario = horas * valorhora\r\n\r\nprint(\"NUMBER = \" + str(num))\r\nprint(\"SALARY = U$ %.2f\" % salario)","repo_name":"brychelle/python","sub_path":"URI/URI1008.py","file_name":"URI1008.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"6701117449","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nCreated on 2023-03-30\n\nUpdated on 2023-07-17\n\n@author: Laurens P. Stoop\n\"\"\"\n\n\n# load the dependencies\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport xarray as xr\nimport sys\nfrom datetime import datetime\nimport matplotlib.dates as mdates\nimport matplotlib.transforms as mtransforms\n\n# The scripts\nsys.path.append('/Users/3986209/Library/CloudStorage/OneDrive-UniversiteitUtrecht/Projects/ccmetrics/src/')\n\n\n#%% \nimport matplotlib.pylab as pylab\nparams = {'legend.fontsize': 'xx-large',\n 'figure.figsize': (15, 5),\n 'axes.labelsize': 'xx-large',\n 'axes.titlesize':'xx-large',\n 'xtick.labelsize':'xx-large',\n 'ytick.labelsize':'xx-large'}\npylab.rcParams.update(params)\n\n\n\n## colour definitions\n\n# Solar\ncolour_solar = 'burlywood' # 0.03\ncolour_solar_clim = 'orange' # 1\ncolour_solar_hrw = 'tab:red' # 0.7\n\n# Wind\ncolour_wind = 'skyblue' # 0.03\ncolour_wind_clim = 'lightsteelblue' # 1\ncolour_wind_hrw = 'dodgerblue' # 0.7\n\n\n\n\n# Region selection\nREGION = 'NL01'\n# REGION = 'SK00'\n# REGION = 'SE02' \n# REGION = 'FR10'\n\n\n#%%\n# =============================================================================\n# Define file locations\n# =============================================================================\n\n# Define some folders\nFOLDER_drive='/Users/3986209/Library/CloudStorage/OneDrive-UniversiteitUtrecht/'\nFOLDER_project=FOLDER_drive+'Projects/ccmetrics/'\nFOLDER_pecd = FOLDER_drive+'Data/PECD/HIST/ENER/'\n\n# file name\nfileName_SPV = 'SPV/PEON/H_ERA5_ECMW_T639_SPV_0000m_Pecd_PEON_S198001010000_E202112312300_CFR_TIM_01h_NA-_noc_org_NA_NA---_NA---_PhM01.csv'\nfileName_WON = 'WON/PEON/H_ERA5_ECMW_T639_WON_NA---_Pecd_PEON_S198001010000_E202112312300_CFR_TIM_01h_NA-_noc_org_30_NA---_NA---_PhM01.csv'\n\n\n#%%\n# =============================================================================\n# Get the data to open\n# =============================================================================\n\n# Open the file and set the index as the date\ndf_SPV = pd.read_csv(FOLDER_pecd+fileName_SPV, header=52, parse_dates=True, index_col='Date')\ndf_WON = pd.read_csv(FOLDER_pecd+fileName_WON, header=52, parse_dates=True, index_col='Date')\ndf_SPV.index = df_SPV.index.rename('time')\ndf_WON.index = df_WON.index.rename('time')\n\nds_SPV = df_SPV[REGION].to_xarray()\nds_WON = df_WON[REGION].to_xarray()\n\n\n#%%\n# =============================================================================\n# Fix time\n# =============================================================================\n\n# for easier figures we remove the leap days, see notes in RES-balance functions on how to keep this in\nds_SPV = ds_SPV.sel(time=~((ds_SPV.time.dt.month == 2) & (ds_SPV.time.dt.day == 29)))\nds_WON = ds_WON.sel(time=~((ds_WON.time.dt.month == 2) & (ds_WON.time.dt.day == 29)))\n\n\n\n#%%\n# =============================================================================\n# Figure for climatological behaviour\n# =============================================================================\n\n\n\n\n\n\n\n\n# we start a new figure\n# fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(17,10))\nfig, axes = plt.subplot_mosaic([['a)', 'b)', 'c)'], ['d)', 'e)', 'f)']], figsize=(17,10))\n\n# fix date-format\nfig.autofmt_xdate()\n\n# show year\nds_WON.sel(time=slice(\"2002-01-01\", \"2004-06-15\")).plot(ax=axes['a)'], alpha=1, linewidth=0.25, color=colour_wind)\nds_SPV.sel(time=slice(\"2002-01-01\", \"2004-06-15\")).plot(ax=axes['d)'], alpha=1, linewidth=0.25, color=colour_solar)\n\n# Show subseasonal\nds_WON.sel(time=slice(\"2003-02-15\", \"2003-05-15\")).plot(ax=axes['b)'], alpha=1, linewidth=0.5, color=colour_wind)\nds_SPV.sel(time=slice(\"2003-02-15\", \"2003-05-15\")).plot(ax=axes['e)'], alpha=1, linewidth=0.5, color=colour_solar)\n\n# show diurnal\nds_WON.sel(time=slice(\"2003-04-03\", \"2003-04-10\")).plot(ax=axes['c)'], alpha=1, color=colour_wind)\nds_SPV.sel(time=slice(\"2003-04-03\", \"2003-04-10\")).plot(ax=axes['f)'], alpha=1, color=colour_solar)\n\n\n### Fix limits\naxes['a)'].set_ylim(0,0.92)\naxes['b)'].set_ylim(0,0.92)\naxes['c)'].set_ylim(0,0.92)\naxes['d)'].set_ylim(0,0.8)\naxes['e)'].set_ylim(0,0.8)\naxes['f)'].set_ylim(0,0.8)\n\n\n## formate the date-axis \n# years\nfor a in ['a)', 'd)']:\n axes[a].xaxis.set_major_locator(mdates.YearLocator(base=1))\n axes[a].xaxis.set_minor_locator(mdates.MonthLocator(bymonth=(1,4,7,10)))\n axes[a].xaxis.set_major_formatter(mdates.DateFormatter('%Y'))\n \n# months\nfor a in ['b)', 'e)']:\n axes[a].xaxis.set_major_locator(mdates.MonthLocator(bymonth=(3,4,5)))\n axes[a].xaxis.set_minor_locator(mdates.DayLocator(interval=3))\n axes[a].xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))\n\n# Dates\nfor a in ['c)', 'f)']:\n axes[a].xaxis.set_major_locator(mdates.DayLocator(interval=3))\n axes[a].xaxis.set_minor_locator(mdates.DayLocator(interval=1))\n axes[a].xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))\n\n### Fix labels\n# y-label\naxes['a)'].set_ylabel('Wind potential [0-1]')\naxes['d)'].set_ylabel('Solar potential [0-1]')\naxes['b)'].set_ylabel('')\naxes['e)'].set_ylabel('')\naxes['c)'].set_ylabel('')\naxes['f)'].set_ylabel('')\n\n# x-label\naxes['a)'].set_xlabel('')\naxes['b)'].set_xlabel('')\naxes['c)'].set_xlabel('')\naxes['d)'].set_xlabel('')\naxes['e)'].set_xlabel('')\naxes['f)'].set_xlabel('')\n\n# make it look better\nplt.tight_layout()\n\n# print subplot names\nfor label, ax in axes.items():\n # label physical distance in and down:\n trans = mtransforms.ScaledTranslation(10/72, -8/72, fig.dpi_scale_trans)\n ax.text(0.0, 1.0, label, transform=ax.transAxes + trans,\n fontsize='xx-large', verticalalignment='top')\n\n\nif REGION == 'NLO1':\n plt.savefig(FOLDER_project+'results/publication/Climatological_Behaviour.png')\n plt.savefig(FOLDER_project+'results/publication/Climatological_Behaviour.pdf')\nelse:\n plt.savefig(FOLDER_project+'results/additional_regions/Climatological_Behaviour_'+REGION+'.png')\n plt.savefig(FOLDER_project+'results/additional_regions/Climatological_Behaviour_'+REGION+'.pdf')\nplt.show()\n","repo_name":"laurensstoop/CREDI","sub_path":"src/Figure_climatological_behaviour.py","file_name":"Figure_climatological_behaviour.py","file_ext":"py","file_size_in_byte":6053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"9907686222","text":"import structlog\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import scoped_session, sessionmaker, declarative_base\nfrom sqlalchemy_utils import database_exists, create_database\nfrom app.configs.config import get_environment_variables\n\nlogger = structlog.get_logger()\n\nenv = get_environment_variables()\n\nDATABASE_URL = f\"{env.DATABASE_DIALECT}://{env.DATABASE_USERNAME}:{env.DATABASE_PASSWORD}@{env.DATABASE_HOSTNAME}:{env.DATABASE_PORT}/{env.DATABASE_NAME}\"\n\nengine = create_engine(\n DATABASE_URL, echo=env.DEBUG_MODE, future=True\n)\n\nSessionLocal = sessionmaker(\n autocommit=False, autoflush=False, bind=engine\n)\n\nBase = declarative_base()\n\ndef get_db_connection():\n db = scoped_session(SessionLocal)\n try:\n yield db\n finally:\n db.close()\n\ndef init_db():\n if not database_exists(engine.url):\n logger.info('database does not exists creating new database')\n create_database(engine.url)\n else:\n logger.info('database exists omitting creation of new database')\n Base.metadata.create_all(bind=engine)\n","repo_name":"Nomow/time-based-key-value-store","sub_path":"app/utils/db/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"1081739730","text":"from microprediction import MicroWriter\nimport numpy as np\nfrom pprint import pprint\nimport matplotlib.pyplot as plt\nimport random \nimport time\nimport warnings\nwarnings.filterwarnings('ignore')\nfrom copulas.multivariate import GaussianMultivariate\nimport pandas as pd\n\n\n# Grab the Github secret \nimport os \nWRITE_KEY = os.environ.get('WRITE_KEY') # <-- You need to add a Github secret\nANIMAL = MicroWriter.animal_from_key(WRITE_KEY) # <-- Your nom de plume \nREPO = 'https://github.com/microprediction/microactors/blob/master/fit.py' # <--- Change your username\nprint('This is '+ANIMAL+' firing up')\n\nSTOP_LOSS = 25 # <--- Governs when we give up on a stream/horizon\n\n# Get historical data, fit a copula, and submit \n\ndef fit_and_sample(lagged_zvalues:[[float]],num:int, copula=None):\n \"\"\" Example of creating a \"sample\" of future values\n \n lagged_zvalues: [ [z1,z2,z3] ] distributed N(0,1) margins, roughly\n copula : Something from https://pypi.org/project/copulas/\n returns: [ [z1, z2, z3] ] representative sample\n\n Swap out this function for whatever you like. \n \"\"\"\n # Remark 1: It's lazy to just sample synthetic data\n # Remark 2: Any multivariate density estimation could go here. \n # Remark 3: If you prefer uniform margin, use mw.get_lagged_copulas(name=name, count= 5000) \n #\n # See https://www.microprediction.com/blog/lottery for discussion of this \"game\" \n \n df = pd.DataFrame(data=lagged_zvalues)\n if copula is None:\n copula = GaussianMultivariate() # <--- \n copula.fit(df)\n synthetic = copula.sample(num)\n return synthetic.values.tolist()\n\n\n\nif __name__ == \"__main__\":\n mw = MicroWriter(write_key=WRITE_KEY)\n mw.set_repository(REPO) # Just polite, creates a CODE badge on the leaderboard\n \n NAMES = [ n for n in mw.get_stream_names() if 'z2~' in n or 'z3~' in n ]\n for _ in range(1): \n name = random.choice(NAMES)\n lagged_zvalues = mw.get_lagged_zvalues(name=name, count= 5000)\n if len(lagged_zvalues)>20:\n zvalues = fit_and_sample(lagged_zvalues=lagged_zvalues, num=mw.num_predictions)\n pprint( (name, len(lagged_zvalues), len(zvalues)))\n try:\n for delay in mw.DELAYS:\n res = mw.submit_zvalues(name=name, zvalues=zvalues, delay=delay )\n pprint(res)\n except Exception as e:\n print(e)\n # Quit some stream/horizon combinations where we fare poorly\n mw.cancel_worst_active(stop_loss=STOP_LOSS, num=3)\n","repo_name":"microprediction/microactors","sub_path":"fit.py","file_name":"fit.py","file_ext":"py","file_size_in_byte":2596,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"76"} +{"seq_id":"26261347608","text":"#!/usr/bin/python\nimport time\nimport random\n\n\nlines=[]\ndef buildURL():\n # build random URL\n url_list=['www.quicloud.com', 'www.cloudera.com', 'www.infiniteskills.com', 'flume.apache.org','hadoop.apache.org','console.amazon.com','www.globalknowledge.com','www.gigaom.com']\n return random.choice(url_list)\n\ndef buildPath():\n # build random Path\n path_list=['/index.html', '/contact.html', '/contact/submit.html', '/about.html','/products.html','/services.html','/support.html']\n return random.choice(path_list)\n\ndef buildHTTP():\n # build random HTTP code\n a=200\n b=599\n return random.randrange(a,b,1)\n\ndef getHTTP():\n # build random HTTP status\n HTTP_status = [ 100, 101, 102, 200, 201, 202, 203, 204, 205, 206, 207, 226, 300, 301, 302, 303, 304, 305, 307, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 422, 423, 424, 426, 500, 501, 502, 503, 504, 505, 507, 510 ]\n return random.choice(HTTP_status)\n\ndef buildIP():\n # build random IP\n b1 = random.randrange(0, 255, 1)\n b2 = random.randrange(0, 255, 1)\n b3 = random.randrange(0, 255, 1)\n b4 = random.randrange(0, 255, 1)\n return str(b1) + '.' + str(b2) + '.' + str(b3) + '.' + str(b4)\nj=0\nwhile True:\n count=1\n while(count<=10):\n #Http = buildHTTP()\n Http = getHTTP()\n Http = str(Http)\n Url = buildURL()\n Path = buildPath()\n Ip = str(buildIP())\n line = \"HTTP \" + Http + \" \" + Url + \" \" + Path + \" \" + Ip + \"\\n\"\n lines.append(line)\n count=count+1\n print(line)\n time.sleep(1)\n with open(\"Logs/Log_generator\"+str(j)+\".txt\",'w') as Log:\n for linee in lines:\n Log.write(linee)\n lines=[] \n j=j+1\n ","repo_name":"zainabdah/SparkLogs","sub_path":"src/main/scala/logs/log-generator.py","file_name":"log-generator.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"7862425422","text":"import torch\nfrom exp_reaching_goals.reaching_goals_utils import flatten_layers\nfrom exp_reaching_goals.network import actor, critic, signaling_net\n\nimport numpy as np\n\n\ndef calculate_critic_loss(critic, target_critic, loss_criterion, r, input, a, input_next, a_next, gamma):\n output_table = critic(input)\n target_output_table = target_critic(input_next)\n output = output_table[range(len(a)), a]\n target_output = target_output_table[range(len(a)), a_next]\n\n td_target = r + gamma * target_output\n critic_loss = loss_criterion(td_target, output)\n\n return critic_loss\n\n\ndef grad_and_step(net, net_optimizer, obj, type):\n assert type in ['descent', 'ascent']\n\n net_optimizer.zero_grad()\n net_grad = torch.autograd.grad(obj, list(net.parameters()), retain_graph=True)\n net_params = list(net.parameters())\n for layer in range(len(net_params)):\n if type == 'descent':\n net_params[layer].grad = net_grad[layer]\n else:\n net_params[layer].grad = - net_grad[layer]\n net_params[layer].grad.data.clamp_(-1, 1)\n net_optimizer.step()\n return\n\n\nclass sender_class(object):\n def __init__(self, config, device, id=0):\n self.name = name = 'sender'\n self.config = config\n self.device = device\n self.id = id\n self.dim_action = dim_action = config.env.dim_action\n self.epsilon = config.sender.epsilon_greedy\n\n # Gi(s,aj)\n self.critic_Gi = critic(config.n_channels.obs_sender, dim_action, config, belongto=name, name='critic_Gi',\n device=device)\n # Gi(s,aj)\n self.critic_Gj = critic(config.n_channels.obs_sender, dim_action, config, belongto=name, name='critic_Gj',\n device=device)\n # phi(sigma|s)\n self.signaling_net = signaling_net(config, device=device)\n\n self.critic_loss_criterion = torch.nn.MSELoss(reduction='mean')\n self.critic_Gi_optimizer = torch.optim.Adam(self.critic_Gi.parameters(), config.sender.lr_critic_Gi)\n self.critic_Gj_optimizer = torch.optim.Adam(self.critic_Gj.parameters(), config.sender.lr_critic_Gj)\n self.signaling_optimizer = torch.optim.Adam(self.signaling_net.parameters(), config.sender.lr_signal)\n\n # target critics\n self.target_critic_Gi = critic(config.n_channels.obs_sender, dim_action, config, belongto=name,\n name='target_critic_Gi', device=device)\n self.target_critic_Gi.load_state_dict(self.critic_Gi.state_dict())\n self.target_critic_Gj = critic(config.n_channels.obs_sender, dim_action, config, belongto=name,\n name='target_critic_Gj', device=device)\n self.target_critic_Gj.load_state_dict(self.critic_Gj.state_dict())\n\n self.temperature = 1\n\n def build_connection(self, receiver):\n self.receiver = receiver\n\n def calculate_v(self, critic, input_critic, phi, obs_receiver):\n # v(s) = \\sum_sigma phi(sigma|s) * \\sum_a pi(a|sigma) * Gi(s,a)\n batch_size = phi.shape[0]\n message_dim = phi.shape[1]\n all_message = torch.nn.functional.one_hot(torch.arange(message_dim)) \\\n .view(message_dim,\n self.config.env.map_height,\n self.config.env.map_width) \\\n .unsqueeze(dim=0).repeat(batch_size, 1, 1, 1).unsqueeze(dim=2).to(self.device)\n\n obs_receiver = obs_receiver.repeat(1, message_dim, 1, 1).unsqueeze(dim=2)\n obs_and_message_receiver = torch.cat([obs_receiver, all_message], dim=2)\n\n obs_and_message_receiver_flatten = obs_and_message_receiver.view(batch_size * message_dim, 2,\n obs_and_message_receiver.shape[-2],\n obs_and_message_receiver.shape[-1])\n\n _, pi_flatten = self.receiver.choose_action(obs_and_message_receiver_flatten)\n pi = pi_flatten.view(obs_and_message_receiver.shape[0], obs_and_message_receiver.shape[1], pi_flatten.shape[-1])\n pi_sum_all_message = torch.sum(pi * phi.unsqueeze(dim=2).repeat(1, 1, pi.shape[-1]), dim=1)\n\n g_table = critic(input_critic)\n v = torch.sum(g_table * pi_sum_all_message, dim=1)\n return v\n\n def calculate_2critics_loss(self, batch):\n ri = batch.data[batch.name_dict['ri']]\n rj = batch.data[batch.name_dict['rj']]\n obs_sender = batch.data[batch.name_dict['obs_sender']]\n obs_sender_next = batch.data[batch.name_dict['obs_sender_next']]\n aj = batch.data[batch.name_dict['a']]\n aj_next = batch.data[batch.name_dict['a_next']]\n\n critic_loss_Gi = calculate_critic_loss(self.critic_Gi, self.target_critic_Gi, self.critic_loss_criterion,\n ri, input=obs_sender, a=aj, input_next=obs_sender_next, a_next=aj_next,\n gamma=self.config.sender.gamma)\n critic_loss_Gj = calculate_critic_loss(self.critic_Gj, self.target_critic_Gj, self.critic_loss_criterion,\n rj, input=obs_sender, a=aj, input_next=obs_sender_next, a_next=aj_next,\n gamma=self.config.sender.gamma)\n return critic_loss_Gi, critic_loss_Gj\n\n def softupdate_2target_critics(self):\n tau = self.config.nn.target_critic_tau\n for tar, cur in zip(self.target_critic_Gi.parameters(), self.critic_Gi.parameters()):\n tar.data.copy_(cur.data * (1.0 - tau) + tar.data * tau)\n for tar, cur in zip(self.target_critic_Gj.parameters(), self.critic_Gj.parameters()):\n tar.data.copy_(cur.data * (1.0 - tau) + tar.data * tau)\n return\n\n def calculate_for_updating(self, batch):\n critic_loss_Gi, critic_loss_Gj = self.calculate_2critics_loss(batch)\n gradeta = self.calculate_gradeta(batch)\n\n return critic_loss_Gi, critic_loss_Gj, gradeta\n\n def update(self, critic_loss_Gi, critic_loss_Gj, gradeta):\n\n grad_and_step(self.critic_Gi, self.critic_Gi_optimizer, critic_loss_Gi, 'descent')\n grad_and_step(self.critic_Gj, self.critic_Gj_optimizer, critic_loss_Gj, 'descent')\n\n self.softupdate_2target_critics()\n\n self.signaling_optimizer.zero_grad()\n params = list(self.signaling_net.parameters())\n for i in range(len(list(self.signaling_net.parameters()))):\n params[i].grad = - gradeta[i] # gradient ascent\n params[i].grad.data.clamp_(-1, 1)\n self.signaling_optimizer.step()\n\n def send_message(self, obs):\n batch_size = len(obs)\n logits, phi = self.signaling_net(obs)\n phi = (1 - self.epsilon) * phi + self.epsilon / phi.shape[0]\n sample = torch.nn.functional.gumbel_softmax(logits, tau=self.temperature, hard=True)\n message = sample.view(batch_size, 1, self.config.env.map_height, self.config.env.map_width)\n return message, phi\n\n def calculate_gradeta(self, batch):\n obs_sender = batch.data[batch.name_dict['obs_sender']]\n aj = batch.data[batch.name_dict['a']]\n pij = batch.data[batch.name_dict['pi']]\n pij_aj = pij[range(len(aj)), aj]\n\n phi = batch.data[batch.name_dict['phi']]\n # phi_np = np.array(phi.detach())\n sigma = message = batch.data[batch.name_dict['message']]\n sigma_flatten = sigma.view(sigma.shape[0], -1)\n idx_flatten = torch.nonzero(sigma_flatten)[:, 1]\n phi_sigma = phi[range(idx_flatten.shape[0]), idx_flatten]\n\n ''' SG (Signaling Gradient) '''\n # s, aj\n Gi_table = self.critic_Gi(obs_sender)\n Gi = Gi_table[range(len(aj)), aj]\n obs_receiver = obs_sender[:, 0:1:, :,\n :] # This is for advantage. The other way is to make the receiver to tell the results, in which the sender doesn't need to have access to this var.\n Vi = self.calculate_v(self.critic_Gi, obs_sender, phi, obs_receiver)\n advantage_i = Gi - Vi\n\n log_phi_sigma = torch.log(phi_sigma)\n log_pij_aj = torch.log(pij_aj)\n\n # tuning for gumbel-softmax\n term = torch.mean(advantage_i.detach() * (log_phi_sigma\n + log_pij_aj * self.config.sender.coe_for_recovery_fromgumbel\n ))\n # term1 = torch.mean(Gi.detach() * log_phi_sigma)\n # term2 = torch.mean(Gi.detach() * log_pij_aj)\n # gradeta1 = torch.autograd.grad(term1, list(self.signaling_net.parameters()), retain_graph=True)\n # gradeta2 = torch.autograd.grad(term2, list(self.signaling_net.parameters()), retain_graph=True)\n\n gradeta = torch.autograd.grad(term, list(self.signaling_net.parameters()), retain_graph=True)\n gradeta_flatten = flatten_layers(gradeta)\n\n ''' BCE Obedience Constraint (Lagrangian) '''\n if not self.config.env.aligned_object:\n batch_len = aj.shape[0]\n sigma_counterfactual_index_flatten = torch.randint(self.config.env.map_height * self.config.env.map_width,\n size=(batch_len,)).to(self.device) # negative sampling\n sigma_counterfactual_index = [\n torch.floor(sigma_counterfactual_index_flatten / self.config.env.map_height).long().unsqueeze(dim=0),\n (sigma_counterfactual_index_flatten % self.config.env.map_width).unsqueeze(dim=0)]\n sigma_counterfactual_index = torch.cat(sigma_counterfactual_index).to(self.device)\n sigma_counterfactual = torch.zeros(batch_len, self.config.env.map_height, self.config.env.map_width,\n dtype=torch.double).to(self.device)\n sigma_counterfactual[range(batch_len), sigma_counterfactual_index[0], sigma_counterfactual_index[1]] = 1\n # sigma_counterfactual_np = np.array(sigma_counterfactual)\n sigma_counterfactual = sigma_counterfactual.unsqueeze(dim=1)\n obs_and_message_receiver = batch.data[batch.name_dict['obs_and_message_receiver']]\n obs_and_message_counterfactual_receiver = torch.cat([obs_and_message_receiver[:, 0:1, :, :],\n sigma_counterfactual], dim=1)\n _, pij_counterfactual = self.receiver.choose_action(obs_and_message_counterfactual_receiver)\n\n # s, aj\n Gj_table = self.critic_Gj(obs_sender)\n # Vj = self.calculate_v(self.critic_Gj, obs_sender, phi, obs_receiver)\n # advantage_j_table = Gj_table - Vj.unsqueeze(dim=1).repeat(1, self.dim_action)\n term1 = phi_sigma * torch.sum(pij.detach() * Gj_table.detach(), dim=1).unsqueeze(dim=1)\n term2 = phi_sigma.detach() * torch.sum(pij * Gj_table.detach(), dim=1).unsqueeze(dim=1)\n # term1 = phi_sigma * torch.sum(pij.detach() * advantage_j_table.detach(), dim=1).unsqueeze(dim=1)\n # term2 = phi_sigma.detach() * torch.sum(pij * advantage_j_table.detach(), dim=1).unsqueeze(dim=1)\n\n # every pixel\n term1_sum = torch.sum(term1, dim=1)\n term2_sum = torch.sum(term2, dim=1)\n\n term1_mean = torch.mean(term1_sum)\n term2_mean = torch.mean(term2_sum)\n\n gradeta_constraint_term1 = torch.autograd.grad(term1_mean, list(self.signaling_net.parameters()),\n retain_graph=True)\n gradeta_constraint_term2 = torch.autograd.grad(term2_mean, list(self.signaling_net.parameters()),\n retain_graph=True)\n\n gradeta_constraint_term_1st_flatten = flatten_layers(gradeta_constraint_term1)\n gradeta_constraint_term_2nd_flatten = flatten_layers(\n gradeta_constraint_term2) * self.config.sender.coe_for_recovery_fromgumbel\n\n gradeta_constraint_flatten = gradeta_constraint_term_1st_flatten \\\n + gradeta_constraint_term_2nd_flatten\n if self.config.sender.sender_objective_alpha >= 1:\n gradeta_flatten = gradeta_flatten / self.config.sender.sender_objective_alpha + gradeta_constraint_flatten\n elif 0 <= self.config.sender.sender_objective_alpha < 1:\n gradeta_flatten = gradeta_flatten + self.config.sender.sender_objective_alpha * gradeta_constraint_flatten\n else:\n # raise IOError\n pass\n\n # reform to be in original shape\n gradeta_flatten = gradeta_flatten.squeeze()\n gradeta = []\n idx = 0\n for layerl in self.signaling_net.parameters():\n len_layerl = 1\n for i in layerl.shape:\n len_layerl *= i\n gradeta_layerl_section = gradeta_flatten[idx:idx + len_layerl]\n gradeta_layerl = gradeta_layerl_section.view(layerl.shape)\n gradeta.append(gradeta_layerl)\n idx += len_layerl\n\n return gradeta\n\n def save_models(self):\n self.critic_Gi.save_checkpoint()\n self.critic_Gj.save_checkpoint()\n self.target_critic_Gi.save_checkpoint()\n self.target_critic_Gj.save_checkpoint()\n self.signaling_net.save_checkpoint()\n\n def load_models(self):\n self.critic_Gi.load_checkpoint()\n self.critic_Gj.load_checkpoint()\n self.target_critic_Gi.load_checkpoint()\n self.target_critic_Gj.load_checkpoint()\n self.signaling_net.load_checkpoint()\n","repo_name":"YueLin301/InformationDesignMARL","sub_path":"exp_reaching_goals/agent_class.py","file_name":"agent_class.py","file_ext":"py","file_size_in_byte":13649,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"76"} +{"seq_id":"18948297398","text":"# 部���永続Union-Find\n# N: 頂点数\nN = ...\n\n# p[u]: 頂点uの親頂点\n# sz[u]: 現在の親頂点uの木が含む頂点数\n# H[u]: 現在の親頂点uの木の高さ\n# S[u] = [(t, s), ...]:\n# 時刻tに別の頂点をマージした親頂点uの木が含む頂点数s\n# T[u]: 頂点uが親頂点でなくなる時刻\n\nINF = 1e18\n*p, = range(N)\nsz = [1]*N\nH = [1]*N\nS = [[(0, 1)] for i in range(N)]\nT = [INF]*N\n \ndef find(x, t):\n while T[x] <= t:\n x = p[x]\n return x\n \ndef unite(x, y, t):\n px = find(x, t)\n py = find(y, t)\n if px == py:\n return 0\n if H[py] < H[px]:\n p[py] = px\n T[py] = t\n sz[px] += sz[py]\n S[px].append((t, sz[px]))\n else:\n p[px] = py\n T[px] = t\n sz[py] += sz[px]\n S[py].append((t, sz[py]))\n H[py] = max(H[py], H[px]+1)\n return 1\n\nfrom bisect import bisect\n \ndef size(x, t):\n y = find(x, t)\n idx = bisect(S[y], (t, INF))-1\n return S[y][idx]\n","repo_name":"tjkendev/procon-library","sub_path":"python/union_find/pp_union_find.py","file_name":"pp_union_find.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"76"} +{"seq_id":"24055283922","text":"class Validator:\n\n def __init__(self):\n pass\n\n def isEmail(self, str):\n return ('@' in str) and ('.' in str)\n\n def isPhone(self, str):\n if len(str.split(\"-\")) == 5:\n return True\n\n\n def isDomain(self, domain):\n return ('.' in domain)\n\n\n\n\nemail = \"example@example.com\"\nphone_number = \"+381\"\ndom = \"lol.ru\"\nvalidator = Validator()\n\nif validator.isEmail(email):\n print(\"Email корректен\")\nelse:\n print(\"Email некорректен\")\n\nif validator.isDomain(dom):\n print(\"домен корректен\")\nelse:\n print(\"домен некорректен\")\nif validator.isPhone(phone_number):\n print(\"Номер телефона корректен\")\nelse:\n print(\"Номер телефона некорректен\")\n","repo_name":"sqweeeek/laba2","sub_path":"22/22.4.py","file_name":"22.4.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"37883613658","text":"import os\nimport tweepy\nimport requests\nimport base64\nfrom dotenv import load_dotenv\n\nload_dotenv()\nconsumer_key = os.getenv(\"CONSUMER_KEY\")\nconsumer_secret = os.getenv(\"CONSUMER_SECRET\")\naccess_token = os.getenv(\"ACCESS_TOKEN\")\naccess_token_secret = os.getenv(\"ACCESS_TOKEN_SECRET\")\n\n# Authenticate to Twitter\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\napi = tweepy.API(auth)\n\n\n#Reformat the keys and encode them\nkey_secret = '{}:{}'.format(consumer_key, consumer_secret).encode('ascii')\n#Transform from bytes to bytes that can be printed\nb64_encoded_key = base64.b64encode(key_secret)\n#Transform from bytes back into Unicode\nb64_encoded_key = b64_encoded_key.decode('ascii')\n\nbase_url = 'https://api.twitter.com/'\nauth_url = '{}oauth2/token'.format(base_url)\nauth_headers = {\n 'Authorization': 'Basic {}'.format(b64_encoded_key),\n 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'\n}\nauth_data = {\n 'grant_type': 'client_credentials'\n}\nauth_resp = requests.post(auth_url, headers=auth_headers, data=auth_data)\nprint(auth_resp.status_code)\naccess_token = auth_resp.json()['access_token']\n#print(access_token)\n\nfile = open('C:/Temp/th.jpg', 'rb')\ndata = file.read()\nresource_url = 'https://upload.twitter.com/1.1/media/upload.json'\nupload_image = {\n 'media':data,\n 'media_category':'tweet_image'}\n \nimage_headers = {\n 'Authorization': 'Bearer {}'.format(access_token) \n}\n\nmedia_id = requests.post(resource_url, headers=image_headers, params=upload_image)\nprint(media_id.status_code)\n\n\"\"\"\ntweet_meta={ \"media_id\": media_id,\n \"alt_text\": {\n \"text\":\"tlogo\" \n }}\nmetadata_url = 'https://upload.twitter.com/1.1/media/metadata/create.json' \nmetadata_resp = requests.post(metadata_url, params=tweet_meta, headers=auth_data)\nprint(metadata_resp.status_code)\n\n#tweet = {'status': 'just test #tweepy', 'media_ids': media_id}\ntweet = {'status': 'just test #tweepy'}\npost_url = 'https://api.twitter.com/1.1/statuses/update.json' \npost_resp = requests.post(post_url, params=tweet, headers=image_headers)\nprint(post_resp.status_code)\n\"\"\"\n\n#try:\n# api.verify_credentials()\n# print(\"Authentication OK\")\n# api.update_status(\"just test.. #tweepy\")\n#except:\n# print(\"Error during authentication\")\n","repo_name":"tomfutago/gangstabet-feed","sub_path":"tests/tweepy_media_upload_test.py","file_name":"tweepy_media_upload_test.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"70482521206","text":"#!/usr/bin/env python\n# coding=utf-8\n\n# Author: Junjie Wang\n# Mail: dreamboy.gns@sjtu.edu.cn\n\n# Website:http://www.dbgns.com\n# Blog:http://www.dbgns.com/blog\n\n\"\"\"\nsome help functions\n\"\"\"\n\nimport pandas as pd\nimport os.path as osp\n\nDATA_DIR = \"../data\"\nTABLE = {\"TableA\": \"order\", \"TableB\": \"commodity\", \"TableC\": \"distance\", \"TableD\": \"vehicle\"}\nVEHICLES = ['Plane', 'Ship', 'Truck', 'Train']\n\n\ndef std2min(std_time):\n \"\"\"\n convert the time of standard form into minutes\n\n :param std_time: time in the standard form(e.g. 22:41:30)\n :return: minutes\n \"\"\"\n hour, minute, second = std_time.split(\":\")\n return int(hour) * 60 + int(minute) + round(int(second)/60, 2)\n\n\ndef min2std(min_time, get_day=False):\n \"\"\"\n convert the time in the form of minutes into standard form\n\n :param min_time: minutes\n :param get_day: calculate day or not(e.g. (+1day)17:31:25, useful when we want to get true arrival time\n :return: the time in the standard form\n \"\"\"\n day = 0\n second = int((min_time - int(min_time)) * 60)\n min_time = int(min_time)\n hour = min_time // 60\n while hour >= 24:\n day += 1\n hour -= 24\n minute = min_time % 60\n hour, minute, second = str(hour), str(minute), str(second)\n\n if len(minute) == 1:\n minute = '0' + minute\n if len(second) == 1:\n second = '0' + second\n # if we need more than one day\n if day != 0 and get_day:\n return ':'.join(['(+' + str(day) + 'day)', hour, minute, second])\n return ':'.join([hour, minute, second])\n\n\ndef xlsx2csv(filename, with_header=True):\n \"\"\"\n convert the .xlsx format data into csv format(speed up I/O)\n\n :param filename: xlsx filename\n :param with_header(e.g. the distance.xlsx does not have a header)\n \"\"\"\n csv_path = osp.join(DATA_DIR, TABLE[osp.splitext(filename)[0]] + \".csv\")\n\n if osp.exists(csv_path):\n print(\"Found {0}. No need for conversion.\".format(csv_path))\n return\n\n if with_header:\n xlsx = pd.read_excel(osp.join(DATA_DIR, filename))\n else:\n xlsx = pd.read_excel(osp.join(DATA_DIR, filename), header=None)\n\n xlsx.to_csv(csv_path, index=False)\n print(\"Saving => {0}.\".format(csv_path))\n return\n\n\ndef prep_data():\n \"\"\"\n do some pre-processing work\n\n \"\"\"\n xlsx2csv(\"TableA.xlsx\")\n xlsx2csv(\"TableB.xlsx\")\n xlsx2csv(\"TableC.xlsx\", with_header=False)\n\n order = pd.read_csv(osp.join(DATA_DIR, \"order.csv\"))\n order.columns = ['CityOfSeller', 'CityOfPurchaser', 'TimeOfOrder', 'IndexOfCommodity', 'AmountOfCommodity', 'Emergency']\n order.to_csv(osp.join(DATA_DIR, \"order.csv\"), index=False)\n\n commodity = pd.read_csv(osp.join(DATA_DIR, \"commodity.csv\"))\n commodity.columns = ['IndexOfCommodity', 'PriceOfUnit', 'CategoryOfCommodity', 'Weight']\n commodity.to_csv(osp.join(DATA_DIR, \"commodity.csv\"), index=False)\n\n if osp.exists(osp.join(DATA_DIR, \"vehicle.csv\")):\n print(\"Found {0}. No need for conversion.\".format(osp.join(DATA_DIR, \"vehicle.csv\")))\n return\n\n vehicles_dict = {}\n for sheet_name in VEHICLES:\n vehicles_dict[sheet_name] = pd.read_excel(osp.join(DATA_DIR, \"TableD.xlsx\"), sheet_name=sheet_name)\n vehicles_dict[sheet_name]['Vehicle'] = sheet_name\n\n vehicles = pd.concat(vehicles_dict.values())\n vehicles.columns = ['IndexOfDepartureCity', 'IndexOfArrivalCity',\n 'AverageDelay', 'Speed', 'Cost', 'TimeOfDeparture', 'Vehicle']\n vehicles.to_csv(osp.join(DATA_DIR, \"vehicle.csv\"), index=False)\n print(\"Vehicles schedule merged into {0}\".format(osp.join(DATA_DIR, \"vehicle.csv\")))\n\n\ndef look_up_vehicle(seller_city, purchaser_city):\n vehicle = pd.read_csv(osp.join(DATA_DIR, \"vehicle.csv\"))\n\n if vehicle.loc[(vehicle['IndexOfDepartureCity'] == seller_city)\n & (vehicle['IndexOfArrivalCity'] == purchaser_city)].empty:\n return None\n else:\n return vehicle.loc[(vehicle['IndexOfDepartureCity'] == seller_city)\n & (vehicle['IndexOfArrivalCity'] == purchaser_city)]\n\n\nif __name__ == '__main__':\n prep_data()\n","repo_name":"AdamQinwt/package-delivery","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"24583147926","text":"import cv2, torch\nfrom model.dataset import Vocabulary\nfrom torchvision import transforms\nimport model.models as models\n\ntransform = transforms.Compose(\n [transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))]\n)\nvocab = Vocabulary(\"./model/meta/data_props.pkl\")\nhidden_size = 256\nmodel = models.Transcriptor(hidden_size, len(vocab)).to(models.device)\nmodel.load_state_dict(torch.load(\"./model/epoch_50.pt\"))\nmodel.eval()\n\n\ndef predict(img_path, length=50):\n\timg = 255 - cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)\n\timg = transform(img).to(models.device).unsqueeze(0)\n\touts = model(img, length=length)\n\tpred = vocab.decode(outs.argmax(dim=1)[0].cpu().numpy())\n\treturn pred.replace(r\" \\eos\", \"\")\n","repo_name":"calvinyusno2359/50039-im2latex","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"31661148629","text":"\nimport toml\n\n\nclass Extender:\n \"\"\"\n The base class for TidyPy configuration extenders.\n \"\"\"\n\n @classmethod\n def can_handle(cls, location):\n \"\"\"\n Indicates whether or not this Extender is capable of retrieving the\n specified location.\n\n :param location:\n a URI indicating where to retrieve the TidyPy configuration from\n :type location: str\n :rtype: bool\n \"\"\"\n\n raise NotImplementedError()\n\n @classmethod\n def retrieve(cls, location, project_path):\n \"\"\"\n Retrieves a TidyPy configuration from the specified location.\n\n :param location:\n a URI indicating where to retrieve the TidyPy configuration from\n :type location: str\n :param project_path: the full path to the project's base\n :type project_path: str\n :rtype: dict\n \"\"\"\n\n raise NotImplementedError()\n\n @classmethod\n def parse(cls, content, is_pyproject=False):\n \"\"\"\n A convenience method for parsing a TOML-serialized configuration.\n\n :param content: a TOML string containing a TidyPy configuration\n :type content: str\n :param is_pyproject:\n whether or not the content is (or resembles) a ``pyproject.toml``\n file, where the TidyPy configuration is located within a key named\n ``tool``.\n :type is_pyproject: bool\n :rtype: dict\n \"\"\"\n\n parsed = toml.loads(content)\n\n if is_pyproject:\n parsed = parsed.get('tool', {})\n parsed = parsed.get('tidypy', {})\n\n return parsed\n\n\nclass ExtenderError(Exception):\n \"\"\"\n The base class for all exceptions raised by an Extender during its\n operation.\n \"\"\"\n\n\nclass DoesNotExistError(ExtenderError):\n \"\"\"\n An exception indicating that the specified Extender does not exist in the\n current environment.\n \"\"\"\n\n","repo_name":"jayclassless/tidypy","sub_path":"src/tidypy/extenders/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1915,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"76"} +{"seq_id":"17415051269","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals, print_function, absolute_import\nfrom sqlalchemy.ext.orderinglist import ordering_list\n\nfrom .. import db\nfrom ..models import declarative_base\nfrom ..resource import (\n Resource,\n Scope,\n Permission,\n ResourceScope,\n Serializer,\n SerializedProperty as SP,\n SerializedResourceRelationship as SRR,\n ResourceGroup)\n\nfrom .util import _\n\nBase = declarative_base()\n\n\nclass WebMapScope(Scope):\n identity = 'webmap'\n label = _(\"Web map\")\n\n display = Permission(_(\"Display\"))\n\n\nclass WebMap(Base, Resource):\n identity = 'webmap'\n cls_display_name = _(\"Web map\")\n\n __scope__ = WebMapScope\n\n root_item_id = db.Column(db.ForeignKey('webmap_item.id'), nullable=False)\n bookmark_resource_id = db.Column(db.ForeignKey(Resource.id), nullable=True)\n draw_order_enabled = db.Column(db.Boolean, nullable=True)\n editable = db.Column(db.Boolean, nullable=False, default=False)\n\n extent_left = db.Column(db.Float, default=-180)\n extent_right = db.Column(db.Float, default=+180)\n extent_bottom = db.Column(db.Float, default=-90)\n extent_top = db.Column(db.Float, default=+90)\n\n bookmark_resource = db.relationship(\n Resource, foreign_keys=bookmark_resource_id,\n backref=db.backref('bookmarked_webmaps'))\n\n root_item = db.relationship('WebMapItem', cascade='all')\n\n @classmethod\n def check_parent(cls, parent):\n return isinstance(parent, ResourceGroup)\n\n def to_dict(self):\n return dict(\n id=self.id,\n display_name=self.display_name,\n editable=self.editable,\n root_item=self.root_item.to_dict(),\n bookmark_resource_id=self.bookmark_resource_id,\n extent=(self.extent_left, self.extent_bottom,\n self.extent_right, self.extent_top),\n )\n\n def from_dict(self, data):\n if 'display_name' in data:\n self.display_name = data['display_name']\n\n if 'root_item' in data:\n self.root_item = WebMapItem(item_type='root')\n self.root_item.from_dict(data['root_item'])\n\n if 'bookmark_resource_id' in data:\n self.bookmark_resource_id = data['bookmark_resource_id']\n\n if 'extent' in data:\n self.extent_left, self.extent_bottom, \\\n self.extent_right, self.extent_top = data['extent']\n\n if 'editable' in data:\n self.editable = data['editable']\n\n\nclass WebMapItem(Base):\n __tablename__ = 'webmap_item'\n\n id = db.Column(db.Integer, primary_key=True)\n parent_id = db.Column(db.Integer, db.ForeignKey('webmap_item.id'))\n item_type = db.Column(db.Enum('root', 'group', 'layer'), nullable=False)\n position = db.Column(db.Integer, nullable=True)\n display_name = db.Column(db.Unicode, nullable=True)\n group_expanded = db.Column(db.Boolean, nullable=True)\n layer_style_id = db.Column(db.ForeignKey(Resource.id), nullable=True)\n layer_enabled = db.Column(db.Boolean, nullable=True)\n layer_transparency = db.Column(db.Float, nullable=True)\n layer_min_scale_denom = db.Column(db.Float, nullable=True)\n layer_max_scale_denom = db.Column(db.Float, nullable=True)\n layer_adapter = db.Column(db.Unicode, nullable=True)\n draw_order_position = db.Column(db.Integer, nullable=True)\n\n parent = db.relationship(\n 'WebMapItem', remote_side=id, backref=db.backref(\n 'children', order_by=position, cascade='all, delete-orphan',\n collection_class=ordering_list('position')))\n\n style = db.relationship(\n 'Resource',\n # Temporary solution that allows to automatically\n # remove web-map elements when style is removed\n backref=db.backref('webmap_items', cascade='all')\n )\n\n def to_dict(self):\n if self.item_type in ('root', 'group'):\n children = list(self.children)\n sorted(children, key=lambda c: c.position)\n\n if self.item_type == 'root':\n return dict(\n item_type=self.item_type,\n children=[i.to_dict() for i in children],\n )\n\n elif self.item_type == 'group':\n return dict(\n item_type=self.item_type,\n display_name=self.display_name,\n group_expanded=self.group_expanded,\n children=[i.to_dict() for i in children],\n )\n\n elif self.item_type == 'layer':\n return dict(\n item_type=self.item_type,\n display_name=self.display_name,\n layer_enabled=self.layer_enabled,\n layer_transparency=self.layer_transparency,\n layer_style_id=self.layer_style_id,\n layer_min_scale_denom=self.layer_min_scale_denom,\n layer_max_scale_denom=self.layer_max_scale_denom,\n layer_adapter=self.layer_adapter,\n draw_order_position=self.draw_order_position,\n )\n\n def from_dict(self, data):\n assert data['item_type'] == self.item_type\n if data['item_type'] in ('root', 'group') and 'children' in data:\n self.children = []\n for i in data['children']:\n child = WebMapItem(parent=self, item_type=i['item_type'])\n child.from_dict(i)\n self.children.append(child)\n\n for a in ('display_name', 'group_expanded', 'layer_enabled',\n 'layer_adapter', 'layer_style_id', 'layer_transparency',\n 'layer_min_scale_denom', 'layer_max_scale_denom',\n 'draw_order_position'):\n\n if a in data:\n setattr(self, a, data[a])\n\n\nPR_READ = ResourceScope.read\nPR_UPDATE = ResourceScope.update\n\n_mdargs = dict(read=PR_READ, write=PR_UPDATE)\n\n\nclass _root_item_attr(SP):\n\n def getter(self, srlzr):\n return srlzr.obj.root_item.to_dict()\n\n def setter(self, srlzr, value):\n if srlzr.obj.root_item is None:\n srlzr.obj.root_item = WebMapItem(item_type='root')\n\n srlzr.obj.root_item.from_dict(value)\n\n\nclass WebMapSerializer(Serializer):\n identity = WebMap.identity\n resclass = WebMap\n\n extent_left = SP(**_mdargs)\n extent_right = SP(**_mdargs)\n extent_bottom = SP(**_mdargs)\n extent_top = SP(**_mdargs)\n\n draw_order_enabled = SP(**_mdargs)\n editable = SP(**_mdargs)\n\n bookmark_resource = SRR(**_mdargs)\n\n root_item = _root_item_attr(**_mdargs)\n","repo_name":"annamarieroja/annamarieroja.github.io","sub_path":"nextgisweb/webmap/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"2727769494","text":"import os\nimport json\nimport pandas as pd\n\nimport numpy as np\nfrom datetime import datetime\n\n\ndef dump_json_log(options, train_results, output_directory):\n config = json.load(open(options.config))\n results = {\n 'training': {\n 'trials': train_results,\n 'average_train_auc': np.mean([result['train_auc'] for result in train_results]),\n 'average_valid_auc': np.mean([result['valid_auc'] for result in train_results]),\n 'train_auc_std': np.std([result['train_auc'] for result in train_results]),\n 'valid_auc_std': np.std([result['valid_auc'] for result in train_results]),\n 'average_train_time': np.mean([result['train_time'] for result in train_results])\n },\n 'config': config,\n }\n log_path = os.path.join(output_directory,\n os.path.splitext(os.path.basename(options.config))[0] + '.result.json')\n json.dump(results, open(log_path, 'w'), indent=2)\n\n\ndef dump_json_opt_log(bst_params, trials, output_path):\n\n ret = {\n 'bst_params': bst_params,\n 'trials': trials\n }\n\n\ndef update_result_summary(run_file, options, train_results):\n\n df = pd.DataFrame()\n\n df['datetime'] = [datetime.now().strftime('%Y/%m/%d %H:%M:%S')]\n df['run_file'] = [run_file] # os.path.basename(__file__)\n df['config_file'] = [options.config]\n df['average_train_auc'] = [np.mean([result['train_auc'] for result in train_results])]\n df['average_valid_auc'] = [np.mean([result['valid_auc'] for result in train_results])]\n df['train_auc_std'] = [np.std([result['train_auc'] for result in train_results])]\n df['valid_auc_std'] = [np.std([result['valid_auc'] for result in train_results])]\n\n result_file = '../data/output/result_summary.csv'\n if os.path.exists(result_file):\n ret_df = pd.read_csv(result_file)\n ret_df = pd.concat([ret_df, df], axis=0)\n else:\n ret_df = df\n\n ret_df.to_csv(result_file, index=False)\n","repo_name":"SS1031/kaggle-HomeCreditDefaultRisk","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"76"} +{"seq_id":"9390116702","text":"\"\"\"Server for creating Flask app and handling routes\"\"\"\n\nfrom flask import Flask, render_template\nfrom model import connect_to_db, db\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef display_homepage():\n \"\"\"Show homepage\"\"\"\n return render_template('index.html')\n\n\nif __name__ == \"__main__\":\n\n connect_to_db(app)\n app.run(debug=True)\n","repo_name":"Nmargolis/landlord-data-sf","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"35684767239","text":"# A = Rock X = Lose\n# B = Paper Y = Draw\n# C = Scissors Z = Win\n\n# Rock 1p Lose 0p\n# Paper 2p Draw 3p\n# Scissors 3p Win 6p\n\n# Score per round = Shape + Outcome\n\nclass Shape:\n def __init__(self, losesAgainst, drawAgainst, winsAgainst, points):\n self.losesAgainst = losesAgainst\n self.drawAgainst = drawAgainst\n self.winsAgainst = winsAgainst\n self.points = points\n\nclass Rock (Shape):\n def __init__(self):\n super().__init__('B', 'A', 'C', 1)\n\nclass Paper (Shape):\n def __init__(self):\n super().__init__('C', 'B', 'A', 2)\n\nclass Scissors (Shape):\n def __init__(self):\n super().__init__('A', 'C', 'B', 3)\n\ndef getShapeObj(shape: str):\n if shape == 'A':\n return Rock()\n elif shape == 'B':\n return Paper()\n elif shape == 'C':\n return Scissors()\n\ndef getSelectionByDesiredResult(opponentShape: Shape, desiredResult: str):\n if desiredResult == 'X':\n return opponentShape.winsAgainst\n elif desiredResult == 'Y':\n return opponentShape.drawAgainst\n elif desiredResult == 'Z':\n return opponentShape.losesAgainst\n\ndef getPointsForResult(result):\n if result == 'X':\n return 0\n elif result == 'Y':\n return 3\n elif result == 'Z':\n return 6\n\nfile = open('input.txt', 'r')\n\ntotalPoints = 0\n\nfor line in file:\n opponentSelection, desiredResult = line.split();\n\n opponentShape = getShapeObj(opponentSelection)\n myShape = getShapeObj(getSelectionByDesiredResult(opponentShape, desiredResult))\n\n pointsForThisOutcome = getPointsForResult(desiredResult)\n pointsForThisShape = myShape.points\n\n totalPoints += pointsForThisOutcome + pointsForThisShape\n\n# answer to part 2\nprint('totalPoints: ' + str(totalPoints))","repo_name":"elvekjaer/adventofcode22","sub_path":"02/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"73594029365","text":"#!/usr/bin/env python3\nimport sqlite3\n\ndef init(dbPath):\n print(\"[DB] Starting database\")\n global path\n path = dbPath\n prepare(\"gamedata.db\")\n c.execute(\"CREATE TABLE IF NOT EXISTS groups (userID INTEGER, posX INTEGER DEFAULT 0, posY INTEGER DEFAULT 0)\")\n end()\n\ndef prepare(dbName):\n global db\n global c\n db = sqlite3.connect(path + dbName)\n c = db.cursor()\n\ndef newGroup(username):\n print(\"[DB] Creating new group\")\n prepare(\"gamedata.db\")\n c.execute(\"INSERT INTO groups (userID) VALUES (\" + username + \")\")\n db.commit()\n db.close()\n\ndef end():\n try:\n db.commit()\n db.close()\n print(\"[DB] Closing the connection to the database was succesful\")\n return True\n except:\n print(\"[DB] Closing the connection to the database failed\")\n return False\n\nif __name__ == \"__main__\":\n print(\"This is a module you fool!\")\n","repo_name":"Benjadahl/BenjaWorld","sub_path":"dbHandler.py","file_name":"dbHandler.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"35906880465","text":" # -*- coding: utf-8 -*-\nfrom django.shortcuts import render\n\nARABIZI_CHARS_AR = u\"ا ب ت ث ج ح خ د ذ ر ز س ش ص د ط ظ ع غ ف ق ك ل م ن ه و ي\".split()\nARABIZI_CHARS_EN = u\"a b t th j 7 `7 d th r z s sh 9 `9 6 `6 3 `3 f \\\"9 k l m n h w y\".split()\nARABIZI_CHARS = dict(zip(ARABIZI_CHARS_AR, ARABIZI_CHARS_EN))\n\ndef convert_arabizi(s):\n return u\"\".join([ARABIZI_CHARS.get(x,x) for x in s])\n\ndef arabizi(request, word=None):\n word = word or request.GET.get(\"w\")\n return render(\n request,\n \"arabizi.html\",\n {\n \"word\": word,\n \"aword\": word and convert_arabizi(word),\n },\n )\n\n# Create your views here.\ndef hello_world(request, username=None):\n return render(\n request,\n \"hello_world.html\",\n {\n \"name\": username,\n },\n )\n\n\n","repo_name":"koutbo6/djc_1stproj","sub_path":"myfirstapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"42380193391","text":"# non repeating letter\n\n# create a list and a subsequent set from the letters in the string, all lowercase\n# count each occurence until the count is greater than 2. if there are none return None\n# step thru each letter in the list to see if it is the first letter upper of lower case.\n# return that letter\n\ndef first_non_repeating_letter(string):\n\tstringLwr = string.lower()\n\tfor letter in stringLwr:\n\t\t\tif stringLwr.count(letter) == 1:\n\t\t\t\treturn string[stringLwr.index(letter)]\n\t\t\t\n\treturn None\n\t\n\ns1='sTress'\n\nprint(first_non_repeating_letter(s1))\n\n\n\n'''Write a function named first_non_repeating_letter that takes a string input, and returns the first character that is not repeated anywhere in the string.\n\nFor example, if given the input 'stress', the function should return 't', since the letter t only occurs once in the string, and occurs first in the string.\n\nAs an added challenge, upper- and lowercase letters are considered the same character, but the function should return the correct case for the initial letter. For example, the input 'sTreSS' should return 'T'.\n\nIf a string contains all repeating characters, it should return an empty string (\"\") or None\n'''\n'''\nEnumerate is also a good option\n\ndef first_non_repeating_letter(string):\n string_lower = string.lower()\n for i, letter in enumerate(string_lower):\n if string_lower.count(letter) == 1:\n return string[i]\n \n return \"\"\n'''\n","repo_name":"OzRhodes/CodeWars","sub_path":"first_non_repeating_letter.py","file_name":"first_non_repeating_letter.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"11885508801","text":"from __future__ import print_function\n__author__ = 'kmchugg'\n\nimport random\nimport numpy as np\nimport scipy.stats as stats\nimport matplotlib.pyplot as plt\nfrom random import sample \nfrom matplotlib import pyplot\nimport statistics\nimport collections\n\nC = 0.15/0.05 #maximum value of the target \naccepted = 0\nrejected = 0\nsample_data = []\np = [0.06,0.06,0.06,0.06,0.06,0.15,0.13,0.14,0.15,0.13,0,0,0,0,0,0,0,0,0,0,] #extra zeros added added to accoujt for the size of q\np_plot = [0,0.06,0.06,0.06,0.06,0.06,0.15,0.13,0.14,0.15,0.13,0,0,0,0,0,0,0,0,0] #to plot the first value is taken as zero as the first value doesn't get printed.\nI = np.ones(20)\nq = 0.05*I\n# print(p)\n# print(q)\n\nfor i in range(10000):\n Y= random.randrange(1,21)\n value_test = C*np.random.rand(1)\n if(value_test <= p[Y-1]/0.05): # the algorithm\n sample_data.append(Y)\n accepted = accepted + 1\n else:\n rejected = rejected + 1\n \nefficiency = accepted / (accepted + rejected)\nprint('---efficiency---')\nprint(efficiency)\nprint('--calculated---')\nprint(1/C)\n\nprint(sample_data)\nvalue = []\nfreqList = (collections.Counter(sample_data)) #the disctionary that stores the frequency of occurrence of numbers\nprint(freqList)\ndenom = (len(sample_data))\nfor i in range(1, (len(freqList)+1)):\n value.append(freqList[i]/denom) #calculating the Probabilities\nprint('---value---')\nprint(value)\n\nx = [1,2,3,4,5,6,7,8,9,10]\ny = value\nprint('---x---')\nprint(x)\n\n\nplt.figure(figsize=(10, 3))\nplt.bar(x,y,align='center') # A bar chart\nplt.plot(p_plot,\"r-\")\nplt.xlabel('Numbers')\nplt.ylabel('Probabilities')\nplt.show()\n\nsam_mean = statistics.mean(sample_data)\nprint('---sample mean---')\nprint(sam_mean)\nsam_variance = statistics.variance(sample_data)\nprint('---sample variance---')\nprint(sam_variance)\n\n\ntheo_mean = 0\ntheo_var = 0\np_cal = [0.06,0.06,0.06,0.06,0.06,0.15,0.13,0.14,0.15,0.13]\nfor i in range(len(p_cal)):\n theo_mean = theo_mean + (i+1)*p_cal[i]\nfor i in range(len(p_cal)):\n theo_var = theo_var + (p_cal[i]*((i+1) - theo_mean)*((i+1) - theo_mean))\nprint('--theoretical mean---')\nprint(theo_mean)\nprint('--theoretical variance---')\nprint(theo_var)\n\nfig = plt.figure()\nplt.hist(p_plot,30,facecolor='b', alpha=1)\nplt.hist(sample_data,30,facecolor='r', alpha=1)\nplt.show()\n\n","repo_name":"SahayDivyanshu/Simulation_Stochastic_Systems","sub_path":"project3/CODE/Q5.py","file_name":"Q5.py","file_ext":"py","file_size_in_byte":2275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"15475028590","text":"class Solution:\n def minSetSize(self, arr: List[int]) -> int:\n count = defaultdict(int)\n for i in arr:\n count[i] += 1\n reps = []\n for i in count:\n reps.append(count[i])\n reps.sort(reverse=True)\n count2 = 0\n count3 = 0\n while count2 < len(arr) //2:\n count2 += reps[count3]\n count3 +=1\n return count3\n \n ","repo_name":"Tolosa-mitiku/leet-code","sub_path":"1338-reduce-array-size-to-the-half/1338-reduce-array-size-to-the-half.py","file_name":"1338-reduce-array-size-to-the-half.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"29392628719","text":"def revisar_horizontal(tablero,fila):\n suma_gato=0\n suma_raton=0\n for i in range(len(tablero[fila])):\n if tablero[fila][i]==\"X\":\n suma_gato+=1\n elif tablero[fila][i]==\"O\":\n suma_raton+=1\n if suma_gato==3:\n return -1\n elif suma_raton==3:\n return 1\n else:\n return 0\n\ndef revisar_vertical(tablero,columna):\n suma_gato=0\n suma_raton=0\n for i in range(len(tablero)):\n if tablero[i][columna]==\"X\":\n suma_gato+=1\n elif tablero[i][columna]==\"O\":\n suma_raton+=1\n if suma_gato==3:\n return -1\n elif suma_raton==3:\n return 1\n else:\n return 0\n\ndef revisar_diagonal_derecha(tablero):\n suma_gato=0\n suma_raton=0\n for i in range(len(tablero)):\n if tablero[i][i]==\"X\":\n suma_gato+=1\n elif tablero[i][i]==\"O\":\n suma_raton+=1\n if suma_gato==3:\n return -1\n elif suma_raton==3:\n return 1\n else:\n return 0\n\ndef revisar_diagonal_izquierda(tablero):\n suma_gato=0\n suma_raton=0\n for i in range(len(tablero)):\n if tablero[i][2-i]==\"X\":\n suma_gato+=1\n elif tablero[i][2-i]==\"O\":\n suma_raton+=1\n if suma_gato==3:\n return -1\n elif suma_raton==3:\n return 1\n else:\n return 0\n\ndef jugar(tablero,fila,columna,marca):\n if fila>=0 and fila=0 and columna 0 and arr[parent(i)] > v:\n arr[i], arr[parent(i)] = arr[parent(i)], arr[i]\n i = parent(i)\n \n#Fuction to delete indicated value\ndef delete(arr, v):\n \n for i in range(len(arr)-1):\n if arr[i] == v:\n arr[i], arr[len(arr)-1] = arr[len(arr)-1], arr[i]\n arr.pop()\n sink(arr, i)\n\n#Function to retun min value of heap\ndef find_min(arr):\n print (arr[0])\n\nif __name__ == '__main__':\n arr = []\n number_queries = int(input())\n for i in range (number_queries):\n query = list(map(int,input().strip().split()))\n if query[0] == 1:\n insert(arr, query[1])\n elif query[0] == 2:\n delete(arr, query[1])\n else:\n find_min(arr)","repo_name":"Gabospa/PythonHeaps","sub_path":"Qheap.py","file_name":"Qheap.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"42409250775","text":"import datetime\n\n\ndef parse_dict(data: dict, path_list=None, res=None) -> list:\n \"\"\"\n Recursive function which makes iris globals compatible data structure from dict\n\n :param data: dict, required field\n :param path_list:\n :param res:\n :return: list\n \"\"\"\n if res is None:\n res = []\n if path_list is None:\n path_list = []\n\n new_data = {}\n if isinstance(data, list):\n for i, item in enumerate(data):\n new_data[i] = item\n else:\n new_data = data\n\n if isinstance(new_data, dict):\n for key, value in new_data.items():\n\n if isinstance(value, list):\n i = 0\n for el in value:\n path_part = [key, i]\n if isinstance(el, dict):\n parse_dict(el, path_list + path_part, res)\n else:\n if isinstance(el, (datetime.date, datetime.datetime)):\n el = el.isoformat()\n res.append({\n \"path_list\": path_list + path_part,\n \"value\": el\n })\n i += 1\n\n elif isinstance(value, dict):\n mod_path = path_list + [key]\n parse_dict(value, mod_path, res)\n\n else:\n mod_path = path_list + [key]\n if isinstance(value, (datetime.date, datetime.datetime)):\n value = value.isoformat()\n res.append({\n \"path_list\": mod_path,\n \"value\": value\n })\n return res\n","repo_name":"danoleg/mongo-to-iris-migration","sub_path":"app/helpers/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"} +{"seq_id":"36187052188","text":"import unittest\nimport sys\nsys.path.append('classifier/')\nsys.path.append('data/')\nimport s1_proximity\nimport data\n\nclass TestUnitProximityTransitions(unittest.TestCase):\n\n def setUp(self):\n self.data = data.Data()\n self.proximity = s1_proximity.ProximityState()\n\n def test_transition_19(self):\n self.data.set_proximity(19)\n ret = self.proximity.handle()\n\n self.assertTrue(ret == \"Inductive\", \"The expected transition was Inductive, we got: \" + ret)\n\n def test_transition_20(self):\n self.data.set_proximity(20)\n ret = self.proximity.handle()\n\n self.assertTrue(ret == \"Proximity\", \"The expected transition was Proximity, we got: \" + ret)\n\n def test_transition_10(self):\n self.data.set_proximity(10)\n ret = self.proximity.handle()\n\n self.assertTrue(ret == \"Inductive\", \"The expected transition was Inductive, we got: \" + ret)\n\n def test_transition_30(self):\n self.data.set_proximity(30)\n ret = self.proximity.handle()\n\n self.assertTrue(ret == \"Proximity\", \"The expected transition was Proximity, we got: \" + ret)\n\nif __name__ == '__main__':\n unittest.main()\n ","repo_name":"Seanmullan/type-swipe","sub_path":"src/RaspberryPi/tests/test_unit_proximity_transitions.py","file_name":"test_unit_proximity_transitions.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"} +{"seq_id":"34275874370","text":"from copy import copy\nfrom math import inf\n\nfrom enums.enums import NoteType\n\n\nclass UltrastarMapGenerator:\n\n @staticmethod\n def create_headers(artist, title, bpm, gap, mp3):\n return [\n '#TITLE: ' + title,\n '#ARTIST: ' + artist,\n '#MP3: ' + mp3,\n '#BPM: ' + bpm,\n '#GAP: ' + gap,\n ]\n\n @staticmethod\n def create_line(note_type, beat_number, time_before_next_syllable, pitch, syllable):\n return NoteType.get_note_type_string(note_type) + ' ' + \\\n beat_number + ' ' + \\\n time_before_next_syllable + ' ' + \\\n pitch + ' ' + \\\n syllable\n\n @staticmethod\n def create_break_line(beat_number):\n return NoteType.get_note_type_string(NoteType.LINE_BREAK) + ' ' + beat_number\n\n @staticmethod\n def create_line_break():\n return NoteType.get_note_type_string(NoteType.LINE_BREAK)\n\n @staticmethod\n def end_of_the_file():\n return NoteType.get_note_type_string(NoteType.END_OF_THE_FILE)\n\n @staticmethod\n def generate_map_lines(notes_with_duration_and_syllables):\n lines = []\n for note in notes_with_duration_and_syllables:\n line = ''\n if note[3] == NoteType.LINE_BREAK:\n line = UltrastarMapGenerator.create_break_line(str(note[0]))\n else:\n line = UltrastarMapGenerator.create_line(\n NoteType.STANDARD_NOTE, str(note[0]), str(note[1]), str(int(note[2])), note[3]\n )\n lines.append(line)\n lines.append(UltrastarMapGenerator.end_of_the_file())\n return lines\n\n @staticmethod\n def get_gap(notes_with_duration):\n first_note = notes_with_duration[0]\n gap_in_beats = 0\n if first_note[1] == -inf:\n gap_in_beats = first_note[0]\n del notes_with_duration[0]\n return notes_with_duration, gap_in_beats\n\n @staticmethod\n def get_duration_with_note(extracted_midis, duration):\n lines = []\n line = [duration, extracted_midis[0]]\n for midi_index in range(1, len(extracted_midis)):\n midi_note = extracted_midis[midi_index]\n if midi_note == line[1] or UltrastarMapGenerator.is_octave(line[1], midi_note):\n line[0] += duration\n else:\n lines.append(copy(line))\n line[0] = duration\n line[1] = midi_note\n lines.append(copy(line))\n return lines\n\n @staticmethod\n def get_ultrastar_note(midi_note):\n return midi_note - 60\n\n @staticmethod\n def is_octave(note_a, note_b):\n return note_a - 12 == note_b\n\n @staticmethod\n def get_beat_numbers(duration_with_notes):\n duration_with_notes[0].insert(0, 0)\n for index in range(1, len(duration_with_notes)):\n previous_element = duration_with_notes[index - 1]\n beat_number = previous_element[0] + previous_element[1] + 1\n duration_with_notes[index].insert(0, beat_number)\n return duration_with_notes\n\n @staticmethod\n def get_notes_with_duration_and_syllables(notes_with_duration, syllables):\n syllables_index = 0\n notes_with_duration_and_syllables = []\n for index, note_with_duration in enumerate(notes_with_duration):\n if note_with_duration[2] == -inf:\n syllable = NoteType.LINE_BREAK\n else:\n syllable = syllables[syllables_index]\n if syllable == NoteType.LINE_BREAK:\n beat_number = notes_with_duration[index][0]\n line = UltrastarMapGenerator.create_dummy_break_line(beat_number)\n notes_with_duration_and_syllables.append(line)\n syllables_index += 1\n syllable = syllables[syllables_index]\n syllables_index += 1\n note_with_duration.append(syllable)\n notes_with_duration_and_syllables.append(note_with_duration)\n return notes_with_duration_and_syllables\n\n @staticmethod\n def create_dummy_break_line(beat_number):\n return [beat_number, 0, 0, NoteType.LINE_BREAK]\n\n @staticmethod\n def write_list_to_file(file_name, elements):\n with open(file_name, 'w') as file:\n for element in elements:\n file.write(element + '\\n')\n file.close()\n\n @staticmethod\n def round_beats(us_lines):\n return list(map(lambda us_line: [round(us_line[0]), us_line[1]], us_lines))\n\n @staticmethod\n def midi_to_ultrastar_note(midi_notes):\n for i, midi_note in enumerate(midi_notes):\n midi_note[-1] = UltrastarMapGenerator.get_ultrastar_note(midi_note[-1])\n return midi_notes\n","repo_name":"Pineapple69/karioki_mapper","sub_path":"ultrastar_map_generator/ultrastar_map_generator.py","file_name":"ultrastar_map_generator.py","file_ext":"py","file_size_in_byte":4772,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"73003114487","text":"from datetime import datetime\nfrom django.db import models\n\nclass TimeStampedModel(models.Model):\n created_at = models.DateTimeField(auto_now_add=True)\n modified_at = models.DateTimeField(auto_now=True)\n\n class Meta:\n abstract = True\n\nclass Rental(TimeStampedModel):\n name = models.CharField(max_length=30)\n\nclass Reservation(TimeStampedModel):\n rental = models.ForeignKey(Rental, on_delete=models.CASCADE, null=False, blank=False)\n checkin = models.DateField()\n checkout = models.DateField()","repo_name":"qnx-dev/rentalproject","sub_path":"base/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"8231208295","text":"import numpy as np\n\nR, C = map(int, input().split())\n\nB = []\n\nfor i in range(R):\n b = list(input())\n B.append(b)\n\nout = [[B[i][j] for j in range(C)] for i in range(R)]\n\nfor i in range(R):\n for j in range(C):\n if B[i][j] == \".\":\n continue\n elif B[i][j] == \"#\":\n continue\n else:\n num = int(B[i][j])\n for k in range(num+1):\n for l in range(num+1 - k):\n aa = np.clip(i + k, 0, R - 1)\n bb = np.clip(i - k, 0, R - 1)\n cc =np.clip(j + l, 0, C - 1)\n dd = np.clip(j - l, 0, C - 1)\n out[aa][cc] = \".\"\n out[bb][cc] = \".\"\n out[aa][dd] = \".\"\n out[bb][dd] = \".\"\nfor o in out:\n print(\"\".join(o))\n","repo_name":"SWEET-creator/Atcoder","sub_path":"AtCoder_Beginner_Contest/295/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"73978390647","text":"from bs4 import BeautifulSoup\nimport requests\nimport pandas as pd\n\n\"\"\"\nWebscraping project: Getting all listing (with Requests) from Airbnb in India\nResults include: Name of listing, description, old price, original price and star reviews\nSaving results to a CSV file\n\"\"\"\n\n# Airbnb URL to get\nurl = 'https://www.airbnb.com/s/India/homes?adults=1&tab_id=home_tab&refinement_paths%5B%5D=%2Fhomes&query=India' \\\n '&place_id=ChIJkbeSa_BfYzARphNChaFPjNc&flexible_trip_lengths%5B%5D=one_week&price_filter_input_type=0' \\\n '&price_filter_num_nights=5&channel=EXPLORE&search_type=user_map_move&ne_lat=59.139778890987905&ne_lng=93' \\\n '.6332587156628&sw_lat=4.84557715667748&sw_lng=52.15767331460464&zoom=4&zoom_level=4&search_by_map=true'\n\nr = (requests.get(url)).content\n\nsoup = BeautifulSoup(r, 'html.parser')\n\n# Results are written to empty list Houses\nhouses = []\n\n# Loop from page 1 to page 15 of Airbnb\nfor i in range(1, 16):\n\n # Webscraping html\n div = soup.find('div', class_='gh7uyir giajdwt g14v8520 dir dir-ltr')\n div_card = div.find_all('div', class_='g1qv1ctd cb4nyux dir dir-ltr')\n\n for item in div_card:\n\n # Every loop sabes the item result to a dictionary\n dict_house = {}\n\n name = item.find('div', class_='t1jojoys dir dir-ltr').string\n description = item.find('span', class_='t6mzqp7 dir dir-ltr').string\n list_price = item.find('span', class_='a8jt5op dir dir-ltr').string\n price = list_price.split()\n original_price = ''\n if len(price) == 7:\n old_price = float(price[1])\n original_price = float(price[6])\n else:\n old_price = float(price[1])\n original_price = old_price\n\n stars = item.find('span', class_='t5eq1io r4a59j5 dir dir-ltr')\n\n if stars is not None:\n stars = ((stars['aria-label']).split())[0]\n else:\n stars = 'No Review'\n\n # Dictionary\n dict_house = {'page': i, 'name': name, 'description': description, 'old_price': old_price,\n 'original_price': original_price, 'stars': stars}\n\n # Adding the dictionary to a list\n houses.append(dict_house)\n\n # Getting the link for the next page\n before_np = soup.find('a', class_='l1j9v1wn c1ytbx3a dir dir-ltr')\n np = before_np.find('href')\n\n # If to verify if next page exists. If not, stop running\n if np is not None:\n cnp = 'https://www.airbnb.com' + np.get('href')\n\n url = str(cnp)\n\n r = (requests.get(url)).content\n\n soup = BeautifulSoup(r, 'html.parser')\n else:\n print('stop')\n\n# Using Pandas to save results to a CSV\ndata_frame = pd.DataFrame.from_dict(houses)\ndata_frame.to_csv('airbnb_stays.csv')\n","repo_name":"pesseguita/webscraper-airbnb-to-csv","sub_path":"webscraper-airbnb-to-csv/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"41990119185","text":"\"\"\"\nFile: anagram.py\nName:Cherry\n----------------------------------\nThis program recursively finds all the anagram(s)\nfor the word input by user and terminates when the\ninput string matches the EXIT constant defined\nat line 19\n\nIf you correctly implement this program, you should see the\nnumber of anagrams for each word listed below:\n * arm -> 3 anagrams\n * contains -> 5 anagrams\n * stop -> 6 anagrams\n * tesla -> 10 anagrams\n * spear -> 12 anagrams\n\"\"\"\n\n# Constants\nFILE = 'dictionary.txt' # This is the filename of an English dictionary\nEXIT = '-1' # Controls when to stop the loop\n\nmay_anagrams_list = []\ndic = {}\nanagrams_list = []\ntimes = 0\n\n\ndef main():\n global may_anagrams_list, anagrams_list, times\n print(\"Welcome to stanCode \\\" Anagram Generator\\\"(or -1 to quit)\")\n read_dictionary()\n while True:\n s = input(\"Find anagrams for: \")\n if s == EXIT:\n break\n else:\n may_anagrams_list = []\n anagrams_list = []\n times = 0\n find_anagrams(s)\n\n\ndef read_dictionary():\n global dic\n with open(FILE, \"r\") as f:\n for word in f:\n sub = word[0:1]\n word = word[:\"\\n\".find(word)]\n if sub in dic:\n dic[sub] += [word]\n else:\n dic[sub] = []\n dic[sub] += [word]\n\n\ndef get_all_may_anagrams_list(s_list, letter_change_list):\n # 獲得要排列組合的字母的清單(s_list)、獲得全新的清單(letter_change_list)\n global may_anagrams_list\n # Base Case\n if len(s_list) == len(letter_change_list):\n may_anagrams_str = \"\" # 建立新的字��,用來把排列好的清單(letter_change_list)變成字串(may_anagrams_str)\n for letter in letter_change_list:\n # 處理重複的字母\n while len(letter) != 1: # 如果是重複的字母,把數字清掉\n letter = letter[0]\n may_anagrams_str += str(letter)\n if may_anagrams_str not in may_anagrams_list:\n may_anagrams_list += [may_anagrams_str]\n # Self-Similarity\n else: # 排列組合\n for letter in s_list:\n if letter not in letter_change_list:\n letter_change_list += [letter]\n get_all_may_anagrams_list(s_list, letter_change_list)\n letter_change_list.pop()\n\n\ndef find_anagrams(s):\n \"\"\"\n :param s:str, the word need to search in dictionary\n :return:(directly print)\n \"\"\"\n # get all may_anagrams\n global anagrams_list, times\n s_list = []\n double_count = 0\n # 檢查詞語中有沒有重複的字母\n for i in range(len(s)):\n if s[i] in s[i + 1:]: # 如果有重複,進行加工\n double_count += 1\n s_list += [s[i] + str(double_count)]\n else:\n s_list += s[i]\n # print(s_list)\n # 把詞語(沒有重複的字母)丟進去,獲得所有字母(含重複的字母)的排列組合\n get_all_may_anagrams_list(s_list, [])\n # print(may_anagrams_list) # 到時交作業要刪掉\n # find anagrams in dictionary\n for i in range(len(may_anagrams_list)):\n if str(may_anagrams_list[i]) in dic[str(may_anagrams_list[i][0])]:\n anagrams_list += [may_anagrams_list[i]]\n times += 1\n print(\"Searching...\")\n print(\"Find:\" + str(may_anagrams_list[i]))\n print(\"Searching...\")\n print(str(times) + \" anagrams: \"+str(anagrams_list))\n print(\"\")\n\n\ndef has_prefix(sub_s):\n \"\"\"\n :param sub_s:\n :return:\n \"\"\"\n pass\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Cherry-RB/sc-projects","sub_path":"stanCode_Projects/boggle_game_solver/anagram.py","file_name":"anagram.py","file_ext":"py","file_size_in_byte":3636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"22514906652","text":"from tkinter import *\r\nfrom src.dictionary import dictionary\r\n\r\ndef insert1(data):\r\n if type(data) == list:\r\n for item in data:\r\n t.insert(END, item + '\\n')\r\n else:\r\n t.insert(END, data + '\\n')\r\n\r\ndef search_meaning():\r\n word = ent_val.get()\r\n result = dictionary(word)\r\n t.delete(1.0, END)\r\n if type(result) == list:\r\n insert1(result)\r\n else:\r\n insert1(result)\r\n\r\ndef clear():\r\n t.delete(1.0, END)\r\n ent.delete(0, END)\r\n\r\nroot = Tk()\r\nroot.title(\"Dictionary\")\r\n\r\nhead = Label(root, text=\"Python Dictionary\", bg=\"red\", fg=\"white\")\r\nhead.pack(fill=X)\r\n\r\nlabel1 = Label(root, text=\"Enter Word\")\r\nlabel1.pack(fill=X)\r\n\r\nent_val = StringVar()\r\nent = Entry(root, textvariable=ent_val)\r\nent.pack()\r\n\r\nbutton = Button(root, text=\"Meaning\", command=search_meaning, bg=\"orange\")\r\nbutton.pack()\r\n\r\nt = Text(root)\r\nt.pack(fill=X)\r\n\r\nlabel2 = Label(root, text=\"Clear Screen\")\r\nlabel2.pack()\r\n\r\nbutton2 = Button(root, text=\"Clear\", command=clear, bg=\"orange\")\r\nbutton2.pack()\r\n\r\nroot.mainloop()\r\n","repo_name":"pras-ops/My_Dictionary_App","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"1554283972","text":"import scrapy\n\n\nclass VetclinicSpider(scrapy.Spider):\n name = 'vetclinic'\n start_urls = ['http://www.findalocalvet.com/']\n\n def parse(self, response):\n cities = response.css('#SideByCity .itemresult a::attr(href)').getall()\n for city in cities:\n link = response.urljoin(city)\n yield scrapy.Request(link, callback=self.parsecity)\n\n\n def parsecity(self, response):\n clinincs = response.css('.org::attr(href)').getall()\n for clinic in clinincs:\n link = response.urljoin(clinic)\n yield scrapy.Request(link, callback=self.parseclinic)\n \n Nextpage = response.css('a.dataheader:contains(\"Next\")::attr(href)').get()\n if Nextpage:\n \n Nextlink = response.urljoin(Nextpage)\n yield scrapy.Request(Nextlink, callback=self.parsecity) \n\n def parseclinic(self, response):\n \n yield {\n \n ' Name ' : response.css('.Results-Header h1::text').get(),\n ' city ' : response.css('.locality::text').get(), \n ' state ' : response.css('.region::text').get(), \n ' phone ' : response.css('.Phone::text').get(),\n ' site ' : response.url,\n } ","repo_name":"Manoj-M-DS/WEB-Scraping","sub_path":"vetclinic.py","file_name":"vetclinic.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"33853606353","text":"#!/usr/bin/python\r\n# -*- coding: utf-8 -*-\r\n\r\n\r\n# import matplotlib.pylab as plt\r\nimport datetime as dt\r\nimport config\r\n\r\n\r\n# funkcja aktualizuje pliki z danymi statystycznymi użytkownika\r\n\r\ndef check_date():\r\n def update(cur_day: dt.date, last_day: dt.date, w_file: []):\r\n dif = (cur_day - last_day).days\r\n if dif > config.positions:\r\n w_file.clear()\r\n for d in range(config.positions):\r\n new_list = [f'{(cur_day - dt.timedelta(days=d)).isoformat()} 0 0 0 0']\r\n w_file.extend(new_list)\r\n else:\r\n while dif > 0:\r\n dif -= 1\r\n new_list = [f'{(cur_day - dt.timedelta(days=dif)).isoformat()} 0 0 0 0']\r\n w_file = new_list + w_file\r\n w_file = w_file[:config.positions]\r\n return w_file\r\n\r\n def create_new(cur_day: dt.date, w_file: []):\r\n w_file.clear()\r\n for d in range(config.positions):\r\n new_list = [f'{(cur_day - dt.timedelta(days=d)).isoformat()} 0 0 0 0']\r\n w_file.extend(new_list)\r\n return w_file\r\n\r\n with open(f'statistics\\\\{config.nick}.txt', 'r', encoding='utf-8') as f:\r\n user_stats = f.read().split('\\n')\r\n\r\n today = dt.date.today()\r\n if user_stats[0] == '':\r\n user_stats = create_new(today, user_stats)\r\n else:\r\n temp_var = user_stats[0].split(' ')[0].split('-')\r\n previous = dt.date(int(temp_var[0]), int(temp_var[1]), int(temp_var[2]))\r\n if previous > today:\r\n # data ostatniego logowania znajduje się chronologicznie poźniej niż data dzisiejsza (wg systemu)\r\n print('error occurred due to time travel - check your system time')\r\n elif previous < today:\r\n user_stats = update(today, previous, user_stats)\r\n\r\n new_part = ''\r\n for i in user_stats:\r\n new_part += f'{i}\\n'\r\n\r\n with open(f'statistics\\\\{config.nick}.txt', 'w', encoding='utf-8') as f:\r\n f.write(new_part[:-1])\r\n return\r\n\r\n\r\n# funkcja wyświetla wykres punktów z ostatnich 7 dni\r\n\r\n# def show_plot():\r\n# with open(f'statistics\\\\{config.nick}.txt', 'r', encoding='utf-8') as f:\r\n# src = f.read().split('\\n')\r\n# dates = []\r\n# pol_cor = []\r\n# eng_cor = []\r\n# for e in src[:7]:\r\n# i = e.split(' ')\r\n# temp_var = i[0].split('-')\r\n# temp_date = dt.date(int(temp_var[0]), int(temp_var[1]), int(temp_var[2]))\r\n# i[0] = temp_date.strftime('%b %d.')\r\n# dates += [i[0]]\r\n# pol_cor += [int(i[3])]\r\n# eng_cor += [int(i[4])]\r\n#\r\n# plt.plot(dates, pol_cor, 'bo-', dates, eng_cor, 'ro-')\r\n# plt.ylim(0)\r\n# plt.grid(True, alpha=0.2)\r\n# plt.title('wykaz uzyskanych punktów za gry:')\r\n# plt.legend(['w wersji polskiej', 'w wersji angielskiej'], loc='upper left')\r\n# plt.show()\r\n#\r\n# return\r\n\r\n\r\n# funkcja zwraca zmienną string ze sformatowanym tekstem\r\n# prezentującym dane statystyczne - wystarczy go wyświetlić\r\n\r\ndef show_stats_full():\r\n with open(f'statistics\\\\{config.nick}.txt', 'r', encoding='utf-8') as f:\r\n user_stats = f.read().split('\\n')\r\n ret_file = 'data'.center(18, ' ') + 'liczba'.center(16, ' ') + 'liczba'.center(28, ' ') +\\\r\n 'liczba odgadniętych słów'.center(28, ' ') + '\\n' +\\\r\n 'rozgrywek'.center(13, ' ') + 'rozgrywek'.center(11, ' ') + 'wyświetlony słów'.center(20, ' ') +\\\r\n 'po polsku'.center(13, ' ') + '|' + 'po angielsku'.center(14, ' ') + '\\n\\n'\r\n for i in user_stats:\r\n temp_var = i.split(' ')\r\n ret_file += f'{temp_var[0].center(11)}{temp_var[1].center(22)}' \\\r\n f'{temp_var[2].center(28)}{temp_var[3].center(18)} {temp_var[4].center(21)}\\n'\r\n # print(ret_file)\r\n return ret_file\r\n\r\n\r\n# funkcja aktualizująca statystyki po każdej grze\r\n# 1. argument - liczba sesji (domyślnie 1)\r\n# 2. argument - liczba wyświetlonych par do odgadnięcia\r\n# 3. argument - liczba poprawnie odgadniętych par w trakcie jednej gry w wersji polskiej\r\n# 4. argument - liczba poprawnie odgadniętych par w trakcie jednej gry w wersji angielskiej\r\n\r\ndef after_session(sessions: int = 1, shown_words: int = 0, pol_correct: int = 0, eng_correct: int = 0):\r\n with open(f'statistics\\\\{config.nick}.txt', 'r', encoding='utf-8') as f:\r\n user_stats = f.read().split('\\n', 1)\r\n\r\n temp_var = user_stats[0].split(' ')\r\n temp_var[1] = f'{sessions + int(temp_var[1])}'\r\n temp_var[2] = f'{shown_words + int(temp_var[2])}'\r\n temp_var[3] = f'{pol_correct + int(temp_var[3])}'\r\n temp_var[4] = f'{eng_correct + int(temp_var[4])}'\r\n user_stats[0] = f'{temp_var[0]} {temp_var[1]} {temp_var[2]} {temp_var[3]} {temp_var[4]}\\n'\r\n\r\n new_part = f'{user_stats[0]}{user_stats[1]}'\r\n with open(f'statistics\\\\{config.nick}.txt', 'w', encoding='utf-8') as f:\r\n f.write(new_part)\r\n return\r\n\r\n\r\n# if __name__ == \"__main__\":\r\n# pass\r\n","repo_name":"Jakub-Jalt/NPG_Fiszki","sub_path":"mode_stat.py","file_name":"mode_stat.py","file_ext":"py","file_size_in_byte":4945,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"16452058228","text":"#!env python\n\nOUTPUT_DIR = \"../output\" # Relative path to output files\nCLASS_LABEL = \"label\" # Name of the attribute you classify for\n\nimport sys\nimport os\nimport pickle\nimport Models\n\ndef convert_output_dir(directory):\n \"\"\"\n Looks in the cwd, parent dir, and sibling dirs for the output directory.\n Calls sys.exit(1) on failed search for output file dir.\n\n Otherwise, returns the relative path to the output directory.\n \n \"\"\"\n\n if not os.path.isdir(directory):\n dirname = os.path.split(directory)[1]\n dircontents = os.listdir(os.getcwd())\n cwd_name = os.path.split(os.getcwd())[1]\n if os.path.isdir(dirname):\n directory = dirname\n elif cwd_name == dirname:\n directory = os.getcwd()\n elif \"eeg.py\" in dircontents or \"README.md\" in dircontents:\n print(\"No output files located. Exiting!\")\n sys.exit(1)\n else:\n sys.stderr.write(\"\"\"ERROR: Please execute this script\n from its native directory. Exiting!\"\"\")\n print(\"ERROR: Please execute this script from its native directory.\")\n sys.exit(1)\n return os.path.relpath(directory)\n\ndef get_file_list(path):\n \"Returns a list of the files at :path\"\n\n file_list = map(lambda x: os.path.join(path, x), os.listdir(path))\n return file_list\n\ndef get_file_contents(files):\n \"\"\"\n Takes in a list of files :files and attempts to loop over each file.\n For each file, it attempts to unpickle the contents, which should have\n been loaded into the file using the pickle module and the ThinkWave\n connector.\n\n \"\"\"\n\n file_contents = []\n for fn in files:\n file_contents.append(pickle.load(open(fn, \"rb\")))\n return file_contents\n\nif __name__ == '__main__':\n training_file_dir = convert_output_dir(OUTPUT_DIR)\n training_file_list = get_file_list(training_file_dir)\n training_data = get_file_contents(training_file_list)\n training_set = Models.TrainingSet(CLASS_LABEL, training_data)\n proc = training_set.processor\n # Processor methods:\n # get_point_selection(label=None, user=None, session_number=None, feature=None)\n # get_mean/media/mode/variance/stdev(same as above)\n# print(proc.get_point_selection(feature=\"theta\"))\n# print(training_set.processor.get_points_by_label(label_name=\"Blue\"))\n# print(training_set.processor.get_point_selection(label=\"Blue\", user=\"daniel\", feature=\"theta\"))\n# print(proc.get_stdev(feature=\"theta\", label=\"Blue\", user=\"daniel\"))\n print(proc.get_variance(feature=\"theta\", label=\"Blue\", user=\"michael\"))\n sys.exit(0)\n\n","repo_name":"georgeBoole/BrainTrain","sub_path":"analysis/Analyze.py","file_name":"Analyze.py","file_ext":"py","file_size_in_byte":2626,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"77"} +{"seq_id":"7331352182","text":"\"\"\"\r\nfor/while\r\n0 10\r\n1 9\r\n2 8\r\n3 7\r\n4 6\r\n5 5\r\n6 4\r\n7 3\r\n8 2\r\n\"\"\"\r\ncont2 = 10\r\n\r\nfor cont1 in range(9):\r\n print(f'cont1 = {cont1} cont2 = {cont2}')\r\n cont1 += 1\r\n cont2 -= 1\r\nprint('\\n')\r\nfor p, r in enumerate(range(10, 1, -1)):\r\n print(f'progressivo = {p} regressivo = {r}')\r\n\r\n","repo_name":"rianteam22/outros","sub_path":"contadores.py","file_name":"contadores.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"39986526485","text":"from datetime import datetime, date, timedelta, timezone\nfrom flask import jsonify, abort\nimport jwt\nimport mysql.connector\nimport os\nimport uuid\n\ndef createUUID():\n return str(uuid.uuid4())\n\ndef getProfileFromDb(conn, uid): \n with conn.cursor() as c:\n # get latest (by row creation timetsamp) profile from db\n q = 'SELECT weight, height, gender, age, goal, userid FROM profiles WHERE userid=%s ORDER BY datecreated DESC LIMIT 1'\n args = (uid,)\n c.execute(q, args)\n retVal = c.fetchall()\n if len(retVal) != 1:\n return abort(400)\n retVal = {\n 'weight': retVal[0][0],\n 'height': retVal[0][1],\n 'gender': retVal[0][2],\n 'age': retVal[0][3],\n 'goal': retVal[0][4],\n 'uid': retVal[0][5]\n }\n\n return retVal\n\ndef getProfile(conn, uid):\n # simply return result from obtaining latest profile from DB utility function\n return jsonify(getProfileFromDb(conn, uid))\n \ndef postProfile(conn, uid, data):\n # extract and validate data from body \n if 'weight' not in data:\n return abort(400)\n if 'height' not in data:\n return abort(400)\n if 'gender' not in data:\n return abort(400)\n if 'age' not in data:\n return abort(400)\n if 'goal' not in data:\n return abort(400)\n # weight, height, gender, age\n weight = data['weight']\n height = data['height']\n gender = data['gender']\n age = data['age']\n goal = data['goal']\n if weight is None or height is None or gender is None or age is None or goal is None:\n return abort(400)\n try:\n weight = int(weight) \n height = int(height)\n age = int(age)\n except:\n return abort(400)\n\n if weight < 40:\n return abort(400)\n if height < 120:\n return abort(400)\n if age < 16 or age > 110:\n return abort(400)\n if len(goal) < 1:\n return abort(400)\n \n with conn.cursor() as c:\n # insert new profile row into db\n q = 'INSERT INTO profiles (id, userid, weight, height, gender, age, goal) VALUES(%s, %s, %s, %s, %s, %s, %s)'\n args = (str(uuid.uuid4()), uid, weight, height, gender, age, goal)\n c.execute(q, args)\n try:\n conn.commit()\n except:\n abort(500)\n\n # return create/ update success message\n return jsonify({\n 'message': 'profile created/ updated successfully'\n }) \n\ndef parseMeal(meal):\n # extract relevant fields from meal and parse/ validate them\n if 'name' not in meal:\n return False\n if 'uri' not in meal:\n return False\n if 'image' not in meal:\n return False\n if 'calories' not in meal:\n return False\n name = meal['name']\n uri = meal['uri']\n image = meal['image']\n calories = meal['calories']\n if name is None or uri is None or image is None or calories is None:\n return False\n try:\n calories = int(calories)\n except:\n return False\n\n # return a dict of extracted data\n return {\n 'name': name,\n 'uri': uri,\n 'image': image,\n 'calories': calories\n }\n\ndef getPlan(conn, uid, data):\n # extract, parse and validate meal plan id from data\n if 'planId' not in data:\n return abort(400)\n planId = data['planId']\n with conn.cursor() as c:\n # query DB using the id \n q = 'SELECT breakfast_name, breakfast_uri, breakfast_image, breakfast_calories, lunch_name, lunch_uri, lunch_image, lunch_calories, dinner_name, dinner_uri, dinner_image, dinner_calories, DATE_FORMAT(dateplanned, \"%Y/%m/%d\") FROM plans WHERE userid=%s AND id=%s'\n args = (uid, planId)\n print(args)\n c.execute(q, args)\n retVal = c.fetchall()\n\n # return error status if no matching plan found\n if len(retVal) == 0:\n return abort(400)\n\n # format as JSON to return to requestor\n return jsonify({\n 'breakfast': {\n 'name': retVal[0][0],\n 'uri': retVal[0][1],\n 'image': retVal[0][2],\n 'calories': retVal[0][3]\n },\n 'lunch': {\n 'name': retVal[0][4],\n 'uri': retVal[0][5],\n 'image': retVal[0][6],\n 'calories': retVal[0][7]\n },\n 'dinner': {\n 'name': retVal[0][8],\n 'uri': retVal[0][9],\n 'image': retVal[0][10],\n 'calories': retVal[0][11]\n },\n 'plannedDate': retVal[0][12]\n })\n\ndef postPlan(conn, uid, data): \n # extract, parse and validate relevant arguments from data \n if 'breakfast' not in data:\n return abort(400) \n if 'lunch' not in data:\n return abort(400)\n if 'dinner' not in data:\n return abort(400)\n if 'plannedDate' not in data:\n return abort(400)\n\n breakfast = parseMeal(data['breakfast'])\n lunch = parseMeal(data['lunch'])\n dinner = parseMeal(data['dinner'])\n plannedDate = data['plannedDate']\n if not breakfast or not lunch or not dinner or not plannedDate:\n return abort(400)\n try:\n # check if the planned date is the current date or in the future\n dt = datetime.strptime(plannedDate, '%Y/%m/%d').date()\n today = date.today()\n # if the planned date is in the past, return error status\n if dt < today:\n return abort(400)\n plannedDate = dt.strftime('%Y-%m-%d')\n except:\n return abort(400)\n with conn.cursor() as c:\n # insert new meal plan into DB\n q = 'INSERT INTO plans(id, breakfast_name, breakfast_uri, breakfast_image, breakfast_calories, lunch_name, lunch_uri, lunch_image, lunch_calories, dinner_name, dinner_uri, dinner_image, dinner_calories, datePlanned, userid) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'\n args = (createUUID(), breakfast['name'], breakfast['uri'], breakfast['image'], breakfast['calories'], lunch['name'], lunch['uri'], lunch['image'], lunch['calories'], dinner['name'], dinner['uri'], dinner['image'], dinner['calories'], plannedDate, uid)\n try:\n c.execute(q, args)\n conn.commit()\n except mysql.connector.Error as err:\n print('MySQL error:', err)\n return abort(500)\n except Exception as e:\n print('Misc. error:', e)\n return abort(500)\n \n # return success message when insertion is successful\n return jsonify({\n 'message': 'plan successfully created.'\n })\n\ndef createToken(sub):\n # use environment variables and current date time to create a valid JWT token\n # to be passed to the frontend\n delta = int(os.environ['JWT_DELTA'])\n secret = os.environ['JWT_SECRET']\n now = datetime.now(tz=timezone.utc)\n expiry = now + timedelta(seconds=delta)\n return jwt.encode({\n 'iat': now,\n 'exp': expiry,\n 'sub': sub\n }, secret)\n\ndef checkToken(token):\n # obtain the secret needed to decode a JWT token\n secret = os.environ['JWT_SECRET']\n try:\n # return the subject field of the token when decoding is successful\n return jwt.decode(token, secret, algorithms=['HS256'])['sub']\n except:\n # return None if the token is invalid or expired\n return None\n \ndef checkUser(conn, token):\n # extract the JWT token from the Authorization header\n token = token.replace('Bearer ', '')\n # check the validity of the token\n uid = checkToken(token)\n if uid is None:\n return False\n \n with conn.cursor() as c:\n # query the DB to ensure the extracted id is valid\n q = 'SELECT COUNT(*) FROM users WHERE id = %s'\n args = (uid,)\n c.execute(q, args)\n retVal = c.fetchall()\n # return uid if token is valid\n if retVal[0][0] == 1:\n return uid\n # return False if the uid is invalid\n return False","repo_name":"HakureiAnna/CM2020GroupProject","sub_path":"caldown/backend/app/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":7950,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"74451834168","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 29 14:50:39 2017\n\nThis script is meant to determine the Voxelization parameters.\n\n@author: arsalanadil\n\"\"\"\nimport numpy as np, matplotlib.pyplot as plt\nfrom scipy.integrate import dblquad, quad\nimport RemoteQuad as Remote\nimport matplotlib.pyplot as plt\nimport time\n#import RemoteQuad_Harmonic as Remote2\n\ndef RemoteCMB(clusters, n):\n\n varMatrix = np.zeros((n,n)).astype(complex)\n relMatrix = np.zeros((n,n)).astype(complex)\n \n for i in range(n):\n print(i)\n for j in range(i+1):\n #print(\"For Remote: Cluster number\", i, \"and\",j)\n temp = Remote.wignerRotation(clusters[i,:],clusters[j,:])[0]\n #print(\"For Remote: Cluster number\", i, \"and\",j,\".Covariance\",temp[0][0])\n #print(\"wignerRotation() returned:\", temp[0]) \n varMatrix[i][j] = temp[0][0]\n varMatrix[j][i] = np.conjugate(temp[0][0])\n relMatrix[i][j] = temp[0][4]\n relMatrix[j][i] = temp[0][4]\n \n return varMatrix, relMatrix\n\n\"\"\"\nThe following piece of code gives you the voxelization in z (using the old code - VarMatrixGeneralized.py)\n\"\"\"\n\"\"\"\nzVoxel = np.zeros(20)#don't know how much we'll need. keeping 20 to be safe.\nn = 200\nzvals = np.linspace(0,2,n)\nclusters = np.array([[zvals[i],0,0] for i in range(0,n)])\n#varMat = RemoteCMB(clusters,n)[0]\nvarMat = np.load(\"VoxelizeCovarianceMat.npy\")\n\ncut = 0.96\nm = 0\nk = 0\ni = 0\nprint(\"RESULT USING OLD CODE:\")\nwhile(i < n):\n for j in range(k,n):\n corel = varMat[i][j]/np.sqrt(varMat[i][i] * varMat[j][j])\n \n if(i != j and corel.real < cut):\n #print(i,j)\n #cut = varMat[i][j]/np.sqrt(varMat[i][i] * varMat[j][j])\n print(\"Correlation Coefficient:\", corel)\n print(\"z\",j,clusters[j])\n zVoxel[m] = zvals[j]#store this value since we need it to figure out theta and phi voxelization.\n k = j\n i = k\n m+=1\n break \n\n\"\"\"\n\n\n\n\n\n\n\n\n\"\"\"\n------------------------------------------------------------------\nUse the following if you want to use/compare results with the new code in Harmonic Space:\n\"\"\"\n \n\"\"\"\ndef RemoteHarm(clusters,n):\n varMatrix = np.zeros((n,n)).astype(complex)\n for i in range(n):\n print(i)\n for j in range(i+1):\n #print(\"For Remote: Cluster number\", i, \"and\",j)\n temp = Remote2.UnrotCovRel(0,clusters[i][0],clusters[j][0])[0]#for things on the z-axis we only care about UnrotCovRel\n #print(\"For Remote: Cluster number\", i, \"and\",j,\".Covariance\",temp)\n varMatrix[i][j] = temp\n varMatrix[j][i] = np.conjugate(temp)\n return varMatrix\n\ndef RempoteHarmComp(clusters,n):\n varMatrix = np.zeros((n,n)).astype(complex)\n for i in range(n):\n print(i)\n for j in range(i+1):\n #print(\"For Remote: Cluster number\", i, \"and\",j)\n temp = Remote2.CovRel(clusters[i],clusters[j])[0]\n #print(\"For Remote: Cluster number\", i, \"and\",j,\".Covariance\",temp)\n varMatrix[i][j] = temp\n varMatrix[j][i] = np.conjugate(temp)\n return varMatrix\n\"\"\"\n\"\"\"\nn = 10\nzvals = np.linspace(0,0.5,n)\ncut = 0.95\n\nvarMat2 = RemoteHarm(zvals,n)\nprint(\"RESULT USING Harmonic Space CODE:\")\n\nk = 0\ni = 0\nwhile(i < n):\n for j in range(k,n):\n corel = varMat2[i][j]/np.sqrt(varMat2[i][i] * varMat2[j][j])\n \n if(corel.real < cut):\n #print(i,j)\n #cut = varMat[i][j]/np.sqrt(varMat[i][i] * varMat[j][j])\n print(\"Correlation Coefficient:\", corel)\n print(\"z\",j,zvals[j])\n k = j\n i = k\n break\n\"\"\"\n\n\n\n\"\"\"\n---------------------------------------------------------------------------\nThe following piece is for determining Nside for each \"z-shell\". \n\"\"\"\n\"\"\"\nzVox = np.load(\"zVox.npy\")\nzVox = np.concatenate((zVox,[2]))\nNstore = np.zeros(len(zVox)+1)\nj = 0\nfor i in range(0,len(zVox)):\n print('\\n')\n print(\"At shell number:\", i, \"corresponding to z=\",zVox[i])\n corel = 1\n Nside = 32\n while(corel > 0.96):\n z = zVox[i]\n Np = 12 * Nside**2\n theta = np.sqrt(4*np.pi/Np)\n corel = np.abs(\n Remote.wignerRotation([z,0,0],[z,theta,0])[0][0][0]/np.sqrt(Remote.wignerRotation([z,0,0],[z,0,0])[0][0][0] \n * Remote.wignerRotation([z,theta,0],[z,theta,0])[0][0][0]))\n corel2 = np.abs(\n Remote.wignerRotation([z,0,theta],[z,theta,theta/np.sin(theta)])[0][0][0]/np.sqrt(Remote.wignerRotation([z,theta,theta/np.sin(theta)],[z,theta,theta/np.sin(theta)])[0][0][0] \n * Remote.wignerRotation([z,theta,0],[z,theta,0])[0][0][0]))\n print(\" Theta Corelation:\", corel, \"Phi Corel:\",corel2, \"Nside:\",Nside, \"delta Theta:\", theta, \"delta phi:\", theta/np.sin(theta))\n if(corel < 0.96 or corel2 <0.96):\n Nstore[j] = Nside * 2#stores the Nside that I want to use for each zshell (for ease of checking in the end)\n j+=1\n Nside = Nside/2#Nside needs to be in powers of two...\n\n #print(\"Corel:\", corel,\"theta:\",theta, \"Corresponding to Nside=\",Nside)\n\n\"\"\"\n\n\n\n\n\"\"\"\n------------------------------------------------------------------\nThe following piece is for verifying that \\delta theta is uniform for any given z-shell\n\"\"\"\n\"\"\"\nNside = 4\nz = 0.070351758794\nNp = 12 * Nside**2\ntempTheta = np.sqrt(4*np.pi/Np)\ndelTheta = 0\ntheta = tempTheta\nwhile(delTheta < np.pi):\n corel = np.abs(\n Remote.wignerRotation([z,0,delTheta],[z,0,theta])[0][0][0]/np.sqrt(Remote.wignerRotation([z,0,delTheta],[z,0,delTheta])[0][0][0] \n * Remote.wignerRotation([z,0,theta],[z,0,theta])[0][0][0]))\n \n #At each theta value, we want delta phi = delta t*heta/ sin(theta) and this should return the same correlation as above.\n \n delPhi = tempTheta/np.sin(theta)\n corel2 = np.abs(\n Remote.wignerRotation([z,0,theta],[z,delPhi,theta])[0][0][0]/np.sqrt(Remote.wignerRotation([z,delPhi,theta],\n [z,delPhi,theta])[0][0][0] \n * Remote.wignerRotation([z,0,theta],[z,0,theta])[0][0][0]))\n print(\"theta:\",theta,\"theta2:\",delTheta,\"Corelation\",corel, \"Phi Correlation:\", corel2, \"delPhi:\", delPhi)\n print(\"Number of Phi Voxels at this theta val:\", 2*np.pi/delPhi)\n theta = delTheta\n delTheta += tempTheta\n\"\"\" \n\n\"\"\"\n--------------------------------------------------------------\nThe following code checks for discrepencies in the covariance matrices between \nthe old (real space) code and the new (harmonic space) code \n\"\"\"\n\"\"\"\nn = 10\nzvals = np.linspace(1,2,n)\nclusters = np.array([[zvals[i],0,0] for i in range(0,n)])\nclusters = np.load(\"rand20Clusters.npy\")\nvMatOld = RemoteCMB(clusters, n)[0]\nvMatNew = RemoteHarm(clusters,n) \n\nprint(vMatNew - vMatOld)\n\"\"\" \n\n\n","repo_name":"arsalanadil/RemoteQuadrupole","sub_path":"Optimize/Voxelization.py","file_name":"Voxelization.py","file_ext":"py","file_size_in_byte":6865,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"74213079608","text":"'''\r\nPalindrome Creator from Coderbyte\r\nDecember 2020 Jakub Kazimierski\r\nI'm not quite glad about this code, but it \r\ncovers all cases, which are wrongly interpreted at Coderbyte.\r\n'''\r\n\r\ndef PalindromeCreator(strParam):\r\n '''\r\n Have the function PalindromeCreator(str) \r\n take the str parameter being passed and \r\n determine if it is possible to create a \r\n palindromic string of minimum length 3 \r\n characters by removing 1 or 2 characters. \r\n \r\n For example: if str is \"abjchba\" then \r\n you can remove the characters jc to produce \r\n \"abhba\" which is a palindrome. \r\n For this example your program should return the \r\n two characters that were removed with no delimiter \r\n and in the order they appear in the string, so \"jc\". \r\n If 1 or 2 characters cannot be removed to produce a \r\n palindrome, then return the string \"not possible\".\r\n\r\n If the input string is already a palindrome, \r\n your program should return the string palindrome. \r\n Your program should always remove the characters that \r\n appear earlier in the string. \r\n \r\n In the example above, you can also remove ch to form a \r\n palindrome but jc appears first, so the correct answer is jc.\r\n\r\n The input will only contain lowercase alphabetic characters. \r\n Your program should always attempt to create the longest palindromic \r\n substring by removing 1 or 2 characters \r\n The 2 characters you remove do not have to be adjacent in the string.\r\n '''\r\n try:\r\n # if it is already palindrome\r\n if strParam[::-1] == strParam:\r\n return \"palindrome\"\r\n else:\r\n # counter for first match remeber\r\n counter = 0\r\n output = []\r\n\r\n # make lenght of param longer, in order to chek all indexes\r\n strParam_longer = strParam + \" \"\r\n # below checks if lack of one letter inside string is enough to create palindrome\r\n for i in range (1, len(strParam_longer)):\r\n temp_String = strParam_longer[0:i-1] + strParam_longer[i:len(strParam_longer)-1]\r\n \r\n # if it is, return this letter\r\n if temp_String[::-1] == temp_String:\r\n return strParam[i-1]\r\n \r\n temp_String_longer = temp_String + \" \"\r\n # if it is not, try next letter\r\n for j in range (1, len(temp_String_longer)):\r\n temp_String_second = temp_String_longer[0:j-1] + temp_String[j:len(temp_String_longer)-1]\r\n # if lack of two letters is enough return those letters\r\n if temp_String_second[::-1] == temp_String_second:\r\n # return first output\r\n if counter == 0:\r\n output = [letter for letter in strParam if letter not in temp_String_second]\r\n counter += 1\r\n\r\n if len(output) != 0:\r\n return \"\".join(letter for letter in output)\r\n else: \r\n # if 2 letters was not enough return not possible\r\n return \"not possible\"\r\n\r\n except(AttributeError, TypeError):\r\n return -1\r\n\r\n","repo_name":"JakubKazimierski/PythonPortfolio","sub_path":"Coderbyte_algorithms/Easy/PalindromeCreator/PalindromeCreator.py","file_name":"PalindromeCreator.py","file_ext":"py","file_size_in_byte":3237,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"77"} +{"seq_id":"9229260272","text":"import pygame\n#в данном файле представленные константы для работы программы\n#------------------------------------------------------------\nWIDTH, HEIGHT = 1200, 800 # размеры ОКНА\nFONT = 'EpilepsySansBold.ttf'\nwidth_d, height_d = 240, 160 # размеры происходящего в игре, игрового пространства?, display\nTILE_SIZE = 10\nFPS = 60\nPLAYER_VEL = 1\nBACKGROUND = pygame.transform.scale(pygame.image.load(\"working_sprites/background.png\"), (width_d, height_d))\nBACKGROUND_1 = pygame.image.load('working_sprites/background0.png')\nIMAGE_BULLET = pygame.image.load('working_sprites/bullet.png')\nBG_WIDTH = BACKGROUND.get_width()\nVOLUME_MUSIC = 0.8\nVOLUME_SOUNDS = 0.5\nTILES = 1000\nSCROLL = 0\nSPAWN_ENEMY = pygame.USEREVENT + 1","repo_name":"sprittzer/shooter","sub_path":"code/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"3449354118","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Feb 7 15:00:33 2020\r\n\r\n@author: marta\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom mlxtend.preprocessing import TransactionEncoder\r\nfrom mlxtend.frequent_patterns import apriori\r\nfrom mlxtend.frequent_patterns import association_rules\r\nfrom kmodes.kmodes import KModes\r\nimport sklearn.cluster as cluster\r\nimport sklearn.neighbors as neighbors\r\nimport math\r\nfrom numpy import linalg as LA\r\n\r\n#QUESTION 1\r\ndata= pd.read_csv(\"Groceries.csv\");\r\n#a)\r\ndf = data.groupby('Customer')['Item'].nunique()\r\n\r\n\r\nhist=plt.hist(df)\r\nplt.xlabel('Number of different items')\r\nplt.ylabel('Number of clients')\r\nplt.savefig('hist_numitems.png')\r\nplt.show\r\n\r\np_25 = np.percentile(df,25)\r\nprint('The 25th percentile is :'+str(p_25)) \r\np_50 = np.percentile(df, 50)\r\nprint('The 50th percentile or median is :'+str(p_50)) \r\np_75 = np.percentile(df, 75)\r\nprint('The 75th percentile is :'+str(p_75)) \r\n\r\n#b)\r\nNx=75;\r\nN=df.size;\r\nsupport=(Nx/N);\r\nprint('The support is:'+str(support*100))\r\nListItem = data.groupby(['Customer'])['Item'].apply(list).values.tolist() \r\nte = TransactionEncoder()\r\nte_ary = te.fit(ListItem).transform(ListItem)\r\ntrainData = pd.DataFrame(te_ary, columns=te.columns_) # Item List -> Item Indicator\r\n\r\nfrequent_itemsets = apriori(trainData, min_support = support ,use_colnames = True)\r\nlength = frequent_itemsets.support.size\r\nprint('The number of frequent itemsets is: ' , length )\r\nprint('Itemset with most items: ' , frequent_itemsets.iloc[length-1]['itemsets'])\r\n\r\n#c)\r\n\r\nassoc_rules = association_rules(frequent_itemsets, metric = \"confidence\", min_threshold = 0.01)\r\nprint('The number of association rules is: ', assoc_rules['confidence'].count())\r\n\r\n#d)\r\nsupport_rule = assoc_rules['support'].to_numpy()\r\nconfidence = assoc_rules['confidence'].to_numpy()\r\nlift = assoc_rules['lift'].to_numpy()\r\nprint('The size of the marker is:',lift.shape[0])\r\n\r\nplt.scatter(confidence,support_rule, alpha=0.7 , s=lift)\r\nplt.xlabel('Confidence')\r\nplt.ylabel('Support')\r\nplt.title('Support vs Confidence')\r\nplt.savefig('support_confidence.png')\r\n\r\n#e)\r\nassoc_rules = association_rules(frequent_itemsets, metric = \"confidence\", min_threshold = 0.6)\r\nprint(assoc_rules)\r\n\r\n#QUESTION 2\r\ndf_2=pd.read_csv(\"cars.csv\")\r\n#a)\r\ntype_freq = df_2.groupby('Type')['Type'].count()\r\nprint( 'The frequency of Types is:',type_freq)\r\n#b)\r\nDriveTrain_freq = df_2.groupby('DriveTrain')['DriveTrain'].count()\r\nprint( 'The frequencies of DriveTrain are:',DriveTrain_freq)\r\n\r\n#c)\r\nOrigin_freq = df_2.groupby('Origin')['Origin'].count()\r\nprint( 'The frequencies of Origin is:',Origin_freq)\r\nd_Asia_Europe=(1/Origin_freq['Asia'])+(1/Origin_freq['Europe'])\r\nprint('The distance between Asia and Europe is:'+str(d_Asia_Europe))\r\n\r\n#d)\r\n\r\ndf_na = df_2.fillna(\"Missing\")\r\ncyl_freq = df_na.groupby('Cylinders')['Cylinders'].count()\r\nprint( 'The frequencies of Cylinder is:',cyl_freq)\r\nd_5_missing=(1/cyl_freq[5])+(1/cyl_freq['Missing'])\r\nprint('The distance between Cylinder 5 and Missing is:'+str(d_5_missing))\r\n\r\n#e)\r\ndf_na = df_2.fillna(0)\r\ndf1 = df_na[['Type','DriveTrain','Origin','Cylinders']]\r\ndf1[\"Cylinders\"] = df1[\"Cylinders\"].astype('category')\r\nkm = KModes(n_clusters=3, init='Huang')\r\nclusters = km.fit_predict(df1)\r\n\r\nunique, counts = np.unique(clusters, return_counts=True)\r\nprint('The number of observations in each cluster is:',counts)\r\n\r\n# Print the cluster centroids\r\nprint(km.cluster_centroids_)\r\n#f)\r\nclusters=pd.DataFrame(clusters)\r\ndata = pd.concat([df1, clusters],axis=1)\r\ndata.columns = ['Type', 'DriveTrain','Origin','Cylinders','Cluster']\r\norigin_freq = data.groupby('Cluster').Origin.value_counts()\r\n\r\n\r\n\r\n\r\n#QUESTION 3\r\ndata_3= pd.read_csv(\"FourCircle.csv\");\r\nrdm_state=60616;\r\nplt.scatter(data_3.x,data_3.y)\r\nplt.title('Scatter plot')\r\nplt.savefig('scatter.png')\r\n\r\n#b)\r\nx = np.array(data_3['x'])\r\ny = np.array(data_3['y'])\r\nX = np.column_stack((x,y))\r\nkmeans = cluster.KMeans(n_clusters=4, random_state=rdm_state).fit(X)\r\nprint(\"Cluster Assignment:\", kmeans.labels_)\r\nprint(\"Cluster Centroid 0:\", kmeans.cluster_centers_[0])\r\nprint(\"Cluster Centroid 1:\", kmeans.cluster_centers_[1])\r\nprint(\"Cluster Centroid 2:\", kmeans.cluster_centers_[2])\r\nprint(\"Cluster Centroid 3:\", kmeans.cluster_centers_[3])\r\n\r\nplt.scatter(x, y, c=kmeans.labels_.astype(float))\r\nplt.xlabel('x')\r\nplt.ylabel('y')\r\nplt.title('Scatter plot before K-mean clustering')\r\nplt.show()\r\nplt.savefig('scatter_KMeans.png')\r\n\r\n\r\n#c)\r\n\r\nn_neigh = 10\r\nkNNSpec =neighbors.NearestNeighbors(n_neighbors = n_neigh, algorithm = 'brute', metric = 'euclidean')\r\nnbrs = kNNSpec.fit(X)\r\nd3, i3 = nbrs.kneighbors(X)\r\nprint('Distance to the nearest neighbors: '+str(d3))\r\nprint('Which are the nearest neihbors: '+str(i3))\r\n\r\n# Retrieve the distances among the observations\r\ndistObject =neighbors.DistanceMetric.get_metric('euclidean')\r\ndistances = distObject.pairwise(X)\r\n\r\nnObs = 1440\r\n\r\n# Create the Adjacency matrix\r\nAdjacency = np.zeros((nObs, nObs))\r\nfor i in range(nObs):\r\n for j in i3[i]:\r\n Adjacency[i,j] = math.exp(- (distances[i][j])**2 )\r\n\r\n# Make the Adjacency matrix symmetric\r\nAdjacency = 0.5 * (Adjacency + Adjacency.transpose())\r\n\r\n# Create the Degree matrix\r\nDegree = np.zeros((nObs, nObs))\r\nfor i in range(nObs):\r\n sum = 0\r\n for j in range(nObs):\r\n sum += Adjacency[i,j]\r\n Degree[i,i] = sum\r\n\r\n# Create the Laplacian matrix \r\nLmatrix = Degree - Adjacency\r\n\r\n# Obtain the eigenvalues and the eigenvectors of the Laplacian matrix\r\nevals, evecs = LA.eigh(Lmatrix)\r\n\r\n# Series plot of the smallest five eigenvalues to determine the number of clusters\r\nsequence = np.arange(1,6,1) \r\nplt.plot(sequence, evals[0:5,], marker = \"o\")\r\nplt.xlabel('Sequence')\r\nplt.ylabel('Eigenvalue')\r\nplt.xticks(sequence)\r\nplt.grid(\"both\")\r\nplt.show()\r\nprint('The eigenvalues in scientific notation are:',evals[0:5,])\r\n\r\n# Series plot of the smallest twenty eigenvalues to determine the number of neighbors\r\nsequence = np.arange(1,21,1) \r\nplt.plot(sequence, evals[0:20,], marker = \"o\")\r\nplt.xlabel('Sequence')\r\nplt.ylabel('Eigenvalue')\r\nplt.grid(\"both\")\r\nplt.xticks(sequence)\r\nplt.show()\r\n\r\n\r\n#e)\r\nZ = evecs[:,[0,3]]\r\nprint('The eigenvectors are:',Z)\r\n# Final KMeans solution \r\nkmeans_spectral = cluster.KMeans(n_clusters=4, random_state=rdm_state).fit(Z)\r\ndata_3['SpectralCluster'] = kmeans_spectral.labels_\r\n\r\nplt.scatter(data_3['x'], data_3['y'], c = data_3['SpectralCluster'])\r\nplt.xlabel('x')\r\nplt.ylabel('y')\r\nplt.title('Spectral Cluster with {neighbors} neighbors'.format(neighbors = n_neigh))\r\nplt.savefig('Spectral_{neighbors}.png'.format(neighbors = n_neigh))\r\nplt.grid(True)\r\nplt.show()\r\n","repo_name":"martagruizdeleon/IIT-","sub_path":"Homework 2.py","file_name":"Homework 2.py","file_ext":"py","file_size_in_byte":6652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"33291380219","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Aug 8 09:55:38 2018\n\n@author: smh\n\"\"\"\n\nimport os\nimport subprocess \nfrom datetime import datetime\nimport LandscapeModel\n\nclass RunFactory(object):\n \n def __init__(self,fdir,fname):\n \"\"\"\n fdir (string): path of project folder\n \"\"\"\n# self.message(\"create runfactory: \" + fdir)\n self.fdir = fdir\n self.fname = fname\n self.runlist = LandscapeModel.utils.ParameterList(self.fdir,self.fname,\",\")\n self.runs = []\n\n def setup(self,key=\"\",printMessage=False,createDatabase=True,**kwargs):\n \n # get list with model runs\n if key != \"\" and key!=\"None\":\n runs = [i for i in self.runlist if i.key == key and i.simulate == True]\n else:\n runs = [i for i in self.runlist if i.simulate == True] \n \n if len(runs)<1:\n raise ValueError(\"No valid run ID found\")\n \n for run in runs: \n if printMessage: self.message(\"# Create catchment\") \n self.runs.append(LandscapeModel.Catchment(run,printMessage=printMessage,\n createDatabase=createDatabase))\n \n def __call__(self,key=\"\",printMessage=False,plotMap=False,**kwargs): \n \"\"\"\n Make a single model run with 'name' or comptue all runs listed in\n run List.\n \"\"\"\n \n # get list with model runs\n if key != \"\" and key!=\"None\":\n runs = [i for i in self.runlist if i.key == key and i.simulation == True]\n else:\n runs = [i for i in self.runlist if i.simulation == True] \n \n if len(runs)<1:\n \n self.message(\"simulation: no run to simulate\")\n \n else:\n \n for run in runs: \n \n if printMessage: self.message(\"simulation: create catchment\") \n print(\"project: \",run.key)\n self.runs.append(LandscapeModel.Catchment(run,printMessage=printMessage))\n \n if plotMap:\n plot=LandscapeModel.utils.Plotting()\n catchment = self.runs[-1]\n plot.CatchmentMap(catchment,withnames=True,\n fpath=os.path.join(catchment.fpath,\"Map.png\"))\n if run.catchment_separation != True:\n print(\"simulation: run\",self.runs[-1].modelrun.key)\n self.runs[-1](**kwargs)\n \n else:\n print(\"simulation: separate\",self.runs[-1].modelrun.key) \n catchSep = LandscapeModel.utils.CatchmentSeparator(self.runs[-1])\n catchSep()\n catchSep.plotMap(fontsize=8,withnames=True)\n print(\"simulation: run\",self.runs[-1].modelrun.key) \n catchSep.run_SolverUnits()\n\n def preprocessing(self,key,\n make_catchcon=False,\n has_scenarios=False):\n \"\"\"\n \"\"\"\n # select specific key if needed\n if key != \"\" and key!=\"None\":\n runs = [i for i in self.runlist if i.key == key and i.preprocessing == True]\n else:\n runs = [i for i in self.runlist if i.preprocessing == True]\n \n # conduct pre-processing\n for run in runs:\n self.__preprocessing(run,make_catchcon,has_scenarios)\n \n def __preprocessing(self,run,\n make_catchcon=False,\n has_scenarios=False):\n \"\"\"\n \"\"\"\n key = run.key\n fpath_project = os.path.join(run.fpath,run.key)\n ###########################################################################\n # pre-processing\n \n if make_catchcon:\n # create connections between cells<>cells and cells<>reches\n catchcon = LandscapeModel.utils.PreProcessing.CatchmentConnector(\n fpath_project,\n simplify_connections=4,\n connection_type=\"RO_GW\")\n # plot results of connections\n catchcon.makePlot(os.path.join(fpath_project,\"flow_network_voroni.png\"),resX=100,resY=100,plotVoroni=True,\n plotElevation=False,plot_simplified=True,fontsize=4,markersize=0.5)\n catchcon.makePlot(os.path.join(fpath_project,\"flow_network.png\"),resX=100,resY=100,plotVoroni=False,\n plotElevation=True,plot_simplified=True,fontsize=4,markersize=0.5)\n \n # calculate area-weighted flow timeseries of reach each and create files\n if run.runtype == \"inStream\":\n ayc = LandscapeModel.utils.PreProcessing.AreaYieldCatchment(\n run.fpath,\n key,\n frunlist=self.fname,\n filetype = run.database,\n time_format=\"%Y-%m-%dT%H:%M\")\n \n data_resampled=ayc.create_timeseries(resample_rule=\"1H\",\n resample_type=\"interpolate\")\n \n if has_scenarios:\n # create scenarios (365 days dry 10%-percentile, medium 50%-percentile and \n # wet 90%-percentile year) and create files\n ayc.create_timeseries_scenarios(resample_rule=\"1H\",\n resample_type=\"interpolate\")\n\n def postprocessing(self,key=\"None\",**kwargs):\n \"\"\"\n \"\"\"\n # select specific key if needed\n if key != \"\" and key!=\"None\":\n runs = [i for i in self.runlist if i.key == key and i.postprocessing == True]\n else:\n runs = [i for i in self.runlist if i.postprocessing == True]\n # conduct post-processing\n for run in runs:\n self.__postprocessing(run,**kwargs)\n \n def __postprocessing(self,run,\n stats = True,\n zero_flow = True,\n performance = False,\n catchment_hydrology = False,\n catchment_efate=False,\n branch_hydrology_and_efate=False,\n reach_hydrology_and_efate=False,\n catchment_validation=False,\n plot_percentile_over_time=False,\n ):\n \"\"\"\n Conducts post-processing.\n \n :param run: Modelrun settings related to runlist.csv\n :type run: modelrun\n \n :returns: - \n :rtype: -\n \"\"\"\n \n # create post-processing class\n pstPrc = LandscapeModel.utils.PostProcessing(os.path.join(run.fpath,run.key),\n run.key,time_format=\"%Y-%m-%dT%H:%M\")\n \n if stats:\n # calculate stats and save file\n stats = pstPrc.get_stats(stats= ['mean', 'median',\"min\",\"max\"],\n params=['depth', 'volume', 'flow', 'area'])\n \n # make plots\n pstPrc.map_stats(stats)\n \n # plot percentiles of variables\n if plot_percentile_over_time:\n pstPrc.plot_percentile_over_time(params=['depth', 'volume', 'flow', 'area'])\n \n if zero_flow:\n # get all reaches with at least one value with flow == 0 and make a plot.\n pstPrc.get_zero_flow_reaches(stats)\n \n if performance:\n # plot observed versus simulated flow\n pstPrc.performance(\"flow\")\n \n if catchment_hydrology:\n # plot histogramm of hydrological parameter across catchment\n pstPrc.catchment_hydrology()\n \n if catchment_efate:\n # plot cumulative distribution function of PEC values across catchment\n pstPrc.catchment_efate(datetime(1900,5,10,10),[1,2,4,8,16,24],\n maxSW=.4,maxSED=.05)\n \n if branch_hydrology_and_efate:\n # plot 3-D plot of two reach variables, e.g. PEC_SW and flow\n pstPrc.branch_hydrology_and_efate(\"PEC_SW\",\n \"PEC$_{SW}$ [$\\mu$g L$^{-1}$]\",\n \"flow\",\n \"Flow [m³ sec$^{-1}$]\",\n reach_start=\"r1443\",reach_end=\"r1438\",\n tstart = datetime(1900,5,2,8),\n tend = datetime(1900,5,3,23),\n tintverval = 4,\n timescale=\"hourly\",\n vmin=None,vmax=None,fname=\"1\")\n if reach_hydrology_and_efate:\n # plot resutls of single reach \n pstPrc.reach_hydrology_and_efate(\"r1443\",tstart=datetime(1900,5,2,8),\n tend=datetime(1900,5,3,23),\n ymax=[0.15,4,0.5,20],\n maxconc=5.,\n maxload=5.) \n\n if catchment_validation:\n pstPrc.catchment_validation()\n\n def message(self,s):\n \"\"\"\n Writes a user message.\n \"\"\"\n print(s)\n\n def split(self,a, n):\n \"\"\"\n Allocates a set of a modelruns to n cores.\n a (int): count of modelruns\n n (int): count of cores\n \n Returns (list):\n List with number of runs per sub-process.\n \"\"\"\n k, m = divmod(len(a), n)\n return (a[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in iter(range(n)))\n\n def __create_batchfiles(self,ncores=2,pythonpath=\"\",execute = True):\n \"\"\"\n Creates a batch process to run several single projects in parallel. The\n batch process is governed by a master batch-file which calls 1 to n \n slave - batch files. Each slave is run in its own separated process. A \n slave itself contain 1 - n projects.\n \n ncores (int): Nubmer of cores available for modelling (= nubmer of slaves)\n pythonpath (string): path of python.exe\n execute (boolean): if True, the master batch-file is called with subpross.Popen\n \"\"\"\n names = []\n filenames=[]\n for chunk in list(self.split(range(len(self.runList)), ncores)):\n batch = []\n batch.append(\"@echo off\")\n if len(chunk)>0:\n for c in chunk:\n filename = self.__getExecutable(self.fdir,self.runList[c].name) \n filenames.append(filename)\n batch.append('call '+ pythonpath +' ' + '\"' + self.fdir +os.sep+ filename + '\"') \n #create batch-file\n name = str(min(chunk)+1) + \"_\" + str(max(chunk)+1)\n f = open(os.path.join(self.fdir,\"slave_\" + name + \".cmd\"),\"w\")\n f.write(\"\\n\".join(batch))\n f.close() \n names.append(name) \n\n # preapre master batch-file to start slaves\n #create master batch-self\n f = open(os.path.join(self.fdir,\"master_run.cmd\"),\"w\")\n f.write(\"\\n\".join([\"start slave_\" + name + \".cmd\" for name in names]))\n f.close() \n\n #make runs \n if execute:\n os.chdir(self.fdir)\n process = subprocess.Popen(self.fdir + os.sep + \"master_run.cmd\", shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)\n out, err = process.communicate()\n process.wait()\n\n def __getExecutable(self,fdir,runname):\n s=[]\n s.append('import os')\n s.append('import LandscapeModel')\n s.append('if __name__ == \"__main__\":')\n s.append('\\tfdir = os.sep.join(os.path.abspath(__file__).split(os.sep)[:-1])')\n s.append('\\trunFactory = LandscapeModel.utils.RunFactory(fdir=r\"' + self.fdir + '\",fname=\"' + self.fname + '\")')\n s.append('\\trunFactory(\"' + runname + '\")')\n s=\"\\n\".join(s)\n filename = \"main_\"+runname+\".py\"\n f = open(os.path.join(fdir,filename),\"w\")\n f.write(s)\n f.close()\n return filename\n \n ","repo_name":"xlandscape/CmfContinuous-Component","sub_path":"module/bin/LandscapeModel/utils/RunFactory.py","file_name":"RunFactory.py","file_ext":"py","file_size_in_byte":12725,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"17023239257","text":"\"\"\"\nFind the distance between the two nodes in binary tree\n\"\"\"\n\nclass Tree:\n def __init__(self, node, left=None, right=None):\n self.node = node\n self.left = left\n self.right = right\n\n\ndef make_tree(index=0):\n if index == 0:\n '''\n 1\n 2 3\n 4 5 6\n 7 8 9 10 11 12\n 15 14\n '''\n t1 = Tree(2, Tree(4, Tree(7), Tree(8)))\n t2 = Tree(5, Tree(9, Tree(15)), Tree(10))\n t3 = Tree(6, Tree(11), Tree(12, Tree(14)))\n t = Tree(1, t1, Tree(3, t2, t3))\n return t\n\n\ndef preorder_traversal(tree, path=None):\n if path is None:\n path = []\n if tree is not None:\n preorder_traversal(tree.left, path)\n path.append(tree.node)\n preorder_traversal(tree.right, path)\n return path\n\n\ndef find_distance(tree, nodes, path):\n if tree is not None:\n path.append(tree.node)\n if tree.node in nodes:\n nodes[tree.node] = path.copy()\n\n l = find_distance(tree.left, nodes, path)\n r = find_distance(tree.right, nodes, path)\n path.pop()\n\ndef get_distance(found, nodes):\n i = j = 0\n while i < len(found[nodes[0]]) and j < len(found[nodes[1]]):\n if found[nodes[0]][i] == found[nodes[1]][j]:\n i += 1\n j += 1\n else:\n break\n return len(found[nodes[0]][i:]) + len(found[nodes[1]][j:])\n\ndef find_distance_between_nodes(tree, nodes):\n found = {node: False for node in nodes}\n find_distance(tree, found, [])\n # print(found)\n if any([True if found[node] is False else False for node in found]):\n return False\n return get_distance(found, nodes)\n\ntree = make_tree()\nprint('Preorder traversal: ', preorder_traversal(tree))\n\nnodes = [(8, 11), (1, 2), (2, 3), (4, 7), (3, 12), (1, 4), (6, 15), (3, 15), (9, 13), (0, 5), (15, 19), (14, 13), (-3, -9)]\n\nfor node in nodes:\n print(node, '-', find_distance_between_nodes(tree, node))\n","repo_name":"ravikailash/Algo-and-DS","sub_path":"Trees and Graphs/distance_between_two_nodes_bt.py","file_name":"distance_between_two_nodes_bt.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"11696412560","text":"# -*- coding:utf-8 -*-\n\n# 题目:现在有 a 到 z 26 个元素, 编写程序打印 a 到 z 中任取 3 个元素的组合(比如 打印 a b c ,d y z等)\n\ndef choice(n):\n for i in range(24):\n for j in range(i + 1, 25):\n for k in range(j + 1, 26):\n print(chr(ord('a') + i), end=' ')\n print(chr(ord('a') + j), end=' ')\n print(chr(ord('a') + k))\n\n\ndef bit(x):\n c = 0\n while x:\n c += 1\n x = (x & (x - 1))\n\n\ndef print_(x, count):\n i = 0\n if bit(x) == count:\n for i in range(26):\n if x & 1:\n print('%c', chr(ord('a') + i))\n x = (x >> 1)\n\nif __name__ == '__main__':\n choice(2)\n","repo_name":"AidenLong/ai","sub_path":"test/python/test_1.py","file_name":"test_1.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"} +{"seq_id":"17257463006","text":"import networkx as nx\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport math\n\n\ndef latlon_to_xy(lat, lon):\n \"\"\"Convert angluar to cartesian coordiantes\n\n latitude is the 90deg - zenith angle in range [-90;90]\n lonitude is the azimuthal angle in range [-180;180]\n \"\"\"\n r = 6371 # https://en.wikipedia.org/wiki/Earth_radius\n theta = math.pi / 2 - math.radians(float(lat))\n phi = math.radians(float(lon))\n x = r * math.sin(theta) * math.cos(phi) # bronstein (3.381a)\n y = r * math.sin(theta) * math.sin(phi)\n return [x, y]\n\n\nG = nx.MultiGraph()\n\ngraph_data_nodes = np.loadtxt('data/reuse/nodes.csv', dtype='str', delimiter=',', encoding=\"utf-8-sig\", skiprows=1)\ngraph_data_edges = np.loadtxt('data/reuse/edges.csv', dtype='str', delimiter=',', encoding=\"utf-8-sig\", skiprows=1)\npath_edges = []\ntry:\n path_edges = np.loadtxt('data/reuse/path_edges.csv', dtype='str', delimiter=',', encoding=\"utf-8-sig\", skiprows=1)\nexcept:\n pass\n\nfor node in graph_data_nodes:\n x, y = latlon_to_xy((node[0]), (node[1]))\n G.add_node(node[4], pos=(y, -x))\n\nG.add_edges_from(graph_data_edges)\n\npos = nx.get_node_attributes(G, 'pos')\n\nbusNodes = []\nmetroNodes = []\nbusEdges = []\nmetroEdges = []\nwalkNodes = []\nwalkEdges = []\npathEdges = []\n\npathEdgeExist = set()\n\nfor edge in path_edges:\n pathEdgeExist.add(edge[0] + \"::\" + edge[1])\n\nfor node in G.nodes:\n if 'bus' in node:\n busNodes.append(node)\n elif 'metro' in node:\n metroNodes.append(node)\n elif 'walk' in node:\n walkNodes.append(node)\n\nfor node in G.edges:\n if (node[0] + \"::\" + node[1] in pathEdgeExist or node[1] + \"::\" + node[0] in pathEdgeExist):\n pathEdges.append(node)\n elif ('bus' in node[0] and 'bus' in node[1]):\n busEdges.append(node)\n elif ('metro' in node[0] and 'metro' in node[1]):\n metroEdges.append(node)\n elif ('walk' in node[0] and 'walk' in node[1]):\n walkEdges.append(node)\n\n# Draw Bus Nodes\ntry:\n nx.draw_networkx_nodes(G, pos, nodelist=busNodes, node_size=15, node_color='tab:blue', alpha=0.5)\nexcept nx.NetworkXError:\n print('Error drawing bus nodes')\n\n# Draw Metro Nodes\ntry:\n nx.draw_networkx_nodes(G, pos, nodelist=metroNodes, node_size=25, node_color='tab:red', alpha=0.5)\nexcept nx.NetworkXError:\n print('Error drawing metro nodes')\n\n# Draw Walk Nodes\n# try: nx.draw_networkx_nodes(G, pos, nodelist=walkNodes, node_size=5, node_color='tab:green', alpha=0.9)\n# except nx.NetworkXError:\n# print('Error drawing walk nodes')\n\n# Draw Bus Edges\ntry:\n nx.draw_networkx_edges(G, pos, edgelist=busEdges, edge_color='tab:blue', alpha=0.2)\nexcept nx.NetworkXError:\n print('Error drawing bus edges')\n\n# Draw Metro Edges\ntry:\n nx.draw_networkx_edges(G, pos, edgelist=metroEdges, edge_color='tab:red', alpha=0.2)\nexcept nx.NetworkXError:\n print('Error drawing metro edges')\n\n# Draw Walk Edges\ntry:\n nx.draw_networkx_edges(G, pos, edgelist=walkEdges, edge_color='tab:green', alpha=0.2)\nexcept nx.NetworkXError:\n print('Error drawing walk edges')\n\n# Draw Path Edges\ntry:\n nx.draw_networkx_edges(G, pos, edgelist=pathEdges, edge_color='black', width=5)\nexcept nx.NetworkXError:\n print('Error drawing path edges')\n\n\n# Draw Labels\t\n# nx.draw_networkx_labels(G, pos, font_size=10)\n\ndef maximize():\n plot_backend = plt.get_backend()\n mng = plt.get_current_fig_manager()\n if plot_backend == 'TkAgg':\n mng.resize(*mng.window.maxsize())\n elif plot_backend == 'wxAgg':\n mng.frame.Maximize(True)\n elif plot_backend == 'Qt4Agg':\n mng.window.showMaximized()\n\n\nplt.axis('equal')\nmaximize()\nplt.show()\n","repo_name":"rocas777/RouteFInder","sub_path":"networkx/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":3632,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"77"} +{"seq_id":"70446086970","text":"import numpy as np\nimport sys\nfrom copy import deepcopy as cdc\nfrom P1_Base.Classes_base import *\n\n#SIMULATORE CON:\n#-conversion rates\n#-alpha\n#-n.ro acquisti\n#-transition prob.\n\ndef single_MC_simulator(prices, MC_env: Hyperparameters, n_users_pt) -> float:\n\n MC_daily = Daily_Website(MC_env, cdc(prices))\n MC_daily.n_users = [n_users_pt, n_users_pt, n_users_pt]\n MC_daily.alphas = np.array(MC_env.dir_params, dtype=float)/np.sum(MC_env.dir_params)\n\n MC_day = Day(cdc(MC_env), cdc(prices))\n MC_day.website = cdc(MC_daily)\n MC_day.n_users = MC_day.website.get_users_per_product_and_type()\n\n MC_day.run_simulation()\n\n return MC_day.profit\n\n\ndef pull_prices(env: Hyperparameters, conv_rates, alpha, n_buy, trans_prob, n_users_pt=100, print_message=\"Simulating\") -> np.array:\n prices = []\n profits = []\n conv_rate = cdc(conv_rates)\n tran_prob = cdc(trans_prob)\n envv = cdc(env)\n if len(conv_rate) != 3: # SE SONO PASSATI GLI STIMATORI E NON QUELLI VERI\n for i in range(5):\n for j in range(4):\n if (conv_rate[i][j] > 1) or (np.isinf(conv_rate[i][j])):\n conv_rate[i][j] = 1\n\n if len(tran_prob) != 3: # SE SONO PASSATI GLI STIMATORI E NON QUELLI VERI\n for i in range(5):\n for j in range(5):\n if (tran_prob[i][j] > 1) or (np.isinf(tran_prob[i][j])):\n tran_prob[i][j] = 1\n\n if len(conv_rate) != 3: # if I am in the case with one class only\n conv_rate = [conv_rate for i in range(3)]\n if len(tran_prob) != 3:\n tran_prob = [tran_prob for i in range(3)]\n if len(alpha) != 3:\n alpha = [alpha for i in range(3)]\n\n MC_env = Hyperparameters(tran_prob, alpha, envv.pois_param, conv_rate, envv.global_margin, n_buy)\n\n count = 1\n cc = 4**5\n for p1 in range(4):\n for p2 in range(4):\n for p3 in range(4):\n for p4 in range(4):\n for p5 in range(4):\n sim_prices = np.array([p1, p2, p3, p4, p5])\n profits.append(single_MC_simulator(sim_prices, cdc(MC_env), n_users_pt))\n prices.append(sim_prices)\n sys.stdout.write('\\r' + print_message + str(\", pulling prices: \") + f'{count * 100 / cc} %')\n count += 1\n\n profits = np.array(profits, dtype=float)\n best = np.argmax(profits)\n return prices[best]\n","repo_name":"carloghiglione/HOLA_project","sub_path":"Final_Code/P1_Base/MC_simulator.py","file_name":"MC_simulator.py","file_ext":"py","file_size_in_byte":2463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"32438391931","text":"import glob\nimport csv\nimport wikipedia\n\nfilenames = glob.glob(\"/Users/ephraimkunz/Desktop/WikipediaDataMiner/incorrectly_classified/*.txt\")\nwrong = {}\n\nfor filename in filenames:\n with open(filename, 'r') as f:\n reader = csv.reader(f, delimiter=\",\")\n on_header = True\n for row in reader:\n if len(row) == 0:\n continue\n if on_header:\n on_header = False\n continue\n \n pageid = row[5]\n confidence = float(row[4])\n actual = row[1]\n predicted = row[2]\n\n if predicted != actual:\n false_pos = actual == \"2:no\"\n if pageid not in wrong.keys():\n wrong[pageid] = [(\"false_pos\" if false_pos else \"false_neg\", confidence)]\n else:\n wrong[pageid].append((\"false_pos\" if false_pos else \"false_neg\", confidence))\n\n\n# Lookup pageids for the mostly wrong\nitem_list = []\nfor k, v in wrong.iteritems():\n item_list.append((k, v[0][0], v[0][1]))\n\nitem_list.sort(key=lambda x: x[2], reverse=True)\n\ntop = [x for x in item_list if x[2] >= 0.9]\n\nprint()\nfor item in top:\n page = wikipedia.page(pageid=item[0])\n print(\"%s (%0.1f%%): %s\" % (page.title, item[2] * 100, item[1]))","repo_name":"ephraimkunz/WikipediaDataMiner","sub_path":"incorrectly_classified/incorrectly_classified.py","file_name":"incorrectly_classified.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"72341040889","text":"import os\nimport sys\n\nimport flask\nfrom flask import request, render_template, redirect, url_for\n\napp = flask.Flask(__name__)\n\nfrom User import persist_user\n# import User\n\n\n\n@app.route('/')\ndef home():\n return redirect(url_for('register'))\n\n\n@app.route('/register', methods=['GET', 'POST'])\ndef register():\n message = None\n try:\n if request.method == 'POST':\n data = request.form.to_dict()\n op = persist_user(data)\n # print('request params: ', data)\n print('op', op)\n message = 'Registered!'\n\n except Exception as e:\n render_template('register.html', error=e.message) # GET or invalid cred\n\n return render_template('register.html', message=message)\n\n\n\n# if __name__ == '__main__':\n# sys.path.append(os.path.dirname(__name__))\n# User.createDB()\n# app.run(debug=True)\n","repo_name":"gurnoors/TravelBuddy","sub_path":"com/fireeye/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"17602625026","text":"\"\"\"This file contains all the classes you must complete for this project.\n\nYou can use the test cases in agent_test.py to help during development, and\naugment the test suite with your own test cases to further test your code.\n\nYou must test your agent's strength against a set of agents with known\nrelative strength using tournament.py and include the results in your report.\n\"\"\"\nimport random\n\n\nclass Timeout(Exception):\n \"\"\"Subclass base exception for code clarity.\"\"\"\n pass\n\n\ndef custom_score(game, player):\n \"\"\"Calculate the heuristic value of a game state from the point of view\n of the given player.\n\n Note: this function should be called from within a Player instance as\n `self.score()` -- you should not need to call this function directly.\n\n Parameters\n ----------\n game : `isolation.Board`\n An instance of `isolation.Board` encoding the current state of the\n game (e.g., player locations and blocked cells).\n\n player : object\n A player instance in the current game (i.e., an object corresponding to\n one of the player objects `game.__player_1__` or `game.__player_2__`.)\n\n Returns\n -------\n float\n The heuristic value of the current game state to the specified player.\n \"\"\"\n\n if game.is_loser(player):\n return float(\"-inf\")\n\n if game.is_winner(player):\n return float(\"inf\")\n\n # Return score using heuristic 3\n return custom_score3(game,player)\n\ndef custom_score1(game, player):\n \"\"\"\n Heuristic 1: Aggressive Improved Score Heuristic\n This heuristic is similar to the improved score heuristic except that the number\n of opponent moves are weighted more heavily\n\n Parameters\n ----------\n game : `isolation.Board`\n An instance of `isolation.Board` encoding the current state of the\n game (e.g., player locations and blocked cells).\n\n player : object\n A player instance in the current game (i.e., an object corresponding to\n one of the player objects `game.__player_1__` or `game.__player_2__`.)\n\n Returns\n -------\n float\n The heuristic value of the current game state to the specified player.\n \"\"\"\n\n # Get number of own moves and opponent moves\n own_moves = len(game.get_legal_moves(player))\n opp_moves = len(game.get_legal_moves(game.get_opponent(player)))\n\n return float(own_moves-2*opp_moves)\n\ndef custom_score2(game, player):\n \"\"\"\n Heuristic 2: Euclidean Distance from center and opponent.\n In this heuristic we assume that moves closer to the middle of the board is\n better than moves further to the side of the board. In addition, we assume\n that it is better to be further away from the opponent at the same time.\n\n Parameters\n ----------\n game : `isolation.Board`\n An instance of `isolation.Board` encoding the current state of the\n game (e.g., player locations and blocked cells).\n\n player : object\n A player instance in the current game (i.e., an object corresponding to\n one of the player objects `game.__player_1__` or `game.__player_2__`.)\n\n Returns\n -------\n float\n The heuristic value of the current game state to the specified player.\n \"\"\"\n # Calculate the enclidean distance from current player location to the middle_width\n # of board\n row, col = game.get_player_location(player)\n middle_col = (game.width)//2\n middle_row = (game.height)//2\n euclidean_dist = ((row-middle_row)**2+(col-middle_col)**2)**0.5\n\n # Calculate the enclidean distance from current player location to opponent's\n # location\n row_opp, col_opp = game.get_player_location(game.get_opponent(player))\n opp_euclidean_dist = ((row_opp-middle_row)**2+(col_opp-middle_col)**2)**0.5\n dist_opp = ((row_opp-row)**2+(col_opp-col)**2)**0.5\n\n # Return sum of negative enclidean distance to center (since the further it is the\n # less desirable the move) and positive encliden distance to opponent (since the\n # further the opponent is the better)\n return -euclidean_dist + dist_opp\n\ndef custom_score3(game, player):\n \"\"\"\n Heuristic 3: Combination of improved score heuristic and heuristic 2\n This heuristic uses a weighted combination of the improved heuristic score\n and heuristic 2. At the start of the game, heuristic 2 is weighted more heavily,\n whereas at the end of the game, improved score heuristic is weighted more heavily\n\n Parameters\n ----------\n game : `isolation.Board`\n An instance of `isolation.Board` encoding the current state of the\n game (e.g., player locations and blocked cells).\n\n player : object\n A player instance in the current game (i.e., an object corresponding to\n one of the player objects `game.__player_1__` or `game.__player_2__`.)\n\n Returns\n -------\n float\n The heuristic value of the current game state to the specified player.\n\n \"\"\"\n\n # Find % of board still empty\n board_size = game.width*game.height\n empty_size = len(game.get_blank_spaces())\n empty_ratio = empty_size/board_size\n\n # Calculate the enclidean distance from current player location to the middle_width\n # of board\n row, col = game.get_player_location(player)\n middle_col = (game.width)//2\n middle_row = (game.height)//2\n euclidean_dist = ((row-middle_row)**2+(col-middle_col)**2)**0.5\n\n # Calculate the enclidean distance from current player location to opponent's\n # location\n row_opp, col_opp = game.get_player_location(game.get_opponent(player))\n opp_euclidean_dist = ((row_opp-middle_row)**2+(col_opp-middle_col)**2)**0.5\n dist_opp = ((row_opp-row)**2+(col_opp-col)**2)**0.5\n\n # Calculate number of own moves and opponent moves\n own_moves = len(game.get_legal_moves(player))\n opp_moves = len(game.get_legal_moves(game.get_opponent(player)))\n\n # Return weighted score\n return (-euclidean_dist + dist_opp)*empty_ratio + (own_moves-opp_moves)*(1-empty_ratio)\n\n\nclass CustomPlayer:\n \"\"\"Game-playing agent that chooses a move using your evaluation function\n and a depth-limited minimax algorithm with alpha-beta pruning. You must\n finish and test this player to make sure it properly uses minimax and\n alpha-beta to return a good move before the search time limit expires.\n\n Parameters\n ----------\n search_depth : int (optional)\n A strictly positive integer (i.e., 1, 2, 3,...) for the number of\n layers in the game tree to explore for fixed-depth search. (i.e., a\n depth of one (1) would only explore the immediate sucessors of the\n current state.)\n\n score_fn : callable (optional)\n A function to use for heuristic evaluation of game states.\n\n iterative : boolean (optional)\n Flag indicating whether to perform fixed-depth search (False) or\n iterative deepening search (True).\n\n method : {'minimax', 'alphabeta'} (optional)\n The name of the search method to use in get_move().\n\n timeout : float (optional)\n Time remaining (in milliseconds) when search is aborted. Should be a\n positive value large enough to allow the function to return before the\n timer expires.\n \"\"\"\n\n def __init__(self, search_depth=3, score_fn=custom_score,\n iterative=True, method='minimax', timeout=10.):\n self.search_depth = search_depth\n self.iterative = iterative\n self.score = score_fn\n self.method = method\n self.time_left = None\n self.TIMER_THRESHOLD = timeout\n\n def get_move(self, game, legal_moves, time_left):\n \"\"\"Search for the best move from the available legal moves and return a\n result before the time limit expires.\n\n This function must perform iterative deepening if self.iterative=True,\n and it must use the search method (minimax or alphabeta) corresponding\n to the self.method value.\n\n **********************************************************************\n NOTE: If time_left < 0 when this function returns, the agent will\n forfeit the game due to timeout. You must return _before_ the\n timer reaches 0.\n **********************************************************************\n\n Parameters\n ----------\n game : `isolation.Board`\n An instance of `isolation.Board` encoding the current state of the\n game (e.g., player locations and blocked cells).\n\n legal_moves : list<(int, int)>\n A list containing legal moves. Moves are encoded as tuples of pairs\n of ints defining the next (row, col) for the agent to occupy.\n\n time_left : callable\n A function that returns the number of milliseconds left in the\n current turn. Returning with any less than 0 ms remaining forfeits\n the game.\n\n Returns\n -------\n (int, int)\n Board coordinates corresponding to a legal move; may return\n (-1, -1) if there are no available legal moves.\n \"\"\"\n\n self.time_left = time_left\n\n # TODO: finish this function!\n\n # If there are no legal moves, return immediately\n if not legal_moves:\n return(-1, -1)\n\n try:\n # Determine which search method to use\n if self.method == 'minimax':\n strategy = self.minimax\n else:\n strategy = self.alphabeta\n\n # Determine whether iterative deepening needs to be used.\n if self.iterative==True:\n self.search_depth = 1\n while game.get_legal_moves():\n search_score, search_move = strategy(game, self.search_depth)\n self.search_depth += 1\n else:\n search_score, search_move = strategy(game, self.search_depth)\n\n\n except Timeout:\n return search_move\n\n # Return the best move from the last completed search iteration\n return search_move\n\n def minimax(self, game, depth, maximizing_player=True):\n \"\"\"Implement the minimax search algorithm as described in the lectures.\n\n Parameters\n ----------\n game : isolation.Board\n An instance of the Isolation game `Board` class representing the\n current game state\n\n depth : int\n Depth is an integer representing the maximum number of plies to\n search in the game tree before aborting\n\n maximizing_player : bool\n Flag indicating whether the current search depth corresponds to a\n maximizing layer (True) or a minimizing layer (False)\n\n Returns\n -------\n float\n The score for the current search branch\n\n tuple(int, int)\n The best move for the current branch; (-1, -1) for no legal moves\n\n Notes\n -----\n (1) You MUST use the `self.score()` method for board evaluation\n to pass the project unit tests; you cannot call any other\n evaluation function directly.\n \"\"\"\n if self.time_left() < self.TIMER_THRESHOLD:\n raise Timeout()\n\n\n # If end of search depth, return value of current node\n if depth == 0:\n return (self.score(game,self), (-1,-1))\n\n # If it is the maximizing player's turn, find the highest value move assuming that the minimizing player\n # will pick the minimizing moves\n if maximizing_player:\n best_value = float('-inf')\n best_move = (-1,-1)\n for move in game.get_legal_moves():\n (value, new_move) = self.minimax(game.forecast_move(move), depth-1, maximizing_player=False)\n if value > best_value:\n best_value = value\n best_move = move\n\n return best_value, best_move\n # If it it the minimizing player's turn, find the lowest value move assuming that the maximizing player\n # will pick the maximizing moves\n else:\n best_value = float('inf')\n best_move = (-1,-1)\n for move in game.get_legal_moves():\n (value, new_move) = self.minimax(game.forecast_move(move), depth-1, maximizing_player=True)\n if value < best_value:\n best_value = value\n best_move = move\n\n return best_value, best_move\n\n\n\n def alphabeta(self, game, depth, alpha=float(\"-inf\"), beta=float(\"inf\"), maximizing_player=True):\n \"\"\"Implement minimax search with alpha-beta pruning as described in the\n lectures.\n\n Parameters\n ----------\n game : isolation.Board\n An instance of the Isolation game `Board` class representing the\n current game state\n\n depth : int\n Depth is an integer representing the maximum number of plies to\n search in the game tree before aborting\n\n alpha : float\n Alpha limits the lower bound of search on minimizing layers\n\n beta : float\n Beta limits the upper bound of search on maximizing layers\n\n maximizing_player : bool\n Flag indicating whether the current search depth corresponds to a\n maximizing layer (True) or a minimizing layer (False)\n\n Returns\n -------\n float\n The score for the current search branch\n\n tuple(int, int)\n The best move for the current branch; (-1, -1) for no legal moves\n\n Notes\n -----\n (1) You MUST use the `self.score()` method for board evaluation\n to pass the project unit tests; you cannot call any other\n evaluation function directly.\n \"\"\"\n if self.time_left() < self.TIMER_THRESHOLD:\n raise Timeout()\n\n # If end of search depth, return value of current node\n if depth == 0:\n return (self.score(game,self), (-1,-1))\n\n # If it is the maximizing player's turn, find the highest value move assuming that the minimizing player\n # will pick the minimizing moves\n if maximizing_player:\n best_value = float('-inf')\n best_move = (-1,-1)\n for move in game.get_legal_moves():\n (value, new_move) = self.alphabeta(game.forecast_move(move), depth-1, alpha, beta, maximizing_player=False)\n if value > best_value:\n best_value = value\n best_move = move\n\n # If the value of the node is greater than the maximum score for the miminimizing player,\n # the tree can be cut\n if value >= beta:\n return best_value, best_move\n\n # Update alpha (the minimum score for the maximizing player)\n alpha = max(alpha,value)\n\n\n\n return best_value, best_move\n # If it it the minimizing player's turn, find the lowest value move assuming that the maximizing player\n # will pick the maximizing moves\n else:\n best_value = float('inf')\n best_move = (-1,-1)\n for move in game.get_legal_moves():\n (value, new_move) = self.alphabeta(game.forecast_move(move), depth-1, alpha, beta, maximizing_player=True)\n if value < best_value:\n best_value = value\n best_move = move\n\n # If the value of the node is less than the minimum score for the maximizing player,\n # the tree can be current\n if value <= alpha:\n return best_value, best_move\n\n # Update beta (the maximum score for the minimizing player)\n beta = min(beta,value)\n\n\n return best_value, best_move\n","repo_name":"chinyen/AIND-Isolation","sub_path":"game_agent.py","file_name":"game_agent.py","file_ext":"py","file_size_in_byte":15848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"77"} +{"seq_id":"26208507944","text":"from diablo import std_commit\nfrom diablo.jobs.tasks.queued_emails_task import QueuedEmailsTask\nfrom diablo.lib.util import utc_now\nfrom diablo.models.course_preference import CoursePreference\nfrom diablo.models.queued_email import QueuedEmail\nfrom diablo.models.sent_email import SentEmail\nfrom diablo.models.sis_section import SisSection\nfrom flask import current_app as app\n\n\nclass TestQueuedEmailsTask:\n\n def test_no_email_queued(self):\n \"\"\"Do nothing if 'queued_emails' table is empty.\"\"\"\n term_id = app.config['CURRENT_TERM_ID']\n QueuedEmailsTask().run()\n std_commit(allow_test_environment=True)\n # Verify that the next job run will have zero queued emails.\n assert len(QueuedEmail.get_all(term_id=term_id)) == 0\n\n QueuedEmailsTask().run()\n std_commit(allow_test_environment=True)\n # If we reach this point then no error occurred.\n\n def test_send_invitation_emails(self):\n \"\"\"Send all email in 'queued_emails' table.\"\"\"\n term_id = app.config['CURRENT_TERM_ID']\n courses = SisSection.get_courses(section_ids=[50000, 50001], term_id=term_id)\n email_template_type = 'invitation'\n\n for course in courses:\n for instructor in course['instructors']:\n QueuedEmail.create(course['sectionId'], email_template_type, term_id, recipient=instructor)\n std_commit(allow_test_environment=True)\n\n def _get_emails_to_courses():\n emails_sent = []\n for c in courses:\n emails_sent.extend(\n _get_emails_sent(\n email_template_type=email_template_type,\n section_id=c['sectionId'],\n term_id=term_id,\n ),\n )\n return emails_sent\n\n before = utc_now()\n emails_sent_before = _get_emails_to_courses()\n # Run the job\n QueuedEmailsTask().run()\n std_commit(allow_test_environment=True)\n\n # Expect one email per instructor\n emails_sent_after = _get_emails_to_courses()\n assert len(emails_sent_after) == len(emails_sent_before) + 3\n\n def _find_email(section_id, uid):\n return next((e for e in emails_sent_after if e.section_id == section_id and e.sent_at > before and uid == e.recipient_uid), None)\n\n for course in courses:\n for instructor in course['instructors']:\n sent_email = _find_email(section_id=course['sectionId'], uid=instructor['uid'])\n assert sent_email\n email_json = sent_email.to_api_json()\n assert email_json['recipientUid'] == instructor['uid']\n assert email_json['sectionId'] == course['sectionId']\n assert email_json['templateType'] == email_template_type\n assert email_json['termId'] == term_id\n assert email_json['sentAt']\n\n def test_course_has_opted_out(self):\n \"\"\"Do not send email to courses that have opted out.\"\"\"\n def _emails_sent():\n return _get_emails_sent(email_template_type=email_template_type, section_id=section_id, term_id=term_id)\n\n term_id = app.config['CURRENT_TERM_ID']\n section_id = 50000\n CoursePreference.update_opt_out(term_id=term_id, section_id=section_id, opt_out=True)\n email_template_type = 'invitation'\n recipient = {\n 'name': 'William Peter Blatty',\n 'uid': '10001',\n }\n QueuedEmail.create(section_id, email_template_type, term_id, recipient=recipient)\n std_commit(allow_test_environment=True)\n\n emails_sent_before = _emails_sent()\n # Run the job\n QueuedEmailsTask().run()\n std_commit(allow_test_environment=True)\n\n # Expect no emails sent\n emails_sent_after = _emails_sent()\n assert len(emails_sent_after) == len(emails_sent_before)\n assert list(map(lambda e: e.id, emails_sent_before)) == list(map(lambda e: e.id, emails_sent_after))\n\n def test_queued_email_for_admin(self):\n \"\"\"Certain email template types are for admin recipients only.\"\"\"\n def _emails_sent():\n return _get_emails_sent(email_template_type=email_template_type, section_id=section_id, term_id=term_id)\n\n term_id = app.config['CURRENT_TERM_ID']\n section_id = 50005\n email_template_type = 'admin_alert_room_change'\n recipient_uid = app.config['EMAIL_DIABLO_ADMIN_UID']\n QueuedEmail.create(\n section_id,\n email_template_type,\n term_id,\n recipient={\n 'name': 'Course Capture Admin',\n 'uid': recipient_uid,\n },\n )\n std_commit(allow_test_environment=True)\n\n before = utc_now()\n emails_sent_before = _emails_sent()\n # Run the job\n QueuedEmailsTask().run()\n std_commit(allow_test_environment=True)\n\n # Expect email to admin email address\n emails_sent_after = _emails_sent()\n assert len(emails_sent_after) == len(emails_sent_before) + 1\n\n sent_email = next((e for e in emails_sent_after if e.section_id == section_id and e.sent_at > before), None)\n assert sent_email\n email_json = sent_email.to_api_json()\n assert email_json['recipientUid'] == recipient_uid\n assert email_json['sectionId'] == section_id\n assert email_json['templateType'] == email_template_type\n assert email_json['termId'] == term_id\n assert email_json['sentAt']\n\n\ndef _get_emails_sent(email_template_type, section_id, term_id):\n return SentEmail.get_emails_of_type(\n section_ids=[section_id],\n template_type=email_template_type,\n term_id=term_id,\n )\n","repo_name":"ets-berkeley-edu/diablo","sub_path":"tests/test_tasks/test_queued_emails_task.py","file_name":"test_queued_emails_task.py","file_ext":"py","file_size_in_byte":5790,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"} +{"seq_id":"9134671695","text":"from functools import partial\nfrom tkinter import *\nfrom Parser import Parser\nimport shelve\nfrom tkinter.messagebox import showerror\n# globally declare the expression variable\nclass Calculator:\n\n def __init__(self):\n self.expression = \"\"\n self.window = Tk()\n self.parser = Parser()\n self.window.title(\"Calculator\")\n self.equation = StringVar()\n self.entry = Entry(self.window, textvariable=self.equation)\n self.entry.grid(row=1)\n buttonFrame = Frame(self.window)\n buttonFrame.grid(row=3)\n for i in range(9):\n Button(buttonFrame, command=partial(self.press, i + 1), text=str(i + 1), height=4, width=4) \\\n .grid(row=i // 3, column=i % 3)\n\n btnEquals = Button(buttonFrame, text='=', command=lambda: self.result(), height=4, width=4) \\\n .grid(row=4, column=0)\n btnZero = Button(buttonFrame, command=partial(self.press, 0), text=str(0), height=4, width=4) \\\n .grid(row=4, column=1)\n btnClean = Button(buttonFrame, command=lambda :self.clean(), text='C', height=4, width=4) \\\n .grid(row=4, column=2)\n btnLeftBracket = Button(buttonFrame, command=partial(self.press, ')'), text=')', height=4, width=4) \\\n .grid(row=0, column=4)\n btnRightBracket = Button(buttonFrame, command=partial(self.press, '('), text='(', height=4, width=4) \\\n .grid(row=1, column=4)\n btnPlus = Button(buttonFrame, command=partial(self.press, '+'), text='+', height=4, width=4) \\\n .grid(row=0, column=5)\n btnMinus = Button(buttonFrame, command=partial(self.press, '-'), text='-', height=4, width=4) \\\n .grid(row=1, column=5)\n # btnProd = Button(buttonFrame, command=partial(self.press, '*'), text='*', height=4, width=4) .grid(row=2, column=5)\n self.window.mainloop()\n\n\n def clean(self):\n self.expression = \"\"\n self.equation.set(self.expression)\n def press(self, num):\n self.expression = self.expression + str(num)\n self.equation.set(self.expression)\n\n\n def result(self):\n print(\"Result\")\n result = self.parser.parse(self.expression)\n self.equation.set(result)\n\n\ndef makeWidget():\n\n global equation\n\n\nif __name__ == '__main__':\n c = Calculator()\n","repo_name":"DmitrySavkin/calculator","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2314,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"13267224658","text":"#!/usr/bin/env python3\n\"\"\"\n This is python2 + python3 compatible and has no third\n party dependencies.\n\"\"\"\n\nimport sys\nimport time\nimport os\nimport pwd\nimport grp\nfrom hashlib import md5\nimport json\n\nfrom ipdb import set_trace\n\ntarget_dir = \"\"\noutput_file = \"\"\nblacklist_dirs = [\n \"/tmp/\",\n \"/proc/\",\n \"/run/\",\n \"/dev/\",\n \"/sys/\",\n \"/lost+found\",\n \"/usr/share/man/\",\n \"/usr/include/\",\n]\n\ncounter_files = counter_dirs = 0\n\nbig_data = {}\nerrors = []\n\n\ndef parse_args():\n global target_dir, output_file\n if len(sys.argv) != 3:\n print(\"ERROR: {} \".format(sys.argv[0]))\n sys.exit(1)\n output_file = sys.argv[1]\n target_dir = sys.argv[2]\n\n\ndef get_perm(path):\n global errors\n file_info = {}\n file_info['type'] = 'dir'\n try:\n s = os.stat(path)\n file_info['owner'] = pwd.getpwuid(s.st_uid).pw_name\n file_info['group'] = grp.getgrgid(s.st_gid).gr_name\n file_info['permissions'] = oct(s.st_mode)[-4:]\n except (KeyError, OSError) as e:\n msg = \"{}: {}\".format(path, e)\n errors.append(msg)\n return file_info\n\n\ndef process_file(f_abs):\n file_info = get_perm(f_abs)\n file_info['type'] = 'file' # get_perm sets fix dir. we overwrite here\n file_info['can_read'] = True\n try:\n with open(f_abs, \"rb\") as f:\n m = md5(f.read())\n file_info['md5'] = m.hexdigest()\n except Exception:\n file_info['can_read'] = False\n return file_info\n\n\ndef extract_files_and_dirs(target_dir):\n global counter_dirs, counter_files, big_data\n for dirpath, directories, filenames in os.walk(target_dir):\n\n # process all files\n for f in filenames:\n f_abs = os.path.join(dirpath, f)\n if is_blacklisted(f_abs):\n continue\n counter_files += 1\n print(\"FILE {}\".format(f_abs))\n file_info = process_file(f_abs)\n big_data[f_abs] = file_info\n\n # process all dirs\n for d in directories:\n d_abs = os.path.join(dirpath, d)\n if is_blacklisted(d_abs):\n continue\n counter_dirs += 1\n print(\"DIR {}\".format(d_abs))\n file_info = get_perm(d_abs)\n big_data[d_abs] = file_info\n print(\"\\nProcessed {} files and {} dirs from {}\".format(counter_files, \n counter_dirs,\n target_dir))\n\n\ndef is_blacklisted(d_abs):\n for blacklisted_dir in blacklist_dirs:\n if d_abs.startswith(blacklisted_dir):\n print(\"BLACKLIST {}\".format(d_abs))\n return True\n return False\n\n\ndef dump():\n with open(output_file, \"w\") as f:\n json.dump(big_data, f)\n print(\"Data written to {}\".format(output_file))\n\n\nif __name__ == '__main__':\n parse_args()\n start = time.time()\n extract_files_and_dirs(target_dir)\n dump()\n end = time.time()\n print(\"We needed {} seconds\".format(int(end-start)))\n if len(errors) > 0:\n print(\"\\nWe got the following errors:\")\n for error in errors:\n print(error)\n","repo_name":"kmille/rusted-in-the-air","sub_path":"lauf.py","file_name":"lauf.py","file_ext":"py","file_size_in_byte":3221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"72065510010","text":"\"\"\"\nImplementation of Algorithms 1 and 4 of [Ball2018]_\n\n.. moduleauthor:: Fabian Ball \n\"\"\"\nfrom orbits import compute_orbit_partition\n\n\ndef test_stability(P, S):\n \"\"\"\n Test partition stability.\n\n Usage:\n\n >>> from sparsepermutation import SparsePermutation\n >>> from partitionstability import test_stability\n >>> p1 = SparsePermutation([1, 0, 2, 3, 5, 4, 6, 7, 8, 9]) # (0 1)(4 5)\n >>> p2 = SparsePermutation([0, 1, 2, 3, 4, 5, 6, 7, 9, 8]) # (8 9)\n >>> p3 = SparsePermutation([0, 8, 2, 3, 4, 5, 6, 7, 1, 9]) # (1 8)\n >>> S = [p1, p2, p3]\n >>> P = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n >>> assert test_stability(P, S) == True\n >>> Q = [1, 1, 0, 0, 0, 0, 0, 0, 2, 2]\n >>> assert test_stability(Q, S) == False\n\n :param P: A partition in an array-like representation, clusters are identified by cluster ids\n :type P: list | tuple\n :param S: A set of generators for a permutation group\n :type S: list | tuple | set\n :return: True, if the partition is stable\n :rtype: bool\n \"\"\"\n if not S:\n return True\n\n O = compute_orbit_partition(S, len(P))\n\n if geq(P, O):\n return True\n\n for pi in S:\n P_pi = [P[pi[i]] for i in range(len(P))] # Apply pi on P\n if not geq(P, P_pi):\n return False\n\n return True\n\n\ndef geq(P, Q):\n \"\"\"\n Test if ``P`` is coarser than or equal to ``Q``.\n Both, equality and coarseness are up to label isomorphism, i.e. partitions [0, 0, 1] and [3, 3, 7] are equal.\n A partition ``P`` is coarser than a partition ``Q`` if each cluster in ``Q`` is a subset of a cluster in ``P``.\n\n Data representation is:\n * Partition ``P``: array-like, i.e. ``P[i]`` corresponds to the (arbitrary) cluster id of node ``i``\n\n Usage:\n\n >>> from partitionstability import geq\n >>> P = [0,0,0,1,1,1]\n >>> P_prime = [1,1,1,0,0,0]\n >>> Q = [3,3,0,2,2,1]\n >>> R = [3,3,3,3,1,1]\n >>> assert geq(P, Q) == True\n >>> assert geq(P, P_prime) == True\n >>> assert geq(P, P_prime) == geq(P_prime, P) # Cluster ids are arbitrary!\n >>> assert geq(P, R) == False\n >>> assert geq(R, P) == False\n >>> S = list(range(100))\n >>> from random import shuffle\n >>> shuffle(S)\n >>> assert geq(list(range(100)), S) == True\n\n :param P: A partition in an array-like representation of node ids\n :type P: list | tuple\n :param Q: A partition in an array-like representation of node ids\n :type Q: list | tuple\n :return: True, if :math:`P \\geq Q`\n :rtype: bool\n \"\"\"\n assert len(P) == len(Q)\n maps = {} # Save cluster ids from Q in P. Multiple clusters in Q can map to the same cluster id in P\n\n for i in range(len(P)):\n if Q[i] in maps: # The orbit id in Q was already seen\n o_id = maps[Q[i]]\n else: # The first occurrence of an orbit id is saved\n o_id = P[i] # The orbit id in P\n maps[Q[i]] = o_id # The orbit id in Q maps to the one in P\n\n if P[i] != o_id: # The orbit ids must match\n return False\n\n return True\n","repo_name":"KIT-IISM-EM/partitionstability","sub_path":"Python/partitionstability.py","file_name":"partitionstability.py","file_ext":"py","file_size_in_byte":3072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"38638882208","text":"import pytest\r\nfrom wordle_solver.solver import Solver\r\n\r\nclass TestBase:\r\n @pytest.fixture(autouse=True)\r\n def _solver(self):\r\n word_list = ['abc', 'cde', 'def']\r\n self.solver = Solver(word_list, alphabet='abcdef')\r\n\r\n @pytest.fixture(autouse=True)\r\n def _useful_setup_variables(self):\r\n self.list_of_empty_sets = [set(), set(), set()]\r\n self.state_abc = ['a', 'b', 'c']\r\n self.state_ab_None = ['a', 'b', None]\r\n\r\nclass TestAvailableLetters(TestBase):\r\n def test_without_restrictions(self):\r\n warm_letters = self.list_of_empty_sets\r\n available_letters = self.solver.available_letters(warm_letters, set())\r\n for position in available_letters:\r\n assert sorted(position) == list('abcdef')\r\n\r\n def test_with_warm_letters(self):\r\n warm_letters = [{'a', 'b'}, {'c'}, set()]\r\n available_letters = self.solver.available_letters(warm_letters, set())\r\n assert sorted(available_letters[0]) == list('cdef')\r\n assert sorted(available_letters[1]) == list('abdef')\r\n assert sorted(available_letters[2]) == list('abcdef')\r\n\r\n def test_with_cold_letters(self):\r\n warm_letters = self.list_of_empty_sets\r\n cold_letters = {'a', 'b'}\r\n available_letters = self.solver.available_letters(warm_letters, cold_letters)\r\n for position in available_letters:\r\n assert sorted(position) == list('cdef')\r\n\r\n def test_with_warm_and_cold_letters(self):\r\n warm_letters = [{'b'}, set(), {'d'}]\r\n cold_letters = {'a'}\r\n available_letters = self.solver.available_letters(warm_letters, cold_letters)\r\n assert sorted(available_letters[0]) == list('cdef')\r\n assert sorted(available_letters[1]) == list('bcdef')\r\n assert sorted(available_letters[2]) == list('bcef')\r\n\r\nclass TestTransition(TestBase):\r\n def test_updates_value(self):\r\n new_state = self.solver.transition(self.state_ab_None, 'c', 2)\r\n assert ''.join(new_state) == 'abc'\r\n\r\n def test_maintains_original(self):\r\n state = [None]\r\n new_state = self.solver.transition(state, 'a', 0)\r\n assert state[0] is None\r\n\r\nclass TestSuccesors(TestBase):\r\n def test_terminal_state(self):\r\n available_letters = [{'d'}] * 3\r\n successors = self.solver.successors(self.state_abc, available_letters)\r\n assert len(list(successors)) == 0\r\n\r\n def test_nonterminal_state(self):\r\n state = ['a', None]\r\n available_letters = [{'b', 'c', 'd'}] * 2\r\n successors = self.solver.successors(state, available_letters)\r\n assert sorted(successors) == [['a', 'b'], ['a', 'c'], ['a', 'd']]\r\n\r\nclass TestIsValid(TestBase):\r\n def test_valid_state_no_requirements(self):\r\n warm_letters = self.list_of_empty_sets\r\n is_valid = self.solver.is_valid(self.state_abc, warm_letters)\r\n assert is_valid\r\n\r\n def test_valid_state_with_requirements(self):\r\n warm_letters = [set(), {'c'}, {'a'}]\r\n is_valid = self.solver.is_valid(self.state_abc, warm_letters)\r\n assert is_valid\r\n\r\n def test_invalid_state_with_requirements(self):\r\n warm_letters = self.list_of_empty_sets\r\n warm_letters[0] = {'d'}\r\n is_valid = self.solver.is_valid(self.state_abc, warm_letters)\r\n assert not is_valid\r\n\r\nclass TestIsTerminal(TestBase):\r\n def test_terminal_state(self):\r\n is_terminal = self.solver.is_terminal(self.state_abc)\r\n assert is_terminal\r\n\r\n def test_nonterminal_state(self):\r\n is_terminal = self.solver.is_terminal(self.state_ab_None)\r\n assert not is_terminal\r\n\r\nclass TestSearch(TestBase):\r\n def test_no_starting_info(self):\r\n initial_state = [None] * 3\r\n warm_letters = self.list_of_empty_sets\r\n possible_words = self.solver.search(initial_state, warm_letters, set())\r\n assert len(possible_words) == len(self.solver.alphabet) ** self.solver.word_length\r\n\r\n def test_with_cold_letters(self):\r\n initial_state = self.state_ab_None\r\n warm_letters = self.list_of_empty_sets\r\n cold_letters = {'e', 'f'}\r\n possible_words = self.solver.search(initial_state, warm_letters, cold_letters)\r\n assert sorted(possible_words) == ['aba', 'abb', 'abc', 'abd']\r\n\r\n def test_with_warm_and_cold_letters(self):\r\n initial_state = self.state_ab_None\r\n warm_letters = self.list_of_empty_sets\r\n warm_letters[0] = {'c'}\r\n cold_letters = {'e', 'f'}\r\n possible_words = self.solver.search(initial_state, warm_letters, cold_letters)\r\n assert sorted(possible_words) == ['abc']\r\n\r\nclass TestPossibleAnswers(TestBase):\r\n def test_no_starting_info(self):\r\n initial_state = [None] * 3\r\n warm_letters = self.list_of_empty_sets\r\n possible_answers = self.solver.possible_answers(initial_state, warm_letters, set())\r\n assert sorted(possible_answers) == sorted(self.solver.master_word_list)\r\n\r\n def test_with_starting_info(self):\r\n initial_state = self.state_ab_None\r\n warm_letters = self.list_of_empty_sets\r\n warm_letters[0] = {'c'}\r\n cold_letters = {'e', 'f'}\r\n possible_answers = self.solver.possible_answers(initial_state, warm_letters, cold_letters)\r\n assert sorted(possible_answers) == ['abc']\r\n","repo_name":"jakeoeding/wordle-solver","sub_path":"tests/solver_test.py","file_name":"solver_test.py","file_ext":"py","file_size_in_byte":5327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"13021856190","text":"import pytest\n\nfrom company_name import CompanyNameAgent, Reason, Result, Solution\n\n\n@pytest.mark.parametrize(\n (\"first\", \"second\"),\n (\n ((), ()),\n ((), (\"COMPANY NAME\",)),\n ((\"COMPANY NAME\",), ()),\n ((\"\",), (\"\",)),\n ((None,), (None,)),\n ((\"\",), (None,)),\n ),\n)\ndef test_when_no_names(first, second):\n print(first, second)\n result = CompanyNameAgent().resolve(first, second)\n print(result)\n assert result == Result(Solution.NO_DATA, Reason())\n\n\n@pytest.mark.parametrize(\n (\"first\", \"second\", \"expected_solution\"),\n (\n ((\"Google limited liability company\",), (\"GOOGLE LLC\",), Solution.MATCH),\n ((\"Google\",), (\"Facebook\",), Solution.NO_MATCH),\n ),\n)\ndef test_when_one_name(first, second, expected_solution):\n print(first, second)\n result = CompanyNameAgent().resolve(first, second)\n assert result.solution == expected_solution\n\n\n@pytest.mark.parametrize(\n (\"first\", \"second\"),\n (\n ((\"GOOGLE LLC\",), (\"GOOGLE LLC\",)),\n ((\"GOOGLE LLC\",), (\"GOOGLE LLC\", \"FACEBOOK\", \"AMAZON.COM\")),\n (\n (\n \"AGRICULTURAL BANK OF CHINA\",\n \"POWERCHINA\",\n ),\n (\"AGRICULTURAL BANK OF CHINA\",),\n ),\n ),\n)\ndef test_choose_exact_name(first, second):\n print(first, second)\n result = CompanyNameAgent().resolve(first, second)\n assert result.solution == Solution.MATCH\n assert (\n result.reason.results[0].alerted_party_name == result.reason.results[0].watchlist_party_name\n )\n\n\n@pytest.mark.parametrize((\"first\", \"second\"), (((\"THE VTB BANK\",), (\"SAFE NAME\",)),))\ndef test_blacklist(first, second):\n print(first, second)\n assert CompanyNameAgent().resolve(first, second).solution == Solution.MATCH\n\n\n@pytest.mark.parametrize(\n (\"first\", \"second\"),\n (\n ((\"THE NATIONAL COMMERCIAL BANK\",), (\"NCB\",)),\n (\n (\"THE NATIONAL COMMERCIAL BANK\",),\n (\"NCB\", \"BANK OF CHINA\", \"NATIONAL TREASURY\"),\n ),\n ),\n)\ndef test_abbreviation(first, second):\n print(first, second)\n result = CompanyNameAgent().resolve(first, second)\n assert result.solution == Solution.MATCH\n\n\n@pytest.mark.parametrize(\n (\"first\", \"second\", \"abbreviation_not_chosen\"),\n (\n (\n (\"THE NATIONAL COMMERCIAL BANK\",),\n (\"NCB\", \"THE NATIONAL COMMERCIAL BANK\"),\n \"NCB\",\n ),\n ),\n)\ndef test_choose_exact_name_over_abbreviation(first, second, abbreviation_not_chosen):\n print(first, second)\n result = CompanyNameAgent()._resolve(first, second)\n assert result.solution == Solution.MATCH\n assert abbreviation_not_chosen != result.reason.results[0].watchlist_party_name\n\n\n@pytest.mark.parametrize(\n \"first, second\",\n [\n ((\"OSANG HEAL THCARE CO LTD INFOPIA\",), (\"INFOPIA CO LTD\",)),\n ((\"SCCM DYBNG AND PRINTING CO. ATO\",), (\"ATO, OOO\",)),\n ],\n)\ndef test_match_when_base_name_after_legal_take_it_from_other(first, second):\n print(first, second)\n result = CompanyNameAgent().resolve(first, second)\n assert result.solution == Solution.MATCH\n","repo_name":"ngraczykowski/iris-root","sub_path":"modules/organization-name-agent/tests/agent/test_company_name_agent.py","file_name":"test_company_name_agent.py","file_ext":"py","file_size_in_byte":3131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"72090163448","text":"from unstructured.partition.auto import partition\nfrom unstructured.staging.base import elements_to_json\nfrom time import perf_counter as pc\n\nt0 = pc()\n\n\nelements = partition(filename=\"./resume.pdf\")\nfor element in elements:\n print(elements)\n print(\"\\n\")\n\n\nelements_to_json(elements, filename=\"output.json\")\n\nprint(pc() - t0)\n","repo_name":"alextanhongpin/python-unstructured","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"36886290725","text":"from cgitb import grey\nfrom msilib.schema import Icon\nfrom string import whitespace\nfrom tkinter import *\nimport sqlite3\nfrom tkinter import messagebox\nfrom turtle import bgcolor\ncon =sqlite3.connect('crm.db')\ncur =con.cursor()\n\n\n\nclass Createclient(Toplevel):\n def __init__(self):\n Toplevel.__init__(self)\n self.title(\"CRM System\")\n self.geometry(\"700x550+350+200\")\n self.resizable(False,False)\n\n self.top= Frame(self,height=150)\n self.top.pack(fill=X)\n self.bottom= Frame(self,height=500)\n self.bottom.pack(fill=X)\n self.heading=Label(self.top, text='Create a Client',\n font='arial 18 ')\n self.heading.place(x=260 ,y=60)\n\n self.lablel_fullname = Label(self.bottom, text=\"Utilize the same format as shown in the input fields below:\", font='arial 10')\n self.lablel_fullname.place(x=49, y=-6)\n\n # fullname, sin, dob\n self.lablel_fullname=Label(self.bottom,text=\"Full name, SIN#, DOB:\",font='arial 15')\n self.lablel_fullname.place(x=49,y=19)\n self.entry_fullname=Entry(self.bottom,width=30,bd=4)\n self.entry_fullname.insert(0,\"John Doe, 999999999, 1960-01-01\")\n self.entry_fullname.place(x=265,y=19)\n\n #jobtitle\n self.lablel_JobTittle=Label(self.bottom,text=\"Job title:\",font='arial 15')\n self.lablel_JobTittle.place(x=49,y=49)\n self.entry_JobTittle=Entry(self.bottom,width=30,bd=4)\n self.entry_JobTittle.insert(0,\"Manager\")\n self.entry_JobTittle.place(x=150,y=49)\n #phonenumber\n self.lablel_phonenumber=Label(self.bottom,text=\"Phone number:\",font='arial 15')\n self.lablel_phonenumber.place(x=49,y=79)\n self.entry_phonenumber=Entry(self.bottom,width=30,bd=4)\n self.entry_phonenumber.insert(0,\"6040001111\")\n self.entry_phonenumber.place(x=200,y=79)\n #buisnessphonenumber\n self.lablel_buisnessphonenumber=Label(self.bottom,text=\"Business phone number:\",font='arial 15')\n self.lablel_buisnessphonenumber.place(x=49,y=109)\n self.entry_buisnessphonenumber=Entry(self.bottom,width=30,bd=4)\n self.entry_buisnessphonenumber.insert(0,\"6040002222\")\n self.entry_buisnessphonenumber.place(x=280,y=109)\n #networth\n self.lablel_networth=Label(self.bottom,text=\"Net worth:\",font='arial 15')\n self.lablel_networth.place(x=49,y=139)\n self.entry_networth=Entry(self.bottom,width=30,bd=4)\n self.entry_networth.insert(0,\"100000\")\n self.entry_networth.place(x=150,y=139)\n #assets\n self.lablel_assets=Label(self.bottom,text=\"Assets:\",font='arial 15')\n self.lablel_assets.place(x=49,y=169)\n self.entry_assets=Entry(self.bottom,width=30,bd=4)\n self.entry_assets.insert(0,\"2 cars, 1 house\")\n self.entry_assets.place(x=150,y=169)\n #liabilities\n self.lablel_liabilities=Label(self.bottom,text=\"Liabilities:\",font='arial 15')\n self.lablel_liabilities.place(x=49,y=199)\n self.entry_liabilities=Entry(self.bottom,width=30,bd=4)\n self.entry_liabilities.insert(0,\"Car payments, 2 CCs to pay off\")\n self.entry_liabilities.place(x=150,y=199)\n #expenses\n self.lablel_expenses=Label(self.bottom,text=\"Expenses:\",font='arial 15')\n self.lablel_expenses.place(x=49,y=229)\n self.entry_expenses=Entry(self.bottom,width=30,bd=4)\n self.entry_expenses.insert(0,\"25000\")\n self.entry_expenses.place(x=150,y=229)\n #email\n self.lablel_email=Label(self.bottom,text=\"E-mail:\",font='arial 15')\n self.lablel_email.place(x=49,y=259)\n self.entry_email=Entry(self.bottom,width=30,bd=4)\n self.entry_email.insert(0,\"email@johndoe.com\")\n self.entry_email.place(x=150,y=259)\n \n\n\n btnadd=Button(self.bottom,text=\"Add New Client\",font='arial 12 ',width=15,height=2,command=self.add_client)\n btnadd.place(x=270,y=320)\n \n def add_client(self):\n full_name=self.entry_fullname.get()\n job_tittle=self.entry_JobTittle.get()\n\n phone_number=self.entry_phonenumber.get()\n buisness_number=self.entry_buisnessphonenumber.get()\n net_worth=self.entry_networth.get()\n assets=self.entry_assets.get()\n liabilites=self.entry_liabilities.get()\n Expenses=self.entry_expenses.get()\n email=self.entry_email.get()\n\n client_error: bool = False\n\n #check if the client information contains errors\n\n if full_name == \"\"or job_tittle == \"\"or phone_number == \"\"or buisness_number == \"\"or net_worth == \"\"or assets == \"\"or liabilites == \"\"or Expenses == \"\"or email == \"\":\n messagebox.showinfo(\"Error\",\"Please fill all the fields.\")\n client_error = True\n self.destroy()\n\n if isinstance(full_name, str) is False or isinstance(job_tittle, str) is False or phone_number.isnumeric() is False or buisness_number.isnumeric() is False or net_worth.isnumeric() is False or isinstance(assets, str) is False or isinstance (liabilites, str) is False or Expenses.isnumeric() is False or isinstance(email, str) is False:\n messagebox.showinfo(\"Error\",\"One or more user input is not in the correct format (numbers, letters, etc) Do not use the $ for money amounts.\")\n client_error = True\n self.destroy()\n\n # checks if the full name is in the correct format prior to splitting it up into lists for further error checking\n if full_name.count('-') != 2 or full_name.count(',') != 2 or full_name.count(' ') < 2:\n messagebox.showinfo(\"Error\",\n \"Please enter the names, social security number and date of birth seperated by commas and the date of birth in the YYYY-MM-DD format. Use spaces between the sections.\")\n client_error = True\n self.destroy()\n else:\n # holds the name, sin number and dob in a list\n client_list = full_name.split(\",\")\n\n date_of_birth_list = client_list[2].split(\"-\")\n\n # checks the number of numbers in the SIN number, must be a 9 digit number\n if len(client_list[1]) - client_list[1].count(' ') != 9:\n messagebox.showinfo(\"Error\", \"Please enter a SIN number with 9 digits.\")\n client_error = True\n self.destroy()\n \n #checks if the SIN number is numeric\n if client_list[1].strip().isnumeric() == False:\n messagebox.showinfo(\"Error\", \"Please enter a SIN number with with only numeric characters.\")\n client_error = True\n self.destroy()\n\n # checks if the date of birth is in the right format\n if client_list[2].count('-') != 2 or len(date_of_birth_list[0]) - date_of_birth_list[0].count(\n ' ') != 4 or len(date_of_birth_list[1]) - date_of_birth_list[1].count(' ') != 2 or len(\n date_of_birth_list[2]) - date_of_birth_list[2].count(' ') != 2:\n messagebox.showinfo(\"Error\", \"Please enter the date of birth in the YYYY-MM-DD format.\")\n client_error = True\n self.destroy()\n\n\n if email.count('@') < 1:\n messagebox.showinfo(\"Error\",\"Please enter a email with a @ symbol.\")\n client_error = True\n self.destroy()\n\n if len(buisness_number) != 10:\n messagebox.showinfo(\"Error\",\"Please enter a 10 digit phone number.\")\n client_error = True\n self.destroy()\n \n if len(phone_number) != 10:\n messagebox.showinfo(\"Error\",\"Please enter a 10 digit phone number.\")\n client_error = True\n self.destroy()\n\n\n #if no errors are present, try to add the client into the db\n if client_error == False:\n try:\n query = \"insert into 'client_info'('full_name','job_tittle','phone_number','buisness_number','net_worth','assets','liabilites','Expenses','email') values(?,?,?,?,?,?,?,?,?)\"\n cur.execute(query, (\n full_name, job_tittle, phone_number, buisness_number, net_worth, assets, liabilites, Expenses, email))\n except:\n messagebox.showerror(\"Error\")\n self.destroy()\n else:\n con.commit()\n messagebox.showinfo(\"Success\", \"Client was added successfully.\")\n self.destroy()\n","repo_name":"hardec303/finalProject","sub_path":"create_client.py","file_name":"create_client.py","file_ext":"py","file_size_in_byte":8555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"3442989528","text":"#!/usr/bin/env python3\n\nimport soundfile as sf\nfrom sys import argv\nfrom pedalboard import (\n Pedalboard,\n Compressor,\n Convolution,\n Chorus,\n Gain,\n Reverb,\n Limiter,\n LadderFilter,\n Phaser,\n)\nimport time, webbrowser\n\nfileName = argv[0] if argv[0] != 'demo.py' else 'short-demo-song.wav'\n\nprint('reading soundfile %s...' % (fileName))\n\naudio, sample_rate = sf.read(fileName)\n\nnewFileName = 'short-demo-song-processed' + str(int(time.time())) + '.wav'\n\nprint('setting up board...')\n\n# Make a Pedalboard object, containing multiple plugins:\nboard = Pedalboard([\n Compressor(threshold_db=-24, ratio=25),\n Gain(gain_db=0.3),\n Chorus(rate_hz=0.2, mix=0.2, depth=0.1),\n Convolution('crash.wav', 0.6),\n LadderFilter(mode=LadderFilter.Mode.HPF12, cutoff_hz=300),\n # Phaser(),\n Reverb(room_size=0.3),\n], sample_rate=sample_rate)\n\nprint('board set up!')\n\n# Pedalboard objects behave like lists, so you can add plugins:\nboard.append(Compressor(threshold_db=-25, ratio=10))\n# board.append(Gain(gain_db=1))\nboard.append(Limiter())\n\nprint('running audio through pedalboard...')\n\n# Run the audio through this pedalboard!\neffected = board(audio)\n\nprint('writing back as wav file...')\n\n# Write the audio back as a wav file:\nwith sf.SoundFile(newFileName, 'w', samplerate=sample_rate, channels=len(effected.shape)) as f:\n f.write(effected)\n\nprint('done!')\n\nchrome_path = 'open -a /Applications/Google\\ Chrome.app %s'\n\nwebbrowser.get(chrome_path).open(newFileName)","repo_name":"jonathanfann/jfx","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"29275175134","text":"import os, sys, math, pygame, pygame.mixer, euclid, time\nfrom pygame.locals import *\nimport random\n\nblack = 0, 0, 0\nwhite = 255, 255, 255\nred = 255, 0, 0\ngreen = 0, 255, 0\nblue = 0, 0, 255\nyellow = 255, 255, 0\ntimediff = 1\ncolors = [white, green, blue, red, yellow]\nscreen = None\nscreen_size = None\nclock = pygame.time.Clock()\ncenter_circle = None\nimage = None\nrect = None\n\n\ndef initialize():\n global center_circle, Road1, Road2, screen, screen_size\n screen_size = screen_width, screen_height = 300, 300\n screen = pygame.display.set_mode(screen_size)\n clock = pygame.time.Clock()\n pygame.display.set_caption(\"Assignment 1\")\n screen.fill(white)\n\nclass Mycircle:\n def __init__(self, position, size, color = (255, 255, 255),velocity = euclid.Vector2(0, 0) , width = 0):\n self.position = position\n self.size = size\n self.color = color\n self.width = width\n self.velocity = velocity\n self.display()\n\n def display(self):\n rx, ry = int(self.position.x), int(self.position.y)\n pygame.draw.circle(screen, self.color, (rx, ry), self.size, self.width)\n\n def changeColor(self, color):\n self.color = color\n\n def move(self ,position):\n self.changeColor(white)\n self.display()\n self.position = position\n self.changeColor(green)\n self.display()\n\n def change_velocity(self, velocity):\n self.velocity = velocity\n\nclass environment:\n def __init__(self, center, radius, angularVelocity, initialAngle):\n C = Mycircle(center, 4, black)\n size = 3\n initialPosition = center + euclid.Vector2(math.cos(initialAngle), math.sin(initialAngle))\n self.agent = Mycircle(initialPosition, size, green, width = 3)\n time = 0\n flag = True\n dtime_ms = clock.tick(60)\n timediff = dtime_ms / 10000.0\n while flag:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n flag = False\n current = AgentFunction(radius, center, initialAngle, time, angularVelocity)\n self.agent.move(current)\n time -= timediff\n pygame.display.flip()\n\n\ndef check(pos1, pos2):\n if pos1.x <= pos2.x+1 and pos1.x > pos2.x-1 and pos1.y <= pos2.y+1 and pos1.y > pos2.y-1:\n return True\n\ndef AgentFunction(radius, center, initialAngle, time, angularVelocity):\n Angle = initialAngle + angularVelocity*time\n position = center + radius * euclid.Vector2(math.cos(Angle), math.sin(Angle))\n return position\n\ndef main():\n initialize()\n env = environment(euclid.Vector2(150, 150), 100, .01 ,0)\n pygame.quit()\n\nmain()","repo_name":"vampcoder/Artificial-Life-Simulation-Lab","sub_path":"Lab 1/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":2679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"38020077297","text":"import argparse\nimport copy\nimport numpy as np\nimport os\nfrom pathlib import Path\nimport pandapower.plotting as ppl\nimport pandapower as pp\nimport pandapower.networks as pn\nimport pandapower.toolbox as tb\nimport random\nimport string\nimport subgraphs_methods\nimport time\nimport warnings\n# Suppress FutureWarning\nwarnings.filterwarnings(\"ignore\", category=FutureWarning)\n\n\ndef generate():\n arguments = get_arguments()\n x, t = create_networks(arguments)\n print(f\"{x} networks created in {t:0.2f} seconds\")\n\n\ndef get_arguments():\n parser = argparse.ArgumentParser(\n prog=\"power network subgraph generator\",\n description=\"Generates a specified number of subnetworks from a power network\",\n )\n parser.add_argument(\"network\", choices=['case4gs', 'case5', 'case6ww', 'case9', 'case14', 'case24_ieee_rts', 'case30', 'case_ieee30', 'case39', 'case57', 'case89pegase', 'case118', 'case145', 'case_illinois200', 'case300', 'case1354pegase', 'case1888rte', 'case2848rte', 'case2869pegase', 'case3120sp', 'case6470rte', 'case6495rte', 'case6515rte', 'case9241', 'GBnetwork', 'GBreducednetwork', 'iceland'])\n parser.add_argument(\"-n\", \"--num_subgraphs\", type=int, default=10)\n\n # if file is moved in another directory level relative to the root (currently in root/data_generation), this needs to be changed\n root_directory = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n parser.add_argument(\"-s\", \"--save_dir\", default=root_directory + \"/Data\") \n\n parser.add_argument(\"--min_size\", type=int, default=5)\n parser.add_argument(\"--max_size\", type=int, default=30)\n # parser.add_argument(\"--n_1\", type=bool, default=False)\n parser.add_argument(\"--subgraphing_method\", choices=['rnd_neighbor', 'bfs', 'rnd_walk', 'partitioning'], default='rnd_neighbor')\n\n args = parser.parse_args()\n print(args)\n return args\n\n\ndef get_network(network_name):\n if network_name == 'case4gs':\n network = pn.case4gs()\n elif network_name == 'case5':\n network = pn.case5()\n elif network_name == 'case6ww':\n network = pn.case6ww()\n elif network_name == 'case14':\n network = pn.case14()\n elif network_name == 'case24_ieee_rts':\n network = pn.case24_ieee_rts()\n elif network_name == 'case30':\n network = pn.case30()\n elif network_name == 'case_ieee30':\n network = pn.case_ieee30()\n elif network_name == 'case39':\n network = pn.case39()\n elif network_name == 'case57':\n network = pn.case57()\n elif network_name == 'case89pegase':\n network = pn.case89pegase()\n elif network_name == 'case118':\n network = pn.case118()\n elif network_name == 'case145':\n network = pn.case145()\n elif network_name == 'case_illinois200':\n network = pn.case_illinois200()\n elif network_name == 'case300':\n network = pn.case300()\n elif network_name == 'case1354pegase': \n network = pn.case1354pegase()\n elif network_name == 'case1888rte':\n network = pn.case1888rte()\n elif network_name == 'case2848rte':\n network = pn.case2848rte()\n elif network_name == 'case2869pegase': \n network = pn.case2869pegase()\n elif network_name == 'case3120sp':\n network = pn.case3120sp()\n elif network_name == 'case6470rte':\n network = pn.case6470rte()\n elif network_name == 'case6495rte':\n network = pn.case6495rte()\n elif network_name == 'case6515rte':\n network = pn.case6515rte()\n elif network_name == 'case9241':\n network = pn.case9241()\n elif network_name == 'GBnetwork':\n network = pn.GBnetwork()\n elif network_name == 'GBreducednetwork':\n network = pn.GBreducednetwork()\n elif network_name == 'iceland':\n network = pn.iceland()\n return network\n\n\ndef get_subgraphing_method(method_name):\n if method_name == 'rnd_neighbor':\n return subgraphs_methods.random_neighbor_selection\n elif method_name == 'bfs':\n return subgraphs_methods.bfs_neighbor_selection\n elif method_name == 'rnd_walk':\n return subgraphs_methods.random_walk_neighbor_selection\n elif method_name == 'partitioning':\n return subgraphs_methods.partition_graph\n\n\ndef create_networks(arguments):\n start = time.perf_counter()\n full_net = get_network(arguments.network)\n\n # the external grid is plotted as a yellow rectangle, buses are blue dots, loads are black triangles with tip pointing down\n # transformers are red overlapping circles, generators are black circle with a small black propeller in the middle \n # ppl.simple_plot(full_net, plot_loads=True, plot_gens=True, trafo_color=\"r\", switch_color=\"g\") \n\n subgraphing_method = get_subgraphing_method(arguments.subgraphing_method)\n n_subgraph_generated = 0\n if arguments.subgraphing_method == 'partitioning':\n all_partitions_busses = subgraphing_method(full_net)\n for partition_busses in all_partitions_busses:\n is_subgraph_solved = solve_and_save(full_net, partition_busses, arguments)\n if is_subgraph_solved:\n n_subgraph_generated += 1\n else:\n # A starting point is any bus that is connected to a generator to ensure that subgraphs contain at least one generator\n starting_points = full_net.gen.bus\n while n_subgraph_generated < arguments.num_subgraphs:\n print(f\"generating network {n_subgraph_generated + 1}\")\n # if arguments.n_1:\n # subgraph_busses = list(full_net.bus.index)\n # downed_bus = np.random.randint(0, len(subgraph_busses))\n # del subgraph_busses[downed_bus]\n \n # else:\n subgraph_length = np.random.randint(arguments.min_size, min(arguments.max_size, len(full_net.bus)))\n initial_bus = starting_points[np.random.randint(0, len(starting_points))]\n subgraph_busses = subgraphing_method(full_net, initial_bus, subgraph_length)\n \n is_subgraph_solved = solve_and_save(full_net, subgraph_busses, arguments)\n \n if is_subgraph_solved:\n n_subgraph_generated += 1\n\n end = time.perf_counter()\n return n_subgraph_generated, end - start\n\n\ndef solve_and_save(full_net, subgraph_busses, arguments):\n subgraph_net = tb.select_subnet(full_net, subgraph_busses)\n subgraph_length = len(subgraph_busses)\n\n try:\n subgraph_net = modify_network_values(subgraph_net)\n subgraph_net.sn_mva = full_net.sn_mva\n # check if the subgraph contains a slack bus, if not add one by setting the slack bus to a random bus\n # if full_net.ext_grid.bus.item() not in subgraph_busses:\n # slack_bus = subgraph_busses[np.random.randint(0, len(subgraph_busses))]\n # # https://pandapower.readthedocs.io/en/v2.1.0/elements/ext_grid.html#pandapower.create_ext_grid\n # pp.create_ext_grid(subgraph_net, slack_bus)\n pp.runpp(subgraph_net, numba = False)\n # ppl.simple_plot(subgraph_net, plot_loads=True, plot_gens=True, trafo_color=\"r\", switch_color=\"g\") \n\n except:\n print(f\"Network not solvable trying a new one\")\n return False\n\n uid = ''.join([random.choice(string.ascii_letters\n + string.digits) for _ in range(8)])\n \n Path(f\"{arguments.save_dir}/x\").mkdir(parents=True, exist_ok=True)\n Path(f\"{arguments.save_dir}/y\").mkdir(parents=True, exist_ok=True)\n \n pp.to_json(subgraph_net, f\"{arguments.save_dir}/x/{arguments.network}_{subgraph_length}_{arguments.subgraphing_method}_{uid}.json\")\n subgraph_net.res_gen.to_csv(f\"{arguments.save_dir}/y/{arguments.network}_{subgraph_length}_{arguments.subgraphing_method}_{uid}_gen.csv\")\n subgraph_net.res_line.to_csv(f\"{arguments.save_dir}/y/{arguments.network}_{subgraph_length}_{arguments.subgraphing_method}_{uid}_line.csv\")\n subgraph_net.res_bus.to_csv(f\"{arguments.save_dir}/y/{arguments.network}_{subgraph_length}_{arguments.subgraphing_method}_{uid}_bus.csv\")\n\n return True\n\n\ndef modify_network_values(netw):\n # Set leakage (shunt) values to 0\n netw.line['c_nf_per_km'] = 0.0\n netw.line['g_us_per_km'] = 0.0\n netw.shunt = netw.shunt[0:0]\n\n # Set transformer leakage values to 0\n netw.trafo['vkr_percent'] = 0.0\n netw.trafo['pfe_kw'] = 0.0\n netw.trafo['i0_percent'] = 0.0\n netw.trafo['tap_step_percent'] = 0.0\n return netw\n\n\nif __name__ == \"__main__\":\n generate()","repo_name":"AlexDeLos/GNN_OPF","sub_path":"data_generation/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":8439,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"} +{"seq_id":"22518199097","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\nfrom typing import List\n\nclass Solution:\n def evaluate(self, s: str, knowledge: List[List[str]]) -> str:\n knowledge = {k: v for k, v in knowledge}\n key = \"\"\n for ch in s:\n if ch == \"(\":\n key = \"\"\n elif ch == \")\":\n v = knowledge.get(key, \"?\")\n s = s.replace(\"({})\".format(key), v)\n key = \"\"\n elif key:\n key += ch\n return s","repo_name":"ftakanashi/JobProjects","sub_path":"LeetCode/1807.替换字符串中的括号内容/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"} +{"seq_id":"13911412360","text":"import random\n\nimport config\n\nclass Figure:\n def __init__(self, grid):\n # Выбираем рандомно фигуру и вытаскиваем её положения\n self.figurePositions = config.FIGURES[random.randint(1, len(config.FIGURES))]\n # Положение по умолчанию стоит 0\n self.figurePosition = 0\n # Выбираем данную позицию\n self.figure = self.figurePositions[self.figurePosition]\n # Устанавливаем начальные координаты фигуры\n self.figureXY = {\n 'x1': 4,\n 'y1': 0,\n 'x2': len(self.figure[0])+4,\n 'y2': len(self.figure),\n }\n\n self.grid = grid\n self.statusDecline = True\n\n\n def declineMethod(self):\n ''' Опускает фигуру, увеличивая её координаты проекции на сетку '''\n self.figureXY['y1'] += 1\n self.figureXY['y2'] += 1\n\n self.grid.print_grid(self)\n\n def insertFigureInGrid(self):\n ''' Вставляем фигуру в сетку игры '''\n\n figureRangeY = range(self.figureXY['y1'], self.figureXY['y2'])\n figureRangeX = range(self.figureXY['x1'], self.figureXY['x2'])\n\n for figureLineY, y in enumerate(figureRangeY):\n for figureLineX, x in enumerate(figureRangeX):\n if self.figure[figureLineY][figureLineX]:\n self.grid.matrix[y-1][x] = 1\n self.grid.cleanCollectedLine(y-1)\n\n def declineCheckConditions(self):\n '''\n Проверяет нижнюю линию на присутствие блоков, если они стоят - опускаем\n фигуру вниз, ставим её, и выходим из главного цикла работы с фигурой,\n если нету - меняем координаты её видимости (y1, y2).\n '''\n try:\n # Беру линию находящуюся под фигурой\n # mainline = self.grid.matrix[self.figureXY['y2']+1]\n # Перебирает значения нижней линии сетки и сравнивать со значением\n # нижней линии фигуры, если каждый из них будет равен 1 - обрывает\n # выполнение функции, и устанавливает статус опускания фигуры в False.\n for figureLineY, gridY in enumerate(range(self.figureXY['y1'], self.figureXY['y2'])):\n for figureLineX, gridX in enumerate(range(self.figureXY['x1'],self.figureXY['x2'])):\n if self.grid.matrix[gridY+1][gridX] and self.figure[figureLineY][figureLineX]:\n self.statusDecline = False\n return\n\n # Опускаем фигуру\n self.declineMethod()\n except IndexError:\n # Реагирует на начало стакана, обрывает выполнение и меняет статус\n # падения фигуры\n self.statusDecline = False\n return\n\n\n def moving(self, side):\n ''' Перемещает фигуру вправо или влево, если в той стороне нет помех '''\n\n # FigureLineY, для цикла for, который начнёт перебирать\n # значения всех линий сетки по Yn, в пределах которогых находится\n # фигура (определены в mainlines, работа через yline).\n\n mainlines = [self.grid.matrix[y] for y in range(self.figureXY['y1'], self.figureXY['y2'])]\n\n figureLineY = 0\n\n if side == 'left':\n # Индекс блока, находящегося слева от блока фигуры и его проверка\n # на случай попытки выходка за границы сетки\n xIndexChar = self.figureXY['x1'] - 1\n if xIndexChar < 0:\n return False\n\n for yline in mainlines:\n xchar = yline[xIndexChar]\n\n # Проверяем, нет ли слева блока, который может помешать.\n if xchar == 1 and self.figure[figureLineY][0] == 1:\n return False\n figureLineY += 1\n\n # Перемещение влево\n self.figureXY['x1'] -= 1\n self.figureXY['x2'] -= 1\n\n elif side == 'right':\n # Индекс блока, находящегося справа от блока фигуры и его проверка\n # на случай попытки выхода за границы сетки\n xIndexChar = self.figureXY['x2']\n if xIndexChar > config.WEIGHT_GRID-1:\n return False\n\n for yline in mainlines:\n xchar = yline[xIndexChar]\n\n # Проверяем, нет ли спрва блока, который может помешать.\n if xchar == 1 and self.figure[figureLineY][-1] == 1:\n return False\n figureLineY += 1\n\n # Перемещение вправо\n self.figureXY['x1'] += 1\n self.figureXY['x2'] += 1\n\n self.grid.print_grid(self)\n\n def coup(self):\n ''' Меняем положение фигуры '''\n\n # Инкрементируем идекс позиции\n self.figurePosition += 1\n\n # Вытаскиваем значение и устанавливаем его фигуре, если его нет, то\n # возвращаемся в позицию по умолчанию\n try:\n self.figure = self.figurePositions[self.figurePosition]\n except IndexError:\n self.figurePosition = 0\n self.figure = self.figurePositions[self.figurePosition]\n\n # Устанавливаем новые координты фигуры, т.к при изменении её размер\n # может меняться.\n self.figureXY['x2'] = len(self.figure[-1]) + self.figureXY['x1']\n self.figureXY['y2'] = len(self.figure) + self.figureXY['y1']\n\n # Сразу выводим, что бы не заставлять ждать пользователя появления\n # позиции.\n self.grid.print_grid(self)\n\n def checkLose(self):\n figureRangeY = range(self.figureXY['y1'], self.figureXY['y2'])\n figureRangeX = range(self.figureXY['x1'], self.figureXY['x2'])\n\n for yCoord in figureRangeY:\n for xCoord in figureRangeX:\n if self.grid.matrix[yCoord][xCoord] == 1:\n exit('\\nLosing!')\n","repo_name":"DUZA-dev/Tetris-in-terminal","sub_path":"figure.py","file_name":"figure.py","file_ext":"py","file_size_in_byte":7010,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"31274248698","text":"import pygame\nfrom bang import Bang\nfrom constants import BULLET_SIZE\n\npygame.init()\n# Загрузка изображений (и звуков) для вражеской пули, используя конверт_альфа для снижения нагрузки\nb_Up = pygame.image.load('Images/EnBull_up.png').convert_alpha()\nUpEnBull = pygame.transform.scale(b_Up, (BULLET_SIZE, BULLET_SIZE))\nb_Right = pygame.image.load('Images/EnBull_right.png').convert_alpha()\nRightEnBull = pygame.transform.scale(b_Right, (BULLET_SIZE, BULLET_SIZE))\nb_Left = pygame.image.load('Images/EnBull_left.png').convert_alpha()\nLeftEnBull = pygame.transform.scale(b_Left, (BULLET_SIZE, BULLET_SIZE))\nb_Down = pygame.image.load('Images/EnBull_down.png').convert_alpha()\nDownEnBull = pygame.transform.scale(b_Down, (BULLET_SIZE, BULLET_SIZE))\nbullet_explosion = pygame.mixer.Sound('Sounds/bullet_exp.mp3')\n\n\nclass EnemyBullet(pygame.sprite.Sprite):\n def __init__(self, screen, all_objects, enemy):\n super(EnemyBullet, self).__init__()\n all_objects.add(self)\n self.screen = screen\n self.screen_rect = self.screen.get_rect()\n self.type = 'EnBull'\n self.image = UpEnBull\n self.rect = self.image.get_rect()\n self.rect.centerx = enemy.rect.centerx - (BULLET_SIZE / 2)\n self.rect.centery = enemy.rect.centery - (BULLET_SIZE / 2)\n self.y = float(self.rect.centery)\n self.x = float(self.rect.centerx)\n self.sound_exp = bullet_explosion\n self.btUp = False\n self.btRight = False\n self.btLeft = False\n self.btDown = False\n\n def update(self, delta_ms, blocks, bangs, screen):\n \"\"\"Перемещение пули врагов\"\"\"\n self.speed = 350 * delta_ms / 1000 # Скорость от фпс\n\n if self.btDown: # Пуля летит вниз\n self.image = DownEnBull\n self.y += self.speed\n # Пуля летит вверх\n elif self.btUp:\n self.image = UpEnBull\n self.y -= self.speed\n # Пуля летит вправо\n elif self.btRight:\n self.image = RightEnBull\n self.x += self.speed\n # Пуля летит влево\n elif self.btLeft:\n self.image = LeftEnBull\n self.x -= self.speed\n\n for block in blocks:\n if self.rect.colliderect(block.rect):\n self.kill()\n block.kill()\n new_bang = Bang(screen, self.rect.centerx, self.rect.centery)\n bangs.add(new_bang)\n break\n\n if self.rect.bottom > self.screen_rect.bottom or \\\n self.rect.top <= self.screen_rect.top or \\\n self.rect.right > self.screen_rect.right or \\\n self.rect.left < self.screen_rect.left:\n pygame.mixer.Sound.play(self.sound_exp)\n new_bang = Bang(screen, self.rect.centerx, self.rect.centery)\n bangs.add(new_bang)\n self.kill()\n\n self.rect.y = self.y\n self.rect.x = self.x\n\n def draw(self):\n self.screen.blit(self.image, self.rect)\n","repo_name":"ZectOff/TanksProjectMUIV","sub_path":"enemy_bullet.py","file_name":"enemy_bullet.py","file_ext":"py","file_size_in_byte":3154,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"28044357565","text":"def isprime(num):\n if num == 1:\n return True\n for x in range(2, num//2 +1):\n if num % x == 0:\n return False\n return True\n\n\nwith open(\"liczby_przyklad.txt\") as nums:\n for num in nums:\n num = int(num.strip())\n if isprime(num) and num > 100 and num < 5000:\n print(num)\n\nwith open(\"pierwsze_przyklad.txt\") as primes: \n for prime in primes:\n revprime = int(str(prime.strip())[::-1])\n if isprime(revprime):\n print(str(revprime)[::-1])\n\nwith open(\"pierwsze_przyklad.txt\") as primes:\n count = 0 \n for prime in primes:\n prime = list(map(int, list(prime.strip())))\n while len(prime) != 1:\n prime = list(map(int, list(str(sum(prime)))))\n if prime == [1]:\n count += 1\n \n print(count)\n","repo_name":"jnowak123/Database","sub_path":"Matura/Wybrane liczby/rozwiazanie.py","file_name":"rozwiazanie.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"} +{"seq_id":"3409587731","text":"from sql_alchemy import banco\nfrom datetime import datetime\nfrom resources.extend_date import extend_license\n\n\nclass FoodModel(banco.Model):\n __tablename__ = 'food'\n food_id = banco.Column(banco.Integer, primary_key = True)\n user_id = banco.Column(banco.Integer, banco.ForeignKey('users.user_id')) #adicionar Relacionamento na tabela Users\n barcode = banco.Column(banco.String(13))\n name = banco.Column(banco.String(80))\n brand = banco.Column(banco.String(80))\n created_in = banco.Column(banco.String(30))\n updated_in = banco.Column(banco.String(30))\n description = banco.Column(banco.String(30))\n ingredients = banco.Column(banco.String(300))\n serving_unit = banco.Column(banco.String(10))\n serving_amount = banco.Column(banco.Float(precision = 2))\n calories = banco.Column(banco.Integer)\n carbohydrate = banco.Column(banco.Float(precision = 2))\n protein = banco.Column(banco.Float(precision = 2))\n total_fat = banco.Column(banco.Float(precision = 2))\n saturated_fat = banco.Column(banco.Float(precision = 2))\n polyunsaturated_fat = banco.Column(banco.Float(precision = 2))\n monounsaturated_fat = banco.Column(banco.Float(precision = 2))\n trans_fat = banco.Column(banco.Float(precision = 2))\n cholesterol = banco.Column(banco.Float(precision = 2))\n sodium = banco.Column(banco.Float(precision = 2))\n fiber = banco.Column(banco.Float(precision = 2))\n sugar = banco.Column(banco.Float(precision = 2))\n vitamin_a = banco.Column(banco.Float(precision = 2)) \n vitamin_b1 = banco.Column(banco.Float(precision = 2))\n vitamin_b12 = banco.Column(banco.Float(precision = 2))\n vitamin_c = banco.Column(banco.Float(precision = 2))\n vitamin_d = banco.Column(banco.Float(precision = 2))\n vitamin_e = banco.Column(banco.Float(precision = 2))\n vitamin_k = banco.Column(banco.Float(precision = 2))\n potassium = banco.Column(banco.Float(precision = 2))\n zync = banco.Column(banco.Float(precision = 2))\n magnesium = banco.Column(banco.Float(precision = 2)) \n iron = banco.Column(banco.Float(precision = 2)) \n chromium= banco.Column(banco.Float(precision = 2)) \n\n \n def __init__(self, user_id, barcode, name, brand, description,\\\n ingredients, serving_unit, serving_amount, calories, carbohydrate, protein,\\\n total_fat, saturated_fat, polyunsaturated_fat, monounsaturated_fat, trans_fat, \\\n cholesterol, sodium, fiber, sugar, vitamin_a, vitamin_b1, vitamin_b12, vitamin_c,\\\n vitamin_d, vitamin_e, vitamin_k, potassium, zync, magnesium, iron, chromium ):\n self.user_id = user_id \n self.barcode = barcode \n self.name = name \n self.brand = brand \n self.created_in = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\") \n self.updated_in = None \n self.description = description \n self.ingredients = ingredients\n self.serving_unit = serving_unit\n self.serving_amount = serving_amount \n self.calories = calories \n self.carbohydrate = carbohydrate \n self.protein = protein \n self.total_fat = total_fat \n self.saturated_fat = saturated_fat \n self.polyunsaturated_fat = polyunsaturated_fat \n self.monounsaturated_fat = monounsaturated_fat \n self.trans_fat = trans_fat\n self.cholesterol = cholesterol \n self.sodium = sodium \n self.fiber = fiber \n self.sugar = sugar \n self.vitamin_a = vitamin_a \n self.vitamin_b1 = vitamin_b1 \n self.vitamin_b12 = vitamin_b12 \n self.vitamin_c = vitamin_c \n self.vitamin_d = vitamin_d \n self.vitamin_e = vitamin_e \n self.vitamin_k = vitamin_k \n self.potassium = potassium \n self.zync = zync \n self.magnesium = magnesium \n self.iron = iron \n self.chromium = chromium \n\n \n def json(self):\n return {\n 'food_id': self.food_id,\n 'user_id': self.user_id, \n 'barcode': self.barcode, \n 'name': self.name, \n 'brand': self.brand, \n 'created_in': self.created_in, \n 'updated_in': self.updated_in, \n 'description': self.description, \n 'ingredients': self.ingredients,\n 'serving_unit': self.serving_unit,\n 'serving_amount': self.serving_amount, \n 'calories': self.calories, \n 'carbohydrate': self.carbohydrate, \n 'protein': self.protein, \n 'total_fat': self.total_fat, \n 'saturated_fat': self.saturated_fat, \n 'polyunsaturated_fat': self.polyunsaturated_fat, \n 'monounsaturated_fat': self.monounsaturated_fat, \n 'trans_fat': self.trans_fat,\n 'cholesterol': self.cholesterol, \n 'sodium': self.sodium, \n 'fiber': self.fiber, \n 'sugar': self.sugar, \n 'vitamin_a': self.vitamin_a,\n 'vitamin_b1': self.vitamin_b1, \n 'vitamin_b12': self.vitamin_b12, \n 'vitamin_c': self.vitamin_c, \n 'vitamin_d': self.vitamin_d, \n 'vitamin_e': self.vitamin_e, \n 'vitamin_k': self.vitamin_k, \n 'potassium': self.potassium, \n 'zync': self.zync, \n 'magnesium': self.magnesium, \n 'iron': self.iron, \n 'chromium': self.chromium\n }\n \n @classmethod\n def find_food(cls, food_id):\n with banco.session.no_autoflush:\n food = cls.query.filter_by(food_id = food_id).first()\n if food:\n return food\n return None\n \n @classmethod #aqui vai acontecer busca, fazer uma busca usando o %like%, que vai retornar uma lista de IDs e descrições\n def find_by_name(cls, name):\n pass\n \n @classmethod\n def find_by_barcode(cls, barcode):\n food = cls.query.filter_by(barcode = barcode).first()\n if food:\n return food\n return None\n \n def update_food(self):\n self.updated_in = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\") \n \n def save_food(self):\n banco.session.add(self)\n banco.session.commit()\n \n def delete_food(self):\n banco.session.delete(self)\n banco.session.commit()\n \n ","repo_name":"randallvictorflagg/NutrInput","sub_path":"models/food.py","file_name":"food.py","file_ext":"py","file_size_in_byte":6346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"7897729106","text":"# maaf teman2 mau tanya, cara iterasi dictionary di mana ada 5 keys dan \n# tiap key punya 2 value sedangkan yg mau ditampilin hanya tiap key dengan value pertamanya gimana ya?\n\n# buku = [\n# {\n# 'nama': ['a', 'b'],\n# 'exp': [1980,1981],\n# 'alamat': ['rumah', 'kantor'],\n# 'keterangan': ['bagus', 'sangat bagus'],\n# 'tanggal': [1,2]\n# },\n# {\n# 'nama': ['c', 'd'],\n# 'exp': [1982, 1983],\n# 'alamat': ['mall', 'indomaret'],\n# 'keterangan': ['biasa', 'sangat biasa'],\n# 'tanggal': [3, 4]\n# },\n# {\n# 'nama': ['e', 'f'],\n# 'exp': [1984, 1985],\n# 'alamat': ['masjid', 'gereja'],\n# 'keterangan': ['ok', 'sangat ok'],\n# 'tanggal': [5, 6]\n# }\n# ]\n\n# for i in range(len(buku)):\n\npeople= {\n 1: {\n 'Name': 'John',\n 'Age': 27,\n 'Sex': 'Male'\n },\n 2: {\n 'Name': 'Marie',\n 'Age': 22,\n 'Sex': 'Female'\n },\n}\n\nprint(people)","repo_name":"fatjan/code-practices","sub_path":"python/loop-dict.py","file_name":"loop-dict.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"13715098786","text":"print(\"Welcome to my Computer quiz\")\n\n# Making a Quiz Game\n\nplaying = input (\"Do you want to play ??\")\n\nif playing.lower() != \"yes\":\n quit() # quits the program\n\nprint(\"Okay! Let's Playyy\")\nscore = 0 # to track the score of the correct answers \n\n\nanswer = input(\" What does CPU stands for? \")\nif answer.lower() == \"central processing unit\": # .lower() to make the program read in lower case (program will automatically convert it into lower case)\n print(\"Correct!\") # but the one written in double code \"....\" must be in lower case\n score += 1 # score increment \nelse:\n print(\"Incorrect!\")\n\n\nanswer = input(\" What does RAM stands for? \")\nif answer.lower() == \"random access memory\":\n print(\"Correct!\")\n score += 1 # score increment \nelse:\n print(\"Incorrect!\")\n\n\nanswer = input(\" What does ROM stands for? \")\nif answer.lower() == \"read only memory\":\n print(\"Correct!\")\n score += 1 # score increment \nelse:\n print(\"Incorrect!\")\n\n\nanswer = input(\" What does GPU stands for? \")\nif answer.lower() == \"graphics processing unit\":\n print(\"Correct!\")\n score += 1 # score increment \nelse:\n print(\"Incorrect!\")\n\n\nprint (\"You got \" + str(score) + \" questions correct!\") # score stored in string to join in that sentence\nprint (\"You got \" + str((score/4)*100) + \"%\") # for percentage\n\n\n\n# end of first mini project","repo_name":"RuShakya/Py5","sub_path":"Quiz.py","file_name":"Quiz.py","file_ext":"py","file_size_in_byte":1507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"20537729700","text":"from loss import *\r\nfrom CV_params import *\r\nimport pandas as pd\r\nimport time\r\nimport scipy.stats as stats\r\nfrom sklearn.utils.fixes import loguniform\r\nfrom sklearn.model_selection import ParameterSampler\r\nfrom random import shuffle\r\n\r\nwith np.errstate(divide='ignore'):\r\n np.float64(1.0) / 0.0\r\n\r\n\r\n\r\nreal_cyc = pd.read_csv(r'D:\\thesis\\data\\real_cyc.csv', index_col='starttime')\r\narray_real_cyc = np.array(real_cyc)\r\n\r\n\r\ngroup = generate_sets(array_real_cyc, groups=5)\r\ntest_matrix, _, train_matrix = generate_matrix(data=array_real_cyc, groups=group, test_order=0)\r\n'''\r\n# MF\r\ntime1 = time.time()\r\nMF = ExplicitMF(train_matrix, test_matrix, n_factors=3, learning='sgd',\r\n item_fact_reg=0.0125, user_fact_reg=0.0808,\r\n item_bias_reg=1.9189, user_bias_reg=0.0729,\r\n process=True, verbose=True)\r\nMF.fit(n_iter=150, learning_rate=0.001)\r\npred_matrix_MF = MF.predict_all()\r\nMSE_MF = get_mse(pred_matrix_MF, test_matrix)\r\nMF.plot_learning_curve(mse=MSE_MF)\r\n\r\nprint('spend: ', time.time()-time1, '(s)')\r\nprint('MSE = ', MSE_MF)\r\n\r\n# PMF\r\ntime2 = time.time()\r\nPMF = PoissonMF(train_matrix, test_matrix, n_factors=3, learning='sgd',\r\n temp_reg=0.2350, geo_reg=0.4308,\r\n temp_bias_reg=0.0165, geo_bias_reg=0.2566,\r\n process=True, verbose=True)\r\nPMF.fit(n_iter=150, learning_rate=0.0005)\r\npred_matrix_PMF = PMF.predict_all()\r\nMSE_PMF = get_mse(pred_matrix_PMF, test_matrix)\r\nPMF.plot_learning_curve(mse=MSE_PMF)\r\n\r\nprint('spend: ', time.time()-time2, '(s)')\r\nprint('MSE = ', MSE_PMF)\r\n'''\r\n\r\n# PMF_VAR, parameters 1\r\ntime3 = time.time()\r\nPMF_VAR = PoissonMF_VAR(train_matrix, test_matrix, n_factors=3, learning='sgd',\r\n temp_reg=0.1, geo_reg=0.4136, var_reg=0.5081,\r\n temp_bias_reg=0.0488, geo_bias_reg=0.0127,\r\n process=True, verbose=True)\r\nPMF_VAR.fit(n_iter=150, learning_rate=0.0003)\r\npred_matrix_PMF_VAR = PMF_VAR.predict_all()\r\nMSE_VAR = get_mse(pred_matrix_PMF_VAR, test_matrix)\r\nPMF_VAR.plot_learning_curve(mse=MSE_VAR)\r\n\r\nprint('spend: ', time.time()-time3, '(s)')\r\nprint('MSE = ', MSE_VAR)\r\n\r\n\r\n# PMF_VAR, parameters 2\r\ntime4 = time.time()\r\nPMF_VAR2 = PoissonMF_VAR(train_matrix, test_matrix, n_factors=3, learning='sgd',\r\n temp_reg=0.1, geo_reg=0.4136, var_reg=0.5081,\r\n temp_bias_reg=0.0488, geo_bias_reg=0.0127,\r\n process=True, verbose=True)\r\nPMF_VAR2.fit(n_iter=150, learning_rate=0.0003)\r\npred_matrix_PMF_VAR2 = PMF_VAR2.predict_all()\r\nMSE_VAR2 = get_mse(pred_matrix_PMF_VAR2, test_matrix)\r\nPMF_VAR2.plot_learning_curve(mse=MSE_VAR2)\r\n\r\nprint('spend: ', time.time()-time3, '(s)')\r\nprint('MSE = ', MSE_VAR2)\r\n","repo_name":"Drsongl/Undergraduate-Thesis","sub_path":"python/comparision.py","file_name":"comparision.py","file_ext":"py","file_size_in_byte":2794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"30796316321","text":"from .base import Base\nfrom sqlalchemy import Column, BIGINT, String, BOOLEAN, TIMESTAMP, func, Index, text, INTEGER, ForeignKey\nfrom .user import User\n\nclass Shop(Base):\n __tablename__ = \"shop\"\n\n id = Column(BIGINT, autoincrement=True, primary_key=True)\n name = Column(String(50), nullable=False)\n owner_id = Column(BIGINT, ForeignKey(\"user.id\", ondelete=\"CASCADE\", name=\"shop_owner_fk\"), nullable=False) \n created_at = Column(TIMESTAMP, server_default=func.now())\n updated_at = Column(TIMESTAMP, server_default=text(\"CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP\"))\n\n __table_args__ = ()\n","repo_name":"msyamsula/SyamsulApp-alembic","sub_path":"models/shop.py","file_name":"shop.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"13539299125","text":"# https://leetcode.com/problems/minimum-fuel-cost-to-report-to-the-capital/\n\nclass Solution:\n def minimumFuelCost(self, roads: List[List[int]], target: int) -> int:\n \n g = defaultdict(list)\n for u, v in roads:\n g[u].append(v)\n g[v].append(u)\n \n result = []\n \n self.ans = 0 \n \n def helper(node, prev_node):\n count = 1\n for children in g[node]:\n if children != prev_node:\n count += helper(children, node)\n\n if node != 0:\n self.ans += math.ceil(count/target)\n\n return count\n\n helper(0, -1)\n return self.ans\n","repo_name":"Jiganesh/Loads-Of-Logic","sub_path":"graphs/minimumFuelCostToReportToTheCapital.py","file_name":"minimumFuelCostToReportToTheCapital.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","stars":189,"dataset":"github-code","pt":"76"} +{"seq_id":"20523569403","text":"'''Exercise : Biggest Exercise'''\n#Write a procedure, called biggest, which returns the key corresponding\n#to the entry with the largest number of values associated with it.\n#If there is more than one such entry, return any one of the matching keys.\n\n\ndef biggest(beings):\n '''\n aDict: A dictionary, where all the values are lists.\n\n returns: The key with the largest number of values associated with it\n '''\n # Your Code Here\n values = beings.values()\n count = 0\n for j in values:\n if len(j)>count:\n count = len(j)\n for i in beings:\n c = len(beings[i])\n if c==count:\n return i\n break\n\n\n\n\ndef main():\n '''dict'''\n number = input()\n animals = {}\n for i in range(int(number)):\n entries = input()\n list1 = entries.split()\n if list1[0][0] not in animals:\n animals[list1[0][0]] = [list1[1]]\n else:\n animals[list1[0][0]].append(list1[1])\n print(animals)\n print(biggest(animals))\n\n #animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']}\n\n #animals['d'] = ['donkey']\n #animals['d'].append('dog')\n #animals['d'].append('dingo')\n #print(animals)\n #print(biggest(animals))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ravalishnuguri/CSPP_1","sub_path":"M10/biggest Exercise/biggest_exercise.py","file_name":"biggest_exercise.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"15231774499","text":"from ac2020.days import AbstractDay\n\n\ndef _get_class(canonical_name: str):\n \"\"\"\n Gets a class by it's canonical name. Mind that this can only work with classes that does not require\n any argument during instantiation.\n\n :param canonical_name: the canonical name of the class to load dynamically, e.g. x.y.Module.Class\n\n :returns: the instance of the class.\n \"\"\"\n parts = canonical_name.split('.')\n module = \".\".join(parts[:-1])\n m = __import__( module )\n for comp in parts[1:]:\n m = getattr(m, comp)\n return type(parts[-1], (m,), {})()\n\n\ndef run(argv):\n \"\"\"\n Main logic of the program:\n\n - Requests the number of Day\n - Requests the input\n - Prints the result for Part1\n - Prints the result for Part2\n \"\"\"\n number_of_day = -1\n while number_of_day < 0:\n data = str(input('Enter # of day (1-24): '))\n if data.isdecimal():\n number_of_day = int(data)\n if number_of_day > 24:\n number_of_day = -1\n day: AbstractDay = _get_class('ac2020.days.Day' + str(number_of_day) + '.Day' + str(number_of_day))\n day.read_input()\n print()\n print('Result for Day' + str(number_of_day) + ':')\n print('Part 1: ' + day.part1())\n print('Part 2: ' + day.part2())\n\n","repo_name":"IstvanOri/adventofcode-2020","sub_path":"ac2020/runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"38206964965","text":"\"\"\"\nUmonna\n======\n\nUncertain Multi Observer Neural Network Assembler\nwith non-parametric distributions models.\n\"\"\"\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import (\n Input, Add,\n Conv2D, MaxPooling2D, Conv3D,\n Conv2DTranspose, Conv3DTranspose,\n UpSampling1D, UpSampling2D, UpSampling3D,\n AveragePooling1D, AveragePooling2D, AveragePooling3D,\n Dense, Flatten, Concatenate, Reshape,\n Activation, BatchNormalization, Dropout\n)\nfrom tensorflow.keras.regularizers import l2\nfrom . import CUSTOM_OBJECTS\nfrom .assembler import ModelAssembler\nfrom .layers import HexConvLayer, softmax\n\ndef calculate_target_shapes(deconv_blocks=5, first_deconv=(3, 3, 3)):\n target_shape = [k * 3**(deconv_blocks - 2) for k in first_deconv]\n return tuple(target_shape)\n\ndef calculate_deconv_parameters(target_shapes=(81, 81, 81), max_deconv=8, max_kernel_size=7):\n deconv_blocks = None\n for deconv_blocks_size in range(2, 1+max_deconv):\n first_deconv = [None] * len(target_shapes)\n candidates = [False] * len(target_shapes)\n for i, target_i in enumerate(target_shapes):\n #print(target_i, deconv_blocks_size)\n kernel_size_i = target_i / (3 ** (deconv_blocks_size - 2))\n #print(kernel_size_i)\n candidates[i] = kernel_size_i.is_integer() and (1 < kernel_size_i <= max_kernel_size)\n first_deconv[i] = int(kernel_size_i) \n if all(candidates):\n return deconv_blocks_size, first_deconv\n raise ValueError(\"\"\"target_shapes doesn't have a valid combination. Try a target_shapes from this expresion:\n target_shape_i = kernel_size_i * 3 ** (deconv_blocks - 2) \n With kernel_size_i > 1 and it can be different for each target, and deconv_blocks >= 2.\n \"\"\")\n\ndef deconvolution_block(front, targets, deconv_blocks, first_deconv, latent_variables):\n for deconv_i in range(deconv_blocks - 1):\n filters = 4**(deconv_blocks - deconv_i - 1)\n if len(targets) == 1:\n if deconv_i == 0:\n conv_transpose = Conv2DTranspose\n get_new_shape = lambda layer: (layer.get_shape()[2],)\n axis = [1]\n kernel_size = (1, first_deconv[0])\n strides = 1\n else:\n kernel_size = (1, 3)\n strides = (1, 3)\n elif len(targets) == 2:\n if deconv_i == 0:\n conv_transpose = Conv2DTranspose\n get_new_shape = lambda layer: (layer.get_shape()[1], layer.get_shape()[2])\n axis = [1, 2]\n kernel_size = first_deconv\n strides = 1\n else:\n kernel_size = 3\n strides = 3\n elif len(targets) == 3:\n if deconv_i == 0:\n front = Reshape((1, 1, 1, latent_variables//2))(front)\n conv_transpose = Conv3DTranspose\n get_new_shape = lambda layer: (layer.get_shape()[1], layer.get_shape()[2], layer.get_shape()[3])\n axis = [1, 2, 3]\n kernel_size = first_deconv\n strides = 1\n else:\n kernel_size = 3\n strides = 3\n front = conv_transpose(filters=filters, kernel_size=kernel_size,\n strides=strides, padding=\"valid\", output_padding=0,\n kernel_initializer='he_uniform')(front)\n front = Activation(\"relu\")(front)\n front = BatchNormalization()(front)\n front = conv_transpose(filters=1, kernel_size=1, strides=1, output_padding=0)(front)\n shape = get_new_shape(front)\n front = Reshape(shape)(front)\n output = softmax(front, axis=axis)\n return output\n\ndef upsampling_block(front, targets, deconv_blocks, first_deconv, latent_variables):\n for deconv_i in range(deconv_blocks - 1):\n filters = 4**(deconv_blocks - deconv_i - 1)\n if len(targets) == 1:\n if deconv_i == 0:\n upsampling = UpSampling2D\n average = AveragePooling2D\n conv = Conv2D\n get_new_shape = lambda layer: (layer.get_shape()[2],)\n axis = [1]\n kernel_size = (1, first_deconv[0])\n else:\n kernel_size = (1, 3)\n elif len(targets) == 2:\n if deconv_i == 0:\n upsampling = UpSampling2D\n average = AveragePooling2D\n conv = Conv2D\n get_new_shape = lambda layer: (layer.get_shape()[1], layer.get_shape()[2])\n axis = [1, 2]\n kernel_size = first_deconv\n else:\n kernel_size = 3\n elif len(targets) == 3:\n if deconv_i == 0:\n front = Reshape((1, 1, 1, latent_variables//2))(front)\n upsampling = UpSampling3D\n average = AveragePooling3D\n conv = Conv3D\n get_new_shape = lambda layer: (layer.get_shape()[1], layer.get_shape()[2], layer.get_shape()[3])\n axis = [1, 2, 3]\n kernel_size = first_deconv\n else:\n kernel_size = 3\n front = upsampling(size=kernel_size, name=f\"decoder_upsampling_layer_{deconv_i}\")(front)\n front = average(kernel_size, 1, \"same\", name=f\"decoder_average_layer_{deconv_i}\")(front)\n front = conv(filters, kernel_size, 1, \"same\", name=f\"decoder_conv_layer_{deconv_i}_a\")(front)\n front = Activation(\"relu\", name=f\"decoder_ReLU_layer_{deconv_i}_a\")(front)\n front = BatchNormalization(name=f\"decoder_batchnorm_layer_{deconv_i}_a\")(front)\n front = conv(filters, kernel_size, 1, \"same\", name=f\"decoder_conv_layer_{deconv_i}_b\")(front)\n front = Activation(\"relu\", name=f\"decoder_ReLU_layer_{deconv_i}_b\")(front)\n front = BatchNormalization(name=f\"decoder_batchnorm_layer_{deconv_i}_b\")(front)\n \n deconv_i += 1\n front = conv(filters=1, kernel_size=1, strides=1, name=f\"decoder_conv_layer_{deconv_i}\")(front)\n shape = get_new_shape(front)\n front = Reshape(shape, name=f\"decoder_reshape_layer_{deconv_i}\")(front)\n output = softmax(front, axis=axis)\n return output\n\ndef umonna_unit(telescope, image_mode, image_mask, input_img_shape, input_features_shape,\n targets, target_mode, target_shapes=None,\n conv_kernel_sizes=[5, 3, 3], latent_variables=800, dense_layer_blocks=5, deconv_blocks=None, first_deconv=None,\n activity_regularizer_l2=None):\n \"\"\"Build Umonna Unit Model\n Parameters\n ==========\n telescope\n image_mode\n image_mask\n input_img_shape\n input_features_shape\n output_mode\n output_shape\n Return\n ======\n keras.Model \n \"\"\"\n # Image Encoding Block\n ## HexConvLayer\n input_img = Input(name=\"image_input\", shape=input_img_shape)\n if image_mode in (\"simple-shift\", \"time-shift\"):\n front = HexConvLayer(filters=32, kernel_size=(3,3), name=\"encoder_hex_conv_layer\")(input_img)\n elif image_mode in (\"simple\", \"time\"):\n front = Conv2D(name=\"encoder_conv_layer_0\",\n filters=32, kernel_size=(3,3),\n kernel_initializer=\"he_uniform\",\n padding = \"valid\",\n activation=\"relu\")(input_img)\n front = MaxPooling2D(name=f\"encoder_conv_layer_0\", pool_size=(2, 2))(front)\n else:\n raise ValueError(f\"Invalid image mode {image_mode}\")\n\n ## convolutional layers\n conv_kernel_sizes = conv_kernel_sizes if conv_kernel_sizes is not None else []\n filters = 32\n conv_i = 0\n for kernel_size in conv_kernel_sizes:\n conv_i += 1\n front = Conv2D(name=f\"encoder_conv_layer_{conv_i}_a\",\n filters=filters, kernel_size=kernel_size,\n kernel_initializer=\"he_uniform\",\n padding = \"same\")(front)\n front = Activation(name=f\"encoder_ReLU_layer_{conv_i}_a\", activation=\"relu\")(front)\n front = BatchNormalization(name=f\"encoder_batchnorm_{conv_i}_a\")(front)\n \n front = Conv2D(name=f\"encoder_conv_layer_{conv_i}_b\",\n filters=filters, kernel_size=kernel_size,\n kernel_initializer=\"he_uniform\",\n padding = \"same\")(front)\n front = Activation(name=f\"encoder_ReLU_layer_{conv_i}_b\", activation=\"relu\")(front)\n front = BatchNormalization(name=f\"encoder_batchnorm_{conv_i}_b\")(front)\n front = MaxPooling2D(name=f\"encoder_maxpool_layer_{conv_i}\", pool_size=(2,2))(front)\n filters *= 2\n \n ## generate latent variables by 1x1 Convolutions\n filters = 2**(5+len(conv_kernel_sizes))\n if telescope == \"LST_LSTCam\":\n kernel_size = (3, 2)\n elif telescope == \"MST_FlashCam\":\n kernel_size = (5, 1)\n elif telescope == \"SST1M_DigiCam\":\n kernel_size = (4, 1)\n\n front = Conv2D(name=f\"encoder_conv_layer_{conv_i}\",\n filters=filters, kernel_size=kernel_size,\n kernel_initializer=\"he_uniform\",\n padding = \"valid\")(front)\n front = Activation(name=f\"encoder_ReLU_layer_{conv_i}\", activation=\"relu\")(front)\n front = BatchNormalization(name=f\"encoder_batchnorm_{conv_i}\")(front)\n front = Conv2D(name=\"encoder_conv_layer_to_latent\",\n filters=latent_variables, kernel_size=1,\n kernel_initializer=\"he_uniform\",\n padding = \"valid\",\n activation=\"relu\")(front)\n front = Flatten(name=\"encoder_flatten\")(front)\n \n l2_ = lambda activity_regularizer_l2: None if activity_regularizer_l2 is None else l2(activity_regularizer_l2)\n # Skip Connection\n # skip_front = front\n # skip_front = Dense(name=f\"logic_dense_shortcut\", units=latent_variables//2, \\\n # kernel_regularizer=l2_(activity_regularizer_l2))(skip_front)\n # skip_front = Activation(name=f\"logic_ReLU_layer_shortcut\", activation=\"relu\")(skip_front)\n # skip_front = BatchNormalization(name=f\"logic_batchnorm_shortcut\")(skip_front)\n\n # Logic Block\n ## extra Telescope Features\n input_params = Input(name=\"feature_input\", shape=input_features_shape)\n front = Concatenate()([input_params, front])\n\n ## dense blocks\n for dense_i in range(dense_layer_blocks):\n front = Dense(name=f\"logic_dense_{dense_i}\", units=latent_variables//2, \\\n kernel_regularizer=l2_(activity_regularizer_l2))(front)\n front = Activation(name=f\"logic_ReLU_layer_{dense_i}\", activation=\"relu\")(front)\n front = BatchNormalization(name=f\"logic_batchnorm_{dense_i}\")(front)\n front = Dropout(name=f\"logic_Dropout_layer_{dense_i}\", rate=0.1)(front)\n\n # Add Skip connection\n #front = Add()([front, skip_front])\n front = Reshape((1, 1, latent_variables//2), name=\"logic_reshape\")(front)\n\n # Deconvolution Blocks\n ## calculate deconvolution parameters\n if target_shapes is None:\n if deconv_blocks is None or first_deconv is None:\n raise ValueError(\"target_shape, deconv_blocks and first_deconv can be None at the same time.\")\n target_shapes = calculate_target_shapes(deconv_blocks, first_deconv)\n else:\n #print(target_shapes)\n deconv_blocks, first_deconv = calculate_deconv_parameters(target_shapes)\n\n\n ## \n front = Conv2D(name=f\"logic_dense_last\", kernel_size=1, \n filters=latent_variables//2,\n kernel_initializer=\"he_uniform\")(front)\n front = Activation(activation=\"relu\")(front)\n front = BatchNormalization()(front)\n\n if target_mode in [\"probability_map\", \"one_cell\", \"distance\", \"lineal\"]:\n output = upsampling_block(front, targets, deconv_blocks, first_deconv, latent_variables)\n else:\n raise ValueError(f\"Invalid target_mode: '{target_mode}'\" )\n\n model_name = f\"Umonna_Unit_{telescope}\"\n model = Model(name=model_name, inputs=[input_img, input_params], outputs=output)\n return model\n\nclass Umonna(ModelAssembler):\n def __init__(self, sst1m_model_or_path=None, mst_model_or_path=None, lst_model_or_path=None,\n targets=[], target_domains=tuple(), target_resolutions=tuple(), target_shapes=(),\n assembler_mode=\"normalized_product\", point_estimation_mode=\"expected_value\", custom_objects=CUSTOM_OBJECTS):\n super().__init__(sst1m_model_or_path=sst1m_model_or_path, mst_model_or_path=mst_model_or_path, lst_model_or_path=lst_model_or_path,\n targets=targets, target_domains=target_domains, target_shapes=target_shapes, custom_objects=custom_objects)\n if assembler_mode not in (None, \"normalized_product\"):\n raise ValueError(f\"Invalid assembler_mode: {assembler_mode}\")\n self.assemble_mode = assembler_mode or \"normalized_product\"\n \n if point_estimation_mode not in [\"expected_value\", \"log_expected_value\"]:\n raise ValueError(f\"Invalid point_estimation_mode: {point_estimation_mode}\")\n self.point_estimation_mode = point_estimation_mode\n self.target_resolutions = target_resolutions\n\n def model_estimation(self, x_i_telescope, telescope, verbose=0, **kwargs):\n \"\"\"\n Predict values for a batch of inputs `x_i_telescope` with the `telescope` model.\n \n Parameters\n ----------\n x_i_telescope : `np.ndarray`\n Batch of inputs with shape [(batch_size, [shift], height, width, channels), (batch_size, telescope_features)]\n telescope : `str`\n Telesope \n verbose : `int`, optional\n Log extra info. (default=0)\n kwargs : `dict`, optinal\n keras.model.predict() kwargs\n\n Returns\n -------\n Iterable of size batch_size\n A list or array with the model's predictions.\n \"\"\"\n model_telescope = self.models[telescope]\n return model_telescope.predict(x_i_telescope, verbose=verbose, **kwargs)\n\n def point_estimation(self, y_predictions):\n \"\"\"\n Predict points for a batch of predictions `y_predictions` using `self.point_estimation_mode` method.\n \n Parameters\n ----------\n y_predictions : `np.ndarray` or `list`\n Batch of predictions with len batch_size.\n\n Returns\n -------\n Iterable of size batch_size\n A list or array with the model's point predictions.\n \"\"\"\n if self.point_estimation_mode == \"expected_value\":\n y_point_estimations = self.expected_value(y_predictions)\n elif self.point_estimation_mode == \"log_expected_value\":\n y_point_estimations = self.log_expected_value(y_predictions)\n return y_point_estimations\n\n def expected_value(self, y_predictions):\n n_samples = len(y_predictions)\n dimensions = len(self.targets)\n y_point_estimations = np.empty((n_samples, dimensions))\n axis = set(np.arange(dimensions))\n if dimensions == 1:\n indexes_d = np.arange(self.target_shapes[0])\n y_point_estimations[:, 0] = np.array(\n [np.dot(y_i, indexes_d) for y_i in y_predictions]\n )\n else:\n for d in range(dimensions):\n indexes_d = np.arange(self.target_shapes[d])\n reduce_axis = tuple(axis - {d})\n y_point_estimations[:, d] = np.array(\n [np.dot(y_i.sum(axis=reduce_axis), indexes_d) for y_i in y_predictions]\n )\n # transform from index's domain to target's domain\n target_domains_arr = np.array(self.target_domains)\n target_resolutions_arr = np.array(self.target_resolutions)\n y_point_estimations = (y_point_estimations*target_resolutions_arr) + target_domains_arr[:,0]\n return y_point_estimations\n\n def log_expected_value(self, y_predictions):\n n_samples = len(y_predictions)\n dimensions = len(self.targets)\n y_point_estimations = np.empty((n_samples, dimensions))\n if dimensions == 1:\n # Transform log domain\n log_y_domain = np.arange(self.target_shapes[0])\n target_domains_arr = np.array(self.target_domains)\n target_resolutions_arr = np.array(self.target_resolutions)\n log_y_domain = (log_y_domain*target_resolutions_arr) + target_domains_arr[:,0]\n y_domain = np.power(10, log_y_domain)\n # Expected value\n y_point_estimations[:, 0] = np.log10(np.array(\n [np.dot(y_domain, prob_i) for prob_i in y_predictions]\n ))\n else:\n raise ValueError(\"Expected 1-D target. Got\", dimensions)\n return y_point_estimations\n\n def assemble(self, y_i_by_telescope, **kwargs):\n y_i_all = np.concatenate(list(y_i_by_telescope.values()))\n if self.assemble_mode == \"normalized_product\":\n #yi_assembled = self.normalized_product(y_i_all)\n #elif self.assemble_mode == \"normalized_product_with_prior\":\n yi_assembled = self.normalized_product_with_prior(y_i_all)\n return yi_assembled\n \n def normalized_product(self, y_i):\n epsilon = 1e-20\n Y_i = np.exp(np.sum(np.log(y_i+epsilon), axis=0))\n Y_i_sum = Y_i.sum()\n if Y_i_sum > 0:\n Y_i /= Y_i.sum() \n return Y_i\n\n def normalized_product_with_prior(self, y_i):\n epsilon = 1e-20\n assert y_i.shape[1:] == (81,), \"Only support log energy with shape 81\"\n y_i_prior = np.log(\n np.array([0.01234376, 0.01234376, 0.01234377, 0.01234379, 0.01234381,\n 0.01234385, 0.01234391, 0.01234398, 0.01234407, 0.01234416,\n 0.01234421, 0.01234436, 0.01234441, 0.01234456, 0.01234469,\n 0.01234482, 0.01234523, 0.01234558, 0.01234595, 0.01234629,\n 0.01234678, 0.01234694, 0.01234709, 0.01234718, 0.01234705,\n 0.0123472 , 0.01234719, 0.0123474 , 0.01234756, 0.01234756,\n 0.01234803, 0.01234822, 0.01234816, 0.01234803, 0.01234791,\n 0.01234814, 0.0123479 , 0.01234776, 0.01234773, 0.0123475 ,\n 0.01234726, 0.01234749, 0.01234749, 0.01234699, 0.01234649,\n 0.01234694, 0.0123466 , 0.01234663, 0.01234642, 0.01234612,\n 0.01234616, 0.01234595, 0.01234601, 0.01234588, 0.01234574,\n 0.01234572, 0.01234544, 0.01234555, 0.01234522, 0.01234556,\n 0.01234531, 0.01234504, 0.01234488, 0.01234482, 0.01234501,\n 0.01234471, 0.01234458, 0.01234469, 0.01234447, 0.01234457,\n 0.01234451, 0.01234465, 0.01234426, 0.01234417, 0.0123441 ,\n 0.01234405, 0.012344 , 0.01234413, 0.01234413, 0.01234396,\n 0.01234399]))\n y_i_ = np.sum(np.log(y_i+epsilon), axis=0) + y_i_prior\n Y_i = np.exp(y_i_)\n Y_i_sum = Y_i.sum()\n if Y_i_sum > 0:\n Y_i /= Y_i.sum() \n return Y_i\n","repo_name":"sborquez/gerumo","sub_path":"gerumo/models/umonna.py","file_name":"umonna.py","file_ext":"py","file_size_in_byte":19243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"22321535811","text":"#!/usr/bin/env python\n# coding=utf-8\n\nimport six\n\ndef camel_to_underline(camel_format):\n underline_format=''\n if isinstance(camel_format, str):\n for _s_ in camel_format:\n underline_format += _s_ if _s_.islower() else '_'+_s_.lower()\n return underline_format\n\ndef sort_dict_in_list(data, sort_key, reverse=False):\n return sorted(data, key=lambda k: getattr(k, sort_key), reverse=reverse)\n\nclass ApiModel(object):\n \n @classmethod\n def object_from_dictionary(cls, entry):\n if entry is None:\n return \"\"\n entry_str_dict = dict([(camel_to_underline(str(key)), value) for key, value in entry.items()])\n return cls(**entry_str_dict)\n\n def __repr__(self):\n return str(self)\n\n def __str__(self):\n if six.PY3:\n return self.__unicode__()\n else:\n return unicode(self).encode('utf-8')\n\nclass Entry(ApiModel):\n def __init__(self, *args, **kwargs):\n for key, value in six.iteritems(kwargs):\n setattr(self, key, value)\n\n def __unicode__(self):\n return \"Entry\"\n\nclass Bid(ApiModel):\n\n def __init__(self, price, qty):\n self.price = price\n self.qty = qty\n\n @classmethod\n def object_from_dictionary(cls, array):\n new_bid = Bid(array[0], array[1])\n return new_bid\n\n def __unicode__(self):\n return \"Bid: (%s, %s)\" % (self.price, self.qty)\n \nclass Ask(ApiModel):\n def __init__(self, price, qty):\n self.price = price\n self.qty = qty\n\n @classmethod\n def object_from_dictionary(cls, array):\n new_ask = Ask(array[0], array[1])\n return new_ask\n\n def __unicode__(self):\n return \"Ask: (%s, %s)\" % (self.price, self.qty)\n\nclass Depth(ApiModel):\n\n def __init__(self, last_update_id=None, bids=None, asks=None):\n self.last_update_id = last_update_id\n if bids != None: self.bids = sort_dict_in_list(bids, \"price\", reverse=True)\n if asks != None: self.asks = sort_dict_in_list(asks, \"price\")\n\n def _get_volume(self, data):\n volume = {\n \"base\": 0.0,\n \"qty\": 0.0,\n }\n\n for d in data:\n volume[\"base\"] = volume[\"base\"] + float(d.price) * float(d.qty)\n volume[\"qty\"] = volume[\"qty\"] + float(d.qty)\n\n volume[\"base\"] = round(volume[\"base\"], 8)\n volume[\"qty\"] = round(volume[\"qty\"], 8)\n return volume\n\n def get_depth_volume(self):\n volume = {}\n volume[\"bids\"] = self._get_volume(self.bids)\n volume[\"asks\"] = self._get_volume(self.asks)\n return volume\n\n def get_bids_highest_price(self):\n return self.bids[0].price\n\n def get_asks_lowest_price(self):\n return self.asks[0].price\n\n @classmethod\n def object_from_dictionary(cls, entry):\n new_depth = Depth(last_update_id=entry[\"lastUpdateId\"])\n new_depth.bids = []\n new_depth.asks = []\n \n if \"bids\" in entry:\n for bid in entry[\"bids\"]:\n new_depth.bids.append(Bid.object_from_dictionary(bid))\n new_depth.bids = sort_dict_in_list(new_depth.bids, \"price\", reverse=True)\n\n if \"asks\" in entry:\n for ask in entry[\"asks\"]:\n new_depth.asks.append(Ask.object_from_dictionary(ask))\n new_depth.asks = sort_dict_in_list(new_depth.asks, \"price\")\n\n return new_depth\n\n def __unicode__(self):\n return \"Depth: %s\" % self.last_update_id\n\nclass DepthCache(object):\n def __init__(self, depth):\n self.last_update_id = depth.last_update_id\n self.bids = {}\n self.asks = {}\n for bid in depth.bids:\n self.bids[bid.price] = bid.qty\n\n for ask in depth.asks:\n self.asks[ask.price] = ask.qty\n\n def update_bid(self, bid):\n self.bids[bid.price] = bid.qty\n if bid.qty == \"0.00000000\": \n del self.bids[bid.price]\n\n def update_ask(self, ask):\n self.asks[ask.price] = ask.qty\n if ask.qty == \"0.00000000\": \n del self.asks[ask.price]\n\n def update(self, delta):\n if delta.update_id > self.last_update_id:\n self.last_update_id = delta.update_id\n for bid in delta.bids: self.update_bid(bid)\n for ask in delta.asks: self.update_ask(ask)\n\n def __unicode__(self):\n return \"DepthCache: %s\" % self.last_update_id\n\n def __repr__(self):\n return str(self)\n\n def __str__(self):\n if six.PY3:\n return self.__unicode__()\n else:\n return unicode(self).encode('utf-8')\n\nclass Trade(ApiModel):\n def __init__(self, id=None, **kwargs):\n self.id = id\n for key, value in six.iteritems(kwargs):\n setattr(self, key, value)\n\n def __unicode__(self):\n return \"Trade: %s\" % self.id\n\nclass AggregateTrade(ApiModel):\n def __init__(self, id=None, **kwargs):\n self.id = id\n for key, value in six.iteritems(kwargs):\n setattr(self, key, value)\n\n @classmethod\n def object_from_dictionary(cls, entry):\n new_aggregate_trade = AggregateTrade(id=entry[\"a\"])\n\n new_aggregate_trade.price = entry[\"p\"]\n new_aggregate_trade.qty = entry[\"q\"]\n new_aggregate_trade.first_trade_id = entry[\"f\"]\n new_aggregate_trade.last_trade_id = entry[\"l\"]\n new_aggregate_trade.timestamp = entry[\"T\"]\n new_aggregate_trade.is_maker = entry[\"m\"]\n new_aggregate_trade.is_best_match = entry[\"M\"]\n\n return new_aggregate_trade\n\n def __unicode__(self):\n return \"AggregateTrade: %s\" % self.id\n\nclass Candlestick(ApiModel):\n def __init__(self, open_time, close_time, **kwargs):\n self.open_time = open_time\n self.close_time = close_time\n for key, value in six.iteritems(kwargs):\n setattr(self, key, value)\n\n @classmethod\n def object_from_dictionary(cls, entry):\n new_candlestick = Candlestick(open_time=entry[0], close_time=entry[6])\n \n new_candlestick.open = entry[1]\n new_candlestick.high = entry[2]\n new_candlestick.low = entry[3]\n new_candlestick.close = entry[4]\n new_candlestick.volume = entry[5]\n new_candlestick.quote_asset_volume = entry[7]\n new_candlestick.number_of_trades = entry[8]\n new_candlestick.base_asset_volume = entry[9]\n new_candlestick.quote_asset_volume = entry[10]\n\n return new_candlestick\n\n def __unicode__(self):\n return \"Candlestick: %s-%s\" % (self.open_time, self.close_time)\n\nclass Statistics(ApiModel):\n def __init__(self, first_id, last_id, **kwargs):\n self.first_id = first_id\n self.last_id = last_id\n for key, value in six.iteritems(kwargs):\n setattr(self, key, value)\n\n @classmethod\n def object_from_dictionary(cls, entry):\n new_statistics = Statistics(entry[\"firstId\"], entry[\"lastId\"])\n\n for key, value in six.iteritems(entry):\n setattr(new_statistics, camel_to_underline(str(key)), value)\n\n return new_statistics\n\n def __unicode__(self):\n return \"Statistics: %s-%s\" % (self.first_id, self.last_id)\n\nclass Price(ApiModel):\n def __init__(self, price, **kwargs):\n self.price = price\n for key, value in six.iteritems(kwargs):\n setattr(self, key, value)\n\n @classmethod\n def object_from_dictionary(cls, entry):\n new_price = Price(entry[\"price\"])\n new_price.symbol = entry[\"symbol\"]\n\n return new_price\n\n def __unicode__(self):\n return \"Price: %s(%s)\" % (self.symbol, self.price)\n\nclass Ticker(ApiModel):\n def __init__(self, symbol, **kwargs):\n self.symbol = symbol\n for key, value in six.iteritems(kwargs):\n setattr(self, key, value)\n\n @classmethod\n def object_from_dictionary(cls, entry):\n new_ticker = Ticker(entry[\"symbol\"])\n new_ticker.bid = Bid(entry[\"bidPrice\"], entry[\"bidQty\"])\n new_ticker.ask = Ask(entry[\"askPrice\"], entry[\"askQty\"])\n\n return new_ticker\n\n def __unicode__(self):\n return \"Ticker: %s\" % self.symbol\n\nclass Order(ApiModel):\n def __init__(self, id, **kwargs):\n self.id = id\n for key, value in six.iteritems(kwargs):\n setattr(self, key, value)\n \n @classmethod\n def object_from_dictionary(cls, entry):\n new_order = Order(entry[\"orderId\"])\n \n for key, value in six.iteritems(entry):\n setattr(new_order, camel_to_underline(str(key)), value)\n\n return new_order\n\n def __unicode__(self):\n return \"Order: %s\" % self.id\n\nclass Balance(ApiModel):\n def __init__(self, asset, free, locked, **kwargs):\n self.asset = asset\n self.free = free\n self.locked = locked\n for key, value in six.iteritems(kwargs):\n setattr(self, key, value)\n\n def __unicode__(self):\n return \"Balance: %s\" % self.asset\n\nclass Account(ApiModel):\n def __init__(self, *args, **kwargs):\n for key, value in six.iteritems(kwargs):\n setattr(self, key, value)\n\n def balances_dict(self):\n return dict([(balance[\"asset\"], balance) for balance in self.balances])\n\n @classmethod\n def object_from_dictionary(cls, entry):\n new_account = Account()\n \n for key, value in six.iteritems(entry):\n setattr(new_account, camel_to_underline(str(key)), value)\n\n new_account.balances = []\n new_account.balances_dict = {}\n for balance in entry[\"balances\"]:\n new_account.balances.append(Balance.object_from_dictionary(balance))\n\n return new_account\n\n def __unicode__(self):\n return \"Account\"\n\nclass Deposit(ApiModel):\n def __init__(self, *args, **kwargs):\n for key, value in six.iteritems(kwargs):\n setattr(self, key, value)\n\n @classmethod\n def object_from_dictionary(cls, entry):\n deposit_list = []\n for deposit in entry[\"depositList\"]:\n new_deposit = Deposit()\n new_deposit.insert_time = deposit[\"insertTime\"]\n new_deposit.amount = deposit[\"amount\"]\n new_deposit.asset = deposit[\"asset\"]\n new_deposit.status = deposit[\"status\"]\n deposit_list.append(new_deposit)\n return deposit_list\n\n def __unicode__(self):\n return \"Deposit\"\n\nclass Withdraw(ApiModel):\n def __init__(self, *args, **kwargs):\n for key, value in six.iteritems(kwargs):\n setattr(self, key, value)\n\n @classmethod\n def object_from_dictionary(cls, entry):\n withdraw_list = []\n for withdraw in entry[\"withdrawList\"]:\n new_withdraw = WithDraw()\n new_withdraw.amount = withdraw[\"amount\"]\n new_withdraw.address = withdraw[\"address\"]\n new_withdraw.asset = withdraw[\"asset\"]\n new_withdraw.apply_time = withdraw[\"applyTime\"]\n new_withdraw.status = withdraw[\"status\"]\n withdraw_list.append(new_withdraw)\n return withdraw_list\n\n def __unicode__(self):\n return \"Withdraw\"\n\nclass DepthUpdateEvent(ApiModel):\n EVENT_TYPE = \"depthUpdate\" \n\n def __init__(self, update_id, **kwargs):\n self.update_id = update_id\n for key, value in six.iteritems(kwargs):\n setattr(self, key, value)\n\n @classmethod\n def object_from_dictionary(cls, entry):\n new_depth_delta = DepthUpdateEvent(entry[\"u\"])\n\n new_depth_delta.event_type = entry[\"e\"]\n new_depth_delta.event_time = entry[\"E\"]\n new_depth_delta.symbol = entry[\"s\"]\n new_depth_delta.bids = []\n new_depth_delta.asks = []\n\n for bid in entry[\"b\"]:\n new_depth_delta.bids.append(Bid.object_from_dictionary(bid))\n\n for ask in entry[\"a\"]:\n new_depth_delta.asks.append(Ask.object_from_dictionary(ask))\n\n return new_depth_delta\n\n def __unicode__(self):\n return \"DepthDeltaEvent: %s\" % self.update_id\n\nclass KLineEvent(ApiModel):\n EVENT_TYPE = \"kline\" \n\n def __init__(self, start_time, end_time, **kwargs):\n self.start_time = start_time\n self.end_time = end_time\n for key, value in six.iteritems(kwargs):\n setattr(self, key, value)\n\n @classmethod\n def object_from_dictionary(cls, entry):\n new_kline = KLineEvent(entry[\"k\"][\"t\"], entry[\"k\"][\"T\"])\n\n new_kline.event_type = entry[\"e\"]\n new_kline.event_time = entry[\"E\"]\n entry = entry[\"k\"]\n new_kline.symbol = entry[\"s\"]\n new_kline.interval = entry[\"i\"]\n new_kline.first_trade_id = entry[\"f\"]\n new_kline.last_trade_id = entry[\"L\"]\n new_kline.open = entry[\"o\"]\n new_kline.close = entry[\"c\"]\n new_kline.high = entry[\"h\"]\n new_kline.low = entry[\"l\"]\n new_kline.volume = entry[\"v\"]\n new_kline.number_of_trades = entry[\"n\"]\n new_kline.is_final = entry[\"x\"]\n new_kline.quote_volume = entry[\"q\"]\n new_kline.active_buy_volume = entry[\"V\"]\n new_kline.active_buy_quote_volume = entry[\"Q\"]\n\n return new_kline\n\n def __unicode__(self):\n return \"KLineEvent: %s-%s\" % (self.start_time, self.end_time)\n\nclass AggregateTradeEvent(ApiModel):\n EVENT_TYPE = \"aggTrade\" \n\n def __init__(self, event_time, **kwargs):\n self.event_time = event_time\n for key, value in six.iteritems(kwargs):\n setattr(self, key, value)\n\n @classmethod\n def object_from_dictionary(cls, entry):\n new_aggregate_trade = AggregateTradeEvent(event_time=entry[\"E\"])\n\n new_aggregate_trade.event_type = entry[\"e\"]\n new_aggregate_trade.symbol = entry[\"s\"]\n new_aggregate_trade.price = entry[\"p\"]\n new_aggregate_trade.qty = entry[\"q\"]\n new_aggregate_trade.first_breakdown_trade_id = entry[\"f\"]\n new_aggregate_trade.last_breakdown_trade_id = entry[\"l\"]\n new_aggregate_trade.trade_time = entry[\"T\"]\n new_aggregate_trade.is_maker = entry[\"m\"]\n\n return new_aggregate_trade\n\n def __unicode__(self):\n return \"AggregateTradeEvent: %s\" % self.event_time\n\nclass OutBoundAccountInfoEvent(ApiModel):\n EVENT_TYPE = \"outboundAccountInfo\" \n\n def __init__(self, event_time, **kwargs):\n self.event_time = event_time\n for key, value in six.iteritems(kwargs):\n setattr(self, key, value)\n\n @classmethod\n def object_from_dictionary(cls, entry):\n new_event = OutBoundAccountInfoEvent(event_time=entry[\"E\"])\n\n new_event.event_type = entry[\"e\"]\n new_event.balances = []\n for balance in entry[\"B\"]:\n new_event.balances.append(Balance(balance[\"a\"], balance[\"f\"], balance[\"l\"]))\n\n return new_event\n\n def __unicode__(self):\n return \"OutBoundAccountInfoEvent: %s\" % self.event_time\n\nclass ExecutionReportEvent(ApiModel):\n EVENT_TYPE = \"executionReport\" \n\n def __init__(self, event_time, **kwargs):\n self.event_time = event_time\n for key, value in six.iteritems(kwargs):\n setattr(self, key, value)\n\n @classmethod\n def object_from_dictionary(cls, entry):\n new_event = ExecutionReportEvent(event_time=entry[\"E\"])\n\n new_event.event_type = entry[\"e\"]\n new_event.symbol = entry[\"s\"]\n new_event.new_client_order_id = entry[\"c\"]\n new_event.side = entry[\"S\"]\n new_event.order_type = entry[\"o\"]\n new_event.time_in_force = entry[\"f\"]\n new_event.original_quantity = entry[\"q\"]\n new_event.price = entry[\"p\"]\n new_event.execution_type = entry[\"x\"]\n new_event.order_status = entry[\"X\"]\n new_event.order_reject_reason = entry[\"r\"]\n new_event.order_id = entry[\"i\"]\n new_event.last_filled_trade_quantity = entry[\"l\"]\n new_event.filled_trade_accumulated_quantity = entry[\"z\"]\n new_event.last_filled_trade_price = entry[\"L\"]\n new_event.commission = entry[\"n\"]\n new_event.commission_asset = entry[\"N\"]\n new_event.order_time = entry[\"T\"]\n new_event.trade_time = entry[\"T\"]\n new_event.trade_id = entry[\"t\"]\n new_event.is_maker = entry[\"m\"]\n\n return new_event\n\n def __unicode__(self):\n return \"ExecutionReportEvent: %s\" % self.event_time \n\nclass UserDataEvent(object):\n\n @classmethod\n def object_from_dictionary(cls, entry):\n if entry[\"e\"] == OutBoundAccountInfoEvent.EVENT_TYPE:\n return OutBoundAccountInfoEvent.object_from_dictionary(entry)\n elif entry[\"e\"] == ExecutionReportEvent.EVENT_TYPE:\n return ExecutionReportEvent.object_from_dictionary(entry)\n","repo_name":"cnfuyu/python-binance-api","sub_path":"binance/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":16609,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"76"} +{"seq_id":"72862076726","text":"from django.shortcuts import redirect, render\nfrom .models import *\nfrom django.contrib import messages\nfrom django.core.mail import send_mail\n\ndef home(request):\n\n data = {\n \"services\":Services.objects.all(),\n \"members\": Member.objects.all(),\n \"testimonial\": Testimonial.objects.all(),\n \"address\": Address.objects.all()[:1]\n }\n\n\n return render(request,\"index.html\",data)\n\ndef contact(request):\n if request.method == \"POST\":\n name = request.POST.get(\"name\")\n email = request.POST.get(\"email\")\n phone = request.POST.get(\"phone\")\n subject = request.POST.get(\"subject\")\n message = request.POST.get(\"message\")\n Contact.objects.create(\n name = name,\n email = email,\n mobile_number = phone,\n subject = subject,\n message = message\n )\n\n send_mail(f\"Name - {name}, Email - {email}, Phone Number - {phone}, Subject- {subject}\",message,\"urbanspacerealtors.rkl@gmail.com\",[\"hr.rsdastudio@gmail.com\"])\n messages.success( request,\"Thank you for contacting us\")\n return redirect(\"home\")\n\n return redirect(\"home\")\n\n\n\ndef testimonialform(request):\n if request.method == \"POST\":\n name = request.POST.get(\"name\")\n prof = request.POST.get(\"prof\")\n prop_img = request.FILES.get(\"prop_img\")\n disc = request.POST.get(\"disc\")\n Testimonial.objects.create(\n name = name,\n prof = prof,\n prop_img = prop_img,\n disc = disc\n )\n messages.success(request,\"Thank you for giving your valuble feedback here\")\n return redirect(\"home\")\n return render(request,\"form.html\")\n\n","repo_name":"ishwar-jethwani/portfolio","sub_path":"core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"42573330072","text":"from random import randint\nclass Enemy():\n #constructor\n def __init__(self, health):\n self.health = health\n #return string\n def __str__(self):\n return f\"Enemy has {self.health} HP remaining.\"\n\n def turnActions(self,pos):\n damage = 0\n #roll enemy's attack\n enemyai = randint(1,10)\n #check for special conditions\n if enemyai == 1 or enemyai == 2:\n print('The enemy seems distracted...')\n return damage\n elif enemyai == 5:\n print('The enemy fires rapidly!')\n hittimes = randint(1,5)\n if pos == 'front':\n hitdamage = randint(2, 15)\n if pos == 'mid':\n hitdamage = randint(1,10)\n if pos == 'back':\n hitdamage = randint(1, 5)\n damage = hittimes * hitdamage\n print('Hit', hittimes , 'for' , hitdamage , 'each!')\n return damage\n elif enemyai == 10:\n print('The enemy rushes forward!')\n pos = 'front'\n print('Position changed to front!')\n damage = randint(2, 20)\n return damage\n #run normal attack. \n else:\n print('The enemy fires!')\n if pos == 'front':\n damage = randint(5, 30)\n if pos == 'mid':\n damage = randint(2, 20)\n if pos == 'back':\n damage = randint(1,15)\n return damage","repo_name":"jkimbl2/Shootout","sub_path":"enemy.py","file_name":"enemy.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"22463180524","text":"from pip._vendor.distlib.compat import raw_input\nimport random\n\n\ndef food_id(food):\n ''' Returns categorization of food\n\n food is a string\n returns a string of categories\n '''\n # The data\n fruits = ['apple', 'banana', 'orange']\n citrus = ['orange']\n starchy = ['banana', 'potato']\n\n # Check the category and report\n if food in fruits:\n if food in citrus:\n return 'Citrus, Fruit'\n else:\n return 'NOT Citrus, Fruit'\n else:\n if food in starchy:\n return 'Starchy, NOT Fruit'\n else:\n return 'NOT Starchy, NOT Fruit'\n\n\ndef food_id_test():\n ''' Unit test for food_id\n returns True if good, returns False and prints error if not good\n '''\n\n works = True\n if food_id('orange') != 'Citrus, Fruit':\n works = 'orange bug in food id()'\n if food_id('banana') != 'NOT Citrus, Fruit':\n works = 'banana bug in food_id()'\n if food_id('potato') != 'Starchy, NOT Fruit':\n works = 'potato bug in food_id()'\n if food_id('other') != 'NOT Starchy, NOT Fruit':\n works = 'other bug in food_id()'\n # Add tests so that all lines of code are visited during test\n\n if works == True:\n print(\"All good!\")\n return True\n else:\n print(works)\n return False\n\n\ndef f(x):\n if int(x) != x:\n print(\"n is not an integer\")\n if x % 2 != 0:\n print(\"n is odd\")\n if x % 3 != 0:\n print(\"n is even\")\n else:\n print(\"n is a multiple of 6\")\n\n\ndef guess_once():\n secret = random.randint(1, 4)\n print('I have a number between 1 and 4.')\n guess = int(raw_input('Guess: '))\n if guess != secret:\n if guess <= secret:\n print('Too low - my number is ', secret, sep='', end='!\\n')\n else:\n print('Too high - my number is ', secret, sep='', end='!\\n')\n else:\n print('Right, my number is', guess, end='!\\n')\n\ndef quiz_decimal(low, high):\n print('Type a number between', low, 'and', high, '.')\n number = float(raw_input('Number: '))\n if number >= high:\n print('No, ', number, 'is greater than', high,)\n if number <= low:\n print('No, ', number, 'is less than', low,)\n else:\n print('Yes, ', low, ' <= ', number, ' <= ', high)\n\n\n","repo_name":"Techzerobytesman/No-Step-On-Snek","sub_path":"Dillon,Alex_1_3_4A.py","file_name":"Dillon,Alex_1_3_4A.py","file_ext":"py","file_size_in_byte":2302,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"38592748767","text":"from kmk.keys import KC\nfrom peapod import Peapod\n\n\nkeyboard = Peapod()\n\nkeyboard.keymap = [\n [\n KC.Q, KC.W, KC.E, KC.R, KC.T, KC.Y, KC.U, KC.I, KC.O, KC.P,\n KC.A, KC.S, KC.D, KC.F, KC.G, KC.H, KC.J, KC.K, KC.L, KC.BSPC,\n KC.Z, KC.X, KC.C, KC.V, KC.SPC, KC.ENT, KC.B, KC.N, KC.M, KC.RSFT\n ],\n]\n\n\nif __name__ == '__main__':\n keyboard.go()\n\n","repo_name":"mateopase/peapod","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"71567561525","text":"'''\nCreated on Dec 4, 2013\n\n@author: u0490822\n'''\n\nimport numpy as np\nimport scipy.misc as misc\nfrom PIL import Image, TiffTags\n\ndef TiledTifSave():\n '''Allocate an image with dimensions larger than 2^31 and save it as a tiled tif'''\n\n # for i in range(14, 17):\n # dim = 1 << i\n # dim -= 8\n\n print(Image.PILLOW_VERSION)\n\n # xdim = 48000\n # ydim = 32769\n xdim = 1024\n ydim = 1024\n dtypestr = \"uint8\"\n dtype = np.uint8\n\n a = np.ones((xdim, ydim), dtype=dtype)\n for iRow in range(0, ydim):\n a[iRow, :] = iRow % 256\n\n outputname = '%dx%d_%s_test.tif' % (xdim, ydim, dtypestr)\n\n img = Image.fromarray(a, 'L')\n tiff_info = CreateTiledTiffInfo()\n img.save(outputname, tiffinfo=tiff_info)\n\n print(\"All done!\")\n\ndef TagNameToTagNumber():\n NameToNumber = {}\n for k, v in TiffTags.TAGS.items():\n NameToNumber[v] = k\n\n return NameToNumber\n\ndef CreateTiledTiffInfo(img=None):\n '''Create the tiff_info dictionary required to prompt Pillow to write a tiled tiff file'''\n\n Tags = TagNameToTagNumber()\n\n tiff_info = {}\n tiff_info[Tags[\"TileWidth\"]] = 256\n tiff_info[Tags[\"TileLength\"]] = 256\n\n return tiff_info\n\n\nif __name__ == '__main__':\n TiledTifSave()\n pass","repo_name":"jamesra/random","sub_path":"pillow_tif_tiles.py","file_name":"pillow_tif_tiles.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"74938272244","text":"from struct import unpack\nfrom zlib import decompress\nimport sys\nimport re\nimport hashlib\nimport bs4\nfrom dataclasses import dataclass\nfrom torch.utils.data import Dataset\nfrom transformers import PreTrainedTokenizer\nimport logging\nimport os\nimport torch\nimport pickle\nfrom typing import Optional, List, Tuple\n\nlogger = logging.getLogger(__name__)\n\n\n# Helpers for beautiful soup\ndef find_at_most_one(bs, *args, **kwargs):\n t = bs.find_all(*args, **kwargs)\n if not t:\n return t\n elif len(t) > 1:\n raise InvalidParseAssumptionError(\"Too many found!\")\n else:\n return t[0]\n\n\ndef find_exactly_one(bs, *args, **kwargs):\n t = bs.find_all(*args, **kwargs)\n if not t:\n raise InvalidParseAssumptionError(\"Not enough tags found!\")\n elif len(t) > 1:\n raise InvalidParseAssumptionError(\"Too many found!\")\n else:\n return t[0]\n\n\ndef find_at_least_one(bs, *args, **kwargs):\n t = bs.find_all(*args, **kwargs)\n if not t:\n raise InvalidParseAssumptionError(\"Not enough tags found!\")\n return t\n\n\nclass InvalidParseAssumptionError(RuntimeError):\n pass\n\n\n@dataclass\nclass Pronounciation:\n text: str\n type: str\n\n\n@dataclass\nclass Definition:\n pos_modifier: Optional[str]\n definition: str\n examples: List[str]\n topic: Optional[str]\n dates: List[str]\n\n\n@dataclass\nclass ReferenceDefinition:\n pos_modifier: Optional[str]\n reference: str\n\n\n@dataclass\nclass Sense:\n pos: Optional[str]\n definitions: List[Definition]\n\n\n@dataclass\nclass Entry:\n word: str\n variant: Optional[int]\n senses: List[Sense]\n pronounciations: List[Pronounciation]\n phrases: List[Definition]\n phrasal_verbs: List[Tuple[str, List[Definition]]]\n origin: Optional[str]\n derivatives: List[str]\n notes: List[str]\n\n\n@dataclass\nclass DictionaryDefinition:\n title: str\n entry_str: str\n parsed_entry: Optional[bs4.BeautifulSoup] = None\n\n @classmethod\n def gen_from_apple_dictionary(cls, f):\n f.seek(0x40)\n limit = 0x40 + unpack(\"i\", f.read(4))[0]\n f.seek(0x60)\n while f.tell() < limit:\n (sz,) = unpack(\"i\", f.read(4))\n buf = decompress(f.read(sz)[8:])\n for m in re.finditer(b\" 1:\n logging.warning(f\"Too many topics found: {topic_spans}, picking first one\")\n\n local_pos_modifier_span = entry_span.find(\"span\", class_=\"gg\", recursive=False)\n local_pos_modifier = local_pos_modifier_span and local_pos_modifier_span.get_text().strip()\n\n definition = definition_span.get_text().strip()\n examples = [e.get_text().strip().strip(\":\").strip() for e in example_spans]\n topic = topic_spans and topic_spans[0].get_text().strip()\n\n date_spans = definition_span(\"span\", class_=\"dg\")\n dates = [e.get_text().strip() for e in date_spans]\n\n definitions.append(\n Definition(\n pos_modifier=local_pos_modifier or global_pos_modifier,\n definition=definition,\n examples=examples,\n topic=topic,\n dates=dates,\n )\n )\n elif xrg_spans:\n for xrg in xrg_spans:\n referenced_terms = find_at_least_one(xrg, \"span\", class_=\"xr\")\n\n for referenced_term in referenced_terms:\n reference = referenced_term.get_text().strip()\n definitions.append(ReferenceDefinition(pos_modifier=global_pos_modifier, reference=reference,))\n elif entry_span.find(\"span\", class_=\"ex\"):\n logger.warning(f\"Silently ignoring example without corresponding definition {entry_span}\")\n else:\n raise InvalidParseAssumptionError(f\"Weird span: {entry_span}\")\n\n return definitions\n\n @classmethod\n def parse_sense(cls, parsed_entry):\n pos_spans = parsed_entry(\"span\", class_=\"tg_pos\")\n if len(pos_spans) > 1:\n pos = \" \".join([e.get_text().strip() for e in pos_spans])\n elif not pos_spans:\n pos_span = find_at_most_one(parsed_entry, \"span\", class_=\"posg\")\n pos = pos_span.get_text().strip() if pos_span else None\n else:\n pos = pos_spans[0].get_text().strip()\n\n if parsed_entry.findChildren(\"span\", class_=\"se2\"):\n sense_definitions = []\n for c in parsed_entry.children:\n if set(c[\"class\"]) & set((\"tg_pos\", \"posg\", \"x_xdh\")):\n continue\n elif not c.get_text().strip():\n continue\n elif \"se2\" in c[\"class\"]:\n sense_definitions.extend(cls.parse_sense_definitions(c))\n elif \"note\" in c[\"class\"]:\n logger.warning(f\"Dropping note in word sense {c}\")\n elif \"msDict\" in c[\"class\"]:\n logger.warning(f\"Dropping unexpected msDict in sense {c}\")\n else:\n raise InvalidParseAssumptionError(f\"WEIRD TAG: {c}\")\n else:\n sense_definitions = cls.parse_sense_definitions(parsed_entry)\n\n if not sense_definitions:\n raise InvalidParseAssumptionError(\"No sense definitions!\")\n return Sense(pos=pos, definitions=sense_definitions)\n\n @classmethod\n def parse_derivatives(cls, parsed_entry):\n words = find_at_least_one(parsed_entry, \"span\", class_=\"l\")\n return [e.get_text().strip() for e in words]\n\n @classmethod\n def parse_origin(cls, parsed_entry):\n etym_type = find_exactly_one(parsed_entry, \"span\", class_=\"tg_etym\", recursive=False)\n if etym_type.get_text().strip() != \"ORIGIN\":\n raise InvalidParseAssumptionError(f\"Unexpected etym type: {etym_type}\")\n\n origin_span = find_exactly_one(parsed_entry, \"span\", class_=\"x_xo1\")\n origin = origin_span.get_text().strip()\n return origin\n\n @classmethod\n def parse_phrasal_verbs(cls, parsed_entry):\n subentries = find_at_least_one(parsed_entry, \"span\", class_=\"subEntry\")\n ret = []\n for subentry in subentries:\n word_span = subentry.find(\"span\", class_=\"x_xoh\") or subentry.find(\"span\", class_=\"x_xot\")\n if subentry.find(\"span\", class_=\"msDict\"):\n definitions = cls.parse_sense_definitions(subentry)\n else:\n definitions = []\n ret.append((word_span.get_text().strip(), definitions))\n return ret\n\n @classmethod\n def parse(cls, parsed_entry):\n entry = find_exactly_one(parsed_entry, \"d:entry\")\n head_entry = find_exactly_one(entry, \"span\", class_=\"hg\")\n defn_entry = find_exactly_one(entry, \"span\", class_=\"sg\")\n\n head_word_span = find_exactly_one(head_entry, \"span\", class_=\"hw\")\n word = \" \".join([t.strip() for t in head_word_span.contents if type(t) == bs4.element.NavigableString]).strip()\n\n variant_span = find_at_most_one(head_word_span, \"span\", class_=\"tg_hw\")\n variant = int(variant_span.get_text()) if variant_span else None\n\n pronounciations = cls.parse_pronounciations(head_entry)\n\n senses = defn_entry(\"span\", class_=\"se1\")\n if len(senses) == 0:\n raise InvalidParseAssumptionError(f\"No senses found!\")\n\n senses = []\n for c in defn_entry.children:\n if \"se1\" in c[\"class\"]:\n senses.append(cls.parse_sense(c))\n elif c.get_text().strip():\n raise InvalidParseAssumptionError(f\"Weird tag found in definition: {c.prettify()}!\")\n\n phrases = []\n origin = None\n subentries = entry.find_all(\"span\", class_=\"t_derivatives\") # derivatives # TODO: verify\n derivatives = []\n phrasal_verbs = []\n notes = []\n\n for subentry in entry.children:\n if subentry == head_entry or subentry == defn_entry:\n continue\n elif \"t_phrases\" in subentry[\"class\"]:\n phrases = cls.parse_sense_definitions(subentry)\n elif \"t_derivatives\" in subentry[\"class\"]:\n derivatives = cls.parse_derivatives(subentry)\n elif \"t_phrasalVerbs\" in subentry[\"class\"]:\n phrasal_verbs = cls.parse_phrasal_verbs(subentry)\n elif \"etym\" in subentry[\"class\"]:\n origin = cls.parse_origin(subentry)\n elif \"note\" in subentry[\"class\"]:\n notes.append(subentry.get_text())\n else:\n raise InvalidParseAssumptionError(f\"Weird entry found: {subentry}\")\n\n # TODO: determine other direct children types\n return Entry(\n word=word,\n variant=variant,\n pronounciations=pronounciations,\n senses=senses,\n phrases=phrases,\n phrasal_verbs=phrasal_verbs,\n origin=origin,\n derivatives=derivatives,\n notes=notes,\n )\n\n\ndef generate_words(\n tokenizer,\n model,\n allow_proper_nouns=True,\n blacklist=(),\n prefix=\"\",\n num=100,\n batch_size=50,\n max_length=400,\n max_iterations=20,\n):\n ret = []\n num_iteration = 0\n\n input = tokenizer.encode(prefix, return_tensors=\"pt\").to(\"cuda\")\n\n while len(ret) < num and num_iteration < max_iterations:\n num_iteration += 1\n\n generated = model.generate(input, max_length=max_length, num_return_sequences=batch_size, temperature=1.0,)\n valid_i = 0\n\n for i in range(generated.size()[0]):\n sentence_tokens = generated[i, :].tolist()\n decoded = tokenizer.decode(sentence_tokens)\n m = re.search(r\"<title>(.*?)(.*)\", decoded)\n if m:\n title = m.group(1).strip()\n if not allow_proper_nouns and title[:1].upper() == title[:1]:\n continue\n elif title.upper() in blacklist or title.upper().rstrip(\"s\") in blacklist:\n continue\n else:\n ret.append(DictionaryDefinition(title=title, entry_str=m.group(2).rstrip(\"!\")))\n else:\n logger.warning(f'Unable to match regex in \"{decoded}\"')\n\n return ret\n","repo_name":"turtlesoupy/this-word-does-not-exist","sub_path":"title_maker_pro/dictionary_definition.py","file_name":"dictionary_definition.py","file_ext":"py","file_size_in_byte":13104,"program_lang":"python","lang":"en","doc_type":"code","stars":1010,"dataset":"github-code","pt":"76"} +{"seq_id":"42113280749","text":"class Solution:\n def numDecodings(self, s: str) -> int:\n if s[0] == '0':\n return 0\n # dp[i] = number of decode ways for substring of s from index 0 to index i-1.\n dp = [0]*(len(s)+1)\n dp[0] = 1\n dp[1] = 1\n \n for i in range(2, len(dp)):\n if s[i-1] != '0':\n dp[i] += dp[i-1]\n if '10'<=s[i-2:i]<='26':\n dp[i] += dp[i-2]\n return dp[-1]\n \n ","repo_name":"Hana-Workneh/A2SV-competitive-programming","sub_path":"91-decode-ways/91-decode-ways.py","file_name":"91-decode-ways.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"30098083783","text":"import ast\nimport numpy as np\nfrom pyVHR.extraction.sig_processing import *\nfrom pyVHR.extraction.sig_extraction_methods import *\nfrom pyVHR.extraction.skin_extraction_methods import *\nfrom pyVHR.BVP.BVP import *\nfrom pyVHR.BPM.BPM import *\nfrom pyVHR.BVP.methods import *\nfrom pyVHR.BVP.filters import *\n\n\nfrom pyVHR.realtime.params import Params\nimport time\n\nfrom inspect import getmembers, isfunction\n\nroi_method='convexhull'\nroi_approach='holistic' \nmethod='cupy_POS'\nbpm_type='welch' \npre_filt=False\npost_filt=True\nfps = 25\nbpm_plot = []\nbpm_save = []\nbpm_plot_max = 60\nimage = None\noriginal_image = None\nskin_image = None\npatches_image = None\nvhr_t = None\n\n\ntype_options = ['mean', 'median']\npatches_options = ['squares','rects']\nrects_dim_sim = \"[[],]\"\nskin_color_low_threshold = \"75\"\nskin_color_high_threshold = \"230\"\nsig_color_low_threshold = \"75\"\nsig_color_high_threshold = \"230\"\n\nvisualizeskintrue_sim = False\nvisualizeldmkstrue_sim = False\nvisualizepatchestrue_sim = False\nvisualizeldmksnumtrue_sim = False\nfontSize = \"0.3\" ## to correct: allways False when isnumeric()\nfontcolor = '(255, 0, 0, 255)'\ncolor_low_threshold = \"75\"\ncolor_high_threshold = \"230\"\n\n\nbpm_plot_max = 10\n \ndef apply_params():\n \n Params.fake_delay = True\n Params.cuda = cuda\n Params.fps_fixed = fps\n Params.rPPG_method = method\n Params.skin_extractor = roi_method\n Params.approach = roi_approach\n Params.type = type_options[0]\n Params.patches = patches_options[0]\n \n try:\n Params.rects_dims = ast.literal_eval(rects_dim_sim)\n # Default if len is not the same\n if len(Params.rects_dims) != len(Params.landmarks_list):\n new_rect_dim = []\n for i in range(len(Params.landmarks_list)):\n new_rect_dim.append(\n [Params.squares_dim, Params.squares_dim])\n Params.rects_dims = new_rect_dim\n except:\n # Default if parameter is wrong\n new_rect_dim = []\n for i in range(len(Params.landmarks_list)):\n new_rect_dim.append(\n [Params.squares_dim, Params.squares_dim])\n Params.rects_dims = new_rect_dim\n if skin_color_low_threshold.isnumeric():\n Params.skin_color_low_threshold = int(\n skin_color_low_threshold) if int(skin_color_low_threshold) >= 0 and int(skin_color_low_threshold) <= 255 else 2\n if skin_color_high_threshold.isnumeric():\n Params.skin_color_high_threshold = int(\n skin_color_high_threshold) if int(skin_color_high_threshold) >= 0 and int(skin_color_high_threshold) <= 255 else 254\n if sig_color_low_threshold.isnumeric():\n Params.sig_color_low_threshold = int(\n sig_color_low_threshold) if int(sig_color_low_threshold) >= 0 and int(sig_color_low_threshold) <= 255 else 2\n if sig_color_high_threshold.isnumeric():\n Params.sig_color_high_threshold = int(\n sig_color_high_threshold) if int(sig_color_high_threshold) >= 0 and int(sig_color_high_threshold) <= 255 else 254\n if color_low_threshold.isnumeric():\n Params.color_low_threshold = int(\n color_low_threshold) if int(color_low_threshold) >= 0 and int(color_low_threshold) <= 255 else -1\n if color_high_threshold.isnumeric():\n Params.color_high_threshold = int(\n color_high_threshold) if int(color_high_threshold) >= 0 and int(color_high_threshold) <= 255 else 255\n \n \n Params.visualize_skin = True if bool(\n visualizeskintrue_sim) else False\n Params.visualize_landmarks = True if bool(\n visualizeldmkstrue_sim) else False\n Params.visualize_patches = True if bool(\n visualizepatchestrue_sim) else False\n Params.visualize_landmarks_number = True if bool(\n visualizeldmksnumtrue_sim) else False\n try:\n colorfont = ast.literal_eval(fontcolor)\n if len(colorfont) == 4:\n correct = True\n for e in colorfont:\n if not(e >= 0 and e <= 255):\n correct = False\n if correct:\n Params.font_color = colorfont\n except:\n pass\n if fontSize.isnumeric():\n Params.font_size = float(\n fontSize) if float(fontSize) > 0.0 else 0.3\n \n\ndef start_predict():\n bpm_plot = []\n bpm_save = []\n image = None\n\nimport queue\nfrom pyVHR.extraction.sig_processing import *\nfrom pyVHR.extraction.sig_extraction_methods import *\nfrom pyVHR.extraction.skin_extraction_methods import *\n\ndef analisys(frame_input):\n q_bpm = queue.Queue()\n #q_video_image = queue.Queue()\n #q_skin_image = queue.Queue()\n #q_patches_image = queue.Queue()\n q_stop = queue.Queue()\n #q_stop_cap = queue.Queue()\n q_frames = queue.Queue()\n\n #bpm_list = []\n\n sig_ext_met = None\n ldmks_regions = None\n # Holistic settings #\n if Params.approach == 'holistic':\n sig_ext_met = holistic_mean\n # Patches settings #\n elif Params.approach == 'patches':\n # extraction method\n if Params.type == \"mean\" and Params.patches == \"squares\":\n sig_ext_met = landmarks_mean\n elif Params.type == \"mean\" and Params.patches == \"rects\":\n sig_ext_met = landmarks_mean_custom_rect\n elif Params.type == \"median\" and Params.patches == \"squares\":\n sig_ext_met = landmarks_median\n elif Params.type == \"median\" and Params.patches == \"rects\":\n sig_ext_met = landmarks_median_custom_rect\n # patches dims\n if Params.patches == \"squares\":\n ldmks_regions = np.float32(Params.squares_dim)\n elif Params.patches == \"rects\":\n ldmks_regions = np.float32(Params.rects_dims)\n\n SignalProcessingParams.RGB_LOW_TH = np.int32(\n Params.sig_color_low_threshold)\n SignalProcessingParams.RGB_HIGH_TH = np.int32(\n Params.sig_color_high_threshold)\n SkinProcessingParams.RGB_LOW_TH = np.int32(\n Params.skin_color_low_threshold)\n SkinProcessingParams.RGB_HIGH_TH = np.int32(\n Params.skin_color_high_threshold)\n\n color = np.array([Params.font_color[0],\n Params.font_color[1], Params.font_color[2]], dtype=np.uint8)\n\n skin_ex = None\n target_device = 'GPU' if Params.cuda else 'CPU'\n if Params.skin_extractor == 'convexhull':\n skin_ex = SkinExtractionConvexHull(target_device)\n elif Params.skin_extractor == 'faceparsing':\n skin_ex = SkinExtractionFaceParsing(target_device)\n\n mp_drawing = mp.solutions.drawing_utils\n mp_face_mesh = mp.solutions.face_mesh\n PRESENCE_THRESHOLD = 0.5\n VISIBILITY_THRESHOLD = 0.5\n \n fps = Params.fps_fixed\n tot_frames = int(Params.tot_sec*fps)\n #print(\"tot frames: \",tot_frames)\n\n sig = []\n processed_frames_count = 0\n sig_buff_dim = int(fps * Params.winSize)\n sig_stride = int(fps * Params.stride)\n sig_buff_counter = sig_stride # stride en un segundo. Relacionado a FPS\n\n BPM_obj = None\n\n timeCount = []\n\n send_images_count = 0\n send_images_stride = 3\n\n with mp_face_mesh.FaceMesh(\n max_num_faces=1,\n min_detection_confidence=0.5,\n min_tracking_confidence=0.5) as face_mesh:\n counter = 0\n while True:\n counter +=1\n #print(\"----- Iteration counter: \", counter)\n start_time = time.perf_counter()*1000\n if q_frames.empty():\n for f in range(len(frame_input)):\n q_frames.put(frame_input[f])\n\n frame = None\n\n if not q_frames.empty(): \n frame = q_frames.get()\n #frame = q_frames.queue[0]\n if type(frame) == int: \n return(-3)\n if not q_stop.empty(): \n q_stop.get()\n return(-2)\n if frame is None:\n #print(\"Frame is None.\")\n return(-1)\n\n # convert the BGR image to RGB.\n image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n processed_frames_count += 1\n #print(\"processed_frames_count: \", processed_frames_count)\n width = image.shape[1]\n height = image.shape[0]\n # [landmarks, info], with info->x_center ,y_center, r, g, b\n ldmks = np.zeros((468, 5), dtype=np.float32)\n ldmks[:, 0] = -1.0\n ldmks[:, 1] = -1.0\n magic_ldmks = []\n ### face landmarks ###\n results = face_mesh.process(image)\n if results.multi_face_landmarks:\n #print(\"Hay resultados multi face landmarks\")\n face_landmarks = results.multi_face_landmarks[0]\n landmarks = [l for l in face_landmarks.landmark]\n for idx in range(len(landmarks)):\n landmark = landmarks[idx]\n if not ((landmark.HasField('visibility') and landmark.visibility < VISIBILITY_THRESHOLD)\n or (landmark.HasField('presence') and landmark.presence < PRESENCE_THRESHOLD)):\n coords = mp_drawing._normalized_to_pixel_coordinates(\n landmark.x, landmark.y, width, height)\n if coords:\n ldmks[idx, 0] = coords[1]\n ldmks[idx, 1] = coords[0]\n ### skin extraction ###\n cropped_skin_im, full_skin_im = skin_ex.extract_skin(\n image, ldmks)\n else:\n #print(\"ATENCIÓN: no hay resultados multi face landmarks\")\n cropped_skin_im = np.zeros_like(image)\n full_skin_im = np.zeros_like(image)\n ### SIG ###\n if Params.approach == 'patches':\n magic_ldmks = np.array(\n ldmks[Params.landmarks_list], dtype=np.float32)\n temp = sig_ext_met(magic_ldmks, full_skin_im, ldmks_regions,\n np.int32(SignalProcessingParams.RGB_LOW_TH), np.int32(SignalProcessingParams.RGB_HIGH_TH))\n temp = temp[:, 2:] # keep only rgb mean\n elif Params.approach == 'holistic':\n #print(\"enter holistic\")\n temp = sig_ext_met(cropped_skin_im, np.int32(\n SignalProcessingParams.RGB_LOW_TH), np.int32(SignalProcessingParams.RGB_HIGH_TH))\n sig.append(temp)\n #print(\"sig buff dim: \", sig_buff_dim)\n if processed_frames_count > sig_buff_dim:\n #print(\"now processed_frames_count > sig_buff_dim:\")\n sig = sig[1:]\n #print(\"sig_buff_counter: \",sig_buff_counter)\n if sig_buff_counter == 0:\n sig_buff_counter = sig_stride\n copy_sig = np.array(sig, dtype=np.float32)\n copy_sig = np.swapaxes(copy_sig, 0, 1)\n copy_sig = np.swapaxes(copy_sig, 1, 2)\n ### Pre_filtering ###\n if Params.approach == 'patches':\n copy_sig = rgb_filter_th(copy_sig, **{'RGB_LOW_TH': np.int32(Params.color_low_threshold),\n 'RGB_HIGH_TH': np.int32(Params.color_high_threshold)})\n for filt in Params.pre_filter:\n #print(\"pre filt: \", filt)\n if filt != {}:\n if 'fps' in filt['params'] and filt['params']['fps'] == 'adaptive' and fps is not None:\n filt['params']['fps'] = float(fps)\n if filt['params'] == {}:\n copy_sig = filt['filter_func'](\n copy_sig)\n else:\n copy_sig = filt['filter_func'](\n copy_sig, **filt['params'])\n ### BVP ###\n bvp = np.zeros((0, 1), dtype=np.float32)\n if Params.method['device_type'] == 'cpu':\n bvp = signals_to_bvps_cpu(\n copy_sig, Params.method['method_func'], Params.method['params'])\n elif Params.method['device_type'] == 'torch':\n bvp = signals_to_bvps_torch(\n copy_sig, Params.method['method_func'], Params.method['params'])\n elif Params.method['device_type'] == 'cuda':\n bvp = signals_to_bvps_cuda(\n copy_sig, Params.method['method_func'], Params.method['params'])\n ### Post_filtering ###\n for filt in Params.pre_filter:\n #print(\"post filt: \", filt)\n if filt != {}:\n bvp = np.expand_dims(bvp, axis=1)\n if 'fps' in filt['params'] and filt['params']['fps'] == 'adaptive' and fps is not None:\n filt['params']['fps'] = float(fps)\n if filt['params'] == {}:\n bvp = filt['filter_func'](bvp)\n else:\n bvp = filt['filter_func'](\n bvp, **filt['params'])\n bvp = np.squeeze(bvp, axis=1)\n ### BPM ###\n if Params.cuda:\n bvp_device = cupy.asarray(bvp)\n if BPM_obj == None:\n BPM_obj = BPMcuda(bvp_device, fps,\n minHz=Params.minHz, maxHz=Params.maxHz)\n else:\n BPM_obj.data = bvp_device\n if Params.BPM_extraction_type == \"welch\":\n bpm = BPM_obj.BVP_to_BPM()\n bpm = cupy.asnumpy(bpm)\n elif Params.BPM_extraction_type == \"psd_clustering\":\n bpm = BPM_obj.BVP_to_BPM_PSD_clustering()\n else:\n if BPM_obj == None:\n BPM_obj = BPM(bvp, fps, minHz=Params.minHz,\n maxHz=Params.maxHz)\n else:\n BPM_obj.data = bvp\n if Params.BPM_extraction_type == \"welch\":\n bpm = BPM_obj.BVP_to_BPM()\n elif Params.BPM_extraction_type == \"psd_clustering\":\n bpm = BPM_obj.BVP_to_BPM_PSD_clustering()\n if Params.approach == 'patches': # Median of multi BPMs\n if len(bpm.shape) > 0 and bpm.shape[0] == 0:\n bpm = np.float32(0.0)\n else:\n bpm = np.float32(np.median(bpm))\n q_bpm.put(bpm)\n #print(\"processed frames: \",processed_frames_count)\n print(\"bpm: \",bpm)\n #bpm_list.append(bpm)\n return bpm\n\n else: # si signal buff counter no es 0:\n sig_buff_counter -= 1\n\n end_time = time.perf_counter()*1000\n timeCount.append(end_time-start_time)\n if len(timeCount) > 100:\n timeCount = timeCount[1:]\n ### loop break ###\n if tot_frames is not None and tot_frames > 0 and processed_frames_count >= tot_frames:\n #print(\"tot frames not None and tot frames > 0, processed_frames_count >= tot frames\")\n #return bpm_list,q_bpm\n pass\n\n","repo_name":"SebastianAraneda/HeartRate_module","sub_path":"mainBPM.py","file_name":"mainBPM.py","file_ext":"py","file_size_in_byte":15680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"1700697969","text":"\n#A simple project with the task of storing information in a .txt file. The program is a login page\n\n\nfrom tkinter import *\n\nr = Tk()\n\nr.config(background='#36454F') \n\n\n#الدوال\n\ndef save_bata() :\n\t\n\t#جلب قيم الندخلات\n\tname = E1.get()\n\tage = E2.get()\n\tphone = E3.get()\n\t\n\t#اضافة القيم الى ملف\n\tf = open(\"xx.txt\",'a')\n\n\tf.write(f'''\n--------------------------------------------------\nname : {name}\nage : {age}\nnumber phone : {phone}\n--------------------------------------------------\n''')\n\n\tf.close()\n\t\n\t#فتح نافذة جديدة\n\tKT = Tk()\n\t\n\t#تعريض النافذة\n\tKm = Label(KT,text='_______________________________________________',fg='white',bg='white',height='39')\n\tKm.pack()\n\t\n\t##زر لانتهاء البرنامج\n\tBO = Button(KT,text='Finch',bg='white',command=(KT.quit))\n\tBO.place(x=800,y=1200)\n\t\n\t#نص ترحيب\n\tLa1 = Label(KT,text='Welcom',fg='green',bg='white',font=('a',30))\n\tLa1.place(x=200,y=50)\n\t\n\n\t\n\n\n\n#المدخلات\nE1 = Entry(r , width =20,justify='center' )\nE1.place(x= 320 , y = 300)\n\nE2 = Entry(r , width =20,justify='center' )\nE2.place(x= 320 , y = 500)\n\nE3 = Entry(r , width =20,justify='center' )\nE3.place(x= 320 , y = 700)\n\n\n\n\n#النصوص\nL1 = Label(r , text = 'Enter your name',bg = '#36454F',font=('',10))\nL1.place(x= 320 , y = 200)\n\nL2 = Label(r , text = 'Enter your age',bg = '#36454F',font=('',10))\nL2.place(x= 320 , y = 400)\n\nL3 = Label(r , text = 'Enter your phone n..',bg = '#36454F',font=('',10))\nL3.place(x= 320 , y = 600)\n\n\n\n\n#الازرار\nB = Button(r, text='gain it' , width=8,command=(save_bata))\nB.place(x= 700 , y = 1000)\n\nB1 = Button(r, text='Fainsh' , width=8,command=(r.quit))\nB1.place(x= 70 , y = 1000)\n\n\n \nr.mainloop() \n","repo_name":"Hadi-lraq/Hadi-lraq","sub_path":"Tkinter.py","file_name":"Tkinter.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"ar","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"38773721213","text":"from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter\nfrom src.gat2vec import gat2vec\nfrom Evaluation.Classification import Classification\n\n\ndef main():\n parser = ArgumentParser(\"gat2vec\",\n formatter_class=ArgumentDefaultsHelpFormatter,\n conflict_handler='resolve')\n\n parser.add_argument('--data', nargs='?', required=True,\n help='Input data directory in ../data/ folder')\n\n parser.add_argument('--label', nargs='?', default=False, type=bool,\n help=' If data is labelled')\n\n parser.add_argument('--num-walks', default=10, type=int,\n help='Random walks per node')\n\n parser.add_argument('--walk-length', default=80, type=int,\n help='Random walk length')\n\n parser.add_argument('--output', default=True,\n help='save output embedding')\n\n parser.add_argument('--dimension', default=128, type=int,\n help='size of representation.')\n\n parser.add_argument('--window-size', default=5, type=int,\n help='Window size of skipgram model.')\n return parser.parse_args()\n\nif __name__ == \"__main__\":\n args = main()\n g2v = gat2vec(args.data)\n model = g2v.train_gat2vec(args.data, args.label, args.num_walks, args.walk_length, args.dimension,\n args.window_size, args.output)\n\n ''' for blogcatalog set multilabel = True'''\n c_eval = Classification(args.data, multilabel=False)\n c_eval.evaluate(model, args.label)","repo_name":"afcarl/REFLAG","sub_path":"__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"6612915112","text":"from sqlalchemy.exc import IntegrityError\n\nfrom tests.base import BaseTestCase\nfrom tests.test_models.test_user_model import create_user\n\nfrom app import db\nfrom models.deck import Deck\nfrom models.user import User\n\n\ndef create_deck(owner, **overrides):\n params = {\n \"name\": \"My Awesome Deck\",\n \"owner\": owner,\n }\n params.update(overrides)\n\n deck = Deck(**params)\n\n db.session.add(deck)\n db.session.commit()\n\n return deck\n\n\nclass TestDeckModel(BaseTestCase):\n def setUp(self):\n super(TestDeckModel, self).setUp()\n\n self.test_user = create_user()\n\n def test_raises_integrity_error_if_name_is_null(self):\n self.assertRaises(IntegrityError, create_deck, owner=self.test_user, name=None)\n\n def test_raises_error_if_owner_is_invalid(self):\n self.assertRaises(IntegrityError, create_deck, owner=User())\n\n def test_creates_deck(self):\n deck = create_deck(owner=self.test_user)\n\n deck_in_db = Deck.query.one()\n\n self.assertEqual(deck, deck_in_db)\n self.assertEqual(self.test_user, deck_in_db.owner)\n self.assertEqual([deck], self.test_user.decks)\n","repo_name":"ravipunj/flashy","sub_path":"tests/test_models/test_deck_model.py","file_name":"test_deck_model.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"28594936060","text":"\"\"\"Fix to introduce on delete cascade\n\nRevision ID: ef82c4359bb4\nRevises: 3d2d24f3da61\nCreate Date: 2020-08-28 22:14:09.294268\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'ef82c4359bb4'\ndown_revision = '3d2d24f3da61'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(\n 'data_format_files_data_type_id_fkey', 'data_format_files', type_='foreignkey'\n )\n op.create_foreign_key(\n None,\n 'data_format_files',\n 'data_types',\n ['data_type_id'],\n ['id'],\n ondelete='CASCADE',\n )\n op.drop_constraint('data_types_project_id_fkey', 'data_types', type_='foreignkey')\n op.create_foreign_key(\n None, 'data_types', 'projects', ['project_id'], ['id'], ondelete='CASCADE'\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'data_types', type_='foreignkey')\n op.create_foreign_key(\n 'data_types_project_id_fkey', 'data_types', 'projects', ['project_id'], ['id']\n )\n op.drop_constraint(None, 'data_format_files', type_='foreignkey')\n op.create_foreign_key(\n 'data_format_files_data_type_id_fkey',\n 'data_format_files',\n 'data_types',\n ['data_type_id'],\n ['id'],\n )\n # ### end Alembic commands ###\n","repo_name":"ikennaokpala/flask-restful-api-example","sub_path":"src/main/config/db/migrations/versions/ef82c4359bb4_.py","file_name":"ef82c4359bb4_.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"25268775131","text":"# Function for transformation of dataframes for hotspots by subregion\nimport requests\nimport pandas as pd\nimport time\n\nimport os\nfrom dotenv import load_dotenv\nload_dotenv()\napi_key = os.environ.get('EBIRD_API_KEY')\n\ndef fetch_hotspot_data(hotspots):\n hotspot_data_list = []\n \n for hotspot in hotspots:\n hotspots_url = 'https://api.ebird.org/v2/ref/hotspot/' + hotspot + '?fmt=json'\n try:\n response = requests.get(hotspots_url, params=api_key)\n response.raise_for_status() # Raise an exception for bad status codes\n\n hotspots_data = response.json()\n hotspots_df = pd.DataFrame(hotspots_data)\n hotspot_data_list.append(hotspots_df)\n\n time.sleep(1) # Add a 1-second delay to avoid rate limits\n except requests.exceptions.RequestException as e:\n print(f\"An error occurred for hotspot {hotspot}: {e}\")\n print(response.content)\n\n # Concatenate all DataFrames in the list into a single DataFrame\n all_hotspots_df = pd.concat(hotspot_data_list, ignore_index=True)\n\n return all_hotspots_df","repo_name":"nicole440/dryocopus-pileatus","sub_path":"get_local_hotspots.py","file_name":"get_local_hotspots.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"26895458478","text":"from django.urls import path\nfrom Firstapp import views\n\nurlpatterns=[\n #Welcome admin Page\n path('admin_welcome/',views.welcome_admin),\n\n #IT JOBS\n path('dashboard/',views.dashboard),\n path('it_show/',views.it_show),\n path('it_add/',views.it_add),\n path('it_update//',views.it_update),\n path('it_delete//',views.it_delete),\n\n #MECHANICAL JOBS\n path('mech_show/',views.mech_show),\n path('mech_add/',views.mech_add),\n path('mech_update//',views.mech_update),\n path('mech_delete//',views.mech_delete),\n\n #CIVIL JOBS\n path('civil_show/',views.civil_show),\n path('civil_add/',views.civil_add),\n path('civil_update//',views.civil_update),\n path('civil_delete//',views.civil_delete),\n\n #show resume\n path('show_resume//',views.showresume),\n path('mech_show_resume//',views.mech_showresume),\n path('civil_show_resume//',views.civil_showresume)\n\n\n\n]","repo_name":"Ruchika-Munde/Django_Task","sub_path":"Dashboard/dashboard/Firstapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"7107331589","text":"import hashlib\nfrom datetime import datetime\n\nfrom fastapi.encoders import jsonable_encoder\nfrom sqlalchemy.orm import Session\n\nfrom app.crud.base import CRUDBase\nfrom app.models.msg import Msg\nfrom app.schemas.msg import MsgCreate, MsgUpdate\n\n\nclass CRUDMsg(CRUDBase[Msg, MsgCreate, MsgUpdate]):\n def create(\n self, db: Session, *, obj_in: MsgCreate, interaction_id: str\n ) -> Msg:\n obj_in_data = jsonable_encoder(obj_in)\n db_obj = self.model(**obj_in_data, interaction_id=interaction_id)\n db_obj.created_at = datetime.now()\n db_obj.updated_at = datetime.now()\n db_obj.id = hashlib.sha256(\n (\n f\"{db_obj.id}{db_obj.content}{db_obj.role}\"\n + f\"{db_obj.interaction_id}\"\n + f\"{db_obj.created_at.strftime('%Y-%m-%d %H:%M:%S')}\"\n + f\"{db_obj.updated_at.strftime('%Y-%m-%d %H:%M:%S')}\"\n ).encode()\n ).hexdigest()\n db.add(db_obj)\n db.commit()\n db.refresh(db_obj)\n return db_obj\n\n def get_multi(\n self,\n db: Session,\n *,\n interaction_id: int,\n skip: int = 0,\n limit: int = 100,\n ) -> list[Msg]:\n return (\n db.query(self.model)\n .filter(Msg.interaction_id == interaction_id)\n .offset(skip)\n .limit(limit)\n .all()\n )\n\n\nmsg = CRUDMsg(Msg)\n","repo_name":"smb-h/mock-ai-chat","sub_path":"backend/app/app/crud/crud_msg.py","file_name":"crud_msg.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"32349796768","text":"import cv2 as cv\nimport numpy as np\nimport torch\nimport os\n\n\ndef distinguish_image(path, high_path, low_path, threshold):\n \"\"\"\n distinguish image by mean pixel value\n :param path: initial images path,type=string\n :param high_path: the path you store the high illumination image,type=string\n :param low_path: the path you store the low illumination image,type=string\n :param threshold: the threshold between low&high illumination image,type=int|float\n :return: None\n \"\"\"\n # path = \"C:/Users/comin/Desktop/highlightdata256/\"\n imgs = os.listdir(path) # images name list under path\n num_low, num_high = 0, 0\n for i in imgs:\n img = cv.imread(path + str(i))\n tensor_cv = torch.from_numpy(img)\n if tensor_cv.float().mean() >= threshold:\n cv.imwrite(high_path + str(i), img)\n num_high += 1\n else:\n cv.imwrite(low_path + str(i), img)\n num_low += 1\n\n print('low illumination numbers:%d,high illumination numbers:%d' % (num_low, num_high))\n\n\n# example\ninit_path = \"C:/Users/comin/Desktop/highlightdata256/\"\nt_high_path = \"C:/Users/comin/Desktop/high/\"\nt_low_paht = \"C:/Users/comin/Desktop/low/\"\nt_threshold = 40\ndistinguish_image(init_path, t_high_path, t_low_paht, t_threshold)\n","repo_name":"BingGoX/LightPollutionRemovalReasrch","sub_path":"src/tools/DistinguishImg.py","file_name":"DistinguishImg.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"76"} +{"seq_id":"24878980677","text":"import os\n\nimport pygame\nimport time\nimport random as r\nimport patterns\n\nfrom random import randrange, randint, uniform\nfrom pygame import display, draw\nfrom datetime import datetime\n\npatterns.init_patterns()\n\nscreen_size = (600, 600)\ngame = pygame.init()\nscreen = display.set_mode(screen_size)\nclock = pygame.time.Clock()\n\nwidth = 2.5\nheight = width\n\ndraw_chance = 10\ndraw_index = 0 # len(patterns.pattern_list) - 1\ndraw_modifier = 1\nFPS = 0\n\nin_game = True\ndraw_delay = False\nrandomize_color = False\nforce_random_color = False\nclear_screen = False\nrequire_left_mouse_held = True\nleft_mouse_held = False\nupdate_bg_color = False\nreset_bg_color = False\nmouse_visible = True\n\ncolor = (255, 0, 0)\nbg_color = (0, 0, 0)\nmouse_pos = (0, 0)\n# mouse_c = (-10, -10)\n\ntext_to_render = [\n {\n \"name\": \"draw_mod\",\n \"font\": pygame.font.SysFont(name='Times New Roman', size=15),\n \"clear_h\": 15,\n \"clear_w\": 125,\n \"color\": (0, 255, 0),\n \"draw_pos\": (screen_size[0] // 2 - 50, 10),\n \"text\": \"Draw multiplier: {0}\"\n }\n]\n\n\ndef draw_rect(x, y, width=1, height=1, color=(255, 0, 0)):\n draw.rect(screen, color, [x, y, width, height])\n\n\ndef random_color():\n return (randint(0, 255), randint(0, 255), randint(0, 255))\n\n\ndef apply_draw_mod():\n if draw_modifier <= 0:\n return 1\n return draw_modifier\n\n\ndef l_shift_pressed():\n return pygame.key.get_mods() & pygame.KMOD_LSHIFT\n\n\ndef l_ctrl_pressed():\n return pygame.key.get_mods() & pygame.KMOD_LCTRL\n\n\nif __name__ == '__main__':\n\n # game loop\n while in_game:\n if left_mouse_held and mouse_visible or not left_mouse_held and not mouse_visible:\n pygame.mouse.set_visible(False if mouse_visible else True)\n mouse_visible = not mouse_visible\n\n # Event handling\n for e in pygame.event.get():\n if e.type == pygame.QUIT:\n in_game = False\n\n # name press event handling\n if e.type == pygame.KEYDOWN:\n if e.key == pygame.K_ESCAPE:\n in_game = False\n elif e.key == pygame.K_r:\n reset_bg_color = True\n elif e.key == pygame.K_n:\n draw_index = draw_index + 1 if draw_index < len(patterns.pattern_list) - 1 else 0\n elif e.key == pygame.K_SPACE:\n color = random_color()\n elif e.key == pygame.K_c:\n force_random_color = not force_random_color\n elif e.key == pygame.K_x:\n color = random_color()\n elif e.key == pygame.K_f:\n update_bg_color = True\n elif e.key == pygame.K_MINUS and draw_modifier != 0:\n draw_modifier -= 1\n elif e.key == pygame.K_EQUALS:\n draw_modifier += 1\n elif e.key == pygame.K_LEFTBRACKET:\n if l_shift_pressed() and l_ctrl_pressed():\n draw_modifier -= 20\n elif l_shift_pressed():\n draw_modifier -= 10\n else:\n draw_modifier -= 5\n if draw_modifier < 0: draw_modifier = 0\n elif e.key == pygame.K_RIGHTBRACKET:\n if l_shift_pressed() and l_ctrl_pressed():\n draw_modifier += 20\n elif l_shift_pressed():\n draw_modifier += 10\n else:\n draw_modifier += 5\n\n if e.type == pygame.MOUSEMOTION:\n mouse_pos = e.pos\n\n if e.type == pygame.MOUSEBUTTONDOWN or e.type == pygame.MOUSEBUTTONUP and e.button == 1:\n left_mouse_held = not left_mouse_held\n\n # Randomize Color\n if force_random_color:\n color = random_color()\n\n # Rendering shapes\n if require_left_mouse_held and left_mouse_held or not require_left_mouse_held:\n p = patterns.get_pattern_at(draw_index)\n s = p.size if draw_modifier != 0 else (1, 1)\n s = s[0] * apply_draw_mod(), s[1] * apply_draw_mod()\n\n for point in p.points:\n draw_rect(mouse_pos[0] + point[0], mouse_pos[1] + point[1], s[0],\n s[1], color=color)\n\n # Rendering text\n for f in text_to_render:\n draw_color = f['color']\n render_text = f['text']\n fill_x, fill_y = f['draw_pos'][0], f['draw_pos'][1] + 3\n\n if 'random' in draw_color: draw_color = random_color()\n if 'multiplier' in render_text.lower():\n render_text = render_text.format(draw_modifier)\n\n label = f['font'].render(render_text, 1, draw_color)\n draw_rect(fill_x, fill_y, len(render_text) * 7, f['clear_h'], color=bg_color)\n screen.blit(label, f['draw_pos'])\n\n # Updating display\n if update_bg_color:\n update_bg_color = False\n clear_screen = True\n bg_color = random_color()\n\n if reset_bg_color:\n reset_bg_color = False\n clear_screen = True\n bg_color = (0, 0, 0)\n\n if clear_screen:\n screen.fill(bg_color)\n clear_screen = False\n\n if draw_delay and randint(1, draw_chance) == draw_chance:\n pygame.display.update()\n else:\n display.update()\n\n FPS = int(clock.get_fps())\n display.set_caption(f'FPS: {FPS}')\n clock.tick(60_0000)\n","repo_name":"sharkbound/Python-Projects","sub_path":"pygameapps/pygame_sketch/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5556,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"76"} +{"seq_id":"42368559129","text":"import discord as d\nfrom discord.ext import commands\nfrom bot.constants import EMOJI_SUCCESS, EMOJI_WARNING, PRIMARY_COLOR\n\n\nclass Duelist(commands.Cog):\n def __init__(self, bot) -> None:\n self.bot = bot\n\n @commands.slash_command()\n @d.guild_only()\n async def duelist_create_role(self, ctx: d.ApplicationContext):\n \"\"\"Creates duelist role if it does not alreay exist\n\n Handled Cases:\n - Does not have permission to manage roles\n - Role already exists\n \"\"\"\n embed = d.Embed(color=PRIMARY_COLOR)\n if not ctx.user.guild_permissions.manage_roles: # type: ignore\n embed.description = f\"{EMOJI_WARNING} You don't have the permission to manage roles. Please contact with the admin\"\n await ctx.respond(embed=embed, ephemeral=True)\n return\n for role in ctx.guild.roles: # type: ignore\n if role.name == \"duelist\":\n embed.description = f\"{EMOJI_WARNING} {role.mention} already exists\"\n await ctx.respond(embed=embed, ephemeral=True)\n return\n role = await ctx.guild.create_role(name=\"duelist\") # type: ignore\n embed.description = f\"{EMOJI_SUCCESS} Created {role.mention} role\"\n await ctx.respond(embed=embed, ephemeral=True)\n\n @commands.slash_command()\n @d.guild_only()\n async def duelist_get_role(self, ctx: d.ApplicationContext):\n \"\"\"Get notified for open duels\n\n Handled Cases:\n - Already have duelist role\n - Role does not exist in guild\n \"\"\"\n embed = d.Embed(color=PRIMARY_COLOR)\n for role in ctx.user.roles: # type: ignore\n if role.name == \"duelist\":\n embed.description = (\n f\"{EMOJI_WARNING} You already have {role.mention} role\"\n )\n await ctx.respond(embed=embed, ephemeral=True)\n return\n for role in ctx.guild.roles: # type: ignore\n if role.name == \"duelist\":\n await ctx.user.add_roles(role) # type: ignore\n embed.description = f\"{EMOJI_SUCCESS} Added {role.mention} role\"\n await ctx.respond(embed=embed, ephemeral=True)\n return\n embed.description = f\"{EMOJI_WARNING} This server does not have `duelist` role. Please use /duelist_create_role to create the role\"\n await ctx.respond(embed=embed, ephemeral=True)\n\n @commands.slash_command()\n @d.guild_only()\n async def duelist_remove_role(self, ctx: d.ApplicationContext):\n \"\"\"Remove duelist role from user\n\n Handled Cases:\n - Role does not exist in guild\n - User does not have duelist role\n \"\"\"\n embed = d.Embed(color=PRIMARY_COLOR)\n for role in ctx.guild.roles: # type: ignore\n if role.name == \"duelist\":\n for user_role in ctx.user.roles: # type: ignore\n if user_role.name == \"duelist\":\n await ctx.user.remove_roles(user_role) # type: ignore\n embed.description = (\n f\"{EMOJI_SUCCESS} Removed {role.mention} role\"\n )\n await ctx.respond(embed=embed, ephemeral=True)\n return\n embed.description = (\n f\"{EMOJI_WARNING} You don't have {role.mention} role\"\n )\n await ctx.respond(embed=embed, ephemeral=True)\n return\n embed.description = f\"{EMOJI_WARNING} This server does not have `duelist` role. Please use /duelist_create_role to create the role\"\n await ctx.respond(embed=embed, ephemeral=True)\n\n\ndef setup(bot):\n bot.add_cog(Duelist(bot))\n","repo_name":"roundspecs/khelile-ayyun","sub_path":"bot/cogs/duelist.py","file_name":"duelist.py","file_ext":"py","file_size_in_byte":3756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"76"} +{"seq_id":"5301214484","text":"class Solution:\n def build(self, arr, tree, s, e, node):\n if s == e:\n tree[node] = arr[s]\n return\n\n mid = (s + e) // 2\n self.build(arr, tree, s, mid, 2 * node + 1)\n self.build(arr, tree, mid + 1, e, 2 * node + 2)\n tree[node] = tree[2 * node + 1] + tree[2 * node + 2]\n\n def update(self, arr, tree, s, e, node, idx, val):\n if s == e:\n A[idx] = val\n tree[node] = arr[idx]\n return\n\n mid = (s + e) // 2\n\n if idx > mid:\n self.update(arr, tree, mid + 1, e, 2 * node + 2, idx, val)\n else:\n self.update(arr, tree, s, mid, 2 * node + 1, idx, val)\n\n tree[node] = tree[2 * node + 1] + tree[2 * node + 2]\n\n def query(self, arr, tree, s, e, node, l, h):\n if s > h or e < l:\n return 0\n\n if s >= l and e <= h:\n return tree[node]\n\n mid = (s + e) // 2\n ans1 = self.query(arr, tree, s, mid, 2 * node + 1, l, h)\n ans2 = self.query(arr, tree, mid + 1, e, 2 * node + 2, l, h)\n return ans1 + ans2\n\n def solve(self, A):\n n = len(A)\n tree = [0 for _ in range(4 * n)]\n self.build(A, tree, 0, n - 1, 0)\n return tree\n\n\nif __name__ == '__main__':\n A = [2, 3, 1, 7, 6, -1, 3]\n B = Solution()\n print(B.solve(A))\n","repo_name":"srajsonu/100DaysOfCode","sub_path":"Segment Tree/Segment Tree/1. Segment Tree.py","file_name":"1. Segment Tree.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"4235702863","text":"\"\"\"\nImplement a stack API using only a heap.\n\n(memo) most recently := largest\n\"\"\"\n\n\nclass Stack:\n def __init__(self):\n self.key = Heap()\n self.idx = 0\n self.stack = []\n\n def push(self, item):\n \"\"\"\n adds an element to the stack.\n :param item:\n \"\"\"\n self.key.push(self.idx)\n self.stack.append(item)\n self.idx += 1\n\n def pop(self):\n \"\"\"\n removes and returns the most recently added element.\n \"\"\"\n if not self.key or not self.stack:\n raise TypeError('nothing on the stack')\n\n value = self.stack[self.key.pop()]\n self.stack.remove(value)\n self.idx -= 1\n\n return value\n\n\nclass Heap:\n def __init__(self):\n self.heap = []\n\n def push(self, item):\n \"\"\"\n adds a new key to the heap.\n\n :param item:\n \"\"\"\n self.heap.append(item)\n\n def pop(self):\n \"\"\"\n removes and returns the max value of the heap.\n \"\"\"\n value = max(self.heap)\n self.heap.remove(value)\n return value\n\n\n# Test\n# heap = Heap()\n# heap.push(3)\n# heap.push(7)\n# heap.push(5)\n# rst = heap.pop()\n# print(rst)\n\nstack = Stack()\nstack.push(2)\nstack.push(1)\nrst01 = stack.pop()\nprint(rst01)\nstack.push(3)\nstack.push(4)\nrst02 = stack.pop()\nprint(rst02)\nprint(stack.stack)\n","repo_name":"b1ueskydragon/PythonGround","sub_path":"dailyOne/P154/stack_with_heap.py","file_name":"stack_with_heap.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"1791119634","text":"import logging\n\nimport gobject\nimport hippo\nimport gconf\n\nfrom sugar.graphics import style\nfrom sugar.graphics.icon import CanvasIcon\nfrom sugar.graphics.xocolor import XoColor\n\nfrom jarabe.view.buddymenu import BuddyMenu\nfrom jarabe.model.buddy import get_owner_instance\nfrom jarabe.model import friends\nfrom jarabe.desktop.friendview import FriendView\nfrom jarabe.desktop.spreadlayout import SpreadLayout\n\n\nclass GroupBox(hippo.Canvas):\n __gtype_name__ = 'SugarGroupBox'\n\n def __init__(self):\n logging.debug('STARTUP: Loading the group view')\n\n gobject.GObject.__init__(self)\n\n self._box = hippo.CanvasBox()\n self._box.props.background_color = style.COLOR_WHITE.get_int()\n self.set_root(self._box)\n\n self._friends = {}\n\n self._layout = SpreadLayout()\n self._box.set_layout(self._layout)\n\n client = gconf.client_get_default()\n color = XoColor(client.get_string('/desktop/sugar/user/color'))\n\n self._owner_icon = CanvasIcon(icon_name='computer-xo', cache=True,\n xo_color=color)\n self._owner_icon.props.size = style.LARGE_ICON_SIZE\n\n self._owner_icon.set_palette(BuddyMenu(get_owner_instance()))\n self._layout.add(self._owner_icon)\n\n friends_model = friends.get_model()\n\n for friend in friends_model:\n self.add_friend(friend)\n\n friends_model.connect('friend-added', self._friend_added_cb)\n friends_model.connect('friend-removed', self._friend_removed_cb)\n\n def add_friend(self, buddy_info):\n icon = FriendView(buddy_info)\n self._layout.add(icon)\n\n self._friends[buddy_info.get_key()] = icon\n\n def _friend_added_cb(self, data_model, buddy_info):\n self.add_friend(buddy_info)\n\n def _friend_removed_cb(self, data_model, key):\n icon = self._friends[key]\n self._layout.remove(icon)\n del self._friends[key]\n icon.destroy()\n\n def do_size_allocate(self, allocation):\n width = allocation.width\n height = allocation.height\n\n min_w_, icon_width = self._owner_icon.get_width_request()\n min_h_, icon_height = self._owner_icon.get_height_request(icon_width)\n x = (width - icon_width) / 2\n y = (height - icon_height) / 2\n self._layout.move(self._owner_icon, x, y)\n\n hippo.Canvas.do_size_allocate(self, allocation)\n","repo_name":"nemesiscodex/JukyOS-sugar","sub_path":"src/jarabe/desktop/groupbox.py","file_name":"groupbox.py","file_ext":"py","file_size_in_byte":2402,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"30950211225","text":"# Assignment 1\nprint('---------- Assignment 1 ----------')\n\n## Part 1: Write Excel\nimport pandas as pd\n\nstudent_score = pd.DataFrame({ # Define the value and colume name in the DataFrame\n 'Student': ['Student A', 'Student B', 'Student C', 'Student D', 'Student E'],\n 'Reading': [80, 88, 92, 81, 75],\n 'Listening': [75, 86, 85, 88, 80],\n 'Speaking': [88, 90, 92, 80, 78],\n 'Writing': [80, 95, 98, 82, 80] \n})\n\nfile_name = 'StudentScore_sheet.xlsx' # Define the file name of Excel\n\nstudent_score.to_excel(file_name, index = False) # Write DataFrame to Excel file\n\n## Part 2: Read Excel\ndf = pd.read_excel('StudentScore_sheet.xlsx') # Read Excel\nsection = ['Reading', 'Listening', 'Speaking', 'Writing'] # Column names\nweight = [0.2, 0.25, 0.3, 0.25] # The weights of different section of the score\n\nfor i in range(len(df)): # 計算每一位學生的分數\n score = 0 # 初始化 score 的值\n for j in range(len(section)): # 計算每一個 section * 比重後的分數\n score += df.iloc[i][section[j]] * weight[j]\n print(f'student: {df.iloc[i][\"Student\"]}, score: {score}') # print 出該位學生的名字和分數\n\n\n# Assignment 2\nprint('---------- Assignment 2 ----------')\n\ndef division(x, y):\n\n try:\n if type(y) != int: # TypeError 的情境是 y 不等於整數\n raise TypeError('y should be integer') # 定義要顯示的文字\n else:\n print(x / y) # 無錯誤的情況時,做除法運算\n except ZeroDivisionError as e:\n print(f\"{type(e).__name__}('y cannot be 0')\") # Throw ZeroDivisionError\n except TypeError as e:\n print(repr(e)) # Throw TypeError\n finally:\n print('---Finish---') # 無論結果為何最終顯示 \"---Finish---\"\n\ndivision(100, 10) # Should print 10.0 and \"---Finish---\"\ndivision(100, 0) # Should Throw ZeroDivisionError, print \"y cannot be 0\" and \"---Finish---\"\ndivision(100, \"a\") # Should Throw TypeError, print \"y should be integer\" and \"---Finish---\"\ndivision(100, 0.5) # Should Throw TypeError, print \"y should be integer\" and \"---Finish---\"\n\n\n# Assignment 3\nprint('---------- Assignment 3 ----------')\ndef running_sum(nums):\n\n for i in range(1, len(nums)): # 除了 index = 0 不變之外,其餘的值都需要重新計算\n nums[i] += nums[i - 1] # 從 index = 1 開始,新的 list 中的值會變成 (前一個 index 新的值) + (自己原本的值)\n\n return nums # 全部的 index 都改寫完之後即可 return\n\nprint(running_sum([1, 2, 3, 4])) # Should be [1, 3, 6, 10] because [1, 1+2, 1+2+3, 1+2+3+4]\nprint(running_sum([1, 1, 1, 1, 1])) # Should be [1, 2, 3, 4, 5]\nprint(running_sum([3, 1, 2, 10, 1])) # Should be [3, 4, 6, 16, 17]","repo_name":"tsaitzu01/AutomationTest_Assignment","sub_path":"week_2_part_1.py","file_name":"week_2_part_1.py","file_ext":"py","file_size_in_byte":3044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"20366559554","text":"import requests\nimport json\nimport sys\nfrom bs4 import BeautifulSoup\nfrom casos import casos_positivos, casos_fallecidos\n\n\npoblacion_total = 33028673\n\n#!total_positivos: esto me obtiene una tupla de filas y columnas, por eso lo convierto en un array\ntotal_positivos = list(casos_positivos.shape)[0]\n#!total_positivos_hombres\ntotal_positivos_hombres = list(casos_positivos[casos_positivos['SEXO'] == \"MASCULINO\"].shape)[0]\n\n#!total_positivos_mujeres\ntotal_positivos_mujeres = list(casos_positivos[casos_positivos['SEXO'] == \"FEMENINO\"].shape)[0]\n\n\n#!total_fallecidos:\ntotal_fallecidos = list(casos_fallecidos.shape)[0]\n\n#!total_fallecidos_hombre:\ntotal_fallecidos_hombres = list(\n casos_fallecidos[casos_fallecidos['SEXO'] == \"MASCULINO\"].shape)[0]\n\n#!total_fallecidos_mujeres:\ntotal_fallecidos_mujeres = list(\n casos_fallecidos[casos_fallecidos['SEXO'] == \"FEMENINO\"].shape)[0]\n\n\n\n#!total_poblacion:\n# total_poblacion = poblacion_total[poblacion_total['Unnamed: 1'] == \"PERU\"].iloc[0,2]\ntotal_poblacion = poblacion_total\n#!positivos departamento loreto\npositivos_loreto = list(casos_positivos[casos_positivos['DEPARTAMENTO'] == \"LORETO\"].shape)[0]\n\n#!positivos departamento amazonas\npositivos_amazonas = list(\n casos_positivos[casos_positivos['DEPARTAMENTO'] == \"AMAZONAS\"].shape)[0]\n\n\n#!positivos departamento tumbes\npositivos_tumbes = list(\n casos_positivos[casos_positivos['DEPARTAMENTO'] == \"TUMBES\"].shape)[0]\n\n\n#!positivos departamento piura\npositivos_piura = list(\n casos_positivos[casos_positivos['DEPARTAMENTO'] == \"PIURA\"].shape)[0]\n\n\n#!positivos departamento lambayeque\npositivos_lambayeque = list(\n casos_positivos[casos_positivos['DEPARTAMENTO'] == \"LAMBAYEQUE\"].shape)[0]\n\n\n#!positivos departamento Cajamarca\npositivos_cajamarca = list(\n casos_positivos[casos_positivos['DEPARTAMENTO'] == \"CAJAMARCA\"].shape)[0]\n\n\n\n#!positivos departamento La Libertad\npositivos_libertad = list(\n casos_positivos[casos_positivos['DEPARTAMENTO'] == \"LA LIBERTAD\"].shape)[0]\n\n\n#!positivos departamento ancash\npositivos_ancash = list(\n casos_positivos[casos_positivos['DEPARTAMENTO'] == \"ANCASH\"].shape)[0]\n\n#!positivos departamento san martin\npositivos_sanmartin = list(\n casos_positivos[casos_positivos['DEPARTAMENTO'] == \"SAN MARTIN\"].shape)[0]\n\n\n\n#!positivos departamento huanuco\npositivos_huanuco = list(\n casos_positivos[casos_positivos['DEPARTAMENTO'] == \"HUANUCO\"].shape)[0]\n\n\n\n#!positivos departamento ucayali\npositivos_ucayali = list(\n casos_positivos[casos_positivos['DEPARTAMENTO'] == \"UCAYALI\"].shape)[0]\n\n\n\n#!positivos departamento pasco\npositivos_pasco = list(\n casos_positivos[casos_positivos['DEPARTAMENTO'] == \"PASCO\"].shape)[0]\n\n\n\n#!positivos departamento lima\npositivos_lima = list(\n casos_positivos[(casos_positivos['DEPARTAMENTO'] == \"LIMA\") | (casos_positivos['DEPARTAMENTO'] == \"LIMA REGION\")].shape)[0]\n\n\n#!positivos departamento junin\npositivos_junin = list(\n casos_positivos[casos_positivos['DEPARTAMENTO'] == \"JUNIN\"].shape)[0]\n\n\n\n#!positivos departamento huancavelica\npositivos_huancavelica = list(\n casos_positivos[casos_positivos['DEPARTAMENTO'] == \"HUANCAVELICA\"].shape)[0]\n\n\n\n#!positivos departamento ica\npositivos_ica = list(\n casos_positivos[casos_positivos['DEPARTAMENTO'] == \"ICA\"].shape)[0]\n\n\n#!positivos departamento ayacucho\npositivos_ayacucho = list(\n casos_positivos[casos_positivos['DEPARTAMENTO'] == \"AYACUCHO\"].shape)[0]\n\n#!positivos departamento apurimac\npositivos_apurimac = list(\n casos_positivos[casos_positivos['DEPARTAMENTO'] == \"APURIMAC\"].shape)[0]\n\n\n#!positivos departamento cusco\npositivos_cusco = list(\n casos_positivos[casos_positivos['DEPARTAMENTO'] == \"CUSCO\"].shape)[0]\n\n#!positivos departamento madre de dios\npositivos_madrededios = list(\n casos_positivos[casos_positivos['DEPARTAMENTO'] == \"MADRE DE DIOS\"].shape)[0]\n\n\n#!positivos departamento puno\npositivos_puno = list(\n casos_positivos[casos_positivos['DEPARTAMENTO'] == \"PUNO\"].shape)[0]\n\n#!positivos departamento arequipa\npositivos_arequipa = list(\n casos_positivos[casos_positivos['DEPARTAMENTO'] == \"AREQUIPA\"].shape)[0]\n\n\n#!positivos departamento moquegua\npositivos_moquegua = list(\n casos_positivos[casos_positivos['DEPARTAMENTO'] == \"MOQUEGUA\"].shape)[0]\n\n\n#!positivos departamento tacna\npositivos_tacna = list(\n casos_positivos[casos_positivos['DEPARTAMENTO'] == \"TACNA\"].shape)[0]\n\n#!positivos departamento callao\n\npositivos_callao = list(\n casos_positivos[casos_positivos['DEPARTAMENTO'] == \"CALLAO\"].shape)[0]\n\n#!Fallecidos por etapa de vida\n#!0 a 5 años (Primera infancia o Bebes o Infancia Temprana)\nfallecidos_preinfancia = list(casos_fallecidos[(casos_fallecidos['EDAD_DECLARADA'] >= 0) & (\n casos_fallecidos['EDAD_DECLARADA'] <= 5)].shape)[0]\n\n#!6 a 11 años (Infancia o Niños o Niñez)\nfallecidos_infancia = list(casos_fallecidos[(casos_fallecidos['EDAD_DECLARADA'] >= 6) & (\n casos_fallecidos['EDAD_DECLARADA'] <= 11)].shape)[0]\n\n#!12 a 18 años (Adolescencia o Adolescentes)\nfallecidos_adolescencia = list(casos_fallecidos[(casos_fallecidos['EDAD_DECLARADA'] >= 12) & (\n casos_fallecidos['EDAD_DECLARADA'] <= 18)].shape)[0]\n\n#!19 a 26 años (Juventud o Jóvenes)\nfallecidos_juventud = list(casos_fallecidos[(casos_fallecidos['EDAD_DECLARADA'] >= 19) & (\n casos_fallecidos['EDAD_DECLARADA'] <= 26)].shape)[0]\n\n#!27 a 59 años (Adultez o Adultos)\nfallecidos_adultez = list(casos_fallecidos[(casos_fallecidos['EDAD_DECLARADA'] >= 27) & (\n casos_fallecidos['EDAD_DECLARADA'] <= 59)].shape)[0]\n\n#!60 a mas (Persona Mayor o Ancianos)\nfallecidos_persona_mayor = list(\n casos_fallecidos[(casos_fallecidos['EDAD_DECLARADA'] >= 60)].shape)[0]\n\ncasos_generales = {\n \"name\": \"peru\",\n \"poblacion\": total_poblacion,\n \"positivos\": total_positivos,\n \"hombres_infectados\": total_positivos_hombres,\n \"mujeres_infectados\": total_positivos_mujeres,\n \"fallecidos\": total_fallecidos,\n \"hombres_fallecidos\": total_fallecidos_hombres,\n \"mujeres_fallecidos\": total_fallecidos_mujeres,\n \"etapa_de_vida_fallecidos\": {\n \"primera_infancia\": fallecidos_preinfancia,\n \"infancia\": fallecidos_infancia,\n \"adolescencia\": fallecidos_adolescencia,\n \"juventud\": fallecidos_juventud,\n \"adultez\": fallecidos_adultez,\n \"persona_mayor\": fallecidos_persona_mayor\n },\n \"mapa_hijos\": [\n positivos_amazonas,\n positivos_ancash,\n positivos_apurimac,\n positivos_arequipa,\n positivos_ayacucho,\n positivos_cajamarca,\n positivos_callao, \n positivos_cusco,\n positivos_huancavelica,\n positivos_huanuco,\n positivos_ica,\n positivos_junin,\n positivos_libertad,\n positivos_lambayeque,\n positivos_lima,\n positivos_loreto,\n positivos_madrededios,\n positivos_moquegua,\n positivos_pasco,\n positivos_piura,\n positivos_puno,\n positivos_sanmartin,\n positivos_tacna,\n positivos_tumbes,\n positivos_ucayali\n ]\n}\n\nprint(json.dumps(casos_generales));\nsys.stdout.flush();\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"vqc1909a/COVID19Peru-Backend","sub_path":"python/peru.py","file_name":"peru.py","file_ext":"py","file_size_in_byte":7102,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"42998906900","text":"import flask\nfrom flask import abort, render_template\nimport sys\n\nsys.path.insert(0, \"/var/www/flask/error_as_a_service\")\napp = flask.Flask(__name__)\nfrom error_as_a_service import app as application\n\n\n@app.route('/')\ndef hello_world():\n return render_template('index.html')\n\n@app.route('/')\ndef error_page(error_code):\n abort(int(error_code))\n\n\nif __name__ == '__main__':\n app.run(debug=False)\n\n","repo_name":"jeremiah1066/error_as_a_service","sub_path":"error_as_a_service.py","file_name":"error_as_a_service.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"34096615455","text":"def predict_smart_contract_word():\n # List of common four-letter words used in smart contracts\n four_letter_words = ['CODE','NODE', 'DEMO', 'DONE', 'DEAL', 'DEMO', 'DOOR', 'DEBT', 'DEEP', 'EDGE', 'FEND', 'HERO', 'HOLD', 'HOME', 'IDOL', 'JUDO', 'KIND', 'LIED', 'MODE', 'POEM', 'REDO', 'SEND', 'VEND', 'YOND', 'ZEDS']\n\n # Set of letters to ignore\n ignore_letters = {'A', 'T', 'R', 'L', 'N', 'S', 'F', 'I', 'M'}\n\n # Initialize an empty list to store potential matches\n potential_matches = []\n\n # Iterate through each word in the list\n for word in four_letter_words:\n # Check if the word contains the letters D, E, and O\n if 'D' in word and 'E' in word and 'O' in word:\n # Check if the word contains any of the ignored letters\n if not any(letter in ignore_letters for letter in word):\n potential_matches.append(word)\n\n return potential_matches\n\n# Call the function and print the result\nresult = predict_smart_contract_word()\nprint(result)\n","repo_name":"MaxwellNdegwa/Smart-contract-word-prediction","sub_path":"smart_contract_word_prediction.py","file_name":"smart_contract_word_prediction.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"29444696298","text":"# -*- coding: utf-8 -*-\n###############################################################################\n# License, author and contributors information in: #\n# __manifest__.py file at the root folder of this module. #\n###############################################################################\n\nimport json\nimport logging\nimport requests\nimport werkzeug\nfrom werkzeug import urls\n\nfrom odoo import http, fields\nfrom odoo.http import request\nfrom odoo.service import common\n\n_logger = logging.getLogger(__name__)\n\nversion_info = common.exp_version()\nserver_serie = version_info.get('server_serie')\n\n\nclass SSLCommerzController(http.Controller):\n _success_url = '/payment/sslcommerz/success/'\n _fail_url = '/payment/sslcommerz/fail/'\n _cancel_url = '/payment/sslcommerz/cancel/'\n _ipn_url = '/payment/sslcommerz/ipn/'\n\n def _get_return_url(self, **post):\n \"\"\" Extract the return URL from the data coming from sslcommerz. \"\"\"\n return_url = post.pop('return_url', '')\n\n if not return_url:\n return_url = '/shop/payment/validate'\n\n return return_url\n\n # Newly added\n @http.route([\n '/payment/sslcommerz/return/',\n '/payment/sslcommerz/cancel/',\n ], type='http', auth='public', csrf=False)\n def sslcommerz_form_feedback(self, **post):\n if post:\n request.env['payment.transaction'].sudo(\n ).form_feedback(post, 'sslcommerz')\n base_url = request.env['ir.config_parameter'].sudo(\n ).get_param('web.base.url')\n return request.render('bose_ssl_commerz.payment_sslcommerz_redirect', {\n 'return_url': urls.url_join(base_url, \"/payment/process\")\n })\n\n def sslcommerz_validate_data(self, **post):\n \"\"\"\n SSLCOMMERZ Receive Payment Notification (IPN): Validate Payment with IPN\n\n As IPN URL already set in panel. All the payment notification will reach through IPN prior to user return back. So it needs validation for amount and transaction properly.\n\n The IPN will send a POST REQUEST with below parameters. Grab the post notification with your desired platform ( PHP: $_POST)\n Once data is validated, process it.\n\n Doc: 'https://developer.sslcommerz.com/doc/v4/'\n \"\"\"\n _logger.info(\n '**************** sslcommerz_validate_data *******************')\n res = False\n model_name = post.get('value_a') \n rec_id = post.get('value_b') \n reference = post.get('value_c') \n val_id = post.get('val_id')\n tx = None\n\n if reference:\n domain = [('reference', 'like', reference)]\n if model_name == 'sale.order':\n domain = [('sale_order_ids', '=', int(rec_id))]\n\n tx = request.env['payment.transaction'].sudo().search(\n domain, order='id desc', limit=1)\n\n if 'payment.transaction' in post.get('value_d'):\n tx_id = post.get('value_d').split(\"&\")[0].replace(\"payment.transaction(\",\"\").replace(\")\", \"\").replace(\",\",\"\")\n domain = [('id', '=', int(tx_id))]\n tx = request.env['payment.transaction'].sudo().search(\n domain, order='id desc', limit=1)\n\n if not tx:\n # we have seemingly received a notification for a payment that did not come from\n # odoo, acknowledge it otherwise sslcommerz will keep trying\n _logger.warning(\n 'received notification for unknown payment reference')\n return False\n\n sslcommerz_urls = request.env['payment.acquirer']._get_sslcommerz_urls(\n tx and tx.acquirer_id and tx.acquirer_id.state or 'prod')\n validate_url = sslcommerz_urls['sslcommerz_validation_url']\n acquirer_id = request.env['payment.acquirer'].search(\n [('provider', '=', 'sslcommerz')])\n store_id = acquirer_id.sslcommerz_store_id\n store_passwd = acquirer_id.sslcommerz_store_passwd\n new_post = dict(store_id=store_id,\n store_passwd=store_passwd, \n val_id=val_id)\n urequest_json = self._sslcommerz_validate_url(validate_url, new_post)\n _logger.info(\"\\nValidation Response:\\n\" + str(urequest_json))\n\n res = ''\n txn_key = post.get(\"val_id\")\n \n print(\"IPN Status: \" + str(post.get('status')))\n print(\"Order Validation Status: \" + str(urequest_json.get('status')))\n\n\n if post.get('status') == \"VALID\" and (urequest_json.get(\"status\") == 'VALID' or urequest_json.get(\"status\") == 'VALIDATED'):\n res = \"status=approved&transactionKey={}\".format(txn_key)\n\n date_validate = fields.datetime.now()\n if post.get(\"date_stamp\"):\n date_validate = post.get('date_stamp', fields.datetime.now())\n\n if tx:\n session = {}\n tx_data = tx.get_tx_values({}, post)\n tx_data.update({\n \"state\": \"done\",\n \"acquirer_reference\": post.get(\"val_id\"),\n \"type\": \"validation\",\n \"date\": date_validate,\n })\n tx.sudo().write(tx_data)\n tx._post_process_after_done()\n\n if tx.sale_order_ids:\n print(\"tx.sale_order_ids\")\n if float(tx.sale_order_ids[0].amount_total) == float(post.get('currency_amount')):\n if tx.sale_order_ids[0].state != 'sale':\n tx.sale_order_ids[0].sudo().action_confirm()\n res += \"&transaction_id=%s&sale_order_id=%s\" %(tx.id, tx.sale_order_ids[0].id)\n\n if tx.invoice_ids:\n print(\" tx.invoice_ids\")\n if float(tx.invoice_ids[0].amount_total) == float(post.get('currency_amount')):\n self.invoice_reg_payment(tx, post)\n value_id = post.get(\"value_d\")\n if len(value_id.split(\"&\")) > 1:\n session = value_id.split(\"&\")[1].replace(\"session=\",\"\").replace(\"'\",'\"')\n try:\n session = json.loads(session)\n except Exception as e:\n session = json.dumps(session)\n session = json.loads(session)\n new_session = dict(request.session).copy()\n if session:\n if request.session.get('uid') == None:\n request.session['uid'] = session.get('uid')\n if request.session.get('login') == None:\n request.session['login'] = session.get('login')\n if request.session.get('session_token') == None:\n request.session['session_token'] = session.get('session_token')\n res += \"&transaction_id=%s&invoice_id=%s\" %(tx.id, tx.invoice_ids[0].id)\n\n return res\n\n\n def _sslcommerz_validate_url(self, validate_url, new_post):\n \"\"\"\n Order Validation API\n Request Parameters\n PARAM NAME\t DATA TYPE\tDESCRIPTION\n val_id\t string (50)\tMandatory - A Validation ID against the successful transaction which is provided by SSLCOMMERZ.\n store_id\t string (30)\tMandatory - Your SSLCOMMERZ Store ID is the integration credential which can be collected through our managers\n store_passwd\tstring (30)\tMandatory - Your SSLCOMMERZ Store Password is the integration credential which can be collected through our managers\n format\t string (10)\tPredefined value is json or xml. This parameter is used to get the response in two different format such as json or xml. By default it returns json format.\n v\t integer (1)\tOpen for future use only.\n Returned Parameters\n PARAM NAME\t DATA TYPE\t DESCRIPTION\n status\t string (20)\t Transaction Status. This parameter needs to be checked before update your database as a successful transaction.\n VALID : A successful transaction.\n VALIDATED : A successful transaction but called by your end more than one.\n INVALID_TRANSACTION : Invalid validation id (val_id).\n ....\n ....\n risk_level\tinteger (1)\tTransaction's Risk Level - High (1) for most risky transactions and Low (0) for safe transactions. Please hold the service and proceed to collect customer verification documents\n status\tstring (20)\tOpen for future use only.\n risk_title\tstring (50)\tTransaction's Risk Level Description\n \"\"\"\n urequest = requests.get(validate_url, new_post)\n resp = urequest.text\n urequest_json = json.loads(resp)\n return urequest_json\n\n def invoice_reg_payment(self, tx, post):\n \"\"\"invoice_reg_payment\"\"\"\n if tx.invoice_ids[0].state != 'posted':\n tx.sale_order_ids[0].sudo().action_post()\n # Register Payment\n if tx.invoice_ids[0].amount_residual > 0 and float(tx.invoice_ids[0].amount_residual) == float(post.get('currency_amount')):\n invoice = tx.invoice_ids[0]\n AccountPayment = request.env['account.payment']\n APMethod = request.env['account.payment.method']\n payment_method_id = APMethod.sudo().search([\n ('name','=','Electronic'),\n ('code','=','electronic'),\n ('payment_type','=','inbound')\n ])\n\n payment_vals = {\n 'amount':tx.amount,\n 'currency_id':invoice.currency_id.id,\n 'journal_id':tx.acquirer_id.journal_id.id,\n 'date':fields.Datetime.now().date().strftime(\"%Y-%m-%d\"),\n 'payment_method_id':payment_method_id.id,\n 'partner_type':'customer',\n 'partner_id':invoice.partner_id.id,\n 'payment_type':'inbound',\n 'invoice_origin':tx.reference,\n 'payment_transaction_id':tx.id,\n # 'payment_token_id':tx.reference,\n 'ref':tx.reference,\n 'company_id': tx.acquirer_id.company_id.id,\n }\n payment = AccountPayment.sudo().create(payment_vals)\n invoice.sudo().write({'payment_id' : payment.id})\n\n print(\"payment_vals\")\n print(payment_vals)\n print(payment)\n print(\"-----------------------------------------\")\n\n\n\n @http.route('/payment/sslcommerz/ipn/', type='http', auth='none', methods=['POST'], csrf=False)\n def sslcommerz_ipn(self, **post):\n \"\"\" sslcommerz ipn \"\"\"\n _logger.info('****************************** /IPN')\n res = self.sslcommerz_validate_data(**post)\n return werkzeug.utils.redirect('/sslcommerz?{}'.format(res))\n\n @http.route('/payment/sslcommerz/success', type='http', auth=\"none\", methods=['POST'], csrf=False)\n def sslcommerz_success(self, **post):\n \"\"\" sslcommerz Success \"\"\"\n _logger.info('****************************** /success')\n return_url = self._get_return_url(**post)\n res = self.sslcommerz_validate_data(**post)\n\n\n if res:\n if 'sale_order_id' in res:\n for part in res.split(\"&\"):\n if part.split(\"=\")[0] == 'sale_order_id':\n if part.split(\"=\")[1] != False:\n if part.split(\"=\")[1] != request.session.get('sale_last_order_id'):\n request.session.update({'sale_last_order_id' : int(part.split(\"=\")[1]) })\n if 'invoice_id' in res:\n for part in res.split(\"&\"):\n if part.split(\"=\")[0] == 'invoice_id':\n if part.split(\"=\")[1] != False:\n invoice_id = part.split(\"=\")[1]\n invoice = request.env['account.move'].sudo().browse(int(invoice_id))\n return_url = '/my/invoices/' + invoice_id + '?access_token=%s' %invoice.access_token\n\n # print(\"res---->\\n\", res)\n # print(\"return_url---->\\n\", return_url)\n # print(\"&&&&&&&&&&&&&&&&&&&&&&&&&&&&\")\n # print(\"session\", request.session)\n\n return werkzeug.utils.redirect(return_url + '?{}'.format(res))\n else:\n return werkzeug.utils.redirect(self._cancel_url)\n\n\n @http.route('/payment/sslcommerz/cancel', type='http', auth=\"none\", methods=['POST'], csrf=False)\n def sslcommerz_cancel(self, **post):\n \"\"\" When the user cancels its sslcommerz payment: GET on this route \"\"\"\n _logger.info('****************************** /cancel')\n reference = post.get('val_id')\n if reference:\n sales_order_obj = request.env['sale.order']\n so_ids = sales_order_obj.sudo().search([('name', '=', reference)])\n if so_ids:\n '''return_url = '/shop/payment/get_status/' + str(so_ids[0])'''\n so = sales_order_obj.browse(so_ids[0].id)\n\n msg = \"/sslcommerz?status=cancelled&\"\n for key, value in post.items():\n msg += str(key)\n msg += '='\n msg += str(value)\n msg += '&'\n return werkzeug.utils.redirect(msg)\n\n # @http.route('/sslcommerz', type='http', auth='public', methods=['GET'], website=True)\n # def sslcommerz_status(self, **get):\n # _logger.info('****************************** /SSLCOMMERZ')\n # status = ''\n # transactionKey = ''\n # response_code = ''\n # message = ''\n # infoemail = ''\n # if 'status' in get:\n # status = get['status']\n # if 'transactionKey' in get:\n # transactionKey = get['transactionKey']\n # if 'response_code' in get:\n # response_code = get['response_code']\n # if 'message' in get:\n # message = get['message']\n\n # return request.render('bose_ssl_commerz.sslcommerz_status', {'status': status, 'transactionKey': transactionKey, 'response_code': response_code, 'message': message})\n","repo_name":"real-ariful/hfmfurniture","sub_path":"bose_ssl_commerz/controllers/ssl_commerz_controllers.py","file_name":"ssl_commerz_controllers.py","file_ext":"py","file_size_in_byte":14546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"3634030563","text":"from to_do_list_context import ToDoListContext\n\n\nclass ToDoListRepository:\n def __init__(self):\n self.to_do_list_context = ToDoListContext('to_do_list_db')\n\n def get_all_to_do_items(self):\n self.locking_table_read()\n sql = 'SELECT * FROM todolist'\n self.to_do_list_context.execute_database(sql)\n result = self.to_do_list_context.fetchall_database()\n self.unlocking_table()\n return result\n\n def delete_to_do_item(self, to_do_item_id):\n sql = 'DELETE FROM todolist WHERE ToDoListID=%s'\n self.to_do_list_context.execute_database(sql, (to_do_item_id,))\n self.to_do_list_context.commit_database()\n\n def search_to_do_item(self, text):\n self.locking_table_read()\n sql = '''\nSELECT \n *\nFROM \n todolist\nWHERE \n ToDoListTitle LIKE %s OR \n ToDoListDetails LIKE %s OR\n ToDoListActive LIKE %s OR\n ToDoListStartDateTime LIKE %s OR\n ToDoListEndDateTime LIKE %s;\n '''\n text = '%' + text + '%'\n self.to_do_list_context.execute_database(sql, (text, text, text, text, text))\n result = self.to_do_list_context.fetchall_database()\n self.unlocking_table()\n return result\n\n def get_to_do_list_item_by_id(self, to_do_item_id):\n self.locking_table_read()\n sql = '''\n SELECT \n * \n FROM \n todolist\n WHERE\n ToDoListID = %s \n '''\n self.to_do_list_context.execute_database(sql, (str(to_do_item_id),))\n result = self.to_do_list_context.fetchone_database()\n self.unlocking_table()\n return result\n\n def to_or_do(self, to_do_item_id):\n self.locking_table_write()\n sql = '''\nUPDATE \n todolist \nSET \n ToDoListActive = NOT ToDoListActive \nWHERE \n ToDoListID = %s; \n '''\n self.to_do_list_context.execute_database(sql, (to_do_item_id,))\n self.to_do_list_context.commit_database()\n self.unlocking_table()\n\n def close_database(self):\n self.to_do_list_context.close_database()\n\n def insert_to_do_item(self, title_to_do_item, details_to_do_item, start_datetime_to_do_item,\n end_datetime_to_do_item):\n self.locking_table_write()\n sql = '''\n INSERT INTO `todolist`(\n `ToDoListID`,\n `ToDoListTitle`,\n `ToDoListDetails`,\n `ToDoListActive`,\n `ToDoListStartDateTime`,\n `ToDoListEndDateTime`\n )\n VALUES(NULL,%s,%s,%s,%s,%s);\n '''\n self.to_do_list_context.execute_database(sql, (\n title_to_do_item, details_to_do_item, 0, start_datetime_to_do_item, end_datetime_to_do_item))\n self.to_do_list_context.commit_database()\n self.unlocking_table()\n\n def update_to_do_item(self, to_do_item_id, title_to_do_item, details_to_do_item, start_datetime_to_do_item,\n end_datetime_to_do_item):\n self.locking_table_write()\n sql = '''\n UPDATE \n todolist\n SET \n ToDoListTitle = %s,\n ToDoListDetails = %s,\n ToDoListStartDateTime = %s,\n ToDoListEndDateTime = %s\n WHERE\n ToDoListID = %s\n '''\n self.to_do_list_context.execute_database(sql, (\n title_to_do_item, details_to_do_item, start_datetime_to_do_item, end_datetime_to_do_item, to_do_item_id))\n self.to_do_list_context.commit_database()\n self.unlocking_table()\n\n def locking_table_write(self):\n sql = 'LOCK TABLES todolist WRITE;'\n self.to_do_list_context.execute_database(sql)\n\n def locking_table_read(self):\n sql = 'LOCK TABLES todolist READ;'\n self.to_do_list_context.execute_database(sql)\n\n def unlocking_table(self):\n sql = 'UNLOCK TABLES;'\n self.to_do_list_context.execute_database(sql)\n\n\nif __name__ == '__main__':\n to_do_list_repository = ToDoListRepository()\n to_do_list_repository.to_or_do(7)\n print(to_do_list_repository.get_to_do_list_item_by_id(7)[3])\n\n\ndef initialize_database():\n to_do_list_context_instantiation = ToDoListContext()\n to_do_list_context_instantiation.create_database('to_do_list_db')\n to_do_list_context_instantiation.close_database()\n\n to_do_list_context_instantiation = ToDoListContext('to_do_list_db')\n sql_create_table_to_do_list = '''\n CREATE TABLE IF NOT EXISTS ToDoList (\n ToDoListID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,\n ToDoListTitle VARCHAR(150) NOT NULL,\n ToDoListDetails TEXT NOT NULL,\n ToDoListActive BOOLEAN NOT NULL DEFAULT FALSE,\n ToDoListStartDateTime DATETIME NULL,\n ToDoListEndDateTime DATETIME NULL\n );\n '''\n\n to_do_list_context_instantiation.execute_database(sql_create_table_to_do_list)\n to_do_list_context_instantiation.close_database()\n","repo_name":"EbrahimQ01/To-Do-List","sub_path":"Scripts/to_do_list_repository.py","file_name":"to_do_list_repository.py","file_ext":"py","file_size_in_byte":5019,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"3480636072","text":"from __future__ import absolute_import, division, print_function, with_statement\n\nimport os\nimport sys\ntry:\n import builtins\nexcept ImportError:\n path = os.path.realpath(os.path.join(os.path.dirname(__file__),\n \"..\", \"..\", \"..\", \"deps\", \"future\", \"src\"))\n sys.path.append(path)\n\nfrom builtins import input\nfrom builtins import str\nfrom builtins import range\n\n# Standard library imports\nimport argparse\nimport cmd\nimport fnmatch\nimport glob\nimport io\nimport math\nimport readline\nimport subprocess\nimport time\n\n# iRODS imports\nfrom irods.exception import (CATALOG_ALREADY_HAS_ITEM_BY_THAT_NAME,\n CAT_NAME_EXISTS_AS_COLLECTION,\n CollectionDoesNotExist, DataObjectDoesNotExist,\n USER_FILE_DOES_NOT_EXIST)\nfrom irods.session import iRODSSession\nfrom irods.data_object import chunks, irods_basename\nfrom irods.keywords import FORCE_FLAG_KW\ntry:\n from irods.manager.data_object_manager import (READ_BUFFER_SIZE,\n WRITE_BUFFER_SIZE)\nexcept ImportError:\n READ_BUFFER_SIZE = 1024 * io.DEFAULT_BUFFER_SIZE\n WRITE_BUFFER_SIZE = 1024 * io.DEFAULT_BUFFER_SIZE\n\n__all__ = [\"IShell\"]\n\n\n# Redefine the delimiters according to file name syntax. This is required\n# for autocompletion of file names.\nreadline.set_completer_delims(\" \\t\\n\")\n\n\nclass IShell(cmd.Cmd, object):\n \"\"\"Shell like client for managing iRODS data\n \"\"\"\n\n cursor = None\n\n interactive = False\n\n parser = {}\n\n session = None\n\n class _IShellError(Exception):\n pass\n\n def default(self, line):\n \"\"\"Handle unknown commands\n \"\"\"\n args = line.split(None, 1)\n self.errorln(\"error: unknown command `{:}'\", args[0])\n\n def completedefault(self, text, line, begidx, endidx):\n dirname, _, content = self.get_content(text + \"*\")\n completion = list(content.keys())\n if dirname:\n if dirname == \"/\":\n dirname = \"\"\n else: \n dirname = dirname.replace(\"/\", r\"/\")\n completion = [r\"/\".join((dirname, c)) for c in completion]\n return completion\n\n def get_content(self, pattern, data=True, collections=True, base=None):\n \"\"\"Get items within the collection that match the pattern\n \"\"\"\n if base is None:\n base = self.cursor\n if pattern.endswith(\"/\"):\n pattern += \"*\"\n elif pattern.endswith(\"..\"):\n pattern += \"/*\"\n elif pattern.endswith(\"/.\"):\n pattern = pattern[:-1] + \"*\"\n elif pattern == \".\":\n pattern = \"*\"\n\n if pattern.startswith(\"~\"):\n pattern = self.home + pattern[1:]\n\n try:\n dirname, basename = pattern.rsplit(\"/\", 1)\n except ValueError:\n dirname = None\n else:\n if dirname == \"\":\n dirname = \"/\"\n path = self.get_path(dirname, base)\n try:\n base = self.session.collections.get(path)\n except CollectionDoesNotExist:\n return None, base, None\n pattern = basename\n\n content, n = {}, 0\n if collections:\n for c in base.subcollections:\n n += 1\n if c.name == \"\":\n continue\n if fnmatch.fnmatch(c.name, pattern):\n content[c.name] = (True, c)\n if data:\n for d in base.data_objects:\n n += 1\n if fnmatch.fnmatch(d.name, pattern):\n content[d.name] = (False, d)\n\n if (n > 0) and not content:\n content = None\n return dirname, base, content\n\n def get_path(self, path, base=None):\n if path.startswith(\"/\"):\n return os.path.normpath(path)\n else:\n if base is None:\n base = self.cursor\n path = os.path.join(base.path, path)\n return os.path.normpath(path)\n\n def parse_command(self, command, options, noargs=False):\n \"\"\"Parse a command line for arguments and options\n \"\"\"\n args = self._command[1:]\n try:\n opts = vars(self.parser[command].parse_args(args))\n try:\n args = opts.pop(\"args\")\n except KeyError:\n arg = opts.pop(\"arg\")\n if arg is None:\n args = []\n else:\n args = [arg]\n except SystemExit:\n raise self._IShellError()\n\n if (not noargs) and (not args):\n self.errorln(\"{:}: missing operand\", command)\n raise self._IShellError()\n return opts, args\n\n def parse_line(self, line):\n \"\"\"Parse a line and strip commands\n \"\"\"\n cmds, cmd, arg = [], [], []\n quote, commented = None, False\n for c in line:\n if commented:\n if c in \"\\r\\n\":\n commented = False\n elif quote is None:\n if c in \"#;\\r\\n\":\n if arg:\n cmd.append(\"\".join(arg))\n arg = []\n if cmd:\n cmds.append(cmd)\n cmd = []\n if c == \"#\":\n commented = True\n elif c in \" \\t\":\n if arg:\n cmd.append(\"\".join(arg))\n arg = []\n elif c in \"'\\\"\":\n quote = c\n else:\n arg.append(c)\n else:\n if c == quote:\n quote = None\n else:\n arg.append(c)\n if arg:\n cmd.append(\"\".join(arg))\n if cmd:\n cmds.append(cmd)\n return cmds\n\n def println(self, text, *opts, **kwopts):\n self.printfmt(text, *opts, **kwopts)\n print()\n\n def printfmt(self, text, *opts, **kwopts):\n if opts or kwopts:\n text = text.format(*opts, **kwopts)\n else:\n text = str(text)\n print(text, end=\"\")\n\n def errorln(self, text, *opts, **kwopts):\n if opts or kwopts:\n text = text.format(*opts, **kwopts)\n else:\n text = str(text)\n if self.interactive:\n text = \"\\033[93m{:}\\033[0m\".format(text)\n print(text, file=sys.stderr)\n\n def ask_for_confirmation(self, text, *args):\n self.printfmt(text, *args)\n try:\n answer = input()\n except EOFError:\n return False\n if answer in (\"y\", \"Y\", \"yes\", \"Yes\"):\n return True\n return False\n\n def _register_cd(self):\n if \"cd\" not in self.parser:\n p = argparse.ArgumentParser(\n prog=\"cd\",\n description=\"Change the iRODS collection to the given path. \"\n \"If no path is provided then get back to HOME ({:}).\".format(\n self.home))\n p.add_argument(\"arg\", metavar=\"path\", type=str, nargs=\"?\",\n help=\"the path to change the current collection to\")\n self.parser[\"cd\"] = p\n\n def help_cd(self):\n \"\"\"Print a help message for the `cd' command\n \"\"\"\n self._register_cd()\n self.println(self.parser[\"cd\"].format_help())\n\n def do_cd(self, line):\n \"\"\"Change the current iRODS collection\n \"\"\"\n self._register_cd()\n try:\n opts, args = self.parse_command(\"cd\", \"\", noargs=True)\n except self._IShellError:\n return\n if not args:\n path = self.home\n else:\n path = args[0]\n if path.startswith(\"~\"):\n path = path.replace(\"~\", self.home)\n path = self.get_path(path)\n\n # Fetch the corresponding iRODS collection\n try:\n self.cursor = self.session.collections.get(path)\n except CollectionDoesNotExist:\n self.errorln(\"cd: path `{:}' does not exist\", args[0])\n else:\n # Update the prompt\n current = irods_basename(self.cursor.path)\n self.prompt = \"[{:} \\033[94m{:}\\033[0m]$ \".format(\n self.prompt_prefix, current)\n\n def _register_ls(self):\n if \"ls\" not in self.parser:\n p = argparse.ArgumentParser(\n prog=\"ls\",\n description=\"List the objects inside the given iRODS \"\n \"collection. If no path is provided then list the current \"\n \"collection.\")\n p.add_argument(\"args\", metavar=\"path\", type=str, nargs=\"*\",\n help=\"the path(s) to list\")\n self.parser[\"ls\"] = p\n\n def help_ls(self):\n \"\"\"Print a help message for the `ls' command\n \"\"\"\n self._register_ls()\n self.println(self.parser[\"ls\"].format_help())\n\n def do_ls(self, line):\n \"\"\"List the objects inside the given iRODS collection\n \"\"\"\n self._register_ls()\n try:\n opts, args = self.parse_command(\"ls\", \"\", noargs=True)\n except self._IShellError:\n return\n list_subcol = True\n if not args:\n args = (\"*\",)\n\n for iteration, pattern in enumerate(args):\n # Find items that match the pattern\n if ((pattern == \".\") or (pattern == \"*\") or (pattern == \"/\") or\n pattern.endswith(\"/.\") or pattern.endswith(\"/*\")):\n list_subcol = False\n\n dirname, base, content = self.get_content(pattern)\n if content is None:\n \tself.errorln(\"ls: cannot access `{:}':\"\n \" No such data object or collection\",\n pattern)\n \tbreak\n elif len(content) == 0:\n break\n\n # Print the result\n if iteration > 0:\n self.println(\"\")\n if len(args) > 1:\n self.println(\"{:}:\", pattern)\n if (len(content) == 1) and list_subcol:\n pattern = list(content.keys())[0]\n if pattern[-1] == \"/\":\n pattern += \"*\"\n else:\n pattern += \"/*\"\n if dirname:\n pattern = os.path.join(dirname, pattern)\n _, _, content = self.get_content(pattern)\n keys = sorted([str(s) for s in content.keys()], key=str.lower)\n\n if len(keys) == 0:\n continue\n\n if self.interactive:\n # Get the current terminal's width\n p = subprocess.Popen(\"stty size\", shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n out, err = p.communicate()\n if err:\n screen_width = 80\n else:\n screen_width = int(out.split()[-1])\n\n # Compute the layout\n tokens = []\n for item in keys:\n n = len(item) + 2\n if content[item][0]:\n item = \"\\033[94m{:}\\033[0m\".format(item)\n extra = len(item) - n + 3\n else:\n extra = 1\n tokens.append((n, item, extra))\n max_width = max(tokens)[0]\n n_columns = max(screen_width // max_width, 1)\n n_tokens = len(tokens)\n if n_columns >= n_tokens:\n n_columns = n_tokens\n n_rows = 1\n else:\n n_rows = int(math.ceil(n_tokens / float(n_columns)))\n\n column_width = n_columns * [0]\n for i in range(n_columns):\n w = 0\n for j in range(n_rows):\n index = i * n_rows + j\n if index >= n_tokens:\n continue\n wj = tokens[index][0]\n if wj > w:\n w = wj\n column_width[i] = w - 1\n\n # Print the result\n for i in range(n_rows):\n for j in range(n_columns):\n index = j * n_rows + i\n if index >= n_tokens:\n continue\n self.printfmt(\"{:<{width}}\", tokens[index][1],\n width=column_width[j] + tokens[index][2])\n self.println(\"\")\n else:\n self.println(os.linesep.join(keys))\n\n def _register_mkdir(self):\n if \"mkdir\" not in self.parser:\n p = argparse.ArgumentParser(\n prog=\"mkdir\", description=\"Create new iRODS collection(s)\")\n p.add_argument(\"args\", metavar=\"path\", type=str, nargs=\"+\",\n help=\"the path(s) of the new collection(s)\")\n self.parser[\"mkdir\"] = p\n\n def help_mkdir(self):\n \"\"\"Print a help message for the `mkdir' command\n \"\"\"\n self._register_mkdir()\n self.println(self.parser[\"mkdir\"].format_help())\n\n def do_mkdir(self, line):\n \"\"\"Create new iRODS collection(s)\n \"\"\"\n self._register_mkdir()\n try:\n opts, args = self.parse_command(\"mkdir\", \"\")\n except self._IShellError:\n return\n\n for arg in args:\n path = self.get_path(arg)\n try:\n self.session.collections.create(path)\n except CATALOG_ALREADY_HAS_ITEM_BY_THAT_NAME:\n self.errorln(\"mkdir: cannot create collection `{:}':\"\n \" Object exists\", irods_basename(path))\n break\n\n def _register_pwd(self):\n if \"pwd\" not in self.parser:\n p = argparse.ArgumentParser(\n prog=\"mkdir\", description=\"Show the current iRODS collection.\")\n self.parser[\"pwd\"] = p\n\n def help_pwd(self):\n \"\"\"Print a help message for the `pwd' command\n \"\"\"\n self._register_pwd()\n self.println(self.parser[\"pwd\"].format_help())\n\n def do_pwd(self, line):\n \"\"\"Show the current iRODS collection\n \"\"\"\n self._register_pwd()\n self.println(self.cursor.path)\n\n def _register_rm(self):\n if \"rm\" not in self.parser:\n p = argparse.ArgumentParser(\n prog=\"rm\", description=\"Remove collection(s) or data object(s) \"\n \"from iRODS.\")\n p.add_argument(\"args\", metavar=\"path\", type=str, nargs=\"+\",\n help=\"the path(s) of the object(s) to remove\")\n p.add_argument(\"-f\", \"--force\", action=\"store_true\",\n help=\"do not prompt before removal\")\n p.add_argument(\"-r\", \"--recursive\", action=\"store_true\",\n help=\"remove collections and their content \"\n \"recursively\")\n p.add_argument(\"-T\", \"--no-trash\", action=\"store_true\",\n help=\"do not put the erased object in the trash.\"\n \" Remove them definitively\")\n self.parser[\"rm\"] = p\n\n def help_rm(self):\n \"\"\"Print a help message for the `rm' command\n \"\"\"\n self._register_rm()\n self.println(self.parser[\"rm\"].format_help())\n\n def do_rm(self, line):\n \"\"\"Remove collection(s) or data object(s) from iRODS\n \"\"\"\n self._register_rm()\n try:\n opts, args = self.parse_command(\"rm\", \"rfT\")\n except self._IShellError:\n return\n protect_collections = not opts[\"recursive\"]\n request_confirmation = not opts[\"force\"]\n skip_trash = opts[\"no_trash\"]\n\n for arg in args:\n # Check that the object exist and what is its type\n path = self.get_path(arg)\n basename = irods_basename(path)\n try:\n target = self.session.data_objects.get(path)\n except DataObjectDoesNotExist:\n try:\n target = self.session.collections.get(path)\n except CollectionDoesNotExist:\n self.errorln(\"rm: cannot remove object `{:}':\"\n \"No such data or collection\", basename)\n return\n else:\n itype = \"collection\"\n else:\n itype = \"data object\"\n\n # Check for the recursive mode\n if protect_collections and (itype == \"collection\"):\n self.errorln(\"rm: cannot remove `{:}': Is a collection\",\n basename)\n return\n\n # Check for a confirmation\n if request_confirmation:\n if not self.ask_for_confirmation(\n \"rm: remove {:} `{:}'?\", itype, basename):\n continue\n\n # Now we can remove the data\n try:\n if itype == \"collection\":\n self.session.collections.remove(path)\n else:\n self.session.data_objects.unlink(path, force=skip_trash)\n except USER_FILE_DOES_NOT_EXIST:\n self.errorln(\"rm: cannot remove object `{:}':\"\n \"No such data or collection\", basename)\n return\n\n def _register_put(self):\n if \"put\" not in self.parser:\n p = argparse.ArgumentParser(\n prog=\"put\", description=\"Upload collection(s) or data \"\n \"object(s) to iRODS.\")\n p.add_argument(\"args\", metavar=\"path\", type=str, nargs=\"+\",\n help=\"the local path(s) of the object(s) to \"\n \"download. If more than one argument is given, the \"\n \"last one specifies the iRODS destination path\")\n p.add_argument(\"-f\", \"--force\", action=\"store_true\",\n help=\"do not prompt before overwriting\")\n p.add_argument(\"-r\", \"--recursive\", action=\"store_true\",\n help=\"upload directories and their content \"\n \"recursively\")\n self.parser[\"put\"] = p\n\n def help_put(self):\n \"\"\"Print a help message for the `put' command\n \"\"\"\n self._register_put()\n self.println(self.parser[\"put\"].format_help())\n\n @staticmethod\n def _hrdb(x):\n \"\"\"Format a number as human readable text\n \"\"\"\n if x > 1125899906842624:\n return \"{:.1f}P\".format(x / 1125899906842624.)\n elif x == 0:\n return \"0.0B\"\n i = int(math.floor(math.log(x) / math.log(1024)))\n unit = (\"B\", \"kB\", \"MB\", \"GB\", \"TB\")\n return \"{:.1f} {:}\".format(x / 1024**i, unit[i])\n\n def do_put(self, line):\n \"\"\"Upload collection(s) or data object(s) to iRODS\n \"\"\"\n self._register_put()\n try:\n opts, args = self.parse_command(\"put\", \"rf\")\n except self._IShellError:\n return\n recursive = opts[\"recursive\"]\n request_confirmation = not opts[\"force\"]\n\n # Parse the src(s) and the destination\n if len(args) == 1:\n srcs = args\n dst = self.cursor.path\n else:\n if len(args) == 2:\n srcs = (args[0],)\n else:\n srcs = args[:-1]\n dst = self.get_path(args[-1])\n\n # Expand the source(s)\n expanded = []\n for src in srcs:\n s = glob.glob(src)\n if not s:\n self.errorln(\"cannot access {:}: No such file or directory\",\n os.path.basename(src))\n return\n expanded += s\n srcs = expanded\n\n # Check if the destination is an existing collection\n if self.session.collections.exists(dst):\n if not dst.endswith(\"/\"):\n dst += \"/\"\n elif len(srcs) > 1:\n self.errorln(\"put: target `{:}' is not a directory\", basename)\n return\n\n # Upload the data\n def upload(srcs, dst):\n for src in srcs:\n basename = os.path.basename(src)\n if not os.path.exists(src):\n self.errorln(\"cannot access {:}: No such file or directory\",\n basename)\n raise self._IShellError()\n if dst.endswith(\"/\"):\n target = dst + basename\n else:\n target = dst\n\n if os.path.isdir(src):\n if not recursive:\n self.errorln(\"put: omitting collection `{:}'\",\n basename)\n raise self._IShellError()\n if not self.session.collections.exists(target):\n self.session.collections.create(target)\n children = [os.path.join(src, f) for f in os.listdir(src)]\n upload(children, target + \"/\")\n else:\n if self.session.data_objects.exists(target):\n if request_confirmation:\n if not self.ask_for_confirmation(\n \"put: overwrite data object `{:}'?\", basename):\n continue\n\n size = os.stat(src).st_size\n done = 0\n t0 = t1 = time.time()\n if self.interactive:\n red, blue, reset = \"\\033[91m\", \"\\033[94m\", \"\\033[0m\"\n else:\n red, blue, reset = \"\", \"\", \"\"\n self.printfmt(\"Uploading {:}{:}{:} ...\",\n red, basename, reset),\n sys.stdout.flush()\n dmgr = self.session.data_objects\n try:\n with open(src, \"rb\") as f, dmgr.open(\n target, \"w\", oprType=1) as o:\n for chunk in chunks(f, WRITE_BUFFER_SIZE):\n o.write(chunk)\n\n n_chunk = len(chunk)\n done += n_chunk\n if done < size:\n status = int(100 * done / float(size))\n t2 = time.time()\n dt, t1 = t2 - t1, t2\n self.printfmt(\n \"\\rUploading {:}{:}{:} ({:2d}%), \"\n \"size={:}{:}{:}, speed={:}{:}/s{:}\",\n red, basename, reset, status,\n blue, self._hrdb(done), reset,\n blue, self._hrdb(n_chunk / dt),\n reset),\n sys.stdout.flush()\n dt = time.time() - t0\n self.println(\n \"\\rUploaded {:}{:}{:} as {:} ({:}{:}{:} at \"\n \"{:}{:}/s{:})\", red, basename, reset,\n irods_basename(target), blue, self._hrdb(done),\n reset, blue, self._hrdb(done / dt), reset)\n except CAT_NAME_EXISTS_AS_COLLECTION:\n self.errorln(\"put: `{:}' is an existing collection\",\n basename)\n raise self._IShellError()\n except KeyboardInterrupt:\n print(\"^C\")\n raise self._IShellError\n except EOFError:\n print(\"^D\")\n raise self._IShellError\n\n try:\n upload(srcs, dst)\n except self._IShellError:\n return\n\n def complete_put(self, text, line, begidx, endidx):\n self._register_put()\n self._command = self.parse_line(line)[0]\n try:\n opts, args = self.parse_command(\"put\", \"rf\", noargs=True)\n except self._IShellError:\n return []\n nargs = len(args)\n if (nargs < 1) or ((nargs == 1) and (line[-1] != \" \")):\n dirname = os.path.dirname(text)\n if not dirname:\n pattern = text + \"*\"\n return [s for s in os.listdir(\".\")\n if fnmatch.fnmatch(s, pattern)]\n else:\n pattern = os.path.basename(text) + \"*\"\n completion = [os.path.join(dirname, s)\n for s in os.listdir(dirname)\n if fnmatch.fnmatch(s, pattern)]\n return completion\n else:\n return self.completedefault(text, line, begidx, endidx)\n\n def _register_get(self):\n if \"get\" not in self.parser:\n p = argparse.ArgumentParser(\n prog=\"get\", description=\"Download collection(s) or data \"\n \"object(s) from iRODS.\")\n p.add_argument(\"args\", metavar=\"path\", type=str, nargs=\"+\",\n help=\"the iRODS path(s) of the object(s) to \"\n \"download. If more than one argument is given, the \"\n \"last one specifies the local destination path\")\n p.add_argument(\"-f\", \"--force\", action=\"store_true\",\n help=\"do not prompt before overwriting\")\n p.add_argument(\"-r\", \"--recursive\", action=\"store_true\",\n help=\"Download collections and their content \"\n \"recursively\")\n self.parser[\"get\"] = p\n\n def help_get(self):\n \"\"\"Print a help message for the `get' command\n \"\"\"\n self._register_get()\n self.println(self.parser[\"get\"].format_help())\n\n def do_get(self, line):\n \"\"\"Download collection(s) or data object(s) from iRODS\n \"\"\"\n self._register_get()\n try:\n opts, args = self.parse_command(\"get\", \"rf\")\n except self._IShellError:\n return\n recursive = opts[\"recursive\"]\n request_confirmation = not opts[\"force\"]\n\n # Parse the src(s) and the destination\n if len(args) == 1:\n srcs = args\n dst = \".\"\n else:\n if len(args) == 2:\n srcs = (args[0],)\n else:\n srcs = args[:-1]\n dst = args[-1]\n\n # Check the consistency of the inputs\n if os.path.isdir(dst):\n isdir = True\n else:\n isdir = False\n if len(srcs) > 1:\n self.errorln(\"get: target `{:}' is not a directory\",\n os.path.basename(dst))\n return\n\n # Download the data\n def download(srcs, dst, isdir):\n for src in srcs:\n basename = os.path.basename(src)\n if isdir:\n target = os.path.join(dst, basename)\n else:\n target = dst\n\n if self.session.collections.exists(src):\n if not recursive:\n self.errorln(\"get: omitting collection `{:}'\",\n irods_basename(src))\n raise self._IShellError()\n\n if os.path.exists(target):\n if not os.path.isdir(target):\n self.println(\"get: cannot overwrite non-directory \"\n \"`{:}'\", target)\n raise self._IShellError()\n else:\n os.makedirs(target)\n\n base = self.session.collections.get(src)\n _, _, content = self.get_content(\"*\", base=base)\n newsrcs = [self.get_path(src, base=base)\n for src in content.keys()]\n download(newsrcs, target, True)\n else:\n if not self.session.data_objects.exists(src):\n self.errorln(\"get: cannot stat `{:}': No such data \"\n \"object or collection\",\n irods_basename(src))\n raise self._IShellError()\n\n if os.path.exists(target) and request_confirmation:\n if not self.ask_for_confirmation(\n \"get: overwrite file `{:}'?\", basename):\n continue\n\n dmgr = self.session.data_objects\n obj = dmgr.get(src)\n size = obj.size\n done = 0\n t0 = t1 = time.time()\n if self.interactive:\n red, blue, reset = \"\\033[91m\", \"\\033[94m\", \"\\033[0m\"\n else:\n red, blue, reset = \"\", \"\", \"\"\n self.printfmt(\"Downloading {:}{:}{:} ...\",\n red, irods_basename(src), reset),\n sys.stdout.flush()\n try:\n with open(target, \"wb\") as f, dmgr.open(\n src, \"r\", forceFlag=True) as o:\n for chunk in chunks(o, READ_BUFFER_SIZE):\n f.write(chunk)\n\n n_chunk = len(chunk)\n done += n_chunk\n if done < size:\n status = int(100 * done / float(size))\n t2 = time.time()\n dt, t1 = t2 - t1, t2\n self.printfmt(\n \"\\rDownloading {:}{:}{:} ({:2d}%), \"\n \"size={:}{:}{:}, speed={:}{:}/s{:}\",\n red, irods_basename(src), reset, status,\n blue, self._hrdb(done), reset,\n blue, self._hrdb(n_chunk / dt),\n reset),\n sys.stdout.flush()\n dt = time.time() - t0\n self.println(\n \"\\rDownloaded {:}{:}{:} as {:} ({:}{:}{:} at \"\n \"{:}{:}/s{:})\", red, irods_basename(src), reset,\n target, blue, self._hrdb(done), reset,\n blue, self._hrdb(done / dt), reset)\n except KeyboardInterrupt:\n print(\"^C\")\n raise self._IShellError\n except EOFError:\n print(\"^D\")\n raise self._IShellError\n\n srcs = [self.get_path(src) for src in srcs]\n try:\n download(srcs, dst, isdir)\n except self._IShellError:\n return\n\n def _register_shell(self):\n if \"shell\" not in self.parser:\n p = argparse.ArgumentParser(\n prog=\"shell\", description=\"escape with a local shell command.\")\n p.add_argument(\"args\", metavar=\"command\", type=str, nargs=1,\n help=\"the local command\")\n p.add_argument(\"args\", metavar=\"argument\", type=str, nargs=\"*\",\n help=\"the argument(s) of the local command\",\n action=\"append\")\n self.parser[\"shell\"] = p\n\n def help_shell(self):\n \"\"\"Print a help message for the `get' command\n \"\"\"\n self._register_shell()\n self.println(self.parser[\"shell\"].format_help())\n\n def do_shell(self, line):\n \"\"\"Escape with a local shell command\n \"\"\"\n self._register_shell()\n args = line.split(None, 1)\n if args and (args[0] == \"cd\"):\n os.chdir(args[1])\n else:\n p = subprocess.Popen(line, shell=True)\n p.communicate()\n\n def do_EOF(self, line):\n \"\"\"Exit to the OS\n \"\"\"\n return True\n\n def do_exit(self, line):\n \"\"\"Exit to the OS\n \"\"\"\n return True\n\n def onecmd(self, line):\n \"\"\"Override the default command processing in order to strip commands\n \"\"\"\n for self._command in self.parse_line(line):\n if super(IShell, self).onecmd(\" \".join(self._command)):\n return True\n\n def cmdloop(self, intro=None):\n \"\"\"Override the default command loop in order to catch Ctrl+C\n \"\"\"\n # Initialise the session\n self.initialise()\n\n # Run the command loop\n self.interactive = True\n\n while True:\n try:\n super(IShell, self).cmdloop(intro=\"\")\n break\n except KeyboardInterrupt:\n print(\"^C\")\n print()\n\n # Finalise the session\n self.finalise()\n\n def initialise(self):\n \"\"\"Start an iRODS session and initialise the environment\n \"\"\"\n # Start the iRODS session\n environment = os.path.expanduser(\"~/.irods/irods_environment.json\")\n self.session = iRODSSession(irods_env_file=environment)\n\n # Fetch the environment\n env = self.session.get_irods_env(environment)\n self.home = env[\"irods_home\"]\n self.user = env[\"irods_user_name\"]\n self.host = env[\"irods_host\"]\n self.prompt_prefix = \"\\033[91m{:}@{:}\\033[0m\".format(\n self.host.split(\".\", 1)[0], self.user)\n\n # Go to the home directory\n self._command = [\"cd\"]\n self.do_cd(\"\")\n\n def finalise(self):\n \"\"\"Close the current iRODS session\n \"\"\"\n self.session.cleanup()\n self.session = None\n","repo_name":"niess/ishell","sub_path":"ishell/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":34304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"72924338484","text":"#! /usr/bin/env python\n\nfrom __future__ import print_function\nimport tensorflow as tf\nimport numpy as np\nimport re\nimport os\nimport time\nimport datetime\nimport gc\nfrom input_helpers import InputHelper\nfrom siamese_network import SiameseLSTM\nfrom siamese_network_semantic import SiameseLSTMw2v\nfrom random import random\nimport sqlite3 as lite\nimport sys\nimport math\nimport pickle\n\n# Parameters\n# ==================================================\n\ntf.flags.DEFINE_boolean(\"is_char_based\", False, \"is character based syntactic similarity. \"\n \"if false then word embedding based semantic similarity is used.\"\n \"(default: False)\")\n\ntf.flags.DEFINE_string(\"word2vec_model\", \"enwiki_20180420_100d.txt\", \"word2vec pre-trained embeddings file (default: enwiki_20180420_100d.txt)\")\ntf.flags.DEFINE_string(\"word2vec_format\", \"text\", \"word2vec pre-trained embeddings file format (bin/text/textgz)(default: text)\")\n\ntf.flags.DEFINE_integer(\"embedding_dim\", 100, \"Dimensionality of character embedding (default: 100)\")\ntf.flags.DEFINE_float(\"dropout_keep_prob\", 1.0, \"Dropout keep probability (default: 1.0)\")\ntf.flags.DEFINE_float(\"l2_reg_lambda\", 0.0, \"L2 regularization lambda (default: 0.0)\")\ntf.flags.DEFINE_string(\"database\", \"../plag.db\", \"training file (default: ../plag.db)\")\ntf.flags.DEFINE_string(\"training_folder\", 'ds', \"path to folder containing dataset (default: ds)\")\ntf.flags.DEFINE_integer(\"hidden_units\", 50, \"Number of hidden units (default:50)\")\n\n# Training parameters\ntf.flags.DEFINE_integer(\"batch_size\", 32, \"Batch Size (default: 32)\")\ntf.flags.DEFINE_integer(\"num_epochs\", 300, \"Number of training epochs (default: 300)\")\ntf.flags.DEFINE_integer(\"evaluate_every\", 1, \"Evaluate model on dev set after this many steps (default: 1)\")\ntf.flags.DEFINE_integer(\"checkpoint_every\", 50, \"Save model after this many steps (default: 50)\")\ntf.flags.DEFINE_integer(\"patience\", 20, \"Patience for early stopping (default: 20)\")\ntf.flags.DEFINE_integer(\"log_every\", 1000, \"Log results every X steps (default: 100000)\")\n# Misc Parameters\ntf.flags.DEFINE_boolean(\"allow_soft_placement\", True, \"Allow device soft device placement\")\ntf.flags.DEFINE_boolean(\"log_device_placement\", False, \"Log placement of ops on devices\")\n\nFLAGS = tf.flags.FLAGS\n\nbatch_size = FLAGS.batch_size\nnum_epochs = FLAGS.num_epochs\n\nprint(\"\\nParameters:\")\nfor attr, value in sorted(FLAGS.flag_values_dict().iteritems()):\n print(\"{}={}\".format(attr.upper(), value))\nprint(\"\")\n\nif FLAGS.database==None:\n print(\"Input Files List is empty. use -database argument.\")\n exit()\n\nmax_document_length=15\n#max_document_length=sys.maxint # attempt to read all words in a document\ninpH = InputHelper()\n#train_set, dev_set, vocab_processor,sum_no_of_batches = inpH.getDataSets(FLAGS.database,max_document_length, 10,\n# FLAGS.batch_size, FLAGS.is_char_based)\n\nnum_docs = inpH.get_num_docs(FLAGS.training_folder)\n\ndb = lite.connect(FLAGS.database)\ncursor = db.cursor()\nemb_map, vocab_processor = inpH.getEmbeddingsMap(cursor, max_document_length, num_docs)\ntrain_count, dev_count = inpH.get_counts(FLAGS.training_folder)[0:2]\ntotal_count = train_count + dev_count\n\nsum_no_of_batches = int(math.ceil(float(train_count) / batch_size))\ndev_no_of_batches = int(math.ceil(float(dev_count) / batch_size))\n\ntrain_set = inpH.my_train_batch(emb_map, train_count, FLAGS.batch_size, num_epochs)\n\ndev_set = inpH.my_dev_batch(emb_map, dev_count, FLAGS.batch_size, num_epochs)\n\n# train_set, dev_set, sum_no_of_batches = inpH.myGetDataSets(cursor ,max_document_length, 10,\n# FLAGS.batch_size, FLAGS.is_char_based, 1000)\n\ntrainableEmbeddings=False\nif FLAGS.is_char_based==True:\n FLAGS.word2vec_model = False\nelse:\n if FLAGS.word2vec_model==None:\n trainableEmbeddings=True\n print(\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\n\"\n \"You are using word embedding based semantic similarity but \"\n \"word2vec model path is empty. It is Recommended to use --word2vec_model argument. \"\n \"Otherwise now the code is automatically trying to learn embedding values (may not help in accuracy)\"\n \"\\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\n\")\n else:\n inpH.loadW2V(FLAGS.word2vec_model, FLAGS.word2vec_format)\n\n# Training\n# ==================================================\nprint(\"starting graph def\")\nwith tf.Graph().as_default():\n session_conf = tf.ConfigProto(\n allow_soft_placement=FLAGS.allow_soft_placement,\n log_device_placement=FLAGS.log_device_placement)\n sess = tf.Session(config=session_conf)\n print(\"started session\")\n with sess.as_default():\n if FLAGS.is_char_based:\n siameseModel = SiameseLSTM(\n sequence_length=max_document_length,\n vocab_size=len(vocab_processor.vocabulary_),\n embedding_size=FLAGS.embedding_dim,\n hidden_units=FLAGS.hidden_units,\n l2_reg_lambda=FLAGS.l2_reg_lambda,\n batch_size=FLAGS.batch_size\n )\n else:\n siameseModel = SiameseLSTMw2v(\n sequence_length=max_document_length,\n vocab_size=len(vocab_processor.vocabulary_),\n embedding_size=FLAGS.embedding_dim,\n hidden_units=FLAGS.hidden_units,\n l2_reg_lambda=FLAGS.l2_reg_lambda,\n batch_size=FLAGS.batch_size,\n trainableEmbeddings=trainableEmbeddings\n )\n # Define Training procedure\n global_step = tf.Variable(0, name=\"global_step\", trainable=False)\n print(siameseModel.accuracy)\n optimizer = tf.train.AdamOptimizer(1e-3)\n print(\"initialized siameseModel object\")\n \n grads_and_vars=optimizer.compute_gradients(siameseModel.loss)\n tr_op_set = optimizer.apply_gradients(grads_and_vars, global_step=global_step)\n print(\"defined training_ops\")\n # Keep track of gradient values and sparsity (optional)\n # grad_summaries = []\n # for g, v in grads_and_vars:\n # if g is not None:\n # grad_hist_summary = tf.summary.histogram(\"{}/grad/hist\".format(v.name), g)\n # sparsity_summary = tf.summary.scalar(\"{}/grad/sparsity\".format(v.name), tf.nn.zero_fraction(g))\n # grad_summaries.append(grad_hist_summary)\n # grad_summaries.append(sparsity_summary)\n # grad_summaries_merged = tf.summary.merge(grad_summaries)\n # print(\"defined gradient summaries\")\n # Output directory for models and summaries\n timestamp = str(int(time.time()))\n out_dir = os.path.abspath(os.path.join(os.path.curdir, \"runs\", timestamp))\n print(\"Writing to {}\\n\".format(out_dir))\n\n # Summaries for loss and accuracy\n loss_summary = tf.summary.scalar(\"loss\", siameseModel.loss)\n acc_summary = tf.summary.scalar(\"accuracy\", siameseModel.accuracy)\n\n # Train Summaries\n # train_summary_op = tf.summary.merge([loss_summary, acc_summary, grad_summaries_merged])\n # train_summary_dir = os.path.join(out_dir, \"summaries\", \"train\")\n # train_summary_writer = tf.summary.FileWriter(train_summary_dir, sess.graph)\n\n # Dev summaries\n # dev_summary_op = tf.summary.merge([loss_summary, acc_summary])\n # dev_summary_dir = os.path.join(out_dir, \"summaries\", \"dev\")\n # dev_summary_writer = tf.summary.FileWriter(dev_summary_dir, sess.graph)\n\n # Checkpoint directory. Tensorflow assumes this directory already exists so we need to create it\n checkpoint_dir = os.path.abspath(os.path.join(out_dir, \"checkpoints\"))\n checkpoint_prefix = os.path.join(checkpoint_dir, \"model\")\n if not os.path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n saver = tf.train.Saver(tf.global_variables(), max_to_keep=100)\n \n # my summary dir\n summary_dir = os.path.join(out_dir, \"summaries\")\n if not os.path.exists(summary_dir):\n os.makedirs(summary_dir)\n\n # Write vocabulary\n vocab_processor.save(os.path.join(checkpoint_dir, \"vocab\"))\n\n # Write ids_mapping\n pickle.dump(emb_map, open(os.path.join(checkpoint_dir + '/ids_mapping'), 'w'))\n\n # Initialize all variables\n sess.run(tf.global_variables_initializer())\n \n print(\"init all variables\")\n graph_def = tf.get_default_graph().as_graph_def()\n graphpb_txt = str(graph_def)\n with open(os.path.join(checkpoint_dir, \"graphpb.txt\"), 'w') as f:\n f.write(graphpb_txt)\n\n if FLAGS.word2vec_model :\n # initial matrix with random uniform\n initW = np.random.uniform(-0.25,0.25,(len(vocab_processor.vocabulary_), FLAGS.embedding_dim))\n #initW = np.zeros(shape=(len(vocab_processor.vocabulary_), FLAGS.embedding_dim))\n # load any vectors from the word2vec\n print(\"initializing initW with pre-trained word2vec embeddings\")\n for w in vocab_processor.vocabulary_._mapping:\n arr=[]\n s = re.sub('[^0-9a-zA-Z]+', '', w)\n if w in inpH.pre_emb:\n arr=inpH.pre_emb[w]\n elif w.lower() in inpH.pre_emb:\n arr=inpH.pre_emb[w.lower()]\n elif s in inpH.pre_emb:\n arr=inpH.pre_emb[s]\n elif s.isdigit():\n arr=inpH.pre_emb[\"zero\"]\n if len(arr)>0:\n idx = vocab_processor.vocabulary_.get(w)\n initW[idx]=np.asarray(arr).astype(np.float32)\n print(\"Done assigning intiW. len=\"+str(len(initW)))\n inpH.deletePreEmb()\n gc.collect()\n sess.run(siameseModel.W.assign(initW))\n\n def train_step(x1_batch, x2_batch, y_batch, epoch, batch):\n \"\"\"\n A single training step\n \"\"\"\n if random()>0.5:\n feed_dict = {\n siameseModel.input_x1: x1_batch,\n siameseModel.input_x2: x2_batch,\n siameseModel.input_y: y_batch,\n siameseModel.dropout_keep_prob: FLAGS.dropout_keep_prob,\n }\n else:\n feed_dict = {\n siameseModel.input_x1: x2_batch,\n siameseModel.input_x2: x1_batch,\n siameseModel.input_y: y_batch,\n siameseModel.dropout_keep_prob: FLAGS.dropout_keep_prob,\n }\n _, step, loss, accuracy, dist, sim = sess.run([tr_op_set, global_step, siameseModel.loss, siameseModel.accuracy, siameseModel.distance, siameseModel.temp_sim], feed_dict)\n time_str = datetime.datetime.now().isoformat()\n if batch*(epoch+1) % FLAGS.log_every == 0:\n print(\"TRAIN {}: epoch/step {}/{}, loss {:g}, f1 {:g}\".format(time_str, epoch, batch, loss, accuracy))\n #train_summary_writer.add_summary(summaries, step)\n # print(y_batch, dist, sim)\n return loss, accuracy\n\n def dev_step(x1_batch, x2_batch, y_batch, epoch, batch):\n \"\"\"\n A single training step\n \"\"\" \n if random()>0.5:\n feed_dict = {\n siameseModel.input_x1: x1_batch,\n siameseModel.input_x2: x2_batch,\n siameseModel.input_y: y_batch,\n siameseModel.dropout_keep_prob: 1.0,\n }\n else:\n feed_dict = {\n siameseModel.input_x1: x2_batch,\n siameseModel.input_x2: x1_batch,\n siameseModel.input_y: y_batch,\n siameseModel.dropout_keep_prob: 1.0,\n }\n step, loss, accuracy, sim = sess.run([global_step, siameseModel.loss, siameseModel.accuracy, siameseModel.temp_sim], feed_dict)\n time_str = datetime.datetime.now().isoformat()\n if batch*(epoch+1) % FLAGS.log_every == 0:\n print(\"DEV {}: epoch/batch {}/{}, loss {:g}, f1 {:g}\".format(time_str, epoch, batch, loss, accuracy))\n #dev_summary_writer.add_summary(summaries, step)\n return loss, accuracy\n\n # Generate batches\n # batches=inpH.batch_batch_iter(\n # list(zip(train_set[0], train_set[1], train_set[2])), 128, FLAGS.batch_size, FLAGS.num_epochs)\n\n train_batches = train_set\n dev_batches = dev_set\n ptr=0\n max_validation_f1=0.0\n stopping_step = 0\n best_loss = sys.float_info.max\n\n for epoch in xrange(FLAGS.num_epochs):\n start_time = time.time()\n\n current_step = tf.train.global_step(sess, global_step)\n losses = []\n f1s = []\n\n for nn in xrange(sum_no_of_batches):\n train_batch = train_batches.next()\n if len(train_batch)<1:\n continue\n x1_batch,x2_batch, y_batch = zip(*train_batch)\n if len(y_batch)<1:\n continue\n loss, f1 = train_step(x1_batch, x2_batch, y_batch, epoch, nn)\n losses.append(loss)\n f1s.append(f1)\n \n epoch_f1 = np.mean(np.nan_to_num(f1s))\n epoch_loss = np.mean(np.nan_to_num(losses))\n \n with open(os.path.join(summary_dir, 'train_summary'), 'a') as f:\n f.write('\\t'.join((str(epoch), str(epoch_loss), str(epoch_f1))) + '\\n')\n \n \n\n if epoch % FLAGS.evaluate_every == 0:\n losses = []\n f1s = []\n \n print(\"\\nEvaluation:\")\n for _ in xrange(dev_no_of_batches):\n dev_batch = dev_batches.next()\n if len(dev_batch)<1:\n continue\n x1_dev_b,x2_dev_b,y_dev_b = zip(*dev_batch)\n if len(y_dev_b)<1:\n continue\n loss, f1 = dev_step(x1_dev_b, x2_dev_b, y_dev_b, epoch, nn)\n losses.append(loss)\n f1s.append(f1)\n\n train_epoch_f1 = np.mean(np.nan_to_num(f1s))\n train_epoch_loss = np.mean(np.nan_to_num(losses))\n\n with open(os.path.join(summary_dir, 'dev_summary'), 'a') as f:\n f.write('\\t'.join((str(epoch), str(train_epoch_loss), str(train_epoch_f1))) + '\\n')\n \n if epoch % FLAGS.checkpoint_every == 0:\n if epoch_f1 >= max_validation_f1:\n max_validation_f1 = epoch_f1\n saver.save(sess, checkpoint_prefix, global_step=current_step)\n tf.train.write_graph(sess.graph.as_graph_def(), checkpoint_prefix, \"graph\"+str(epoch)+\".pb\", as_text=False)\n print(\"Saved model {} with sum_accuracy={} checkpoint to {}\\n\".format(nn, max_validation_f1, checkpoint_prefix))\n\n # early stopping\n if epoch_loss < best_loss:\n stopping_step = 0\n best_loss = epoch_loss\n else:\n stopping_step += 1\n if stopping_step >= FLAGS.patience:\n print(\"Early stopping is trigger at epoch: {} loss:{}\".format(epoch, epoch_loss))\n saver.save(sess, checkpoint_prefix, global_step=current_step)\n tf.train.write_graph(sess.graph.as_graph_def(), checkpoint_prefix, \"graph\"+str(epoch)+\".pb\", as_text=False)\n print(\"Saved model {} with sum_accuracy={} checkpoint to {}\\n\".format(epoch, max_validation_f1, checkpoint_prefix))\n exit(0)\n\n end_time = time.time()\n print('Time spent on epoch {}: {:.2f} seconds. TRAIN - loss: {:f}, f1: {:f} | DEV - loss: {:f}, f1: {:f}'.format(epoch, end_time-start_time, train_epoch_loss, train_epoch_f1, epoch_loss, epoch_f1))\n\n print(\"End of training.\")\n saver.save(sess, checkpoint_prefix, global_step=current_step)\n tf.train.write_graph(sess.graph.as_graph_def(), checkpoint_prefix, \"graph\" + str(epoch) + \".pb\", as_text=False)\n print(\"Saved model {} with sum_accuracy={} checkpoint to {}\\n\".format(nn, max_validation_f1, checkpoint_prefix))\n","repo_name":"MLRG-CEFET-RJ/plagdetect","sub_path":"lstm/my_train.py","file_name":"my_train.py","file_ext":"py","file_size_in_byte":15717,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"76"} +{"seq_id":"18500294038","text":"from otree.api import *\nfrom .choices import *\nfrom .constants import Constants\nimport json\nimport itertools\nimport random\nfrom math import copysign\n\n# TODO: remove proportions from methods\n# TODO: write down the logic of treatment\n# TODO: what to do with recipieints?\nf = lambda x: f'{(x / 100):.2f}$'\n\n\nclass Subsession(BaseSubsession):\n treatment = models.StringField()\n\n\ndef creating_session(subsession):\n subsession.treatment = subsession.session.config.get('name')\n orders = [False, True]\n partner_positions = itertools.cycle([False, True])\n\n for p in subsession.get_players():\n c = sorted(REVEAL_CHOICES, key=lambda x: x[0], reverse=random.choice(orders))\n p.reveal_order = json.dumps(c)\n p.partner_position = next(partner_positions)\n p.egoendowment = Constants.DICTATOR_ENDOWMENT\n p.alterendowment = Constants.BASIC_ENDOWMENT\n\n\nclass Group(BaseGroup):\n pass\n\n\ndef reveal_choices(player):\n return json.loads(player.reveal_order)\n\n\nclass Player(BasePlayer):\n # Main vars\n opinion_lgbt = models.BooleanField(choices=OPINION_CHOICES, widget=widgets.RadioSelectHorizontal, label='')\n partner_position = models.BooleanField()\n aligned = models.BooleanField()\n reveal = models.BooleanField()\n dg_decision = models.IntegerField(widget=widgets.RadioSelectHorizontal)\n payable = models.BooleanField()\n cq_err_counter = models.IntegerField(initial=0)\n blocked = models.BooleanField(initial=False)\n\n def html_dg_decision_choices(self):\n _choices = dg_decision_choices(self)\n res = []\n for i, j in enumerate(_choices):\n res.append(dict(id=i, value=j[0], label=j[1]))\n return res\n\n def cq_choices(self):\n return [dict(id=0, value=0, label='0$'),\n dict(id=1, value=50, label='0.50$'),\n dict(id=2, value=100, label='1.00$'),\n dict(id=3, value=150, label='1.50$'), ]\n\n def payoff_table(self):\n conv_ = {-1: 'Взять', 0: 'Оставить без изменений', 1: 'Отдать'}\n\n def conv(v):\n if v == 0:\n return conv_[0]\n return conv_[copysign(1, v)]\n\n _choices = dg_decision_choices(self)\n\n res = []\n for i in _choices:\n res.append(dict(decision=i[1], ego=f(Constants.DICTATOR_ENDOWMENT - i[0]),\n alter=f(Constants.BASIC_ENDOWMENT + i[0]),\n label=conv(i[0])))\n return res\n\n def get_partner_opinion(self):\n return 'СОГЛАСИЛСЯ' if self.partner_position else 'НЕ СОГЛАСИЛСЯ'\n\n @property\n def reverted_opinion(self):\n try:\n return 'не согласны' if (self.opinion_lgbt) else 'согласны'\n except TypeError:\n # just for debugging\n return 'не согласны'\n\n def reverted_opinion_single(self):\n try:\n return 'не согласен' if (self.opinion_lgbt) else 'согласен'\n except TypeError:\n # just for debugging\n return 'не согласен'\n\n opinion_competition = models.BooleanField(choices=OPINION_CHOICES, widget=widgets.RadioSelectHorizontal,\n label='')\n\n opinion_covid = models.BooleanField(choices=OPINION_CHOICES, widget=widgets.RadioSelectHorizontal, label='')\n\n risk_general = models.IntegerField()\n risk_financial_matters = models.IntegerField()\n risk_free = models.IntegerField()\n risk_profession = models.IntegerField()\n risk_health = models.IntegerField()\n risk_strangers = models.IntegerField()\n risk_driving = models.IntegerField()\n sdi_politics = models.StringField()\n sdi_neighbors = models.StringField()\n sdi_friends = models.StringField()\n sdi_family = models.StringField()\n scs_habits = models.IntegerField()\n scs_why = models.IntegerField()\n scs_conversation = models.IntegerField()\n scs_listening = models.IntegerField()\n scs_quarrel = models.IntegerField()\n ias_friend = models.StringField()\n ias_coworker = models.StringField()\n ias_stranger = models.StringField()\n # REASONS\n reason_dg = models.LongStringField(\n label='Вспомните, пожалуйста, свое решение о том отдавать или брать деньги у участника Б, с которым вы были в паре. Чем вы руководствовались при принятии вашего решения?')\n keyword_dg_1 = models.StringField()\n keyword_dg_2 = models.StringField()\n keyword_dg_3 = models.StringField()\n reason_reveal = models.LongStringField(\n label=\"\"\"Вспомните, пожалуйста, ваше решение относительно того, узнавать или не узнавать ответ участника Б. Чем вы руководствовались при принятии вашего решения?\"\"\")\n keyword_rev_1 = models.StringField()\n keyword_rev_2 = models.StringField()\n keyword_rev_3 = models.StringField()\n # Comprehension questions\n cq1_ego = models.IntegerField(label=Constants.CQ_EGO_LABEL, choices=CQ_CHOICES,\n widget=widgets.RadioSelectHorizontal)\n cq1_alter = models.IntegerField(label=Constants.CQ_ALTER_LABEL, choices=CQ_CHOICES,\n widget=widgets.RadioSelectHorizontal)\n cq2_ego = models.IntegerField(label=Constants.CQ_EGO_LABEL, choices=CQ_CHOICES,\n widget=widgets.RadioSelectHorizontal)\n cq2_alter = models.IntegerField(label=Constants.CQ_ALTER_LABEL, choices=CQ_CHOICES,\n widget=widgets.RadioSelectHorizontal)\n cq3_ego = models.IntegerField(label=Constants.CQ_EGO_LABEL, choices=CQ_CHOICES,\n widget=widgets.RadioSelectHorizontal)\n cq3_alter = models.IntegerField(label=Constants.CQ_ALTER_LABEL, choices=CQ_CHOICES,\n widget=widgets.RadioSelectHorizontal)\n\n # other main variables\n reveal_order = models.StringField()\n egoendowment = models.IntegerField()\n alterendowment = models.IntegerField()\n # BELIEFS:\n reveal_belief = models.IntegerField(min=0, max=100)\n dg_belief_ra = models.IntegerField()\n dg_belief_rb_nonrev = models.IntegerField()\n dg_belief_rb_rev_diff = models.IntegerField()\n dg_belief_rb_rev_same = models.IntegerField()\n dg_belief_fr_diff = models.IntegerField()\n dg_belief_fr_same = models.IntegerField()\n proportion = models.IntegerField(min=0, max=100, label='')\n # DEMOGRAPHICS\n religion = models.IntegerField(label=\"\"\"\n Насколько сильно вы верите в существование Бога? (укажите свой ответ в диапазоне от 1 = совсем нет 5 = очень сильно)\n \"\"\", choices=range(1, 6), widget=widgets.RadioSelectHorizontal)\n political = models.IntegerField(label=\"\"\"\n Ниже представлена 7-балльная шкала, на которой политические взгляды, которых могут придерживаться люди, расположены от крайне либеральных (слева) до крайне конс��рвативных (справа). Куда бы вы поставили себя на этой шкале?\n \"\"\", choices=range(0, 8), widget=widgets.RadioSelectHorizontal)\n age = models.StringField(label='Укажите ваш возраст:', choices=AGE_CHOICES, widget=widgets.RadioSelect)\n education = models.StringField(\n label=\"Какой самый высокий уровень школы вы закончили или какую высшую степень вы получили?\",\n choices=EDUCATION_CHOICES, widget=widgets.RadioSelect)\n gender = models.StringField(label='Укажите ваш пол:',\n choices=GENDER_CHOICES, widget=widgets.RadioSelect)\n marital = models.StringField(label='В настоящий момент вы:',\n choices=MARITAL_CHOICES, widget=widgets.RadioSelect)\n employment = models.StringField(label='В настоящий момент вы:',\n choices=EMPLOYMENT_CHOICES, widget=widgets.RadioSelect)\n income = models.StringField(\n label=\"Какое высказывание наиболее точно описывает финансовое положение вашей семьи?\",\n choices=INCOME_CHOICES,\n widget=widgets.RadioSelect()\n )\n # Demand and clarity\n demand = models.LongStringField()\n instructions_clarity = models.IntegerField(label=\"\"\"\n Насколько понятными и ясными были для вас инструкции? (укажите свой ответ в диапазоне от 1 = совсем непонятны 5 = абсолютно понятны)\n \"\"\", choices=range(1, 6), widget=widgets.RadioSelectHorizontal)\n\n\ndef dg_decision_choices(player):\n ints = list(range(-50, 51, 10))\n\n return [(i, f(i)) for i in ints]\n\n\ndef cq1_ego_error_message(player, value):\n if value != 50:\n return Constants.ERR_MSG\n\n\ndef cq1_alter_error_message(player, value):\n if value != 100:\n return Constants.ERR_MSG\n\n\ndef cq2_ego_error_message(player, value):\n if value != 100:\n return Constants.ERR_MSG\n\n\ndef cq2_alter_error_message(player, value):\n if value != 50:\n return Constants.ERR_MSG\n\n\ndef cq3_ego_error_message(player, value):\n if value != 150:\n return Constants.ERR_MSG\n\n\ndef cq3_alter_error_message(player, value):\n if value != 0:\n return Constants.ERR_MSG\n","repo_name":"chapkovski/polarization","sub_path":"polar/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":9861,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"29440572386","text":"import pymysql\n\nhost = \"127.0.0.1\"\nport = 3306\nusername = \"root\"\npassword = \"root\"\ndatabase = \"crew1\"\n\n\nclass ConnMysql(object):\n\n def __init__(self):\n self.conn = pymysql.Connect(host=host, port=port, user=username, password=password, database=database)\n self.cursor = self.conn.cursor()\n\n def exAndCom(self, sql):\n self.cursor.execute(sql)\n self.conn.commit()\n\n def innsert(self, **kwargs):\n id_ = kwargs.get(\"id\")\n name = kwargs.get(\"name\")\n detail = kwargs.get(\"detail\")\n path = kwargs.get(\"path\")\n sql = str.format(\"insert into info1(id, name, detail, path) value ({0}, {1}, {2}, {3})\", id_, name, detail, path)\n self.exAndCom(sql)\n\n def delete(self, id_):\n sql = str.format(\"delete from info1 where id = {0}\", id_)\n self.exAndCom(sql)\n\n def update(self, **kwargs):\n sql = \"update info1 set \"\n if kwargs.get(\"id\") is None:\n return\n i = 0\n for k, v in kwargs.items():\n i += 1\n if k != \"id\":\n if i == len(kwargs):\n sql = str.format(\"{0}{1}={2}\", sql, k, v)\n else:\n sql = str.format(\"{0}{1}={2},\", sql, k, v)\n sql += str.format(\" where id={0}\", kwargs.get(\"id\"))\n self.exAndCom(sql)\n\n def query(self, **kwargs):\n sql = \"select * from info1\"\n if len(kwargs) > 0:\n flag = True\n sql += \" where\"\n for k, v in kwargs.items():\n if flag:\n flag = False\n sql = str.format(\" {0} {1}={2}\", sql, k, v)\n else:\n sql = str.format(\"{0} and {1} = {2}\", sql, k, v)\n self.cursor.execute(sql)\n return self.cursor\n\n\ndef main():\n map = {\n \"id\": 1,\n \"name\": 2,\n \"detail\": 23,\n \"path\": 234\n }\n mapU = {\n \"id\": 1,\n \"name\": 222,\n \"detail\": 222,\n \"path\": 222\n }\n conn = ConnMysql()\n conn.innsert(**map)\n conn.update(**mapU)\n print(\"--------add after----------\")\n for c in conn.query():\n print(c)\n conn.delete(1)\n print(\"--------delete after-------\")\n for c in conn.query():\n print(c)\n\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"zhangwei19910109/zwpython","sub_path":"connMysql.py","file_name":"connMysql.py","file_ext":"py","file_size_in_byte":2299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"21483035978","text":"#!/usr/bin/python3\n\nimport sys\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nuser_data_url = 'https://si3.ufc.br/public/restauranteConsultarSaldo.do'\nmenu_url = 'http://www.ufc.br/restaurante/cardapio/1-restaurante-universitario-de-fortaleza'\ndata = {\n 'codigoCartao': sys.argv[1],\n 'matriculaAtreladaCartao': sys.argv[2]\n}\n\ndef convert_to_dict(list_):\n \"\"\"\n Converts a list into a dict, eg:\n ['a', 1, 'b', 2] -> {'a': 1, 'b': 2}\n\n Args:\n list_: a list to be converted\n \"\"\"\n it = iter( list_ )\n \n return dict( zip(it,it) )\n\ndef print_user_credits(r):\n \"\"\"\n Extracts the username and the amount of credits in the card\n\n Args:\n r: a requests.models.Response\n \"\"\"\n \n raw_data = BeautifulSoup( r.text, 'html.parser' )\n raw_data.find( 'tbody' ).text\n\n user_info = raw_data.find( 'tbody' ).text.split('\\n')\n \n # Removing empty strings from the list\n user_info = [ no_empty_str for no_empty_str in user_info if no_empty_str ]\n\n info_dict = convert_to_dict( user_info )\n\n print( \"Usuário: {}\\nCréditos: {}\\n\".format(\n info_dict.get( 'Nome:','Indisponível' ), info_dict.get( 'Créditos:','Indisponível' ) ))\n\ndef print_menu(r):\n \"\"\"\n Get the menu of the day\n\n Args:\n r: a requests.models.Response\n \"\"\"\n\n raw_data = BeautifulSoup( r.text, 'html.parser' )\n almoco = raw_data.find( class_='refeicao almoco' ).find_all( class_='desc' )\n jantar = raw_data.find( class_='refeicao jantar' ).find_all( class_='desc' )\n\n print( 'Cardápio:' )\n print( ' Almoço: ')\n for item in almoco:\n print( ' ', item.text )\n \n print( ' Jantar' )\n for item in jantar:\n print( ' ', item.text )\n\ntry:\n r = requests.post( user_data_url, data=data )\n print_user_credits( r )\n\nexcept requests.exceptions.ConnectionError as e:\n print( e )\n print( 'Erro ao tentar obter a quantidade de créditos do usuário.' )\n\ntry:\n r = requests.get( menu_url )\n print_menu( r )\n\nexcept requests.exceptions.ConnectionError:\n print( 'Erro ao tentar obter o cardápio do dia.' ) \n","repo_name":"alvesRenan/extratoRU","sub_path":"extrato_ru.py","file_name":"extrato_ru.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"31321385495","text":"\"\"\"\n 2. Посчитать четные и нечетные цифры введенного натурального числа.\n Например, если введено число 34560, в нем 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5).\n\"\"\"\n\n\ndef nut_num(into, reg=0, irreg=0):\n if (into % 10) % 2 == 0:\n reg += 1\n else:\n irreg += 1\n if len(str(into)) > 1:\n into = into // 10\n return nut_num(into, reg, irreg)\n else:\n return f'Чётных: {reg}, нечётных {irreg}'\n\n\nprint(nut_num(int(input('Введите натуральное число: '))))\n","repo_name":"TheMacte/Py","sub_path":"lesson_2/task_2.py","file_name":"task_2.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"43248732436","text":"\"\"\"https://www.codewars.com/kata/5a03af9606d5b65ff7000009/train/python\"\"\"\n\n\nclass User(object):\n def __init__(self, name, balance, checking_account):\n self.name = name\n self.balance = balance\n self.checking_account = checking_account\n\n def withdraw(self, money):\n if money > self.balance:\n raise ValueError()\n self.balance -= money\n return f\"{self.name} has {self.balance}.\"\n\n def check(self, user_name, vol_money):\n if user_name.checking_account and user_name.balance > vol_money:\n self.balance += vol_money\n user_name.balance -= vol_money\n return f\"{self.name} has {self.balance} and {user_name.name} has {user_name.balance}.\"\n raise ValueError()\n\n def add_cash(self, vol_cash):\n self.balance += vol_cash\n return f\"{self.name} has {self.balance}.\"\n\n\nJeff = User('Jeff', 70, True)\nJoe = User('Joe', 70, True)\n\nprint(Jeff.withdraw(50))\nprint(Joe.check(Jeff, 50))\nprint(Jeff.check(Joe, 80))\nprint(Joe.checking_account)\nprint(Jeff.check(Joe, 80))\nprint(Joe.check(Jeff, 100))\nprint(Jeff.add_cash(20.00))","repo_name":"Anfibik/CodeWars","sub_path":"OOP_Kata/Kata_9_7kyuOOP.py","file_name":"Kata_9_7kyuOOP.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"3522239538","text":"import matplotlib.pyplot as plt\n#from matplotlib.axis import Ticker\nimport streamlit as st \nimport requests \nimport simfin as sf\nimport pandas as pd\nimport numpy as np\nfrom simfin.names import *\n\nst.set_page_config(layout=\"wide\")\n\nsf.set_data_dir('~/simfin_data/')\n\nsf.set_api_key(api_key=\"enter API key\")\n\nsymbol = st.sidebar.text_input (\"Symbol\", value = \"MSFT\")\n\nscreen = st.sidebar.selectbox (\"View\", (\"Company info\", \"Income statement\", \"Balance sheet\", \"Cash flow statement\"))\n\n#st.title(symbol + ' ' + screen)\n\n#if screen == \"Company info\":\n #col1, col2, col3 = st.columns([3,4,3])\n #with col2:\n #st.title(symbol + ' ' + screen)\n\n #col1, col2 = st.columns ([1,2])\n #with col1:\n\n #df_company = sf.load_companies(market='us', index= ['Ticker'])\n\n #df_shareprices = sf.load_shareprices(variant='daily', market='us', index= ['Ticker', DATE])\n\n #st.markdown(\"

Info

\", unsafe_allow_html=True)\n\n #st.subheader ('Company name')\n #df_company.loc [symbol] [COMPANY_NAME]\n\n #df_price_ratios = sf.load_derived_shareprices(variant='daily', market='us', index= ['Ticker', DATE])\n\n #st.subheader ('Market-Cap')\n #df_banaan = df_price_ratios.loc [symbol] [MCAP] \n #df_banaan.loc ['2022-03-14']\n\n #st.subheader ('P/E Ratio')\n #df_pe_today = df_price_ratios.loc [symbol] [PE_QUARTERLY]\n #df_pe_today.loc ['2022-03-14']\n\n\n #with col2:\n\n #df_shareprices = df_shareprices.loc [symbol]\n\n #st.markdown(\"

Share price

\", unsafe_allow_html=True)\n\n # st.line_chart(df_shareprices [SHARE_PRICE_CLOSE])\n\n\n #st.markdown(\"

Some title

\", unsafe_allow_html=True)\n\nif screen == \"Income statement\":\n col1, col2, col3 = st.columns([3,4,3])\n with col2:\n st.title(symbol + ' ' + screen)\n df_income = sf.load_income(variant='annual', market='us', index=['Ticker', FISCAL_YEAR])\n df_income2 = df_income.loc [symbol][[REVENUE, COST_REVENUE, GROSS_PROFIT, OPERATING_EXPENSES, SELLING_GEN_ADMIN\n,RESEARCH_DEV\n,DEPR_AMOR, OP_INCOME\n,NON_OP_INCOME\n,INTEREST_EXP_NET\n, PRETAX_INCOME_LOSS_ADJ\n,ABNORM_GAIN_LOSS,PRETAX_INCOME_LOSS, \nINCOME_TAX,INCOME_CONT_OP, NET_EXTR_GAIN_LOSS\n, NET_INCOME]]\n\n df_tr_income = df_income2.transpose()\n\n df_income_done = df_tr_income[df_tr_income.columns[::-1]]\n\n df_income_done\n\n col1, col2, col3 = st.columns([3,2,7])\n\n with col1:\n st.markdown(\"

Select

\", unsafe_allow_html=True)\n\n select = st.multiselect ( 'Type something', ['Revenue', 'Gross profit', 'Net income'], ['Revenue'])\n\n with col2:\n pass\n\n\n with col3:\n if select == ['Revenue']:\n st.markdown(\"

Revenue

\", unsafe_allow_html=True)\n st.bar_chart(df_income_done.loc [REVENUE])\n\n if select == ['Gross profit']:\n st.markdown(\"

Gross profit

\", unsafe_allow_html=True)\n st.bar_chart(df_income_done.loc [GROSS_PROFIT])\n\n if select == ['Net income']:\n st.markdown(\"

Net income

\", unsafe_allow_html=True)\n st.bar_chart(df_income_done.loc [NET_INCOME])\n\n if select == ['Revenue', 'Net income']:\n st.markdown(\"

Revenue

\", unsafe_allow_html=True)\n st.bar_chart(df_income_done.loc [REVENUE])\n st.markdown(\"

Net income

\", unsafe_allow_html=True)\n st.bar_chart(df_income_done.loc [NET_INCOME])\n\n\n\nif screen == \"Balance sheet\":\n col1, col2, col3 = st.columns([3,4,3])\n with col2:\n st.title(symbol + ' ' + screen)\n df_balance = sf.load_balance(variant='annual', market='us', index=['Ticker', 'Fiscal Year']) \n df_balance = df_balance.loc [symbol] [[CASH_EQUIV_ST_INVEST\n, ACC_NOTES_RECV,INVENTORIES, TOTAL_CUR_ASSETS\n, PROP_PLANT_EQUIP_NET, LT_INVEST_RECV, OTHER_LT_ASSETS, TOTAL_NONCUR_ASSETS, TOTAL_ASSETS, PAYABLES_ACCRUALS\n, ST_DEBT, TOTAL_CUR_LIAB\n, LT_DEBT, TOTAL_NONCUR_LIAB, TOTAL_LIABILITIES, SHARE_CAPITAL_ADD, TREASURY_STOCK, RETAINED_EARNINGS, TOTAL_EQUITY, TOTAL_LIAB_EQUITY]]\n\n df_tr_balance = df_balance.transpose()\n\n df_tr_balance[df_tr_balance.columns[::-1]]\n\n col1, col2, col3 = st.columns([3,2,7])\n with col1:\n st.markdown(\"

Select

\", unsafe_allow_html=True)\n\n select_balance = st.selectbox (\"Select\", (\"Total assets\", \"Total liabilities\", \"Shareholders equity\"))\n\n with col2:\n pass\n\n\n with col3:\n if select_balance == 'Total assets':\n st.markdown(\"

Total assets

\", unsafe_allow_html=True)\n st.bar_chart(df_tr_balance.loc [TOTAL_ASSETS])\n\n if select_balance == 'Total liabilities':\n st.markdown(\"

Total liabilities

\", unsafe_allow_html=True)\n st.bar_chart(df_tr_balance.loc [TOTAL_LIABILITIES])\n\n if select_balance == 'Shareholders equity':\n st.markdown(\"

Shareholders equity

\", unsafe_allow_html=True)\n st.bar_chart(df_tr_balance.loc [TOTAL_EQUITY])\n\n\n\n\nif screen == \"Cash flow statement\":\n col1, col2, col3 = st.columns([3,4,3])\n with col2:\n st.title(symbol + ' ' + screen)\n df_cashflow = sf.load_cashflow(variant='annual', market='us', index= [ 'Ticker', 'Fiscal Year'])\n df_cashflow = df_cashflow.loc [symbol] [[NET_INCOME_START, DEPR_AMOR, NON_CASH_ITEMS, CHG_WORKING_CAPITAL, CHG_ACCOUNTS_RECV, CHG_INVENTORIES, CHG_ACC_PAYABLE, CHG_OTHER, NET_CASH_OPS, CHG_FIX_ASSETS_INT, NET_CHG_LT_INVEST, NET_CASH_ACQ_DIVEST, NET_CASH_INV, DIVIDENDS_PAID, CASH_REPAY_DEBT, CASH_REPURCHASE_EQUITY, NET_CASH_FIN, NET_CHG_CASH]]\n\n df_tr_cashflow = df_cashflow.transpose ()\n\n df_tr_cashflow[df_tr_cashflow.columns[::-1]]\n\n col1, col2, col3 = st.columns([3,2,7])\n with col1:\n st.markdown(\"

Select

\", unsafe_allow_html=True)\n\n select_cashflow = st.selectbox (\"Select\", (\"Net change in cash\", \"Net cash from operating activities\", \"Net income\"))\n\n with col2:\n pass\n\n\n with col3:\n if select_cashflow == 'Net change in cash':\n st.markdown(\"

Net change in cash

\", unsafe_allow_html=True)\n st.bar_chart(df_tr_cashflow.loc [NET_CHG_CASH])\n\n if select_cashflow == 'Net cash from operating activities':\n st.markdown(\"

Net cash from operating activitiess

\", unsafe_allow_html=True)\n st.bar_chart(df_tr_cashflow.loc [NET_CASH_OPS])\n\n if select_cashflow == 'Net income':\n st.markdown(\"

Net income

\", unsafe_allow_html=True)\n st.bar_chart(df_tr_cashflow.loc [NET_INCOME_START])\n","repo_name":"valueinvestorr/us-stock-data","sub_path":"dashboard.py","file_name":"dashboard.py","file_ext":"py","file_size_in_byte":6917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"15584336661","text":"import pandas as pd\n\nfrom research_tools import trading\nfrom research_tools import behavior\nfrom research_tools import storage\nfrom research_tools import reconstruct_tob\nfrom research_tools import dominant_contracts\nfrom research_tools import trader_efficiency\n\n\nprint('load data from data directory')\norders_dem = pd.read_csv('data/dem_iowa_caucus_orders.csv', index_col=0)\ntrades_dem = pd.read_csv('data/dem_iowa_caucus_trades.csv', index_col=0)\n\norders_dem.date_created = pd.to_datetime(orders_dem.date_created).dt.tz_localize('UTC').dt.tz_convert('US/Eastern')\ntrades_dem.date_executed = pd.to_datetime(trades_dem.date_executed).dt.tz_localize('UTC').dt.tz_convert('US/Eastern')\n\nprint(\"analyze DEM trader pnl\")\ntrader_analysis_dem = trading.trader_analysis(orders_dem, trades_dem)\nprint(\"generate DEM taq\")\nreconstructed_quotes_dem = reconstruct_tob.generate_quotes(trades_dem)\nprint(\"calculate DEM replicating contract prices\")\nreplicating_contracts_dem = dominant_contracts.calculate_replicating_prices(\n trader_analysis_dem, reconstructed_quotes_dem)\nprint(\"calculate DEM trader efficiency\")\ntrader_efficiency_dem = trader_efficiency.calculate_trader_efficiency(\n trader_analysis_dem,\n replicating_contracts_dem['yes contracts spreads and fees'],\n replicating_contracts_dem['no contracts spreads and fees'],\n 10)\nprint(\"analyze DEM trader behavior\")\nbehavior_analysis_dem = behavior.behavior_analysis(\n trader_analysis_dem, trader_efficiency_dem)\n\nprint(\"storing DEM data\")\nbasename = 'dem'\nstorage.save_all(\n [(basename + '.orders', orders_dem),\n (basename + '.trades', trades_dem),\n (basename + '.trader_analysis', trader_analysis_dem),\n (basename + '.behavior_analysis', behavior_analysis_dem),\n (basename + '.reconstructed_quotes', reconstructed_quotes_dem),\n (basename + '.replicating_contracts', replicating_contracts_dem),\n (basename + '.trader_efficiency', trader_efficiency_dem)])\n","repo_name":"hx2A/predictit_plos_one","sub_path":"scripts/iowa_dem_caucuses.py","file_name":"iowa_dem_caucuses.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"76"} +{"seq_id":"33875863221","text":"def make_DF_minmaxasc():\n import os\n import glob\n import sys\n import numpy as np\n file_list = glob.glob(\"*\")\n if \"output_DF_asc\" in file_list:\n tdir = os.path.join(os.getcwd(), \"output_DF_asc\")\n else:\n os.mkdir(os.path.join(os.getcwd(), \"output_DF_asc\"))\n tdir = os.path.join(os.getcwd(), \"output_DF_asc\")\n print(\"DF out @ [dz, cc]\")\n ls='\\n'\n sdir = os.path.join(os.getcwd(), \"output_DF\")\n files_dz=glob.glob(os.path.join(sdir,'res_dz_??????????.asc'))\n files_dz.sort()\n files_cc=glob.glob(os.path.join(sdir,'res_cc_??????????.asc'))\n files_cc.sort()\n #\n fn=files_dz[0]\n head=open(fn).read().split(ls)[:6]\n ncols=int(head[0].split()[1])\n nrows=int(head[1].split()[1])\n xllcorner=float(head[2].split()[1])\n yllcorner=float(head[3].split()[1])\n dx=float(head[4].split()[1])\n dy=dx\n head[5] = head[5].replace(\"NODATA_value -9999.000\", \"NODATA_value 0.0\")\n head=ls.join(head)\n #\n dzmin = np.zeros((nrows,ncols))\n dzmax = np.zeros((nrows,ncols))\n ccmax = np.zeros((nrows,ncols))\n #\n for i in range(len(files_dz)):\n dz = np.loadtxt(files_dz[i],skiprows=6)\n dzmax = np.maximum(dzmax, dz)\n dzmin = np.minimum(dzmin, dz)\n cc = np.loadtxt(files_cc[i],skiprows=6)\n ccmax = np.maximum(ccmax, cc)\n #\n np.savetxt(os.path.join(tdir,'dzmax_inDF.asc'),dzmax,fmt='%7.2f',header=head,comments='')\n np.savetxt(os.path.join(tdir,'dzmin_inDF.asc'),dzmin,fmt='%7.2f',header=head,comments='')\n np.savetxt(os.path.join(tdir,'ccmax_inDF.asc'),ccmax,fmt='%7.2f',header=head,comments='')\n #\n # rearrange .asc files in output_DF \n # revise NODATA_value and copy\n names = [\"rain_map.asc\", \"rain_sum.asc\", \"res_hmax.asc\", \"res_hsmax.asc\"]\n for name in names:\n data = np.loadtxt(os.path.join(sdir, name), skiprows=6)\n if name == \"rain_map.asc\":\n name = \"mask.asc\"\n np.savetxt(os.path.join(tdir,name),data,fmt='%7.2f',header=head,comments='')\n\n\nimport argparse\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--version\", version=\"%(prog)s 1.0.0\",\n action=\"version\",\n default=False)\nargs = parser.parse_args()\n\ntry:\n make_DF_minmaxasc()\nexcept Exception as e:\n import sys, traceback\n print(traceback.format_exc())\n sys.exit(-1)\n","repo_name":"PWRI-volcano-debrisflow-team/DFSS","sub_path":"13_Furuegawa_flattenDir/bin_fig/DF_map_asc.py","file_name":"DF_map_asc.py","file_ext":"py","file_size_in_byte":2361,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"16968761299","text":"import tensorflow as tf\nimport numpy as np\nfrom numpy import *\nimport yaml\nimport os\n\nimport matplotlib.pyplot as plt\nplt.rcParams.update({'font.size': 22})\n\nfrom matplotlib.patches import FancyArrowPatch\nfrom mpl_toolkits.mplot3d import proj3d\n\nimport scipy.signal\nfrom scipy.spatial.transform import Rotation as R\n\ndtype = tf.float32\n#dtype = tf.float64\nnpdtype = np.float32\n#npdtype = np.float64\n\ncontrol_items: dict = {}\ncontrol_step = 0\n\n\nclass Arrow3D(FancyArrowPatch):\n def __init__(self, xs, ys, zs, *args, **kwargs):\n FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)\n self._verts3d = xs, ys, zs\n\n def draw(self, renderer):\n xs3d, ys3d, zs3d = self._verts3d\n xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)\n self.set_positions((xs[0],ys[0]),(xs[1],ys[1]))\n FancyArrowPatch.draw(self, renderer)\n\n\ndef assert_shape(array, shape):\n ashape = array.shape\n if len(ashape) != len(shape):\n return False\n for i, j in zip(ashape, shape):\n if j != -1 and i != j:\n return False\n return True\n\n\ndef parse_config(file):\n with open(file) as file:\n conf = yaml.load(file, Loader=yaml.FullLoader)\n return conf\n\n\ndef list_files(log_dir):\n for file in os.listdir(log_dir):\n if os.path.isfile(os.path.join(log_dir, file)):\n yield file\n\n\ndef parse_dir(log_dir):\n for file in list_files(log_dir):\n if file == \"config.yaml\":\n config_file = os.path.join(log_dir, file)\n elif file == \"task.yaml\":\n task_file = os.path.join(log_dir, file)\n return parse_config(config_file), task_file\n\n\ndef plt_sgf(action_seq):\n print(action_seq.numpy()[:, :, 0].shape)\n _ = plt.figure()\n ax1 = plt.subplot(121)\n ax2 = plt.subplot(122)\n\n for i in np.arange(9, 49, 4):\n y = scipy.signal.savgol_filter(action_seq.numpy()[:, :, 0], i, 7,\n deriv=0, delta=1.0, axis=0)\n ax1.plot(y[:, 0], label=\"{}\".format(i))\n ax2.plot(y[:, 1], label=\"{}\".format(i))\n plt.legend()\n plt.show()\n\n\ndef plt_paths(paths, weights, noises, action_seq, cost):\n global control_step\n n_bins = 100\n best_idx = np.argmax(weights)\n # todo extract a_sape from tensor\n noises = noises.numpy().reshape(-1, 2)\n\n _ = plt.figure()\n ax1 = plt.subplot(333)\n ax2 = plt.subplot(336)\n ax3 = plt.subplot(221)\n ax4 = plt.subplot(337)\n ax5 = plt.subplot(338)\n ax6 = plt.subplot(339)\n # We can set the number of bins with the `bins` kwarg\n ax1.set_xlim(-1.5, 1.5)\n ax1.set_ylim(-0.1, 2)\n ax1.hist(noises[:, 0], bins=n_bins, density=True)\n\n ax2.set_xlim(-1.5, 1.5)\n ax2.set_ylim(-0.1, 2)\n ax2.hist(noises[:, 1], bins=n_bins, density=True)\n\n ax3.set_ylim(-5, 5)\n ax3.set_xlim(-5, 5)\n for _, sample in enumerate(paths):\n ax3.plot(sample[:, 0], sample[:, 2], \"-b\")\n ax3.plot(paths[best_idx, :, 0], paths[best_idx, :, 2], \"-r\")\n\n gx, gy = cost.draw_goal()\n ax3.scatter(gx, gy, c=\"k\")\n\n ax4.set_xlim(-1, 60)\n ax4.set_ylim(-0.3, 0.3)\n ax4.plot(action_seq[:, 0])\n\n ax5.set_xlim(-1, 60)\n ax5.set_ylim(-0.3, 0.3)\n ax5.plot(action_seq[:, 1])\n\n # ax6.set_xlim(-0.1, 1.1)\n ax6.plot(weights.numpy().reshape(-1))\n\n plt.savefig('/tmp/mppi_{}.png'.format(control_step-1))\n plt.close(\"all\")\n\n\ndef push_to_tensor(tensor, element):\n tmp = tf.expand_dims(element, axis=1) # shape [k, 1, dim, 1]\n return tf.concat([tensor[:, 1:], tmp], axis=1)\n\n\ndef plot_traj(trajs, seq=None, plotStateCols=None, plotActionCols=None, title=\"Traj\", dir=\".\", filename=None):\n '''\n Plot trajectories and action sequence.\n inputs:\n -------\n - trajs: dict with model name as key and trajectories entry. If key is \"gt\" then it is assumed to be\n the ground truth trajectory.\n - seq: Action Sequence associated to the generated trajectoires. If not None, plots the \n action seqence.\n - histories: list of history used for the different models, ignored when model entry is \"gt\".\n - frequencies: list of history used for the different models, ignored when model entry is \"gt\".\n - plotStateCols: Dict containing the state axis name as key and index as entry\n - plotAcitonCols: Dict containing the action axis name as key and index as entry.\n - title: String the name of fthe figure.\n - horizon: The horizon of the trajectory to plot.\n - dir: The saving directory for the generated images.\n '''\n maxS = len(plotStateCols)\n maxA = len(plotActionCols)\n # fig_state = plt.figure(figsize=(50, 50))\n fig, axes = plt.subplots(6, 2, figsize=(50, 50))\n fig.suptitle(title)\n for k in trajs:\n t, h, freq, tau = trajs[k]\n for i, name in enumerate(plotStateCols):\n m, n = np.unravel_index(i, (2, 6))\n #idx = 1*m + 2*n + 1\n axes[n, m].set_ylabel(f'{name}')\n if k == \"gt\":\n time_steps = np.linspace(0., freq*tau, tau)\n axes[n, m].plot(time_steps, t[:tau, plotStateCols[name]],\n marker='.', zorder=-10, label=k)\n else:\n time_steps = np.linspace(0, freq*(tau+h), (tau+h))\n axes[n, m].plot(time_steps, t[:, plotStateCols[name]],\n marker='X', label=k\n )\n plt.legend()\n #plt.tight_layout()\n if dir is not None:\n name = os.path.join(dir, f\"{filename}.png\")\n plt.savefig(name)\n plt.close()\n\n if seq is not None:\n fig_act = plt.figure(figsize=(30, 30))\n for i, name in enumerate(plotActionCols):\n plt.subplot(maxA, 1, i+1)\n plt.ylabel(f'{name}')\n plt.plot(seq[0, :horizon+h, plotActionCols[name]])\n\n #plt.tight_layout()\n if dir is not None:\n name = os.path.join(dir, f\"{filename}-actions.png\")\n plt.savefig(name)\n plt.close()\n \n plt.show()\n\n\ndef plot_6d(trajs, ColNames=None, title=\"Foo\", dir=\".\", filename=None):\n '''\n Plot trajectories and action sequence.\n inputs:\n -------\n - trajs: dict with model name as key and entries being [traj, delta t, steps]. If key is \"gt\" then it is assumed to be\n the ground truth trajectory.\n - seq: Action Sequence associated to the generated trajectoires. If not None, plots the \n action seqence.\n - plotStateCols: Dict containing the state axis name as key and index as entry\n - plotAcitonCols: Dict containing the action axis name as key and index as entry.\n - dir: The saving directory for the generated images.\n '''\n maxS = len(ColNames)\n #fig_state = plt.figure(figsize=(50, 50))\n fig, axes = plt.subplots(3, 2, figsize=(50, 50))\n fig.suptitle(title)\n for k in trajs:\n t, freq, tau = trajs[k]\n for i, name in enumerate(ColNames):\n m, n = np.unravel_index(i, (2, 3))\n axes[n, m].set_ylabel(f'{name}')\n x = np.linspace(0, freq*tau, tau)\n axes[n, m].plot(\n x, t[:, ColNames[name]],\n marker='X', label=k\n )\n plt.legend()\n #plt.tight_layout()\n if dir is not None:\n name = os.path.join(dir, f\"{filename}.png\")\n plt.savefig(name)\n plt.close()\n \n plt.show()\n\n\ndef traj_to_euler(traj, rep=\"rot\"):\n if rep == \"rot\":\n rot = traj[:, 3:3+9].reshape((-1, 3, 3))\n r = R.from_matrix(rot)\n elif rep == \"quat\":\n quat = traj[:, 3:3+4]\n r = R.from_quat(quat)\n else:\n raise NotImplementedError\n pos = traj[:, :3]\n euler = r.as_euler('XYZ', degrees=True)\n vel = traj[:, -6:]\n\n traj = np.concatenate([pos, euler, vel], axis=-1)\n return traj\n\n\ndef traj_to_forces(model, traj, rep=\"rot\", dt=0.1):\n '''\n Takes as input a trajectory composed of\n pose and velocity. Using a AUV model, it\n computes the different forces acting on the\n vehicle and returns them\n\n inputs:\n -------\n traj: trajectory compose of [pose, vel], shape [tau, sDim, 1]\n rep: the representation used for the rotation\n \n outputs:\n --------\n - Cv: the coriolis component. Shape [tau, 6]\n - Dv: the damping component. Shape [tau, 6]\n - g: the restoring forces. Shape [tau, 6]\n - tau: the control input. Shape [tau, 6]\n '''\n\n # First step: we need to compute the acceleration of the\n # auv a each steps.\n if rep == \"euler\":\n angle_len = 3\n elif rep == \"quat\":\n angle_len = 4\n elif rep == \"rot\":\n angle_len = 9\n\n traj = traj[..., None]\n\n pose = traj[:, :3 + angle_len]\n vel = traj[:, 3+angle_len:]\n\n acc = (vel[2: ] - vel[:-2])/dt\n pose = pose[1:-1]\n vel = vel[1:-1]\n\n cvs = []\n dvs = []\n gs = []\n fs = []\n # Use the acceleration together with the state to\n # compute the different values.\n\n for p, v, a in zip(pose, vel, acc):\n c, cv, d, dv, g, f = model.get_forces(p[None], v[None], a[None])\n cvs.append(cv)\n dvs.append(dv)\n gs.append(g)\n fs.append(f)\n \n cvs = np.concatenate(cvs, axis=0)\n dvs = np.concatenate(dvs, axis=0)\n gs = np.concatenate(gs, axis=0)\n fs = np.concatenate(fs, axis=0)\n\n return cvs, dvs, gs, fs","repo_name":"NicolayP/mppi-rexrov2","sub_path":"scripts/mppi_tf/scripts/src/misc/utile.py","file_name":"utile.py","file_ext":"py","file_size_in_byte":9514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"30440208808","text":"import random\r\n\r\n# Define possible choices\r\noptions = [\"rock\", \"paper\", \"scissors\"]\r\n\r\n# Define win-lose scenarios\r\nwin_scenarios = {\"rock\": \"scissors\", \"paper\": \"rock\", \"scissors\": \"paper\"}\r\n\r\n# Get player's choice\r\nplayer_choice = input(\"Choose rock, paper, or scissors: \").lower()\r\n\r\n# Make sure the player's choice is valid\r\nwhile player_choice not in options:\r\n player_choice = input(\r\n \"Invalid choice. Choose rock, paper, or scissors: \").lower()\r\n\r\n# Get computer's choice\r\ncomputer_choice = random.choice(options)\r\n\r\n# Determine the outcome\r\nif player_choice == computer_choice:\r\n print(f\"Both players chose {player_choice}. It's a tie!\")\r\nelif win_scenarios[player_choice] == computer_choice:\r\n print(f\"{player_choice} beats {computer_choice}. You win!\")\r\nelse:\r\n print(f\"{computer_choice} beats {player_choice}. You lose!\")\r\n","repo_name":"mohammedalbazoon8/rock-paper-scissor-game-in-python","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"21532220008","text":"import os\nimport random\nimport argparse\nimport yaml\nimport shutil\n\n\ndef deck_generator():\n Suites = [\n \"Spades\",\n \"Hearts\",\n \"Diamonds\",\n \"Clubs\"\n ]\n\n Cards = [\n \"A\",\n \"K\",\n \"Q\",\n \"J\"\n ]\n\n for n in range(2,11):\n Cards.append(str(n))\n \n Deck = []\n for Suite in Suites:\n for Card in Cards:\n Deck.append( Suite + \" - \" + Card)\n \n return Deck\n\n\ndef handcard_generator(n_players=4, hand_size=13):\n newdeck = deck_generator()\n handcards = []\n\n for player in range(n_players):\n hand = []\n for hand_index in range(hand_size):\n new_card = random.choice(newdeck)\n newdeck.remove(new_card)\n hand.append(new_card)\n handcards.append(sorted(hand))\n\n return handcards\n\n\ndef run(rounds=10):\n shutil.rmtree(\"bridge_output\")\n for r in range(1, 1+rounds):\n handcards = handcard_generator(hand_size=r, n_players=3)\n for p in range(3):\n output_path = \"bridge_output\" + \"/player\" + str(p) + \"/round\" + str(r) + \".txt\"\n os.makedirs(os.path.dirname(output_path), exist_ok=True)\n with open(output_path, \"w\") as outfile:\n yaml.dump(\n dict(cards=handcards[p], point=0), \n outfile\n )\n\nif __name__ == \"__main__\":\n run()","repo_name":"ghosalya/raw_bridge","sub_path":"generate_bridge.py","file_name":"generate_bridge.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"6686290102","text":"import gmpy2 as gp\r\n\"\"\"\r\nRSA ALGORITHM IMPLEMENTATION\r\nThe steps in an RSA Algorithm are\r\n1. Choose two prime numbers p, q.\r\n2. Let n = p * q\r\n3. Let φ = (p − 1)(q − 1)\r\n4. Choose a large number e ∈ [2, φ − 1]that is coprime to φ.\r\n5. Compute d ∈ [2, φ − 1] such that e × d = 1 (mod φ), and d must be coprime to φ\r\n6. (e, n) is the public key\r\n7. (d, n) is the private key\r\n8. Encryption: C = m^e(mod n)\r\n9. Decryption: m = C^d(mod n)\r\n\"\"\"\r\n\r\ndef encrypt(p, q, m):\r\n\tn = gp.mul(p, q)\r\n\tphi = gp.mul(gp.sub(p, 1), gp.sub(q, 1))\r\n\tif 65537 < phi and gp.gcd(65537, phi) == 1:\r\n\t\te = 65537\r\n\telif 257 < phi and gp.gcd(257, phi) == 1:\r\n\t\te = 257\r\n\telif 17 < phi and gp.gcd(17, phi) == 1:\r\n\t\te = 17\r\n\telif 5 < phi and gp.gcd(5, phi) == 1:\r\n\t\te = 5\r\n\telif 3 < phi and gp.gcd(3, phi) == 1:\r\n\t\te = 3\r\n\telse:\r\n\t\te = gp.sub(phi, 1)\r\n\td = gp.divm(1, e, phi) # returns d such that e * d = 1 mod phi; since 1 mod phi, d is coprime to n\r\n\tc = gp.powmod(m, e, n)\r\n\tprint('c: ', c)\r\n\tprint('e: ', e)\t\r\n\tprint('d: ', d)\r\n\tprint('n: ', n)\r\n\treturn c, d, n\r\n\r\ndef decrypt(c, d, n):\r\n\tm = gp.powmod(c, d, n)\r\n\tprint('m: ', m)\r\n\r\nprint('Enter p, q, m\\nConstraints:\\n* p 100:\r\n peaks1[-1] = len(deaths) - 1\r\n print()\r\n\r\n t = np.linspace(0, int(1 * len(deaths)) - 1, 2000)\r\n t_plot = np.linspace(0, int(1.2 * len(deaths)), 2000)\r\n t0 = np.array(range(len(deaths)))\r\n tw1 = int(.5 * (peaks[len(peaks) - 2] + peaks1[len(peaks1) - 2]))\r\n tw1 = 210\r\n t1 = np.array(range(tw1))\r\n deaths1 = deaths[0:tw1]\r\n tw2 = int(.5 * (peaks[-1] + peaks1[-1]))\r\n tw2 = 320\r\n t2 = np.array(range(tw2))\r\n deaths2 = deaths[0:tw2]\r\n deaths3 = deaths\r\n\r\n daily2 = smoother.smooth_data[0]\r\n\r\n relmin = argrelmin(daily2)\r\n print(relmin)\r\n print()\r\n\r\n ###########################################################\r\n\r\n # Initial conditions vector\r\n y0 = deaths[0]\r\n\r\n # Data to be fited\r\n data2 = []\r\n data2.append(deaths)\r\n data2 = np.array(data2)\r\n\r\n ###########################################################\r\n\r\n params = Parameters()\r\n params.add('r1', value=0.2, min=0, max=1)\r\n params.add('a1', value=0.2, min=0, max=1)\r\n params.add('K1', value=1.1 * deaths1[len(deaths1) - 1], min=deaths1[len(deaths1) - 1])\r\n params.add('p1', value=1, min=1, vary=True)\r\n # params.add('q1', value=q1.value, min=0, max=1, vary=False)\r\n params.add('q1', value=0.6, min=0, max=1)\r\n\r\n minner = Minimizer(func, params, fcn_args=(t1, deaths1))\r\n\r\n # Fit using Nelder-Mead\r\n logger.info('Começou o primeiro processo de minimização...')\r\n out1 = minner.minimize(method='nelder')\r\n # lmfit.report_fit(out1)\r\n logger.info('Terminou o primeiro processo de minimização...')\r\n\r\n print('R2=', 1 - out1.residual.var() / np.var(deaths1))\r\n print(out1.chisqr)\r\n\r\n # Fit using the Levenberg-Marquardt method with the result of the previous fit as initial guess\r\n # logger.info('Começou o segundo processo de minimização...')\r\n # out2 = minner.minimize(method='leastsq', params=out1.params)\r\n # lmfit.report_fit(out2)\r\n # logger.info('Terminou o segundo processo de minimização...')\r\n out2 = out1\r\n\r\n print('R2=', 1 - out2.residual.var() / np.var(deaths1))\r\n print()\r\n params = out2.params\r\n r1 = params['r1']\r\n a1 = params['a1']\r\n K1 = params['K1']\r\n p1 = params['p1']\r\n q1 = params['q1']\r\n\r\n ###########################################################\r\n\r\n params.add('r1', value=r1.value, min=0, max=1, vary=True)\r\n params.add('a1', value=a1.value, min=0, max=1, vary=True)\r\n params.add('K1', value=K1.value, min=0, vary=True)\r\n params.add('p1', value=p1.value, min=1, vary=True)\r\n params.add('q1', value=q1.value, min=0, max=1, vary=True)\r\n # params.add('r2', value=1, min=0, max=1, vary=False)\r\n params.add('r2', value=0.3, min=0, max=1)\r\n params.add('a2', value=1, min=0, max=1, vary=False)\r\n # params.add('a2', value=0.5, min=0, max=1)\r\n params.add('K2', value=1.1 * deaths2[-1], min=deaths2[-1], vary=True)\r\n # params.add('K2', value=1.1*K1.value, min=K1.value, vary=True)\r\n params.add('p2', value=1, min=1, vary=True)\r\n # params.add('q2', value=1, min=0, max=1, vary=False)\r\n params.add('q2', value=0.6, min=0, max=1)\r\n params.add('rho', value=0.01, min=0, max=0.2)\r\n params.add('t_0', value=tw1, min=0, max=len(t2))\r\n\r\n minner1 = Minimizer(func1, params, fcn_args=(t2, deaths2))\r\n\r\n # Fit using Nelder-Mead\r\n logger.info('Começou o terceiro processo de minimização...')\r\n out3 = minner1.minimize(method='least_squares')\r\n # lmfit.report_fit(out3)\r\n logger.info('Terminou o terceiro processo de minimização...')\r\n\r\n print('R2=', 1 - out3.residual.var() / np.var(deaths2))\r\n\r\n # Fit using the Levenberg-Marquardt method with the result of the previous fit as initial guess\r\n logger.info('Começou o quarto processo de minimização...')\r\n out4 = minner1.minimize(method='least_squares', params=out3.params)\r\n # lmfit.report_fit(out4)\r\n logger.info('Terminou o quarto processo de minimização...')\r\n\r\n print('R2=', 1 - out4.residual.var() / np.var(deaths2))\r\n print()\r\n params = out4.params\r\n r1 = params['r1']\r\n a1 = params['a1']\r\n K1 = params['K1']\r\n p1 = params['p1']\r\n q1 = params['q1']\r\n r2 = params['r2']\r\n a2 = params['a2']\r\n K2 = params['K2']\r\n p2 = params['p2']\r\n q2 = params['q2']\r\n rho = params['rho']\r\n t_0 = params['t_0']\r\n\r\n ###########################################################\r\n\r\n params.add('r1', value=r1.value, min=0, max=1, vary=True)\r\n params.add('a1', value=a1.value, min=0, max=1, vary=True)\r\n params.add('K1', value=K1.value, min=0, vary=True)\r\n params.add('p1', value=p1.value, min=1, vary=True)\r\n params.add('q1', value=q1.value, min=0, max=1, vary=True)\r\n params.add('r2', value=r2.value, min=0, max=1)\r\n params.add('a2', value=a2.value, min=0, max=1, vary=False)\r\n params.add('K2', value=K2.value, min=deaths2[-1], vary=True)\r\n params.add('p2', value=p2.value, min=1, vary=True)\r\n params.add('q2', value=q2.value, min=0, max=1)\r\n params.add('rho', value=rho.value, min=0, max=0.2)\r\n params.add('t_0', value=t_0.value, min=0)\r\n params.add('r3', value=0.3, min=0, max=1)\r\n params.add('a3', value=1, min=0, max=1, vary=False)\r\n # params.add('a2', value=0.5, min=0, max=1)\r\n params.add('K3', value=1.1 * deaths3[-1], min=deaths3[-1], vary=True)\r\n # params.add('K2', value=1.1*K1.value, min=K1.value, vary=True)\r\n params.add('p3', value=1, min=0, vary=False)\r\n # params.add('q2', value=1, min=0, max=1, vary=False)\r\n params.add('q3', value=0.6, min=0, max=1)\r\n params.add('rho1', value=0.05, min=0, max=0.2)\r\n params.add('t_1', value=tw2, min=0, max=len(t0))\r\n\r\n minner2 = Minimizer(func2, params, fcn_args=(t0, deaths3))\r\n\r\n # Fit using Nelder-Mead\r\n logger.info('Começou o quinto processo de minimização...')\r\n out5 = minner2.minimize(method='least_squares')\r\n # lmfit.report_fit(out5)\r\n logger.info('Terminou o quinto processo de minimização...')\r\n\r\n print('R2=', 1 - out5.residual.var() / np.var(deaths3))\r\n print()\r\n\r\n # Fit using the Levenberg-Marquardt method with the result of the previous fit as initial guess\r\n logger.info('Começou o sexto processo de minimização...')\r\n out6 = minner2.minimize(method='least_squares', params=out5.params)\r\n # lmfit.report_fit(out6)\r\n logger.info('Terminou o quinto processo de minimização...')\r\n\r\n print('R2=', 1 - out6.residual.var() / np.var(deaths3))\r\n print()\r\n\r\n param_err = []\r\n for name_par, param in out5.params.items():\r\n if (not (param.stderr is None)) & (param.value != 0):\r\n param_err.append(param.stderr / param.value)\r\n\r\n param_err1 = []\r\n for name_par, param in out6.params.items():\r\n if (not (param.stderr is None)) & (param.value != 0):\r\n param_err1.append(param.stderr / param.value)\r\n\r\n for i in param_err1:\r\n if i > 1:\r\n print('hello mf!')\r\n out6 = out5\r\n\r\n if any(x > 1 for x in param_err1) or np.sum(param_err1) > np.sum(param_err):\r\n print('hello mf!')\r\n out6 = out5\r\n\r\n params = out6.params\r\n r1 = params['r1']\r\n a1 = params['a1']\r\n K1 = params['K1']\r\n p1 = params['p1']\r\n q1 = params['q1']\r\n r2 = params['r2']\r\n a2 = params['a2']\r\n K2 = params['K2']\r\n p2 = params['p2']\r\n q2 = params['q2']\r\n rho = params['rho']\r\n t_0 = params['t_0']\r\n r3 = params['r3']\r\n a3 = params['a3']\r\n K3 = params['K3']\r\n p3 = params['p3']\r\n q3 = params['q3']\r\n rho1 = params['rho1']\r\n t_1 = params['t_1']\r\n\r\n logger.info('O fit terminou...')\r\n temp_final = datetime.now()\r\n logger.info(f\"Duração: {temp_final - temp_inicio}\")\r\n\r\n return (r1, a1, K1, p1, q1, r2, a2, K2, p2, q2, r3, a3, K3, p3, q3, rho, t_0, rho1, t_1)\r\n\r\n\r\ndef modelo_acumulado(params, deltaTempo, tmax, y0):\r\n t = np.linspace(0, int(1 * tmax) - 1 + deltaTempo, 2000)\r\n C1 = odeint(deriv2, y0, t, args=params).T[0]\r\n return [t, C1]\r\n\r\n\r\ndef modelo_diario(params, deltaTempo, tmax, y0):\r\n t = np.linspace(0, int(1 * tmax) - 1 + deltaTempo, 2000)\r\n C1 = odeint(deriv2, y0, t, args=params).T[0]\r\n\r\n params = list(params)\r\n params.insert(0, t)\r\n params.insert(0, C1)\r\n\r\n daily_theo = deriv2(*params)\r\n peaks, _ = find_peaks(daily_theo)\r\n peaks1, _ = find_peaks(-daily_theo)\r\n\r\n return [t, daily_theo, peaks, peaks1]","repo_name":"luancordeiro/modintervPR","sub_path":"app/modelo.py","file_name":"modelo.py","file_ext":"py","file_size_in_byte":12876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"27670076257","text":"from django.http import HttpResponse\nfrom django.shortcuts import redirect, render\nfrom .forms import VehicleForm\nfrom .models import Vehicle\nfrom django.contrib import messages\nfrom django.contrib.auth.models import User\nfrom django.core.mail import send_mail\nfrom vehicle_manag import settings\nfrom django.contrib.auth import authenticate,login,logout\nfrom django.contrib.auth.decorators import login_required\n\n\n\n\n\n\ndef remove_spaces(string):\n strg = string.replace(\" \", \"\")\n # also convert vh_number to uppercase\n return strg.upper()\n\n\n\ndef home(request):\n if request.user.is_authenticated:\n if request.user.is_superuser :\n return redirect(\"sadminH\")\n elif request.user.is_staff:\n return redirect(\"adminH\")\n return redirect(\"userH\") \n \n return render(request,'index.html')\n\n\n@login_required(login_url='/login')\ndef add_vehicle(request):\n if request.user.is_superuser:\n if request.method == \"GET\":\n form_obj = VehicleForm()\n context = {}\n context['form'] = form_obj\n\n return render(request,\"super_admin/add_vehicle.html\",context)\n elif request.method == \"POST\":\n\n # removing the white spaces from vehicle number\n mutable_query_set = request.POST.copy()\n mutable_query_set['vh_number'] = remove_spaces(mutable_query_set['vh_number'])\n\n vh_num = mutable_query_set['vh_number']\n\n form_data = VehicleForm(mutable_query_set)\n\n if Vehicle.objects.filter(vh_number=vh_num):\n messages.error(request,\"Vehicle Already Exists\")\n return redirect(\"addV\")\n if form_data.is_valid():\n form_data.save()\n messages.success(request,\"Vehicle Added Successfully!!\")\n return redirect(\"addV\")\n messages.error(request,VehicleForm.errors) \n return redirect(\"addV\") \n return HttpResponse (\"You dont have permission to accces this page\") \n\ndef sgup(request):\n if request.method == \"GET\":\n return render(request,'signup.html')\n elif request.method == \"POST\":\n un = request.POST['uname'] \n fn = request.POST['fname'] \n pw1 = request.POST['pwd1']\n pw2 = request.POST['pwd2']\n em = request.POST['em']\n\n\n if User.objects.filter(username=un):\n messages.error(request,\"Username alredy taken,try another one\")\n return redirect('sgup')\n\n if User.objects.filter(email=em):\n messages.error(request,\"email alredy exists !!\")\n return redirect('sgup')\n\n\n if pw1 != pw2:\n messages.error(request,\"Confirm password didn't match !\")\n return redirect('sgup')\n\n if len(un)>10:\n messages.error(request,\"Username must be less than 10\")\n return redirect('sgup')\n\n if not un.isalnum():\n messages.error(request,\"Username must be alpha numeric ( 'A to Z and 0 to 9') \")\n return redirect('sgup')\n\n new_user = User.objects.create_user(username=un,first_name=fn,password=pw1,email=em)\n new_user.save()\n\n messages.success(request,\"Your account has been successfully created!\")\n\n # welcome mail \n\n subject = \"Welcome to Vehicle Management\"\n message = \"Hello\" + new_user.first_name + \"\\n\" + \"Thankyou for Registering, Your Username is \"+new_user.username \n from_addr = settings.EMAIL_HOST_USER\n to_list = [new_user.email,]\n send_mail(from_email=from_addr,subject=subject,message=message,recipient_list=to_list)\n \n\n \n return redirect('lgin')\n\n\ndef lgin(request):\n if request.user.is_authenticated:\n return home(request)\n if request.method == 'GET': \n return render(request,'login.html')\n elif request.method == 'POST':\n un = request.POST['un']\n pw = request.POST['pw']\n\n user = authenticate(username=un,password=pw)\n\n if user:\n login(request,user)\n if user.is_superuser:\n return redirect('sadminH')\n elif user.is_staff:\n return redirect(\"adminH\") \n else:\n return redirect(\"userH\")\n else:\n messages.error(request,\"Incorrect Cradentials\") \n return redirect(\"lgin\") \n\n@login_required(login_url='/login')\ndef view_vehicle(request):\n data = Vehicle.objects.all()\n return render(request,\"view_vehicle.html\",{'data':data}) \n\ndef lgout(request):\n logout(request) \n return redirect(\"home\") \n\n@login_required(login_url='/login')\ndef s_admin_home(request):\n if request.user.is_superuser:\n return render(request,'super_admin/super_admin_home.html')\n else:\n return HttpResponse(\"You dont have acccess to this page\") \n\n@login_required(login_url='/login')\ndef admin_home(request):\n if request.user.is_staff:\n return render(request,'admin/admin_home.html')\n else:\n return HttpResponse(\"You dont have acccess to this page\") \n\n\n@login_required(login_url='/login')\ndef user_home(request):\n if request.user.is_superuser:\n return redirect(\"sadminH\")\n elif request.user.is_staff:\n return redirect(\"adminH\") \n else: \n return render(request,'user/user_home.html')\n\n\n \n@login_required(login_url='/login')\ndef edit_vehicle(request,vid):\n if request.user.has_perm('vehicle.change_vehicle'):\n if request.method == \"GET\":\n record = Vehicle.objects.get(id = vid)\n form_ob = VehicleForm(instance=record)\n return render (request,\"edit_vehicle.html\",{'form':form_ob})\n elif request.method == \"POST\":\n # getting the old record \n record = Vehicle.objects.get(id = vid)\n form_ob = VehicleForm(instance=record)\n\n\n v_no = remove_spaces(request.POST['vh_number'])\n # Checking if the user edited the vh number. then\n # checking for the new number is exist in the table,if present\n # returning error\n if record.vh_number != v_no and Vehicle.objects.filter(vh_number=v_no):\n messages.error(request,\"Vehicle Number alredy exits!!\")\n return render (request,\"edit_vehicle.html\",{'form':form_ob})\n \n \n v_type = request.POST['vh_type']\n v_model = request.POST['vh_model']\n v_disc = request.POST['vh_disc']\n Vehicle.objects.filter(id=vid).update(vh_number=v_no,vh_type=v_type,vh_model=v_model,vh_disc=v_disc)\n \n msg = \"Vehicle \"+ v_no +\" Edited successfully\"\n messages.success(request,message=msg)\n\n return redirect(\"viewV\")\n return HttpResponse('Permission denied for the user') \n\n\n \n\n\n\n\n \n@login_required(login_url='/login')\ndef del_vehicle(request,vid):\n if request.user.has_perm('vehicle.delete_vehicle'):\n Vehicle.objects.filter(id = vid).delete()\n messages.success(request,\"Vehicle deleted Successfully\")\n return redirect(\"viewV\")\n return HttpResponse('Permission denied for the user') \n \n \n\n\n\n\n\n\n\n \n\n \n\n\n \n\n\n ","repo_name":"anurag-6/Vehicle_management","sub_path":"vehicle/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7249,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"76"} +{"seq_id":"41907641147","text":"from typing import List\n\nfrom fastapi import APIRouter, HTTPException, Depends\nfrom sqlalchemy.orm import Session\n\nfrom .. import schemas\nfrom ..db.init_db import get_db\nfrom ... import crud\n\nrouter = APIRouter()\n\n\n@router.post(\"/\", response_model=schemas.users.UserResponse)\nasync def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):\n db_user = await crud.get_user_by_email(db, email=user.email)\n if db_user:\n raise HTTPException(status_code=400, detail=\"Email already exist\")\n created = await crud.create_user(db=db, user=user)\n return schemas.users.UserResponse(id=created.id, email=created.email, birth=created.birth)\n\n\n@router.get(\"/\", response_model=List[schemas.users.UserResponse])\nasync def all_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):\n users = await crud.get_users(db, skip=skip, limit=limit)\n return [schemas.users.UserResponse(id=user.id, email=user.email, birth=user.birth) for user in users]\n\n\n@router.post(\"/{user_id}/items/\", response_model=schemas.ItemResponse)\nasync def create_item_for_user(user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db)):\n item = await crud.create_user_item(db, item, user_id)\n return schemas.ItemResponse(title=item.title, price=item.price)\n","repo_name":"sejin-P/fastapi-prc","sub_path":"fastapi_prc/app/api/endpoints/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"73742594164","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nfrom flask import Flask, request, render_template\nimport joblib\napp = Flask(__name__) #dunder name\n\n#The @ is for funning a generator\n@app.route(\"/\", methods=[\"GET\",\"POST\"])\ndef index():\n if request.method=='POST':\n #Get things from the front end\n num = float(request.form.get(\"rate\")) #make this float. Double confirm\n print(num)\n \n model = joblib.load(\"python_lm\")\n pred = model.predict([[num]])\n pred_float = round(pred[0][0],2)\n print(pred)\n \n s = str(pred_float)\n return(render_template('index.html', result = s))\n\n #What to do before pressing the button?\n else:\n return render_template('index.html', result = '...')\n\n\n# In[ ]:\n\n\n#Need this in the cloud because Heroku need to verify this is your program\nif __name__=='__main__':\n app.run()\n \n#I can calso change the host number\n# app.run(host=\"127.0.0.1\", port=int(\"80\"))\n\n","repo_name":"angkj1995/DBS-prediction-exercise","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"70815543286","text":"# region Example -1\r\n\r\nsayac = 0\r\ntoplam = 0\r\n\r\nwhile sayac <= 10:\r\n x = int(input(\"Lütfen bir sayı giriniz: \"))\r\n toplam += x\r\n sayac += 1\r\nprint(f'Sayıların toplamı: {toplam}')\r\n\r\n# endregion\r\n\r\n# region Example-2\r\n\r\nsayac = 0\r\nwhile sayac <= 100:\r\n print(sayac)\r\n sayac += 1\r\n\r\n# endregion\r\n\r\n# region Example -3\r\n\r\nsayac = 1\r\nc_s = 0\r\nt_s = 0\r\nwhile sayac <= 101:\r\n if sayac % 2 == 0:\r\n c_s += 1\r\n else:\r\n t_s += 1\r\n sayac += 1\r\nprint(f'Çift sayılar: {c_s} \\nTek sayılar:{t_s}')\r\n\r\n\r\n# endregion\r\n\r\n# region Example -4\r\n\r\nsayac = 1\r\ncs = 0\r\nts = 0\r\n\r\nwhile sayac <= 100:\r\n if sayac % 2 == 0:\r\n cs += 1\r\n sayac += 1\r\n else:\r\n ts += 1\r\n sayac += 1\r\nprint(f'{cs} tane çift sayı vardır')\r\nprint(f'{ts} tane tek sayı vardır')\r\n\r\n# endregion\r\n\r\n# region Example -5\r\n\r\nsayac = 1\r\ncst = 0\r\ntst = 0\r\n\r\nwhile sayac <= 100:\r\n if sayac % 2 == 0:\r\n cst += sayac\r\n else:\r\n tst += sayac\r\n sayac += 1\r\nprint(f'Çift sayıların toplamı: {cst}')\r\nprint(f'Tek sayıların toplamı: {tst}')\r\n\r\n# endregion\r\n\r\n# region Example -6\r\n\r\np_t_l = ['+', '-', '*', '/', 'e']\r\nwhile True:\r\n i = input(\"İşlem işareti giriniz: \")\r\n if i in p_t_l:\r\n \r\n if i == (\"e\"):\r\n break\r\n else:\r\n x = int(input(\"Sayı giriniz: \"))\r\n y = int(input(\"Sayı giriniz: \"))\r\n if i == (\"+\"):\r\n print(x+y)\r\n elif i == (\"-\"):\r\n print(x-y)\r\n elif i == (\"*\"):\r\n print(x*y)\r\n elif i == (\"/\"):\r\n print(x/y)\r\n else:\r\n print(\"Lütfen doğru bir işlem türü giriniz..'\")\r\n\r\n# endregion\r\n\r\n# region Example -7\r\n\r\nsayac = 0\r\ntst = 0\r\nwhile sayac <= 101:\r\n sayac += 1\r\n if sayac % 2 == 0:\r\n continue\r\n tst += sayac\r\nprint(f'Tek sayıların toplamı: {tst}')\r\n\r\n# endregion\r\n\r\n# region Example -8\r\n\r\nfrom datetime import datetime\r\nsayac = 1950\r\ny = int(input(\"Yıl giriniz: \"))\r\nin_exist = False\r\nwhile sayac <= datetime.now().year:\r\n if y == sayac:\r\n print(\"Bulundu\")\r\n in_exist = True\r\n break\r\n sayac += 1\r\nif not in_exist:\r\n print(\"Bulunamadı\")\r\n\r\n# endregion\r\n\r\n# region Example -9\r\nx = int(input(\"Bir sayı giriniz: \"))\r\ny = int(input(\"Bir sayı giriniz: \"))\r\nz = int(input(\"Bir sayı giriniz: \"))\r\nst = 0\r\nwhile x < y:\r\n st = st + x + z\r\n x += z\r\nprint(st)\r\n# endregion\r\n\r\n# region Example -10\r\nimport random\r\nx =random.randint(1, 100)\r\nhak = 3\r\n\r\nwhile x > 0:\r\n hak -= 1\r\n t = int(input(\"Tahminizi Griniz: \"))\r\n if hak == 0:\r\n print(f'Bilemediniz cevap:{x}')\r\n break\r\n if x == t:\r\n print(\"Bildiniz\")\r\n break\r\n elif x < t:\r\n print(\"Bilemediniz daha küçük\")\r\n elif x > t:\r\n print(\"Bilemediniz daha büyük\")\r\n\r\n# endregionn\r\n\r\n# region Example -11\r\n\r\nx = int(input(\"Bir sayı giriniz: \"))\r\nb = 2\r\nis_prime = True\r\nif x == 1 or x <= 0:\r\n is_prime = False\r\n print(\"Sıfır ve Negatif sayılar asal değildir...\")\r\nelse:\r\n while b < x:\r\n if x % b == 0:\r\n is_prime = False\r\n else:\r\n b += 1\r\n if is_prime == True:\r\n print(\"Asal sayı.\")\r\n break\r\n else:\r\n print(\"Asal sayı değil\")\r\n break\r\n\r\n# endregion\r\n","repo_name":"Gufran99/Python","sub_path":"01_introduution/while-loop.py","file_name":"while-loop.py","file_ext":"py","file_size_in_byte":3369,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"34257012008","text":"# -*- coding: utf-8 -*-\nfrom odoo import api, models, fields\nfrom odoo.tools.translate import _\nfrom odoo.exceptions import UserError\nimport logging\n_logger = logging.getLogger(__name__)\n\n\nclass AccountJournalSiiDocumentClass(models.Model):\n _name = \"account.journal.dian_document_class\"\n _description = \"Journal DIAN Documents\"\n _order = 'sequence'\n\n @api.depends('dian_document_class_id', 'sequence_id')\n def get_secuence_name(self):\n for r in self:\n sequence_name = (': ' + r.sequence_id.name) if r.sequence_id else ''\n name = (r.dian_document_class_id.name or '') + sequence_name\n r.name = name\n\n name = fields.Char(\n compute=\"get_secuence_name\",\n )\n dian_document_class_id = fields.Many2one(\n 'dian.document_class',\n string='Document Type',\n required=True,\n )\n sequence_id = fields.Many2one(\n 'ir.sequence',\n string='Entry Sequence',\n help=\"\"\"This field contains the information related to the numbering \\\n of the documents entries of this document type.\"\"\",\n )\n journal_id = fields.Many2one(\n 'account.journal',\n string='Journal',\n required=True,\n )\n sequence = fields.Integer(\n string='Sequence',\n )\n\n @api.onchange('dian_document_class_id')\n def check_dian_document_class(self):\n if self.dian_document_class_id and self.sequence_id and self.dian_document_class_id != self.sequence_id.dian_document_class_id:\n raise UserError(\"El tipo de Documento de la secuencia es distinto\")\n\nclass account_journal(models.Model):\n _inherit = \"account.journal\"\n\n journal_document_class_ids = fields.One2many(\n 'account.journal.dian_document_class',\n 'journal_id',\n 'Documents Class',\n )\n use_documents = fields.Boolean(\n string='Use Documents?',\n default='_get_default_doc',\n )\n\n restore_mode = fields.Boolean(\n string=\"Restore Mode\",\n default=False,\n )\n\n @api.onchange('journal_activities_ids')\n def max_actecos(self):\n if len(self.journal_activities_ids) > 4:\n raise UserError(\"Deben Ser máximo 4 actecos por Diario, seleccione los más significativos para este diario\")\n\n @api.multi\n def _get_default_doc(self):\n self.ensure_one()\n if self.type == 'sale' or self.type == 'purchase':\n self.use_documents = True\n\n @api.multi\n def name_get(self):\n res = []\n for journal in self:\n currency = journal.currency_id or journal.company_id.currency_id\n name = \"%s (%s)\" % (journal.name, currency.name)\n #if journal.sucursal_id and self.env.context.get('show_full_name', False):\n # name = \"%s (%s)\" % (name, journal.sucursal_id.name)\n res.append((journal.id, name))\n return res\n","repo_name":"dansanti/l10n_co_fe","sub_path":"models/account_journal.py","file_name":"account_journal.py","file_ext":"py","file_size_in_byte":2974,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"76"} +{"seq_id":"17221524463","text":"from django.db import transaction\n\nfrom rest_framework_nested.relations import NestedHyperlinkedIdentityField\n\nfrom eric.core.rest.serializers import BaseModelSerializer, HyperlinkedToListField\nfrom eric.sortable_menu.models import MenuEntry, MenuEntryParameter\n\n\nclass MenuEntryParameterSerializer(BaseModelSerializer):\n class Meta:\n model = MenuEntryParameter\n fields = (\n \"name\",\n \"value\",\n )\n\n\nclass MenuEntrySerializer(BaseModelSerializer):\n \"\"\"\n Serializer for Menu Entries, showing also the menu_entry_parameters\n \"\"\"\n\n menu_entry_parameters = MenuEntryParameterSerializer(many=True, read_only=True)\n\n class Meta:\n model = MenuEntry\n # Note: if you add the owner field, make sure it is set to readonly\n fields = (\n \"id\",\n \"pk\",\n \"route\",\n \"ordering\",\n \"menu_entry_parameters\",\n \"visible\",\n \"url\",\n )\n","repo_name":"eWorkbench/eWorkbench","sub_path":"backend-django/app/eric/sortable_menu/rest/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"76"} +{"seq_id":"36382160500","text":"class Queue2Stacks():\n\n def __init__(self):\n\n self.instack = []\n self.outstack = []\n\n def __str__(self):\n return '{}'.format(self.instack)\n\n def enqueue(self, element):\n\n self.instack.append(element)\n\n def dequeue(self):\n\n if not self.outstack:\n while self.instack:\n self.outstack.append(self.instack.pop())\n\n return self.outstack.pop()\n\n\nq = Queue2Stacks()\nq.enqueue(2)\nq.enqueue(12)\nq.enqueue(312)\nprint(q)\nprint(q.dequeue())\nprint(q.instack)\nq.enqueue(77)\nprint(q.instack)\nprint(q)","repo_name":"causeyo/algorithms","sub_path":"stacks_and_queues/queue_from_stacks.py","file_name":"queue_from_stacks.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"76"} +{"seq_id":"14084282438","text":"import pytz\nfrom dateutil import parser\nfrom bs4 import BeautifulSoup\nimport utils\nimport config\nimport regex\n\n\ndef format_item(item, feedinfo, channelid):\n category = config.get_feed_category(channelid, feedinfo)\n format = config.get_format_by_category(channelid, category)\n\n title = utils.get_entry(item, 'title')\n pubdate = format_date(utils.get_entry(item, 'published'))\n author = utils.get_entry(item, 'author')\n link = f'[Link]({utils.get_entry(item, \"link\")})'\n author = utils.get_entry(item, 'author')\n hashtags = '\\\\%23\\\\'.join(feedinfo['tags'])\n name = feedinfo['name']\n\n desc = format_desc(utils.get_entry(item, 'description'))\n\n posttext = utils.format_str(format, name=name, author=author, title=title,\n body=desc, url=link, hashtags=hashtags, pubdate=pubdate)\n return posttext\n\n\ndef format_date(date: str):\n parsed = parser.parse(date)\n gmt = str(pytz.timezone('GMT').normalize(parsed))\n return gmt.replace('+00:00', ' GMT')\n\n\ndef format_desc(description: str):\n description = BeautifulSoup(description).prettify()\n soup = BeautifulSoup(description)\n\n ans = soup.find_all('a')\n for a in ans:\n ancl = a.get('href')\n if(regex.match('twitter.com/*./status/', ancl)):\n description = description.replace(\n a, '[quted tweet link](%s)' % ancl)\n else:\n description = description.replace(a, '[link](%s)' % ancl)\n description.replace(a, '[link](%s)' % ancl)\n\n brs = soup.find_all('br')\n for br in brs:\n description.replace(br, '\\n')\n\n imgs = soup.find_all('img')\n for img in imgs:\n description.replace(img, '[image](%s)' % img.get('src'))\n\n vids = soup.find_all('video')\n for vid in vids:\n description.replace(vid, '[video](%s)' % vid.get('src'))\n\n bs = soup.find_all(['b', 'strong'])\n for b in bs:\n description.replace(b, '*%s*' % b.string)\n\n itals = soup.find_all(['i', 'em'])\n for i in itals:\n description.replace(i, '_%s_' % i.string)\n\n heads = soup.find_all(['h1', 'h2', 'h3', 'h4', 'h5', 'h6'])\n for h in heads:\n description.replace(h, '▍*%s*\\n' % h.string)\n\n return regex.sub(r'([_*[]()~`>+-=|{}.!])', r'\\\\\\1', soup.get_text('\\n').replace('#', '\\\\%23\\\\'))\n\n\n# def format_description(description: str):\n# # replace img tags with markdown link\n# for img in regex.findall('', description):\n# imgl = regex.search(\n# '(http|ftp|https):\\/\\/([\\w_-]+(?:(?:\\.[\\w_-]+)+))([\\w.,@?^=%&:\\/~+#-]*[\\w@?^=%&\\/~+#-])', img).group()\n# description = description.replace(img, f'[image]({imgl})')\n\n# # replace video tags with markdown link\n# for vid in regex.findall('