content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # coding: utf-8 """Context management API of mxnet.""" from __future__ import absolute_import import threading import warnings from .base import classproperty, with_metaclass, _MXClassPropertyMetaClass # initialize the default context in Context Context._default_ctx.value = Context('cpu', 0) def cpu(device_id=0): """Returns a CPU context. This function is a short cut for ``Context('cpu', device_id)``. For most operations, when no context is specified, the default context is `cpu()`. Examples ---------- >>> with mx.cpu(): ... cpu_array = mx.nd.ones((2, 3)) >>> cpu_array.context cpu(0) >>> cpu_array = mx.nd.ones((2, 3), ctx=mx.cpu()) >>> cpu_array.context cpu(0) Parameters ---------- device_id : int, optional The device id of the device. `device_id` is not needed for CPU. This is included to make interface compatible with GPU. Returns ------- context : Context The corresponding CPU context. """ return Context('cpu', device_id) def cpu_pinned(device_id=0): """Returns a CPU pinned memory context. Copying from CPU pinned memory to GPU is faster than from normal CPU memory. This function is a short cut for ``Context('cpu_pinned', device_id)``. Examples ---------- >>> with mx.cpu_pinned(): ... cpu_array = mx.nd.ones((2, 3)) >>> cpu_array.context cpu_pinned(0) >>> cpu_array = mx.nd.ones((2, 3), ctx=mx.cpu_pinned()) >>> cpu_array.context cpu_pinned(0) Parameters ---------- device_id : int, optional The device id of the device. `device_id` is not needed for CPU. This is included to make interface compatible with GPU. Returns ------- context : Context The corresponding CPU pinned memory context. """ return Context('cpu_pinned', device_id) def gpu(device_id=0): """Returns a GPU context. This function is a short cut for Context('gpu', device_id). The K GPUs on a node are typically numbered as 0,...,K-1. Examples ---------- >>> cpu_array = mx.nd.ones((2, 3)) >>> cpu_array.context cpu(0) >>> with mx.gpu(1): ... gpu_array = mx.nd.ones((2, 3)) >>> gpu_array.context gpu(1) >>> gpu_array = mx.nd.ones((2, 3), ctx=mx.gpu(1)) >>> gpu_array.context gpu(1) Parameters ---------- device_id : int, optional The device id of the device, needed for GPU. Returns ------- context : Context The corresponding GPU context. """ return Context('gpu', device_id) def current_context(): """Returns the current context. By default, `mx.cpu()` is used for all the computations and it can be overridden by using `with mx.Context(x)` statement where x can be cpu(device_id) or gpu(device_id). Examples ------- >>> mx.current_context() cpu(0) >>> with mx.Context('gpu', 1): # Context changed in `with` block. ... mx.current_context() # Computation done here will be on gpu(1). ... gpu(1) >>> mx.current_context() # Back to default context. cpu(0) Returns ------- default_ctx : Context """ if not hasattr(Context._default_ctx, "value"): Context._default_ctx.value = Context('cpu', 0) return Context._default_ctx.value
[ 2, 49962, 284, 262, 24843, 10442, 5693, 357, 1921, 37, 8, 739, 530, 198, 2, 393, 517, 18920, 5964, 11704, 13, 220, 4091, 262, 28536, 2393, 198, 2, 9387, 351, 428, 670, 329, 3224, 1321, 198, 2, 5115, 6634, 9238, 13, 220, 383, 7054,...
2.833789
1,462
# theory MPD client # Copyright (C) 2008 Ryan Roemmich <ralfonso@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import ConfigParser import pickle from pylons import config from pylons import app_globals as g
[ 2, 4583, 4904, 35, 5456, 198, 2, 15069, 357, 34, 8, 3648, 220, 6047, 5564, 368, 76, 488, 1279, 1373, 69, 26666, 31, 14816, 13, 785, 29, 198, 2, 198, 2, 770, 1430, 318, 1479, 3788, 25, 345, 460, 17678, 4163, 340, 290, 14, 273, ...
3.669683
221
"""Test `iotanbo_py_utils.error.py`.""" from iotanbo_py_utils.error import Error from iotanbo_py_utils.error import ErrorKind
[ 37811, 14402, 4600, 5151, 272, 2127, 62, 9078, 62, 26791, 13, 18224, 13, 9078, 63, 526, 15931, 198, 6738, 1312, 313, 272, 2127, 62, 9078, 62, 26791, 13, 18224, 1330, 13047, 198, 6738, 1312, 313, 272, 2127, 62, 9078, 62, 26791, 13, 1...
2.634615
52
from setuptools import setup, find_packages from os import path from io import open here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='orvibo', version='1.5.0', description='Python module to controll Orvibo devices, such as s20 wifi sockets and AllOne IR blasters', long_description=long_description, long_description_content_type='text/markdown', url='https://github.com/cherezov/orvibo', packages=find_packages(exclude=['contrib', 'docs', 'tests']), # Required )
[ 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 6738, 28686, 1330, 3108, 198, 6738, 33245, 1330, 1280, 198, 198, 1456, 796, 3108, 13, 397, 2777, 776, 7, 6978, 13, 15908, 3672, 7, 834, 7753, 834, 4008, 198, 198, 2, 349...
2.919283
223
import glob, os import subprocess from difflib import context_diff
[ 11748, 15095, 11, 28686, 198, 11748, 850, 14681, 198, 6738, 814, 8019, 1330, 4732, 62, 26069, 628 ]
4
17
from amazon.model import db
[ 6738, 716, 5168, 13, 19849, 1330, 20613, 628 ]
3.625
8
expected = [ { "abstract_type": None, "content": "RET can be activated in cis or trans by its co-receptors and ligands in vitro, but the physiological roles of trans signaling are unclear. Rapidly adapting (RA) mechanoreceptors in dorsal root ganglia (DRGs) express Ret and the co-receptor Gfr\u03b12 and depend on Ret for survival and central projection growth. Here, we show that Ret and Gfr\u03b12 null mice display comparable early central projection deficits, but Gfr\u03b12 null RA mechanoreceptors recover later. Loss of Gfr\u03b11, the co-receptor implicated in activating RET in trans, causes no significant central projection or cell survival deficit, but Gfr\u03b11;Gfr\u03b12 double nulls phenocopy Ret nulls. Finally, we demonstrate that GFR\u03b11 produced by neighboring DRG neurons activates RET in RA mechanoreceptors. Taken together, our results suggest that trans and cis RET signaling could function in the same developmental process and that the availability of both forms of activation likely enhances but not diversifies outcomes of RET signaling.", "full_content": "<p>RET can be activated in <italic>cis</italic> or <italic>trans</italic> by its co-receptors and ligands <italic>in vitro</italic>, but the physiological roles of <italic>trans</italic> signaling are unclear. Rapidly adapting (RA) mechanoreceptors in dorsal root ganglia (DRGs) express <italic>Ret</italic> and the co-receptor <italic>Gfr\u03b12</italic> and depend on <italic>Ret</italic> for survival and central projection growth. Here, we show that <italic>Ret</italic> and <italic>Gfr\u03b12</italic> null mice display comparable early central projection deficits, but <italic>Gfr\u03b12</italic> null RA mechanoreceptors recover later. Loss of <italic>Gfr\u03b11</italic>, the co-receptor implicated in activating RET <italic>in trans</italic>, causes no significant central projection or cell survival deficit, but <italic>Gfr\u03b11;Gfr\u03b12</italic> double nulls phenocopy <italic>Ret</italic> nulls. Finally, we demonstrate that GFR\u03b11 produced by neighboring DRG neurons activates RET in RA mechanoreceptors. Taken together, our results suggest that <italic>trans</italic> and <italic>cis</italic> RET signaling could function in the same developmental process and that the availability of both forms of activation likely enhances but not diversifies outcomes of RET signaling.</p>", }, ]
[ 40319, 796, 685, 198, 220, 220, 220, 1391, 198, 220, 220, 220, 220, 220, 220, 220, 366, 397, 8709, 62, 4906, 1298, 6045, 11, 198, 220, 220, 220, 220, 220, 220, 220, 366, 11299, 1298, 366, 26087, 460, 307, 13906, 287, 33325, 393, 1...
3.625373
670
# coding=utf-8 import optparse import torch import time import pickle from torch.autograd import Variable from loader import * from utils import * # python -m visdom.server optparser = optparse.OptionParser() optparser.add_option( "-t", "--test", default="data/eng.testb", help="Test set location" ) optparser.add_option( '--score', default='evaluation/temp/score.txt', help='score file location' ) optparser.add_option( "-g", '--use_gpu', default='1', type='int', help='whether or not to ues gpu' ) optparser.add_option( '--loss', default='loss.txt', help='loss file location' ) optparser.add_option( '--model_path', default='models/test', help='model path' ) optparser.add_option( '--map_path', default='models/mapping.pkl', help='model path' ) optparser.add_option( '--char_mode', choices=['CNN', 'LSTM'], default='CNN', help='char_CNN or char_LSTM' ) opts = optparser.parse_args()[0] mapping_file = opts.map_path with open(mapping_file, 'rb') as f: mappings = pickle.load(f) word_to_id = mappings['word_to_id'] tag_to_id = mappings['tag_to_id'] id_to_tag = {k[1]: k[0] for k in tag_to_id.items()} char_to_id = mappings['char_to_id'] parameters = mappings['parameters'] word_embeds = mappings['word_embeds'] use_gpu = opts.use_gpu == 1 and torch.cuda.is_available() assert os.path.isfile(opts.test) assert parameters['tag_scheme'] in ['iob', 'iobes'] if not os.path.isfile(eval_script): raise Exception('CoNLL evaluation script not found at "%s"' % eval_script) if not os.path.exists(eval_temp): os.makedirs(eval_temp) lower = parameters['lower'] zeros = parameters['zeros'] tag_scheme = parameters['tag_scheme'] test_sentences = load_sentences(opts.test, lower, zeros) update_tag_scheme(test_sentences, tag_scheme) test_data = prepare_dataset( test_sentences, word_to_id, char_to_id, tag_to_id, lower ) model = torch.load(opts.model_path) model_name = opts.model_path.split('/')[-1].split('.')[0] if use_gpu: model.cuda() model.eval() t = time.time() eval(model, test_data) print(time.time() - t)
[ 2, 19617, 28, 40477, 12, 23, 198, 11748, 2172, 29572, 198, 11748, 28034, 198, 11748, 640, 198, 11748, 2298, 293, 198, 6738, 28034, 13, 2306, 519, 6335, 1330, 35748, 198, 198, 6738, 40213, 1330, 1635, 198, 6738, 3384, 4487, 1330, 1635, ...
2.524096
830
from openbiolink.graph_creation.metadata_db_file.edge.dbMetadataEdge import DbMetadataEdge from openbiolink.graph_creation.types.dbType import DbType
[ 6738, 1280, 65, 1669, 676, 13, 34960, 62, 38793, 13, 38993, 62, 9945, 62, 7753, 13, 14907, 13, 9945, 9171, 14706, 37021, 1330, 360, 65, 9171, 14706, 37021, 198, 6738, 1280, 65, 1669, 676, 13, 34960, 62, 38793, 13, 19199, 13, 9945, 6...
3.125
48
import mahotas as mh import glob import os # rename files from 0 to number of files. files = glob.glob("/path/*") files.sort() if not os.path.isdir("/path/renamed/"): os.mkdir("/path/renamed/") for i in range(len(files)): print("Processing " + files[i]) renamedFile = mh.imread(files[i]) mh.imsave("/path/renamed/" + str(i).zfill(5) + ".tif", renamedFile)
[ 11748, 42768, 313, 292, 355, 285, 71, 198, 11748, 15095, 198, 11748, 28686, 198, 198, 2, 36265, 3696, 422, 657, 284, 1271, 286, 3696, 13, 198, 198, 16624, 796, 15095, 13, 4743, 672, 7203, 14, 6978, 15211, 4943, 198, 16624, 13, 30619, ...
2.448052
154
import os import re from base64 import b64decode from pathlib import Path import requests username = os.environ["GITHUB_USERNAME"] password = os.environ["GITHUB_PERSONAL_ACCESS_TOKEN"] auth = requests.auth.HTTPBasicAuth(username, password) directory = Path(__file__).resolve().parent.parent / "github" directory.mkdir(exist_ok=True) start_url = "https://api.github.com/search/code?q=view+language:lookml" next_url = None page = 1 with requests.Session() as session: session.auth = auth while True: response = session.get(next_url or start_url) response.raise_for_status() links = response.headers["Link"] finds = re.findall( r"<(https://api.github.com/search/code\?" r'q=view\+language%3Alookml&page=\d+)>; rel="next"', links, ) if finds: next_url = finds[0] else: next_url = None print(next_url) urls = [item["url"] for item in response.json()["items"]] print(f"Downloading all content from page {page}") for url in urls: response = session.get(url) response.raise_for_status() response_json = response.json() name = response_json["name"] encoded = response_json["content"] content = b64decode(encoded).decode("utf-8") if ( name.endswith(".lookml") or content.startswith("-") or "- view" in content ): continue file_path = directory / name with file_path.open("w+") as file: file.write(content) if next_url is None: break else: page += 1
[ 11748, 28686, 198, 11748, 302, 198, 6738, 2779, 2414, 1330, 275, 2414, 12501, 1098, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 11748, 7007, 198, 198, 29460, 796, 28686, 13, 268, 2268, 14692, 38, 10554, 10526, 62, 29904, 20608, 8973, ...
2.09964
833
import os import sys sys.path.insert(0, os.path.abspath('..')) project = 'carreralib' copyright = '2015-2017 Thomas Kemmer' version = get_version(b'../carreralib/__init__.py') release = version extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.coverage', 'sphinx.ext.doctest', 'sphinx.ext.todo' ] exclude_patterns = ['_build'] master_doc = 'index' html_theme = 'default'
[ 11748, 28686, 198, 11748, 25064, 198, 198, 17597, 13, 6978, 13, 28463, 7, 15, 11, 28686, 13, 6978, 13, 397, 2777, 776, 10786, 492, 6, 4008, 628, 198, 198, 16302, 796, 705, 7718, 260, 1373, 571, 6, 198, 22163, 4766, 796, 705, 4626, ...
2.327381
168
def lcs(x, y): """ Longest Common Subsequence """ n = len(x) + 1 m = len(y) + 1 table = [ [0]*m for i in range(n) ] for i in range(n): for j in range(m): # If either string is empty, then lcs = 0 if i == 0 or j == 0: table[i][j] = 0 elif x[i - 1] == y[j - 1]: table[i][j] = 1 + table[i-1][j-1] else: table[i][j] = max(table[i-1][j], table[i][j-1]) return table[len(x)][len(y)] if __name__ == '__main__': x = "AGGTAB" y = "GXTXAYB" print lcs(x, y)
[ 4299, 300, 6359, 7, 87, 11, 331, 2599, 198, 197, 37811, 198, 197, 14617, 395, 8070, 3834, 43167, 220, 198, 197, 37811, 198, 197, 77, 796, 18896, 7, 87, 8, 1343, 352, 198, 197, 76, 796, 18896, 7, 88, 8, 1343, 352, 628, 197, 11487...
1.898113
265
from models.methods import method from typing import Any
[ 6738, 4981, 13, 24396, 82, 1330, 2446, 198, 6738, 19720, 1330, 4377, 628 ]
4.461538
13
#!/usr/bin/env python # encoding: utf-8 """ @author: sherlock @contact: sherlockliao01@gmail.com """ import logging import os import sys sys.path.append('.') from fastreid.config import get_cfg from projects.InterpretationReID.interpretationreid.engine import DefaultTrainer, default_argument_parser, default_setup, launch from fastreid.utils.checkpoint import Checkpointer from projects.InterpretationReID.interpretationreid.evaluation import ReidEvaluator import projects.InterpretationReID.interpretationreid as PII from fastreid.utils.logger import setup_logger def setup(args): """ Create configs_old and perform basic setups. """ cfg = get_cfg() PII.add_interpretation_config(cfg) cfg.merge_from_file(args.config_file) cfg.merge_from_list(args.opts) cfg.freeze() default_setup(cfg, args) return cfg if __name__ == "__main__": args = default_argument_parser().parse_args() print("Command Line Args:", args) launch( main, args.num_gpus, num_machines=args.num_machines, machine_rank=args.machine_rank, dist_url=args.dist_url, args=(args,), )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 21004, 25, 3384, 69, 12, 23, 198, 37811, 198, 31, 9800, 25, 220, 15059, 5354, 198, 31, 32057, 25, 15059, 5354, 75, 13481, 486, 31, 14816, 13, 785, 198, 37811, 198, 198, 11748, 1...
2.579065
449
from collections import deque from asynciomeasures.events import Event
[ 6738, 17268, 1330, 390, 4188, 198, 6738, 355, 2047, 979, 462, 13846, 13, 31534, 1330, 8558, 628 ]
4.235294
17
# Copyright 2021, Peter Birch, mailto:peter@lightlogic.co.uk # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from cocotb_bus.drivers import Driver from cocotb.triggers import RisingEdge from ..driver_common import BaseDriver
[ 2, 15069, 33448, 11, 5613, 47631, 11, 6920, 1462, 25, 79, 2357, 31, 2971, 6404, 291, 13, 1073, 13, 2724, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, ...
3.735751
193
# Prim's Algorithm in Python INF = 9999999 # number of vertices in graph V = 5 # create a 2d array of size 5x5 # for adjacency matrix to represent graph G = [ [0, 9, 75, 0, 0], [9, 0, 95, 19, 42], [75, 95, 0, 51, 66], [0, 19, 51, 0, 31], [0, 42, 66, 31, 0], ] # create a array to track selected vertex # selected will become true otherwise false selected = [0, 0, 0, 0, 0] # set number of edge to 0 no_edge = 0 # the number of egde in minimum spanning tree will be # always less than(V - 1), where V is number of vertices in # graph # choose 0th vertex and make it true selected[0] = True # print for edge and weight print("Edge : Weight\n") while no_edge < V - 1: # For every vertex in the set S, find the all adjacent vertices # , calculate the distance from the vertex selected at step 1. # if the vertex is already in the set S, discard it otherwise # choose another vertex nearest to selected vertex at step 1. minimum = INF x = 0 y = 0 for i in range(V): if selected[i]: for j in range(V): if (not selected[j]) and G[i][j]: # not in selected and there is an edge if minimum > G[i][j]: minimum = G[i][j] x = i y = j print(str(x) + "-" + str(y) + ":" + str(G[x][y])) selected[y] = True no_edge += 1
[ 2, 11460, 338, 978, 42289, 287, 11361, 201, 198, 201, 198, 1268, 37, 796, 860, 24214, 2079, 201, 198, 2, 1271, 286, 9421, 1063, 287, 4823, 201, 198, 53, 796, 642, 201, 198, 2, 2251, 257, 362, 67, 7177, 286, 2546, 642, 87, 20, 20...
2.223404
658
#!/usr/bin/env python '''Tests for the likelihood.py module''' from time import perf_counter_ns import pytest import numpy as np from numpy.testing import assert_array_equal, assert_almost_equal from scipy.stats import gamma import likelihood SMALL_FIT_PARAMS = { 'baseline_intensities': np.asarray([1, 2, np.nan, np.nan]), 'r_h': 1.5, 'r_c': 0.5 } SIMPLE_DIST_PARAMS = { 'self_excitation_shape': 2, 'self_excitation_scale': 1, 'discharge_excitation_shape': 3, 'discharge_excitation_scale': 2 } SMALL_CASES_FILE = 'tests/fixtures/small.csv' SMALL_COVARIATES_FILE = 'tests/fixtures/small_covariates.csv' LARGE_FIT_PARAMS = { 'baseline_intensities': np.asarray([0.3, 0.4, 0.6, 0.9]), 'r_h': 1.5, 'r_c': 0.5 } FULL_DIST_PARAMS = { 'self_excitation_shape': 2.6, 'self_excitation_scale': 2.5, 'discharge_excitation_shape': 2.6, 'discharge_excitation_scale': 2.5 } def test_read_and_tidy_data(): '''Test that a CSV file with care home IDs as a header row is read, sorted, and split correctly.''' ids, values = likelihood.read_and_tidy_data(SMALL_CASES_FILE) assert_array_equal(ids, [14, 16, 35]) assert_array_equal( values, [[4, 1, 6], [4, 0, 3], [6, 66, 2]] ) def test_carehome_intensity_null(small_cases, small_covariates): '''Test that calculating the null-case intensity (based on mapping banded carehome size to a base intensity) gives the correct result''' _, cases = small_cases _, covariates = small_covariates intensity = likelihood.carehome_intensity_null( covariates=covariates, cases=cases, fit_params=SMALL_FIT_PARAMS ) assert_array_equal(intensity, [[1, 2, 2], [1, 2, 2], [1, 2, 2]]) def test_single_excitation(small_cases): '''Test that excitation terms of the form e_i(t) = \\sum_{s<t} f(t - s) triggers_i(s) are correctly calculated''' _, cases = small_cases excitation = likelihood.single_excitation(cases, 2, 1) assert_almost_equal( excitation, [[0, 0, 0], [1.472, 0.368, 2.207], [2.554, 0.271, 2.728]], decimal=3 ) def test_cached_single_excitation(small_cases): ''' Test that the caching of the single_excitation function works correctly. ''' _, cases = small_cases cases.flags.writeable = False shape = SIMPLE_DIST_PARAMS['self_excitation_shape'] scale = SIMPLE_DIST_PARAMS['self_excitation_scale'] uncached_start = perf_counter_ns() uncached_excitation = likelihood.single_excitation(cases, shape, scale) uncached_end = perf_counter_ns() first_excitation = likelihood.cached_single_excitation( cases, shape, scale ) assert_array_equal(uncached_excitation, first_excitation) cached_start = perf_counter_ns() cached_excitation = likelihood.cached_single_excitation( cases, shape, scale ) cached_end = perf_counter_ns() assert_array_equal(uncached_excitation, cached_excitation) # Cached version should be quicker assert (cached_end - cached_start) < (uncached_end - uncached_start) def test_carehome_intensity_no_discharges(small_cases, small_covariates): '''Test that the behaviour of carehome_intensity in the case where discharges are not considered.''' _, cases = small_cases _, covariates = small_covariates fit_params_no_rh = {**SMALL_FIT_PARAMS, 'r_h': None} intensity = likelihood.carehome_intensity( covariates=covariates, cases=cases, fit_params=fit_params_no_rh, dist_params=SIMPLE_DIST_PARAMS ) assert_almost_equal( intensity, [[1, 2, 2], [1.736, 2.184, 3.104], [2.277, 2.135, 3.364]], decimal=3 ) def test_carehome_intensity_with_discharges(small_cases, small_covariates): '''Test that the behaviour of carehome_intensity is correct in the case where discharges are considered.''' _, cases = small_cases _, covariates = small_covariates discharges = cases[::-1] intensity = likelihood.carehome_intensity( covariates=covariates, cases=cases, fit_params=SMALL_FIT_PARAMS, dist_params=SIMPLE_DIST_PARAMS, discharges=discharges ) assert_almost_equal( intensity, [[1, 2, 2], [2.077, 5.937, 3.217], [3.332, 11.240, 3.810]], decimal=3 ) def test_likelihood(): '''Test that the likelihood calculation is correct''' cases = np.asarray([[3, 1, 0, 1], [1, 0, 2, 1], [0, 0, 0, 1]]) intensity = np.asarray( [[1, 3, 1.5, 6], [4.2, 3.1, 7, 1.4], [2, 5.1, 4.2, 8.9]] ) result = likelihood.likelihood(intensity, cases) assert_almost_equal(result, -39.145, decimal=3) def test_calculate_likelihood_from_files_no_discharges(): '''Test that likelihood is correctly calculated from input files when discharges are not considered.''' fit_params_no_rh = {**SMALL_FIT_PARAMS, 'r_h': None} result = likelihood.calculate_likelihood_from_files( SMALL_CASES_FILE, SMALL_COVARIATES_FILE, fit_params=fit_params_no_rh, dist_params=SIMPLE_DIST_PARAMS ) assert_almost_equal(result, -187.443, decimal=3) def test_calculate_likelihood_from_files_no_cases(): '''Test that likelihood is correctly calculated from input files when cases are not considered.''' fit_params_no_rh = {**SMALL_FIT_PARAMS, 'r_c': 0} result = likelihood.calculate_likelihood_from_files( SMALL_CASES_FILE, SMALL_COVARIATES_FILE, discharges_file=SMALL_CASES_FILE, fit_params=fit_params_no_rh, dist_params=SIMPLE_DIST_PARAMS ) assert_almost_equal(result, -189.046, decimal=3) def test_calculate_likelihood_from_files_no_discharges_or_cases(): '''Test that likelihood is correctly calculated from input files when neither cases nor discharges are considered.''' fit_params_no_rh = {**SMALL_FIT_PARAMS, 'r_h': None, 'r_c': 0} result = likelihood.calculate_likelihood_from_files( SMALL_CASES_FILE, SMALL_COVARIATES_FILE, fit_params=fit_params_no_rh, dist_params=SIMPLE_DIST_PARAMS ) assert_almost_equal(result, -196.466, decimal=3) def test_calculate_likelihood_from_files_with_discharges(): '''Test that likelihood is correctly calculated from input files when discharges are considered.''' result = likelihood.calculate_likelihood_from_files( SMALL_CASES_FILE, SMALL_COVARIATES_FILE, discharges_file=SMALL_CASES_FILE, fit_params=SMALL_FIT_PARAMS, dist_params=SIMPLE_DIST_PARAMS ) assert_almost_equal(result, -182.761, decimal=3) def test_calculate_likelihood_from_files_missing_discharges(): '''Test that an error is generated when r_h is provided but discharge data are not''' with pytest.raises(AssertionError): likelihood.calculate_likelihood_from_files( SMALL_CASES_FILE, SMALL_COVARIATES_FILE, fit_params=SMALL_FIT_PARAMS, dist_params=SIMPLE_DIST_PARAMS ) def test_intensity_performance_base(large_test_data, benchmark): ''' Test the performance of the intensity function for the base case ''' _, cases, covariates, _ = large_test_data kwargs = { 'fit_params': {**LARGE_FIT_PARAMS, 'r_h': None, 'r_c': None}, 'covariates': covariates, 'cases': cases } # Ensure that numba can jit the function before timing it likelihood.carehome_intensity_null(**kwargs) benchmark(likelihood.carehome_intensity_null, **kwargs) def test_likelihood_performance(large_test_data, benchmark): ''' Test the performance of the calculation of likelihood from the intensity and case distribution.''' _, cases, covariates, discharges = large_test_data intensity = likelihood.carehome_intensity( fit_params=LARGE_FIT_PARAMS, covariates=covariates, cases=cases, discharges=discharges, dist_params=FULL_DIST_PARAMS ) benchmark(likelihood.likelihood, intensity, cases)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 7061, 6, 51, 3558, 329, 262, 14955, 13, 9078, 8265, 7061, 6, 628, 198, 6738, 640, 1330, 23035, 62, 24588, 62, 5907, 198, 11748, 12972, 9288, 198, 11748, 299, 32152, 355, 45941, ...
2.433243
3,303
from django.db import models
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198 ]
3.625
8
import unittest if __name__ == "__main__": unittest.main()
[ 11748, 555, 715, 395, 628, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 555, 715, 395, 13, 12417, 3419, 198 ]
2.392857
28
import logging from iemit_plugin import IEmitter from plugins.emitters.base_http_emitter import BaseHttpEmitter logger = logging.getLogger('crawlutils')
[ 11748, 18931, 198, 198, 6738, 1312, 368, 270, 62, 33803, 1330, 314, 10161, 1967, 198, 6738, 20652, 13, 368, 45512, 13, 8692, 62, 4023, 62, 368, 1967, 1330, 7308, 43481, 10161, 1967, 198, 198, 6404, 1362, 796, 18931, 13, 1136, 11187, 1...
3.25
48
import torch import torch.nn as nn import numpy as np import torch.nn.functional as F import pywt
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 11748, 12972, 46569, 628 ]
3.3
30
import sys import numpy as np import json import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.backends.backend_pdf import PdfPages from datetime import datetime, timedelta import matplotlib.dates as mdates import emoji
[ 11748, 25064, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 33918, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 2603, 29487, 8019, 13, 19581, 1330, 7536, 8479, 1436, 198, 6738, 2603, 29487, 8019, 13, 1891, ...
3.5
74
""" Setup file """ import os import sys from setuptools import setup, find_packages HERE = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(HERE, 'README.rst')).read() CHANGES = open(os.path.join(HERE, 'CHANGES.rst')).read() REQUIREMENTS = [ 'pyramid', 'six', ] TEST_REQUIREMENTS = [ 'mock', ] if sys.version_info[:2] < (2, 7): TEST_REQUIREMENTS.extend(['unittest2']) if __name__ == "__main__": setup( name='pyramid_duh', version='0.1.2', description='Useful utilities for every pyramid app', long_description=README + '\n\n' + CHANGES, classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: Pyramid', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Utilities', ], author='Steven Arcangeli', author_email='arcangeli07@gmail.com', url='http://pyramid-duh.readthedocs.org/', keywords='pyramid util utility', license='MIT', zip_safe=False, include_package_data=True, packages=find_packages(exclude=('tests',)), install_requires=REQUIREMENTS, tests_require=REQUIREMENTS + TEST_REQUIREMENTS, test_suite='tests', )
[ 37811, 31122, 2393, 37227, 198, 11748, 28686, 198, 11748, 25064, 198, 198, 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 628, 198, 39, 9338, 796, 28686, 13, 6978, 13, 397, 2777, 776, 7, 418, 13, 6978, 13, 15908, 3672, 7, ...
2.233799
787
import requests, os from dotenv import load_dotenv load_dotenv() API_TOKEN = os.getenv('API_TOKEN')
[ 11748, 7007, 11, 28686, 198, 6738, 16605, 24330, 1330, 3440, 62, 26518, 24330, 198, 198, 2220, 62, 26518, 24330, 3419, 198, 198, 17614, 62, 10468, 43959, 796, 28686, 13, 1136, 24330, 10786, 17614, 62, 10468, 43959, 11537 ]
2.72973
37
from unittest import TestCase from mock import patch, MagicMock from mangrove.datastore.database import DatabaseManager from datawinners.questionnaire.library import QuestionnaireLibrary
[ 6738, 555, 715, 395, 1330, 6208, 20448, 198, 198, 6738, 15290, 1330, 8529, 11, 6139, 44, 735, 198, 198, 6738, 582, 27333, 303, 13, 19608, 459, 382, 13, 48806, 1330, 24047, 13511, 198, 6738, 4818, 707, 259, 2741, 13, 25652, 24042, 13, ...
3.958333
48
import chainer from chainer import functions from chainer import links import chainer_chemistry from chainer_chemistry.links.connection.graph_linear import GraphLinear from chainer_chemistry.utils import is_sparse
[ 11748, 6333, 263, 198, 6738, 6333, 263, 1330, 5499, 198, 6738, 6333, 263, 1330, 6117, 198, 198, 11748, 6333, 263, 62, 15245, 4592, 198, 6738, 6333, 263, 62, 15245, 4592, 13, 28751, 13, 38659, 13, 34960, 62, 29127, 1330, 29681, 14993, ...
3.789474
57
print("Hello")
[ 198, 198, 4798, 7203, 15496, 4943, 198 ]
2.428571
7
from numpy.testing import assert_array_almost_equal as array_assert from badboids.boids import SimulationParameters def test_simulation_parameters_init(): """Tests Simulation Parameters constructor""" # Arrange formation_flying_distance = 800 formation_flying_strength = 0.10 alert_distance = 8 move_to_middle_strength = 0.2 delta_t = 1.5 # Act sut = SimulationParameters(formation_flying_distance, formation_flying_strength, alert_distance, move_to_middle_strength, delta_t) # Assert array_assert(sut.formation_flying_distance, formation_flying_distance) array_assert(sut.formation_flying_strength, formation_flying_strength) array_assert(sut.alert_distance, alert_distance) array_assert(sut.move_to_middle_strength, move_to_middle_strength) array_assert(sut.delta_t, delta_t) def test_get_defaults(): """Tests Simulation Parameters get defaults method""" # Arrange expected_formation_flying_distance = 10000 expected_formation_flying_strength = 0.125 expected_alert_distance = 100 expected_move_to_middle_strength = 0.01 expected_delta_t = 1.0 # Act parameters = SimulationParameters.get_defaults() # Assert assert parameters.formation_flying_distance == expected_formation_flying_distance assert parameters.formation_flying_strength == expected_formation_flying_strength assert parameters.alert_distance == expected_alert_distance assert parameters.move_to_middle_strength == expected_move_to_middle_strength assert parameters.delta_t == expected_delta_t
[ 6738, 299, 32152, 13, 33407, 1330, 6818, 62, 18747, 62, 28177, 62, 40496, 355, 7177, 62, 30493, 198, 198, 6738, 2089, 65, 10994, 13, 65, 10994, 1330, 41798, 48944, 628, 198, 4299, 1332, 62, 14323, 1741, 62, 17143, 7307, 62, 15003, 335...
3.007421
539
#-*- coding: utf-8 -*- from django_town.core.settings import OAUTH2_SETTINGS try: if not OAUTH2_SETTINGS.ACCESS_TOKEN_SECRET_KEY: raise ImportError except KeyError: # import traceback # traceback.print_exc() raise ImportError from django.db import models from django.conf import settings from django.contrib import admin from django_town.cache.model import CachingModel from django_town.core.fields import JSONField from django_town.utils import generate_random_from_vschar_set # class ServiceSecretKey(CachingModel): # cache_key_format = "_ut_o2ss:%(service__pk)d" # # service = models.ForeignKey(Service, unique=True) # secret_key = models.CharField(max_length=OAUTH2_SETTINGS.SERVICE_SECRET_KEY_LENGTH, # default=lambda: generate_random_from_vschar_set( # OAUTH2_SETTINGS.SERVICE_SECRET_KEY_LENGTH)) def _generate_random_from_vschar_set_for_client_id(): return generate_random_from_vschar_set(OAUTH2_SETTINGS.CLIENT_ID_LENGTH) def _generate_random_from_vschar_set_for_client_secret(): return generate_random_from_vschar_set(OAUTH2_SETTINGS.CLIENT_ID_LENGTH) admin.site.register(Client, admin.ModelAdmin) admin.site.register(Service, admin.ModelAdmin)
[ 2, 12, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 42625, 14208, 62, 12735, 13, 7295, 13, 33692, 1330, 440, 32, 24318, 17, 62, 28480, 51, 20754, 198, 198, 28311, 25, 198, 220, 220, 220, 611, 407, 440, 32, 2...
2.42803
528
# List files in a directory. Useful for testing the path from local_tools import * from image_renamer import ImageRenamer if confirm_config('path'): img_path = get_config('path') fl = ImageRenamer(img_path) for ff in fl.image_files(): print(ff)
[ 2, 7343, 3696, 287, 257, 8619, 13, 49511, 329, 4856, 262, 3108, 198, 6738, 1957, 62, 31391, 1330, 1635, 198, 6738, 2939, 62, 918, 2382, 1330, 7412, 26764, 2382, 198, 361, 6216, 62, 11250, 10786, 6978, 6, 2599, 198, 220, 220, 220, 33...
2.880435
92
import os
[ 11748, 28686, 201 ]
3.333333
3
import os from .default import DefaultModelConfig
[ 11748, 28686, 198, 6738, 764, 12286, 1330, 15161, 17633, 16934, 198 ]
4.545455
11
from __future__ import print_function import time import tensorflow as tf from data import DataGenerator if __name__ == '__main__': main()
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 11748, 640, 198, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 198, 6738, 1366, 1330, 6060, 8645, 1352, 628, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, ...
3.125
48
# Dimmer Switch class # Main code # Create first DimmerSwitch, turn on and raise level twice oDimmer1 = DimmerSwitch('Dimmer1') oDimmer1.turnOn() oDimmer1.raiseLevel() oDimmer1.raiseLevel() # Create second DimmerSwitch, turn on and raise level 3 times oDimmer2 = DimmerSwitch('Dimmer2') oDimmer2.turnOn() oDimmer2.raiseLevel() oDimmer2.raiseLevel() oDimmer2.raiseLevel() # Create third DimmerSwitch, using the default settings oDimmer3 = DimmerSwitch('Dimmer3') # Ask each switch to show itself oDimmer1.show() oDimmer2.show() oDimmer3.show()
[ 2, 360, 10957, 14645, 1398, 628, 220, 220, 220, 220, 198, 2, 8774, 2438, 198, 198, 2, 13610, 717, 360, 10957, 38978, 11, 1210, 319, 290, 5298, 1241, 5403, 198, 78, 35, 10957, 16, 796, 360, 10957, 38978, 10786, 35, 10957, 16, 11537, ...
2.807107
197
#!/usr/bin/env python3 import logging import argparse from pathlib import Path from vosk import list_models, list_languages from vosk.transcriber.transcriber import Transcriber parser = argparse.ArgumentParser( description = 'Transcribe audio file and save result in selected format') parser.add_argument( '--model', '-m', type=str, help='model path') parser.add_argument( '--list-models', default=False, action='store_true', help='list available models') parser.add_argument( '--list-languages', default=False, action='store_true', help='list available languages') parser.add_argument( '--model-name', '-n', type=str, help='select model by name') parser.add_argument( '--lang', '-l', default='en-us', type=str, help='select model by language') parser.add_argument( '--input', '-i', type=str, help='audiofile') parser.add_argument( '--output', '-o', default='', type=str, help='optional output filename path') parser.add_argument( '--output-type', '-t', default='txt', type=str, help='optional arg output data type') parser.add_argument( '--log-level', default='INFO', help='logging level') if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 18931, 198, 11748, 1822, 29572, 198, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 410, 418, 74, 1330, 1351, 62, 27530, 11, 1351, 62, 75, 33213, 198, 6738, 410, 418, ...
2.546535
505
import numpy as np import cv2 from imutils.object_detection import non_max_suppression import pytesseract from matplotlib import pyplot as plt print(ocr(["./images/car_wash.png"]))
[ 11748, 299, 32152, 355, 45941, 198, 11748, 269, 85, 17, 198, 6738, 545, 26791, 13, 15252, 62, 15255, 3213, 1330, 1729, 62, 9806, 62, 18608, 2234, 198, 11748, 12972, 83, 408, 263, 529, 198, 6738, 2603, 29487, 8019, 1330, 12972, 29487, ...
2.967213
61
# Generated by Django 2.0 on 2018-01-28 21:44 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 362, 13, 15, 319, 2864, 12, 486, 12, 2078, 2310, 25, 2598, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.966667
30
""" Tests for validators """ from decimal import Decimal from unittest.mock import Mock import random import string from styler_validation import validators as va from styler_validation import messages as msg
[ 37811, 30307, 329, 4938, 2024, 198, 37811, 198, 198, 6738, 32465, 1330, 4280, 4402, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 44123, 198, 11748, 4738, 198, 11748, 4731, 198, 198, 6738, 8944, 1754, 62, 12102, 341, 1330, 4938, 2024, ...
3.619048
63
from django.core.files.storage import FileSystemStorage from django.db import models # Create your models here. from datetime import date from django.urls import reverse #Used to generate URLs by reversing the URL patterns from django.contrib.auth.models import User #Blog author or commenter """ Metoda vrac cestu k uploadovanmu plaktu. """
[ 6738, 42625, 14208, 13, 7295, 13, 16624, 13, 35350, 1330, 9220, 11964, 31425, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 198, 2, 13610, 534, 4981, 994, 13, 198, 198, 6738, 4818, 8079, 1330, 3128, 198, 6738, 42625, 14208, 13, ...
3.649485
97
print(list(range(10, 0, -2))) # if start > end and step > 0: # a list generated from start to no more than end with step as constant increment # if start > end and step < 0: # an empty list generated # if start < end and step > 0: # an empty list generated # if start < end and step < 0 # a list generated from start to no more than end with step as constant decrement
[ 4798, 7, 4868, 7, 9521, 7, 940, 11, 657, 11, 532, 17, 22305, 198, 2, 611, 923, 1875, 886, 290, 2239, 1875, 657, 25, 198, 2, 257, 1351, 7560, 422, 923, 284, 645, 517, 621, 886, 351, 2239, 355, 6937, 18703, 198, 2, 611, 923, 187...
3.548077
104
""" github : https://github.com/amingolnari/Deep-Learning-Course Author : Amin Golnari Keras Version : 2.2.4 Date : 4/12/2018 Keras CNN Classification on MNIST Data Code 301 """ ## If your GPU is AMD , you can use PlaidML Backend # import os # os.environ["KERAS_BACKEND"] = "plaidml.keras.backend" from keras.models import Sequential from keras.layers import Dense, Flatten, Dropout, Conv2D, MaxPool2D from keras.optimizers import SGD from keras.datasets import mnist from keras.utils.np_utils import to_categorical import matplotlib.pyplot as plt # Load MNIST Data (Download for First) if __name__ == "__main__": main()
[ 37811, 198, 12567, 1058, 3740, 1378, 12567, 13, 785, 14, 3723, 10875, 2743, 14, 29744, 12, 41730, 12, 49046, 198, 13838, 1058, 39869, 402, 10875, 2743, 198, 42, 263, 292, 10628, 1058, 362, 13, 17, 13, 19, 198, 10430, 1058, 604, 14, ...
2.837838
222
start = 104200 end = 702648265 for arm1 in range(start, end + 1): exp = len(str(arm1)) num_sum = 0 c = arm1 while c > 0: num = c % 10 num_sum += num ** exp c //= 10 if arm1 != num_sum: continue else: if arm1 == num_sum: print("The first Armstrong number encountered is:", arm1) break #####OUTPUT##### ## The first Armstrong number encountered is: 548834 ## Process finished with exit code 0
[ 9688, 796, 14436, 2167, 201, 198, 437, 796, 4317, 2075, 2780, 22980, 201, 198, 201, 198, 1640, 3211, 16, 287, 2837, 7, 9688, 11, 886, 1343, 352, 2599, 201, 198, 201, 198, 220, 220, 220, 1033, 796, 18896, 7, 2536, 7, 1670, 16, 4008...
2.023077
260
import requests import json
[ 11748, 7007, 201, 198, 11748, 33918, 201, 198, 201, 198, 201, 198, 201 ]
2.692308
13
#!/bin/env python3 """Handling events as tickets The goal here is, provided a maintenance event, create an event if not a duplicate. To determine if not duplicate, use some combination of values to form a key. Methods to delete, update, and otherwise transform the ticket should be available A base class, Ticket, is provided to do some boiler plate things and enforce a consistent interface. """ from textwrap import dedent from jira import JIRA
[ 2, 48443, 8800, 14, 24330, 21015, 18, 198, 198, 37811, 12885, 1359, 2995, 355, 8587, 198, 198, 464, 3061, 994, 318, 11, 2810, 257, 9262, 1785, 11, 2251, 281, 1785, 611, 407, 257, 198, 646, 489, 5344, 13, 1675, 5004, 611, 407, 23418,...
3.947826
115
from cicdctl.commands.types.flag import FlagParamType
[ 6738, 269, 291, 67, 34168, 13, 9503, 1746, 13, 19199, 13, 32109, 1330, 19762, 22973, 6030, 628 ]
3.235294
17
#!/usr/bin/env python # Copyright 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Merge translations from a set of .po or XMB files into a set of .po files. Usage: ../tools/merge_messages <source-dir> <template-file> ../tools/merge_messages <source-dir> <template-file> <target-dir> ../tools/merge_messages <source-po-file> <template-file> <target-po-file> <source-dir> should be a directory containing a subdirectories named with locale codes (e.g. pt_BR). For each locale, this script looks for the first .po or .xml file it finds anywhere under <source-dir>/<locale-code>/ and adds all its messages and translations to the corresponding django.po file in the target directory, at <target-dir>/<locale-code>/LC_MESSAGES/django.po. <template-file> is the output file from running: 'find_missing_translations --format=po' With the name that corresponds to the --format=xmb output. Make sure to run this in a tree that corresponds to the version used for generating the xmb file or the resulting merge will be wrong. See validate_merge for directions on verifying the merge was correct. If <target-dir> is unspecified, it defaults to the app/locale directory of the current app. Alternatively, you can specify a single source file and a single target file to update. When merging messages from a source file into a target file: - Empty messages and messages marked "fuzzy" in the source file are ignored. - Translations in the source file will replace any existing translations for the same messages in the target file. - Other translations in the source file will be added to the target file. - If the target file doesn't exist, it will be created. - To minimize unnecessary changes from version to version, the target file has no "#: filename:line" comments and the messages are sorted by msgid. """ import babel.messages from babel.messages import pofile import codecs import os import sys import xml.sax def log(text): """Prints out Unicode text.""" print text.encode('utf-8') def log_change(old_message, new_message): """Describes an update to a message.""" if not old_message: if new_message.id: log('+ msgid "%s"' % str(new_message.id)) else: print >>sys.stderr, 'no message id: %s' % new_message log('+ msgstr "%s"' % str(new_message.string.encode('ascii', 'ignore'))) if new_message.flags: log('+ #, %s' % ', '.join(sorted(new_message.flags))) else: if (new_message.string != old_message.string or new_message.flags != old_message.flags): log(' msgid "%s"' % old_message.id) log('- msgstr "%s"' % old_message.string) if old_message.flags: log('- #, %s' % ', '.join(sorted(old_message.flags))) log('+ msgstr "%s"' % new_message.string) if new_message.flags: log('+ #, %s' % ', '.join(sorted(new_message.flags))) def create_file(filename): """Opens a file for writing, creating any necessary parent directories.""" if not os.path.exists(os.path.dirname(filename)): os.makedirs(os.path.dirname(filename)) return open(filename, 'w') def merge(source, target_filename): """Merges the messages from the source Catalog into a .po file at target_filename. Creates the target file if it doesn't exist.""" if os.path.exists(target_filename): target = pofile.read_po(open(target_filename)) for message in source: if message.id and message.string and not message.fuzzy: log_change(message.id in target and target[message.id], message) # This doesn't actually replace the message! It just updates # the fields other than the string. See Catalog.__setitem__. target[message.id] = message # We have to mutate the message to update the string and flags. target[message.id].string = message.string target[message.id].flags = message.flags else: for message in source: log_change(None, message) target = source target_file = create_file(target_filename) pofile.write_po(target_file, target, no_location=True, sort_output=True, ignore_obsolete=True) target_file.close() if __name__ == '__main__': args = sys.argv[1:] if len(args) not in [1, 2, 3]: print __doc__ sys.exit(1) args = (args + [None, None])[:3] source_path = args[0] template_path = args[1] target_path = args[2] or os.path.join(os.environ['APP_DIR'], 'locale') # If a single file is specified, merge it. if ((source_path.endswith('.po') or source_path.endswith('.xml')) and target_path.endswith('.po')): print target_path merge_file(source_path, target_path, template_path) sys.exit(0) # Otherwise, we expect two directories. if not os.path.isdir(source_path) or not os.path.isdir(target_path): print __doc__ sys.exit(1) # Find all the source files. source_filenames = {} # {locale: po_filename} def find_po_file(key, dir, filenames): """Looks for a .po file and records it in source_filenames.""" for filename in filenames: if filename.endswith('.po') or filename.endswith('.xml'): source_filenames[key] = os.path.join(dir, filename) for locale in os.listdir(source_path): os.path.walk(os.path.join(source_path, locale), find_po_file, locale.replace('-', '_')) # Merge them into the target files. for locale in sorted(source_filenames.keys()): target = os.path.join(target_path, locale, 'LC_MESSAGES', 'django.po') print target merge_file(source_filenames[locale], target, template_path)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 15069, 3050, 3012, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 28...
2.657107
2,406
# derwin.py - testing a window within a window import curses # main if __name__ == "__main__": curses.wrapper(main)
[ 2, 4587, 5404, 13, 9078, 532, 4856, 257, 4324, 1626, 257, 4324, 198, 11748, 43878, 628, 198, 2, 1388, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 43878, 13, 48553, 7, 12417, 8, 198 ]
2.952381
42
import sys import logging from unicorn import * from unicorn.arm_const import * from androidemu.emulator import Emulator from UnicornTraceDebugger import udbg logging.basicConfig(stream=sys.stdout, level=logging.DEBUG, format="%(asctime)s %(levelname)7s %(name)34s | %(message)s") logger = logging.getLogger(__name__) emulator = Emulator() libc = emulator.load_library('jnilibs/libc.so', do_init=False) libso = emulator.load_library('jnilibs/libnative-lib.so', do_init=False) # data segment data_base = 0xa00000 data_size = 0x10000 * 3 emulator.mu.mem_map(data_base, data_size) emulator.mu.mem_write(data_base, b'123') emulator.mu.reg_write(UC_ARM_REG_R0, data_base) try: dbg = udbg.UnicornDebugger(emulator.mu) addr_start = 0xcbc66000 + 0x9B68 + 1 addr_end = 0xcbc66000 + 0x9C2C emulator.mu.emu_start(addr_start, addr_end) r2 = emulator.mu.reg_read(UC_ARM_REG_R2) result = emulator.mu.mem_read(r2, 16) print(result.hex()) except UcError as e: list_tracks = dbg.get_tracks() for addr in list_tracks[-100:-1]: print(hex(addr - 0xcbc66000)) print (e)
[ 11748, 25064, 198, 11748, 18931, 198, 6738, 44986, 1330, 1635, 198, 6738, 44986, 13, 1670, 62, 9979, 1330, 1635, 198, 6738, 19286, 368, 84, 13, 368, 8927, 1330, 2295, 8927, 198, 6738, 39481, 2898, 558, 27509, 1362, 1330, 334, 9945, 70, ...
2.371795
468
#!/usr/bin/python # -*- coding: utf-8 -*- """ This package implements several community detection. Originally based on community aka python-louvain library from Thomas Aynaud (https://github.com/taynaud/python-louvain) """ from .community_ext import ( partition_at_level, modularity, best_partition, generate_dendrogram, induced_graph, load_binary, estimate_gamma, estimate_mu, ilfr_mu_loglikelihood, compare_partitions, model_log_likelihood ) __author__ = """Aleksey Tikhonov (altsoph@gmail.com)""" __author__ = """Liudmila Ostroumova Prokhorenkova (ostroumova-la@yandex-team.ru)""" # Copyright (C) 2018 by # Aleksey Tikhonov (altsoph@gmail.com> # Liudmila Ostroumova Prokhorenkova (ostroumova-la@yandex-team.ru) # All rights reserved. # BSD license.
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 1212, 5301, 23986, 1811, 2055, 13326, 13, 198, 198, 22731, 1912, 319, 2055, 22430, 21015, 12, 75, 280, 85, 391, ...
2.472727
330
#!/usr/bin/env python import rospy from std_msgs.msg import String from nav_msgs.msg import Odometry from trajectory_msgs.msg import JointTrajectory from control_msgs.msg import JointTrajectoryControllerState if __name__ == "__main__": listener()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 686, 2777, 88, 198, 6738, 14367, 62, 907, 14542, 13, 19662, 1330, 10903, 198, 6738, 6812, 62, 907, 14542, 13, 19662, 1330, 10529, 15748, 198, 6738, 22942, 62, 907, 14542, 13, 19...
3.096386
83
#Botpic:https://upload.wikimedia.org/wikipedia/commons/thumb/b/b8/Red_Rose_Photography.jpg/800px-Red_Rose_Photography.jpg #Botpic:https://commons.wikimedia.org/wiki/File:Red_Rose_Photography.jpg #reference:https://www.youtube.com/watch?v=SPTfmiYiuok import discord import os import requests import json import math, random from replit import db from keep_alive import keep_alive import asyncpraw, asyncprawcore #import commands import time, asyncio, datetime from discord.ext import tasks from discord import Member from discord.ext.commands import has_permissions, MissingPermissions from prawcore import NotFound import ffmpeg from discord import FFmpegPCMAudio from dotenv import load_dotenv from youtube_search import YoutubeSearch load_dotenv() client = discord.Client() # To cache the every user For on_remove_reaction to be usable # Also enable members intent from https://discord.com/developers/ in bot secition intents = discord.Intents.default() intents.members = True global playing, stream global currently_playing_message #t1 = threading.Timer(10, say_hello) #t1.start() #---------- To keep the bot alive -------------------------- #1. keeping the bot alive ''' #------------------- adding a background task ----------------- status = cycle(['with Python','JetHub']) @bot.event async def on_ready(): change_status.start() print("Your bot is ready") @tasks.loop(seconds=10) async def change_status(): await bot.change_presence(activity=discord.Game(next(status))) #-------------------------------------------------------------- 3. Setup the Uptime Robot : create an account on uptime robot. After creating an account, go to the dashboard and click on Add new monitor (preview) select monitor type Http(s) (preview) then go to to ur project on repl.it and copy the url from the top of the console and paste it in url section of the monitor (preview) now set the monitoring interval to every 5 mins (so that it will ping the bot every 5 mins) and click on create monitor twice (preview) Thats itNow go to ur project on repl.it and hit the Run button ''' reddit = asyncpraw.Reddit( client_id="nnhGBCiBxSJysTobl6SLPQ", client_secret=os.environ['rd_client_secret'], password=os.environ['rd_pass'], user_agent="praw_test", username="Alternative-Ad-8849", ) from discord.ext import commands bot = commands.Bot(command_prefix='.', help_command=None, intents=intents) ''' class MyHelpCommand(commands.MinimalHelpCommand): async def send_pages(self): destination = self.get_destination() e = discord.Embed(colour=discord.Color.blurple(), description='') for page in self.paginator.pages: e.description += page await destination.send(embed=e) bot.help_command = MyHelpCommand()''' # My sample help command: # My sample help command: '''@bot.command() async def schedule(ctx, message='Hello There', seconds = 3): #print(ctx.channel.id) m=str(message) id = ctx.message.id print('\n\n\n{}\n\n'.format(m)) author = str(ctx.message.author).split('#')[0] await ctx.message.delete() #id=ctx.channel.id channel = bot.get_channel(id=id) print(id) print(channel) #await channel.send('hi') #await schedule_message(author, m, id, seconds = seconds) #print(ctx.message) #await ctx.message.delete(ctx.message) #await channel.send('hi') #await ctx.send('pong') #print('Im invoked')''' #name='', brief='', help='e.g. `.`' '''@bot.command(name='', brief='', help='e.g. `.`') async def h(ctx, what='general'): #await ctx.send('pong') if str(what).lower()=='general': for command in commands: await ctx.send(command) elif str(what).lower() == 'fuse': for command in fuse_help_commands: await ctx.send(command)''' #------------------------------------------ # _______________________________________________________________________ # ---------------------------- For Music Bot : https://medium.com/pythonland/build-a-discord-bot-in-python-that-plays-music-and-send-gifs-856385e605a1 # _______________________________________________________________________ import os, youtube_dl import ffmpeg class YTDLSource(discord.PCMVolumeTransformer): #Downloads videb name/url and returns full filename #To make leave voice channel if bot is alone in voice channel #_______________________________________________________________________ # ----------------------------- --------------------------------------- # _______________________________________________________________________ # ----------------------------- FM Player ----------------------------- from discord import FFmpegPCMAudio from discord.ext.commands import Bot from dotenv import load_dotenv load_dotenv() #To be implemented global streams streams = None #To get current, next, previous streams # _____________________________________________________ # ///////////////////// FM Player ///////////////////// # _____________________________________________________ ''' async def my_background_task(): await client.wait_until_ready() counter = 0 channel = client.get_channel(id=123456789) # replace with channel_id while not client.is_closed(): counter += 1 await channel.send(counter) print(counter) await asyncio.sleep(60) # task runs every 60 seconds''' '' sad_words = [ "sad", "depressed", "unhappy", "angry", "miserable", "depressing", "hurt", "pain" ] starter_encouragements = [ "Cheer up!", "You are a great person / bot!", ] commandss = [ '\".h fuse\" or \".help fuse\" -> for fuse_auto_attend help', 'fuse auto-attend registration at: https://ioee.herokuapp.com/', '\".inspire\" or \".quote\" -> to display quote ', '\".joke\" -> to display joke', '\".meme\" -> displays best random meme', '\".riddle\" -> displays best random riddle', '\".puns\" -> displays best random puns', '\".knock knock\" -> displays knock knock joke', '\".deactivate\" -> deactivates the bot .activate -> activates the bot', '\".new inspirational_message\" -> Adds new inspirationsl message to db', '\".del inspirational_message\" -> deletes inspirational message from db', '\".list\" -> lists the current inspirational messages', ] fuse_help_commands = [ '\".h\" or \".help\" - for general help', '----------- ------------------------- -----------', 'fuse auto-attend registration at: https://ioee.herokuapp.com/', '---------------------------------', '\".add_user user_token\" -> to add user for auto-fuse attandance', '.remove_user user_token -> to remove user', '\".list_user\" -> to list available users', '\".check class\" or \".snoop class\" -> checks if live class started.', '\".mute unsuccessful\" -> to mute unsuccessful attending_logs. ie. hide \"Live Class not started\" messages', '\".mute successful\" -> to mute successful attending_logs ie. hide messages when attended successfully', '\".unmute unsuccessful\" -> to unmute unsuccessful attending_logs ie. show \"Live Class not started\" messages', '\".umute successful\" -> to unmute successful attending_logs ie. show messages when attended successfully', ] #from discord.ext import commands #bot = commands.Bot(command_prefix='.') #@bot.command() #async def test(ctx): # await ctx.send('I heard you! {0}'.format(ctx.author)) '''print('--------------Test Mode--------------------------------') print(client.servers) print('-------------------------------------------------------')''' if "responding" not in db.keys(): db["responding"] = True if "unsuccessful_logs" not in db.keys(): db["unsuccessful_logs"] = False if "successful_logs" not in db.keys(): db["successful_logs"] = True #---------------Working------------------------ # For scrapping quotes every 1 min. #----------- To list discord servers --------- #----------- To list discord servers --------- class OwnerCommands(commands.Cog): #------------------------- ''' async def unleash_reddit(subreddit, channel_id, no_of_posts=5): channel = bot.get_channel(id=int(channel_id)) submissions_top = await reddit.subreddit(subreddit) submissions_hot = await reddit.subreddit(subreddit) submissions_new = await reddit.subreddit(subreddit) #30% top, 40%hot, 30%new for i in range(0, no_of_posts): print('Unleash for loop:{}'.format(i)) if i < int(no_of_posts/3): submission=random.choice([x async for x in submissions_top.top(limit=25)]) print(a) ''async for x in submissions_top.top(limit=15): if not x.stickied: submission = x #submission = next(x async for x in submissions_top.top('all') if not x.stickied)'' elif i < int(no_of_posts/7): #submission = next(x async for x in submissions_hot.hot('all') if not x.stickied) submission=random.choice([x async for x in submissions_top.hot(limit=35)]) else: #submission = next(x async for x in submissions_new.new('all') if not x.stickied) submission=random.choice([x async for x in #submissions_top.new(limit=15)]) embed=discord.Embed( title=submission.title, description=submission.selftext, #description=submission.title, colour=discord.Color.green()) embed.set_image(url=submission.url) await channel.send(embed=embed)''' keep_alive() bot.run(os.environ['TOKEN']) #client.loop.create_task(my_background_task()) bot.run('token') #
[ 2, 20630, 16564, 25, 5450, 1378, 25850, 13, 20763, 20626, 13, 2398, 14, 31266, 14, 9503, 684, 14, 400, 2178, 14, 65, 14, 65, 23, 14, 7738, 62, 31087, 62, 27248, 4867, 13, 9479, 14, 7410, 8416, 12, 7738, 62, 31087, 62, 27248, 4867,...
3.029022
3,170
# Code Taken from https://github.com/LYH-YF/MWPToolkit # -*- encoding: utf-8 -*- # @Author: Yihuai Lan # @Time: 2021/08/29 22:05:03 # @File: transformer_layer.py import torch import math from torch import nn from torch.nn import functional as F from transformers.activations import gelu_new as gelu_bert from module.Attention.multi_head_attention import MultiHeadAttention from module.Attention.multi_head_attention import EPTMultiHeadAttention from module.Attention.group_attention import GroupAttention from utils.utils import clones
[ 2, 6127, 30222, 422, 3740, 1378, 12567, 13, 785, 14, 11319, 39, 12, 56, 37, 14, 14326, 11571, 970, 15813, 198, 2, 532, 9, 12, 21004, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2488, 13838, 25, 575, 48406, 1872, 14730, 198, 2, 2...
3.143678
174
import math from seal import * from seal_helper import * if __name__ == '__main__': example_ckks_basics()
[ 11748, 10688, 198, 6738, 13810, 1330, 1635, 198, 6738, 13810, 62, 2978, 525, 1330, 1635, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1672, 62, 694, 591, 62, 12093, 873, 3419, 198 ]
2.756098
41
from correlate import * import matplotlib import matplotlib.pyplot as plt import seaborn as sns from matplotlib import rc, rcParams rc('axes', linewidth=1) rc('font', weight='bold', size=10) if __name__ == "__main__": years = 2 layername = 'block2BN' time_threshold, type = 365*years, 'COG' folder = type + '_correlation_{}_years/'.format(years) if not os.path.exists(folder): os.mkdir(folder) interval = file_interval_info(type) y_lim = [0, 0] corre = collections.defaultdict(dict) error = collections.defaultdict(dict) pool = [[0, prefixes[i], regions[i]] for i in range(len(regions))] for i, region in enumerate(prefixes): for stain in stains: corr, std = get_correlation(region + '_' + stain, prefix_idx[region], time_threshold, interval, folder, type, layername, missing=0) corre[region][stain] = corr error[region][stain] = 0 y_lim[1] = max(y_lim[1], corr) y_lim[0] = min(y_lim[0], corr) pool[i][0] -= corr pool.sort() prefixes = [p[1] for p in pool] regions = [p[2] for p in pool] barplots(prefixes, regions, stains, corre, error, '{}days_{}shap_{}'.format(time_threshold, type, layername), folder, y_lim)
[ 6738, 39684, 1330, 1635, 198, 11748, 2603, 29487, 8019, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 384, 397, 1211, 355, 3013, 82, 198, 198, 6738, 2603, 29487, 8019, 1330, 48321, 11, 48321, 10044, 4105, 198...
2.296029
554
""" An example of running autofaiss by pyspark to produce N indices. You need to install pyspark before using the following example. """ from typing import Dict import faiss import numpy as np from autofaiss import build_index # You'd better create a spark session before calling build_index, # otherwise, a spark session would be created by autofaiss with the least configuration. _, index_path2_metric_infos = build_index( embeddings="hdfs://root/path/to/your/embeddings/folder", distributed="pyspark", file_format="parquet", temporary_indices_folder="hdfs://root/tmp/distributed_autofaiss_indices", current_memory_available="10G", max_index_memory_usage="100G", nb_indices_to_keep=10, ) index_paths = sorted(index_path2_metric_infos.keys()) ########################################### # Use case 1: merging 10 indices into one # ########################################### merged = faiss.read_index(index_paths[0]) for rest_index_file in index_paths[1:]: index = faiss.read_index(rest_index_file) faiss.merge_into(merged, index, shift_ids=False) with open("merged-knn.index", "wb") as f: faiss.write_index(merged, faiss.PyCallbackIOWriter(f.write)) ######################################## # Use case 2: searching from N indices # ######################################## K, DIM, all_distances, all_ids, NB_QUERIES = 5, 512, [], [], 2 queries = faiss.rand((NB_QUERIES, DIM)) for rest_index_file in index_paths: index = faiss.read_index(rest_index_file) distances, ids = index.search(queries, k=K) all_distances.append(distances) all_ids.append(ids) dists_arr = np.stack(all_distances, axis=1).reshape(NB_QUERIES, -1) knn_ids_arr = np.stack(all_ids, axis=1).reshape(NB_QUERIES, -1) sorted_k_indices = np.argsort(-dists_arr)[:, :K] sorted_k_dists = np.take_along_axis(dists_arr, sorted_k_indices, axis=1) sorted_k_ids = np.take_along_axis(knn_ids_arr, sorted_k_indices, axis=1) print(f"{K} nearest distances: {sorted_k_dists}") print(f"{K} nearest ids: {sorted_k_ids}") ############################################ # Use case 3: on disk merging of N indices # ############################################ # using faiss.merge_ondisk (https://github.com/facebookresearch/faiss/blob/30abcd6a865afef7cf86df7e8b839a41b5161505/contrib/ondisk.py ) # https://github.com/facebookresearch/faiss/blob/151e3d7be54aec844b6328dc3e7dd0b83fcfa5bc/demos/demo_ondisk_ivf.py # to merge indices on disk without using memory # this is useful in particular to use a very large index with almost no memory usage. from faiss.contrib.ondisk import merge_ondisk import faiss block_fnames = index_paths empty_index = faiss.read_index(block_fnames[0], faiss.IO_FLAG_MMAP) empty_index.ntotal = 0 merge_ondisk(empty_index, block_fnames, "merged_index.ivfdata") faiss.write_index(empty_index, "populated.index") pop = faiss.read_index("populated.index", faiss.IO_FLAG_ONDISK_SAME_DIR) ######################################################## # Use case 4: use N indices using HStackInvertedLists # ######################################################## # This allows using N indices as a single combined index # without changing anything on disk or loading anything to memory # it works well but it's slower than first using merge_ondisk # because it requires explore N pieces of inverted list for each # list to explore import os index = CombinedIndex(index_paths) index.search(queries, K)
[ 37811, 198, 2025, 1672, 286, 2491, 1960, 1659, 64, 747, 416, 279, 893, 20928, 284, 4439, 399, 36525, 13, 198, 198, 1639, 761, 284, 2721, 279, 893, 20928, 878, 1262, 262, 1708, 1672, 13, 198, 37811, 198, 6738, 19720, 1330, 360, 713, ...
2.923599
1,178
"""Callback module for rbkcli.""" import json from rbkcli.core.handlers.inputs import InputHandler from rbkcli.base.essentials import DotDict, RbkcliException from rbkcli.core.handlers import ApiTargetTools from rbkcli.core.handlers.outputs import OutputHandler
[ 37811, 47258, 8265, 329, 374, 65, 74, 44506, 526, 15931, 201, 198, 201, 198, 11748, 33918, 201, 198, 201, 198, 6738, 374, 65, 74, 44506, 13, 7295, 13, 4993, 8116, 13, 15414, 82, 1330, 23412, 25060, 201, 198, 6738, 374, 65, 74, 44506...
2.863158
95
# Generated by Django 2.2.1 on 2019-05-16 23:28 from django.conf import settings from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 362, 13, 17, 13, 16, 319, 13130, 12, 2713, 12, 1433, 2242, 25, 2078, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14...
3.019231
52
from rest_framework import serializers, exceptions from greenbudget.lib.rest_framework_utils.serializers import ( EnhancedModelSerializer) from greenbudget.app.account.models import BudgetAccount, TemplateAccount from greenbudget.app.tagging.serializers import ColorField from greenbudget.app.subaccount.models import ( BudgetSubAccount, TemplateSubAccount) from .models import ( Group, BudgetAccountGroup, TemplateAccountGroup, BudgetSubAccountGroup, TemplateSubAccountGroup )
[ 6738, 1334, 62, 30604, 1330, 11389, 11341, 11, 13269, 198, 198, 6738, 4077, 37315, 13, 8019, 13, 2118, 62, 30604, 62, 26791, 13, 46911, 11341, 1330, 357, 198, 220, 220, 220, 22104, 17633, 32634, 7509, 8, 198, 198, 6738, 4077, 37315, 1...
3.558621
145
# -*- coding: utf-8 -*- """ INTRO @author: Yi Zhang. Created on Tue May 21 11:57:52 2019 Department of Aerodynamics Faculty of Aerospace Engineering TU Delft, Delft, the Netherlands """ import inspect from screws.freeze.main import FrozenOnly from typing import Dict, Union import numpy as np from screws.decorators.classproperty.main import classproperty def ___PRIVATE_boundary_name_requirement_checker___(self, boundaryRegionSidesDict): """ Requirements: 1). != domain name. 2). Length > 2 3). Can not start with 'R:' (So it must be different from regions names). 4). Only have letters """ for boundary_name in boundaryRegionSidesDict.keys(): assert boundary_name != self.domain_name assert len(boundary_name) > 2, f"boundary_name = {boundary_name} is too short (>2 must)." assert boundary_name[0:2] != 'R:', f"boundary_name = {boundary_name} wrong." assert boundary_name.isalpha(), f"boundary_name = {boundary_name} wrong, boundary_name can only contain letters." def ___PRIVATE_periodic_boundary_requirement_checker___(self, pBd): """ Here we only do a simple check. We make sure that the keys are in format of: 0). boundary_name_1=boundary_name_2. 1). A boundary name at most appear in one pair. """ assert isinstance(pBd, dict) bnPOOL = set() for pair in pBd: assert '=' in pair bn1, bn2 = pair.split('=') lengthPOOL = len(bnPOOL) assert bn1 in self._boundary_names_ and bn2 in self._boundary_names_ bnPOOL.add(bn1) bnPOOL.add(bn2) newLengthPOOL = len(bnPOOL) assert newLengthPOOL == lengthPOOL + 2, "Boundary(s) used for multiple periodic pairs!" self._periodic_boundaries_ = bnPOOL # class properties -------------------------
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 1268, 5446, 46, 198, 198, 31, 9800, 25, 26463, 19439, 13, 15622, 319, 30030, 1737, 2310, 1367, 25, 3553, 25, 4309, 13130, 198, 220, 220, 220, 220, 220, 220...
2.349823
849
""" Vectors over the symbolic ring. Implements vectors over the symbolic ring. AUTHORS: - Robert Bradshaw (2011-05-25): Added more element-wise simplification methods - Joris Vankerschaver (2011-05-15): Initial version EXAMPLES:: sage: x, y = var('x, y') sage: u = vector([sin(x)^2 + cos(x)^2, log(2*y) + log(3*y)]); u (cos(x)^2 + sin(x)^2, log(3*y) + log(2*y)) sage: type(u) <class 'sage.modules.free_module.FreeModule_ambient_field_with_category.element_class'> sage: u.simplify_full() (1, log(3*y) + log(2*y)) TESTS: Check that the outcome of arithmetic with symbolic vectors is again a symbolic vector (:trac:`11549`):: sage: v = vector(SR, [1, 2]) sage: w = vector(SR, [sin(x), 0]) sage: type(v) <class 'sage.modules.free_module.FreeModule_ambient_field_with_category.element_class'> sage: type(w) <class 'sage.modules.free_module.FreeModule_ambient_field_with_category.element_class'> sage: type(v + w) <class 'sage.modules.free_module.FreeModule_ambient_field_with_category.element_class'> sage: type(-v) <class 'sage.modules.free_module.FreeModule_ambient_field_with_category.element_class'> sage: type(5*w) <class 'sage.modules.free_module.FreeModule_ambient_field_with_category.element_class'> Test pickling/unpickling:: sage: u = vector(SR, [sin(x^2)]) sage: loads(dumps(u)) == u True """ from __future__ import absolute_import #***************************************************************************** # Copyright (C) 2011 Joris Vankerschaver (jv@caltech.edu) # # Distributed under the terms of the GNU General Public License (GPL) # as published by the Free Software Foundation; either version 2 of # the License, or (at your option) any later version. # http://www.gnu.org/licenses/ #***************************************************************************** from . import free_module_element from sage.symbolic.all import Expression def apply_map(phi): """ Returns a function that applies phi to its argument. EXAMPLES:: sage: from sage.modules.vector_symbolic_dense import apply_map sage: v = vector([1,2,3]) sage: f = apply_map(lambda x: x+1) sage: f(v) (2, 3, 4) """ def apply(self, *args, **kwds): """ Generic function used to implement common symbolic operations elementwise as methods of a vector. EXAMPLES:: sage: var('x,y') (x, y) sage: v = vector([sin(x)^2 + cos(x)^2, log(x*y), sin(x/(x^2 + x)), factorial(x+1)/factorial(x)]) sage: v.simplify_trig() (1, log(x*y), sin(1/(x + 1)), factorial(x + 1)/factorial(x)) sage: v.canonicalize_radical() (cos(x)^2 + sin(x)^2, log(x) + log(y), sin(1/(x + 1)), factorial(x + 1)/factorial(x)) sage: v.simplify_rational() (cos(x)^2 + sin(x)^2, log(x*y), sin(1/(x + 1)), factorial(x + 1)/factorial(x)) sage: v.simplify_factorial() (cos(x)^2 + sin(x)^2, log(x*y), sin(x/(x^2 + x)), x + 1) sage: v.simplify_full() (1, log(x*y), sin(1/(x + 1)), x + 1) sage: v = vector([sin(2*x), sin(3*x)]) sage: v.simplify_trig() (2*cos(x)*sin(x), (4*cos(x)^2 - 1)*sin(x)) sage: v.simplify_trig(False) (sin(2*x), sin(3*x)) sage: v.simplify_trig(expand=False) (sin(2*x), sin(3*x)) """ return self.apply_map(lambda x: phi(x, *args, **kwds)) apply.__doc__ += "\nSee Expression." + phi.__name__ + "() for optional arguments." return apply # Add elementwise methods. for method in ['simplify', 'simplify_factorial', 'simplify_log', 'simplify_rational', 'simplify_trig', 'simplify_full', 'trig_expand', 'canonicalize_radical', 'trig_reduce']: setattr(Vector_symbolic_dense, method, apply_map(getattr(Expression, method)))
[ 37811, 198, 53, 478, 669, 625, 262, 18975, 5858, 13, 198, 198, 3546, 1154, 902, 30104, 625, 262, 18975, 5858, 13, 198, 198, 32, 24318, 20673, 25, 198, 198, 12, 5199, 8114, 32832, 357, 9804, 12, 2713, 12, 1495, 2599, 10687, 517, 5002...
2.22432
1,801
from app import db from app.models.serializer import Serializer
[ 6738, 598, 1330, 20613, 198, 6738, 598, 13, 27530, 13, 46911, 7509, 1330, 23283, 7509, 628 ]
4.0625
16
# -*- coding: utf-8 -*- # # Copyright Contributors to the Conu project. # SPDX-License-Identifier: MIT # # TODO: move this line to some generic constants, instead of same in # docker and nspawn CONU_ARTIFACT_TAG = 'CONU.' CONU_IMAGES_STORE = "/opt/conu-nspawn-images/" CONU_NSPAWN_BASEPACKAGES = [ "dnf", "iproute", "dhcp-client", "initscripts", "passwd", "systemd", "rpm", "bash", "shadow-utils", "sssd-client", "util-linux", "libcrypt", "sssd-client", "coreutils", "glibc-all-langpacks", "vim-minimal"] BOOTSTRAP_IMAGE_SIZE_IN_MB = 5000 BOOTSTRAP_FS_UTIL = "mkfs.ext4" BOOTSTRAP_PACKAGER = [ "dnf", "-y", "install", "--nogpgcheck", "--setopt=install_weak_deps=False", "--allowerasing"] DEFAULT_RETRYTIMEOUT = 30 DEFAULT_SLEEP = 1
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 15069, 25767, 669, 284, 262, 1482, 84, 1628, 13, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 17168, 198, 2, 198, 198, 2, 16926, 46, 25, 1445, 428...
1.951965
458
import itertools from ..quant_utils import QuantizedValue, QuantizedValueType, attribute_to_kwarg, quantize_nparray from .base_operator import QuantOperatorBase
[ 11748, 340, 861, 10141, 198, 198, 6738, 11485, 40972, 62, 26791, 1330, 16972, 1143, 11395, 11, 16972, 1143, 11395, 6030, 11, 11688, 62, 1462, 62, 46265, 853, 11, 5554, 1096, 62, 77, 1845, 2433, 198, 6738, 764, 8692, 62, 46616, 1330, 1...
3.543478
46
from django.db import models # Create your models here.
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 198, 2, 13610, 534, 4981, 994, 13, 628, 628 ]
3.529412
17
import bottleneck as bn import numpy as np from scipy import sparse """ All the data should be in the shape of (n_users, n_items) All the latent factors should in the shape of (n_users/n_items, n_components) 1. train_data refers to the data that was used to train the model 2. heldout_data refers to the data that was used for evaluation (could be test set or validation set) 3. vad_data refers to the data that should be excluded as validation set, which should only be used when calculating test scores """ # helper functions # def mean_rrank_at_k_batch(train_data, heldout_data, Et, Eb, user_idx, k=5, vad_data=None): ''' mean reciprocal rank@k: For each user, make predictions and rank for all the items. Then calculate the mean reciprocal rank for the top K that are in the held-out set. ''' batch_users = user_idx.stop - user_idx.start X_pred = _make_prediction(train_data, Et, Eb, user_idx, batch_users, vad_data=vad_data) all_rrank = 1. / (np.argsort(np.argsort(-X_pred, axis=1), axis=1) + 1) X_true_binary = (heldout_data[user_idx] > 0).toarray() heldout_rrank = X_true_binary * all_rrank top_k = bn.partsort(-heldout_rrank, k, axis=1) return -top_k[:, :k].mean(axis=1) def NDCG_binary_batch(train_data, heldout_data, Et, Eb, user_idx, vad_data=None): ''' normalized discounted cumulative gain for binary relevance ''' batch_users = user_idx.stop - user_idx.start n_items = train_data.shape[1] X_pred = _make_prediction(train_data, Et, Eb, user_idx, batch_users, vad_data=vad_data) all_rank = np.argsort(np.argsort(-X_pred, axis=1), axis=1) # build the discount template tp = np.hstack((1, 1. / np.log2(np.arange(2, n_items + 1)))) all_disc = tp[all_rank] X_true_binary = (heldout_data[user_idx] > 0).tocoo() disc = sparse.csr_matrix((all_disc[X_true_binary.row, X_true_binary.col], (X_true_binary.row, X_true_binary.col)), shape=all_disc.shape) DCG = np.array(disc.sum(axis=1)).ravel() IDCG = np.array([tp[:n].sum() for n in heldout_data[user_idx].getnnz(axis=1)]) return DCG / IDCG def mean_perc_rank_batch(train_data, heldout_data, Et, Eb, user_idx, vad_data=None): ''' mean percentile rank for a batch of users MPR of the full set is the sum of batch MPR's divided by the sum of all the feedbacks. (Eq. 8 in Hu et al.) This metric not necessarily constrains the data to be binary ''' batch_users = user_idx.stop - user_idx.start X_pred = _make_prediction(train_data, Et, Eb, user_idx, batch_users, vad_data=vad_data) all_perc = np.argsort(np.argsort(-X_pred, axis=1), axis=1) / \ np.isfinite(X_pred).sum(axis=1, keepdims=True).astype(np.float32) perc_batch = (all_perc[heldout_data[user_idx].nonzero()] * heldout_data[user_idx].data).sum() return perc_batch
[ 11748, 49936, 355, 275, 77, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 629, 541, 88, 1330, 29877, 628, 198, 37811, 198, 3237, 262, 1366, 815, 307, 287, 262, 5485, 286, 357, 77, 62, 18417, 11, 299, 62, 23814, 8, 198, 3237, ...
2.228735
1,399
from pgdrive.component.blocks.curve import Curve from pgdrive.component.blocks.first_block import FirstPGBlock from pgdrive.component.blocks.std_t_intersection import StdTInterSection from pgdrive.component.blocks.straight import Straight from pgdrive.component.road.road_network import RoadNetwork from pgdrive.tests.vis_block.vis_block_base import TestBlock if __name__ == "__main__": test = TestBlock(True) from pgdrive.engine.asset_loader import initialize_asset_loader initialize_asset_loader(test) global_network = RoadNetwork() first = FirstPGBlock(global_network, 3.0, 2, test.render, test.world, 1) curve = Curve(1, first.get_socket(0), global_network, 1) curve.construct_block(test.render, test.world) straight = Straight(2, curve.get_socket(0), global_network, 1) straight.construct_block(test.render, test.world) intersection = StdTInterSection(3, straight.get_socket(0), global_network, 1) print(intersection.construct_block(test.render, test.world)) id = 4 for socket_idx in range(intersection.SOCKET_NUM): block = Curve(id, intersection.get_socket(socket_idx), global_network, id + 1) block.construct_block(test.render, test.world) id += 1 test.show_bounding_box(global_network) test.run()
[ 6738, 23241, 19472, 13, 42895, 13, 27372, 13, 22019, 303, 1330, 46300, 198, 6738, 23241, 19472, 13, 42895, 13, 27372, 13, 11085, 62, 9967, 1330, 3274, 6968, 12235, 198, 6738, 23241, 19472, 13, 42895, 13, 27372, 13, 19282, 62, 83, 62, ...
2.903587
446
from selenium import webdriver BASE_URL = 'http://news.163.com/' # ajax,ajax,?callback=data_callback' # json?..json JSON_INDEX_URLS = [ 'http://temp.163.com/special/00804KVA/cm_yaowen.js?callback=data_callback', 'http://house.163.com/special/00078GU7/guangzhou_xw_news_v1.js?callback=data_callback', 'http://temp.163.com/special/00804KVA/cm_shehui.js?callback=data_callback', 'http://temp.163.com/special/00804KVA/cm_guonei.js?callback=data_callback', 'http://temp.163.com/special/00804KVA/cm_guoji.js?callback=data_callback', 'http://temp.163.com/special/00804KVA/cm_dujia.js?callback=data_callback', 'http://temp.163.com/special/00804KVA/cm_war.js?callback=data_callback', 'http://temp.163.com/special/00804KVA/cm_money.js?callback=data_callback', 'http://temp.163.com/special/00804KVA/cm_tech.js?callback=data_callback', 'http://temp.163.com/special/00804KVA/cm_sports.js?callback=data_callback', 'http://temp.163.com/special/00804KVA/cm_ent.js?callback=data_callback', 'http://temp.163.com/special/00804KVA/cm_lady.js?callback=data_callback', 'http://temp.163.com/special/00804KVA/cm_auto.js?callback=data_callback', 'http://temp.163.com/special/00804KVA/cm_houseguangzhou.js?callback=data_callback', 'http://temp.163.com/special/00804KVA/cm_hangkong.js?callback=data_callback', 'http://temp.163.com/special/00804KVA/cm_jiankang.js?callback=data_callback', # 'http://news.163.com/uav/special/000189N0/uav_index.js?callback=data_callback', # 'http://sports.163.com/special/000587PR/newsdata_n_index.js?callback=data_callback', 'http://sports.163.com/special/000587PR/newsdata_n_world.js?callback=data_callback', 'http://sports.163.com/special/000587PR/newsdata_n_china.js?callback=data_callback', 'http://sports.163.com/special/000587PR/newsdata_n_cba.js?callback=data_callback', 'http://sports.163.com/special/000587PR/newsdata_n_allsports.js?callback=data_callback', # NBA 'http://sports.163.com/special/000587PK/newsdata_nba_hj.js?callback=data_callback', 'http://sports.163.com/special/000587PK/newsdata_nba_qsh.js?callback=data_callback', 'http://sports.163.com/special/000587PK/newsdata_nba_ysh.js?callback=data_callback', 'http://sports.163.com/special/000587PK/newsdata_nba_ketr.js?callback=data_callback', 'http://sports.163.com/special/000587PK/newsdata_nba_okc.js?callback=data_callback', 'http://sports.163.com/special/000587PK/newsdata_nba_huren.js?callback=data_callback', 'http://sports.163.com/special/000587PK/newsdata_nba_mc.js?callback=data_callback', # 'http://ent.163.com/special/000380VU/newsdata_index.js?callback=data_callback', 'http://ent.163.com/special/000380VU/newsdata_music.js?callback=data_callback', 'http://ent.163.com/special/000380VU/newsdata_star.js?callback=data_callback', 'http://ent.163.com/special/000380VU/newsdata_movie.js?callback=data_callback', 'http://ent.163.com/special/000380VU/newsdata_tv.js?callback=data_callback', 'http://ent.163.com/special/000380VU/newsdata_show.js?callback=data_callback', # 'http://money.163.com/special/002557S5/newsdata_idx_index.js?callback=data_callback', 'http://money.163.com/special/002557S5/newsdata_idx_stock.js?callback=data_callback', 'http://money.163.com/special/002557S5/newsdata_idx_finance.js?callback=data_callback', 'http://money.163.com/special/002557S5/newsdata_idx_fund.js?callback=data_callback', 'http://money.163.com/special/002557S5/newsdata_idx_licai.js?callback=data_callback', 'http://money.163.com/special/002557S5/newsdata_idx_biz.js?callback=data_callback', 'http://money.163.com/special/002557S5/newsdata_idx_bitcoin.js?callback=data_callback', # 'http://money.163.com/special/002557S6/newsdata_gp_index.js?callback=data_callback', 'http://money.163.com/special/002557S6/newsdata_gp_hkstock.js?callback=data_callback', 'http://money.163.com/special/002557S6/newsdata_gp_usstock.js?callback=data_callback', 'http://money.163.com/special/002557S6/newsdata_gp_ipo.js?callback=data_callback', 'http://money.163.com/special/002557S6/newsdata_gp_bitcoin.js?callback=data_callback', 'http://money.163.com/special/002557S6/newsdata_gp_dy.js?callback=data_callback', # 'http://tech.163.com/special/00097UHL/tech_datalist.js?callback=data_callback', # ,,copy 'http://bendi.news.163.com/beijing/special/04388GGG/bjxinxiliu.js', 'http://bendi.news.163.com/shanghai/special/04188GP4/shxinxiliu.js', 'http://tj.news.163.com/special/04208F5D/tjxxl.js', 'http://bendi.news.163.com/jiangsu/special/04248H8U/njxxl.js', 'http://bendi.news.163.com/zhejiang/special/04098FBT/xinxiliu.js', 'http://sc.news.163.com/special/04268EVT/xinxiliu.js', 'http://bendi.news.163.com/heilongjiang/special/04238DR5/haerbin.js', 'http://bendi.news.163.com/jilin/special/04118E6D/center_news_cc.js', 'http://bendi.news.163.com/liaoning/special/04228EED/xinxiliu.js', 'http://bendi.news.163.com/neimengu/special/04138EHT/nmgxxl.js' ] URLs = ['http://news.163.com/', 'http://news.163.com/rank/', 'http://news.163.com/photo/#Current', 'http://news.163.com/domestic/', 'http://news.163.com/world/', 'http://news.163.com/shehui/', 'http://data.163.com/special/datablog/', 'http://war.163.com/', 'http://news.163.com/air/', 'http://news.163.com/uav/', 'http://news.163.com/college', 'http://gov.163.com/', 'http://gongyi.163.com/', 'http://media.163.com/'] # config mongoDB MONGODB_HOST = 'localhost' MONGODB_PORT = 27017 MONGODB_DBNAME = 'neteasenews' # , MONGODB_TABLE_1 = 'article' # , MONGODB_TABLE_2 = 'newsrank' # , MONGODB_TABLE_3 = 'coldpage' # MONGODB_TABLE_4 = 'picture' # config chromedriver: prefs = { 'profile.default_content_setting_values': { 'images': 2, # 'javascript': 2 # 'User-Agent': ua } } options = webdriver.ChromeOptions() options.add_experimental_option('prefs', prefs) # options.add_argument('--headless')
[ 6738, 384, 11925, 1505, 1330, 3992, 26230, 198, 198, 33, 11159, 62, 21886, 796, 705, 4023, 1378, 10827, 13, 24136, 13, 785, 14, 6, 198, 2, 257, 73, 897, 11, 1228, 897, 11, 30, 47423, 28, 7890, 62, 47423, 6, 198, 2, 33918, 30, 49...
2.300865
2,659
#!/usr/bin/env python3 """ Author : Brian Scott <brianscott@email.arizona.edu> Date : 2021-11-09 Purpose: FInd the similarities between sequences. """ import argparse # -------------------------------------------------- def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Rock the Casbah', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('file', help='Input file', metavar='FILE', type=argparse.FileType('rt')) return parser.parse_args() # -------------------------------------------------- def main(): """Makes it work""" args = get_args() sequences = [] for line in args.file: temp_list = [] for char in line.strip(): temp_list.append(char) sequences.append(temp_list) out_seq = "" for base in range(len(sequences[0])): temp_base = [] # for line in range(len(sequences)): # had to use enumerate to get pylint to shut up. # also had to then use the variable so pylint would shut up # because If i use the range(len()) method pylint doesn't like it # even though it makes more sense than enumerate becuase # it doesn't create unnecessary variables# for line, value in enumerate(sequences): temp_base.append(sequences[line][base]) # print(temp_base) all_same(value) # only here to get enumerate to shup up if all_same(temp_base): out_seq = out_seq + "|" else: out_seq = out_seq + "X" for line in sequences: temp_line = "" for char in line: temp_line = temp_line + char print(temp_line) print(out_seq) def all_same(list1): """checks if all items in list are equal""" return all(x == list1[0] for x in list1) # -------------------------------------------------- if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 37811, 198, 13838, 1058, 8403, 4746, 1279, 65, 19151, 14612, 31, 12888, 13, 283, 528, 4450, 13, 15532, 29, 198, 10430, 220, 220, 1058, 33448, 12, 1157, 12, 2931, 198, 30026, 3455, ...
2.424674
843
#!/usr/bin/env python # -*- coding: utf8 -*- # Loading a few python packages import os import glob import warnings from astropy import log from astropy.io import fits as pyfits import json # Loading iraf packages from pyraf import iraf from pyraf.iraf import onedspec from pyraf.iraf import twodspec, apextract def wcalibrate_spec(self, obs_dict, disp_sol_content_dict, prefix='e_', out_prefix='w'): """ This method runs a couple of IRAF routines to obtain the dispersion function for a arc files and then apply it to the corresponding spectra. Args: obs_dict (dict): prefix (str): out_prefix (str): Returns: """ onedspec.identify.unlearn() onedspec.refspec.unlearn() onedspec.dispcor.unlearn() for target, p in obs_dict.iteritems(): spec_in = prefix + p['spec'] + '.0001.fits' arc_ref = prefix + p['arc'] + '.0001.fits' # Checking sepctral setup self.check_spec_setup(spec_in, arc_ref) ##### Copying disp solution to 'database' dir # 1. Getting content dictionary with disp solutions of the corresponding arc slit, grism, filter = self.get_spec_setup(arc_ref) w1, w2 = self.wrange[grism][0], self.wrange[grism][1] # Getting specific disp sol content of the corresponding arc file key = '{}_{}'.format(grism,filter) content_dict = disp_sol_content_dict[key] # 2. Writting solution to database dir self.write_modified_disp_sol_to_database(arc_ref, content_dict, database_dir=self.database_dir) ##### Running iraf to get updated disp sol print('\n') log.info('Finding wavelength solution to reference arc ' + arc_ref + '...') onedspec.identify(arc_ref, **self.identify_flags) print('\n') log.info('Associating the obtained wavelength solution with the spectrum of the star:') log.info(spec_in + ' -----> REFSPEC = ' + arc_ref + '.') onedspec.refspec(spec_in, reference=arc_ref, sort='', group='') print('\n') log.info('Applying wavelength calibration to ' + spec_in + '.') onedspec.dispcor(spec_in, out=out_prefix + spec_in, w1=w1, w2=w2) if self.fit_continuum: onedspec.continuum.unlearn() print('\n') log.info('Fitting continuum to ' + out_prefix + spec_in + '.') input = out_prefix + spec_in output = 'cont_' + out_prefix + spec_in onedspec.continuum(input=input, output=output, type='fit', function='legendre', order=15, niterate=10, low_reject=2.0, high_reject=0.0)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 23, 532, 9, 12, 198, 198, 2, 12320, 257, 1178, 21015, 10392, 198, 11748, 28686, 198, 11748, 15095, 198, 11748, 14601, 198, 6738, 6468, 28338, 1330...
2.214008
1,285
from ..models import Job from engine.scripts.mirmachine_args import run_mirmachine from .socket_helper import announce_status_change, announce_queue_position, announce_initiation, announce_completed from .maintainer import clean_up_temporary_files from django.utils import timezone from MirMachineWebapp import user_config as config
[ 6738, 11485, 27530, 1330, 15768, 198, 6738, 3113, 13, 46521, 13, 76, 2533, 20480, 62, 22046, 1330, 1057, 62, 76, 2533, 20480, 198, 6738, 764, 44971, 62, 2978, 525, 1330, 5453, 62, 13376, 62, 3803, 11, 5453, 62, 36560, 62, 9150, 11, ...
3.736264
91
""" 33 - Faca um programa que leia um vetor de 15 posicoes e o compacte, ou seja, elimine as posicoes com valor zero. Para isso, todos os elementos a frente do valor zero, devem ser movidos uma posicao para tras no vetor. """ """ vetor = [] count = 0 for x in range(1, 16): vetor.append(int(input(f'Digite o {x}/15: '))) n = len(vetor) for i in range(n): if vetor[i] != 0: vetor[count] = vetor[i] count += 1 while n > count: vetor[count] = 0 count += 1 print(vetor) # [5, 6, 9, 8, 10, 15, 33, 22, 66, 99, 10, 100, 0, 0, 0] Este os zeros vao para tras """ from itertools import compress, repeat, chain vetor = [] for x in range(1, 16): vetor.append(int(input(f'Digite o {x}/15: '))) # usando list.count e itertools.compress y = [0] * vetor.count(0) y.extend(compress(vetor, vetor)) print(y)
[ 37811, 198, 2091, 532, 13585, 64, 23781, 1430, 64, 8358, 443, 544, 23781, 1569, 13165, 390, 1315, 1426, 291, 3028, 304, 267, 16001, 68, 11, 267, 84, 384, 6592, 11, 5687, 500, 355, 1426, 291, 3028, 401, 1188, 273, 6632, 13, 198, 47, ...
2.235294
374
import pygame import my_colors as color pygame.init() screen_width = 800 screen_height = 600 screen_size = (screen_width, screen_height) screen = pygame.display.set_mode(screen_size) pygame.display.set_caption("Search the green pixel at the coordinates (x=10, y=100)") running = True while running: screen.set_at((1, 1), color.white) screen.set_at((10, 100), color.green) pygame.display.update() event = pygame.event.wait() if event.type == pygame.QUIT: running = False pygame.quit() print("Goodbye!")
[ 11748, 12972, 6057, 198, 11748, 616, 62, 4033, 669, 355, 3124, 198, 198, 9078, 6057, 13, 15003, 3419, 198, 9612, 62, 10394, 796, 10460, 198, 9612, 62, 17015, 796, 10053, 198, 9612, 62, 7857, 796, 357, 9612, 62, 10394, 11, 3159, 62, ...
2.691919
198
#!/usr/bin/env python3 import os import re import glob import sys import operator import ast import argparse ############################################################################################### # This script was written as part of the analysis conducted on the output generated by # # hmmsearch, when the ViPhOG database was searched against UniProtKB. The ViPhOG profile HMM # # files were stored in different directories, each containing maximum 2000 files and named # # using a sequential number from 1 to 16 (hmm1...hmm16). For each one of these a corresponding# # output directory was generated, each containing a domtbl output file for each of the files # # stored in the hmm directories. The output directories were named using the same sequential # # numbers as the directories storing the hmm files (hmm1domtbl...hmm16domtbl). # ############################################################################################### parser = argparse.ArgumentParser(description = "Step 3: Generate summary tables for each taxonomic rank. Make sure to run the script from within the directory containing the domtbl output directories (check comment block for guidance) and following the scripts that execute Step 1 and Step 2") parser.add_argument("-i", "--input", dest = "input_file", help = "Path to summary chunk file", required = True) if len(sys.argv) == 1: parser.print_help() else: args = parser.parse_args() summ_file = args.input_file with open(summ_file) as input_file: header_line = input_file.readline().rstrip() taxa_ranks = [] for x,y in enumerate(header_line.split("\t")): if x >= 2: taxa_ranks.append((x, y)) for x,y in taxa_ranks: input_file.seek(0) next(input_file) with open(f"{os.path.splitext(summ_file)[0]}_{y}.tsv", "w") as output_file: output_file.write("ViPhOG\t#_taxons\tMost_significant\tMax_min_score\tOverlapping_taxons\tNext_max_score\n") for line in input_file: line = line.rstrip() viphog_id = line.split("\t")[0] rank_hits = ast.literal_eval(line.split("\t")[x]) total_hits = len(rank_hits) most_significant = "" score_range = "" overlap = "" next_max_score = "" if total_hits > 0: rank_hits_sorted = sorted(rank_hits, key = operator.itemgetter(2), reverse = True) most_significant = rank_hits_sorted[0][0] score_range = (rank_hits_sorted[0][2], rank_hits_sorted[0][3]) if total_hits > 1: overlap = [] for elem in rank_hits_sorted[1:]: if elem[2] >= score_range[1]: overlap.append((elem[0], elem[2])) if len(overlap) < 1: overlap = "" next_max_score = rank_hits_sorted[1][2] output_file.write("{}\t{}\t{}\t{}\t{}\t{}\n".format(viphog_id, total_hits, most_significant, score_range, overlap, next_max_score))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 15095, 198, 11748, 25064, 198, 11748, 10088, 198, 11748, 6468, 198, 11748, 1822, 29572, 198, 198, 29113, 29113, 14468, 7804, 4242, 21017...
2.707224
1,052
""" All permissions are defined here. They are also defined in permissions.zcml. The two files must be kept in sync. bika.lims.__init__ imports * from this file, so bika.lims.PermName or bika.lims.permissions.PermName are both valid. """ from Products.CMFCore.permissions import AddPortalContent # Add Permissions: # ---------------- AddAnalysis = 'BIKA: Add Analysis' AddAnalysisProfile = 'BIKA: Add AnalysisProfile' AddAnalysisRequest = 'BIKA: Add Analysis Request' AddAnalysisSpec = 'BIKA: Add AnalysisSpec' AddAttachment = 'BIKA: Add Attachment' AddARTemplate = 'BIKA: Add ARTemplate' AddBatch = 'BIKA: Add Batch' AddClient = 'BIKA: Add Client' AddClientFolder = 'BIKA: Add ClientFolder' AddInvoice = 'BIKA: Add Invoice' AddMethod = 'BIKA: Add Method' AddMultifile = 'BIKA: Add Multifile' AddPricelist = 'BIKA: Add Pricelist' AddProduct = 'BIKA: Add Product' AddProductCategory = 'BIKA: Add ProductCategory' AddStockItem = 'BIKA: Add StockItem' AddSupplyOrder = 'BIKA: Add SupplyOrder' AddInventoryOrder = 'BIKA: Add Inventory Order' AddSample = 'BIKA: Add Sample' AddSampleMatrix = 'BIKA: Add SampleMatrix' AddSamplePartition = 'BIKA: Add SamplePartition' AddSamplePoint = 'BIKA: Add SamplePoint' AddStorageLocation = 'BIKA: Add StorageLocation' AddSamplingDeviation = 'BIKA: Add SamplingDeviation' AddSamplingRound = 'BIKA: Add SamplingRound' AddSRTemplate = 'BIKA: Add SRTemplate' AddStorageLevel = 'BIKA: Add StorageLevel' AddStorageUnit = 'BIKA: Add StorageUnit' AddSubGroup = 'BIKA: Add Sub-group' # Default Archetypes Add Permission ADD_CONTENT_PERMISSION = AddPortalContent # Add Permissions for specific types, if required ADD_CONTENT_PERMISSIONS = { 'ARAnalysisSpec': AddAnalysisSpec, 'AnalysisProfile': AddAnalysisProfile, 'Analysis': AddAnalysis, 'AnalysisRequest': AddAnalysisRequest, 'Attachment': AddAttachment, 'Batch': AddBatch, 'Client': AddClient, 'Invoice': AddInvoice, 'Method': AddMethod, 'Multifile': AddMultifile, 'SupplyOrder': AddSupplyOrder, 'Order': AddInventoryOrder, 'Sample': AddSample, 'SampleMatrix': AddSampleMatrix, 'SamplePartition': AddSamplePartition, 'SamplingDeviation': AddSamplingDeviation, 'SamplingRound': AddSamplingRound, 'SubGroup': AddSubGroup, 'StorageLevel': AddStorageLevel, 'StorageUnit': AddStorageUnit, } # Very Old permissions: # --------------------- ManageBika = 'BIKA: Manage Bika' DispatchOrder = 'BIKA: Dispatch Order' ManageAnalysisRequests = 'BIKA: Manage Analysis Requests' ManageSamples = 'BIKA: Manage Samples' ManageSuppliers = 'BIKA: Manage Reference Suppliers' ManageReference = 'BIKA: Manage Reference' PostInvoiceBatch = 'BIKA: Post Invoice batch' ManagePricelists = 'BIKA: Manage Pricelists' # This allows to edit all client fields, and perform admin tasks on Clients. ManageClients = 'BIKA: Manage Clients' # this is for creating and transitioning worksheets ManageWorksheets = 'BIKA: Manage Worksheets' # this is for adding/editing/exporting analyses on worksheets EditWorksheet = 'BIKA: Edit Worksheet' RejectWorksheet = 'BIKA: Reject Worksheet' ImportInstrumentResults = "BIKA: Import Instrument Results" AccessJSONAPI = 'BIKA: Access JSON API' # New or changed permissions: # --------------------------- DispatchInventoryOrder = 'BIKA: Dispatch Inventory Order' ReceiveInventoryOrder = 'BIKA: Receive Inventory Order' StoreInventoryOrder = 'BIKA: Store Inventory Order' SampleSample = 'BIKA: Sample Sample' PreserveSample = 'BIKA: Preserve Sample' ReceiveSample = 'BIKA: Receive Sample' ExpireSample = 'BIKA: Expire Sample' DisposeSample = 'BIKA: Dispose Sample' ImportAnalysis = 'BIKA: Import Analysis' Retract = "BIKA: Retract" Verify = 'BIKA: Verify' VerifyOwnResults = 'BIKA: Verify own results' Publish = 'BIKA: Publish' EditSample = 'BIKA: Edit Sample' EditAR = 'BIKA: Edit AR' ResultsNotRequested = 'BIKA: Results not requested' ManageInvoices = 'BIKA: Manage Invoices' ViewResults = 'BIKA: View Results' EditResults = 'BIKA: Edit Results' EditFieldResults = 'BIKA: Edit Field Results' ViewRetractedAnalyses = 'BIKA: View Retracted Analyses' CancelAndReinstate = 'BIKA: Cancel and reinstate' # For adding login credentials to Contacts. ManageLoginDetails = 'BIKA: Manage Login Details' Assign = 'BIKA: Assign analyses' Unassign = 'BIKA: Unassign analyses' # Field permissions EditARContact = "BIKA: Edit AR Contact" ViewLogTab = 'BIKA: View Log Tab' # Edit AR # ----------------------------------------------------------------------------- # Allows to set values for AR fields in AR view # # Only takes effect if: # - The AR's 'cancellation_state' is 'active' # - The AR's 'review_state' is in: # 'sample_registered', 'to_be_sampled', 'sampled', 'to_be_preserved', # 'sample_due', 'sample_received', 'to_be_verified', 'attachment_due' EditAR = 'BIKA: Edit AR' # Edit Sample Partition # ----------------------------------------------------------------------------- # Allows to set a Container and/or Preserver for a Sample Partition. # See AR view: Sample Partitions table and Sample Partitions tab # # Only takes effect if: # - The Sample's 'cancellation_state' is 'active' # - The Sample's 'review_state' is in: # 'sample_registered', 'to_be_sampled', 'sampled', 'to_be_preserved', # 'sample_due', 'sample_received', 'to_be_verified', 'attachment_due' EditSamplePartition = 'BIKA: Edit Sample Partition' # Edit Client # ---------------------------------------------- # Allows access to 'Edit' and 'Contacts' tabs from Client View EditClient = 'BIKA: Edit Client' # Manage Supply Orders # ---------------------------------------------- # Allows access to 'Supply Orders' tab in Client context ManageSupplyOrders = 'BIKA: Manage Supply Orders' # Batch-specific permissions # ---------------------------------------------- EditBatch = 'BIKA: Edit Batch' CloseBatch = 'BIKA: Close Batch' ReopenBatch = 'BIKA: Reopen Batch' # Sampling Round permissions # -------------------------- CloseSamplingRound = 'BIKA: Close SamplingRound' ReopenSamplingRound = 'BIKA: Reopen SamplingRound' # Manage AR Imports # ---------------------------------------------- ManageARImport = 'BIKA: Manage ARImport' # Manage AR Priorities # ---------------------------------------------- ManageARPriority = 'BIKA: Manage ARPriority'
[ 37811, 1439, 21627, 389, 5447, 994, 13, 198, 220, 220, 220, 1119, 389, 635, 5447, 287, 21627, 13, 89, 66, 4029, 13, 198, 220, 220, 220, 383, 734, 3696, 1276, 307, 4030, 287, 17510, 13, 628, 220, 220, 220, 275, 9232, 13, 2475, 82, ...
3.190452
1,990
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import mock import testtools from openstack.telemetry.v2 import sample SAMPLE = { 'id': None, 'metadata': {'1': 'one'}, 'meter': '2', 'project_id': '3', 'recorded_at': '4', 'resource_id': '5', 'source': '6', 'timestamp': '7', 'type': '8', 'unit': '9', 'user_id': '10', 'volume': '11.1', } OLD_SAMPLE = { 'counter_name': '1', 'counter_type': '2', 'counter_unit': '3', 'counter_volume': '4', 'message_id': None, 'project_id': '5', 'recorded_at': '6', 'resource_id': '7', 'resource_metadata': '8', 'source': '9', 'timestamp': '10', 'user_id': '11', }
[ 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 921, 743, 7330, 198, 2, 257, 4866, 286, 262, 13789, 379, 198, 2,...
2.642222
450
#!/usr/bin/env python # -*- coding:utf-8 -*- import os import json from collections import Counter, defaultdict from data_convert.format.text2tree import Entity_Type, Text2Tree from data_convert.task_format.event_extraction import Event, DyIEPP, Conll04 from data_convert.utils import read_file, check_output, data_counter_to_table, get_schema, output_schema from nltk.corpus import stopwords Ace_Entity_Type = {"ORG": "<ORG>", "VEH": "<VEH>", "WEA": "<WEA>", "LOC": "<LOC>", "FAC": "<FAC>", "PER": "<PER>", "GPE": "<GPE>"} Sci_Entity_Type = {'Metric': '<Metric>', 'Task': '<Task>', 'OtherScientificTerm': '<OtherScientificTerm>', 'Generic': '<Generic>', 'Material': '<Material>', 'Method': '<Method>'} Conll04_Type = {'Org': '<Org>', 'Peop': '<Peop>', 'Other': '<Other>', 'Loc': '<Loc>'} english_stopwords = set(stopwords.words('english') + ["'s", "'re", "%"]) if __name__ == "__main__": type_format_name = 'subtype' convert_ace2005_event("data/new_text2tree/one_ie_ace2005_%s" % type_format_name, type_format=type_format_name, ignore_nonevent=False, mark_tree=False ) # """ # convert_sci_event("data/new_text2tree/sci_relation_%s" % type_format_name, # type_format=type_format_name, # ignore_nonevent=False, # mark_tree=False) # """ # convert_conll04_relation("data/new_text2tree/conll04_relation_%s" % type_format_name, # type_format=type_format_name, # ignore_nonevent=False, # mark_tree=False)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 11748, 28686, 198, 11748, 33918, 198, 6738, 17268, 1330, 15034, 11, 4277, 11600, 198, 6738, 1366, 62, 1102, 1851, 13, 18982,...
2.040237
845
from scrapy.utils.misc import walk_modules from scrapy.utils.spider import iter_spider_classes def get_spider_cls(url, spider_packages, default): """ Return spider class based on provided url. :param url: if it looks like `spider://spidername` it tries to load spider named `spidername`, otherwise it returns default spider class :param spider_packages: a list of package names that will be searched for spider classes :param default: the class that is returned when `url` doesn't start with `spider://` """ if url.startswith('spider://'): spider_name = url[len('spider://'):] return find_spider_cls(spider_name, spider_packages) return default def find_spider_cls(spider_name, spider_packages): """ Find spider class which name is equal to `spider_name` argument :param spider_name: spider name to look for :param spider_packages: a list of package names that will be searched for spider classes """ for package_name in spider_packages: for module in walk_modules(package_name): for spider_cls in iter_spider_classes(module): if spider_cls.name == spider_name: return spider_cls
[ 6738, 15881, 88, 13, 26791, 13, 44374, 1330, 2513, 62, 18170, 198, 6738, 15881, 88, 13, 26791, 13, 2777, 1304, 1330, 11629, 62, 2777, 1304, 62, 37724, 628, 198, 4299, 651, 62, 2777, 1304, 62, 565, 82, 7, 6371, 11, 19230, 62, 43789, ...
2.744493
454
import torch import torch.nn as nn from torch.nn import init import torch.nn.functional as F
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 6738, 28034, 13, 20471, 1330, 2315, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 628 ]
3.481481
27
import click import time from deephub.common.io import resolve_glob_pattern from deephub.models.feeders.tfrecords.meta import generate_fileinfo, get_fileinfo, TFRecordValidationError, \ TFRecordInfoMissingError
[ 11748, 3904, 198, 11748, 640, 198, 198, 6738, 2769, 40140, 13, 11321, 13, 952, 1330, 10568, 62, 4743, 672, 62, 33279, 198, 6738, 2769, 40140, 13, 27530, 13, 12363, 364, 13, 27110, 8344, 3669, 13, 28961, 1330, 7716, 62, 7753, 10951, 11...
3.333333
66
import numpy as np import cPickle import os from scipy.io import loadmat import time import h5py import json import copy import bz2 #extension with "." e.g. .jpg def mkdir_if_missing(output_dir): """ def mkdir_if_missing(output_dir) """ if not os.path.exists(output_dir): try: os.makedirs(output_dir) return True; except: #generally happens when many processes try to make this dir return False; def save_variables(pickle_file_name, var, info, overwrite = False): """ def save_variables(pickle_file_name, var, info, overwrite = False) """ fext = os.path.splitext(pickle_file_name)[1] if fext =='.h5': return save_variables_h5(pickle_file_name, var, info, overwrite); elif fext == '.pkl' or fext == '.pklz': if os.path.exists(pickle_file_name) and overwrite == False: raise Exception('{:s} exists and over write is false.'.format(pickle_file_name)) if info is not None: # Construct the dictionary assert(type(var) == list); assert(type(info) == list); d = {} for i in xrange(len(var)): d[info[i]] = var[i] else: #we have the dictionary in var d = var; if fext == '.pkl': with open(pickle_file_name, 'wb') as f: cPickle.dump(d, f, cPickle.HIGHEST_PROTOCOL) else: with bz2.BZ2File(pickle_file_name, 'w') as f: cPickle.dump(d, f, cPickle.HIGHEST_PROTOCOL) else: raise Exception('{:s}: extension unknown'.format(fext)) def load_variables(pickle_file_name): """ d = load_variables(pickle_file_name) Output: d is a dictionary of variables stored in the pickle file. """ fext = os.path.splitext(pickle_file_name)[1] if fext =='.h5': return load_variablesh5(pickle_file_name); elif fext == '.pkl' or fext == '.pklz': if os.path.exists(pickle_file_name): if fext == '.pkl': with open(pickle_file_name, 'rb') as f: d = cPickle.load(f) else: with bz2.BZ2File(pickle_file_name, 'r') as f: d = cPickle.load(f) return d else: raise Exception('{:s} does not exists.'.format(pickle_file_name)) elif fext == '.json': with open(pickle_file_name, 'r') as fh: data = json.load(fh) return data else: raise Exception('{:s}: extension unknown'.format(fext)) #wrappers for load_variables and save_variables def calc_pr_ovr_noref(counts, out): """ [P, R, score, ap] = calc_pr_ovr(counts, out, K) Input : counts : number of occurrences of this word in the ith image out : score for this image Output : P, R : precision and recall score : score which corresponds to the particular precision and recall ap : average precision """ #binarize counts out = out.astype(np.float64) counts = np.array(counts > 0, dtype=np.float32); tog = np.hstack((counts[:,np.newaxis].astype(np.float64), out[:, np.newaxis].astype(np.float64))) ind = np.argsort(out) ind = ind[::-1] score = np.array([tog[i,1] for i in ind]) sortcounts = np.array([tog[i,0] for i in ind]) tp = sortcounts; fp = sortcounts.copy(); for i in xrange(sortcounts.shape[0]): if sortcounts[i] >= 1: fp[i] = 0.; elif sortcounts[i] < 1: fp[i] = 1.; tp = np.cumsum(tp) fp = np.cumsum(fp) # P = np.cumsum(tp)/(np.cumsum(tp) + np.cumsum(fp)); P = tp / np.maximum(tp + fp, np.finfo(np.float64).eps) numinst = np.sum(counts); R = tp/numinst ap = voc_ap(R,P) return P, R, score, ap
[ 11748, 299, 32152, 355, 45941, 198, 11748, 269, 31686, 293, 198, 11748, 28686, 198, 6738, 629, 541, 88, 13, 952, 1330, 3440, 6759, 198, 11748, 640, 198, 11748, 289, 20, 9078, 198, 11748, 33918, 198, 11748, 4866, 198, 11748, 275, 89, 1...
2.286089
1,524
dict = {} lista = [] soma = 0 while True: dict['nome'] = str(input('Nome: ')).capitalize() dict['sexo'] = str(input('Sexo: ')).strip().upper()[0] while dict['sexo'] not in 'MF': print('ERRO! Por favor, digite apenas M ou F') dict['sexo'] = str(input('Sexo: ')).strip().upper()[0] dict['idade'] = int(input('Idade: ')) soma += dict['idade'] lista.append(dict.copy()) opo = str(input('Quer continuar? ')).strip().upper()[0] while opo not in 'SN': print('ERRO! Responda apenas S ou N.') opo = str(input('Quer continuar? ')).strip().upper()[0] if opo == 'N': break print('-='*30) print(f'A) Ao todo temos {len(lista)} pessoas cadastradas.') media = soma / len(lista) print(f'B) A media de idade de {media:5.2f} anos') print('C) As mulheres cadastradas foram ', end='') for p in lista: if p['sexo'] == 'F': print(f'{p["nome"]}', end=' ') print() print('D) As pessoas com idade maior que a mdia so ', end='') for c in lista: if c['idade'] > media: print(f'{c["nome"]}', end=' ')
[ 11600, 796, 23884, 198, 4868, 64, 796, 17635, 198, 82, 6086, 796, 657, 198, 4514, 6407, 25, 198, 220, 220, 220, 8633, 17816, 77, 462, 20520, 796, 965, 7, 15414, 10786, 45, 462, 25, 705, 29720, 27544, 1096, 3419, 198, 220, 220, 220, ...
2.152305
499
# -*- coding: utf8 -*- """ ====================================== Project Name: NLP File Name: linears Author: czh Create Date: 2021/11/15 -------------------------------------- Change Activity: ====================================== """ import math import torch import torch.nn as nn import torch.nn.functional as func from torch.nn.parameter import Parameter
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 23, 532, 9, 12, 198, 37811, 198, 10052, 50155, 198, 220, 220, 220, 4935, 6530, 25, 399, 19930, 198, 220, 220, 220, 9220, 6530, 25, 9493, 4127, 198, 220, 220, 220, 6434, 25, 269, 23548, 198, 22...
3.508929
112
import requests
[ 11748, 7007, 201, 198 ]
4.25
4
""" Opdracht 9 - Loonbrief https://dodona.ugent.be/nl/exercises/990750894/ """ # functie voor start amount # functie voor salaris # functie voor gemiddeld salaris if __name__ == '__main__': main()
[ 37811, 198, 18257, 7109, 19725, 860, 532, 406, 2049, 65, 3796, 198, 198, 5450, 1378, 67, 375, 4450, 13, 1018, 298, 13, 1350, 14, 21283, 14, 1069, 2798, 2696, 14, 2079, 2998, 1120, 4531, 19, 14, 198, 37811, 628, 198, 2, 1257, 310, ...
2.304348
92
# coding: utf-8 from cv2 import cv2 import numpy as np cap = cv2.VideoCapture(0) while(1): # Take each frame _, frame = cap.read() # Convert BGR to HSV hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # define range of blue color in HSV lower_blue = np.array([110,50,50]) upper_blue = np.array([130,255,255]) # Threshold the HSV image to get only blue colors mask = cv2.inRange(hsv, lower_blue, upper_blue) # Bitwise-AND mask and original image res = cv2.bitwise_and(frame,frame, mask= mask) cv2.imshow('frame',frame) cv2.imshow('mask',mask) cv2.imshow('res',res) k = cv2.waitKey(5) & 0xFF if k == 27: break cv2.destroyAllWindows() # OBJECT TRACKING # Take each frame of the video # Convert from BGR to HSV color-space # We threshold the HSV image for a range of blue color # Now extract the blue object alone, we can do whatever on that image we want. # HOW TO FINDHSV VALUES TO TRACK? # It is very simple and you can use the same function, cv2.cvtColor(). Instead of passing an image, you just pass the BGR values you want. For example, to find the HSV value of Green, try following commands in Python terminal: # >>> green = np.uint8([[[0,255,0 ]]]) # >>> hsv_green = cv2.cvtColor(green,cv2.COLOR_BGR2HSV) # >>> print hsv_green # [[[ 60 255 255]]] # Now you take [H-10, 100,100] and [H+10, 255, 255] as lower bound and upper bound respectively. Apart from this method, you can use any image editing tools like GIMP or any online converters to find these values, but dont forget to adjust the HSV ranges. # Now you take [H-10, 100,100] and [H+10, 255, 255] as lower bound and upper bound respectively. Apart from this method, you can use any image editing tools like GIMP or any online converters to find these values, but dont forget to adjust the HSV ranges.
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 6738, 269, 85, 17, 1330, 269, 85, 17, 198, 11748, 299, 32152, 355, 45941, 198, 198, 11128, 796, 269, 85, 17, 13, 10798, 49630, 7, 15, 8, 198, 198, 4514, 7, 16, 2599, 628, 220, 220, 220, 130...
2.822358
653
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- # pylint: disable=line-too-long # pylint: disable=too-many-statements # pylint: disable=too-many-lines # pylint: disable=too-many-locals # pylint: disable=unused-argument import json
[ 2, 16529, 1783, 10541, 198, 2, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 49962, 739, 262, 17168, 13789, 13, 4091, 13789, 13, 14116, 287, 262, 1628, 6808, 329, 5964, 1321, 13, 198, 2, 16529, 1783, 10541, 198,...
4.463415
123
# Generated by Django 3.1.4 on 2020-12-30 00:27 from django.conf import settings from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 19, 319, 12131, 12, 1065, 12, 1270, 3571, 25, 1983, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
3.1
40
from turtle import Turtle FONT = ("Arial", 10, "normal") ALIGN = "center"
[ 6738, 28699, 1330, 33137, 198, 198, 37, 35830, 796, 5855, 32, 4454, 1600, 838, 11, 366, 11265, 4943, 198, 1847, 16284, 796, 366, 16159, 1 ]
2.96
25
import numpy
[ 11748, 299, 32152, 628 ]
3.5
4
"""Coverage based QC calculations. """ import glob import os import subprocess from bcbio.bam import ref, readstats, utils from bcbio.distributed import transaction from bcbio.heterogeneity import chromhacks import bcbio.pipeline.datadict as dd from bcbio.provenance import do from bcbio.variation import coverage as cov from bcbio.variation import bedutils def run(bam_file, data, out_dir): """Run coverage QC analysis """ out = dict() out_dir = utils.safe_makedir(out_dir) if dd.get_coverage(data) and dd.get_coverage(data) not in ["None"]: merged_bed_file = bedutils.clean_file(dd.get_coverage_merged(data), data, prefix="cov-", simple=True) target_name = "coverage" elif dd.get_coverage_interval(data) != "genome": merged_bed_file = dd.get_variant_regions_merged(data) target_name = "variant_regions" else: merged_bed_file = None target_name = "genome" avg_depth = cov.get_average_coverage(target_name, merged_bed_file, data) if target_name == "coverage": out_files = cov.coverage_region_detailed_stats(target_name, merged_bed_file, data, out_dir) else: out_files = [] out['Avg_coverage'] = avg_depth samtools_stats_dir = os.path.join(out_dir, os.path.pardir, 'samtools') from bcbio.qc import samtools samtools_stats = samtools.run(bam_file, data, samtools_stats_dir)["metrics"] out["Total_reads"] = total_reads = int(samtools_stats["Total_reads"]) out["Mapped_reads"] = mapped = int(samtools_stats["Mapped_reads"]) out["Mapped_paired_reads"] = int(samtools_stats["Mapped_paired_reads"]) out['Duplicates'] = dups = int(samtools_stats["Duplicates"]) if total_reads: out["Mapped_reads_pct"] = 100.0 * mapped / total_reads if mapped: out['Duplicates_pct'] = 100.0 * dups / mapped if dd.get_coverage_interval(data) == "genome": mapped_unique = mapped - dups else: mapped_unique = readstats.number_of_mapped_reads(data, bam_file, keep_dups=False) out['Mapped_unique_reads'] = mapped_unique if merged_bed_file: ontarget = readstats.number_of_mapped_reads( data, bam_file, keep_dups=False, bed_file=merged_bed_file, target_name=target_name) out["Ontarget_unique_reads"] = ontarget if mapped_unique: out["Ontarget_pct"] = 100.0 * ontarget / mapped_unique out['Offtarget_pct'] = 100.0 * (mapped_unique - ontarget) / mapped_unique if dd.get_coverage_interval(data) != "genome": # Skip padded calculation for WGS even if the "coverage" file is specified # the padded statistic makes only sense for exomes and panels padded_bed_file = bedutils.get_padded_bed_file(out_dir, merged_bed_file, 200, data) ontarget_padded = readstats.number_of_mapped_reads( data, bam_file, keep_dups=False, bed_file=padded_bed_file, target_name=target_name + "_padded") out["Ontarget_padded_pct"] = 100.0 * ontarget_padded / mapped_unique if total_reads: out['Usable_pct'] = 100.0 * ontarget / total_reads indexcov_files = _goleft_indexcov(bam_file, data, out_dir) out_files += [x for x in indexcov_files if x and utils.file_exists(x)] out = {"metrics": out} if len(out_files) > 0: out["base"] = out_files[0] out["secondary"] = out_files[1:] return out def _goleft_indexcov(bam_file, data, out_dir): """Use goleft indexcov to estimate coverage distributions using BAM index. Only used for whole genome runs as captures typically don't have enough data to be useful for index-only summaries. """ if not dd.get_coverage_interval(data) == "genome": return [] out_dir = utils.safe_makedir(os.path.join(out_dir, "indexcov")) out_files = [os.path.join(out_dir, "%s-indexcov.%s" % (dd.get_sample_name(data), ext)) for ext in ["roc", "ped", "bed.gz"]] if not utils.file_uptodate(out_files[-1], bam_file): with transaction.tx_tmpdir(data) as tmp_dir: tmp_dir = utils.safe_makedir(os.path.join(tmp_dir, dd.get_sample_name(data))) gender_chroms = [x.name for x in ref.file_contigs(dd.get_ref_file(data)) if chromhacks.is_sex(x.name)] gender_args = "--sex %s" % (",".join(gender_chroms)) if gender_chroms else "" cmd = "goleft indexcov --directory {tmp_dir} {gender_args} -- {bam_file}" try: do.run(cmd.format(**locals()), "QC: goleft indexcov") except subprocess.CalledProcessError as msg: if not ("indexcov: no usable" in str(msg) or ("indexcov: expected" in str(msg) and "sex chromosomes, found:" in str(msg))): raise for out_file in out_files: orig_file = os.path.join(tmp_dir, os.path.basename(out_file)) if utils.file_exists(orig_file): utils.copy_plus(orig_file, out_file) # MultiQC needs non-gzipped/BED inputs so unpack the file out_bed = out_files[-1].replace(".bed.gz", ".tsv") if utils.file_exists(out_files[-1]) and not utils.file_exists(out_bed): with transaction.file_transaction(data, out_bed) as tx_out_bed: cmd = "gunzip -c %s > %s" % (out_files[-1], tx_out_bed) do.run(cmd, "Unpack indexcov BED file") out_files[-1] = out_bed return [x for x in out_files if utils.file_exists(x)]
[ 37811, 7222, 1857, 1912, 36070, 16765, 13, 198, 37811, 198, 11748, 15095, 198, 11748, 28686, 198, 11748, 850, 14681, 198, 198, 6738, 275, 21101, 952, 13, 65, 321, 1330, 1006, 11, 1100, 34242, 11, 3384, 4487, 198, 6738, 275, 21101, 952, ...
2.267872
2,434
""" Utility functions for argument parsing """ import argparse def str2bool(val): """ Resolving boolean arguments if they are not given in the standard format Arguments: val (bool or string): boolean argument type Returns: bool: the desired value {True, False} """ if isinstance(val, bool): return val if isinstance(val, str): if val.lower() in ("yes", "true", "t", "y", "1"): return True elif val.lower() in ("no", "false", "f", "n", "0"): return False else: raise argparse.ArgumentTypeError("Boolean value expected.") def str2intlist(val): """Converts comma separated string of integers into list of integers Args: val (str): comma separate string of integers """ return commastring2list(int)(val) def commastring2list(output_type=str): """Returns a lambda function which converts a comma separated string into a list of a given type Args: output_type (function, optional): string type conversion function. Defaults to str. Returns: function: lambda function """ return lambda input_str: list(map(output_type, input_str.split(",")))
[ 37811, 198, 18274, 879, 5499, 329, 4578, 32096, 198, 37811, 198, 11748, 1822, 29572, 628, 198, 4299, 965, 17, 30388, 7, 2100, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 1874, 10890, 25131, 7159, 611, 484, 389, 407, 1813, 287...
2.756264
439
from concepts.letter_addition import LetterAddition from learners.sim_memoryless_learner import SimMemorylessLearner
[ 6738, 10838, 13, 9291, 62, 2860, 653, 1330, 18121, 4550, 653, 198, 6738, 46184, 13, 14323, 62, 31673, 1203, 62, 3238, 1008, 1330, 3184, 30871, 1203, 14961, 1008, 628 ]
4.068966
29
import logging import pandas as pd from datetime import datetime from typing import ( Any, Callable, Dict, Hashable, Iterable, List, NamedTuple, Optional, Pattern, Set, Tuple, Union, ) logger = logging.getLogger(__name__) # add_jde_batch() {{{1 def add_jde_batch(df: pd.DataFrame, col_prefix: str = 'ed', userid: str = 'userid', batch: str = 'ABC', start: int = 100, step: int = 100) -> pd.DataFrame: ''' Add 'standard' JDE timestamp/default columns. For given dataframe, adds the following standard Z-file columns. User ID (edus) Batch Number (edbt) Transaction Number (edtn) Line Number (edln) Examples -------- from piper.defaults import * from piper.jde import * .. code-block: %%piper sample_sales() >> select('-target_profit', '-location', '-month') >> reset_index(drop=True) >> add_jde_batch(start=3) >> head(tablefmt='plain') edus edbt edtn edln product target_sales actual_sales actual_profit 0 userid ABC_20210331 1 3 Beachwear 31749 29209 1753 1 userid ABC_20210331 1 103 Beachwear 37833 34050 5448 2 userid ABC_20210331 1 203 Jeans 29485 31549 4417 3 userid ABC_20210331 1 303 Jeans 37524 40901 4090 Parameters ---------- df : the pandas dataframe object col_prefix : 2 character (e.g. 'ed') column name prefix to be applied to the added columns userid : default userid text value batch : 2 character prefix to concatenated to current timestamp trans_no : start number in xxln column step : step increment in xxln column Returns ------- A pandas dataframe ''' timestamp = datetime.now().strftime('_%Y%m%d') start_position = 0 range_seq = range(start, (df.shape[0]+1)*step, step) df.insert(start_position, f'{col_prefix}us', userid) df.insert(start_position+1, f'{col_prefix}bt', batch + timestamp) df.insert(start_position+2, f'{col_prefix}tn', 1) df.insert(start_position+3, f'{col_prefix}ln', pd.Series(range_seq)) return df
[ 11748, 18931, 201, 198, 11748, 19798, 292, 355, 279, 67, 201, 198, 6738, 4818, 8079, 1330, 4818, 8079, 201, 198, 201, 198, 6738, 19720, 1330, 357, 201, 198, 220, 220, 220, 4377, 11, 201, 198, 220, 220, 220, 4889, 540, 11, 201, 198, ...
1.982799
1,279
import os import shutil import logging def accuracy(output, target, topk=(1,)): """Computes the precision@k for the specified values of k""" maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].view(-1).float().sum(0) res.append(correct_k.mul_(100.0 / batch_size)) return res
[ 11748, 28686, 198, 11748, 4423, 346, 198, 11748, 18931, 628, 628, 198, 198, 4299, 9922, 7, 22915, 11, 2496, 11, 1353, 74, 16193, 16, 35751, 2599, 198, 220, 220, 220, 37227, 7293, 1769, 262, 15440, 31, 74, 329, 262, 7368, 3815, 286, ...
2.365385
208
#!/usr/bin/env python from __future__ import division, absolute_import, print_function from setuptools import setup import os import re import shutil _versionRE = re.compile(r'__version__\s*=\s*\"([^\"]+)\"') # read the version number for the settings file with open('drawBot/drawBotSettings.py', "r") as settings: code = settings.read() found = _versionRE.search(code) assert found is not None, "drawBot __version__ not found" __version__ = found.group(1) externalTools = ("ffmpeg", "gifsicle", "mkbitmap", "potrace") externalToolsSourceRoot = os.path.join(os.path.dirname(__file__), "Resources", "externalTools") externalToolsDestRoot = os.path.join(os.path.dirname(__file__), "drawBot", "context", "tools") # copy all external tools into drawBot.context.tools folder for externalTool in externalTools: source = os.path.join(externalToolsSourceRoot, externalTool) dest = os.path.join(externalToolsDestRoot, externalTool) shutil.copyfile(source, dest) os.chmod(dest, 0o775) setup(name="drawBot", version=__version__, description="DrawBot is a powerful tool that invites you to write simple Python scripts to generate two-dimensional graphics. The builtin graphics primitives support rectangles, ovals, (bezier) paths, polygons, text objects and transparency.", author="Just van Rossum, Erik van Blokland, Frederik Berlaen", author_email="frederik@typemytype.com", url="http://drawbot.com", license="BSD", packages=[ "drawBot", "drawBot.context", "drawBot.context.tools", "drawBot.ui" ], package_data={ "drawBot": [ "context/tools/ffmpeg", "context/tools/gifsicle", "context/tools/mkbitmap", "context/tools/potrace" ] }, install_requires=[ "pyobjc", "fontTools", "booleanOperations", "pillow" ], include_package_data=True, ) # remove all external tools for externalTool in externalTools: dest = os.path.join(externalToolsDestRoot, externalTool) os.remove(dest)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 6738, 11593, 37443, 834, 1330, 7297, 11, 4112, 62, 11748, 11, 3601, 62, 8818, 198, 6738, 900, 37623, 10141, 1330, 9058, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 4423, 346, 628, ...
2.679487
780
# # PySNMP MIB module ZHONE-COM-IP-FILTER-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZHONE-COM-IP-FILTER-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:47:04 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection") ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex") SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Gauge32, Counter64, iso, Integer32, ModuleIdentity, ObjectIdentity, IpAddress, Unsigned32, MibIdentifier, TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, NotificationType, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "Counter64", "iso", "Integer32", "ModuleIdentity", "ObjectIdentity", "IpAddress", "Unsigned32", "MibIdentifier", "TimeTicks", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "NotificationType", "Counter32") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") zhoneModules, zhoneIp = mibBuilder.importSymbols("Zhone", "zhoneModules", "zhoneIp") ZhoneRowStatus, ZhoneAdminString = mibBuilder.importSymbols("Zhone-TC", "ZhoneRowStatus", "ZhoneAdminString") comIpFilter = ModuleIdentity((1, 3, 6, 1, 4, 1, 5504, 6, 58)) comIpFilter.setRevisions(('2005-01-10 10:16', '2005-01-03 09:24', '2004-12-21 09:25', '2004-08-30 11:00', '2004-04-06 00:17', '2001-01-17 08:48', '2000-09-11 16:22',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: comIpFilter.setRevisionsDescriptions(('changed portAccessArg1, portAccessArg2 to more intuitive names.', 'changed portArg1, portArg2 to IP addresses', 'added Port_Access', 'V01.01.02 - Add type field to mcastControlList.', 'V01.01.01 - Implementation of multicast-control-list.', 'V01.01.00 - Added keyword markup, updated SMI, Added the filterStmtRenumTable and filterStatsTable', 'V01.00.00 - Initial Release',)) if mibBuilder.loadTexts: comIpFilter.setLastUpdated('200501100015Z') if mibBuilder.loadTexts: comIpFilter.setOrganization('Zhone Technologies, Inc.') if mibBuilder.loadTexts: comIpFilter.setContactInfo(' Postal: Zhone Technologies, Inc. @ Zhone Way 7001 Oakport Street Oakland, CA 94621 USA Toll-Free: +1 877-ZHONE20 (+1 877-946-6320) Tel: +1-510-777-7000 Fax: +1-510-777-7001 E-mail: support@zhone.com') if mibBuilder.loadTexts: comIpFilter.setDescription('Zhone IP Filter MIB Module. IP Software Minneapolis, MN') filter = ObjectIdentity((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8)) if mibBuilder.loadTexts: filter.setStatus('current') if mibBuilder.loadTexts: filter.setDescription('The MIB module representing IP filter specifications in Zhone Technologies products. IP filtering is typically performed to enhance network security by limiting what access is allowed between two networks. Filtering is also effective in eliminating certain denial-of-service attacks. Packet filtering also provides a framework for sanity checking packet headers, and rejecting packets that are unlikely (or that should be impossible). In this way, packet filtering can prevent certain unfortunate mistakes from shutting a network down.') if mibBuilder.loadTexts: filter.setReference("RFC1812, 'Requirements for IP Version 4 Routers,' ftp://ftp.isi.edu/in-notes/rfc1812.txt. RFC2267, 'Network Ingress Filtering: Defeating Denial of Service Attacks which employ IP Source Address Spoofing,' ftp://ftp.isi.edu/in-notes/rfc2267.txt. RFC2474, 'Definition of the Differentiated Services Field (DS Field) in the IPv4 and IPv6 Headers', ftp://ftp.isi.edu/in-notes/rfc2474.txt. D. Brent Chapman, 'Network (In)Security Through IP Packet Filtering,' Proceedings of the 3rd USENIX Security Symposium, Sept. 1992. Andrew Molitor, 'An Architecture for Advanced Packet Filtering,' Proceedings of the 5th USENIX Security Symposium, June. 1995. Paul Russell, 'Linux IPCHAINS-HOWTO,' http://www.rustcorp.com/linux/ipchains/HOWTO.html, v1.0.7, Mar. 1999.") filterGlobal = ObjectIdentity((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 1)) if mibBuilder.loadTexts: filterGlobal.setStatus('current') if mibBuilder.loadTexts: filterGlobal.setDescription('Global filter provisioning information.') fltGlobalIndexNext = MibScalar((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: fltGlobalIndexNext.setStatus('current') if mibBuilder.loadTexts: fltGlobalIndexNext.setDescription('The next available filter spec table index (filterSpecIndex). A GET on this object increments the value by one. A GETNEXT on this object will always return zero.') fltGlobalTimeout = MibScalar((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setUnits('seconds').setMaxAccess("readwrite") if mibBuilder.loadTexts: fltGlobalTimeout.setStatus('current') if mibBuilder.loadTexts: fltGlobalTimeout.setDescription('Filter inconsistency timeout in seconds. A filter spec is considered to be in an inconsistent state when the value of the objects fltSpecVersion1 and fltSpecVersion2 are not equal. This timeout indicates the minimum number of seconds a filter may be in an inconsistent state before the filter spec becomes invalid and the default action for a filter is used as the filter. Provided fltGlobalTimeout is long enough, it should ensure that both an old modification is permanently stalled (ensuring exclusive access) as well as enough time to repair a filter. Default is five seconds.') filterSpecTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2), ) if mibBuilder.loadTexts: filterSpecTable.setStatus('current') if mibBuilder.loadTexts: filterSpecTable.setDescription("The filter specification table contains specifications for the IP filtering module. Rows are indexed by a single integer index (filterSpecIndex). The fltGlobalIndexNext object is used to determine the next index value. Each row points to a sequence of rows (statements) in the filterStatementTable. When any row in that sequence is modified, created, or removed, the fltSpecVersion1 and fltSpecVersion2 objects must be incremented. Rows are created by assigning fltSpecIndex and setting fltSpecRowStatus to 'createAndGo'. All columnar objects in this table have default values, so no objects other than the index value need be set to create a row. Rows are removed by setting fltSpecRowStatus to 'destroy'. When a row is removed, each row in filterStatementTable with the same fltSpecIndex is automatically removed.") filterSpecEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1), ).setIndexNames((0, "ZHONE-COM-IP-FILTER-MIB", "fltSpecIndex")) if mibBuilder.loadTexts: filterSpecEntry.setStatus('current') if mibBuilder.loadTexts: filterSpecEntry.setDescription('An entry in the filterSpecTable.') fltSpecIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))) if mibBuilder.loadTexts: fltSpecIndex.setStatus('current') if mibBuilder.loadTexts: fltSpecIndex.setDescription('The index that identifies an entry in the filterSpecTable. The fltGlobalIndexNext object is used to determine the next value of this object.') fltSpecName = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 2), ZhoneAdminString()).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltSpecName.setStatus('current') if mibBuilder.loadTexts: fltSpecName.setDescription('The filter name associated with this filter specification. This name should indicate the nature of the filter. The default value is an empty string.') fltSpecDesc = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 3), SnmpAdminString()).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltSpecDesc.setStatus('current') if mibBuilder.loadTexts: fltSpecDesc.setDescription('Textual description of the filter specification. This should briefly describe the nature of the filter defined by the associated filter statements. The default value is an empty string.') fltSpecVersion1 = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 4), Unsigned32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltSpecVersion1.setStatus('current') if mibBuilder.loadTexts: fltSpecVersion1.setDescription('The version number of the filter specification. This is used to flag any changes in the statements that comprise a filter. Each time a modification occurs to an object in a filter spec (including the the list of filter statements of the same fltSpecIndex in filterStatementTable), the value of this object, and fltSpecVersion2 must be incremented. The manager adding, deleting, or modifying a filter statement or statements must increment this version number in the following manner. A read of fltSpecVersion1 returns its current value. A write to fltSpecVersion1 must be one greater than its current value. A successful write of this object transfers ownership to the manager, where the manager must subsequently perform any desired modifications to the filter spec and then write the new value of fltSpecVersion1 to the fltSpecVersion2 object to release ownership. When fltSpecVersion1 does not equal to fltSpecVersion2, the filter spec is in an inconsistent state. If the filter spec remains in an inconsistent state longer than the time specified in fltGlobalTimeout, the filter spec is declared invalid and the filter spec does not become active. The previously provisioned filter spec will remain active. If no previous filter spec was provisioned for this interface, a default action is used. It is up to the manager to fix the invalid filter spec and bring it into a consistent state.') fltSpecVersion2 = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 5), Unsigned32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltSpecVersion2.setStatus('current') if mibBuilder.loadTexts: fltSpecVersion2.setDescription('The version number of the filter specification. The value of this object must be equal to fltSpecVersion1, otherwise the filter spec is inconsistent. See fltSpecVersion1 for details.') fltSpecLanguageVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 6), Unsigned32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltSpecLanguageVersion.setStatus('current') if mibBuilder.loadTexts: fltSpecLanguageVersion.setDescription('The language version of the filter. The language version further details the meaning and use of the objects in filterStatmentTable. The definitions of the filter languages is beyond the scope of this description.') fltSpecRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 2, 1, 7), ZhoneRowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltSpecRowStatus.setStatus('current') if mibBuilder.loadTexts: fltSpecRowStatus.setDescription('Zhone convention to support row creation and deletion. This is the only object required to create or destroy a row in this table.') filterStatementTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3), ) if mibBuilder.loadTexts: filterStatementTable.setStatus('current') if mibBuilder.loadTexts: filterStatementTable.setDescription("This table contains the filter specification statements for the IP filtering module. A complete filter specification is comprised of all the linked statements (rows) that are pointed to by an entry in the filterSpecTable. Filter statements are linked together by fltSpecIndex, and are ordered within the comprised filter using fltStmtIndex. A statement can only be owned by one filter spec. Rows are created by assigning fltSpecIndex and fltStmtIndex, and setting fltStmtRowStatus to 'createAndGo'. All columnar objects in this table have default values, so no objects other than the index values need be set to create a row. Rows are destroyed by setting fltStmtRowStatus to 'delete'. When rows are created or destroyed, the version of the corresponding filter spec row is incremented.") filterStatementEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1), ).setIndexNames((0, "ZHONE-COM-IP-FILTER-MIB", "fltSpecIndex"), (0, "ZHONE-COM-IP-FILTER-MIB", "fltStmtIndex")) if mibBuilder.loadTexts: filterStatementEntry.setStatus('current') if mibBuilder.loadTexts: filterStatementEntry.setDescription('An entry in the filterStatement table. Each entry represents one of a sequence of statements that comprise a filter. Each filter statement consists of an index, specific packet header fields, and arbitrary packet offsets and values. Some objects in this entry define ranges for specific packet header fields. These objects define comparison operations on the field they share in the following manner: Low High Compare Method for field f --- ---- ------------------------------------------- 0 0 no comparison on the field 0 H less than or equal to High (f <= H) L 0 exact match (L == f) L H inclusive between comparison (L <= f <= H) ') fltStmtIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))) if mibBuilder.loadTexts: fltStmtIndex.setStatus('current') if mibBuilder.loadTexts: fltStmtIndex.setDescription('The table index that identifies a filter statement. These indicies should be sparse to allow for insertion into the list.') fltStmtIpSrcAddrLow = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 2), IpAddress().clone(hexValue="00000000")).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtIpSrcAddrLow.setStatus('current') if mibBuilder.loadTexts: fltStmtIpSrcAddrLow.setDescription('The inclusive lower bound for the source IP address range. See the filterStatementEntry description for details.') fltStmtIpSrcAddrHigh = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 3), IpAddress().clone(hexValue="00000000")).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtIpSrcAddrHigh.setStatus('current') if mibBuilder.loadTexts: fltStmtIpSrcAddrHigh.setDescription('The inclusive upper bound for the source IP address range. See the filterStatementEntry description for details.') fltStmtSrcPortLow = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtSrcPortLow.setStatus('current') if mibBuilder.loadTexts: fltStmtSrcPortLow.setDescription('The inclusive lower bound for the transport layer source port range. See the filterStatementEntry description for details.') fltStmtSrcPortHigh = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtSrcPortHigh.setStatus('current') if mibBuilder.loadTexts: fltStmtSrcPortHigh.setDescription('The inclusive upper bound for the transport layer source port range. See the filterStatementEntry description for details.') fltStmtIpDstAddrLow = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 6), IpAddress().clone(hexValue="00000000")).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtIpDstAddrLow.setStatus('current') if mibBuilder.loadTexts: fltStmtIpDstAddrLow.setDescription('The inclusive lower bound for the destination IP address range. See the filterStatementEntry description for details.') fltStmtIpDstAddrHigh = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 7), IpAddress().clone(hexValue="00000000")).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtIpDstAddrHigh.setStatus('current') if mibBuilder.loadTexts: fltStmtIpDstAddrHigh.setDescription('The inclusive upper bound for the destination IP address range. See the filterStatementEntry description for details.') fltStmtDstPortLow = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtDstPortLow.setStatus('current') if mibBuilder.loadTexts: fltStmtDstPortLow.setDescription('The inclusive lower bound for the transport layer destination port range. See the filterStatementEntry description for details.') fltStmtDstPortHigh = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtDstPortHigh.setStatus('current') if mibBuilder.loadTexts: fltStmtDstPortHigh.setDescription('The inclusive upper bound for the transport layer destination port range. See the filterStatementEntry description for details.') fltStmtIpProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("any", 1), ("ip", 2), ("tcp", 3), ("udp", 4), ("icmp", 5))).clone('any')).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtIpProtocol.setStatus('current') if mibBuilder.loadTexts: fltStmtIpProtocol.setDescription('The IP protocol value that is to be matched. The enum values are as follows: any(1) : any protocol type is a match (wildcard) ip(2) : raw IP packet tcp(3) : TCP packet udp(4) : UDP packet icmp(5) : ICMP packet The default value is any(1).') fltStmtArbValueBase = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("none", 1), ("ip", 2), ("udp", 3), ("tcp", 4), ("icmp", 5), ("ipOptions", 6), ("tcpOptions", 7))).clone('none')).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtArbValueBase.setStatus('current') if mibBuilder.loadTexts: fltStmtArbValueBase.setDescription('This field identifies the protocol header to which the arbitrary value comparison applies. The enum values are as follows: none(1) : no arbitrary value comparison ip(2) : base is IP header udp(3) : base is UDP header tcp(4) : base is TCP header icmp(5) : base is ICMP header ipOptions(6) : base is IP options header tcpOptions(7) : base is TCP options header The default value is none(1).') fltStmtArbOffset = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 12), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 64))).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtArbOffset.setStatus('current') if mibBuilder.loadTexts: fltStmtArbOffset.setDescription('The offset, in octets, from the beginning of the header to the most significant octet for the arbitrary value comparison.') fltStmtArbMask = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 13), Unsigned32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtArbMask.setStatus('current') if mibBuilder.loadTexts: fltStmtArbMask.setDescription('This object is mask for for arbitrary value comparisons. The non-zero bits in this field determine the size of the arbitrary field.') fltStmtArbValueLow = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 14), Unsigned32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtArbValueLow.setStatus('current') if mibBuilder.loadTexts: fltStmtArbValueLow.setDescription('This object is the inclusive lower bound for arbitrary value comparison. See the filterStatementEntry description for details.') fltStmtArbValueHigh = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 15), Unsigned32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtArbValueHigh.setStatus('current') if mibBuilder.loadTexts: fltStmtArbValueHigh.setDescription('This object is the inclusive upper bound for arbitrary value comparison. See the filterStatementEntry description for details.') fltStmtModifier = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 16), Bits().clone(namedValues=NamedValues(("notIpSrc", 0), ("notSrcPort", 1), ("notDstIp", 2), ("notPortDst", 3), ("notProtocol", 4), ("notArbitrary", 5), ("notStatement", 6)))).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtModifier.setStatus('current') if mibBuilder.loadTexts: fltStmtModifier.setDescription('Filter statement modifier. The bits set in this object logically negate the results of the comparisons made on their respecive fields as shown : notIpSrcAddr(1) : fltStmtIpSrcAddrLow, fltStmtIpSrcAddrHigh notSrcPort(2) : fltStmtSrcPortLow, fltStmtSrcPortHigh notIpDstAddr(3) : fltStmtIpDstAddrLow, fltStmtIpDstAddrHigh notDstPort(4) : fltStmtDstPortLow, fltStmtDstPortHigh notIpProtocol(5) : fltStmtIpProtocol notArbitrary(6) : fltStmtArbValueLow, fltStmtArbValueHigh notStatement(7) : negate outcome of the entire statement No bits set (the default) specifies to use all outcomes as is.') fltStmtAction = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 17), Bits().clone(namedValues=NamedValues(("reset", 0), ("permit", 1), ("deny", 2), ("forward", 3), ("reject", 4), ("log", 5))).clone(namedValues=NamedValues(("deny", 2)))).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtAction.setStatus('current') if mibBuilder.loadTexts: fltStmtAction.setDescription('Filter statement action. The bits set in this object specify actions to take on packets matching this statement. Supported actions are: reset(0) : Return a TCP reset packet to the packet sender and drop the packet. This cannot be specified with permit. permit(1) : Stop filtering the packet and allow it to be sent on the associated interface. This cannot be specified with deny. deny(2) : Stop filtering the packet and discard it. This cannot be specified with permit. forward(3) : Forward the packet the IP address specified in fltStmtActionArg. reject(4) : Return an ICMP destination unreachable packet (type 3) to the packet sender with code 13 (communication administratively prohibited). This cannot be specified permit. log(5) : Write the packet to the log stream. There are some mutually exclusive bits: reset(0) and permit(1), permit(1) and deny(2), permit(1) and reject(4). No bits set implies to continue filtering on the packet.') fltStmtActionArg = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 18), Integer32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtActionArg.setStatus('current') if mibBuilder.loadTexts: fltStmtActionArg.setDescription('Filter statement action argument. The meaning of this object depends on the value of fltStmtAction: forward(3) : An IP address to forward the packet to. The value of this object must be non-zero. All other values of fltStmtAction have no relation to this object. The default is zero.') fltStmtRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 3, 1, 19), ZhoneRowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: fltStmtRowStatus.setStatus('current') if mibBuilder.loadTexts: fltStmtRowStatus.setDescription('Zhone convention to support row creation and deletion. This is the only object required to create or destroy a row in this table.') filterStmtRenumTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 4), ) if mibBuilder.loadTexts: filterStmtRenumTable.setStatus('current') if mibBuilder.loadTexts: filterStmtRenumTable.setDescription('This table provides a mechanism for renumbering individual filter statments within their particular filter spec.') filterStmtRenumEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 4, 1), ) filterStatementEntry.registerAugmentions(("ZHONE-COM-IP-FILTER-MIB", "filterStmtRenumEntry")) filterStmtRenumEntry.setIndexNames(*filterStatementEntry.getIndexNames()) if mibBuilder.loadTexts: filterStmtRenumEntry.setStatus('current') if mibBuilder.loadTexts: filterStmtRenumEntry.setDescription('An entry in the filterStmtRenumTable.') fltStmtIndexNew = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readwrite") if mibBuilder.loadTexts: fltStmtIndexNew.setStatus('current') if mibBuilder.loadTexts: fltStmtIndexNew.setDescription("The new statement index for the filter statement. Reading this object will return the same value as the 'fltStmtIndex' portion of its index. Writing to this object will cause the corresponding filter statement to be relocated to the position identified by the value written here. If no statement exists at the current index, 'no such instance' will be returned. If a statement already exists at the new index then 'inconsistent value' is returned. For example, to move the second statement of filter #4 to the third position (e.g. to make room for a new statement #2), the following SNMP set-request would be issued: fltStmtIndexNew.4.2 = 3 There is no default value for this object as it is derived from the fltStmtIndex.") filterStatsTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5), ) if mibBuilder.loadTexts: filterStatsTable.setStatus('current') if mibBuilder.loadTexts: filterStatsTable.setDescription('This table provides ingress and egress IP filter statistics for each interface. This table is indexed by the ifIndex of the interface and the direction (ingress or egress) of traffic being filtered. This is a read-only table.') filterStatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"), (0, "ZHONE-COM-IP-FILTER-MIB", "fltStatDirection")) if mibBuilder.loadTexts: filterStatsEntry.setStatus('current') if mibBuilder.loadTexts: filterStatsEntry.setDescription('An entry in the filterStatsTable. There will be an entry for each filter provisioned on an interface. There can be, at most, two filters provisioned per interface; one for ingress filtering and the other for egress filtering.') fltStatDirection = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ingress", 1), ("egress", 2)))) if mibBuilder.loadTexts: fltStatDirection.setStatus('current') if mibBuilder.loadTexts: fltStatDirection.setDescription('The direction for which this set of statistics is kept: ingress or egress.') fltStatResetPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 2), Counter32()).setUnits('packets').setMaxAccess("readonly") if mibBuilder.loadTexts: fltStatResetPkts.setStatus('current') if mibBuilder.loadTexts: fltStatResetPkts.setDescription('The number of discarded packets for which a TCP reset packet was sent.') fltStatPermitPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 3), Counter32()).setUnits('packets').setMaxAccess("readonly") if mibBuilder.loadTexts: fltStatPermitPkts.setStatus('current') if mibBuilder.loadTexts: fltStatPermitPkts.setDescription('The number of permitted packets.') fltStatDenyPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 4), Counter32()).setUnits('packets').setMaxAccess("readonly") if mibBuilder.loadTexts: fltStatDenyPkts.setStatus('current') if mibBuilder.loadTexts: fltStatDenyPkts.setDescription('The number of discarded packets.') fltStatForwardPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 5), Counter32()).setUnits('packets').setMaxAccess("readonly") if mibBuilder.loadTexts: fltStatForwardPkts.setStatus('current') if mibBuilder.loadTexts: fltStatForwardPkts.setDescription('The number of packets forwarded to the IP address specified in the filter.') fltStatRejectPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 6), Counter32()).setUnits('packets').setMaxAccess("readonly") if mibBuilder.loadTexts: fltStatRejectPkts.setStatus('current') if mibBuilder.loadTexts: fltStatRejectPkts.setDescription('The number of discarded packets for which an ICMP destination unreachable packet with code 13 was sent.') fltStatLogPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 7), Counter32()).setUnits('packets').setMaxAccess("readonly") if mibBuilder.loadTexts: fltStatLogPkts.setStatus('current') if mibBuilder.loadTexts: fltStatLogPkts.setDescription('The number of logged packets.') fltStatDefaultPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 8), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: fltStatDefaultPkts.setStatus('current') if mibBuilder.loadTexts: fltStatDefaultPkts.setDescription('The number of packets that pass through the filter without matching upon which the default action is used.') fltStatSpecVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 9), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: fltStatSpecVersion.setStatus('current') if mibBuilder.loadTexts: fltStatSpecVersion.setDescription('The version of the filter being used on this interface.') fltStatSpecIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 5, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: fltStatSpecIndex.setStatus('current') if mibBuilder.loadTexts: fltStatSpecIndex.setDescription('The index of the filter specification being used on this interface. If there is no filter configured for an interface, the entry will not exist in this table.') mcastControl = ObjectIdentity((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6)) if mibBuilder.loadTexts: mcastControl.setStatus('current') if mibBuilder.loadTexts: mcastControl.setDescription('The MIB module representing Multicast control list specifications in Zhone Technologies products. The First application of multicast control list is to accept of deny a IGMP request to join or leave a IGMP group. Any IGMP request to join a group is accepted only if the group address is available in the Multicast Control list pointed by a field in the ip-interface-record.') mcastControlListTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1), ) if mibBuilder.loadTexts: mcastControlListTable.setStatus('current') if mibBuilder.loadTexts: mcastControlListTable.setDescription('Multicast control list table conatins the one of the IP Address that can be allowed to join to by a IGMP join request from IP interface that has the the multicast control list in its ip-interfce-profile. The address to the table is the multicast control list ID and the precedence. The Row status in the table contains indication of whether the row is being created or destroyed. ') mcastControlListEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1, 1), ).setIndexNames((0, "ZHONE-COM-IP-FILTER-MIB", "mcastControlListControlId"), (0, "ZHONE-COM-IP-FILTER-MIB", "mcastControlListControlPrecedence")) if mibBuilder.loadTexts: mcastControlListEntry.setStatus('current') if mibBuilder.loadTexts: mcastControlListEntry.setDescription('An entry in the Multicast Control List.') mcastControlListControlId = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))) if mibBuilder.loadTexts: mcastControlListControlId.setStatus('current') if mibBuilder.loadTexts: mcastControlListControlId.setDescription('Description.') mcastControlListControlPrecedence = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))) if mibBuilder.loadTexts: mcastControlListControlPrecedence.setStatus('current') if mibBuilder.loadTexts: mcastControlListControlPrecedence.setDescription('Description.') mcastControlListRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1, 1, 3), ZhoneRowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: mcastControlListRowStatus.setStatus('current') if mibBuilder.loadTexts: mcastControlListRowStatus.setDescription('Description.') mcastControlListIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1, 1, 4), IpAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: mcastControlListIpAddress.setStatus('current') if mibBuilder.loadTexts: mcastControlListIpAddress.setDescription('multicast ip address.') mcastControlListType = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 6, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("normal", 1), ("always-on", 2), ("periodic", 3))).clone('normal')).setMaxAccess("readcreate") if mibBuilder.loadTexts: mcastControlListType.setStatus('current') if mibBuilder.loadTexts: mcastControlListType.setDescription('Defines the video stream type. normal - join and leave when desired. Used for video. always-on - always joined. Meant for EBS, not video. periodic - will join and leave after task complete. Not meant for video. Used to download the tv guide.') portAccessControl = ObjectIdentity((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7)) if mibBuilder.loadTexts: portAccessControl.setStatus('current') if mibBuilder.loadTexts: portAccessControl.setDescription('This MIB represents the port access control list in Zhone products. It is used to control access to internal ports. Initially it is used just for TELNET (23) , but in theory could be used for other ports as well.') portAccessNextIndex = MibScalar((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: portAccessNextIndex.setStatus('current') if mibBuilder.loadTexts: portAccessNextIndex.setDescription('Description: A hint for the next free index should the manager want to create a new entry.') portAccessTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2), ) if mibBuilder.loadTexts: portAccessTable.setStatus('current') if mibBuilder.loadTexts: portAccessTable.setDescription('Contains the list of entries that control port access on this device.') portAccessEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2, 1), ).setIndexNames((0, "ZHONE-COM-IP-FILTER-MIB", "portAccessIndex")) if mibBuilder.loadTexts: portAccessEntry.setStatus('current') if mibBuilder.loadTexts: portAccessEntry.setDescription('This contains the entry that is to be accepted. Currently only used to control access to port 23. arg1, arg2 provide IP Address/mask to allow in.') portAccessIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 100))) if mibBuilder.loadTexts: portAccessIndex.setStatus('current') if mibBuilder.loadTexts: portAccessIndex.setDescription('The index of this entry in table. 100 entries should be more than enough.') portAccessRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2, 1, 2), ZhoneRowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: portAccessRowStatus.setStatus('current') if mibBuilder.loadTexts: portAccessRowStatus.setDescription('Description.: used to create/delete entries in the table.') portAccessNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1023))).setMaxAccess("readcreate") if mibBuilder.loadTexts: portAccessNumber.setStatus('current') if mibBuilder.loadTexts: portAccessNumber.setDescription('PortNumber that this applies to, 1..1023 supported.') portAccessSrcAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2, 1, 4), IpAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: portAccessSrcAddr.setStatus('current') if mibBuilder.loadTexts: portAccessSrcAddr.setDescription('The IP address that we will accept packets from.') portAccessNetMask = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 4, 1, 8, 7, 2, 1, 5), IpAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: portAccessNetMask.setStatus('current') if mibBuilder.loadTexts: portAccessNetMask.setDescription('portAccessNetMask - used to pass the range that we will accept with regards to portAccessSrcAddr.') mibBuilder.exportSymbols("ZHONE-COM-IP-FILTER-MIB", fltStmtIpDstAddrLow=fltStmtIpDstAddrLow, fltStmtIpSrcAddrHigh=fltStmtIpSrcAddrHigh, mcastControlListIpAddress=mcastControlListIpAddress, fltSpecVersion1=fltSpecVersion1, fltStatSpecIndex=fltStatSpecIndex, portAccessSrcAddr=portAccessSrcAddr, fltStatSpecVersion=fltStatSpecVersion, portAccessNumber=portAccessNumber, fltStmtIpProtocol=fltStmtIpProtocol, fltStmtModifier=fltStmtModifier, fltSpecLanguageVersion=fltSpecLanguageVersion, fltStmtSrcPortLow=fltStmtSrcPortLow, mcastControlListControlPrecedence=mcastControlListControlPrecedence, fltStmtActionArg=fltStmtActionArg, fltSpecVersion2=fltSpecVersion2, filterStmtRenumEntry=filterStmtRenumEntry, filterStmtRenumTable=filterStmtRenumTable, portAccessTable=portAccessTable, mcastControlListControlId=mcastControlListControlId, fltStmtIpDstAddrHigh=fltStmtIpDstAddrHigh, fltStmtRowStatus=fltStmtRowStatus, comIpFilter=comIpFilter, portAccessControl=portAccessControl, fltStatDirection=fltStatDirection, mcastControl=mcastControl, fltStmtArbValueLow=fltStmtArbValueLow, mcastControlListTable=mcastControlListTable, filterGlobal=filterGlobal, fltSpecIndex=fltSpecIndex, PYSNMP_MODULE_ID=comIpFilter, fltStmtSrcPortHigh=fltStmtSrcPortHigh, filterStatsTable=filterStatsTable, fltStmtArbMask=fltStmtArbMask, fltGlobalIndexNext=fltGlobalIndexNext, fltStmtIndexNew=fltStmtIndexNew, mcastControlListRowStatus=mcastControlListRowStatus, filterStatsEntry=filterStatsEntry, fltStmtArbValueBase=fltStmtArbValueBase, fltStatLogPkts=fltStatLogPkts, fltStatResetPkts=fltStatResetPkts, fltStatPermitPkts=fltStatPermitPkts, mcastControlListType=mcastControlListType, portAccessIndex=portAccessIndex, fltStmtDstPortLow=fltStmtDstPortLow, fltGlobalTimeout=fltGlobalTimeout, filterStatementTable=filterStatementTable, fltStatDefaultPkts=fltStatDefaultPkts, filter=filter, fltStmtArbOffset=fltStmtArbOffset, portAccessEntry=portAccessEntry, portAccessNextIndex=portAccessNextIndex, fltStatRejectPkts=fltStatRejectPkts, mcastControlListEntry=mcastControlListEntry, filterStatementEntry=filterStatementEntry, fltStmtIndex=fltStmtIndex, filterSpecTable=filterSpecTable, fltSpecRowStatus=fltSpecRowStatus, fltStmtArbValueHigh=fltStmtArbValueHigh, portAccessNetMask=portAccessNetMask, portAccessRowStatus=portAccessRowStatus, fltStmtAction=fltStmtAction, fltStmtIpSrcAddrLow=fltStmtIpSrcAddrLow, filterSpecEntry=filterSpecEntry, fltStatDenyPkts=fltStatDenyPkts, fltSpecDesc=fltSpecDesc, fltSpecName=fltSpecName, fltStmtDstPortHigh=fltStmtDstPortHigh, fltStatForwardPkts=fltStatForwardPkts)
[ 2, 198, 2, 9485, 15571, 7378, 337, 9865, 8265, 1168, 39, 11651, 12, 9858, 12, 4061, 12, 46700, 5781, 12, 8895, 33, 357, 4023, 1378, 16184, 76, 489, 8937, 13, 785, 14, 79, 893, 11632, 8, 198, 2, 7054, 45, 13, 16, 2723, 2393, 1378...
3.143531
12,290
############################################################################### # WaterTAP Copyright (c) 2021, The Regents of the University of California, # through Lawrence Berkeley National Laboratory, Oak Ridge National # Laboratory, National Renewable Energy Laboratory, and National Energy # Technology Laboratory (subject to receipt of any required approvals from # the U.S. Dept. of Energy). All rights reserved. # # Please see the files COPYRIGHT.md and LICENSE.md for full copyright and license # information, respectively. These files are also available online at the URL # "https://github.com/watertap-org/watertap/" # ############################################################################### from pyomo.environ import ( ConcreteModel, value, TransformationFactory, units as pyunits, assert_optimal_termination, ) from pyomo.network import Arc, SequentialDecomposition from pyomo.util.check_units import assert_units_consistent from idaes.core import FlowsheetBlock from idaes.core.util import get_solver from idaes.generic_models.unit_models import Product import idaes.core.util.scaling as iscale from idaes.generic_models.costing import UnitModelCostingBlock from watertap.core.util.initialization import assert_degrees_of_freedom from watertap.core.wt_database import Database import watertap.core.zero_order_properties as prop_ZO from watertap.unit_models.zero_order import ( FeedZO, MunicipalDrinkingZO, WaterPumpingStationZO, PumpZO, CoagulationFlocculationZO, SedimentationZO, OzoneZO, FixedBedZO, GACZO, UVZO, IonExchangeZO, ChlorinationZO, StorageTankZO, BackwashSolidsHandlingZO, ) from watertap.core.zero_order_costing import ZeroOrderCosting if __name__ == "__main__": m, results = main()
[ 29113, 29113, 7804, 4242, 21017, 198, 2, 5638, 51, 2969, 15069, 357, 66, 8, 33448, 11, 383, 3310, 658, 286, 262, 2059, 286, 3442, 11, 198, 2, 832, 13914, 14727, 2351, 18643, 11, 9121, 20614, 2351, 198, 2, 18643, 11, 2351, 29479, 540...
3.304189
549
# Copyright 2013 Google Inc. All Rights Reserved. """Deletes a Cloud SQL instance.""" from googlecloudapis.apitools.base import py as apitools_base from googlecloudsdk.calliope import base from googlecloudsdk.calliope import exceptions from googlecloudsdk.core import log from googlecloudsdk.core.util import console_io from googlecloudsdk.sql import util
[ 2, 15069, 2211, 3012, 3457, 13, 1439, 6923, 33876, 13, 198, 37811, 5005, 40676, 257, 10130, 16363, 4554, 526, 15931, 198, 198, 6738, 23645, 17721, 499, 271, 13, 499, 270, 10141, 13, 8692, 1330, 12972, 355, 2471, 270, 10141, 62, 8692, ...
3.554455
101