content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
# # Copyright (c) 2019 Intel Corporation # # 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 click.testing import CliRunner from cli_text_consts import ModelExportCmdTexts as Texts from commands.model.common import workflow_description from commands.model.export import export from platform_resources.workflow import ArgoWorkflow, QUEUED_PHASE FEM_NAME = "EXPORT_1" SEM_NAME = "EXPORT_2" FEM_PARAMETERS = "PARAMS_1" SEM_PARAMETERS = "PARAMS_2" FEM_START_DATE = '2000-01-01' FEM_NAMESPACE = 'test-namespace' TEST_AGROWORKFLOW = ArgoWorkflow(name=FEM_NAME, started_at=FEM_START_DATE, finished_at=None, namespace=FEM_NAMESPACE, phase=None) TWO_MODEL_OUTPUT = [workflow_description(name=FEM_NAME, parameters=FEM_PARAMETERS), workflow_description(name=SEM_NAME, parameters=SEM_PARAMETERS)]
[ 2, 198, 2, 15069, 357, 66, 8, 13130, 8180, 10501, 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, 287, 11846, 351, 262, 13789, 13, ...
2.801242
483
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import *
[ 2, 15069, 2211, 12, 1238, 2481, 13914, 45036, 3549, 2351, 4765, 11, 11419, 290, 584, 198, 2, 1338, 441, 4935, 34152, 13, 4091, 262, 1353, 12, 5715, 27975, 38162, 9947, 2393, 329, 3307, 13, 198, 2, 198, 2, 30628, 55, 12, 34156, 12, ...
3.421875
64
from requests import get import matplotlib.pyplot as plt import matplotlib.animation as animation import datetime as dt from bme280 import BME280 try: from smbus2 import SMBus except ImportError: from smbus import SMBus fig = plt.figure() ax = fig.add_subplot(1, 1, 1) xs = [] ys =[] bus = SMBus(1) bme280 = BME280(i2c_dev=bus) ani = animation.FuncAnimation(fig, animate, fargs=(xs, ys), interval=60000) plt.show()
[ 6738, 7007, 1330, 651, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 2603, 29487, 8019, 13, 11227, 341, 355, 11034, 198, 11748, 4818, 8079, 355, 288, 83, 198, 198, 6738, 275, 1326, 21033, 1330, 347, 11682, ...
2.558824
170
from bootstrapvz.base import Task from bootstrapvz.common import phases from bootstrapvz.common.tasks import workspace import os import shutil assets = os.path.normpath(os.path.join(os.path.dirname(__file__), 'assets'))
[ 6738, 6297, 26418, 85, 89, 13, 8692, 1330, 15941, 198, 6738, 6297, 26418, 85, 89, 13, 11321, 1330, 21164, 198, 6738, 6297, 26418, 85, 89, 13, 11321, 13, 83, 6791, 1330, 44573, 198, 11748, 28686, 198, 11748, 4423, 346, 198, 198, 19668,...
3.040541
74
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import shutil import sys sys.path.insert(0, os.path.abspath('..')) # -- Project information ----------------------------------------------------- project = 'homelette' copyright = '2021, Philipp Junk, Christina Kiel' author = 'Philipp Junk, Christina Kiel' # -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'nbsphinx', 'sphinx_rtd_theme', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'sphinx_rtd_theme' html_logo = 'logo.png' html_theme_options = { 'logo_only': False, 'style_nav_header_background': '#000000', } # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". # html_static_path = ['_static'] # -- Options for LaTex output ------------------------------------------------ latex_elements = { 'preamble': r''' \setcounter{tocdepth}{1} \renewcommand{\hyperref}[2][]{#2} ''' } # -- Extension configuration: autodoc ---------------------------------------- autodoc_default_options = { 'member-order': 'bysource', } autoclass_content = 'class' autodoc_mock_imports = ['altmod', 'modeller', 'ost', 'promod3', 'qmean', 'pandas'] # -- Extension configuration: napoleon --------------------------------------- napoleon_use_ivar = True # -- Copy notebooks to include in the documentation -------------------------- notebooks = [ '../examples/Tutorial1_Basics.ipynb', '../examples/Tutorial2_Modelling.ipynb', '../examples/Tutorial3_Evaluation.ipynb', '../examples/Tutorial4_ExtendingHomelette.ipynb', '../examples/Tutorial5_Parallelization.ipynb', '../examples/Tutorial6_ComplexModelling.ipynb', '../examples/Tutorial7_AssemblingPipelines.ipynb', '../examples/Tutorial8_AlignmentGeneration.ipynb', ] for notebook in notebooks: if os.path.exists(notebook): shutil.copy(notebook, '.') # -- Copy logo --------------------------------------------------------------- if os.path.exists('../logo/logo.png'): shutil.copy('../logo/logo.png', '.')
[ 2, 28373, 2393, 329, 262, 45368, 28413, 10314, 27098, 13, 198, 2, 198, 2, 770, 2393, 691, 4909, 257, 6356, 286, 262, 749, 2219, 3689, 13, 1114, 257, 1336, 198, 2, 1351, 766, 262, 10314, 25, 198, 2, 3740, 1378, 2503, 13, 82, 746, ...
3.128801
1,118
# -*- coding: utf-8 -*- # # Copyright (c) 2019~2999 - Cologler <skyoflw@gmail.com> # ---------- # some object for parser # ---------- from typing import List import enum import dis from collections import defaultdict # instrs def add_instr(self, instr: dis.Instruction): ''' add a handled instruction in this state ''' self._instrs.append(instr) def get_instrs(self, key=None) -> List[dis.Instruction]: ''' get all instructions by key from this state ''' if key is None: return self._instrs.copy() else: return [i for i in self._instrs if i.opcode == key or i.opname == key] def copy(self): ''' copy a `CodeState` ''' state = CodeState() state._load_stack = self._load_stack.copy() state._ast_stack = self._ast_stack.copy() return state def copy_with_load(self, load_count): ''' copy a `CodeState` with empty ast stack. ''' state = CodeState() state._load_stack = self._load_stack[-load_count:] return state def push(self, node): ''' push a node into load stack. ''' self._load_stack.append(node) def pop(self): ''' pop the top node from load stack. ''' return self._load_stack.pop() def pop_seq(self, count: int) -> list: ''' pop a list of top nodes from load stack. ''' assert count >= 0 if count > 0: items = self._load_stack[-count:] self._load_stack = self._load_stack[0:-count] return items else: return [] def dup_top(self): ''' repeat top once. ''' self._load_stack.append(self._load_stack[-1]) def store(self, node): ''' store a node ''' self.add_node(node) def add_node(self, node): ''' add a final node into ast stmt tree ''' self._blocks[-1].append(node) def get_value(self) -> list: ''' get stmts from single block. ''' # ensure all status was handled assert not self._state, self._state assert not self._load_stack, self._load_stack # get value assert len(self._blocks) == 1, self._blocks return self._blocks[-1] def new_block(self): ''' make a new stmts block ''' self._blocks.append([]) def get_blocks(self) -> list: ''' get all stmts blocks. ''' # ensure all status was handled assert not self._state, self._state assert not self._load_stack, self._load_stack # get value return self._blocks def get_block_count(self) -> int: ''' get count of stmts blocks. ''' return len(self._blocks) class CodeReaderIter: __slots__ = ('_reader', '_condition') def fill_state(self, state: CodeState): ''' iter self into the `CodeState` and return it. ''' for instr in self: handler = get_instr_handler(instr) handler(self._reader, state, instr) state.add_instr(instr) return state def get_state(self, *, scope=Scope.NONE): ''' iter self into a new `CodeState`, return the `CodeState` ''' state = CodeState(scope=scope) return self.fill_state(state) def get_value(self, *, scope=Scope.NONE): ''' iter self into a new `CodeState`, return value from `CodeState`. ''' return self.get_state(scope=scope).get_value() def get_blocks(self, *, scope=Scope.NONE): ''' iter self into a new `CodeState`, return blocks from `CodeState`. ''' return self.get_state(scope=scope).get_blocks() _OPCODE_MAP = {} def get_instr_handler(instr): ''' the return function `(reader, state, instr) -> None` ''' k = (instr.opname, instr.opcode) try: return _OPCODE_MAP[k] except KeyError: raise NotImplementedError(k, instr)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 15069, 357, 66, 8, 13130, 93, 1959, 2079, 532, 327, 928, 1754, 1279, 15688, 1659, 75, 86, 31, 14816, 13, 785, 29, 198, 2, 24200, 438, 198, 2, 617, 2134,...
2.320642
1,681
from django import forms from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.utils.safestring import mark_safe from django.utils.translation import gettext as _ from dcim.models import DeviceRole, DeviceType, Platform, Region, Site, SiteGroup from tenancy.models import Tenant, TenantGroup from utilities.forms import ( add_blank_choice, APISelectMultiple, BootstrapMixin, BulkEditForm, BulkEditNullBooleanSelect, ColorSelect, CommentField, ContentTypeMultipleChoiceField, CSVModelForm, DateTimePicker, DynamicModelMultipleChoiceField, JSONField, SlugField, StaticSelect2, BOOLEAN_WITH_BLANK_CHOICES, ) from virtualization.models import Cluster, ClusterGroup from .choices import * from .models import ConfigContext, CustomField, ImageAttachment, JournalEntry, ObjectChange, Tag from .utils import FeatureQuery # # Custom fields # # # Tags # # # Config contexts # # # Filter form for local config context data # # # Image attachments # # # Journal entries # # # Change logging # # # Scripts #
[ 6738, 42625, 14208, 1330, 5107, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 11787, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 11299, 19199, 13, 27530, 1330, 14041, 6030, 198, 6738, 42625, 14208, 13, 26791, 13, 4...
3.396285
323
import torch import torch.nn as nn import torch.nn.functional as F from models.misc import modules constrain_path = { ('threeD', 'normal'): (True, True, ''), ('threeD', 'depth'): (True, True, ''), ('normal', 'depth'): (True, True, ''), ('depth', 'normal'): (True, True, ''), }
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 6738, 4981, 13, 44374, 1330, 13103, 198, 198, 1102, 2536, 391, 62, 6978, 796, 1391, 198, 220, 220, 220, 19203, 15542, 35...
2.619469
113
import configparser import os import hashlib import json import shutil import sys import tempfile import subprocess import tarfile import re import stat from functools import cmp_to_key from contextlib import closing from gzip import GzipFile from pathlib import Path from urllib.error import HTTPError from urllib.request import Request from urllib.request import urlopen WINDOWS = sys.platform == "win32" BOOTSTRAP = """\ import os, sys import re import subprocess def _which_python(): allowed_executables = ["python3", "python"] if sys.platform == 'win32': # in favor of 32 bit python to be compatible with the 32bit dlls of test libraries allowed_executables[:0] = ["py.exe -3-32", "py.exe -2-32", "py.exe -3-64", "py.exe -2-64"] # \d in regex ensures we can convert to int later version_matcher = re.compile(r"^Python (?P<major>\d+)\.(?P<minor>\d+)\..+$") fallback = None for executable in allowed_executables: try: raw_version = subprocess.check_output( executable + " --version", stderr=subprocess.STDOUT, shell=True ).decode("utf-8") except subprocess.CalledProcessError: continue match = version_matcher.match(raw_version.strip()) if match and tuple(map(int, match.groups())) >= (3, 0): # favor the first py3 executable we can find. return executable if fallback is None: # keep this one as the fallback; it was the first valid executable we found. fallback = executable if fallback is None: # Avoid breaking existing scripts fallback = "python" return fallback if __name__ == '__main__': py_executable = _which_python() subprocess.run(py_executable + r' {collie_bin} ' + ' '.join(sys.argv[1:]), shell=True) """ BIN = """#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import argparse lib = os.path.normpath(os.path.join(os.path.realpath(__file__), "..", "..", "lib", "collie")) sys.path.insert(0, lib) from test_endpoint.app import main if __name__ == "__main__": sys.exit(main()) """ BAT = '@echo off\r\n{python_executable} "{collie_bootstrap}" %*\r\n' SH = '#!/bin/sh\npython3 "{collie_bootstrap}" $*\n' def expanduser(path): """ Expand ~ and ~user constructions. Includes a workaround for http://bugs.python.org/issue14768 """ expanded = os.path.expanduser(path) if path.startswith("~/") and expanded.startswith("//"): expanded = expanded[1:] return expanded def _which_python(self): """ Decides which python executable we'll embed in the launcher script. """ allowed_executables = ["python", "python3"] if WINDOWS: allowed_executables += ["py.exe -3", "py.exe -2"] # \d in regex ensures we can convert to int later version_matcher = re.compile(r"^Python (?P<major>\d+)\.(?P<minor>\d+)\..+$") fallback = None for executable in allowed_executables: try: raw_version = subprocess.check_output( executable + " --version", stderr=subprocess.STDOUT, shell=True ).decode("utf-8") except subprocess.CalledProcessError: continue match = version_matcher.match(raw_version.strip()) if match and tuple(map(int, match.groups())) >= (3, 0): # favor the first py3 executable we can find. return executable if fallback is None: # keep this one as the fallback; it was the first valid executable we found. fallback = executable if fallback is None: # Avoid breaking existing scripts fallback = "python" return fallback
[ 11748, 4566, 48610, 198, 11748, 28686, 198, 11748, 12234, 8019, 198, 11748, 33918, 198, 11748, 4423, 346, 198, 11748, 25064, 198, 11748, 20218, 7753, 198, 11748, 850, 14681, 198, 11748, 13422, 7753, 198, 11748, 302, 198, 11748, 1185, 198, ...
2.406662
1,591
""" Query BGP neighbor table on a Juniper network device. """ import sys from jnpr.junos import Device from jnpr.junos.factory import loadyaml def juniper_bgp_state(dev, bgp_neighbor): """ This function queries the BGP neighbor table on a Juniper network device. dev = Juniper device connection bgp_neighbor = IP address of BGP neighbor return = Returns state of BGP neighbor """ try: globals().update(loadyaml('yaml/bgp_neighbor.yml')) bgp_ni = bgp_neighbor_info(dev).get(neighbor_address=bgp_neighbor) return bgp_ni except Exception as err: print(err) dev.close() sys.exit(1) return return
[ 37811, 198, 20746, 347, 16960, 4780, 3084, 319, 257, 7653, 9346, 3127, 3335, 13, 198, 37811, 198, 198, 11748, 25064, 198, 6738, 474, 77, 1050, 13, 29741, 418, 1330, 16232, 198, 6738, 474, 77, 1050, 13, 29741, 418, 13, 69, 9548, 1330, ...
2.429577
284
import cherrypy from cherrypy.test import helper
[ 11748, 23612, 9078, 198, 6738, 23612, 9078, 13, 9288, 1330, 31904, 628, 198 ]
3.923077
13
#!/usr/bin/env python from typing import List import aoc from collections import defaultdict with open('test2.txt', 'r') as f: inp = f.read() print("Part 1:", solve(inp)) print("Part 2:", solve(inp, True)) with open('input.txt', 'r') as f: inp = f.read() print("Part 1:", solve(inp)) print("Part 2:", solve(inp, True))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 19720, 1330, 7343, 198, 11748, 257, 420, 198, 6738, 17268, 1330, 4277, 11600, 628, 628, 198, 4480, 1280, 10786, 9288, 17, 13, 14116, 3256, 705, 81, 11537, 355, 277, 25, 198,...
2.440559
143
import numpy as np from ltr.data import transforms import ltr.data.processing_utils as prutils from pytracking.libs import TensorDict
[ 11748, 299, 32152, 355, 45941, 201, 198, 201, 198, 6738, 300, 2213, 13, 7890, 1330, 31408, 201, 198, 11748, 300, 2213, 13, 7890, 13, 36948, 62, 26791, 355, 778, 26791, 201, 198, 6738, 12972, 36280, 13, 8019, 82, 1330, 309, 22854, 35, ...
2.862745
51
import logging from os.path import expanduser #TQ_API_ROOT_URL = 'http://127.0.1.1:8090/dataset' TQ_API_ROOT_URL = 'http://elb-tranquant-ecs-cluster-tqapi-1919110681.us-west-2.elb.amazonaws.com/dataset' LOG_PATH = expanduser('~/tqcli.log') # the chunk size must be at least 5MB for multipart upload DEFAULT_CHUNK_SIZE = 1024 * 1024 * 5 # 5MB logging.basicConfig( level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', filename=LOG_PATH, filemode='w' ) # define a Handler which writes INFO messages or higher to the sys.stderr console = logging.StreamHandler() console.setLevel(logging.INFO) # set a format which is simpler for console use formatter = logging.Formatter('%(message)s') # tell the handler to use this format console.setFormatter(formatter) # add the handler to the root logger logging.getLogger('').addHandler(console)
[ 11748, 18931, 198, 6738, 28686, 13, 6978, 1330, 4292, 7220, 198, 198, 2, 51, 48, 62, 17614, 62, 13252, 2394, 62, 21886, 796, 705, 4023, 1378, 16799, 13, 15, 13, 16, 13, 16, 25, 1795, 3829, 14, 19608, 292, 316, 6, 198, 51, 48, 62...
2.711656
326
from abc import ABC, abstractmethod import os import numpy as np import torch from torch.utils.tensorboard import SummaryWriter from fqf_iqn_qrdqn.memory import LazyMultiStepMemory, \ LazyPrioritizedMultiStepMemory from fqf_iqn_qrdqn.utils import RunningMeanStats, LinearAnneaer
[ 6738, 450, 66, 1330, 9738, 11, 12531, 24396, 198, 11748, 28686, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 6738, 28034, 13, 26791, 13, 83, 22854, 3526, 1330, 21293, 34379, 198, 198, 6738, 277, 80, 69, 62, 25011, 77, 6...
3.097826
92
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. from typing import List, Pattern from recognizers_text.utilities import RegExpUtility from recognizers_text.extractor import Extractor from recognizers_number.number.italian.extractors import ItalianIntegerExtractor from ...resources.italian_date_time import ItalianDateTime from ..extractors import DateTimeExtractor from ..base_timeperiod import TimePeriodExtractorConfiguration, MatchedIndex from ..base_time import BaseTimeExtractor from ..base_timezone import BaseTimeZoneExtractor from .time_extractor_config import ItalianTimeExtractorConfiguration from .base_configs import ItalianDateTimeUtilityConfiguration from .timezone_extractor_config import ItalianTimeZoneExtractorConfiguration
[ 2, 220, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 220, 49962, 739, 262, 17168, 13789, 13, 198, 198, 6738, 19720, 1330, 7343, 11, 23939, 198, 198, 6738, 3018, 11341, 62, 5239, 13, 315, 2410, 1330, 3310, 16870...
4.135417
192
#quartet_condor.py #version 2.0.2 import random, sys def addToDict(d): ''' Ensures each quartet has three concordance factors (CFs) a dictionary d has less than three CFs, add CFs with the value 0 until there are three Input: a dictionary containing CFs, a counter of how many CFs are in the dictionary ''' if ("{1,2|3,4}" not in d): d["{1,2|3,4}"] = 0.0 if ("{1,3|2,4}" not in d): d["{1,3|2,4}"] = 0.0 if ("{1,4|2,3}" not in d): d["{1,4|2,3}"] = 0.0
[ 2, 36008, 316, 62, 17561, 273, 13, 9078, 198, 2, 9641, 362, 13, 15, 13, 17, 198, 198, 11748, 4738, 11, 25064, 628, 198, 4299, 751, 2514, 35, 713, 7, 67, 2599, 198, 220, 220, 220, 705, 7061, 198, 220, 220, 220, 48221, 942, 1123, ...
2.11157
242
from django import forms from models import UserInputModel
[ 6738, 42625, 14208, 1330, 5107, 198, 6738, 4981, 1330, 11787, 20560, 17633, 198 ]
4.538462
13
from pathlib import Path import pytest from oval_graph.arf_xml_parser.arf_xml_parser import ARFXMLParser
[ 6738, 3108, 8019, 1330, 10644, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 41186, 62, 34960, 13, 37595, 62, 19875, 62, 48610, 13, 37595, 62, 19875, 62, 48610, 1330, 5923, 17213, 5805, 46677, 628, 628, 628 ]
3.111111
36
import os import logging import argparse import sys import signal import subprocess from functools import wraps from dotenv import load_dotenv load_dotenv(verbose=True) from app.config import configure_app from app.bot import TrumpBotScheduler from app.sentimentbot import SentimentBot parser = argparse.ArgumentParser(description=r""" """) ROOT = os.getcwd() PID_FILE_PATH = os.path.join(ROOT, 'var/run-dev.pid') CMDS = [] FNCS = [] try: os.setpgrp() if not os.path.exists(os.path.dirname(PID_FILE_PATH)): os.makedirs(os.path.dirname(PID_FILE_PATH)) with open(PID_FILE_PATH, 'w+') as file: file.write(str(os.getpgrp()) + '\n') except Exception as e: logging.error(e) def _start_flask_server(*args, **kwargs): from app import app logging.info('Starting the flask server...') level = os.environ.get('CONFIG_LEVEL') configure_app(app, status='production' if level is None else level) port = app.config.get('PORT') app.run(host='0.0.0.0', port=port) def _start_dev_server(*args, **kwargs): _start_client_server() FNCS.append(_start_flask_server) def _start_prod_server(*args, **kwargs): _start_trump_bot(*args, **kwargs) _start_flask_server(*args, **kwargs) def _start_trump_bot(send_posts=True, start_sentiment_bot=False, *args, **kwargs): logging.info('Starting the trump bot...') # requests_path = os.environ.get('REQUESTS_FILE_PATH', 'requests/request.json') # auth_path = os.environ.get('AUTH_FILE_PATH', 'requests/auth.json') # _file_path_sanity_check(requests_path, auth_path) bot = _initialize_trump_bot(send_posts=send_posts) if not start_sentiment_bot: _start_sentiment_bot(trump_bot=bot, send_posts=send_posts) bot.start() ACTIONS = { "initialize": _initialize_trump_bot, "client": _start_client_server, "trumpbot": _start_trump_bot, "flask": _start_flask_server, "dev": _start_dev_server, "prod": _start_prod_server, } parser.add_argument('action', help='start the Flask app', type=str, choices=[key for key, v in ACTIONS.items()]) parser.add_argument('-np', '--no-post', dest='send_posts', action='store_true', help='Do not send post requests') parser.add_argument('-nsb', '--no-sentiment-bot', dest='start_sentiment_bot', action='store_true', help='Do not to start the sentiment bot') if __name__ == "__main__": logging.basicConfig(level=logging.INFO) main()
[ 11748, 28686, 198, 11748, 18931, 198, 11748, 1822, 29572, 198, 11748, 25064, 198, 11748, 6737, 198, 11748, 850, 14681, 198, 6738, 1257, 310, 10141, 1330, 27521, 198, 198, 6738, 16605, 24330, 1330, 3440, 62, 26518, 24330, 198, 2220, 62, 26...
2.315141
1,136
#! /usr/bin/env python3 import itertools import typing as tp if __name__ == '__main__': main()
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 340, 861, 10141, 198, 11748, 19720, 355, 256, 79, 628, 628, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1388, 3419, 198 ...
2.465116
43
from setuptools import setup, Extension, find_packages import subprocess import errno import re import os import shutil import sys import zipfile from urllib.request import urlretrieve import numpy from Cython.Build import cythonize isWindows = os.name == 'nt' isMac = sys.platform == 'darwin' is64Bit = sys.maxsize > 2**32 # adapted from cffi's setup.py # the following may be overridden if pkg-config exists libraries = ['lensfun'] include_dirs = [] library_dirs = [] extra_compile_args = [] extra_link_args = [] if isWindows or isMac: cmake_build = os.path.abspath('external/lensfun/build') install_dir = os.path.join(cmake_build, 'install') include_dirs += [os.path.join(install_dir, 'include', 'lensfun')] library_dirs += [os.path.join(install_dir, 'lib')] else: use_pkg_config() # this must be after use_pkg_config()! include_dirs += [numpy.get_include()] # for version_helper.h include_dirs += [os.path.abspath('lensfunpy')] package_data = {'lensfunpy': []} # evil hack, check cmd line for relevant commands # custom cmdclasses didn't work out in this case cmdline = ''.join(sys.argv[1:]) needsCompile = any(s in cmdline for s in ['install', 'bdist', 'build_ext', 'wheel', 'nosetests']) if isWindows and needsCompile: windows_lensfun_compile() package_data['lensfunpy'].append('*.dll') elif isMac and needsCompile: mac_lensfun_compile() if any(s in cmdline for s in ['clean', 'sdist']): # When running sdist after a previous run of bdist or build_ext # then even with the 'clean' command the .egg-info folder stays. # This folder contains SOURCES.txt which in turn is used by sdist # to include package data files, but we don't want .dll's and .xml # files in our source distribution. Therefore, to prevent accidents, # we help a little... egg_info = 'lensfunpy.egg-info' print('removing', egg_info) shutil.rmtree(egg_info, ignore_errors=True) if 'sdist' not in cmdline: # This assumes that the lensfun version from external/lensfun was used. # If that's not the case, the bundled files may fail to load, for example, # if lensfunpy was linked against an older lensfun version already on # the system (Linux mostly) and the database format changed in an incompatible way. # In that case, loading of bundled files can still be disabled # with Database(load_bundled=False). package_data['lensfunpy'].append('db_files/*.xml') bundle_db_files() # Support for optional Cython line tracing # run the following to generate a test coverage report: # $ export LINETRACE=1 # $ python setup.py build_ext --inplace # $ nosetests --with-coverage --cover-html --cover-package=lensfunpy compdirectives = {} macros = [] if (os.environ.get('LINETRACE', False)): compdirectives['linetrace'] = True macros.append(('CYTHON_TRACE', '1')) extensions = cythonize([Extension("lensfunpy._lensfun", include_dirs=include_dirs, sources=[os.path.join('lensfunpy', '_lensfun.pyx')], libraries=libraries, library_dirs=library_dirs, extra_compile_args=extra_compile_args, extra_link_args=extra_link_args, define_macros=macros )], compiler_directives=compdirectives) # make __version__ available (https://stackoverflow.com/a/16084844) exec(open('lensfunpy/_version.py').read()) setup( name = 'lensfunpy', version = __version__, description = 'Lens distortion correction for Python, a wrapper for lensfun', long_description = open('README.rst').read(), author = 'Maik Riechert', author_email = 'maik.riechert@arcor.de', url = 'https://github.com/letmaik/lensfunpy', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Cython', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Operating System :: MacOS', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Operating System :: Unix', 'Topic :: Multimedia :: Graphics', 'Topic :: Software Development :: Libraries', ], packages = find_packages(), ext_modules = extensions, package_data = package_data, install_requires=['numpy'] )
[ 6738, 900, 37623, 10141, 1330, 9058, 11, 27995, 11, 1064, 62, 43789, 198, 11748, 850, 14681, 198, 11748, 11454, 3919, 198, 11748, 302, 198, 11748, 28686, 198, 11748, 4423, 346, 198, 11748, 25064, 198, 11748, 19974, 7753, 198, 6738, 2956, ...
2.646625
1,763
"The mailtools Utility Package" 'Initialization File' """ ################################################################################## mailtools package: interface to mail server transfers, used by pymail2, PyMailGUI, and PyMailCGI; does loads, sends, parsing, composing, and deleting, with part attachments, encodings (of both the email and Unicdode kind), etc.; the parser, fetcher, and sender classes here are designed to be mixed-in to subclasses which use their methods, or used as embedded or standalone objects; this package also includes convenience subclasses for silent mode, and more; loads all mail text if pop server doesn't do top; doesn't handle threads or UI here, and allows askPassword to differ per subclass; progress callback funcs get status; all calls raise exceptions on error--client must handle in GUI/other; this changed from file to package: nested modules imported here for bw compat; 4E: need to use package-relative import syntax throughout, because in Py 3.X package dir in no longer on module import search path if package is imported elsewhere (from another directory which uses this package); also performs Unicode decoding on mail text when fetched (see mailFetcher), as well as for some text part payloads which might have been email-encoded (see mailParser); TBD: in saveparts, should file be opened in text mode for text/ contypes? TBD: in walkNamedParts, should we skip oddballs like message/delivery-status? TBD: Unicode support has not been tested exhaustively: see Chapter 13 for more on the Py3.1 email package and its limitations, and the policies used here; ################################################################################## """ # collect contents of all modules here, when package dir imported directly from .mailFetcher import * from .mailSender import * # 4E: package-relative from .mailParser import * # export nested modules here, when from mailtools import * __all__ = 'mailFetcher', 'mailSender', 'mailParser' # self-test code is in selftest.py to allow mailconfig's path # to be set before running thr nested module imports above
[ 1, 464, 6920, 31391, 34030, 15717, 1, 198, 6, 24243, 1634, 9220, 6, 628, 198, 37811, 198, 29113, 29113, 14468, 2235, 198, 4529, 31391, 5301, 25, 7071, 284, 6920, 4382, 16395, 11, 973, 416, 12972, 4529, 17, 11, 9485, 25804, 40156, 11, ...
4.045283
530
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 8 15:25:03 2018 @author: bathmann """ from .BelowgroundCompetition import BelowgroundCompetition from .SimpleTest import SimpleTest from .FON import FON from .OGSWithoutFeedback import OGSWithoutFeedback from .OGSLargeScale3D import OGSLargeScale3D from .OGS.helpers import CellInformation from .FixedSalinity import FixedSalinity
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 26223, 5267, 220, 807, 1315, 25, 1495, 25, 3070, 2864, 198, 198, 31, 9800, 25, 7837, 9038...
3.15625
128
from flask import Flask, render_template from flask_socketio import SocketIO, send, emit app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app) if __name__ == '__main__': socketio.run(app)
[ 6738, 42903, 1330, 46947, 11, 8543, 62, 28243, 198, 6738, 42903, 62, 44971, 952, 1330, 47068, 9399, 11, 3758, 11, 27588, 198, 198, 1324, 796, 46947, 7, 834, 3672, 834, 8, 198, 1324, 13, 11250, 17816, 23683, 26087, 62, 20373, 20520, 79...
2.896104
77
""" Post processing on detected objects """ import pymongo from pymongo import MongoClient import time import logging logging.basicConfig(format='%(levelname)s :: %(asctime)s :: %(message)s', level=logging.DEBUG) from joblib import Parallel, delayed import click from xgboost_model.inference import run_inference, PostprocessException import os if __name__ == '__main__': click_wrapper()
[ 37811, 198, 6307, 7587, 319, 12326, 5563, 198, 37811, 198, 11748, 279, 4948, 25162, 198, 6738, 279, 4948, 25162, 1330, 42591, 11792, 198, 11748, 640, 198, 11748, 18931, 198, 6404, 2667, 13, 35487, 16934, 7, 18982, 11639, 4, 7, 5715, 367...
3.34188
117
""" Copyright (C) 2018-2021 Intel Corporation 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 unittest import numpy as np from mo.front.common.partial_infer.multi_box_prior import multi_box_prior_infer_mxnet from mo.graph.graph import Node from mo.utils.unittest.graph import build_graph nodes_attributes = {'node_1': {'value': None, 'kind': 'data'}, 'node_2': {'value': None, 'kind': 'data'}, 'prior_box_1': {'type': 'PriorBox', 'kind': 'op'}, 'node_3': {'type': 'Identity', 'value': None, 'kind': 'data'} }
[ 37811, 198, 15069, 357, 34, 8, 2864, 12, 1238, 2481, 8180, 10501, 628, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 1...
2.824289
387
#!/usr/bin/env python ############################################################################ # Copyright (C) 2009, Willow Garage, Inc. # # Copyright (C) 2013 by Ralf Kaestner # # ralf.kaestner@gmail.com # # Copyright (C) 2013 by Jerome Maye # # jerome.maye@mavt.ethz.ch # # # # All rights reserved. # # # # Redistribution and use in source and binary forms, with or without # # modification, are permitted provided that the following conditions # # are met: # # # # 1. Redistributions of source code must retain the above copyright # # notice, this list of conditions and the following disclaimer. # # # # 2. Redistributions in binary form must reproduce the above copyright # # notice, this list of conditions and the following disclaimer in # # the documentation and/or other materials provided with the # # distribution. # # # # 3. The name of the copyright holders may be used to endorse or # # promote products derived from this software without specific # # prior written permission. # # # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # # POSSIBILITY OF SUCH DAMAGE. # ############################################################################ from __future__ import with_statement import rospy import traceback import threading from threading import Timer import sys, os, time from time import sleep import subprocess import string import socket from diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus, KeyValue mem_level_warn = 0.95 mem_level_error = 0.99 stat_dict = { 0: 'OK', 1: 'Warning', 2: 'Error' } if __name__ == '__main__': hostname = socket.gethostname() hostname = hostname.replace('-', '_') import optparse parser = optparse.OptionParser(usage="usage: mem_monitor.py [--diag-hostname=cX]") parser.add_option("--diag-hostname", dest="diag_hostname", help="Computer name in diagnostics output (ex: 'c1')", metavar="DIAG_HOSTNAME", action="store", default = hostname) options, args = parser.parse_args(rospy.myargv()) try: rospy.init_node('mem_monitor_%s' % hostname) except rospy.exceptions.ROSInitException: print >> sys.stderr, 'Memory monitor is unable to initialize node. Master may not be running.' sys.exit(0) mem_node = MemMonitor(hostname, options.diag_hostname) rate = rospy.Rate(1.0) try: while not rospy.is_shutdown(): rate.sleep() mem_node.publish_stats() except KeyboardInterrupt: pass except Exception, e: traceback.print_exc() rospy.logerr(traceback.format_exc()) mem_node.cancel_timers() sys.exit(0)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 29113, 29113, 7804, 4242, 198, 2, 220, 220, 220, 15069, 357, 34, 8, 3717, 11, 33021, 45502, 11, 3457, 13, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220,...
2.000896
2,232
#!/usr/bin/env python3 import argparse import os import subprocess parser = argparse.ArgumentParser(description='Produce a dep file from ninja.') parser.add_argument( '--build-dir', help='The build directory.', required=True) parser.add_argument( '--base-dir', help='The directory for which dependencies are rewriten.', required=True) parser.add_argument('--ninja', help='The ninja executable to use.') parser.add_argument( 'base_target', help="The target from the base's perspective.") parser.add_argument( 'targets', nargs='+', help='The target for which dependencies are extracted.') parser.add_argument( '--extra-deps', nargs='+', help='Extra dependencies.') args = parser.parse_args() build_dir = os.path.abspath(args.build_dir) base_dir = os.path.abspath(args.base_dir) ninja = args.ninja base_target = args.base_target targets = args.targets extra_deps = args.extra_deps # Make sure we operate in the right folder. os.chdir(build_dir) if ninja is None: ninja = subprocess.check_output(['command', '-v', 'ninja'])[:-1] # Construct the set of all targets all_targets = set() doto_targets = set() for t in subprocess.check_output([ninja, '-t', 'targets', 'all']).splitlines(): t, r = t.split(b':') all_targets.add(t) if r[:13] == b' C_COMPILER__' or r[:15] == b' CXX_COMPILER__': doto_targets.add(t) base_dir = base_dir.encode() deps = extract_deps(set(targets)) deps = rebase_deps(deps) # Collapse everything under the base target. basedeps = set() if extra_deps is None else set(d.encode() for d in extra_deps) for d in deps.values(): basedeps.update(d) base_target = base_target.encode() basedeps.discard(base_target) dump({base_target: basedeps})
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 1822, 29572, 198, 11748, 28686, 198, 11748, 850, 14681, 198, 198, 48610, 796, 1822, 29572, 13, 28100, 1713, 46677, 7, 11213, 11639, 11547, 344, 257, 1207, 2393, 422, 3704...
2.602679
672
''' Created on 2011-6-22 @author: dholer '''
[ 7061, 6, 198, 41972, 319, 2813, 12, 21, 12, 1828, 198, 198, 31, 9800, 25, 288, 3937, 263, 198, 7061, 6, 198 ]
2.090909
22
"""Tests for the `sendoff` library.""" """ The `sendoff` library tests validate the expected function of the library. """
[ 37811, 51, 3558, 329, 262, 4600, 21280, 2364, 63, 5888, 526, 15931, 198, 37811, 198, 464, 4600, 21280, 2364, 63, 5888, 5254, 26571, 262, 2938, 2163, 286, 262, 5888, 13, 198, 37811, 198 ]
3.69697
33
# # Copyright (c) 2018-2019 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # from sysinv.common import constants from sysinv.common import exception from sysinv.common import utils from sysinv.helm import common from sysinv.helm import base
[ 2, 198, 2, 15069, 357, 66, 8, 2864, 12, 23344, 3086, 5866, 11998, 11, 3457, 13, 198, 2, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 198, 2, 198, 198, 6738, 25064, 16340, 13, 11321, 1330, 38491, 198,...
3.346154
78
#!/usr/bin/env python """Generate frame counts dict for a dataset. Usage: frame_counter.py [options] Options: -h, --help Print help message --root=<str> Path to root of dataset (should contain video folders that contain images) [default: /vision/vision_users/azou/data/hmdb51_flow/u/] --output=<str> Output filename [default: hmdb_frame_count.pickle] """ from __future__ import print_function from docopt import docopt import os import sys import pickle if __name__ == '__main__': args = docopt(__doc__) print(args) # Final counts counts = {} min_count = sys.maxint # Generate list of video folders for root, dirs, files in os.walk(args['--root']): # Skip the root directory if len(dirs) != 0: continue # Process a directory and frame count into a dictionary entry name = os.path.basename(os.path.normpath(root)) print('{}: {} frames'.format(name, len(files))) counts[name] = len(files) # Track minimum count if len(files) < min_count: min_count = len(files) with open(args['--output'], 'wb') as ofile: pickle.dump(counts, ofile) print('Minimum frame count = {}'.format(min_count))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 8645, 378, 5739, 9853, 8633, 329, 257, 27039, 13, 198, 198, 28350, 25, 198, 220, 220, 220, 5739, 62, 24588, 13, 9078, 685, 25811, 60, 198, 198, 29046, 25, 198, 220, 220, 220, ...
2.447419
523
total = 0 for n in range(1000, 1000000): suma = 0 for i in str(n): suma += int(i)**5 if (n == suma): total += n print(total)
[ 23350, 796, 657, 198, 198, 1640, 299, 287, 2837, 7, 12825, 11, 1802, 2388, 2599, 198, 220, 220, 220, 2160, 64, 796, 657, 198, 220, 220, 220, 329, 1312, 287, 965, 7, 77, 2599, 198, 220, 220, 220, 220, 220, 220, 220, 2160, 64, 158...
1.962025
79
"""Settings for generic fuel cycle code.""" import re import os from armi.settings import setting from armi.operators import settingsValidation CONF_ASSEMBLY_ROTATION_ALG = "assemblyRotationAlgorithm" CONF_ASSEM_ROTATION_STATIONARY = "assemblyRotationStationary" CONF_CIRCULAR_RING_MODE = "circularRingMode" CONF_CIRCULAR_RING_ORDER = "circularRingOrder" CONF_CUSTOM_FUEL_MANAGEMENT_INDEX = "customFuelManagementIndex" CONF_RUN_LATTICE_BEFORE_SHUFFLING = "runLatticePhysicsBeforeShuffling" CONF_SHUFFLE_LOGIC = "shuffleLogic" CONF_PLOT_SHUFFLE_ARROWS = "plotShuffleArrows" CONF_FUEL_HANDLER_NAME = "fuelHandlerName" CONF_JUMP_RING_NUM = "jumpRingNum" CONF_LEVELS_PER_CASCADE = "levelsPerCascade" def getFuelCycleSettings(): """Define settings for fuel cycle.""" settings = [ setting.Setting( CONF_ASSEMBLY_ROTATION_ALG, default="", label="Assembly Rotation Algorithm", description="The algorithm to use to rotate the detail assemblies while shuffling", options=["", "buReducingAssemblyRotation", "simpleAssemblyRotation"], enforcedOptions=True, ), setting.Setting( CONF_ASSEM_ROTATION_STATIONARY, default=False, label="Rotate stationary assems", description=( "Whether or not to rotate assemblies that are not shuffled." "This can only be True if 'rotation' is true." ), ), setting.Setting( CONF_CIRCULAR_RING_MODE, default=False, description="Toggle between circular ring definitions to hexagonal ring definitions", label="Use Circular Rings", ), setting.Setting( CONF_CIRCULAR_RING_ORDER, default="angle", description="Order by which locations are sorted in circular rings for equilibrium shuffling", label="Eq. circular sort type", options=["angle", "distance", "distanceSmart"], ), setting.Setting( CONF_CUSTOM_FUEL_MANAGEMENT_INDEX, default=0, description=( "An index that determines which of various options is used in management. " "Useful for optimization sweeps. " ), label="Custom Shuffling Index", ), setting.Setting( CONF_RUN_LATTICE_BEFORE_SHUFFLING, default=False, description=( "Forces the Generation of Cross Sections Prior to Shuffling the Fuel Assemblies. " "Note: This is recommended when performing equilibrium shuffling branching searches." ), label="Generate XS Prior to Fuel Shuffling", ), setting.Setting( CONF_SHUFFLE_LOGIC, default="", label="Shuffle Logic", description=( "Python script written to handle the fuel shuffling for this case. " "This is user-defined per run as a dynamic input." ), # schema here could check if file exists, but this is a bit constraining in testing. # For example, some tests have relative paths for this but aren't running in # the right directory, and IsFile doesn't seem to work well with relative paths. # This is left here as an FYI about how we could check existence of files if we get # around these problem. # schema=vol.All( # vol.IsFile(), # pylint: disable=no-value-for-parameter # msg="Shuffle logic input must be an existing file", # ), ), setting.Setting( CONF_FUEL_HANDLER_NAME, default="", label="Fuel Handler Name", description="The name of the FuelHandler class in the shuffle logic module to activate", ), setting.Setting( CONF_PLOT_SHUFFLE_ARROWS, default=False, description="Make plots with arrows showing each move.", label="Plot shuffle arrows", ), setting.Setting( CONF_JUMP_RING_NUM, default=8, label="Jump Ring Number", description="None" ), setting.Setting( CONF_LEVELS_PER_CASCADE, default=14, label="Move per cascade", description="None", ), ] return settings
[ 37811, 26232, 329, 14276, 5252, 6772, 2438, 526, 15931, 198, 11748, 302, 198, 11748, 28686, 198, 198, 6738, 3211, 72, 13, 33692, 1330, 4634, 198, 6738, 3211, 72, 13, 3575, 2024, 1330, 6460, 7762, 24765, 198, 198, 10943, 37, 62, 10705, ...
2.199611
2,059
from nltk.corpus import gutenberg from nltk import ConditionalFreqDist from random import choice #create the distribution object cfd = ConditionalFreqDist() ## for each token count the current word given the previous word prev_word = None for word in gutenberg.words('austen-persuasion.txt'): cfd[prev_word][word] += 1 prev_word = word ## start predicting at given word, say "therefore" word = "therefore" i = 1 ## find all words that can follow the given word and choose one at random while i<20: print word, lwords = cfd.get(word).keys() follower = choice(lwords) word = follower i += 1
[ 198, 6738, 299, 2528, 74, 13, 10215, 79, 385, 1330, 308, 19028, 198, 6738, 299, 2528, 74, 1330, 9724, 1859, 20366, 80, 20344, 198, 6738, 4738, 1330, 3572, 198, 198, 2, 17953, 262, 6082, 2134, 198, 12993, 67, 796, 9724, 1859, 20366, ...
2.976303
211
#!/usr/bin/env python # Copyright (c) 2016 The Johns Hopkins University/Applied Physics Laboratory # All Rights Reserved. # # 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 logging # noqa: E402 logging.basicConfig(level=logging.DEBUG) from kmip.services.server import server # noqa: E402 if __name__ == '__main__': print('Starting PyKMIP server on 0.0.0.0:5696') server.main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 15069, 357, 66, 8, 1584, 383, 25824, 21183, 2059, 14, 4677, 18511, 23123, 18643, 198, 2, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362,...
3.421456
261
# # test_tempo_event.py # crest-python # # Copyright (C) 2017 Rue Yokaze # Distributed under the MIT License. # import crest_loader import unittest from crest.events.meta import TempoEvent if (__name__ == '__main__'): unittest.main()
[ 2, 198, 2, 220, 220, 1332, 62, 11498, 7501, 62, 15596, 13, 9078, 198, 2, 220, 220, 36893, 12, 29412, 198, 2, 198, 2, 220, 220, 15069, 357, 34, 8, 2177, 45363, 45138, 6201, 198, 2, 220, 220, 4307, 6169, 739, 262, 17168, 13789, 13...
2.648936
94
# Copyright 2020 The TensorFlow Quantum Authors. All Rights Reserved. # # 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. # ============================================================================== """Module functions for tfq.differentiators.*""" from tensorflow_quantum.python.differentiators.adjoint import ( Adjoint,) from tensorflow_quantum.python.differentiators.linear_combination import ( ForwardDifference, CentralDifference, LinearCombination, ) from tensorflow_quantum.python.differentiators.parameter_shift import ( ParameterShift,) from tensorflow_quantum.python.differentiators.differentiator import ( Differentiator,)
[ 2, 15069, 12131, 383, 309, 22854, 37535, 29082, 46665, 13, 1439, 6923, 33876, 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, 287,...
3.762987
308
import unittest import numpy.testing as testing import numpy as np import fitsio import tempfile import os from redmapper import ColorBackground from redmapper import ColorBackgroundGenerator from redmapper import Configuration if __name__=='__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 11748, 299, 32152, 13, 33407, 355, 4856, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 11414, 952, 198, 11748, 20218, 7753, 198, 11748, 28686, 198, 198, 6738, 2266, 76, 11463, 1330, 5315, 21756, 198, 6738, 2...
3.525641
78
# Copyright (c) 2008,2015,2016,2017,2018,2019 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Contains a collection of basic calculations. These include: * wind components * heat index * windchill """ import warnings import numpy as np from scipy.ndimage import gaussian_filter from .. import constants as mpconsts from ..package_tools import Exporter from ..units import atleast_1d, check_units, masked_array, units from ..xarray import preprocess_xarray exporter = Exporter(globals()) # The following variables are constants for a standard atmosphere t0 = 288. * units.kelvin p0 = 1013.25 * units.hPa def _check_radians(value, max_radians=2 * np.pi): """Input validation of values that could be in degrees instead of radians. Parameters ---------- value : `pint.Quantity` The input value to check. max_radians : float Maximum absolute value of radians before warning. Returns ------- `pint.Quantity` The input value """ try: value = value.to('radians').m except AttributeError: pass if np.greater(np.nanmax(np.abs(value)), max_radians): warnings.warn('Input over {} radians. ' 'Ensure proper units are given.'.format(max_radians)) return value
[ 2, 15069, 357, 66, 8, 3648, 11, 4626, 11, 5304, 11, 5539, 11, 7908, 11, 23344, 3395, 20519, 34152, 13, 198, 2, 4307, 6169, 739, 262, 2846, 286, 262, 347, 10305, 513, 12, 2601, 682, 13789, 13, 198, 2, 30628, 55, 12, 34156, 12, 33...
2.795918
490
from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework.reverse import reverse from rest_framework_simplejwt.tokens import RefreshToken
[ 6738, 1334, 62, 30604, 13, 26209, 1330, 18261, 198, 6738, 1334, 62, 30604, 13, 12501, 273, 2024, 1330, 40391, 62, 1177, 198, 6738, 1334, 62, 30604, 13, 50188, 1330, 9575, 198, 6738, 1334, 62, 30604, 62, 36439, 73, 46569, 13, 83, 482, ...
4.020408
49
from rest_framework import serializers from .models import Post, Comment, Like from django.contrib.auth.models import User
[ 6738, 1334, 62, 30604, 1330, 11389, 11341, 198, 6738, 764, 27530, 1330, 2947, 11, 18957, 11, 4525, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 11787, 628, 628, 220, 220, 220, 220, 628 ]
3.567568
37
from ..embeddings.base import Embeddings from flair.data import Sentence
[ 6738, 11485, 20521, 67, 654, 13, 8692, 1330, 13302, 6048, 654, 198, 198, 6738, 37457, 13, 7890, 1330, 11352, 594, 628 ]
3.571429
21
# !/usr/local/bin/python # -*- coding:utf-8 -*- import YunBi import CNBTC import json import threading import Queue import time import logging import numpy import message import random open_platform = [True,True,True,True] numpy.set_printoptions(suppress=True) # logging.basicConfig(level=logging.DEBUG, # format="[%(asctime)20s] [%(levelname)8s] %(filename)10s:%(lineno)-5s --- %(message)s", # datefmt="%Y-%m-%d %H:%M:%S", # filename="log/%s.log"%time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())), # filemode='w') # console = logging.StreamHandler() # console.setLevel(logging.INFO) # formatter = logging.Formatter("[%(asctime)20s] [%(levelname)8s] %(filename)10s:%(lineno)-5s --- %(message)s", "%Y-%m-%d %H:%M:%S") # console.setFormatter(formatter) # logging.getLogger('').addHandler(console) coin_status = [-1,-1,-1,-1] money_status = [-1,-1,-1,-1] history = open("log/historyPrice_%s.txt"%time.strftime('%Y_%m_%d_%H_%M_%S', time.localtime(time.time())),"a") # output = open("journalist.txt",'a') balance = open("log/balance%s.txt"%time.strftime('%Y_%m_%d %H_%M_%S', time.localtime(time.time())),'a') ybQue1 = Queue.Queue() ybQue2 = Queue.Queue() hbQue1 = Queue.Queue() hbQue2 = Queue.Queue() okcQue1 = Queue.Queue() okcQue2 = Queue.Queue() cnbtcQue1 = Queue.Queue() cnbtcQue2 = Queue.Queue() ybTradeQue1 = Queue.Queue() ybTradeQue2 = Queue.Queue() cnbtcTradeQue1 = Queue.Queue() cnbtcTradeQue2 = Queue.Queue() hbTradeQue1 = Queue.Queue() hbTradeQue2 = Queue.Queue() okcTradeQue1 = Queue.Queue() okcTradeQue2 = Queue.Queue() ybAccountQue1 = Queue.Queue() ybAccountQue2 = Queue.Queue() cnbtcAccountQue1 = Queue.Queue() cnbtcAccountQue2 = Queue.Queue() hbAccountQue1 = Queue.Queue() hbAccountQue2 = Queue.Queue() okcAccountQue1 = Queue.Queue() okcAccountQue2 = Queue.Queue() alertQue = Queue.Queue() total_trade_coin = 0 delay_time = 0.2 config = json.load(open("config.json","r")) #####max coin # in each trade maxTradeLimitation = float(config["MaxCoinTradeLimitation"]) tel_list = config["tel"] # maxTradeLimitation_yb_buy_cnbtc_sell = float(config["MaxCoinTradeLimitation_yb_buy_cnbtc_sell"]) # maxTradeLimitation_yb_buy_hb_sell = float(config["MaxCoinTradeLimitation_yb_buy_hb_sell"]) # maxTradeLimitation_yb_sell_hb_buy = float(config["MaxCoinTradeLimitation_yb_sell_hb_buy"]) # maxTradeLimitation_hb_buy_cnbtc_sell = float(config["MaxCoinTradeLimitation_hb_buy_cnbtc_sell"]) # maxTradeLimitation_hb_sell_cnbtc_buy = float(config["MaxCoinTradeLimitation_hb_sell_cnbtc_buy"]) #####max coin # for each account maxCoin = float(config["MaxCoinLimitation"]) #####if spread over this threshold, we trade max_thres_limitation = float(config["max_thres_limitation"]) spread_threshold_yb_sell_cnbtc_buy = float(config["spread_threshold_yb_sell_cnbtc_buy"]) spread_threshold_yb_buy_cnbtc_sell = float(config["spread_threshold_yb_buy_cnbtc_sell"]) spread_threshold_yb_buy_hb_sell = float(config["spread_threshold_yb_buy_hb_sell"]) spread_threshold_yb_sell_hb_buy = float(config["spread_threshold_yb_sell_hb_buy"]) spread_threshold_hb_buy_cnbtc_sell = float(config["spread_threshold_hb_buy_cnbtc_sell"]) spread_threshold_hb_sell_cnbtc_buy = float(config["spread_threshold_hb_sell_cnbtc_buy"]) random_range = float(config["RandomRange"]) spread_threshold_yb_sell_okc_buy = float(config["spread_threshold_yb_sell_okc_buy"]) spread_threshold_yb_buy_okc_sell = float(config["spread_threshold_yb_buy_okc_sell"]) spread_threshold_okc_buy_hb_sell = float(config["spread_threshold_okc_buy_hb_sell"]) spread_threshold_okc_sell_hb_buy = float(config["spread_threshold_okc_sell_hb_buy"]) spread_threshold_okc_buy_cnbtc_sell = float(config["spread_threshold_okc_buy_cnbtc_sell"]) spread_threshold_okc_sell_cnbtc_buy = float(config["spread_threshold_okc_sell_cnbtc_buy"]) max_diff_thres = float(config["max_diff_thres"]) #######if coin # is lower than alert thres, it will increase the thres alert_thres_coin = float(config["alert_thres_coin"]) alert_thres_money = float(config["alert_thres_money"]) thres_coin = float(config["thres_coin"]) thres_money = float(config["thres_money"]) #######max thres increase is slop*alert_thres slope = float(config["alert_slope"]) # print max_diff_thres,alert_thres,slope # spread_threshold = float(config["spread_threshold"]) # spread_threshold_minor = float(config["spread_threshold_minor"]) #####if we start a trade, we will accept all trade until spread reach lowest spread threshold, after that, we cancel all trade lowest_spread_threshold = float(config["lowest_spread_threshold"]) trade_multiplier_ratio = float(config["TradeMultiplyRatio"]) # lowest_spread_threshold_minor = float(config["lowest_spread_threshold_minor"]) #####the trade price is max trade limitation*trade ratio behind the min/max price of ask/bid trade_ratio = float(config["TradeAdvanceRatio"]) # trade_ratio_minor = float(config["TradeAdvanceRatio_minor"]) #####slippage slippage = float(config["slippage"]) tmpThres = maxTradeLimitation*trade_ratio # tmpThres_minor = maxTradeLimitation_minor*trade_ratio offset_player = int(config["offset_player"]) # offset_player_minor = int(config["offset_player_minor"]) offset_coin = float(config["offset_coin"]) # offset_coin_minor = float(config["offset_coin_minor"]) ########return 0 accumulate amount ########return 1 price ########return 2 list #######tradeque1[0]:obj #######tradeque1[1]:buy or sell #######tradeque1[2]:amount #######tradeque1[3]:price #######tradeque1[4]:limit_price import sys import numpy.matlib import HuoBi import OKCoin open_okc = open_platform[3] open_yb = open_platform[1] open_cnbtc = open_platform[0] open_hb = open_platform[2] if open_yb: yb = YunBi.Yunbi(config,"LiChen") print yb.get_account() else: yb = None # import gzip # from StringIO import StringIO # # buf = StringIO(acc["name"]) # f = gzip.GzipFile(fileobj=buf) # print f.read() # sss = acc["name"].encode("raw_unicode_escape").decode() # print ss # logging.info("YB Account "+json.dumps(yb.get_account(),ensure_ascii=False)) if open_cnbtc: cnbtc = CNBTC.CNBTC(config) print("cnbtc Account "+str(cnbtc.get_account())) else: cnbtc = None if open_hb: hb = HuoBi.HuoBi(config) print("HB Account "+str(hb.get_account())) else: hb = None if open_okc: okc = OKCoin.OKCoin(config) print("OKCoin Account "+str(okc.get_account())) okc_thread = threading.Thread(target=okcRun) okc_thread.setDaemon(True) okc_thread.start() else: okc = None if open_yb: yb_thread = threading.Thread(target=ybRun) yb_thread.setDaemon(True) yb_thread.start() if open_cnbtc: cnbtc_thread = threading.Thread(target=cnbtcRun) cnbtc_thread.setDaemon(True) cnbtc_thread.start() if open_hb: hb_thread = threading.Thread(target=hbRun) hb_thread.setDaemon(True) hb_thread.start() if open_okc: okc_trade_thread = threading.Thread(target=okcTradeRun) okc_trade_thread.setDaemon(True) okc_trade_thread.start() if open_yb: yb_trade_thread = threading.Thread(target=ybTradeRun) yb_trade_thread.setDaemon(True) yb_trade_thread.start() if open_cnbtc: cnbtc_trade_thread = threading.Thread(target = cnbtcTradeRun) cnbtc_trade_thread.setDaemon(True) cnbtc_trade_thread.start() if open_hb: hb_trade_thread = threading.Thread(target=hbTradeRun) hb_trade_thread.setDaemon(True) hb_trade_thread.start() if open_okc: okc_account_thread = threading.Thread(target=okcAccountRun) okc_account_thread.setDaemon(True) okc_account_thread.start() if open_yb: yb_account_thread = threading.Thread(target=ybAccountRun) yb_account_thread.setDaemon(True) yb_account_thread.start() if open_cnbtc: cnbtc_account_thread = threading.Thread(target = cnbtcAccountRun) cnbtc_account_thread.setDaemon(True) cnbtc_account_thread.start() if open_hb: hb_account_thread = threading.Thread(target=hbAccountRun) hb_account_thread.setDaemon(True) hb_account_thread.start() alertThread = threading.Thread(target=alert) alertThread.setDaemon(True) alertThread.start() total_coin = 0 total_money = 0 tick = 0 last_total_eth = 0 last_total_cny = 0 first_total_eth = 0 first_total_cny = 0 first = True platform_number = 4 name_list = ["CNBTC","YunBi","HuoBi","OKCoin"] obj_list = [cnbtc,yb,hb,okc] que1_list = [cnbtcQue1,ybQue1,hbQue1,okcQue1] que2_list = [cnbtcQue2,ybQue2,hbQue2,okcQue2] trade_que1_list = [cnbtcTradeQue1,ybTradeQue1,hbTradeQue1,okcTradeQue1] trade_que2_list = [cnbtcTradeQue2,ybTradeQue2,hbTradeQue2,okcTradeQue2] thres_list = numpy.array([[999999,spread_threshold_yb_buy_cnbtc_sell,spread_threshold_hb_buy_cnbtc_sell,spread_threshold_okc_buy_cnbtc_sell], [spread_threshold_yb_sell_cnbtc_buy,999999,spread_threshold_yb_sell_hb_buy,spread_threshold_yb_sell_okc_buy], [spread_threshold_hb_sell_cnbtc_buy,spread_threshold_yb_buy_hb_sell,9999999,spread_threshold_okc_buy_hb_sell], [spread_threshold_okc_sell_cnbtc_buy,spread_threshold_yb_buy_okc_sell,spread_threshold_okc_sell_hb_buy,999999]]) thres_list_origin = thres_list.copy() has_ts = [True,True,True,False] platform_list = [] for i in range(platform_number): platform_list.append( { "name":name_list[i], "obj":obj_list[i], "que1":que1_list[i], "que2":que2_list[i], "trade_que1":trade_que1_list[i], "trade_que2":trade_que2_list[i], "depth_buy":None, "depth_sell":None, "has_ts":has_ts[i] } ) brokerage_fee = numpy.asarray([0.0004,0.001,0.002,0.001]) cash_fee = numpy.asarray([0.001,0.001,0.002,0.002]) while True: print 'tick',tick for platform in platform_list: if platform["obj"]!=None: platform["que1"].put(platform["obj"]) if open_yb: ybAccountQue1.put(yb) if open_okc: okcAccountQue1.put(okc) if open_cnbtc: cnbtcAccountQue1.put(cnbtc) if open_hb: hbAccountQue1.put(hb) for platform in platform_list: if platform["obj"]!=None: platform["depth_sell"] = platform["que2"].get() platform["depth_buy"] = platform["que2"].get() ###depth[0] is amount ###depth[1] is price ###depth[2] is list platform_list["depth_buy"] = platform["que2"].get() max_diff = -1000 trade_info = dict() average_price = 0 open_num = 0 for i in range(platform_number): if platform_list[i]["obj"]!=None: open_num+=1 average_price+=platform_list[i]["depth_buy"][0][1]+platform_list[i]["depth_sell"][0][1] average_price /= open_num*2.0/1.01 print 'average_price %f'%average_price brokerage_trade = numpy.add.outer(brokerage_fee,brokerage_fee)*average_price cash_trade = numpy.add.outer(cash_fee,numpy.zeros(cash_fee.shape[0]))*average_price tick+=1 if tick % 1 == 0: total_cny = 0 total_eth = 0 yb_cny = 0 yb_eth = 0 cnbtc_cny = 0 cnbtc_eth = 0 hb_cny = 0 hb_eth = 0 okc_cny = 0 okc_eth = 0 if open_yb: yb_cny,yb_eth = ybAccountQue2.get() print "yb_balance:%f %f"%(yb_eth,yb_cny) if open_okc: okc_cny,okc_eth = okcAccountQue2.get() print "okc_balance:%f %f"%(okc_eth,okc_cny) if open_hb: hb_cny,hb_eth = hbAccountQue2.get() print "hb balance:%f %f"%(hb_eth,hb_cny) if open_cnbtc: cnbtc_cny,cnbtc_eth = cnbtcAccountQue2.get() print "cnbtc balance:%f %f"%(cnbtc_eth,cnbtc_cny) total_cny = yb_cny+hb_cny+cnbtc_cny+okc_cny total_eth = yb_eth+hb_eth+cnbtc_eth+okc_eth balance.write("%s %f %f %f %f %f %f %f %f %f %f\n"%(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())), cnbtc_eth,cnbtc_cny,yb_eth,yb_cny,hb_eth,hb_cny,okc_eth,okc_cny,total_eth,total_cny)) history.write("%s "%time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))) for i in range(platform_number): if platform_list[i]["obj"]!=None: history.write("%f %f "%(platform_list[i]["depth_buy"][0][1],platform_list[i]["depth_sell"][0][1])) else: history.write('0 0 ') history.write('\n') cny_list = numpy.asarray([cnbtc_cny,yb_cny,hb_cny,okc_cny]) eth_list = numpy.asarray([cnbtc_eth,yb_eth,hb_eth,okc_eth]) last_total_eth = total_eth last_total_cny = total_cny if first: first_total_cny = total_cny first_total_eth = total_eth first = False # history.write("%s %f %f %f %f %f %f\n" % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), # yb_depth[0][1], cnbtc_depth[0][1], yb_depth[0][1] - cnbtc_depth[0][1], # yb_depth_minor[0][1], cnbtc_depth_minor[0][1], # cnbtc_depth_minor[0][1] - yb_depth_minor[0][1])) balance.flush() history.flush() if tick%1 == 0: thres_list,trade_multiplier = setThreshold(cny_list,eth_list,brokerage_fee,cash_fee,thres_list,thres_list_origin,platform_number,average_price,maxTradeLimitation,name_list) # print thres_list i1 = None j1 = None for i in range(platform_number): for j in range(platform_number): if i!=j and platform_list[i]["obj"]!=None and platform_list[j]["obj"]!=None: # if platform_list[i]["has_ts"] and platform_list[j]["has_ts"]: # print i,j,int(platform_list[i]["depth_sell"][1]),int(platform_list[j]["depth_buy"][1]) # if (int(platform_list[i]["depth_sell"][1])-int(platform_list[j]["depth_buy"][1]))>5: # continue # print platform_list[i],platform_list[j] if platform_list[i]["depth_sell"][0][1] - platform_list[j]["depth_buy"][0][1]>thres_list[i,j] and platform_list[i]["depth_sell"][0][1] - platform_list[j]["depth_buy"][0][1]-thres_list[i,j]>max_diff: max_diff = platform_list[i]["depth_sell"][0][1]-platform_list[j]["depth_buy"][0][1]-thres_list[i,j] trade_info["sell_depth"] = platform_list[i]["depth_sell"] trade_info["buy_depth"] = platform_list[j]["depth_buy"] trade_info["sell_name"] = platform_list[i]["name"] trade_info["buy_name"] = platform_list[j]["name"] trade_info["sell_que1"] = platform_list[i]["trade_que1"] trade_info["sell_que2"] = platform_list[i]["trade_que2"] trade_info["buy_que1"] = platform_list[j]["trade_que1"] trade_info["buy_que2"] = platform_list[j]["trade_que2"] trade_info["sell_obj"] = platform_list[i]["obj"] trade_info["buy_obj"]=platform_list[j]["obj"] i1 = i j1 = j if max_diff>0: print "max_diff %f"%max_diff buy_depth = trade_info["buy_depth"] sell_depth = trade_info["sell_depth"] # print("BuySide:%s timestamp:%s amount:\t%f price:\t%f"%(trade_info["buy_name"],buy_depth[1],buy_depth[0][0],buy_depth[0][1],str(buy_depth[0][2]))) # print('SellSide:%s timestamp:%s amount:\t%f price:\t%f'%(trade_info["sell_name"],sell_depth[1],sell_depth[0][0],sell_depth[0][1],str(sell_depth[0][2]))) # print 'BuySide:%s timestamp:%s amount:\t%f price:\t%f asks:%s'%(trade_info["buy_name"],buy_depth[1],buy_depth[0][0],buy_depth[0][1],str(buy_depth[0][2])) # print 'SellSide:%s timestamp:%s amount:\t%f price:\t%f bids:%s'%(trade_info["sell_name"],sell_depth[1],sell_depth[0][0],sell_depth[0][1],str(sell_depth[0][2])) amount = int(min(buy_depth[0][0],sell_depth[0][0])*1.0/trade_ratio*trade_multiplier[i1,j1]*100)/100.0 amount +=int((random.random()-0.5)*2*(random_range+0.01)*100)/100.0 if amount<0: amount = 0 amount_buy=amount amount_sell=amount_buy limit = (buy_depth[0][1]+sell_depth[0][1])*1.0/2.0 if total_coin>0.0001: amount_buy = max(amount_buy-total_coin,0) elif total_coin<-0.0001: amount_sell = max(amount_sell+total_coin,0) print "%s buy %f coins at %f and limit %f" %(trade_info["buy_name"],amount_buy,buy_depth[0][1],limit-lowest_spread_threshold/2.0) trade_info["buy_que1"].put((trade_info["buy_obj"],"buy",amount_buy,buy_depth[0][1],limit-lowest_spread_threshold/2.0)) print "%s sell %f coins at %f and limit %f" %(trade_info["sell_name"],amount_sell,sell_depth[0][1],limit+lowest_spread_threshold/2.0) trade_info["sell_que1"].put((trade_info["sell_obj"],"sell",amount_sell,sell_depth[0][1],limit+lowest_spread_threshold/2.0)) sell_remain = trade_info["sell_que2"].get() buy_remain = trade_info["buy_que2"].get() # output.write('%f, %f, %f, %f\n'%(sell_remain[0]-amount_sell,amount_buy-buy_remain[0],buy_remain[1],sell_remain[1])) # output.flush() total_coin+=sell_remain[0]-amount_sell-buy_remain[0]+amount_buy total_money+=sell_remain[1]+buy_remain[1] print "%s_remain:%f\t %s_remain:%f,total_remain:%f"%(trade_info["buy_name"],buy_remain[0],trade_info["sell_name"],sell_remain[0],maxCoin) print"coin:%f,money:%f"%(total_coin,total_money) maxCoin-=max(sell_remain[0],buy_remain[0]) # if maxCoin<0: # hbQue1.put(None) # cnbtcQue1.put(None) # hbTradeQue1.put(None) # cnbtcTradeQue1.put(None) # break else: # average_price = 0 for i in range(platform_number): for j in range(platform_number): if i!=j and platform_list[i]["obj"]!=None and platform_list[j]["obj"]!=None: print "no trade %s sell:%f %s buy:%f diff:%15f thres:%20f diff_brokerage:%20f"%(platform_list[i]["name"],platform_list[i]["depth_sell"][0][1],platform_list[j]["name"],platform_list[j]["depth_buy"][0][1], platform_list[i]["depth_sell"][0][1]-platform_list[j]["depth_buy"][0][1],thres_list[i,j],platform_list[i]["depth_sell"][0][1]-platform_list[j]["depth_buy"][0][1]-thres_list[i,j]) # average_price+=platform_list[i]["depth_buy"][0][1]+platform_list[i]["depth_sell"][0][1] # average_price/=2.0*platform_number print average_price # print "no trade yb sell:%f cnbtc buy:%f diff:%f"%(yb_depth_sell[0][1],cnbtc_depth_buy[0][1],yb_depth_sell[0][1]-cnbtc_depth_buy[0][1]) # print "no trade hb sell:%f cnbtc buy:%f diff:%f"%(hb_depth_sell[0][1],cnbtc_depth_buy[0][1],hb_depth_sell[0][1]-cnbtc_depth_buy[0][1]) # print "no trade yb buy:%f cnbtc sell:%f diff:%f"%(yb_depth_buy[0][1],cnbtc_depth_sell[0][1],cnbtc_depth_sell[0][1]-yb_depth_buy[0][1]) # print "no trade hb buy:%f cnbtc sell:%f diff:%f"%(hb_depth_buy[0][1],cnbtc_depth_sell[0][1],cnbtc_depth_sell[0][1]-hb_depth_buy[0][1]) # print "no trade yb buy:%f hb sell:%f diff:%f"%(yb_depth_buy[0][1],hb_depth_sell[0][1],hb_depth_sell[0][1]-yb_depth_buy[0][1]) # print "no trade hb buy:%f yb sell:%f diff:%f"%(hb_depth_buy[0][1],yb_depth_sell[0][1],yb_depth_sell[0][1]-hb_depth_buy[0][1]) print "balance %f %f diff: %f %f %f first:%f %f"%(total_eth,total_cny, total_eth - last_total_eth,total_cny - last_total_cny,(total_eth - last_total_eth)*2000.0, total_eth - first_total_eth,total_cny - first_total_cny) print '\n' # # if hb_depth_sell[0][1]-cnbtc_depth_buy[0][1]>spread_threshold_hb_sell_cnbtc_buy and abs(int(cnbtc_depth_buy[1])-int(hb_depth_sell[1])<=3) and hb_depth_sell[0][1]-cnbtc_depth_buy[0][1]>max_diff: # if cnbtc_depth_sell[0][1]-hb_depth_buy[0][1]>spread_threshold_hb_buy_cnbtc_sell and abs(int(hb_depth_buy[1])-int(cnbtc_depth_sell[1])<=3) and cnbtc_depth_sell[0][1]-hb_depth_buy[0][1]>max_diff: # max_diff = cnbtc_depth_sell[0][1]-hb_depth_buy[0][1] # trade_info["sell_depth"] = cnbtc_depth_sell # trade_info["buy_depth"] = hb_depth_buy # trade_info["sell_name"] = "CNBTC" # trade_info["buy_name"] = "HuoBi" # trade_info["sell_que1"] = cnbtcTradeQue1 # trade_info["sell_que2"] = cnbtcTradeQue2 # trade_info["buy_que1"] = hbTradeQue1 # trade_info["buy_que2"] = hbTradeQue2 # trade_info["buy_obj"] = hb # trade_info["sell_obj"]=cnbtc # if hb_depth_sell[0][1]-yb_depth_buy[0][1]>spread_threshold_yb_buy_hb_sell and abs(int(yb_depth_buy[1])-int(hb_depth_sell[1])<=3) and hb_depth_sell[0][1]-yb_depth_buy[0][1]>max_diff: # max_diff = hb_depth_sell[0][1]-yb_depth_buy[0][1] # trade_info["sell_depth"] = hb_depth_sell # trade_info["buy_depth"] = yb_depth_buy # trade_info["sell_name"] = "HuoBi" # trade_info["buy_name"] = "YunBi" # trade_info["sell_que1"] = hbTradeQue1 # trade_info["sell_que2"] = hbTradeQue2 # trade_info["buy_que1"] = ybTradeQue1 # trade_info["buy_que2"] = ybTradeQue2 # trade_info["sell_obj"] = hb # trade_info["buy_obj"]=yb # if yb_depth_sell[0][1]-hb_depth_buy[0][1]>spread_threshold_yb_sell_hb_buy and abs(int(hb_depth_buy[1])-int(yb_depth_sell[1])<=3) and yb_depth_sell[0][1]-hb_depth_buy[0][1]>max_diff: # max_diff = yb_depth_sell[0][1]-hb_depth_buy[0][1] # trade_info["sell_depth"] = yb_depth_sell # trade_info["buy_depth"] = hb_depth_buy # trade_info["sell_name"] = "YunBi" # trade_info["buy_name"] = "HuoBi" # trade_info["sell_que1"] = ybTradeQue1 # trade_info["sell_que2"] = ybTradeQue2 # trade_info["buy_que1"] = hbTradeQue1 # trade_info["buy_que2"] = hbTradeQue2 # trade_info["sell_obj"] = yb # trade_info["buy_obj"]=hb # if yb_depth_sell[0][1]-cnbtc_depth_buy[0][1]>spread_threshold_yb_sell_cnbtc_buy and abs(int(cnbtc_depth_buy[1])-int(yb_depth_sell[1])<=3) and yb_depth_sell[0][1]-cnbtc_depth_buy[0][1]>max_diff: # max_diff = yb_depth_sell[0][1]-cnbtc_depth_buy[0][1] # trade_info["sell_depth"] = yb_depth_sell # trade_info["buy_depth"] = cnbtc_depth_buy # trade_info["sell_name"] = "YunBi" # trade_info["buy_name"] = "CNBTC" # trade_info["sell_que1"] = ybTradeQue1 # trade_info["sell_que2"] = ybTradeQue2 # trade_info["buy_que1"] = cnbtcTradeQue1 # trade_info["buy_que2"] = cnbtcTradeQue2 # trade_info["sell_obj"] = yb # trade_info["buy_obj"]=cnbtc # if cnbtc_depth_sell[0][1]-yb_depth_buy[0][1]>spread_threshold_yb_sell_cnbtc_buy and abs(int(cnbtc_depth_sell[1])-int(yb_depth_buy[1])<=3) and cnbtc_depth_sell[0][1]-yb_depth_buy[0][1]>max_diff: # max_diff = cnbtc_depth_sell[0][1]-yb_depth_buy[0][1] # trade_info["sell_depth"] = cnbtc_depth_sell # trade_info["buy_depth"] = yb_depth_buy # trade_info["sell_name"] = "CNBTC" # trade_info["buy_name"] = "YunBi" # trade_info["sell_que1"] = cnbtcTradeQue1 # trade_info["sell_que2"] = cnbtcTradeQue2 # trade_info["buy_que1"] = ybTradeQue1 # trade_info["buy_que2"] = ybTradeQue2 # trade_info["sell_obj"] = cnbtc # trade_info["buy_obj"]=yb # if open_okc: # if okc_depth_sell[0][1]-cnbtc_depth_buy[0][1]>spread_threshold_okc_sell_cnbtc_buy and okc_depth_sell[0][1]-cnbtc_depth_buy[0][1]>max_diff: # max_diff = okc_depth_sell[0][1]-cnbtc_depth_buy[0][1] # trade_info["sell_depth"] = okc_depth_sell # trade_info["buy_depth"] = cnbtc_depth_buy # trade_info["sell_name"] = "OKCoin" # trade_info["buy_name"] = "CNBTC" # trade_info["sell_que1"] = okcTradeQue1 # trade_info["sell_que2"] = okcTradeQue2 # trade_info["buy_que1"] = cnbtcTradeQue1 # trade_info["buy_que2"] = cnbtcTradeQue2 # trade_info["sell_obj"] = okc # trade_info["buy_obj"]=cnbtc # if cnbtc_depth_sell[0][1]-okc_depth_buy[0][1]>spread_threshold_okc_buy_cnbtc_sell and cnbtc_depth_sell[0][1]-okc_depth_buy[0][1]>max_diff: # max_diff = cnbtc_depth_sell[0][1]-okc_depth_buy[0][1] # trade_info["sell_depth"] = cnbtc_depth_sell # trade_info["buy_depth"] = okc_depth_buy # trade_info["sell_name"] = "CNBTC" # trade_info["buy_name"] = "OKCoin" # trade_info["sell_que1"] = cnbtcTradeQue1 # trade_info["sell_que2"] = cnbtcTradeQue2 # trade_info["buy_que1"] = okcTradeQue1 # trade_info["buy_que2"] = okcTradeQue2 # trade_info["buy_obj"] = okc # trade_info["sell_obj"]=cnbtc # if hb_depth_sell[0][1]-okc_depth_buy[0][1]>spread_threshold_okc_buy_hb_sell and hb_depth_sell[0][1]-okc_depth_buy[0][1]>max_diff: # max_diff = hb_depth_sell[0][1]-okc_depth_buy[0][1] # trade_info["sell_depth"] = hb_depth_sell # trade_info["buy_depth"] = okc_depth_buy # trade_info["sell_name"] = "HuoBi" # trade_info["buy_name"] = "OKCoin" # trade_info["sell_que1"] = hbTradeQue1 # trade_info["sell_que2"] = hbTradeQue2 # trade_info["buy_que1"] = okcTradeQue1 # trade_info["buy_que2"] = okcTradeQue2 # trade_info["sell_obj"] = hb # trade_info["buy_obj"]=okc # if okc_depth_sell[0][1]-hb_depth_buy[0][1]>spread_threshold_okc_sell_hb_buy and okc_depth_sell[0][1]-hb_depth_buy[0][1]>max_diff: # max_diff = okc_depth_sell[0][1]-hb_depth_buy[0][1] # trade_info["sell_depth"] = okc_depth_sell # trade_info["buy_depth"] = hb_depth_buy # trade_info["sell_name"] = "OKCoin" # trade_info["buy_name"] = "HuoBi" # trade_info["sell_que1"] = okcTradeQue1 # trade_info["sell_que2"] = okcTradeQue2 # trade_info["buy_que1"] = hbTradeQue1 # trade_info["buy_que2"] = hbTradeQue2 # trade_info["sell_obj"] = okc # trade_info["buy_obj"]=hb # if yb_depth_sell[0][1]-okc_buy[0][1]>spread_threshold_yb_sell_cnbtc_buy and yb_depth_sell[0][1]-cnbtc_depth_buy[0][1]>max_diff: # max_diff = yb_depth_sell[0][1]-cnbtc_depth_buy[0][1] # trade_info["sell_depth"] = yb_depth_sell # trade_info["buy_depth"] = cnbtc_depth_buy # trade_info["sell_name"] = "YunBi" # trade_info["buy_name"] = "CNBTC" # trade_info["sell_que1"] = ybTradeQue1 # trade_info["sell_que2"] = ybTradeQue2 # trade_info["buy_que1"] = cnbtcTradeQue1 # trade_info["buy_que2"] = cnbtcTradeQue2 # trade_info["sell_obj"] = yb # trade_info["buy_obj"]=cnbtc # if cnbtc_depth_sell[0][1]-yb_depth_buy[0][1]>spread_threshold_yb_sell_cnbtc_buy and cnbtc_depth_sell[0][1]-yb_depth_buy[0][1]>max_diff: # max_diff = cnbtc_depth_sell[0][1]-yb_depth_buy[0][1] # trade_info["sell_depth"] = cnbtc_depth_sell # trade_info["buy_depth"] = yb_depth_buy # trade_info["sell_name"] = "CNBTC" # trade_info["buy_name"] = "YunBi" # trade_info["sell_que1"] = cnbtcTradeQue1 # trade_info["sell_que2"] = cnbtcTradeQue2 # trade_info["buy_que1"] = ybTradeQue1 # trade_info["buy_que2"] = ybTradeQue2 # trade_info["sell_obj"] = cnbtc # trade_info["buy_obj"]=yb # if hb_depth_sell[0][1]-cnbtc_depth_buy[0][1]>spread_threshold_hb_sell_cnbtc_buy and abs(int(cnbtc_depth_buy[1])-int(hb_depth_sell[1])<=3) and hb_depth_sell[0][1]-cnbtc_depth_buy[0][1]>max_diff: # print "start trade major" # # elif yb_depth_sell[0][1]-cnbtc_depth_buy[0][1]>spread_threshold_yb_sell_cnbtc_buy and abs(int(cnbtc_depth_buy[1])-int(yb_depth_sell[1])<=3): # print 'CNBTC: timestamp:%s amount:\t%f price:\t%f asks:%s'%(cnbtc_depth_buy[1],cnbtc_depth_buy[0][0],cnbtc_depth_buy[0][1],str(cnbtc_depth_buy[0][2])) # print 'YUNBI: timestamp:%s amount:\t%f price:\t%f bids:%s'%(yb_depth_sell[1],yb_depth_sell[0][0],yb_depth_sell[0][1],str(yb_depth_sell[0][2])) # print "start trade major" # amount = min(cnbtc_depth_buy[0][0],yb_depth_sell[0][0])*1.0/trade_ratio # amount_buy=amount # amount_sell=amount_buy # limit = (cnbtc_depth_buy[0][1]+yb_depth_sell[0][1])*1.0/2.0 # if total_coin>0.0001: # amount_buy = max(amount_buy-total_coin,0) # elif total_coin<-0.0001: # amount_sell = max(amount_sell+total_coin,0) # print "cnbtc buy %f coins at %f and limit %f" %(amount_buy,cnbtc_depth_buy[0][1],limit-lowest_spread_threshold/2.0) # cnbtcTradeQue1.put((cnbtc,"buy",amount_buy,cnbtc_depth_buy[0][1],limit-lowest_spread_threshold/2.0)) # print "yb sell %f coins at %f and limit %f" %(amount_sell,yb_depth_sell[0][1],limit+lowest_spread_threshold/2.0) # ybTradeQue1.put((yb,"sell",amount_sell,yb_depth_sell[0][1],limit+lowest_spread_threshold/2.0)) # cnbtc_remain = cnbtcTradeQue2.get() # yb_remain = ybTradeQue2.get() # output.write('%f, %f, %f, %f\n'%(yb_remain[0]-amount_sell,amount_buy-cnbtc_remain[0],yb_remain[1],cnbtc_remain[1])) # output.flush() # total_coin+=yb_remain[0]-amount_sell-cnbtc_remain[0]+amount_buy # total_money+=yb_remain[1]+cnbtc_remain[1] # print "cnbtc_remain:%f\t yb_remain:%f,total_remain:%f"%(cnbtc_remain[0],yb_remain[0],maxCoin) # print"coin:%f,money:%f"%(total_coin,total_money) # maxCoin-=max(yb_remain[0],cnbtc_remain[0]) # if maxCoin<0: # ybQue1.put(None) # cnbtcQue1.put(None) # ybTradeQue1.put(None) # cnbtcTradeQue1.put(None) # break # # # elif False: # elif cnbtc_depth_sell[0][1]-yb_depth_buy[0][1]>spread_threshold_yb_buy_cnbtc_sell and abs(int(cnbtc_depth_sell[1])-int(yb_depth_buy[1])<=3): # print 'CNBTC: timestamp:%s amount:\t%f price:\t%f bids:%s'%(cnbtc_depth_sell[1],cnbtc_depth_sell[0][0],cnbtc_depth_sell[0][1],str(cnbtc_depth_sell[0][2])) # print 'YUNBI: timestamp:%s amount:\t%f price:\t%f asks:%s'%(yb_depth_buy[1],yb_depth_buy[0][0],yb_depth_buy[0][1],str(yb_depth_buy[0][2])) # print "start trade minor" # amount = min(cnbtc_depth_sell[0][0], yb_depth_buy[0][0]) * 1.0 / trade_ratio # amount_buy = amount # amount_sell = amount_buy # limit = (cnbtc_depth_sell[0][1] + yb_depth_buy[0][1]) * 1.0 / 2.0 # if total_coin > 0.01: # amount_buy = max(amount_buy - total_coin, 0) # elif total_coin < -0.01: # amount_sell = max(amount_sell + total_coin, 0) # print "cnbtc sell %f coins at %f and limit %f" % (amount_sell, cnbtc_depth_sell[0][1], limit + lowest_spread_threshold/ 2.0) # cnbtcTradeQue1.put((cnbtc, "sell", amount_sell, cnbtc_depth_sell[0][1], limit + lowest_spread_threshold / 2.0)) # print "yb buy %f coins at %f and limit %f" % (amount_buy, yb_depth_buy[0][1], limit - lowest_spread_threshold / 2.0) # ybTradeQue1.put( # (yb, "buy", amount_buy, yb_depth_buy[0][1], limit - lowest_spread_threshold / 2.0)) # cnbtc_remain = cnbtcTradeQue2.get() # yb_remain = ybTradeQue2.get() # output.write('%f, %f, %f, %f\n' % ( # amount_buy - yb_remain[0], cnbtc_remain[0] - amount_sell, yb_remain[1], cnbtc_remain[1])) # total_coin += -yb_remain[0] - amount_sell + cnbtc_remain[0] + amount_buy # total_money += yb_remain[1] + cnbtc_remain[1] # print "cnbtc_remain:%f\t yb_remain:%f,total_remain:%f" % (cnbtc_remain[0], yb_remain[0], maxCoin) # print"coin:%f,money:%f" % (total_coin, total_money) # maxCoin -= max(yb_remain[0], cnbtc_remain[0]) # if maxCoin < 0: # ybQue1.put(None) # cnbtcQue1.put(None) # ybTradeQue1.put(None) # cnbtcTradeQue1.put(None) # break # # elif False: # elif cnbtc_depth_sell[0][1]-hb_depth_buy[0][1]>spread_threshold_hb_buy_cnbtc_sell and abs(int(cnbtc_depth_sell[1])-int(hb_depth_buy[1])<=3): # print 'CNBTC: timestamp:%s amount:\t%f price:\t%f bids:%s'%(cnbtc_depth_sell[1],cnbtc_depth_sell[0][0],cnbtc_depth_sell[0][1],str(cnbtc_depth_sell[0][2])) # print 'HuoBI: timestamp:%s amount:\t%f price:\t%f asks:%s'%(hb_depth_buy[1],hb_depth_buy[0][0],hb_depth_buy[0][1],str(hb_depth_buy[0][2])) # print "start trade minor" # amount = min(cnbtc_depth_sell[0][0], hb_depth_buy[0][0]) * 1.0 / trade_ratio # amount_buy = amount # amount_sell = amount_buy # limit = (cnbtc_depth_sell[0][1] + hb_depth_buy[0][1]) * 1.0 / 2.0 # if total_coin > 0.01: # amount_buy = max(amount_buy - total_coin, 0) # elif total_coin < -0.01: # amount_sell = max(amount_sell + total_coin, 0) # print "cnbtc sell %f coins at %f and limit %f" % (amount_sell, cnbtc_depth_sell[0][1], limit + lowest_spread_threshold/ 2.0) # cnbtcTradeQue1.put((cnbtc, "sell", amount_sell, cnbtc_depth_sell[0][1], limit + lowest_spread_threshold / 2.0)) # print "hb buy %f coins at %f and limit %f" % (amount_buy, hb_depth_buy[0][1], limit - lowest_spread_threshold / 2.0) # hbTradeQue1.put( # (hb, "buy", amount_buy, hb_depth_buy[0][1], limit - lowest_spread_threshold / 2.0)) # cnbtc_remain = cnbtcTradeQue2.get() # hb_remain = hbTradeQue2.get() # output.write('%f, %f, %f, %f\n' % ( # amount_buy - hb_remain[0], cnbtc_remain[0] - amount_sell, hb_remain[1], cnbtc_remain[1])) # total_coin += -hb_remain[0] - amount_sell + cnbtc_remain[0] + amount_buy # total_money += hb_remain[1] + cnbtc_remain[1] # print "cnbtc_remain:%f\t hb_remain:%f,total_remain:%f" % (cnbtc_remain[0], hb_remain[0], maxCoin) # print"coin:%f,money:%f" % (total_coin, total_money) # maxCoin -= max(hb_remain[0], cnbtc_remain[0]) # if maxCoin < 0: # hbQue1.put(None) # cnbtcQue1.put(None) # hbTradeQue1.put(None) # cnbtcTradeQue1.put(None) # break # else: # # print "total coin: %f total_cny %f"%(total_eth,total_cny) # # print "yunbi ",str(yb.get_account()) # # print "cnbtc ",str(cnbtc.get_account()) # print cnbtc.get_account() # cnbtc.getDepth() # print cnbtc.buy(volume=0.01,price=1461) # print cnbtc.get_account() # hft = HaiFengTeng.HaiFengTeng(config) # hft.login() # yb = YunBi.Yunbi(config,"YunBi2") # yb.get_account() # yb.buy(volume=0.001,price=9999.0) # yb.getOrder() # print yb.getDepth()
[ 2, 5145, 14, 14629, 14, 12001, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 11748, 20757, 23286, 198, 11748, 31171, 35964, 198, 11748, 33918, 198, 11748, 4704, 278, 198, 11748, 4670, 518, 198, ...
1.97659
17,813
#!/usr/bin/python3 """ Author: Robert Cudmore Date: 20181013 Purpose: Send a Tweet with IP and MAC address of a Raspberry Pi Install: pip3 install tweepy Usage: python3 startuptweet.py 'this is my tweet' """ import tweepy import sys import socket import subprocess from uuid import getnode as get_mac from datetime import datetime # Create variables for each key, secret, token from my_config import hash_tag from my_config import consumer_key from my_config import consumer_secret from my_config import access_token from my_config import access_token_secret message = '' if len( sys.argv ) > 1: message = sys.argv[1] # Set up OAuth and integrate with API auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) # thetime = datetime.now().strftime('%Y%m%d %H:%M:%S') ip = subprocess.check_output(['hostname', '--all-ip-addresses']) ip = ip.decode('utf-8').strip() hostname = socket.gethostname() mac = get_mac() mac = hex(mac) tweet = thetime + ' ' + hostname + ' ' + ip + ' ' + mac + ' ' + message + ' ' + hash_tag print('tweeting:', tweet) api.update_status(status=tweet)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 198, 37811, 198, 13838, 25, 5199, 327, 463, 3549, 198, 10430, 25, 2864, 8784, 18, 198, 30026, 3455, 25, 16290, 257, 18752, 351, 6101, 290, 20582, 2209, 286, 257, 24244, 13993, 198, 15798,...
2.870416
409
#!/usr/bin/python from bs4 import BeautifulSoup import sqlite3
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 11748, 44161, 578, 18, 198 ]
2.782609
23
""" Copyright (c) 2015-2019 Raj Patel(raj454raj@gmail.com), StopStalk Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import requests, bs4 import sites # Constants to be used in case of request failures SERVER_FAILURE = "SERVER_FAILURE" NOT_FOUND = "NOT_FOUND" OTHER_FAILURE = "OTHER_FAILURE" REQUEST_FAILURES = (SERVER_FAILURE, NOT_FOUND, OTHER_FAILURE) if __name__ == "__main__": ihtable = db.invalid_handle atable = db.auth_user cftable = db.custom_friend stable = db.submission nrtable = db.next_retrieval mapping = {} handle_to_row = {} for site in current.SITES: mapping[site] = get_invalid_handle_method(site) handle_to_row[site] = {} impossiblehandle = "thisreallycantbeahandle308" assert(all(map(lambda site: get_invalid_handle_method(site)(impossiblehandle), current.SITES.keys()))) populate_handle_to_row(atable) populate_handle_to_row(cftable) # for site in current.SITES: # print site # for site_handle in handle_to_row[site]: # print "\t", site_handle # for row in handle_to_row[site][site_handle]: # print "\t\t", row.first_name, row.last_name, row.stopstalk_handle update_dict = {"stopstalk_rating": 0, "stopstalk_prev_rating": 0, "per_day": 0.0, "per_day_change": "0.0", "authentic": False} final_delete_query = False cnt = 0 for row in db(ihtable).iterselect(): # If not an invalid handle anymore if handle_to_row[row.site].has_key(row.handle) and mapping[row.site](row.handle) is False: cnt += 1 print row.site, row.handle, "deleted" for row_obj in handle_to_row[row.site][row.handle]: print "\t", row_obj.stopstalk_handle, "updated" update_dict[row.site.lower() + "_lr"] = current.INITIAL_DATE row_obj.update_record(**update_dict) if "user_id" in row_obj: # Custom user db(nrtable.custom_user_id == row_obj.id).update(**{row.site.lower() + "_delay": 0}) else: db(nrtable.user_id == row_obj.id).update(**{row.site.lower() + "_delay": 0}) final_delete_query |= ((stable.site == row.site) & \ (stable.stopstalk_handle == row_obj.stopstalk_handle)) del update_dict[row.site.lower() + "_lr"] row.delete_record() if cnt >= 10: if final_delete_query: db(final_delete_query).delete() cnt = 0 final_delete_query = False if final_delete_query: db(final_delete_query).delete()
[ 37811, 198, 220, 220, 220, 15069, 357, 66, 8, 1853, 12, 23344, 13308, 33110, 7, 430, 73, 34229, 430, 73, 31, 14816, 13, 785, 828, 13707, 1273, 971, 628, 220, 220, 220, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 59...
2.33867
1,624
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- import tensorflow as tf from keras.models import Model from keras.layers import Layer, InputLayer from ...proto import onnx from ..common._container import KerasModelContainer from ..common._topology import Topology from ..common.data_types import * def parse_keras(model, initial_types=None, targeted_onnx=onnx.__version__): ''' The main parsing function of Keras Model and Sequential objects. :param model: A Keras Model or Sequential object :param initial_types: A list providing some types for some root variables. Each element is a tuple of a variable name and a type defined in data_types.py. :param targeted_onnx: a version string such as `1.1.2` or `1.2.1` for specifying the ONNX version used to produce the output model. :return: a Topology object. It's a intermediate representation of the input Keras model ''' raw_model_container = KerasModelContainer(model) topology = Topology(raw_model_container, default_batch_size=1, initial_types=initial_types, targeted_onnx=targeted_onnx) scope = topology.declare_scope('__root__') # Each inbound node defines an evaluation of the underlining model (if the model is called multiple times, it may # contain several inbound nodes). According to the tensors specified in those inbound nodes, we declare the roots # and leaves of the computational graph described by the Keras input model. for node in _extract_inbound_nodes(model): input_shapes, output_shapes = extract_model_input_and_output_shapes(model, topology.default_batch_size) # Declare inputs for a specific model execution for tensor, shape in zip(node.input_tensors, input_shapes): raw_model_container.add_input_name(tensor.name) tensor_type = determine_tensor_type(tensor, topology.default_batch_size, list(shape)) scope.get_local_variable_or_declare_one(tensor.name, tensor_type) # Declare outputs for a specific model execution for tensor, shape in zip(node.output_tensors, output_shapes): raw_model_container.add_output_name(tensor.name) tensor_type = determine_tensor_type(tensor, topology.default_batch_size, list(shape)) scope.get_local_variable_or_declare_one(tensor.name, tensor_type) # For each model execution, we call a parsing function to create a computational (sub-)graph because ONNX has no # model/layer sharing. for node in _extract_inbound_nodes(model): _parse_keras(topology, scope, model, node) topology.root_names = [variable.onnx_name for variable in scope.variables.values()] return topology
[ 2, 16529, 45537, 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, 198, 2, 5964, 1321, 13, 198, 2, 16529, 35937, 198, 1...
3.086957
966
"""Objects representing regions in space.""" import math import random import itertools import numpy import scipy.spatial import shapely.geometry import shapely.ops from scenic.core.distributions import Samplable, RejectionException, needsSampling from scenic.core.lazy_eval import valueInContext from scenic.core.vectors import Vector, OrientedVector, VectorDistribution from scenic.core.geometry import RotatedRectangle from scenic.core.geometry import sin, cos, hypot, findMinMax, pointIsInCone, averageVectors from scenic.core.geometry import headingOfSegment, triangulatePolygon, plotPolygon, polygonUnion from scenic.core.type_support import toVector from scenic.core.utils import cached, areEquivalent def regionFromShapelyObject(obj, orientation=None): """Build a 'Region' from Shapely geometry.""" assert obj.is_valid, obj if obj.is_empty: return nowhere elif isinstance(obj, (shapely.geometry.Polygon, shapely.geometry.MultiPolygon)): return PolygonalRegion(polygon=obj, orientation=orientation) elif isinstance(obj, (shapely.geometry.LineString, shapely.geometry.MultiLineString)): return PolylineRegion(polyline=obj, orientation=orientation) else: raise RuntimeError(f'unhandled type of Shapely geometry: {obj}') everywhere = AllRegion('everywhere') nowhere = EmptyRegion('nowhere')
[ 37811, 10267, 82, 10200, 7652, 287, 2272, 526, 15931, 198, 198, 11748, 10688, 198, 11748, 4738, 198, 11748, 340, 861, 10141, 198, 198, 11748, 299, 32152, 198, 11748, 629, 541, 88, 13, 2777, 34961, 198, 11748, 5485, 306, 13, 469, 15748, ...
3.352041
392
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import logging import time import json import click import matplotlib.pyplot as plt import orangery as o from orangery.cli import defaults, util from orangery.tools.plotting import get_scale_factor
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 25064, 198, 11748, 18931, 198, 11748, 640, 198, 198, 11748, 33918, 198, 11748, 3904, 198, 11748, 2603, 29487,...
3.011628
86
import os, sys DICTIONARY_FILE = os.path.join(sys.prefix, 'dictionaries/ice_pron_dict_standard_clear.csv') HEAD_FILE = os.path.join(sys.prefix, 'data/head_map.csv') MODIFIER_FILE = os.path.join(sys.prefix, 'data/modifier_map.csv') VOWELS_FILE = os.path.join(sys.prefix, 'data/vowels_sampa.txt') CONS_CLUSTERS_FILE = os.path.join(sys.prefix, 'data/cons_clusters_sampa.txt')
[ 11748, 28686, 11, 25064, 198, 35, 18379, 2849, 13153, 62, 25664, 796, 28686, 13, 6978, 13, 22179, 7, 17597, 13, 40290, 11, 705, 67, 2867, 3166, 14, 501, 62, 31186, 62, 11600, 62, 20307, 62, 20063, 13, 40664, 11537, 198, 37682, 62, 2...
2.426752
157
from pylabelbuddy import _annotations_notebook
[ 6738, 279, 2645, 9608, 65, 21584, 1330, 4808, 34574, 602, 62, 11295, 2070, 628 ]
3.428571
14
from flask import Flask from flask_cors import CORS from flask_restful import Api from flask_sqlalchemy import SQLAlchemy from flask_jwt_extended import JWTManager app = Flask(__name__) CORS(app) api = Api(app) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SECRET_KEY'] = 'some-secret-string' app.config['JWT_SECRET_KEY'] = 'jwt-secret-string' app.config['JWT_BLACKLIST_ENABLED'] = True app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access', 'refresh'] db = SQLAlchemy(app) jwt = JWTManager(app) import models, resources, views api.add_resource(resources.UserRegistration, '/registration') api.add_resource(resources.UserLogin, '/login') api.add_resource(resources.UserLogoutAccess, '/logout/access') api.add_resource(resources.UserLogoutRefresh, '/logout/refresh') api.add_resource(resources.TokenRefresh, '/token/refresh') api.add_resource(resources.AllUsers, '/users') api.add_resource(resources.SecretResource, '/secret')
[ 6738, 42903, 1330, 46947, 198, 6738, 42903, 62, 66, 669, 1330, 327, 20673, 198, 6738, 42903, 62, 2118, 913, 1330, 5949, 72, 198, 6738, 42903, 62, 25410, 282, 26599, 1330, 16363, 2348, 26599, 198, 6738, 42903, 62, 73, 46569, 62, 2302, ...
2.848315
356
nome = input('Qual o seu nome? ') dia = input('Que dia do ms voc nasceu? ') mes = input('Qual o ms em que voc nasceu? ') ano = input('Qual o ano em que voc nasceu? ') print(nome, 'nasceu em', dia,'de',mes,'do ano',ano)
[ 77, 462, 796, 5128, 10786, 46181, 267, 384, 84, 299, 462, 30, 705, 8, 198, 67, 544, 796, 5128, 10786, 15681, 288, 544, 466, 13845, 12776, 25221, 344, 84, 30, 705, 8, 198, 6880, 796, 5128, 10786, 46181, 267, 13845, 795, 8358, 12776, ...
2.369565
92
# ---------------------------------------------------------------------- # CISCO-VLAN-MEMBERSHIP-MIB # Compiled MIB # Do not modify this file directly # Run ./noc mib make-cmib instead # ---------------------------------------------------------------------- # Copyright (C) 2007-2020 The NOC Project # See LICENSE for details # ---------------------------------------------------------------------- # MIB Name NAME = "CISCO-VLAN-MEMBERSHIP-MIB" # Metadata LAST_UPDATED = "2007-12-14" COMPILED = "2020-01-19" # MIB Data: name -> oid MIB = { "CISCO-VLAN-MEMBERSHIP-MIB::ciscoVlanMembershipMIB": "1.3.6.1.4.1.9.9.68", "CISCO-VLAN-MEMBERSHIP-MIB::ciscoVlanMembershipMIBObjects": "1.3.6.1.4.1.9.9.68.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmVmps": "1.3.6.1.4.1.9.9.68.1.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsVQPVersion": "1.3.6.1.4.1.9.9.68.1.1.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsRetries": "1.3.6.1.4.1.9.9.68.1.1.2", "CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsReconfirmInterval": "1.3.6.1.4.1.9.9.68.1.1.3", "CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsReconfirm": "1.3.6.1.4.1.9.9.68.1.1.4", "CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsReconfirmResult": "1.3.6.1.4.1.9.9.68.1.1.5", "CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsCurrent": "1.3.6.1.4.1.9.9.68.1.1.6", "CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsTable": "1.3.6.1.4.1.9.9.68.1.1.7", "CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsEntry": "1.3.6.1.4.1.9.9.68.1.1.7.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsIpAddress": "1.3.6.1.4.1.9.9.68.1.1.7.1.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsPrimary": "1.3.6.1.4.1.9.9.68.1.1.7.1.2", "CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsRowStatus": "1.3.6.1.4.1.9.9.68.1.1.7.1.3", "CISCO-VLAN-MEMBERSHIP-MIB::vmMembership": "1.3.6.1.4.1.9.9.68.1.2", "CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipSummaryTable": "1.3.6.1.4.1.9.9.68.1.2.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipSummaryEntry": "1.3.6.1.4.1.9.9.68.1.2.1.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipSummaryVlanIndex": "1.3.6.1.4.1.9.9.68.1.2.1.1.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipSummaryMemberPorts": "1.3.6.1.4.1.9.9.68.1.2.1.1.2", "CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipSummaryMember2kPorts": "1.3.6.1.4.1.9.9.68.1.2.1.1.3", "CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipTable": "1.3.6.1.4.1.9.9.68.1.2.2", "CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipEntry": "1.3.6.1.4.1.9.9.68.1.2.2.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmVlanType": "1.3.6.1.4.1.9.9.68.1.2.2.1.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmVlan": "1.3.6.1.4.1.9.9.68.1.2.2.1.2", "CISCO-VLAN-MEMBERSHIP-MIB::vmPortStatus": "1.3.6.1.4.1.9.9.68.1.2.2.1.3", "CISCO-VLAN-MEMBERSHIP-MIB::vmVlans": "1.3.6.1.4.1.9.9.68.1.2.2.1.4", "CISCO-VLAN-MEMBERSHIP-MIB::vmVlans2k": "1.3.6.1.4.1.9.9.68.1.2.2.1.5", "CISCO-VLAN-MEMBERSHIP-MIB::vmVlans3k": "1.3.6.1.4.1.9.9.68.1.2.2.1.6", "CISCO-VLAN-MEMBERSHIP-MIB::vmVlans4k": "1.3.6.1.4.1.9.9.68.1.2.2.1.7", "CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipSummaryExtTable": "1.3.6.1.4.1.9.9.68.1.2.3", "CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipSummaryExtEntry": "1.3.6.1.4.1.9.9.68.1.2.3.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipPortRangeIndex": "1.3.6.1.4.1.9.9.68.1.2.3.1.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipSummaryExtPorts": "1.3.6.1.4.1.9.9.68.1.2.3.1.2", "CISCO-VLAN-MEMBERSHIP-MIB::vmVlanCreationMode": "1.3.6.1.4.1.9.9.68.1.2.4", "CISCO-VLAN-MEMBERSHIP-MIB::vmStatistics": "1.3.6.1.4.1.9.9.68.1.3", "CISCO-VLAN-MEMBERSHIP-MIB::vmVQPQueries": "1.3.6.1.4.1.9.9.68.1.3.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmVQPResponses": "1.3.6.1.4.1.9.9.68.1.3.2", "CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsChanges": "1.3.6.1.4.1.9.9.68.1.3.3", "CISCO-VLAN-MEMBERSHIP-MIB::vmVQPShutdown": "1.3.6.1.4.1.9.9.68.1.3.4", "CISCO-VLAN-MEMBERSHIP-MIB::vmVQPDenied": "1.3.6.1.4.1.9.9.68.1.3.5", "CISCO-VLAN-MEMBERSHIP-MIB::vmVQPWrongDomain": "1.3.6.1.4.1.9.9.68.1.3.6", "CISCO-VLAN-MEMBERSHIP-MIB::vmVQPWrongVersion": "1.3.6.1.4.1.9.9.68.1.3.7", "CISCO-VLAN-MEMBERSHIP-MIB::vmInsufficientResources": "1.3.6.1.4.1.9.9.68.1.3.8", "CISCO-VLAN-MEMBERSHIP-MIB::vmStatus": "1.3.6.1.4.1.9.9.68.1.4", "CISCO-VLAN-MEMBERSHIP-MIB::vmNotificationsEnabled": "1.3.6.1.4.1.9.9.68.1.4.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmVoiceVlan": "1.3.6.1.4.1.9.9.68.1.5", "CISCO-VLAN-MEMBERSHIP-MIB::vmVoiceVlanTable": "1.3.6.1.4.1.9.9.68.1.5.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmVoiceVlanEntry": "1.3.6.1.4.1.9.9.68.1.5.1.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmVoiceVlanId": "1.3.6.1.4.1.9.9.68.1.5.1.1.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmVoiceVlanCdpVerifyEnable": "1.3.6.1.4.1.9.9.68.1.5.1.1.2", "CISCO-VLAN-MEMBERSHIP-MIB::vmNotifications": "1.3.6.1.4.1.9.9.68.2", "CISCO-VLAN-MEMBERSHIP-MIB::vmNotificationsPrefix": "1.3.6.1.4.1.9.9.68.2.0", "CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsChange": "1.3.6.1.4.1.9.9.68.2.0.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmMIBConformance": "1.3.6.1.4.1.9.9.68.3", "CISCO-VLAN-MEMBERSHIP-MIB::vmMIBCompliances": "1.3.6.1.4.1.9.9.68.3.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmMIBGroups": "1.3.6.1.4.1.9.9.68.3.2", } DISPLAY_HINTS = {}
[ 2, 16529, 23031, 198, 2, 36159, 8220, 12, 53, 25697, 12, 44, 3620, 33, 4877, 39, 4061, 12, 8895, 33, 198, 2, 3082, 3902, 337, 9865, 198, 2, 2141, 407, 13096, 428, 2393, 3264, 198, 2, 5660, 24457, 77, 420, 285, 571, 787, 12, 1121...
1.578373
3,209
# (C) Datadog, Inc. 2019-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) import pytest from mock import MagicMock from requests import HTTPError from datadog_checks.base import AgentCheck from datadog_checks.dev.http import MockResponse from .common import HARBOR_COMPONENTS, HARBOR_VERSION, VERSION_1_5, VERSION_1_6, VERSION_1_8 def test_api__make_get_request(harbor_api): harbor_api.http = MagicMock() harbor_api.http.get = MagicMock(return_value=MockResponse(json_data={'json': True})) assert harbor_api._make_get_request('{base_url}/api/path') == {"json": True} harbor_api.http.get = MagicMock(return_value=MockResponse(status_code=500)) with pytest.raises(HTTPError): harbor_api._make_get_request('{base_url}/api/path') def test_api__make_paginated_get_request(harbor_api): expected_result = [{'item': i} for i in range(20)] paginated_result = [[expected_result[i], expected_result[i + 1]] for i in range(0, len(expected_result) - 1, 2)] values = [] for r in paginated_result: values.append(MockResponse(json_data=r, headers={'link': 'Link: <unused_url>; rel=next; type="text/plain"'})) values[-1].headers.pop('link') harbor_api.http = MagicMock() harbor_api.http.get = MagicMock(side_effect=values) assert harbor_api._make_paginated_get_request('{base_url}/api/path') == expected_result def test_api__make_post_request(harbor_api): harbor_api.http = MagicMock() harbor_api.http.post = MagicMock(return_value=MockResponse(json_data={'json': True})) assert harbor_api._make_post_request('{base_url}/api/path') == {"json": True} harbor_api.http.post = MagicMock(return_value=MockResponse(status_code=500)) with pytest.raises(HTTPError): harbor_api._make_post_request('{base_url}/api/path')
[ 2, 357, 34, 8, 16092, 324, 519, 11, 3457, 13, 13130, 12, 25579, 198, 2, 1439, 2489, 10395, 198, 2, 49962, 739, 257, 513, 12, 565, 682, 347, 10305, 3918, 5964, 357, 3826, 38559, 24290, 8, 198, 11748, 12972, 9288, 198, 6738, 15290, ...
2.636234
701
# module for adapting templates on the fly if components are reused # check that all reused components are defined consistently -> else: exception # check and return number of reuses # return adapted templates with adapted reused components and exactly one arc per port (allows proportional output)
[ 2, 8265, 329, 35135, 24019, 319, 262, 6129, 611, 6805, 389, 46823, 201, 198, 201, 198, 201, 198, 2, 2198, 326, 477, 46823, 6805, 389, 5447, 9835, 4613, 2073, 25, 6631, 201, 198, 201, 198, 201, 198, 2, 2198, 290, 1441, 1271, 286, 3...
4.375
72
# Copyright 2012 Nebula, 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. from vsm_dashboard.api import swift from .utils import TestDataContainer
[ 2, 15069, 2321, 46915, 11, 3457, 13, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, 220, 220, 407, 779, 428, 2393, 2845, 287, 11846, 351, ...
3.424242
198
# Copyright (C) 2013 Deutsche Telekom AG # All Rights Reserved. # # 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. """Base class for all backup drivers.""" import abc from oslo_config import cfg from oslo_log import log as logging from oslo_serialization import jsonutils import six from cinder.db import base from cinder import exception from cinder.i18n import _ from cinder import keymgr as key_manager service_opts = [ cfg.IntOpt('backup_metadata_version', default=2, help='Backup metadata version to be used when backing up ' 'volume metadata. If this number is bumped, make sure the ' 'service doing the restore supports the new version.'), cfg.IntOpt('backup_object_number_per_notification', default=10, help='The number of chunks or objects, for which one ' 'Ceilometer notification will be sent'), cfg.IntOpt('backup_timer_interval', default=120, help='Interval, in seconds, between two progress notifications ' 'reporting the backup status'), ] CONF = cfg.CONF CONF.register_opts(service_opts) LOG = logging.getLogger(__name__)
[ 2, 15069, 357, 34, 8, 2211, 36763, 14318, 74, 296, 13077, 198, 2, 1439, 6923, 33876, 13, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, ...
2.77193
627
from .chainOpen import chainOpen __all__ = [ 'chainOpen' ]
[ 6738, 764, 7983, 11505, 1330, 6333, 11505, 201, 198, 201, 198, 834, 439, 834, 796, 685, 201, 198, 220, 220, 220, 705, 7983, 11505, 6, 201, 198, 60 ]
2.392857
28
import unittest from QuerySciGraph import QuerySciGraph if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 6738, 43301, 50, 979, 37065, 1330, 43301, 50, 979, 37065, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 555, 715, 395, 13, 12417, 3419, 198 ]
2.717949
39
from typing import Any from ledis import Ledis from ledis.exceptions import InvalidUsage
[ 6738, 19720, 1330, 4377, 198, 198, 6738, 2957, 271, 1330, 22964, 271, 198, 6738, 2957, 271, 13, 1069, 11755, 1330, 17665, 28350, 628 ]
3.956522
23
#group 1: Question 1(b) # A control system for positioning the head of a laser printer has the closed loop transfer function: # !pip install control import matplotlib.pyplot as plt import control a=10 #Value for a b=50 #value for b sys1 = control.tf(20*b,[1,20+a,b+20*a,20*b]) print('3rd order system transfer function T1(s)=',sys1) sys2=control.tf(b,[1,a,b]) print('2nd order system transfer funtion T2(s)',sys2) value = sys1.pole() list_of_poles = [pole.round(2) for pole in value] print('poles',list_of_poles) y1=control.step_response(sys1) y2=control.step_response(sys2) plt.plot(y1[0],y1[1],'r--', label='3rd order actual system') plt.plot(y2[0],y2[1],'g', label='2nd order approximation system') plt.legend() plt.grid() plt.xlabel('time (s)') plt.ylabel('step response y(t)') plt.title('step response comparison of 3rd and 2nd order system') plt.show()
[ 2, 8094, 352, 25, 18233, 352, 7, 65, 8, 198, 2, 317, 1630, 1080, 329, 22097, 262, 1182, 286, 257, 12855, 20632, 468, 262, 4838, 9052, 4351, 2163, 25, 198, 2, 5145, 79, 541, 2721, 1630, 220, 198, 198, 11748, 2603, 29487, 8019, 13, ...
2.547059
340
import re from precise_bbcode.bbcode.tag import BBCodeTag from precise_bbcode.tag_pool import tag_pool color_re = re.compile(r'^([a-z]+|#[0-9abcdefABCDEF]{3,6})$') tag_pool.register_tag(SubTag) tag_pool.register_tag(PreTag) tag_pool.register_tag(SizeTag) tag_pool.register_tag(FruitTag) tag_pool.register_tag(PhoneLinkTag) tag_pool.register_tag(StartsWithATag) tag_pool.register_tag(RoundedBBCodeTag)
[ 11748, 302, 198, 198, 6738, 7141, 62, 11848, 8189, 13, 11848, 8189, 13, 12985, 1330, 7823, 1098, 24835, 198, 6738, 7141, 62, 11848, 8189, 13, 12985, 62, 7742, 1330, 7621, 62, 7742, 628, 198, 8043, 62, 260, 796, 302, 13, 5589, 576, 7...
2.473054
167
## Program: VMTK ## Language: Python ## Date: January 10, 2018 ## Version: 1.4 ## Copyright (c) Richard Izzo, Luca Antiga, All rights reserved. ## See LICENSE file for details. ## This software is distributed WITHOUT ANY WARRANTY; without even ## the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR ## PURPOSE. See the above copyright notices for more information. ## Note: this code was contributed by ## Richard Izzo (Github @rlizzo) ## University at Buffalo import pytest import vmtk.vmtksurfacescaling as scaling
[ 2235, 6118, 25, 569, 13752, 42, 198, 2235, 15417, 25, 220, 11361, 198, 2235, 7536, 25, 220, 220, 220, 220, 220, 3269, 838, 11, 2864, 198, 2235, 10628, 25, 220, 220, 352, 13, 19, 198, 198, 2235, 220, 220, 15069, 357, 66, 8, 6219, ...
3.015625
192
# -*- coding: utf8 -*- # Copyright 1999-2017 Tencent Ltd. # # 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 tencentcloud.common.abstract_model import AbstractModel
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 23, 532, 9, 12, 198, 2, 15069, 7358, 12, 5539, 9368, 1087, 12052, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 4...
3.077739
283
#!/usr/bin/env python """Distribution functions This module provides functions for dealing with normal distributions and generating error maps. When called directly as main, it allows for converting a threshold map into an error map. ``` $ python -m mlcsim.dist --help usage: dist.py [-h] [-b {1,2,3,4}] -f F [-o O] options: -h, --help show this help message and exit -b {1,2,3,4} bits per cell -f F Threshold map json to convert -o O output to file ``` """ import argparse import json from pprint import pprint from typing import Dict, List import numpy as np from scipy import stats as ss # type: ignore # https://stackoverflow.com/a/32574638/9047818 # https://stackoverflow.com/a/13072714/9047818 def normalMidpoint(mean_a: float, mean_b: float, std_a: float, std_b: float) -> float: """Find the midpoint between two normal distributions Args: mean_a (float): Mean of first distribution mean_b (float): Mean of second distribution std_a (float): Std dev of first distribution std_b (float): Std dev of second distribution Returns: float: Midpoint between distributions """ a = 1 / (2 * std_a**2) - 1 / (2 * std_b**2) b = mean_b / (std_b**2) - mean_a / (std_a**2) c = ( mean_a**2 / (2 * std_a**2) - mean_b**2 / (2 * std_b**2) - np.log(std_b / std_a) ) roots = np.roots([a, b, c]) masked = np.ma.masked_outside(roots, mean_a, mean_b) return float(masked[~masked.mask][0][0]) # https://www.askpython.com/python/normal-distribution def normalChance(mean: float, stdev: float, thr: float) -> float: """Find the chance of a normal distribution above/below a given value Args: mean (float): Mean of the distribution stdev (float): Std dev of the distribution thr (float): Threshold to check above/below Returns: float: Chance for threshold to end up above/below the given point in the distribution """ chance = ss.norm(loc=mean, scale=stdev).cdf(thr) return float(chance if mean > thr else 1 - chance) def genErrorMap(thr_maps: Dict[str, List[List[float]]], bpc: int) -> List[List[float]]: """Generate an error map from a threshold map Args: thr_maps (dict): Threshold map bpc (int): Bits per cell Raises: ValueError: if the given bpc is not in the threshold map Returns: list: Error map from the threshold map """ if str(bpc) not in thr_maps.keys(): raise ValueError(f"Threshold map does not have values for {bpc} levels") thr_map: List[List[float]] = thr_maps[str(bpc)] err_map = [[0.0]] for i in range(len(thr_map) - 1): mid = normalMidpoint( thr_map[i][0], thr_map[i + 1][0], thr_map[i][1], thr_map[i + 1][1] ) up = normalChance(thr_map[i][0], thr_map[i][1], mid) dn = normalChance(thr_map[i + 1][0], thr_map[i + 1][1], mid) err_map[i].append(up) err_map.append([dn]) err_map[-1].append(0.0) return err_map if __name__ == "__main__": _main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 37811, 20344, 3890, 5499, 198, 198, 1212, 8265, 3769, 5499, 329, 7219, 351, 3487, 24570, 198, 392, 15453, 4049, 8739, 13, 198, 198, 2215, 1444, 3264, 355, 1388, 11, 340, 3578, 329...
2.435055
1,278
earth = { "Asia": {'Japan': ("Tokyo", 377975, 125620000)}, "Europe": {'Austria': ("Vienna", 83800, 8404000), 'Germany': ("Berlin", 357000, 81751000), 'Great Britain': ("London", 244800, 62700000), 'Iceland': ("Reykjavk", 103000, 317630), 'Italy': ("Rome", 301400, 60605000), 'Spain': ("Madrid", 506000, 46162000), 'Ukraine': ("Kyiv", 603700, 45562000)} } input_str = input("Enter the name of the continent or country: ") if input_str.title() in earth.keys(): Earth(input_str).print_continent() else: print(Earth(continent=None).print_country(input_str))
[ 16442, 796, 1391, 198, 220, 220, 220, 366, 38555, 1298, 198, 220, 220, 220, 220, 220, 220, 220, 1391, 6, 16504, 10354, 5855, 19042, 8226, 1600, 513, 40393, 2425, 11, 1105, 3980, 2167, 405, 8, 5512, 198, 220, 220, 220, 366, 16112, 12...
2.228374
289
"""Declare runtime dependencies These are needed for local dev, and users must install them as well. See https://docs.bazel.build/versions/main/skylark/deploying.html#dependencies """ load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe") # WARNING: any changes in this function may be BREAKING CHANGES for users # because we'll fetch a dependency which may be different from one that # they were previously fetching later in their WORKSPACE setup, and now # ours took precedence. Such breakages are challenging for users, so any # changes in this function should be marked as BREAKING in the commit message # and released only in semver majors.
[ 37811, 37835, 533, 19124, 20086, 198, 198, 4711, 389, 2622, 329, 1957, 1614, 11, 290, 2985, 1276, 2721, 606, 355, 880, 13, 198, 6214, 3740, 1378, 31628, 13, 65, 41319, 13, 11249, 14, 47178, 14, 12417, 14, 15688, 75, 668, 14, 2934, 1...
3.594059
202
import pytest from playhouse.test_utils import assert_query_count from data.registry_model import registry_model from data.database import Manifest from endpoints.api.test.shared import conduct_api_call from endpoints.test.shared import client_with_identity from endpoints.api.tag import RepositoryTag, RestoreTag, ListRepositoryTags from test.fixtures import *
[ 11748, 12972, 9288, 198, 198, 6738, 711, 4803, 13, 9288, 62, 26791, 1330, 6818, 62, 22766, 62, 9127, 198, 198, 6738, 1366, 13, 2301, 4592, 62, 19849, 1330, 20478, 62, 19849, 198, 6738, 1366, 13, 48806, 1330, 36757, 198, 198, 6738, 886...
3.627451
102
import json import os import random import requests from passlib.hash import pbkdf2_sha256 as pbk from PyQt5.QtSql import QSqlDatabase, QSqlQuery from pprint import pprint ENCODING = 'utf-8' DB_PATH = os.path.join(os.path.curdir, 'inventory.db') def scrambleWord(word): """Randomize the letters in word and return the resulting string.""" word_list = list(word) random.shuffle(word_list) word = ''.join(word_list) return word def generateItems(): """Generate a dictionary of retail products and store the data in items.json. Pulls a list of items and artificially doubles it with scrambled item names. Each item is given a random PLU, UPC, and department number. Each dictionary key is the item's PLU. """ response = requests.get('https://www.randomlists.com/data/things.json') json_data = response.json() items = json_data['RandL']['items'] #double sample size by scrambling item names scrambled_list = [] for item in items: scrambled_item = scrambleWord(item) scrambled_list.append(scrambled_item) items = items + scrambled_list data = {} for item in items: random.seed(item) upc = random.randint(100000000000, 999999999999) plu = random.randint(1000, 9999999) department = (plu % 7) + 1 print('UPC:{0} | PLU:{1} | Item:{2} | D{3}'.format(upc, plu, item, department)) if plu in data: print('Duplicate found: {}'.format(plu)) continue data[plu] = {'upc':upc, 'department':department, 'model':item} with open('items.json', 'w') as f: json.dump(data, f) def generatePO(): """Create dumby Purchase Orders and store them in pos.json. Each PO is asigned one random vendor and department number, along with a random length list of items belonging to said department. Returns: True if items.json successfully opens, False otherwise. """ try: with open('items.json', 'r') as f: items_dict = json.load(f) except FileNotFoundError: return False vendors = ['Dyson', 'Ingrammicro', 'LKG', 'Inland', 'Sandisk', 'Seagate', 'Hasbro', 'Mattel',\ 'Gear Head', 'Logitech', 'NTE', 'Dell', 'Microsoft', 'Right Stuff', 'Alliance', 'Energizer'] po_dict = {} for i in range(50): po_num = 24000000 + random.randint(1, 999999) if po_num in po_dict: continue po_dict[po_num] = {'department': (po_num % 7) + 1, 'items': {}, 'vendor': random.choice(vendors)} for key in items_dict: match_found = False loops = 0 while not match_found: loops += 1 if loops > 200: print('\n\nToo many loops.\n\n') break po, department = random.choice(list(po_dict.items())) department = department['department'] print('PO department: {}'.format(department)) print('item plu: {} department: {}'.format(key, items_dict[key]['department'])) if items_dict[key]['department'] == department: max_count = random.randint(1, 20) po_dict[po]['items'][key] = max_count match_found = True with open('pos.json', 'w') as f: json.dump(po_dict, f) return True def fillDB(): """Create a database and populate two tables(named items and purchase_order). The 'items' and 'purchase_order' tables are populated with the data from items.json and pos.json respectively. """ with open('items.json') as f: data = json.load(f) db = QSqlDatabase.addDatabase('QSQLITE') db.setDatabaseName(DB_PATH) if not db.open(): print('DB could not be opened') error = QSqlDatabase.lastError() print(error.text()) return False query = QSqlQuery() if query.exec_("drop table items"): print('successfully dropped table') else: print('unsuccessfully dropped table') print(query.lastError().text()) if query.exec_("create table items(plu int primary key, upc varchar(12) unique, " "model varchar(20), department int)"): print('success') else: print('failure') print(query.lastError().text()) for key in data: if query.exec_("insert into items values({}, '{}', '{}', {})".format(key, data[key]['upc'], data[key]['model'], data[key]['department'])): print("values({}, {}, {}, {}) successfully inserted.".format(key, data[key]['upc'], data[key]['model'], data[key]['department'])) else: print("values({}, {}, {}, {}) unsuccessfully inserted.".format(key, data[key]['upc'], data[key]['model'], data[key]['department'])) print(query.lastError().text()) with open('pos.json') as f: po_dict = json.load(f) if query.exec_("drop table purchase_order"): print('successfully dropped table') else: print('unsuccessfully dropped table') print(query.lastError().text()) if query.exec_("create table purchase_order(po int primary key, vendor varchar(30), " "department int, items blob)"): print('success') else: print('failure') print(query.lastError().text()) for key in po_dict: item_string = json.dumps(po_dict[key]['items']) item_blob = item_string.encode(ENCODING) if query.exec_("insert into purchase_order values({}, '{}', {}, '{}')"\ .format(key, po_dict[key]['vendor'], po_dict[key]['department'], item_string)): print("values({}, {}, {}, {}) successfully inserted."\ .format(key, po_dict[key]['vendor'], po_dict[key]['department'], item_string)) else: print("values({}, {}, {}, {}) unsuccessfully inserted."\ .format(key, po_dict[key]['vendor'], po_dict[key]['department'], item_blob)) print(query.lastError().text()) if __name__ == '__main__': generateItems() generatePO() fillDB() createEmployeeTable() testHashVerification('Terry')
[ 11748, 33918, 198, 11748, 28686, 198, 11748, 4738, 198, 11748, 7007, 198, 6738, 1208, 8019, 13, 17831, 1330, 279, 65, 74, 7568, 17, 62, 26270, 11645, 355, 279, 65, 74, 198, 6738, 9485, 48, 83, 20, 13, 48, 83, 50, 13976, 1330, 1195, ...
2.339104
2,657
import requests from flask import abort, redirect, request, url_for from lnurl import LnurlWithdrawResponse, handle as handle_lnurl from lnurl.exceptions import LnurlException from time import sleep from lnbits.core import core_app from lnbits.helpers import Status from lnbits.settings import WALLET from ..crud import create_account, get_user, create_wallet, create_payment
[ 11748, 7007, 198, 198, 6738, 42903, 1330, 15614, 11, 18941, 11, 2581, 11, 19016, 62, 1640, 198, 6738, 300, 77, 6371, 1330, 406, 77, 6371, 3152, 19334, 31077, 11, 5412, 355, 5412, 62, 18755, 6371, 198, 6738, 300, 77, 6371, 13, 1069, ...
3.486239
109
# Import libraries import argparse from azureml.core import Run import joblib import json import os import pandas as pd import shutil # Import functions from train.py from train import split_data, train_model, get_model_metrics # Get the output folder for the model from the '--output_folder' parameter parser = argparse.ArgumentParser() parser.add_argument('--output_folder', type=str, dest='output_folder', default="outputs") args = parser.parse_args() print(args) output_folder = args.output_folder # Get the experiment run context run = Run.get_context() # load the safe driver prediction dataset train_df = pd.read_csv('porto_seguro_safe_driver_prediction_input.csv') # Load the parameters for training the model from the file with open("parameters.json") as f: pars = json.load(f) parameters = pars["training"] # Log each of the parameters to the run for param_name, param_value in parameters.items(): run.log(param_name, param_value) # Call the functions defined in this file train_data, valid_data = split_data(train_df) data = [train_data, valid_data] model = train_model(data, parameters) # Print the resulting metrics for the model model_metrics = get_model_metrics(model, data) print(model_metrics) for k, v in model_metrics.items(): run.log(k, v) # Save the trained model to the output folder os.makedirs(output_folder, exist_ok=True) output_path = output_folder + "/porto_seguro_safe_driver_model.pkl" joblib.dump(value=model, filename=output_path) run.complete()
[ 2, 17267, 12782, 198, 11748, 1822, 29572, 198, 6738, 35560, 495, 4029, 13, 7295, 1330, 5660, 198, 11748, 1693, 8019, 198, 11748, 33918, 198, 11748, 28686, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 4423, 346, 198, 198, 2, 17267, ...
3.15272
478
from lua_imports import lua_importer lua_importer.register()
[ 6738, 300, 6413, 62, 320, 3742, 1330, 300, 6413, 62, 320, 26634, 198, 198, 40211, 62, 320, 26634, 13, 30238, 3419, 198 ]
2.818182
22
from sqlalchemy import Column, Integer, String, Float from app.database.base_class import Base
[ 6738, 44161, 282, 26599, 1330, 29201, 11, 34142, 11, 10903, 11, 48436, 198, 198, 6738, 598, 13, 48806, 13, 8692, 62, 4871, 1330, 7308, 628 ]
3.88
25
import glob import os import re import errno import shutil def get_sub_dirs_and_files(path, abs_path=False): """ Gets the direct child sub-files and sub-folders of the given directory Args: path: Absolute path to the directory abs_path: If set to True, it returns a list of absolute paths to the sub-directories and sub-files instead of directory names only Returns: dict: {"folders": [list of (if abs_path is True, then path to) sub-folders], "files": [list of (if abs_path is True, then path to) sub-files]} """ folders = get_sub_folders(path, abs_path=abs_path) files = get_sub_files(path, abs_path=abs_path) return {"folders": folders, "files": files} def get_sub_folders(path, abs_path=False): """ Gets the direct child sub-folders of the given directory Args: path: Absolute path to the directory abs_path: If set to True, it returns a list of absolute paths to the sub-directories instead of directory names only Returns: only_folders: [list of sub-folders] """ folders = [] temp = glob.glob(path + os.sep + "*") for folder in temp: if os.path.isdir(folder) and not folder.endswith('__pycache__'): folders.append(folder) only_folders = [f.replace("\\", '/') for f in folders] if not abs_path: only_folders = [f.rpartition('/')[2] for f in only_folders] return only_folders def get_sub_files(path, abs_path=False): """ Gets the direct child sub-files of the given directory Args: path: Absolute path to the directory abs_path: If set to True, it returns a list of absolute paths to the sub-files instead of file names only Returns: only_files: [list of sub-files] """ files = glob.glob(path + os.sep + "*.*") only_files = [f.replace("\\", '/') for f in files] if not abs_path: only_files = [f.rpartition('/')[2] for f in only_files] return only_files def get_abs_path(relative_path, base_path=None, silence_error=False): """ Gets the absolute path from the given relative_path and base_path Args: relative_path: relative path to the file/directory base_path: absolute path from where the relative path should be traced. If not provided, the current working directory path will be used. silence_error: Setting this to True would not verify if the directory exists Returns: path: absolute path derived from relative_path and base_path """ if base_path is None: base_path = os.getcwd() path = os.path.join(base_path.strip(), relative_path.strip()) if not silence_error and not os.path.exists(path): print("An Error Occurred: {0} does not exist".format(path)) path = None return path def get_parent_directory(directory_path, level=1): """ Gets the parent directory Args: directory_path: Absolute path to the file/dir who's parent needs to be returned level: Indicates how many levels up to go to find the parent eg: default of 1 goes one level up (to the parent directory) level=2 would get the grandparent directory Returns: """ if directory_path.endswith(os.sep): directory_path = directory_path[:-1] for i in range(0, level): directory_path = os.path.dirname(directory_path) return directory_path def get_paths_of_subfiles(parent_dir, extension=re.compile("\..*")): """ This function returns a list of all the sub-files inside the given directory Args: parent_dir: Absolute path to the directory extension: Regular Expression tha would match a file extension. If not provided, file paths of all extension will be returned Returns: file_path: Returns a list of paths to sub-files inside the parent_dir """ file_paths = [] sub_files_and_folders = get_sub_dirs_and_files(parent_dir, abs_path=True) for sub_file in sub_files_and_folders["files"]: if extension.match(os.path.splitext(sub_file)[1]): file_paths.append(sub_file) for sub_folder in sub_files_and_folders["folders"]: file_paths.extend(get_paths_of_subfiles(sub_folder, extension=extension)) return file_paths def get_dir_from_path(path): """ This function is wrapper function for os.path.basename. Args: path: a file path [Eg: /home/user/Documents/GitHub/warriorframework] Returns: The base directory name: [Eg: warriorframework] """ return os.path.basename(path) def get_parent_dir_path(path): """ This function is wrapper function for os.path.dirname(os.path.normpath(<path>)). Args: path: a file path [Eg: /home/user/Documents/GitHub/warriorframework] Returns: The parent directory path: [Eg: /home/user/Documents/GitHub] """ return os.path.dirname(os.path.normpath(path)) def join_path(path, *paths): """ This function is wrapper function for os.path.join. Args: path: a file path *paths: paths to be joined to the file path above Returns: Joined path """ return os.path.join(path, *paths) def get_relative_path(path, start_directory): """ This is a wrapper function for the os.path.relpath Args: path: Absolute path to the file/dir to which the relatove path needs to be calculated. start_directory: The absolute path to the starting directory Returns: rel_path: A relative path from start_directory """ if start_directory == "": print("-- Error -- start_directory is empty.") relpath = path else: try: relpath = os.path.relpath(path, start_directory) except Exception as e: print("-- Error -- {0}".format(e)) relpath = None else: if not relpath.startswith(".") and not relpath.startswith(os.sep): relpath = os.sep + relpath return relpath def get_direct_sub_files(path, abs_path=False, extension=re.compile("\..*")): """ Gets the direct child sub-files of the given directory Args: path: Absolute path to the directory abs_path: If set to True, it returns a list of absolute paths to the sub-files instead of file names only Returns: only_files: [list of sub-files] """ files = glob.glob(path + os.sep + "*.*") only_files = [f.replace("\\", '/') for f in files] if not abs_path: only_files = [f.rpartition('/')[2] for f in only_files] final_files = [] for sub_file in only_files: if extension.match(os.path.splitext(sub_file)[1]): final_files.append(sub_file) return final_files
[ 11748, 15095, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 11454, 3919, 198, 11748, 4423, 346, 628, 198, 4299, 651, 62, 7266, 62, 15908, 82, 62, 392, 62, 16624, 7, 6978, 11, 2352, 62, 6978, 28, 25101, 2599, 198, 220, 220, 220, 37...
2.515835
2,747
"""The `alignment` module provides an implementation of the Needleman-Wunsch alignment algorithm.""" from typing import Tuple, Literal, List from math import floor import numpy as np from stats import variance MOVE_DIAGONAL = 0 MOVE_RIGHT = 1 MOVE_DOWN = 2 EditMove = Literal[MOVE_DIAGONAL, MOVE_RIGHT, MOVE_DOWN] CHEMICAL_CLASS = { "A": "Purine", "G": "Purine", "T": "Pyrimidine", "C": "Pyrimidine", } def backtrack(quad: np.ndarray) -> EditMove: """Trace one step back through an edit matrix.""" if quad.shape == (0, 2): return MOVE_DOWN elif quad.shape == (2, 0): return MOVE_RIGHT # numpy's argmax doesn't allow for prioritizing non-indels next_pos = (0, 0) if quad[0, 1] > quad[next_pos]: next_pos = (0, 1) if quad[1, 0] > quad[next_pos]: next_pos = (1, 0) if next_pos == (0, 0): return MOVE_DIAGONAL elif next_pos == (0, 1): return MOVE_RIGHT else: return MOVE_DOWN def score_cell( quad: np.ndarray, top_char: str, left_char: str, nucleotides: bool, chemical_classes: dict, ) -> np.int: """Calculate the Needleman-Wunsch score for a cell.""" down_score = quad[0, 1] - 1 right_score = quad[1, 0] - 1 # Penalize transversions more heavily if nucleotides and chemical_classes[top_char] != chemical_classes[left_char]: down_score -= 1 right_score -= 1 diag_score = quad[0, 0] - 1 if top_char == left_char: diag_score += 2 return max([down_score, right_score, diag_score]) def align_sequences( top_seq: str, left_seq: str, nucleotides: bool = True ) -> AlignmentResult: """ This function aligns the two provided sequences using Needleman-Wunsch alignment. It uses a scoring scheme with a gap penalty of -1, a match bonus of 1, and a mismatch penalty of -1. If the two sequences are `nucleotides`, then an additional -1 penalty is applied to transversions. """ size1 = len(top_seq) + 1 size2 = len(left_seq) + 1 chemical_classes = CHEMICAL_CLASS # Copy this into the local scope so it can be accessed more quickly # Build search matrix search = np.zeros((size2, size1), dtype=np.int) search[0] = [i for i in range(0, -size1, -1)] search[:, 0] = [i for i in range(0, -size2, -1)] # Do scoring for x in range(1, size2): for y in range(1, size1): search[x, y] = score_cell( search[x - 1 : x + 1, y - 1 : y + 1], top_seq[y - 1], left_seq[x - 1], nucleotides, chemical_classes, ) search = search.T # Unwind result final_top = "" final_left = "" bt_x, bt_y = (size1 - 1, size2 - 1) while bt_x != 0 or bt_y != 0: next_move = backtrack(search[bt_x - 1 : bt_x + 1, bt_y - 1 : bt_y + 1]) if next_move == MOVE_DIAGONAL: final_top = top_seq[bt_x - 1] + final_top final_left = left_seq[bt_y - 1] + final_left bt_x -= 1 bt_y -= 1 elif next_move == MOVE_DOWN: final_top = "-" + final_top final_left = left_seq[bt_y - 1] + final_left bt_y -= 1 elif next_move == MOVE_RIGHT: final_top = top_seq[bt_x - 1] + final_top final_left = "-" + final_left bt_x -= 1 return AlignmentResult(final_top, final_left)
[ 37811, 464, 4600, 282, 16747, 63, 8265, 3769, 281, 7822, 286, 262, 10664, 293, 805, 12, 54, 13271, 354, 19114, 11862, 526, 15931, 198, 198, 6738, 19720, 1330, 309, 29291, 11, 25659, 1691, 11, 7343, 198, 6738, 10688, 1330, 4314, 198, 1...
2.173585
1,590
from mock_gripper_op import MockGripType from std_msgs.msg import Bool from erdos.op import Op from erdos.data_stream import DataStream from erdos.message import Message
[ 6738, 15290, 62, 70, 380, 2848, 62, 404, 1330, 44123, 38, 5528, 6030, 198, 6738, 14367, 62, 907, 14542, 13, 19662, 1330, 347, 970, 198, 198, 6738, 1931, 37427, 13, 404, 1330, 8670, 198, 6738, 1931, 37427, 13, 7890, 62, 5532, 1330, 6...
3.245283
53
# -*- coding: utf-8 -*- import pygraphviz as gv # type: ignore import itertools as it from typing import ( List, Optional, ) from pyfsa.lib.types import TransitionsTable def get_state_graph( transitions: TransitionsTable, start: Optional[str] = None, end: Optional[str] = None, nodes: Optional[List[str]] = None, name: str = 'output.png', draw: bool = True, engine: str = 'circo', ) -> gv.AGraph: ''' From a transition dictionary, creates a pygraphviz graph of all the possible states and how to reach the given state. Returns the resulting graph. ''' graph = gv.AGraph(directed=True, strict=False, ranksep='1') key_num = it.count() if nodes is not None: graph.add_nodes_from(nodes) else: graph.add_nodes_from(transitions.keys()) for node, transition_row in transitions.items(): for label, targets in transition_row.items(): for target in targets: graph.add_edge( node, target, key=f'{next(key_num)}', label=label, weight=1, ) if start: n: gv.Node = graph.get_node(start) n.attr['color'] = '#0000FF' n.attr['style'] = 'filled' if end: n = graph.get_node(end) n.attr['color'] = '#00FF00' n.attr['style'] = 'filled' if draw: graph.layout(prog=engine) graph.draw(name) return graph def verify_string( string: str, starting_state: str, final_state: str, transitions: TransitionsTable, ) -> bool: ''' Given a transitions table, a start and end state, and some string, verifies that executing the finite state machine on the given string produces the desired final state. ''' current_state = starting_state for letter in string: transition = transitions[current_state] current_state = transition[letter][0] return current_state == final_state def render_string_graph( string: str, start: str, end: str, transitions: TransitionsTable, name: str = 'output.png', draw: bool = True, engine: str = 'circo' ) -> gv.AGraph: ''' Given a string, a start state, an end state, end a transitions table, produces the graph resulting in the traversal of the string through the states defined in the transitions table. By default, it will output a png file of the result, but that can be suppressed. ''' graph = gv.AGraph(directed=True) graph.graph_attr['label'] = f'Evaluating {string}' node_names = it.count() current_state = start node_name = next(node_names) graph.add_node(node_name) current_node = gv.Node(graph, node_name) current_node.attr['label'] = current_state current_node.attr['fillcolor'] = '#0000FF' current_node.attr['style'] = 'filled' for letter in string: node_name = next(node_names) graph.add_node(node_name) next_node = gv.Node(graph, node_name) # TODO: The algorithm prioritizes just the first # found state, which may not produce a correct # answer. Needs to fix this next_state = transitions[current_state][letter][0] next_node.attr['label'] = next_state graph.add_edge(current_node, next_node, label=letter) current_node = next_node current_state = next_state if current_state == end: current_node.attr['style'] = 'filled' current_node.attr['fillcolor'] = '#00FF00' if draw: graph.layout(prog=engine) graph.draw(name) return graph
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 12972, 34960, 85, 528, 355, 308, 85, 220, 1303, 2099, 25, 8856, 198, 11748, 340, 861, 10141, 355, 340, 198, 198, 6738, 19720, 1330, 357, 198, 220, 220, 220, 734...
2.386909
1,543
import torch import sys import os sys.path.append(os.getcwd()) from utils.helper_modules import Sequential2 from unimodals.common_models import Linear, MLP, MaxOut_MLP from datasets.imdb.get_data import get_dataloader from fusions.common_fusions import Concat from objective_functions.objectives_for_supervised_learning import MFM_objective from objective_functions.recon import sigmloss1d from training_structures.Supervised_Learning import train, test filename = "best_mfm.pt" traindata, validdata, testdata = get_dataloader( "../video/multimodal_imdb.hdf5", "../video/mmimdb", vgg=True, batch_size=128) classes = 23 n_latent = 512 fuse = Sequential2(Concat(), MLP(2*n_latent, n_latent, n_latent//2)).cuda() encoders = [MaxOut_MLP(512, 512, 300, n_latent, False).cuda( ), MaxOut_MLP(512, 1024, 4096, n_latent, False).cuda()] head = Linear(n_latent//2, classes).cuda() decoders = [MLP(n_latent, 600, 300).cuda(), MLP(n_latent, 2048, 4096).cuda()] intermediates = [MLP(n_latent, n_latent//2, n_latent//2).cuda(), MLP(n_latent, n_latent//2, n_latent//2).cuda()] recon_loss = MFM_objective(2.0, [sigmloss1d, sigmloss1d], [ 1.0, 1.0], criterion=torch.nn.BCEWithLogitsLoss()) train(encoders, fuse, head, traindata, validdata, 1000, decoders+intermediates, early_stop=True, task="multilabel", objective_args_dict={"decoders": decoders, "intermediates": intermediates}, save=filename, optimtype=torch.optim.AdamW, lr=5e-3, weight_decay=0.01, objective=recon_loss) print("Testing:") model = torch.load(filename).cuda() test(model, testdata, method_name="MFM", dataset="imdb", criterion=torch.nn.BCEWithLogitsLoss(), task="multilabel")
[ 11748, 28034, 198, 11748, 25064, 198, 11748, 28686, 198, 198, 17597, 13, 6978, 13, 33295, 7, 418, 13, 1136, 66, 16993, 28955, 198, 198, 6738, 3384, 4487, 13, 2978, 525, 62, 18170, 1330, 24604, 1843, 17, 198, 6738, 28418, 375, 874, 13,...
2.445887
693
# Generated by Django 4.0.2 on 2022-06-01 04:43 from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 604, 13, 15, 13, 17, 319, 33160, 12, 3312, 12, 486, 8702, 25, 3559, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14208, 13, 9945, 13, 27530, 13, 2934, 1616, 295, ...
2.818182
44
# -*- coding: utf-8 -*- """ ViewFactor module - VF calculation helper files for bifacial-viewfactor @author Bill Marion @translated to python by sayala 06/09/17 """ # ensure python3 compatible division and printing from __future__ import division, print_function, absolute_import import math import numpy as np from sun import solarPos, sunIncident, perezComp, aOIcorrection import logging # TODO: set level or add formatters if more advanced logging required LOGGER = logging.getLogger(__name__) # only used to raise errors DTOR = math.pi / 180.0 # Factor for converting from degrees to radians def getBackSurfaceIrradiances(rowType, maxShadow, PVbackSurface, beta, sazm, dni, dhi, C, D, albedo, zen, azm, cellRows, pvBackSH, rearGroundGHI, frontGroundGHI, frontReflected, offset=0): """ This method calculates the AOI corrected irradiance on the back of the PV module/panel. 11/19/2015 Added rowType and other changes to distinguish between types of rows. 4/19/2016 Added input of offset of reference cell from PV module back (in PV panel slope lengths) for modeling Sara's reference cell measurements, should be set to zero for PV module cell irradiances. Added while loop so projected Xs aren't too negative causing array index problems (<0) 12/13/2016:: while (projectedX1 < -100.0 || projectedX2 < -100.0): # Offset so array indexes are >= -100.0 12/13/2016 projectedX1 += 100.0; projectedX2 += 100.0; Parameters ---------- rowType : str Type of row: "first", "interior", "last", or "single" maxShadow Maximum shadow length projected to the front(-) or rear (+) from the front of the module PVbackSurface PV module back surface material type, either "glass" or "ARglass" beta Tilt from horizontal of the PV modules/panels (deg) (for front surface) sazm Surface azimuth of PV panels (deg) (for front surface) dni Direct normal irradiance (W/m2) dhi Diffuse horizontal irradiance (W/m2) C Ground clearance of PV panel (in PV panel slope lengths) D Horizontal distance between rows of PV panels (in PV panel slope lengths) albedo Ground albedo zen Sun zenith (in radians) azm Sun azimuth (in radians) pvBackSH Decimal fraction of the back surface of the PV panel that is shaded, 0.0 to 1.0 rearGroundGHI : array of size [100] Global horizontal irradiance for each of 100 ground segments (W/m2) frontGroundGHI : array of size [100] Global horizontal irradiance for each of 100 ground segments (W/m2) frontReflected : array of size [cellRows] Irradiance reflected from the front of the PV module/panel (W/m2) in the row behind the one of interest offset Offset of reference cell from PV module back (in PV panel slope lengths), set to zero for PV module cell irradiances Returns ------- backGTI : array of size [cellRows] AOI corrected irradiance on back side of PV module/panel, one for each cell row (W/m2) aveGroundGHI : numeric Average GHI on ground under PV array Notes ----- 1-degree hemispherical segment AOI correction factor for glass (index=0) and ARglass (index=1) """ backGTI = [] SegAOIcor = [ [0.057563, 0.128570, 0.199651, 0.265024, 0.324661, 0.378968, 0.428391, 0.473670, 0.514788, 0.552454, 0.586857, 0.618484, 0.647076, 0.673762, 0.698029, 0.720118, 0.740726, 0.759671, 0.776946, 0.792833, 0.807374, 0.821010, 0.833534, 0.845241, 0.855524, 0.865562, 0.874567, 0.882831, 0.890769, 0.897939, 0.904373, 0.910646, 0.916297, 0.921589, 0.926512, 0.930906, 0.935179, 0.939074, 0.942627, 0.946009, 0.949096, 0.952030, 0.954555, 0.957157, 0.959669, 0.961500, 0.963481, 0.965353, 0.967387, 0.968580, 0.970311, 0.971567, 0.972948, 0.974114, 0.975264, 0.976287, 0.977213, 0.978142, 0.979057, 0.979662, 0.980460, 0.981100, 0.981771, 0.982459, 0.982837, 0.983199, 0.983956, 0.984156, 0.984682, 0.985026, 0.985364, 0.985645, 0.985954, 0.986241, 0.986484, 0.986686, 0.986895, 0.987043, 0.987287, 0.987388, 0.987541, 0.987669, 0.987755, 0.987877, 0.987903, 0.987996, 0.988022, 0.988091, 0.988104, 0.988114, 0.988114, 0.988104, 0.988091, 0.988022, 0.987996, 0.987903, 0.987877, 0.987755, 0.987669, 0.987541, 0.987388, 0.987287, 0.987043, 0.986895, 0.986686, 0.986484, 0.986240, 0.985954, 0.985645, 0.985364, 0.985020, 0.984676, 0.984156, 0.983956, 0.983199, 0.982837, 0.982459, 0.981771, 0.981100, 0.980460, 0.979662, 0.979057, 0.978142, 0.977213, 0.976287, 0.975264, 0.974114, 0.972947, 0.971567, 0.970311, 0.968580, 0.967387, 0.965353, 0.963481, 0.961501, 0.959671, 0.957157, 0.954555, 0.952030, 0.949096, 0.946009, 0.942627, 0.939074, 0.935179, 0.930906, 0.926512, 0.921589, 0.916297, 0.910646, 0.904373, 0.897939, 0.890769, 0.882831, 0.874567, 0.865562, 0.855524, 0.845241, 0.833534, 0.821010, 0.807374, 0.792833, 0.776946, 0.759671, 0.740726, 0.720118, 0.698029, 0.673762, 0.647076, 0.618484, 0.586857, 0.552454, 0.514788, 0.473670, 0.428391, 0.378968, 0.324661, 0.265024, 0.199651, 0.128570, 0.057563], [0.062742, 0.139913, 0.216842, 0.287226, 0.351055, 0.408796, 0.460966, 0.508397, 0.551116, 0.589915, 0.625035, 0.657029, 0.685667, 0.712150, 0.735991, 0.757467, 0.777313, 0.795374, 0.811669, 0.826496, 0.839932, 0.852416, 0.863766, 0.874277, 0.883399, 0.892242, 0.900084, 0.907216, 0.914023, 0.920103, 0.925504, 0.930744, 0.935424, 0.939752, 0.943788, 0.947313, 0.950768, 0.953860, 0.956675, 0.959339, 0.961755, 0.964039, 0.965984, 0.967994, 0.969968, 0.971283, 0.972800, 0.974223, 0.975784, 0.976647, 0.977953, 0.978887, 0.979922, 0.980773, 0.981637, 0.982386, 0.983068, 0.983759, 0.984436, 0.984855, 0.985453, 0.985916, 0.986417, 0.986934, 0.987182, 0.987435, 0.988022, 0.988146, 0.988537, 0.988792, 0.989043, 0.989235, 0.989470, 0.989681, 0.989857, 0.990006, 0.990159, 0.990263, 0.990455, 0.990515, 0.990636, 0.990731, 0.990787, 0.990884, 0.990900, 0.990971, 0.990986, 0.991042, 0.991048, 0.991057, 0.991057, 0.991048, 0.991042, 0.990986, 0.990971, 0.990900, 0.990884, 0.990787, 0.990731, 0.990636, 0.990515, 0.990455, 0.990263, 0.990159, 0.990006, 0.989857, 0.989681, 0.989470, 0.989235, 0.989043, 0.988787, 0.988532, 0.988146, 0.988022, 0.987435, 0.987182, 0.986934, 0.986417, 0.985916, 0.985453, 0.984855, 0.984436, 0.983759, 0.983068, 0.982386, 0.981637, 0.980773, 0.979920, 0.978887, 0.977953, 0.976647, 0.975784, 0.974223, 0.972800, 0.971284, 0.969970, 0.967994, 0.965984, 0.964039, 0.961755, 0.959339, 0.956675, 0.953860, 0.950768, 0.947313, 0.943788, 0.939752, 0.935424, 0.930744, 0.925504, 0.920103, 0.914023, 0.907216, 0.900084, 0.892242, 0.883399, 0.874277, 0.863766, 0.852416, 0.839932, 0.826496, 0.811669, 0.795374, 0.777313, 0.757467, 0.735991, 0.712150, 0.685667, 0.657029, 0.625035, 0.589915, 0.551116, 0.508397, 0.460966, 0.408796, 0.351055, 0.287226, 0.216842, 0.139913, 0.062742]] # Tilt from horizontal of the PV modules/panels, in radians beta = beta * DTOR sazm = sazm * DTOR # Surface azimuth of PV module/panels, in radians # 1. Calculate and assign various paramters to be used for modeling # irradiances # For calling PerezComp to break diffuse into components for zero tilt # (horizontal) iso_dif = 0.0; circ_dif = 0.0; horiz_dif = 0.0; grd_dif = 0.0; beam = 0.0 # Call to get iso_dif for horizontal surface ghi, iso_dif, circ_dif, horiz_dif, grd_dif, beam = perezComp( dni, dhi, albedo, zen, 0.0, zen) # Isotropic irradiance from sky on horizontal surface, used later for # determining isotropic sky component iso_sky_dif = iso_dif # For calling PerezComp to break diffuse into components for 90 degree tilt # (vertical) inc, tiltr, sazmr = sunIncident(0, 90.0, 180.0, 45.0, zen, azm) # Call to get horiz_dif for vertical surface vti, iso_dif, circ_dif, horiz_dif, grd_dif, beam = perezComp( dni, dhi, albedo, inc, tiltr, zen) # Horizon diffuse irradiance on a vertical surface, used later for # determining horizon brightening irradiance component F2DHI = horiz_dif index = -99 n2 = -99.9 if (PVbackSurface == "glass"): # Index to use with 1-degree hemispherical segment AOI correction # factor array index = 0 n2 = 1.526 # Index of refraction for glass elif (PVbackSurface == "ARglass"): # Index to use with 1-degree hemispherical segment AOI correction # factor array index = 1 n2 = 1.300 # Index of refraction for ARglass else: raise Exception( "Incorrect text input for PVbackSurface." " Must be glass or ARglass.") # Reflectance at normal incidence, Duffie and Beckman p217 Ro = math.pow((n2 - 1.0) / (n2 + 1.0), 2.0) # Average GHI on ground under PV array for cases when x projection exceed # 2*rtr aveGroundGHI = 0.0 for i in range(0,100): aveGroundGHI += rearGroundGHI[i] / 100.0 # Calculate x,y coordinates of bottom and top edges of PV row in back of desired PV row so that portions of sky and ground viewed by the # PV cell may be determined. Origin of x-y axis is the ground pobelow the lower front edge of the desired PV row. The row in back of # the desired row is in the positive x direction. h = math.sin(beta); # Vertical height of sloped PV panel (in PV panel slope lengths) x1 = math.cos(beta); # Horizontal distance from front of panel to rear of panel (in PV panel slope lengths) rtr = D + x1; # Row-to-row distance (in PV panel slope lengths) PbotX = rtr; # x value for poon bottom egde of PV module/panel of row in back of (in PV panel slope lengths) PbotY = C; # y value for poon bottom egde of PV module/panel of row in back of (in PV panel slope lengths) PtopX = rtr + x1; # x value for poon top egde of PV module/panel of row in back of (in PV panel slope lengths) PtopY = h + C; # y value for poon top egde of PV module/panel of row in back of (in PV panel slope lengths) # 2. Calculate diffuse and direct component irradiances for each cell row for i in range (0, cellRows): # Calculate diffuse irradiances and reflected amounts for each cell row over it's field of view of 180 degrees, # beginning with the angle providing the upper most view of the sky (j=0) #PcellX = x1 * (i + 0.5) / ((double)cellRows); # x value for location of PV cell #PcellY = C + h * (i + 0.5) / ((double)cellRows); # y value for location of PV cell PcellX = x1 * (i + 0.5) / (cellRows) + offset * math.sin(beta); # x value for location of PV cell with OFFSET FOR SARA REFERENCE CELLS 4/26/2016 PcellY = C + h * (i + 0.5) / (cellRows) - offset * math.cos(beta); # y value for location of PV cell with OFFSET FOR SARA REFERENCE CELLS 4/26/2016 elvUP = math.atan((PtopY - PcellY) / (PtopX - PcellX)); # Elevation angle up from PV cell to top of PV module/panel, radians elvDOWN = math.atan((PcellY - PbotY) / (PbotX - PcellX)); # Elevation angle down from PV cell to bottom of PV module/panel, radians if (rowType == "last" or rowType == "single"): # 4/19/16 No array to the rear for these cases elvUP = 0.0; elvDOWN = 0.0; #Console.WriteLine("ElvUp = 0", elvUP / DTOR); #if (i == 0) # Console.WriteLine("ElvDown = 0", elvDOWN / DTOR); #123 #iStopIso = Convert.ToInt32((beta - elvUP) / DTOR); # Last whole degree in arc range that sees sky, first is 0 #Console.WriteLine("iStopIso = 0", iStopIso); #iHorBright = Convert.ToInt32(max(0.0, 6.0 - elvUP / DTOR)); # Number of whole degrees for which horizon brightening occurs #iStartGrd = Convert.ToInt32((beta + elvDOWN) / DTOR); # First whole degree in arc range that sees ground, last is 180 iStopIso = int(round((beta - elvUP) / DTOR)); # Last whole degree in arc range that sees sky, first is 0 #Console.WriteLine("iStopIso = 0", iStopIso); iHorBright = int(round(max(0.0, 6.0 - elvUP / DTOR))); # Number of whole degrees for which horizon brightening occurs iStartGrd = int(round((beta + elvDOWN) / DTOR)); # First whole degree in arc range that sees ground, last is 180 backGTI.append(0.0) # Initialtize front GTI for j in range (0, iStopIso): # Add sky diffuse component and horizon brightening if present backGTI[i] += 0.5 * (math.cos(j * DTOR) - math.cos((j + 1) * DTOR)) * SegAOIcor[index][j] * iso_sky_dif; # Sky radiation # backGTI[i] += 0.5 * (math.cos(j * DTOR) - math.cos((j + 1) * DTOR)) * iso_sky_dif; # Sky radiation if ((iStopIso - j) <= iHorBright): # Add horizon brightening term if seen backGTI[i] += 0.5 * (math.cos(j * DTOR) - math.cos((j + 1) * DTOR)) * SegAOIcor[index][j] * F2DHI / 0.052264; # 0.052246 = 0.5 * [cos(84) - cos(90)] #backGTI[i] += 0.5 * (math.cos(j * DTOR) - math.cos((j + 1) * DTOR)) * F2DHI / 0.052264; # 0.052246 = 0.5 * [cos(84) - cos(90)] if (rowType == "interior" or rowType == "first"): # 4/19/16 Only add reflections from PV modules for these cases for j in range (iStopIso, iStartGrd): #j = iStopIso; j < iStartGrd; j++) # Add relections from PV module front surfaces L = (PbotX - PcellX) / math.cos(elvDOWN); # Diagonal distance from cell to bottom of module in row behind startAlpha = -(j - iStopIso) * DTOR + elvUP + elvDOWN; stopAlpha = -(j + 1 - iStopIso) * DTOR + elvUP + elvDOWN; m = L * math.sin(startAlpha); theta = math.pi - elvDOWN - (math.pi / 2.0 - startAlpha) - beta; projectedX2 = m / math.cos(theta); # Projected distance on sloped PV module m = L * math.sin(stopAlpha); theta = math.pi - elvDOWN - (math.pi / 2.0 - stopAlpha) - beta; projectedX1 = m / math.cos(theta); # Projected distance on sloped PV module projectedX1 = max(0.0, projectedX1); #Console.WriteLine("j= 0 projected X1 = 1,6:0.000 projected X2 = 2,6:0.000", j, projectedX1, projectedX2); PVreflectedIrr = 0.0; # Irradiance from PV module front cover reflections deltaCell = 1.0 / cellRows; # Length of cell in sloped direction in module/panel units (dimensionless) for k in range (0, cellRows): # Determine which cells in behind row are seen, and their reflected irradiance cellBot = k * deltaCell; # Position of bottom of cell along PV module/panel cellTop = (k + 1) * deltaCell; # Position of top of cell along PV module/panel cellLengthSeen = 0.0; # Length of cell seen for this row, start with zero if (cellBot >= projectedX1 and cellTop <= projectedX2): cellLengthSeen = cellTop - cellBot; # Sees the whole cell elif (cellBot <= projectedX1 and cellTop >= projectedX2): cellLengthSeen = projectedX2 - projectedX1; # Sees portion in the middle of cell elif (cellBot >= projectedX1 and projectedX2 > cellBot and cellTop >= projectedX2): cellLengthSeen = projectedX2 - cellBot; # Sees bottom of cell elif (cellBot <= projectedX1 and projectedX1 < cellTop and cellTop <= projectedX2): cellLengthSeen = cellTop - projectedX1; # Sees top of cell #Console.WriteLine("cell= 0 cellBot = 1,5:0.00 cellTop = 2,5:0.00 Cell length seen = 3,5:0.00", k, cellBot, cellTop, cellLengthSeen); PVreflectedIrr += cellLengthSeen * frontReflected[k]; # Add reflected radiation for this PV cell, if seen, weight by cell length seen PVreflectedIrr /= projectedX2 - projectedX1; # Reflected irradiance from PV modules (W/m2) backGTI[i] += 0.5 * (math.cos(j * DTOR) - math.cos((j + 1) * DTOR)) * SegAOIcor[index][j] * PVreflectedIrr; # Radiation reflected from PV module surfaces onto back surface of module # End of adding reflections from PV module surfaces #Console.WriteLine(""); #if (i == 0) #Console.WriteLine("iStartGrd = 0", iStartGrd); for j in range (iStartGrd, 180): # Add ground reflected component startElvDown = (j - iStartGrd) * DTOR + elvDOWN; # Start and ending down elevations for this j loop stopElvDown = (j + 1 - iStartGrd) * DTOR + elvDOWN; projectedX2 = PcellX + np.float64(PcellY) / math.tan(startElvDown); # Projection of ElvDown to ground in +x direction (X1 and X2 opposite nomenclature for front irradiance method) projectedX1 = PcellX + PcellY / math.tan(stopElvDown); actualGroundGHI = 0.0; # Actuall ground GHI from summing array values #if (i == 0) # Console.WriteLine("j= 0 projected X1 = 1,6:0.0", j, 100 * projectedX1 / rtr); if (abs(projectedX1 - projectedX2) > 0.99 * rtr): if (rowType == "last" or rowType == "single"): # 4/19/16 No array to rear for these cases actualGroundGHI = ghi; # Use total value if projection approximates the rtr else: actualGroundGHI = aveGroundGHI; # Use average value if projection approximates the rtr else: projectedX1 = 100.0 * projectedX1 / rtr; # Normalize projections and multiply by 100 projectedX2 = 100.0 * projectedX2 / rtr; #Console.WriteLine("projectedX1 = 0 projectedX2 = 1", projectedX1, projectedX2); if ((rowType == "last" or rowType == "single") and (abs(projectedX1) > 99.0 or abs(projectedX2) > 99.0)): #4/19/2016 actualGroundGHI = ghi; # Use total value if projection > rtr for "last" or "single" else: while (projectedX1 >= 100.0 or projectedX2 >= 100.0): # Offset so array indexes are less than 100 projectedX1 -= 100.0; projectedX2 -= 100.0; while (projectedX1 < -100.0 or projectedX2 < -100.0): # Offset so array indexes are >= -100.0 12/13/2016 projectedX1 += 100.0; projectedX2 += 100.0; #Console.WriteLine("projectedX1 = 0 projectedX2 = 1", projectedX1, projectedX2); index1 = (int)(projectedX1 + 100.0) - 100; # Determine indexes for use with rearGroundGHI array and frontGroundGHI array(truncates values) index2 = (int)(projectedX2 + 100.0) - 100; # (int)(1.9) = 1 and (int)(-1.9) = -1; (int)(1.9+100) - 100 = 1 and (int)(-1.9+100) - 100 = -2 #Console.WriteLine("index1=0 index2=1", index1, index2); if (index1 == index2): if (index1 < 0): actualGroundGHI = frontGroundGHI[index1 + 100]; #actualGroundGHI = 0.0; else: actualGroundGHI = rearGroundGHI[index1]; # x projections in same groundGHI element THIS SEEMS TO ADD HICCUP 4/26/2016 *************************** #actualGroundGHI = 0.0; else: for k in range (index1, index2+1): #for (k = index1; k <= index2; k++) # Sum the irradiances on the ground if projections are in different groundGHI elements if (k == index1): if (k < 0): actualGroundGHI += frontGroundGHI[k + 100] * (k + 1.0 - projectedX1); else: actualGroundGHI += rearGroundGHI[k] * (k + 1.0 - projectedX1); elif (k == index2): if (k < 0): actualGroundGHI += frontGroundGHI[k + 100] * (projectedX2 - k); else: actualGroundGHI += rearGroundGHI[k] * (projectedX2 - k); else: if (k < 0): actualGroundGHI += frontGroundGHI[k + 100]; else: actualGroundGHI += rearGroundGHI[k]; actualGroundGHI /= projectedX2 - projectedX1; # Irradiance on ground in the 1 degree field of view #if (i == 0) # Console.WriteLine("j=0 index1=1 index2=2 projectX1=3,5:0.0 projectX2=4,5:0.0 actualGrdGHI=5,6:0.0", j, index1, index2, projectedX1, projectedX2, actualGroundGHI); # End of if looping to determine actualGroundGHI backGTI[i] += 0.5 * (math.cos(j * DTOR) - math.cos((j + 1) * DTOR)) * SegAOIcor[index][j] * actualGroundGHI * albedo; # Add ground reflected component #Console.WriteLine("actualGroundGHI = 0,6:0.0 inputGHI = 1,6:0.0 aveArrayGroundGHI = 2,6:0.0", actualGroundGHI, dhi + dni * math.cos(zen), aveGroundGHI); # End of j loop for adding ground reflected componenet # Calculate and add direct and circumsolar irradiance components inc, tiltr, sazmr = sunIncident(0, 180-beta / DTOR, sazm / DTOR - 180, 45.0, zen, azm) # For calling PerezComp to break diffuse into components for downward facing tilt gtiAllpc, iso_dif, circ_dif, horiz_dif, grd_dif, beam = perezComp(dni, dhi, albedo, inc, tiltr, zen) # Call to get components for the tilt cellShade = pvBackSH * cellRows - i; if (cellShade > 1.0): # Fully shaded if > 1, no shade if < 0, otherwise fractionally shaded cellShade = 1.0; elif (cellShade < 0.0): cellShade = 0.0; if (cellShade < 1.0 and inc < math.pi / 2.0): # Cell not shaded entirely and inc < 90 deg cor = aOIcorrection(n2, inc); # Get AOI correction for beam and circumsolar backGTI[i] += (1.0 - cellShade) * (beam + circ_dif) * cor; # Add beam and circumsolar radiation # End of for i = 0; i < cellRows loop return backGTI, aveGroundGHI; # End of GetBackSurfaceIrradiances def getFrontSurfaceIrradiances(rowType, maxShadow, PVfrontSurface, beta, sazm, dni, dhi, C, D, albedo, zen, azm, cellRows, pvFrontSH, frontGroundGHI): """ This method calculates the AOI corrected irradiance on the front of the PV module/panel and the irradiance reflected from the the front of the PV module/panel. 11/12/2015 Added row type and MaxShadow and changed code to accommodate 4/19/2015 Parameters ---------- rowType : str Type of row: "first", "interior", "last", or "single" maxShadow Maximum shadow length projected to the front (-) or rear (+) from the front of the module row (in PV panel slope lengths), only used for `rowTypes` other than "interior" PVfrontSurface PV module front surface material type, either "glass" or "ARglass" beta Tilt from horizontal of the PV modules/panels (deg) sazm Surface azimuth of PV panels (deg) dni Direct normal irradiance (W/m2) dhi Diffuse horizontal irradiance (W/m2) C Ground clearance of PV panel (in PV panel slope lengths) D Horizontal distance between rows of PV panels (in PV panel slope lengths) albedo Ground albedo zen Sun zenith (in radians) azm Sun azimuth (in radians) pvFrontSH Decimal fraction of the front surface of the PV panel that is shaded, 0.0 to 1.0 froutGroundGHI : array of size [100] Global horizontal irradiance for each of 100 ground segments in front of the module row Returns ------- frontGTI : array of size [cellRows] AOI corrected irradiance on front side of PV module/panel, one for each cell row (W/m2) frontReflected : array of size [cellRows] Irradiance reflected from the front of the PV module/panel (W/m2) aveGroundGHI : numeric Average GHI on the ground (includes effects of shading by array) from the array frontGroundGHI[100] Notes ----- 1-degree hemispherical segment AOI correction factor for glass (index=0) and ARglass (index=1). Creates a list containing 5 lists, each of 8 items, all set to 0 """ frontGTI = [] frontReflected = [] #w, h = 2, 180; #SegAOIcor = [[0 for x in range(w)] for y in range(h)] SegAOIcor = ([[0.057563, 0.128570, 0.199651, 0.265024, 0.324661, 0.378968, 0.428391, 0.473670, 0.514788, 0.552454, 0.586857, 0.618484, 0.647076, 0.673762, 0.698029, 0.720118, 0.740726, 0.759671, 0.776946, 0.792833, 0.807374, 0.821010, 0.833534, 0.845241, 0.855524, 0.865562, 0.874567, 0.882831, 0.890769, 0.897939, 0.904373, 0.910646, 0.916297, 0.921589, 0.926512, 0.930906, 0.935179, 0.939074, 0.942627, 0.946009, 0.949096, 0.952030, 0.954555, 0.957157, 0.959669, 0.961500, 0.963481, 0.965353, 0.967387, 0.968580, 0.970311, 0.971567, 0.972948, 0.974114, 0.975264, 0.976287, 0.977213, 0.978142, 0.979057, 0.979662, 0.980460, 0.981100, 0.981771, 0.982459, 0.982837, 0.983199, 0.983956, 0.984156, 0.984682, 0.985026, 0.985364, 0.985645, 0.985954, 0.986241, 0.986484, 0.986686, 0.986895, 0.987043, 0.987287, 0.987388, 0.987541, 0.987669, 0.987755, 0.987877, 0.987903, 0.987996, 0.988022, 0.988091, 0.988104, 0.988114, 0.988114, 0.988104, 0.988091, 0.988022, 0.987996, 0.987903, 0.987877, 0.987755, 0.987669, 0.987541, 0.987388, 0.987287, 0.987043, 0.986895, 0.986686, 0.986484, 0.986240, 0.985954, 0.985645, 0.985364, 0.985020, 0.984676, 0.984156, 0.983956, 0.983199, 0.982837, 0.982459, 0.981771, 0.981100, 0.980460, 0.979662, 0.979057, 0.978142, 0.977213, 0.976287, 0.975264, 0.974114, 0.972947, 0.971567, 0.970311, 0.968580, 0.967387, 0.965353, 0.963481, 0.961501, 0.959671, 0.957157, 0.954555, 0.952030, 0.949096, 0.946009, 0.942627, 0.939074, 0.935179, 0.930906, 0.926512, 0.921589, 0.916297, 0.910646, 0.904373, 0.897939, 0.890769, 0.882831, 0.874567, 0.865562, 0.855524, 0.845241, 0.833534, 0.821010, 0.807374, 0.792833, 0.776946, 0.759671, 0.740726, 0.720118, 0.698029, 0.673762, 0.647076, 0.618484, 0.586857, 0.552454, 0.514788, 0.473670, 0.428391, 0.378968, 0.324661, 0.265024, 0.199651, 0.128570, 0.057563], [0.062742, 0.139913, 0.216842, 0.287226, 0.351055, 0.408796, 0.460966, 0.508397, 0.551116, 0.589915, 0.625035, 0.657029, 0.685667, 0.712150, 0.735991, 0.757467, 0.777313, 0.795374, 0.811669, 0.826496, 0.839932, 0.852416, 0.863766, 0.874277, 0.883399, 0.892242, 0.900084, 0.907216, 0.914023, 0.920103, 0.925504, 0.930744, 0.935424, 0.939752, 0.943788, 0.947313, 0.950768, 0.953860, 0.956675, 0.959339, 0.961755, 0.964039, 0.965984, 0.967994, 0.969968, 0.971283, 0.972800, 0.974223, 0.975784, 0.976647, 0.977953, 0.978887, 0.979922, 0.980773, 0.981637, 0.982386, 0.983068, 0.983759, 0.984436, 0.984855, 0.985453, 0.985916, 0.986417, 0.986934, 0.987182, 0.987435, 0.988022, 0.988146, 0.988537, 0.988792, 0.989043, 0.989235, 0.989470, 0.989681, 0.989857, 0.990006, 0.990159, 0.990263, 0.990455, 0.990515, 0.990636, 0.990731, 0.990787, 0.990884, 0.990900, 0.990971, 0.990986, 0.991042, 0.991048, 0.991057, 0.991057, 0.991048, 0.991042, 0.990986, 0.990971, 0.990900, 0.990884, 0.990787, 0.990731, 0.990636, 0.990515, 0.990455, 0.990263, 0.990159, 0.990006, 0.989857, 0.989681, 0.989470, 0.989235, 0.989043, 0.988787, 0.988532, 0.988146, 0.988022, 0.987435, 0.987182, 0.986934, 0.986417, 0.985916, 0.985453, 0.984855, 0.984436, 0.983759, 0.983068, 0.982386, 0.981637, 0.980773, 0.979920, 0.978887, 0.977953, 0.976647, 0.975784, 0.974223, 0.972800, 0.971284, 0.969970, 0.967994, 0.965984, 0.964039, 0.961755, 0.959339, 0.956675, 0.953860, 0.950768, 0.947313, 0.943788, 0.939752, 0.935424, 0.930744, 0.925504, 0.920103, 0.914023, 0.907216, 0.900084, 0.892242, 0.883399, 0.874277, 0.863766, 0.852416, 0.839932, 0.826496, 0.811669, 0.795374, 0.777313, 0.757467, 0.735991, 0.712150, 0.685667, 0.657029, 0.625035, 0.589915, 0.551116, 0.508397, 0.460966, 0.408796, 0.351055, 0.287226, 0.216842, 0.139913, 0.062742]]); beta = beta * DTOR # Tilt from horizontal of the PV modules/panels, in radians sazm = sazm * DTOR # Surface azimuth of PV module/panels, in radians # 1. Calculate and assign various paramters to be used for modeling irradiances iso_dif = 0.0; circ_dif = 0.0; horiz_dif = 0.0; grd_dif = 0.0; beam = 0.0; # For calling PerezComp to break diffuse into components for zero tilt (horizontal) ghi, iso_dif, circ_dif, horiz_dif, grd_dif, beam = perezComp(dni, dhi, albedo, zen, 0.0, zen) # Call to get iso_dif for horizontal surface # print "PEREZCOMP1 = " # print "ghi = ", ghi # print "iso_dif = ", iso_dif # print "circ_dif = ", circ_dif # print "horiz_dif = ", horiz_dif # print "grd_dif = ", grd_dif # print "beam = ", beam iso_sky_dif = iso_dif; # Isotropic irradiance from sky on horizontal surface, used later for determining isotropic sky component inc, tiltr, sazmr = sunIncident(0, 90.0, 180.0, 45.0, zen, azm) # For calling PerezComp to break diffuse into components for 90 degree tilt (vertical) # print "sunIncident 1." # print "inc = ", inc # print "tiltr = ", tiltr # print "sazmr = ", sazmr vti, iso_dif, circ_dif, horiz_dif, grd_dif, beam = perezComp(dni, dhi, albedo, inc, tiltr, zen) # Call to get horiz_dif for vertical surface # print "PEREZCOMP1 = " # print "vti = ", vti # print "iso_dif = ", iso_dif # print "circ_dif = ", circ_dif # print "horiz_dif = ", horiz_dif # print "grd_dif = ", grd_dif # print "beam = ", beam F2DHI = horiz_dif; # Horizon diffuse irradiance on a vertical surface, used later for determining horizon brightening irradiance component index = -99; n2 = -99.9; if (PVfrontSurface == "glass"): index = 0; # Index to use with 1-degree hemispherical segment AOI correction factor array n2 = 1.526; # Index of refraction for glass elif (PVfrontSurface == "ARglass"): index = 1; # Index to use with 1-degree hemispherical segment AOI correction factor array n2 = 1.300; # Index of refraction for ARglass else: raise Exception("Incorrect text input for PVfrontSurface. Must be glass or ARglass.") Ro = math.pow((n2 - 1.0) / (n2 + 1.0), 2.0); # Reflectance at normal incidence, Duffie and Beckman p217 aveGroundGHI = 0.0; # Average GHI on ground under PV array for cases when x projection exceed 2*rtr for i in range (0,100): aveGroundGHI += frontGroundGHI[i] / 100.0; # Calculate x,y coordinates of bottom and top edges of PV row in front of desired PV row so that portions of sky and ground viewed by the # PV cell may be determined. Origin of x-y axis is the ground pobelow the lower front edge of the desired PV row. The row in front of # the desired row is in the negative x direction. h = math.sin(beta); # Vertical height of sloped PV panel (in PV panel slope lengths) x1 = math.cos(beta); # Horizontal distance from front of panel to rear of panel (in PV panel slope lengths) rtr = D + x1; # Row-to-row distance (in PV panel slope lengths) PbotX = -rtr; # x value for poon bottom egde of PV module/panel of row in front of (in PV panel slope lengths) PbotY = C; # y value for poon bottom egde of PV module/panel of row in front of (in PV panel slope lengths) PtopX = -D; # x value for poon top egde of PV module/panel of row in front of (in PV panel slope lengths) PtopY = h + C; # y value for poon top egde of PV module/panel of row in front of (in PV panel slope lengths) # 2. Calculate diffuse and direct component irradiances for each cell row for i in range (0, cellRows): # Calculate diffuse irradiances and reflected amounts for each cell row over it's field of view of 180 degrees, # beginning with the angle providing the upper most view of the sky (j=0) PcellX = x1 * (i + 0.5) / (cellRows); # x value for location of PV cell PcellY = C + h * (i + 0.5) / (cellRows); # y value for location of PV cell elvUP = math.atan((PtopY - PcellY) / (PcellX - PtopX)); # Elevation angle up from PV cell to top of PV module/panel, radians elvDOWN = math.atan((PcellY - PbotY) / (PcellX - PbotX)); # Elevation angle down from PV cell to bottom of PV module/panel, radians if (rowType == "first" or rowType == "single"): # 4/19/16 No array in front for these cases elvUP = 0.0; elvDOWN = 0.0; #Console.WriteLine("ElvUp = 0", elvUP / DTOR); #if (i == 0) # Console.WriteLine("ElvDown = 0", elvDOWN / DTOR); if math.isnan(beta): print( "Beta is Nan") if math.isnan(elvUP): print( "elvUP is Nan") if math.isnan((math.pi - beta - elvUP) / DTOR): print( "division is Nan") iStopIso = int(round(np.float64((math.pi - beta - elvUP)) / DTOR)) # Last whole degree in arc range that sees sky, first is 0 #Console.WriteLine("iStopIso = 0", iStopIso); iHorBright = int(round(max(0.0, 6.0 - elvUP / DTOR))); # Number of whole degrees for which horizon brightening occurs iStartGrd = int(round((math.pi - beta + elvDOWN) / DTOR)); # First whole degree in arc range that sees ground, last is 180 # print "iStopIso = ", iStopIso # print "iHorBright = ", iHorBright # print "iStartGrd = ", iStartGrd frontGTI.append(0.0) # Initialtize front GTI frontReflected.append(0.0); # Initialize reflected amount from front for j in range (0, iStopIso): # Add sky diffuse component and horizon brightening if present #for (j = 0; j < iStopIso; j++) frontGTI[i] += 0.5 * (math.cos(j * DTOR) - math.cos((j + 1) * DTOR)) * SegAOIcor[index][j] * iso_sky_dif; # Sky radiation frontReflected[i] += 0.5 * (math.cos(j * DTOR) - math.cos((j + 1) * DTOR)) * iso_sky_dif * (1.0 - SegAOIcor[index][j] * (1.0 - Ro)); # Reflected radiation from module if ((iStopIso - j) <= iHorBright): # Add horizon brightening term if seen frontGTI[i] += 0.5 * (math.cos(j * DTOR) - math.cos((j + 1) * DTOR)) * SegAOIcor[index][j] * F2DHI / 0.052264; # 0.052246 = 0.5 * [cos(84) - cos(90)] frontReflected[i] += 0.5 * (math.cos(j * DTOR) - math.cos((j + 1) * DTOR)) * (F2DHI / 0.052264) * (1.0 - SegAOIcor[index][j] * (1.0 - Ro)); # Reflected radiation from module #if (i == 0) # Console.WriteLine("iStartGrd = 0", iStartGrd); for j in range (iStartGrd, 180): # Add ground reflected component #(j = iStartGrd; j < 180; j++) startElvDown = (j - iStartGrd) * DTOR + elvDOWN; # Start and ending down elevations for this j loop stopElvDown = (j + 1 - iStartGrd) * DTOR + elvDOWN; projectedX1 = PcellX - np.float64(PcellY) / math.tan(startElvDown); # Projection of ElvDown to ground in -x direction projectedX2 = PcellX - PcellY / math.tan(stopElvDown); actualGroundGHI = 0.0; # Actuall ground GHI from summing array values #if (i == 0) # Console.WriteLine("j= 0 projected X1 = 1,6:0.0", j, 100 * projectedX1 / rtr); if (abs(projectedX1 - projectedX2) > 0.99 * rtr): if (rowType == "first" or rowType == "single"): # 4/19/16 No array in front for these cases actualGroundGHI = ghi; # Use total value if projection approximates the rtr else: actualGroundGHI = aveGroundGHI; # Use average value if projection approximates the rtr else: projectedX1 = 100.0 * projectedX1 / rtr; # Normalize projections and multiply by 100 projectedX2 = 100.0 * projectedX2 / rtr; if ((rowType == "first" or rowType == "single") and (abs(projectedX1) > rtr or abs(projectedX2) > rtr)): #4/19/2016 actualGroundGHI = ghi; # Use total value if projection > rtr for "first" or "single" else: while (projectedX1 < 0.0 or projectedX2 < 0.0): # Offset so array indexes are positive projectedX1 += 100.0; projectedX2 += 100.0; index1 = int(projectedX1); # Determine indexes for use with groundGHI array (truncates values) index2 = int(projectedX2); if (index1 == index2): actualGroundGHI = frontGroundGHI[index1]; # x projections in same groundGHI element else: for k in range (index1, index2+1): # Sum the irradiances on the ground if projections are in different groundGHI elements #for (k = index1; k <= index2; k++) #Console.WriteLine("index1=0 index2=1", index1,index2); if (k == index1): actualGroundGHI += frontGroundGHI[k] * (k + 1.0 - projectedX1); elif (k == index2): if (k < 100): actualGroundGHI += frontGroundGHI[k] * (projectedX2 - k); else: actualGroundGHI += frontGroundGHI[k - 100] * (projectedX2 - k); else: if (k < 100): actualGroundGHI += frontGroundGHI[k]; else: actualGroundGHI += frontGroundGHI[k - 100]; actualGroundGHI /= projectedX2 - projectedX1; # Irradiance on ground in the 1 degree field of view #if (i == 0) # Console.WriteLine("j=0 index1=1 index2=2 projectX1=3,5:0.0 projectX2=4,5:0.0 actualGrdGHI=5,6:0.0", j, index1, index2, projectedX1, projectedX2, actualGroundGHI); frontGTI[i] += 0.5 * (math.cos(j * DTOR) - math.cos((j + 1) * DTOR)) * SegAOIcor[index][j] * actualGroundGHI * albedo; # Add ground reflected component frontReflected[i] += 0.5 * (math.cos(j * DTOR) - math.cos((j + 1) * DTOR)) * actualGroundGHI * albedo * (1.0 - SegAOIcor[index][j] * (1.0 - Ro)); # Reflected ground radiation from module #Console.WriteLine("actualGroundGHI = 0,6:0.0 inputGHI = 1,6:0.0 aveArrayGroundGHI = 2,6:0.0", actualGroundGHI, dhi + dni * math.cos(zen), aveGroundGHI); # End of j loop for adding ground reflected componenet # Calculate and add direct and circumsolar irradiance components inc, tiltr, sazmr = sunIncident(0, beta / DTOR, sazm / DTOR, 45.0, zen, azm) # For calling PerezComp to break diffuse into components for 90 degree tilt (vertical) # print "sunIncident 2." # print "inc = ", inc # print "tiltr = ", tiltr # print "sazmr = ", sazmr # print " INCIDENT REALY NEEDED for AOI ", inc gtiAllpc, iso_dif, circ_dif, horiz_dif, grd_dif, beam = perezComp(dni, dhi, albedo, inc, tiltr, zen) # Call to get components for the tilt # print "PEREZCOMP 2 = " # print "gtiAllpc = ", vti # print "iso_dif = ", iso_dif # print "circ_dif = ", circ_dif # print "horiz_dif = ", horiz_dif # print "grd_dif = ", grd_dif # print "beam = ", beam cellShade = pvFrontSH * cellRows - i; if (cellShade > 1.0): # Fully shaded if > 1, no shade if < 0, otherwise fractionally shaded cellShade = 1.0; elif (cellShade < 0.0): cellShade = 0.0; if (cellShade < 1.0 and inc < math.pi / 2.0): # Cell not shaded entirely and inc < 90 deg cor = aOIcorrection(n2, inc); # Get AOI correction for beam and circumsolar frontGTI[i] += (1.0 - cellShade) * (beam + circ_dif) * cor; # Add beam and circumsolar radiation #frontReflected[i] += (1.0 - cellShade) * (beam + circ_dif) * (1.0 - cor * (1.0 - Ro)); # Reflected beam and circumsolar radiation from module # End of for i = 0; i < cellRows loop return aveGroundGHI, frontGTI, frontReflected; # End of GetFrontSurfaceIrradiances def getGroundShadeFactors(rowType, beta, C, D, elv, azm, sazm): """ This method determines if the ground is shaded from direct beam radiation for points on the ground from the leading edge of one row of PV panels to the leading edge of the next row of PV panels behind it. This row-to-row dimension is divided into 100 ground segments and a ground shade factor is returned for each ground segment, with values of 1 for shaded segments and values of 0 for non shaded segments. The fractional amounts of shading of the front and back surfaces of the PV panel are also returned. 8/20/2015 4/18/2016 - Modified to account for different row types. Because the ground factors may now be different depending on row, they are calculated for the row-to-row dimension to the rear of the leading module edge and to the front of the leading edge. Also returned is the maximum shadow length projected to the front or rear from the front of the module row Parameters ---------- rowType : str "first", "interior", "last", or "single" beta Tilt from horizontal of the PV modules/panels (deg) C Ground clearance of PV panel (in PV panel slope lengths) D Horizontal distance between rows of PV panels (in PV panel slope lengths) elv Sun elevation (in radians) azm Sun azimuth (in radians) sazm Surface azimuth of PV panels (deg) Returns ------- pvFrontSH : numeric Decimal fraction of the front surface of the PV panel that is shaded, 0.0 to 1.0 pvBackSH : numeric Decimal fraction of the back surface of the PV panel that is shaded, 0.0 to 1.0 rearGroundSH : array of size [100] Ground shade factors for ground segments to the rear, 0 = not shaded, 1 = shaded frontGroundSH : array of size [100] Ground shade factors for ground segments to the front, 0 = not shaded, 1 = shaded maxShadow : numeric Maximum shadow length projected to the front(-) or rear (+) from the front of the module row (in PV panel slope lengths), only used later for rowTypes other than "interior" """ rearGroundSH = [] frontGroundSH = [] beta = beta * DTOR # Tilt from horizontal of the PV modules/panels, in radians sazm = sazm * DTOR # Surface azimuth of PV module/pamels, in radians h = math.sin(beta); # Vertical height of sloped PV panel (in PV panel slope lengths) x1 = math.cos(beta); # Horizontal distance from front of panel to rear of panel (in PV panel slope lengths) rtr = D + x1; # Row-to-row distance (in PV panel slope lengths) # Divide the row-to-row spacing into 100 intervals for calculating ground shade factors delta = rtr / 100.0; x = -delta / 2.0; # Initialize horizontal dimension x to provide midpoof intervals Lh = (h / math.tan(elv)) * math.cos(sazm - azm); # Horizontal length of shadow perpindicular to row from top of module to bottom of module Lhc = ((h + C) / math.tan(elv)) * math.cos(sazm - azm); # Horizontal length of shadow perpindicular to row from top of module to ground level Lc = (C / math.tan(elv)) * math.cos(sazm - azm); # Horizontal length of shadow perpindicular to row from bottom of module to ground level ss1 = 0.0; se1 = 0.0; ss2 = 0.0; se2 = 0.0; # Initialize shading start (s) and end (e) to zeros for two potential shading segments pvFrontSH = 0.0; pvBackSH = 0.0; if (rowType == "interior"): if (Lh > D): # Front side of PV module partially shaded, back completely shaded, ground completely shaded pvFrontSH = (Lh - D) / (Lh + x1); pvBackSH = 1.0; ss1 = 0.0; # Ground shaded from 0.0 to rtr se1 = rtr; elif (Lh < -(rtr + x1)): # Back side of PV module partially shaded, front completely shaded, ground completely shaded pvFrontSH = 1.0; pvBackSH = (Lh + rtr + x1) / (Lh + x1); ss1 = 0.0; # Ground shaded from 0.0 to rtr se1 = rtr; else: # Ground is partially shaded (I assume) if (Lhc >= 0.0): # Shadow to rear of row, module front unshaded, back shaded pvFrontSH = 0.0; pvBackSH = 1.0; Ss = Lc; # Shadow starts at Lc Se = Lhc + x1; # Shadow ends here while (Ss > rtr): Ss -= rtr; # Put shadow in correct rtr space if needed Se -= rtr; ss1 = Ss; se1 = Se; if (se1 > rtr): # then need to use two shade areas se1 = rtr; ss2 = 0.0; se2 = Se - rtr; if (se2 > ss1): # This would mean ground completely shaded, does this occur? ss1 = 0.0; # Ground shaded from 0.0 to rtr se1 = rtr; else: # Shadow to front of row, either front or back might be shaded, depending on tilt and other factors Ss = 0.0; # Shadow starts at Lc, initialize Se = 0.0; # Shadow ends here, initialize if (Lc < Lhc + x1): pvFrontSH = 0.0; pvBackSH = 1.0; Ss = Lc; # Shadow starts at Lc Se = Lhc + x1; # Shadow ends here else: pvFrontSH = 1.0; pvBackSH = 0.0; Ss = Lhc + x1; # Shadow starts at Lhc + x1 Se = Lc; # Shadow ends here while (Ss < 0.0): Ss += rtr; # Put shadow in correct rtr space if needed Se += rtr; ss1 = Ss; se1 = Se; if (se1 > rtr): # then need to use two shade areas se1 = rtr; ss2 = 0.0; se2 = Se - rtr; if (se2 > ss1): # This would mean ground completely shaded, does this occur? ss1 = 0.0; # Ground shaded from 0.0 to rtr se1 = rtr; # End of if (Lh > D) else branching delta = rtr / 100.0; x = -delta / 2.0; # Initialize horizontal dimension x to provide midpoof intervals #for (i = 0; i <= 99; i++) for i in range(0,100): x += delta; #if ((x >= ss1 && x < se1) || (x >= ss2 && x < se2)): if ((x >= ss1 and x < se1) or (x >= ss2 and x < se2)): rearGroundSH.append(1); # x within a shaded interval, set groundSH to 1 to indicate shaded frontGroundSH.append(1); # same for both front and rear else: rearGroundSH.append(0); # x not within a shaded interval, set groundSH to 0 to indicated not shaded, i.e. sunny frontGroundSH.append(0); # same for both front and rear #Console.WriteLine("x = 0,6:0.0000 groundSH = 1", x, groundSH[i]); # End of if row type == "interior" elif (rowType == "first"): if (Lh > 0.0): # Sun is on front side of PV module pvFrontSH = 0.0; pvBackSH = 1.0; ss1 = Lc; # Ground shaded from shadow of lower edge se1 = x1 + Lhc; # to shadow of upper edge # End of if sun on front side of PV module elif (Lh < -(rtr + x1)): # Back side of PV module partially shaded from row to rear, front completely shaded, ground completely shaded pvFrontSH = 1.0; pvBackSH = (Lh + rtr + x1) / (Lh + x1); ss1 = -rtr; # Ground shaded from -rtr to rtr se1 = rtr; # End of if back side of PV module partially shaded, front completely shaded, ground completely shaded else: # Shadow to frontside of row, either front or back might be shaded, depending on tilt and other factors if (Lc < Lhc + x1): pvFrontSH = 0.0; pvBackSH = 1.0; ss1 = Lc; # Shadow starts at Lc se1 = Lhc + x1; # Shadow ends here else: pvFrontSH = 1.0; pvBackSH = 0.0; ss1 = Lhc + x1; # Shadow starts at Lhc + x1 se1 = Lc; # Shadow ends here # End of shadow to front of row delta = rtr / 100.0; x = -delta / 2.0; # Initialize horizontal dimension x to provide midpoof intervals for i in range(0,100): x += delta; if (x >= ss1 and x < se1): rearGroundSH.append(1) # x within a shaded interval, set groundSH to 1 to indicate shaded else: rearGroundSH.append(0) # x not within a shaded interval, set groundSH to 0 to indicated not shaded, i.e. sunny x = -rtr - delta / 2.0; # Initialize horizontal dimension x to provide midpoof intervals for front interval for i in range(0,100): x += delta; if (x >= ss1 and x < se1): frontGroundSH.append(1) # x within a shaded interval, set groundSH to 1 to indicate shaded else: frontGroundSH.append(0) # x not within a shaded interval, set groundSH to 0 to indicated not shaded, i.e. sunny # End of if row type == "first" elif (rowType == "last"): if (Lh > D): # Front side of PV module partially shaded, back completely shaded, ground completely shaded pvFrontSH = (Lh - D) / (Lh + x1); pvBackSH = 1.0; ss1 = -rtr; # Ground shaded from -rtr to rtr se1 = rtr; else: # Shadow to frontside of row, either front or back might be shaded, depending on tilt and other factors if (Lc < Lhc + x1): pvFrontSH = 0.0; pvBackSH = 1.0; ss1 = Lc; # Shadow starts at Lc se1 = Lhc + x1; # Shadow ends here else: pvFrontSH = 1.0; pvBackSH = 0.0; ss1 = Lhc + x1; # Shadow starts at Lhc + x1 se1 = Lc; # Shadow ends here # End of shadow to front of row delta = rtr / 100.0; x = -delta / 2.0; # Initialize horizontal dimension x to provide midpoof intervals for i in range(0,100): x += delta; if (x >= ss1 and x < se1): rearGroundSH.append(1); # x within a shaded interval, set groundSH to 1 to indicate shaded else: rearGroundSH.append(0); # x not within a shaded interval, set groundSH to 0 to indicated not shaded, i.e. sunny x = -rtr - delta / 2.0; # Initialize horizontal dimension x to provide midpoof intervals for front interval for i in range(0,100): x += delta; if (x >= ss1 and x < se1): frontGroundSH.append(1); # x within a shaded interval, set groundSH to 1 to indicate shaded else: frontGroundSH.append(0); # x not within a shaded interval, set groundSH to 0 to indicated not shaded, i.e. sunny # End of if row type == "last" elif (rowType == "single"): if (Lh > 0.0): # Shadow to the rear pvFrontSH = 0.0; pvBackSH = 1.0; ss1 = Lc; # Ground shaded from shadow of lower edge se1 = x1 + Lhc; # to shadow of upper edge # End of if sun on front side of PV module else: # Shadow to frontside of row, either front or back might be shaded, depending on tilt and other factors if (Lc < Lhc + x1): pvFrontSH = 0.0; pvBackSH = 1.0; ss1 = Lc; # Shadow starts at Lc se1 = Lhc + x1; # Shadow ends here else: pvFrontSH = 1.0; pvBackSH = 0.0; ss1 = Lhc + x1; # Shadow starts at Lhc + x1 se1 = Lc; # Shadow ends here # End of shadow to front of row delta = rtr / 100.0; x = -delta / 2.0; # Initialize horizontal dimension x to provide midpoof intervals for i in range(0,100): x += delta; if (x >= ss1 and x < se1): rearGroundSH.append(1); # x within a shaded interval, set groundSH to 1 to indicate shaded else: rearGroundSH.append(0); # x not within a shaded interval, set groundSH to 0 to indicated not shaded, i.e. sunny x = -rtr - delta / 2.0; # Initialize horizontal dimension x to provide midpoof intervals for front interval for i in range(0,100): x += delta; if (x >= ss1 and x < se1): frontGroundSH.append(1); # x within a shaded interval, set groundSH to 1 to indicate shaded else: frontGroundSH.append(0); # x not within a shaded interval, set groundSH to 0 to indicated not shaded, i.e. sunny # End of if row type == "single" else: print ("ERROR: Incorrect row type not passed to function GetGroundShadedFactors "); if (abs(ss1) > abs(se1)): # Maximum shadow length projected from the front of the PV module row maxShadow = ss1; else: maxShadow = se1; #Console.WriteLine("elv = 0,6:0.00 azm = 1,6:0.00 sazm = 2,6:0.00", elv * 180.0 / math.pi, azm * 180.0 / math.pi, sazm * 180.0 / math.pi); #Console.WriteLine("ss1 = 0,6:0.0000 se1 = 1,6:0.0000 ss2 = 2,6:0.0000 se2 = 3,6:0.0000 rtr = 4,6:0.000", ss1, se1, ss2, se2, rtr); #Console.WriteLine("pvFrontSH = 0,6:0.00 pvBackSH = 1,6:0.00", pvFrontSH, pvBackSH); # End of GetGroundShadedFactors #print "rearGroundSH", rearGroundSH[0] return pvFrontSH, pvBackSH, maxShadow, rearGroundSH, frontGroundSH; # End of getGroundShadeFactors def getSkyConfigurationFactors(rowType, beta, C, D): """ This method determines the sky configuration factors for points on the ground from the leading edge of one row of PV panels to the leading edge of the next row of PV panels behind it. This row-to-row dimension is divided into 100 ground segments and a sky configuration factor is returned for each ground segment. The sky configuration factor represents the fraction of the isotropic diffuse sky radiation (unobstructed) that is present on the ground when partially obstructed by the rows of PV panels. The equations follow that on pages in the notebook dated 8/12/2015. 8/20/2015 4/15/2016 Modifed for calculations other than just the interior rows. Row type is identified with the string `rowType`, with the possilbe values: * first = first row of the array * interior = interior row of array * last = last row of the array * single = a single row array Because the sky configuration factors may now be different depending on row, they are calculated for the row-to-row dimension to the rear of the leading module edge and to the front of the leading edge. Parameters ---------- rowType : str "first", "interior", "last", or "single" beta : float Tilt from horizontal of the PV modules/panels (deg) C : float Ground clearance of PV panel (in PV module/panel slope lengths) D : float Horizontal distance between rows of PV panels (in PV module/panel slope lengths) Returns ------- rearSkyConfigFactors : array of size [100] Sky configuration factors to rear of leading PVmodule edge (decimal fraction) frontSkyConfigFactors : array of size [100] Sky configuration factors to rear of leading PVmodule edge (decimal fraction) Notes ----- The horizontal distance between rows, `D`, is from the back edge of one row to the front edge of the next, and it is not the row-to-row spacing. """ rearSkyConfigFactors = [] frontSkyConfigFactors = [] # Tilt from horizontal of the PV modules/panels, in radians beta = beta * DTOR # Vertical height of sloped PV panel (in PV panel slope lengths) h = math.sin(beta) # Horizontal distance from front of panel to rear of panel (in PV panel # slope lengths) x1 = math.cos(beta) rtr = D + x1 # Row-to-row distance (in PV panel slope lengths) # Forced fix for case of C = 0 # FIXME: for some reason the Config Factors go from 1 to 2 and not 0 to 1. # TODO: investigate why this is happening in the code. if C==0: C=0.0000000001 if C < 0: LOGGER.error( "Height is below ground level. Function GetSkyConfigurationFactors" " will continue but results might be unreliable") # Divide the row-to-row spacing into 100 intervals and calculate # configuration factors delta = rtr / 100.0 if (rowType == "interior"): # Initialize horizontal dimension x to provide midpoint of intervals x = -delta / 2.0 for i in range(0,100): x += delta # <--rtr=x1+D--><--rtr=x1+D--><--rtr=x1+D--> # |\ |\ |\ |\ # | \ ` | \ | \ /| \ # h \ ` h \ h \ / h \ # | \ ` | \ | \ / | \ # |_x1_\____D__`|_x1_\____D___|_x1_\_/_D____|_x1_\_ # | ` <------x-----/| # C ` / # | angA ` / angB # *------------------------`-/--------------------- # x # use ATAN2: 4-quadrant tangent instead of ATAN # check 2 rows away angA = math.atan2(h + C, (2.0 * rtr + x1 - x)) angB = math.atan2(C, (2.0 * rtr - x)) beta1 = max(angA, angB) # check 1 rows away angA = math.atan2(h + C, (rtr + x1 - x)) angB = math.atan2(C, (rtr - x)) beta2 = min(angA, angB) # check 0 rows away beta3 = max(angA, angB) beta4 = math.atan2(h + C, (x1 - x)) beta5 = math.atan2(C, (-x)) beta6 = math.atan2(h + C, (-D - x)) sky1 =0; sky2 =0; sky3 =0 if (beta2 > beta1): sky1 = 0.5 * (math.cos(beta1) - math.cos(beta2)) if (beta4 > beta3): sky2 = 0.5 * (math.cos(beta3) - math.cos(beta4)) if (beta6 > beta5): sky3 = 0.5 * (math.cos(beta5) - math.cos(beta6)) skyAll = sky1 + sky2 + sky3 # Save as arrays of values, same for both to the rear and front rearSkyConfigFactors.append(skyAll) frontSkyConfigFactors.append(skyAll) # End of if "interior" elif (rowType == "first"): # RearSkyConfigFactors don't have a row in front, calculation of sky3 # changed, beta6 = 180 degrees x = -delta / 2.0; # Initialize horizontal dimension x to provide midpoint of intervals for i in range(0,100): x += delta; angA = math.atan((h + C) / (2.0 * rtr + x1 - x)); if (angA < 0.0): angA += math.pi; angB = math.atan(C / (2.0 * rtr - x)); if (angB < 0.0): angB += math.pi; beta1 = max(angA, angB); angA = math.atan((h + C) / (rtr + x1 - x)); if (angA < 0.0): angA += math.pi; angB = math.atan(C / (rtr - x)); if (angB < 0.0): angB += math.pi; beta2 = min(angA, angB); beta3 = max(angA, angB); beta4 = math.atan((h + C) / (x1 - x)); if (beta4 < 0.0): beta4 += math.pi; beta5 = math.atan(C / (-x)); if (beta5 < 0.0): beta5 += math.pi; beta6 = math.pi; sky1 = 0.0; sky2 = 0.0; sky3 = 0.0; if (beta2 > beta1): sky1 = 0.5 * (math.cos(beta1) - math.cos(beta2)); if (beta4 > beta3): sky2 = 0.5 * (math.cos(beta3) - math.cos(beta4)); if (beta6 > beta5): sky3 = 0.5 * (math.cos(beta5) - math.cos(beta6)); skyAll = sky1 + sky2 + sky3; rearSkyConfigFactors.append(skyAll); # Save as arrays of values #Console.WriteLine("0,5:0.000,1,5:0.000,2,5:0.000,3,5:0.000,4,5:0.000", x, sky1, sky2, sky3, skyAll); #sw.WriteLine("0,5:0.000,1,5:0.000,2,5:0.000,3,5:0.000,4,5:0.000", x, sky1, sky2, sky3, skyAll); # frontSkyConfigFactors don't have a row in front, calculation of sky3 included as part of revised sky2, # beta 4 set to 180 degrees x = -delta / 2.0; # Initialize horizontal dimension x to provide midpoint of intervals for i in range(0,100): x += delta; angA = math.atan((h + C) / (2.0 * rtr + x1 - x)); if (angA < 0.0): angA += math.pi; angB = math.atan(C / (2.0 * rtr - x)); if (angB < 0.0): angB += math.pi; beta1 = max(angA, angB); angA = math.atan((h + C) / (rtr + x1 - x)); if (angA < 0.0): angA += math.pi; angB = math.atan(C / (rtr - x)); if (angB < 0.0): angB += math.pi; beta2 = min(angA, angB); beta3 = max(angA, angB); beta4 = math.pi; sky1 = 0.0; sky2 = 0.0; if (beta2 > beta1): sky1 = 0.5 * (math.cos(beta1) - math.cos(beta2)); if (beta4 > beta3): sky2 = 0.5 * (math.cos(beta3) - math.cos(beta4)); skyAll = sky1 + sky2; frontSkyConfigFactors.append(skyAll); # Save as arrays of values #Console.WriteLine("0,5:0.000,1,5:0.000,2,5:0.000,3,5:0.000,4,5:0.000", x, sky1, sky2, sky3, skyAll); #sw.WriteLine("0,5:0.000,1,5:0.000,2,5:0.000,3,5:0.000,4,5:0.000", x, sky1, sky2, sky3, skyAll); # End of if "first" elif (rowType == "last"): # RearSkyConfigFactors don't have a row to the rear, combine sky1 into sky 2, set beta 3 = 0.0 x = -delta / 2.0; # Initialize horizontal dimension x to provide midpoint of intervals for i in range(0,100): x += delta; beta3 = 0.0; beta4 = math.atan((h + C) / (x1 - x)); if (beta4 < 0.0): beta4 += math.pi; beta5 = math.atan(C / (-x)); if (beta5 < 0.0): beta5 += math.pi; beta6 = math.atan((h + C) / (-D - x)); if (beta6 < 0.0): beta6 += math.pi; sky2 = 0.0; sky3 = 0.0; if (beta4 > beta3): sky2 = 0.5 * (math.cos(beta3) - math.cos(beta4)); if (beta6 > beta5): sky3 = 0.5 * (math.cos(beta5) - math.cos(beta6)); skyAll = sky2 + sky3; rearSkyConfigFactors.append(skyAll); # Save as arrays of values #Console.WriteLine("0,5:0.000,1,5:0.000,2,5:0.000,3,5:0.000,4,5:0.000", x, sky1, sky2, sky3, skyAll); #sw.WriteLine("0,5:0.000,1,5:0.000,2,5:0.000,3,5:0.000,4,5:0.000", x, sky1, sky2, sky3, skyAll); # FrontSkyConfigFactors have beta1 = 0.0 x = -delta / 2.0; # Initialize horizontal dimension x to provide midpoint of intervals for i in range(0,100): x += delta; angA = math.atan((h + C) / (2.0 * rtr + x1 - x)); if (angA < 0.0): angA += math.pi; angB = math.atan(C / (2.0 * rtr - x)); if (angB < 0.0): angB += math.pi; beta1 = max(angA, angB); beta1 = 0.0; angA = math.atan((h + C) / (rtr + x1 - x)); if (angA < 0.0): angA += math.pi; angB = math.atan(C / (rtr - x)); if (angB < 0.0): angB += math.pi; beta2 = min(angA, angB); beta3 = max(angA, angB); beta4 = math.atan((h + C) / (x1 - x)); if (beta4 < 0.0): beta4 += math.pi; beta5 = math.atan(C / (-x)); if (beta5 < 0.0): beta5 += math.pi; beta6 = math.atan((h + C) / (-D - x)); if (beta6 < 0.0): beta6 += math.pi; sky1 = 0.0; sky2 = 0.0; sky3 = 0.0; if (beta2 > beta1): sky1 = 0.5 * (math.cos(beta1) - math.cos(beta2)); if (beta4 > beta3): sky2 = 0.5 * (math.cos(beta3) - math.cos(beta4)); if (beta6 > beta5): sky3 = 0.5 * (math.cos(beta5) - math.cos(beta6)); skyAll = sky1 + sky2 + sky3; frontSkyConfigFactors.append(skyAll); # Save as arrays of values, #Console.WriteLine("0,5:0.000,1,5:0.000,2,5:0.000,3,5:0.000,4,5:0.000", x, sky1, sky2, sky3, skyAll); #sw.WriteLine("0,5:0.000,1,5:0.000,2,5:0.000,3,5:0.000,4,5:0.000", x, sky1, sky2, sky3, skyAll); # End of if "last" row elif (rowType == "single"): # RearSkyConfigFactors don't have a row to the rear ir front, combine sky1 into sky 2, set beta 3 = 0.0, # for sky3, beta6 = 180.0. x = -delta / 2.0; # Initialize horizontal dimension x to provide midpoint of intervals for i in range(0,100): x += delta; beta3 = 0.0; beta4 = math.atan((h + C) / (x1 - x)); if (beta4 < 0.0): beta4 += math.pi; beta5 = math.atan(C / (-x)); if (beta5 < 0.0): beta5 += math.pi; beta6 = math.pi; sky2 = 0.0; sky3 = 0.0; if (beta4 > beta3): sky2 = 0.5 * (math.cos(beta3) - math.cos(beta4)); if (beta6 > beta5): sky3 = 0.5 * (math.cos(beta5) - math.cos(beta6)); skyAll = sky2 + sky3; rearSkyConfigFactors.append(skyAll); # Save as arrays of values #Console.WriteLine("0,5:0.000,1,5:0.000,2,5:0.000,3,5:0.000,4,5:0.000", x, sky1, sky2, sky3, skyAll); #sw.WriteLine("0,5:0.000,1,5:0.000,2,5:0.000,3,5:0.000,4,5:0.000", x, sky1, sky2, sky3, skyAll); # FrontSkyConfigFactors have only a row to the rear, combine sky3 into sky2, set beta1 = 0, beta4 = 180 x = -delta / 2.0; # Initialize horizontal dimension x to provide midpoint of intervals for i in range(0,100): x += delta; angA = math.atan((h + C) / (2.0 * rtr + x1 - x)); if (angA < 0.0): angA += math.pi; angB = math.atan(C / (2.0 * rtr - x)); if (angB < 0.0): angB += math.pi; beta1 = max(angA, angB); beta1 = 0.0; angA = math.atan((h + C) / (rtr + x1 - x)); if (angA < 0.0): angA += math.pi; angB = math.atan(C / (rtr - x)); if (angB < 0.0): angB += math.pi; beta2 = min(angA, angB); beta3 = max(angA, angB); beta4 = math.pi; sky1 = 0.0; sky2 = 0.0; if (beta2 > beta1): sky1 = 0.5 * (math.cos(beta1) - math.cos(beta2)); if (beta4 > beta3): sky2 = 0.5 * (math.cos(beta3) - math.cos(beta4)); skyAll = sky1 + sky2; frontSkyConfigFactors.append(skyAll); # Save as arrays of values #Console.WriteLine("0,5:0.000,1,5:0.000,2,5:0.000,3,5:0.000,4,5:0.000", x, sky1, sky2, sky3, skyAll); #sw.WriteLine("0,5:0.000,1,5:0.000,2,5:0.000,3,5:0.000,4,5:0.000", x, sky1, sky2, sky3, skyAll); # End of if "single" else: print("ERROR: Incorrect row type not passed to function GetSkyConfigurationFactors "); return rearSkyConfigFactors, frontSkyConfigFactors; # End of GetSkyConfigurationFactors def rowSpacing(beta, sazm, lat, lng, tz, hour, minute): """ This method determines the horizontal distance D between rows of PV panels (in PV module/panel slope lengths) for no shading on December 21 (north hemisphere) June 21 (south hemisphere) for a module tilt angle beta and surface azimuth sazm, and a given latitude, longitude, and time zone and for the time passed to the method (typically 9 am). (Ref: the row-to-row spacing is then ``D + cos(beta)``) 8/21/2015 Parameters ---------- beta : double Tilt from horizontal of the PV modules/panels (deg) sazm : double Surface azimuth of the PV modules/panels (deg) lat : double Site latitude (deg) lng : double Site longitude (deg) tz : double Time zone (hrs) hour : int hour for no shading criteria minute: double minute for no shading Returns ------- D : numeric Horizontal distance between rows of PV panels (in PV panel slope lengths) """ beta = beta * DTOR # Tilt from horizontal of the PV modules/panels, in radians sazm = sazm * DTOR # Surface azimuth of PV module/pamels, in radians if lat >= 0: [azm, zen, elv, dec, sunrise, sunset, Eo, tst] = solarPos (2014, 12, 21, hour, minute, lat, lng, tz) else: [azm, zen, elv, dec, sunrise, sunset, Eo, tst] = solarPos (2014, 6, 21, hour, minute, lat, lng, tz) tst = 8.877 ##DLL Forced value minute -= 60.0 * (tst - hour); # Adjust minute so sun position is calculated for a tst equal to the # time passed to the function if lat >= 0: [azm, zen, elv, dec, sunrise, sunset, Eo, tst] = solarPos(2014, 12, 21, hour, minute, lat, lng, tz) else: [azm, zen, elv, dec, sunrise, sunset, Eo, tst] = solarPos(2014, 6, 21, hour, minute, lat, lng, tz) # Console.WriteLine("tst = {0} azm = {1} elv = {2}", tst, azm * 180.0 / Math.PI, elv * 180.0 / Math.PI); D = math.cos(sazm - azm) * math.sin(beta) / math.tan(elv) return D # End of RowSpacing def trackingBFvaluescalculator(beta, hub_height, r2r): ''' 1-axis tracking helper file Parameters ---------- beta : float Tilt from horizontal of the PV modules/panels, in radians hub_height : float tracker hub height r2r : float Row-to-row distance (in PV panel slope lengths) Returns ------- C : float ground clearance of PV panel D : float row-to-row distance (each in PV panel slope lengths) ''' # Created on Tue Jun 13 08:01:56 2017 # @author: sayala beta = beta * DTOR # Tilt from horizontal of the PV modules/panels, in radians x1 = math.cos(beta); # Horizontal distance from front of panel to rear of panel (in PV panel slope lengths) #rtr = D + x1; # Row-to-row distance (in PV panel slope lengths) D = r2r - x1; # Calculates D DistanceBetweenRows(panel slope lengths) hm = 0.5*math.sin(beta); # vertical distance from bottom of panel to top of panel (in PV panel slope lengths) #C = 0.5+Cv-hm # Ground clearance of PV panel (in PV panel slope lengths). C = hub_height - hm #Adding a 0.5 for half a panel slope length, since it is assumed the panel is rotating around its middle axis return C, D
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 7680, 41384, 8265, 532, 569, 37, 17952, 31904, 3696, 329, 275, 361, 18150, 12, 1177, 31412, 198, 220, 220, 220, 220, 198, 31, 9800, 3941, 32473, 198, 31, 7...
1.937812
40,683
from slisonner import decoder, encoder from tests import mocker from tempfile import mkdtemp from shutil import rmtree
[ 6738, 1017, 1653, 1008, 1330, 875, 12342, 11, 2207, 12342, 198, 6738, 5254, 1330, 285, 12721, 198, 6738, 20218, 7753, 1330, 33480, 67, 29510, 198, 6738, 4423, 346, 1330, 374, 16762, 631, 628 ]
3.636364
33
# -*- coding: utf-8 -*- # Copyright (c) 2018, Tridots Tech Pvt. Ltd. and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.website.website_generator import WebsiteGenerator
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 357, 66, 8, 2864, 11, 833, 312, 1747, 9634, 18367, 83, 13, 12052, 13, 290, 20420, 198, 2, 1114, 5964, 1321, 11, 3387, 766, 5964, 13, 14116, 198, 198, 6738,...
3.315789
76
import matplotlib.pyplot as plt import math xtab = [] ytab = [] for i in range(0, 628): # Calculate polar coordinates for provided equation phi = float(i) / 100.0 r = 4 * math.cos(2 * phi) # Convert to Cartesian and store in lists x = r * math.cos(phi) y = r * math.sin(phi) xtab.append(x) ytab.append(y) plt.plot(xtab, ytab) plt.show()
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 10688, 628, 198, 742, 397, 796, 17635, 198, 88, 8658, 796, 17635, 198, 198, 1640, 1312, 287, 2837, 7, 15, 11, 718, 2078, 2599, 198, 220, 220, 220, 1303, 27131, 378...
2.282209
163
# Copyright (c) 2003-2010 LOGILAB S.A. (Paris, FRANCE). # http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free Software # Foundation; either version 2 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, write to the Free Software Foundation, Inc., # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # copyright 2003-2010 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # copyright 2003-2010 Sylvain Thenault, all rights reserved. # contact mailto:thenault@gmail.com # # This file is part of logilab-astng. # # logilab-astng is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # logilab-astng 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 Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-astng. If not, see <http://www.gnu.org/licenses/>. """ logilab.astng packaging information """ distname = 'logilab-astng' modname = 'astng' subpackage_of = 'logilab' numversion = (0, 20, 1) version = '.'.join([str(num) for num in numversion]) install_requires = ['logilab-common >= 0.49.0'] pyversions = ["2.3", "2.4", "2.5", '2.6'] license = 'LGPL' author = 'Logilab' author_email = 'python-projects@lists.logilab.org' mailinglist = "mailto://%s" % author_email web = "http://www.logilab.org/project/%s" % distname ftp = "ftp://ftp.logilab.org/pub/%s" % modname short_desc = "rebuild a new abstract syntax tree from Python's ast" long_desc = """The aim of this module is to provide a common base \ representation of python source code for projects such as pychecker, pyreverse, pylint... Well, actually the development of this library is essentially governed by pylint's needs. It rebuilds the tree generated by the compiler.ast [1] module (python <= 2.4) or by the builtin _ast module (python >= 2.5) by recursively walking down the AST and building an extended ast (let's call it astng ;). The new node classes have additional methods and attributes for different usages. Furthermore, astng builds partial trees by inspecting living objects.""" from os.path import join include_dirs = [join('test', 'regrtest_data'), join('test', 'data'), join('test', 'data2')]
[ 2, 15069, 357, 66, 8, 5816, 12, 10333, 41605, 4146, 6242, 311, 13, 32, 13, 357, 40313, 11, 8782, 19240, 737, 198, 2, 2638, 1378, 2503, 13, 6404, 346, 397, 13, 8310, 14, 1377, 6920, 1462, 25, 32057, 31, 6404, 346, 397, 13, 8310, ...
3.278481
948
import torch import torch.nn as nn
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 628, 220, 220, 220, 220, 198 ]
2.5625
16
import fire import gtfparse from pathlib import Path GENCODE_CATEGORY_MAP = { 'IG_C_gene': 'protein_coding', 'IG_D_gene': 'protein_coding', 'IG_J_gene': 'protein_coding', 'IG_V_gene': 'protein_coding', 'IG_LV_gene': 'protein_coding', 'TR_C_gene': 'protein_coding', 'TR_J_gene': 'protein_coding', 'TR_V_gene': 'protein_coding', 'TR_D_gene': 'protein_coding', 'TEC': 'protein_coding', 'nonsense_mediated_decay': 'protein_coding', 'non_stop_decay': 'protein_coding', 'retained_intron': 'lncRNA', 'protein_coding': 'protein_coding', 'ambiguous_orf': 'lncRNA', 'Mt_rRNA': 'ncRNA', 'Mt_tRNA': 'ncRNA', 'miRNA': 'ncRNA', 'misc_RNA': 'ncRNA', 'rRNA': 'ncRNA', 'snRNA': 'ncRNA', 'snoRNA': 'ncRNA', 'ribozyme': 'ncRNA', 'sRNA': 'ncRNA', 'scaRNA': 'ncRNA', 'scRNA': 'ncRNA', 'non_coding': 'lncRNA', 'known_ncrna': 'ncRNA', '3prime_overlapping_ncrna': 'lncRNA', '3prime_overlapping_ncRNA': 'lncRNA', 'vaultRNA': 'ncRNA', 'processed_transcript': 'lncRNA', 'lincRNA': 'lncRNA', 'macro_lncRNA': 'lncRNA', 'sense_intronic': 'lncRNA', 'sense_overlapping': 'lncRNA', 'antisense': 'lncRNA', 'antisense_RNA': 'lncRNA', 'bidirectional_promoter_lncRNA': 'lncRNA', 'IG_pseudogene': 'pseudogene', 'IG_D_pseudogene': 'pseudogene', 'IG_C_pseudogene': 'pseudogene', 'IG_J_pseudogene': 'pseudogene', 'IG_V_pseudogene': 'pseudogene', 'TR_V_pseudogene': 'pseudogene', 'TR_J_pseudogene': 'pseudogene', 'Mt_tRNA_pseudogene': 'pseudogene', 'tRNA_pseudogene': 'pseudogene', 'snoRNA_pseudogene': 'pseudogene', 'snRNA_pseudogene': 'pseudogene', 'scRNA_pseudogene': 'pseudogene', 'rRNA_pseudogene': 'pseudogene', 'misc_RNA_pseudogene': 'pseudogene', 'miRNA_pseudogene': 'pseudogene', 'pseudogene': 'pseudogene', 'processed_pseudogene': 'pseudogene', 'polymorphic_pseudogene': 'pseudogene', 'retrotransposed': 'pseudogene', 'transcribed_processed_pseudogene': 'pseudogene', 'transcribed_unprocessed_pseudogene': 'pseudogene', 'transcribed_unitary_pseudogene': 'pseudogene', 'translated_processed_pseudogene': 'pseudogene', 'translated_unprocessed_pseudogene': 'pseudogene', 'unitary_pseudogene': 'pseudogene', 'unprocessed_pseudogene': 'pseudogene', 'novel_lncRNA': 'lncRNA', 'TUCP': 'TUCP', 'lncRNA': 'lncRNA' } if __name__ == '__main__': fire.Fire(split_gtf)
[ 11748, 2046, 198, 11748, 308, 27110, 29572, 198, 6738, 3108, 8019, 1330, 10644, 628, 198, 38, 24181, 16820, 62, 34, 6158, 38, 15513, 62, 33767, 796, 1391, 198, 220, 220, 220, 705, 3528, 62, 34, 62, 70, 1734, 10354, 705, 48693, 62, 6...
2.121931
1,181
import math q1=Q(1,2) q2=Q(1,3) print(q1/q2)
[ 11748, 10688, 201, 198, 201, 198, 201, 198, 80, 16, 28, 48, 7, 16, 11, 17, 8, 201, 198, 80, 17, 28, 48, 7, 16, 11, 18, 8, 201, 198, 4798, 7, 80, 16, 14, 80, 17, 8 ]
1.342105
38
from __future__ import unicode_literals import glob import os from dbdiff.fixture import Fixture from .base import TestImportBase, FixtureDir from ..settings import DATA_DIR
[ 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 11748, 15095, 198, 11748, 28686, 198, 198, 6738, 288, 17457, 733, 13, 69, 9602, 1330, 376, 9602, 198, 6738, 764, 8692, 1330, 6208, 20939, 14881, 11, 376, 9602, 35277,...
3.490196
51
import datetime import logging import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv from .const import ( CONF_PLANT_ID, ) _LOGGER = logging.getLogger(__name__) MIN_TIME_BETWEEN_UPDATES = datetime.timedelta(seconds=600) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_PLANT_ID): cv.string, } )
[ 11748, 4818, 8079, 198, 11748, 18931, 198, 198, 11748, 2322, 37623, 5623, 355, 2322, 198, 198, 6738, 1363, 562, 10167, 13, 5589, 3906, 13, 82, 22854, 1330, 9297, 1404, 21389, 62, 50, 3398, 27630, 198, 6738, 1363, 562, 10167, 13, 9979, ...
2.411765
238
from flask import Blueprint, redirect, render_template, request, flash, session from database import base from database.base import User from forms import UserForm, LoginForm, MyPageUserForm from flask_login import login_required, login_user, logout_user, current_user import requests auth_blueprint = Blueprint('auth', __name__) kakao_oauth = {} def kakao_me_and_signup(): url = "https://kapi.kakao.com/v1/user/me" headers = { "Authorization": "Bearer {0}".format(kakao_oauth["access_token"]), "Content-Type": "application/x-www-form-urlencoded;charset=utf-8" } response = requests.post( url=url, headers=headers ) #print("kakao_me_and_signup", response.json()) kakao_oauth["kaccount_email"] = response.json()["kaccount_email"] kakao_oauth["id"] = response.json()["id"] kakao_oauth["kakao_profile_image"] = response.json()["properties"]["profile_image"] kakao_oauth["nickname"] = response.json()["properties"]["nickname"] kakao_oauth["kakao_thumbnail_image"] = response.json()["properties"]["thumbnail_image"] c = base.db_session.query(User).filter(User.email == kakao_oauth["kaccount_email"]).count() if c == 0: user = User(name=kakao_oauth["nickname"], email=kakao_oauth["kaccount_email"], affiliation=None) user.set_password("1234") base.db_session.add(user) base.db_session.commit()
[ 6738, 42903, 1330, 39932, 11, 18941, 11, 8543, 62, 28243, 11, 2581, 11, 7644, 11, 6246, 198, 198, 6738, 6831, 1330, 2779, 198, 6738, 6831, 13, 8692, 1330, 11787, 198, 6738, 5107, 1330, 11787, 8479, 11, 23093, 8479, 11, 2011, 9876, 129...
2.545781
557
import matplotlib.pyplot as plt def model(): """Solve u'' = -1, u(0)=0, u'(1)=0.""" import sympy as sym x, c_0, c_1, = sym.symbols('x c_0 c_1') u_x = sym.integrate(1, (x, 0, x)) + c_0 u = sym.integrate(u_x, (x, 0, x)) + c_1 r = sym.solve([u.subs(x,0) - 0, sym.diff(u,x).subs(x, 1) - 0], [c_0, c_1]) u = u.subs(c_0, r[c_0]).subs(c_1, r[c_1]) u = sym.simplify(sym.expand(u)) return u def midpoint_rule(f, M=100000): """Integrate f(x) over [0,1] using M intervals.""" from numpy import sum, linspace dx = 1.0/M # interval length x = linspace(dx/2, 1-dx/2, M) # integration points return dx*sum(f(x)) if __name__ == '__main__': import sys print(model()) print('sine 2*i+1 integral:') check_integral_b() print('sine i+1 integral, sympy answer:') check_integral_d_sympy_answer() print('sine i+1 integral:') check_integral_d() #sys.exit(0) plot_sine_sum() plt.figure() plot_sine_sum_d() plt.show()
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198, 4299, 2746, 33529, 198, 220, 220, 220, 37227, 50, 6442, 334, 7061, 796, 532, 16, 11, 334, 7, 15, 47505, 15, 11, 334, 6, 7, 16, 47505, 15, 526, 15931, 198, 220, 2...
1.861888
572
from sklearn.mixture import GaussianMixture import operator import numpy as np import math
[ 6738, 1341, 35720, 13, 76, 9602, 1330, 12822, 31562, 44, 9602, 198, 11748, 10088, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 10688, 198 ]
3.791667
24
from .heatmaploss import HeatmapLoss from .offsetloss import OffsetLoss from .refineloss import RefineLoss
[ 6738, 764, 25080, 2611, 489, 793, 1330, 12308, 8899, 43, 793, 198, 6738, 764, 28968, 22462, 1330, 3242, 2617, 43, 793, 198, 6738, 764, 5420, 20538, 793, 1330, 6524, 500, 43, 793 ]
3.3125
32
from typing import Sequence from eth.constants import ZERO_HASH32 from eth_typing import Hash32 import ssz from ssz.sedes import Vector, bytes32 from eth2.configs import Eth2Config from .defaults import default_tuple, default_tuple_of_size
[ 6738, 19720, 1330, 45835, 198, 198, 6738, 4555, 13, 9979, 1187, 1330, 1168, 34812, 62, 39, 11211, 2624, 198, 6738, 4555, 62, 774, 13886, 1330, 21059, 2624, 198, 11748, 37786, 89, 198, 6738, 37786, 89, 13, 36622, 274, 1330, 20650, 11, ...
3.210526
76
import os from pydantic import BaseSettings
[ 11748, 28686, 198, 198, 6738, 279, 5173, 5109, 1330, 7308, 26232, 628 ]
3.833333
12
import numpy as np import xarray as xr def create_bathymetry_from_land_mask(land_mask: xr.DataArray) -> xr.DataArray: """Method: identifies the lower depth bound of the shallowest ocean cell (non-null) in each vertical grid column. :param land_mask: dimensions {time, depth, lat, lon}, boloean array, True where cell is land""" assert np.all(land_mask.depth <= 0), "depth coordinate must be positive up" assert np.all( np.diff(land_mask.depth) > 0 ), "depth coordinate must be sorted ascending" # In the kernel, particles look up data based on the nearest cell-center. # Thus cell bounds are the midpoints between each centers. # Very top cell bound is surface, and bottom cell bounds are # assumed to be symmetric about bottom cell center. depth_diff = np.diff(land_mask.depth) depth_bnds = np.concatenate( [ land_mask.depth.values[:1] - depth_diff[0] / 2, land_mask.depth.values[:-1] + depth_diff / 2, [0], ] ) bathy = ( (~land_mask) .assign_coords({"depth": depth_bnds[:-1]}) .idxmax(dim="depth") .where(~land_mask.isel(depth=-1), depth_bnds[-1]) ) bathy = bathy.drop(["time", "depth"]) bathy.name = "bathymetry" bathy.attrs = {"units": "m", "positive": "up"} return bathy
[ 11748, 299, 32152, 355, 45941, 198, 11748, 2124, 18747, 355, 2124, 81, 628, 198, 4299, 2251, 62, 65, 10036, 41935, 62, 6738, 62, 1044, 62, 27932, 7, 1044, 62, 27932, 25, 2124, 81, 13, 6601, 19182, 8, 4613, 2124, 81, 13, 6601, 19182,...
2.461818
550
""" A simple python module for converting kilometers to miles or vice versa. So simple that it doesn't even have any dependencies. """ def kilometers_to_miles(dist_in_km): """ Actually does the conversion of distance from km to mi. PARAMETERS -------- dist_in_km: float A distance in kilometers. RETURNS ------- dist_in_mi: float The same distance converted to miles. """ return (dist_in_km)/1.609344 def miles_to_kilometers(dist_in_mi): """ Actually does the conversion of distance from mi to km. PARAMETERS ---------- dist_in_mi: float A distance to miles. RETURNS ------- dist_in_km: float The same distance converted to kilometers. """ return (dist_in_mi)*1.609344
[ 37811, 198, 32, 2829, 21015, 8265, 329, 23202, 18212, 284, 4608, 393, 7927, 25470, 13, 198, 2396, 2829, 326, 340, 1595, 470, 772, 423, 597, 20086, 13, 198, 37811, 198, 198, 4299, 18212, 62, 1462, 62, 76, 2915, 7, 17080, 62, 259, 62,...
2.906122
245