content
stringlengths
5
1.05M
import os import sys import inspect import pathlib import tempfile import unittest import platform import contextlib import unittest.mock import importlib.util from dffml.util.asynctestcase import AsyncTestCase from dffml.util.testing.consoletest.commands import * from dffml.util.testing.consoletest.parser import par...
# # PySNMP MIB module HC-ALARM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HC-ALARM-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:11:46 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019,...
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: out_list = ListNode(0) out_run = out_list cf = 0 while True: n1...
"""Defines an Equivalent Circuit Battery Model""" import numpy as np import math from battery import Battery from metric import Charge import config class EquivalentCircuitBattery(Battery): """Battery class with an interface that can hook up to a tester for cycling.""" def apply_potential(self, potential):...
from SpiffWorkflow.bpmn.PythonScriptEngine import Box from tests.base_test import BaseTest from unittest.mock import patch from crc import db, session from crc.api.common import ApiError from crc.models.file import FileDataModel, FileModel from crc.models.protocol_builder import ProtocolBuilderRequiredDocumentSchema...
import numpy as np def check_model(model_dict, labels, dimensions, anchoring): """Check consistency and validity of the model specification. labels, dimensions and anchoring information are done before the model checking because processing them will not raise any errors except for easy to understand ...
import csv import matplotlib.pyplot as plt Cdir = 'GH_usefull/rhino_inside_python_Nurbs' x = [] y = [] reader=csv.reader(open(Cdir + '/xy.csv', 'r')) for row in reader: try: x.append(float(row[0])) y.append(float(row[1])) except: break plt.plot(x, y) plt.show() plt.savefig(Cdir + "/nurbs.pn...
#print hello world to the Python console. print("Hello World..Welcome to Python.") print("-----------------------------") print("Hello World### ",end=' ') print("Welcome to Python..",end='\n') # import inbuilt standard input output from sys import stdin, stdout stdout.write("Hello Stdout")
#!/usr/bin/env python """ This code holds the solution for part 1 of day 10 of the Advent of Code for 2017. """ import sys def get_sublist(data, pos, length): sub_list = [0] * length count = 0 cur_pos = pos while count < length: sub_list[count] = data[cur_pos] cur_pos += 1 if...
import os from ruamel import yaml from util import load_data_into_database import great_expectations as ge from great_expectations.core.batch import BatchRequest, RuntimeBatchRequest sfAccount = os.environ.get("SNOWFLAKE_ACCOUNT") sfUser = os.environ.get("SNOWFLAKE_USER") sfPswd = os.environ.get("SNOWFLAKE_PW") sfDa...
#region Imports import json; from Models.V1 import FutureOdds, Future; from Base import ResponseBase; #endregion Imports class GetFutureOddsResponse(ResponseBase): def __init__(self, response: str): super().__init__(response); self.FutureOdds = self.ParseResponse(response); def ParseRe...
"""The Friendly data schema registry This module provides getter methods to retrieve individual columns, :func:`get`, or the whole registry, :func:`getall`. The function utilities and classes are used by the module internally. """ from itertools import chain import json from logging import getLogger from pathlib im...
#Testando as funções anonimas Lambda- ordenano uma lista lista = [ ['p1', 2], ['p2', 6], ['p3', 4], ] lista.sort(key=lambda item: item[0]) print(lista)
print('hello name') print('hello name')
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import, unicode_literals import dataproperty from mbstrdecoder import MultiByteStrDecoder from ._null_logger import NullLogger def _disable_logger(l): try: l.disable() except A...
import copy import numpy as np from models.mlm import MLMModel from models.aggnet import AggNet import os import torch import pickle as pickle import sys from collections import Counter from nltk.util import ngrams from utils.config import args, DEVICE import math import logging import gc logging.getLogger().setL...
# 7. Изготвяне на проекти # Напишете програма, която изчислява колко часове ще са необходими на един архитект, за да изготви проектите на няколко строителни обекта. Изготвянето на един проект отнема три часа. architect_name = input() project_number = int(input()) project_hours = project_number * 3 print(f"The architect...
from lassen import PE_fc as lassen_fc from metamapper.common_passes import print_dag, Constant2CoreIRConstant, gen_dag_img from metamapper.irs.coreir import gen_CoreIRNodes import metamapper.coreir_util as cutil import metamapper.peak_util as putil from metamapper.node import Nodes from metamapper import CoreIRContext...
import multiprocessing import socket ############################################## NET MANAGER AREA ############################################## class NET_MANAGER: __default_port = 12000 __default_net_ip = None __default_net_socket = None __connection_server = None __connection_manager = None __connection_...
# -*- coding: utf-8 -*- # Copyright 2018, Carsten Blank. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. import logging import unittest import numpy import qiskit from qiskit.providers import BaseBackend from scipy imp...
from django.contrib.auth import login, get_user_model from django.contrib.auth.forms import PasswordResetForm, SetPasswordForm from django.contrib.auth.models import AnonymousUser from django.contrib.sites.models import get_current_site from django.conf import settings from django.template import loader from django.con...
import random from koon.geo import Vec2D from koon.res import resman from event import Event class Pickup (object): """Object that cars can pick up. container: the object that owns this pickup """ def __init__( self ): self._is_good = True self.container = None self.jump_c...
x = int(input()) if x == 1: print("Hello World") else: a = int(input()) b = int(input()) print(a+b)
__version__='1.3.1' from .util import fuse_model from .util import post_training_quant
#!/usr/bin/env python3 import sys import os import re #see https://stackoverflow.com/questions/16982625/only-accept-alphanumeric-characters-and-underscores-for-a-string-in-python#16982669 if sys.version_info >= (3, 0): _w = re.compile("^\w+$", re.A) # str.isalnum(this_char) or this_char=="_" else: _w = re.co...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import django.db.models.deletion from django.conf import settings from django.db import migrations, models from django.db.models.fields import GenericIPAddressField as IPAddressField import wiki.plugins.attachments.models class Migration(migrations.Mig...
# -*- coding: utf-8 -*- from functions import luck from datetime import datetime import unittest class Test_Functions_Luck(unittest.TestCase): def test_get_luck(self): test_time = datetime(2000, 1, 1, 0, 0) test_uid = 100000000 self.assertEqual(luck.get_luck(test_uid,test_time), u'...
""" This file contains only functions that deal with the version of the repository. It can set a new version as a tag and look up the current version. """ import subprocess import logging import os from vdt.version.shared import VersionError, VersionNotFound, Version log = logging.getLogger('vdt.versionplugin.defaul...
# Copyright 2021 AIPlan4EU project # # 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 wri...
from django.utils.safestring import SafeText as S from django.utils.six import with_metaclass from . import FormPresentationItem,FormPresentationBoundItem class FormPresentationMetaclass(type): """Metaclass to create items and form objects on the FormPresentation instance.""" def __new__(meta,name,bases,attr...
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='Equivariant-GNNs', version='0.0.0', description='An environment for running experiments with equivariant GNN architectures', author='Alex Morehead', author_email='alex.morehead@gmail.com', url='https://github.com/am...
# Generated by Django 3.0.2 on 2020-01-28 15:29 from django.conf import settings import django.contrib.auth.models from django.db import migrations, models import django.db.models.deletion import django.db.models.manager class Migration(migrations.Migration): dependencies = [ ('login', '0001_initial'), ...
from sit2standpy.core import Sit2Stand from sit2standpy import detectors from sit2standpy.utility import mov_stats, Transition from sit2standpy.processing import AccelerationFilter, process_timestamps from sit2standpy.quantify import TransitionQuantifier from sit2standpy import v2 from sit2standpy.version import __vers...
# Copyright (c) 2020 PaddlePaddle 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 app...
#!/usr/bin/env python import os, sys import json import messytables import subprocess from dgitcore.helper import cd from dgitcore.plugins.instrumentation import InstrumentationBase from dgitcore.config import get_config def run(cmd): output = subprocess.check_output(cmd, std...
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def hasCycle(self, head: ListNode) -> bool: """ 解法一:快慢指针,每一次,快指针走2步,慢指针走1步 :param head: :return: """ if head is None: ...
# -*- coding: utf-8 -*- """ Nordic file format support for ObsPy :copyright: The ObsPy Development Team (devs@obspy.org) :license: GNU Lesser General Public License, Version 3 (https://www.gnu.org/copyleft/lesser.html) .. note:: Currently does not read nor write moment tensors or focal mechanism ...
# Copyright (c) 2021 Graphcore Ltd. All rights reserved. import popart.ir as pir import popart.ir.ops as ops import popart._internal.ir as _ir from utils import contains_op_of_type from popart import popart_exception import pytest class TestSplit: def test_fn_int(self): ir = pir.Ir() g = ir.main_g...
#!/usr/bin/python # ============================================================================== # Author: Tao Li (taoli@ucsd.edu) # Date: May 1, 2015 # Question: 141-Linked-List-Cycle # Link: https://leetcode.com/problems/binary-tree-preorder-traversal/ # ===================================================...
import os import pandas as pd variables = { 'subject': 'poll_subject', 'modeldate': 'date_modeled', 'approve_estimate': 'pct_approve_estimate', 'disapprove_estimate': 'pct_disapprove_estimate' } def clean(data): df = pd.DataFrame(data) # Rename the file headers df.rename(variables, axis=...
"""Middleware for launch views.""" from django.conf import settings from lti_app import strings from lti_app.launch import exceptions from lti_app.core import services from lti.contrib import django as lti_django class ValidLaunchMiddleware: """A middleware to check if a launch request is a valid one.""" d...
from pathlib import Path import yaml class MetadataFile(dict): def __init__(self, location: Path): self.location = location self.load() def load(self): with self.location.open('r') as stream: self.update(yaml.safe_load(stream)) def save(self): with self.locat...
# Generated by Django 3.0.3 on 2020-10-24 23:53 import camphoric.models import django.contrib.postgres.fields.jsonb from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('camphoric', '0012_auto_20200530_1635'), ] opera...
# -*- coding: utf-8 -*- from pystructs import fields from pystructs.models import StructObject def test_simple_object(): """test a simple class type with a single field to be unpacked""" data = b'\x00\x00\x00\x01' class Sized(StructObject): size = fields.IntegerField() s = Sized() s.unpac...
# -*- coding: utf-8 -*- from math import log import numpy as np __author__ = 'Rafael Martin-Cuevas Redondo' class QuantumGate: def __init__(self, matrix, identifier='A'): if not isinstance(matrix, np.matrix): raise TypeError("The gate's matrix must be a Numpy 2D matrix.") elif matrix...
#!/usr/bin/env python3 import time, argparse import numpy as np from context import arkouda as ak from base_test import ArkoudaTest def check_int(N): z = ak.zeros(N, dtype=ak.int64) a2 = ak.randint(0, 2**16, N) b2 = ak.randint(0, 2**16, N) c2 = ak.randint(0, 2**16, N) d2 = ak.randint(0, 2**16, N...
# Enter your code here. Read input from STDIN. Print output to STDOUT class Query(): def __init__(self, command, operand_set): self.command = command self.operand_set = operand_set from typing import Set def query_handler( set_a:Set, query_entry:Query ): if query_entry.command == "intersect...
import asyncio import logging from contextlib import suppress # Base PeriodicTimer that executes some action after started time runs out class PeriodicTimer: def __init__(self, func, time): self.func = func self.time = time self.is_started = False self._task = None async def s...
#!/usr/bin/env python -u ############################################################################## # # Copyright (c) 2007 Agendaless Consulting and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the BSD-like license at # http://www.repoze.org/LICENSE.txt. A copy of the lice...
# Copyright 2017 - Nokia # # 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...
def findDecision(obj): #obj[0]: Coupon, obj[1]: Education, obj[2]: Occupation, obj[3]: Distance # {"feature": "Coupon", "instances": 85, "metric_value": 0.9975, "depth": 1} if obj[0]>0: # {"feature": "Occupation", "instances": 70, "metric_value": 0.9518, "depth": 2} if obj[2]>0: # {"feature": "Distance", "inst...
""" This module contains tests for mixins defined, and checks that the behavior of the mixins which compose more specific mixins (such as RequiresOnlyType) is correct. Uses simple equivalence partitions. """ import copy import unittest from uuid import UUID from pydantic import BaseModel, Field, conint from pydantic.f...
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.chrome.options import Options import unittest class...
import argparse import base64 import sys import uuid RECORD_COMMANDS = [ 'create', 'get', 'set', 'inc', 'dec', 'delete', 'find', ] def printRecord(nf, recordId, fields=None): if not fields: print(recordId) else: record = nf.get(recordId) ...
import time, DAN, requests, random from bs4 import BeautifulSoup #解析html網頁 from datetime import datetime #handle timestamp ServerURL = 'http://140.113.199.189:9999' #with no secure connection #ServerURL = 'https://DomainName' #with SSL connection Reg_addr = None #if None, Reg_addr = MAC address DAN.profile['d...
from sys import stdin from operator import itemgetter class RangeAddSegmentTree: def __init__(self, size): self._size = size t = 1 while t < size: t *= 2 self._offset = t - 1 self._data = [0] * (t * 2 - 1) def range_add(self, start, stop, x): data =...
''' Date: 2021-02-07 10:48:03 LastEditors: Jecosine LastEditTime: 2021-02-07 11:00:08 ''' class User(object): def __init__(self): self.username = '' self.password = ''
import torch from .entropy import TotalVariation, Range from .sinkhorn import BatchVanillaSinkhorn from .utils import dist_matrix def regularized_ot( a, x, b, y, cost, entropy, solver=BatchVanillaSinkhorn( nits=100, nits_grad=5, tol=1e-3, assume_convergence=True ), ): f_x, ...
#!/usr/bin/env python # File: server.py import BaseHTTPServer import cgi import SimpleHTTPServer import sys import time from mailgunner import MailGunHandler from mandriller import MandrillHandler from log import logColor ServerClass = BaseHTTPServer.HTTPServer # HTTP requests handler. class ContactorRequestHandler(...
#!/usr/bin/env python from collections import defaultdict from utils.utils import get_input import re import math WANTED = "FUEL" MAX_ORE = 10 ** 12 chem_store = defaultdict(int) reactions_inverted = {} def how_often_reaction(required_amount, resulting_amount): return math.ceil(required_amount / resulting_amo...
from __future__ import unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ class StandardMetadata(models.Model): """ A basic (abstract) model for metadata. """ created = models.DateTimeField(_('Created'), auto_now=True) updated = models.DateTimeFi...
#!/usr/bin/env python # quicksort.py import numpy as np from mpi4py import MPI comm = MPI.COMM_WORLD rank = comm.Get_rank(); size = comm.Get_size(); status = MPI.Status(); N = 16 HAS = 1 HASNOT = 0 unsorted = np.zeros(N, dtype="int") final_sorted = np.zeros(N, dtype="int") local_array = None local_tmp = None local_tmp_...
from kivymd.uix.screen import MDScreen class LoginScreen(MDScreen): pass
from flask_wtf import FlaskForm from wtforms import StringField, SubmitField, BooleanField, PasswordField from wtforms.validators import DataRequired, EqualTo, Length, ValidationError from app.models import Employee class RegistrationForm(FlaskForm): username = StringField('Username', validators=[DataRequired(), L...
#!/usr/bin/env python3 # # Copyright (c) 2015, Roberto Riggio # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, t...
# -*- coding: utf-8 -*- import visa import numpy as np import time ''' Updated by Micah Black July 2019: Changes: BK8600 E-Load: - Support CV, CR, CP modes - Support use of Remote Sense Features - Support triggering timers - Support Transients (current, voltage, resistance, power) - Support for lists of cur...
# -*- coding: utf-8 -*- """ A simple countdown timer. This is a very basic countdown timer. You can change the timer length as well as pausing, restarting and resetting it. Currently this is more of a demo of a composite. Each part of the timer can be changed independently hours, minutes, seconds using mouse button...
"""Added created date field to script model 2 Revision ID: da4a08d36859 Revises: 4e99af2a12a7 Create Date: 2020-05-18 21:42:54.271163 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = "da4a08d36859" down_revision = "4e99af2a12a7" branch_labels = None depends_on =...
# -*- coding: utf-8 -*- # Copyright 2012 Google Inc. 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 require...
################################################## # Caution: returned LDRs are sorted by L-M-H, RGB ################################################## import tensorflow as tf GAMMA = 2.2 # LDR&HDR domain transform parameter def LDR2HDR(img, expo): # input/output -1~1 return (((img+1)/2.)**GAMMA / expo) *2.-1 de...
# -*- coding: utf-8 -*- # FOGLAMP_BEGIN # See: http://foglamp.readthedocs.io/ # FOGLAMP_END """ Storage layer python client payload builder """ __author__ = "Amarendra K Sinha" __copyright__ = "Copyright (c) 2017 OSIsoft, LLC" __license__ = "Apache 2.0" __version__ = "${VERSION}" from collections import OrderedDict...
#: Object types for object ids object_type = {} object_type["null"] = 0 object_type["base"] = 1 object_type["account"] = 2 object_type["OBJECT_TYPE_COUNT"] = 3
import numpy as np import matplotlib.pyplot as plt from skimage import color from tqdm import tqdm import pprint import scipy.ndimage as ndimage pp = pprint.PrettyPrinter(indent=4) # Threshold for flood fill threshold = 15. # Merge areas with a size of 3 pixels or less with their surrounding threshold_cell_size = 3 ...
import click from DeepNovelARG.predict import predict from DeepNovelARG.fasta2vec import fasta2vec from DeepNovelARG.train import train from DeepNovelARG.train_word_vectors import train_word_vectors @click.group() def cli(): ''' novelDeepARG: A deep learning approach for the identification of novel ARGs. ...
from CTFd.plugins import register_plugin_assets_directory from models import Dependencies from routes import plugin_blueprint, get_available_challenges from utils import satisfies_challenge_dependencies, satisfies_hint_dependencies def load(app): def wrap_method(name, wrapper): old = app.view_functions[nam...
from yandeley.models.base_documents import BaseDocument, BaseClientView, BaseBibView from yandeley.response import LazyResponseObject class CatalogDocument(BaseDocument): """ Base class for catalog documents. .. attribute:: id .. attribute:: title .. attribute:: type .. attribute:: source ...
from .measures.nfoldcrossvalidation import foldgenerator, getfold, nfoldcrossvalidation
import json import logging import os import threading import time import traceback from collections import defaultdict from typing import List from opencensus.stats import aggregation from opencensus.stats import measure as measure_module from opencensus.stats.measurement_map import MeasurementMap from opencensus.sta...
from .generator import QuantumRandomNumberGenerator
#!/usr/bin/env python import numpy import scipy import sys print sys.version print "numpy", numpy.__version__ print "scipy", scipy.__version__
# -------------- # import packages import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import warnings warnings.filterwarnings("ignore") # Load the dataset df = pd.read_csv(path, sep="\t") # Converting date attribute from string to datetime.date datatype df['date'] = pd.to_d...
car_brands = ["Audi", "Bugatti", "Mercedes-Benz", "BMW", "VW"] for name in car_brands: print(name)
from dataclasses import dataclass @dataclass class Mimic: """ classe responsavel por permutacao de palavras """ palavra: str = None def permutacoes(self, palavra:str) -> list: """ retorna todas as permutacoes possiveis """ ls_permutacao = list() if len(palavra) <= 1...
""" Augmenters that apply temporal transformations. To use the augmenters, clone the complete repo and use `from vidaug import augmenters as va` and then e.g. : seq = va.Sequential([ va.RandomRotate(30), va.RandomResize(0.2) ]) List of augmenters: * TemporalBeginCrop * TemporalC...
from functools import partial from multiprocessing import Process from tqdm import tqdm import multiprocessing import numpy as np def predict(matrix_U, matrix_V, topK, matrix_Train, bias=None, measure="Cosine", gpu=False): # Disable gpu option since CC doesn't like Cupy gpu = False if gpu: impor...
from __future__ import print_function import time import redis import logging import traceback from django.conf import settings from .models import CountBeansTask from django_task.job import Job from rq import get_current_job class CountBeansJob(Job): @staticmethod def execute(job, task): params = ta...
from abc import ABC, abstractmethod import re from typing import List from nltk.tokenize import word_tokenize from nltk.stem import PorterStemmer from nltk.corpus import stopwords from nltk import ngrams import nltk TOKEN_RE = re.compile(r'\w+') class Tokenizer(ABC): @abstractmethod def tokenize(self, text:...
from itertools import groupby import json import s3 with open("metadata/charts.json") as f: CHART_METADATA = json.loads(f.read()) def get_previous_total_ballots(path): previous_data = s3.read_from(f"{path}/latest.json") if previous_data: as_dict = json.loads(previous_data) previous_tot...
from keygen import key_gen, serialize_sk, print_sk from prng import prng_sample_then_update, prng_rerandomize from param import d, default_param import sys import filecmp import copy from curve_ops import point_mul, point_add from util import print_g1_hex, print_g2_hex from hash_to_field import I2OSP # see the rust...
from __future__ import absolute_import import base64 import etcd import json import logging import os import six import socket import sys import time import urllib3 from threading import Condition, Lock, Thread from . import ClusterConfig, Cluster, Failover, Leader, Member, SyncState, TimelineHistory from .etcd impor...
from asyncio import Task from typing import Any class Resolvers: resolver_map = {} def __init__(self) -> None: pass def set(self, k, v: Task[Any]): self.resolver_map[k] = v def has(self, k): return k in self.resolver_map async def get_key_result(self, k): return...
import datetime import json import logging from json import JSONDecodeError from django.utils.timesince import timesince from accounts.models import User from common.utils.etc import datetime2timestamp from django.contrib.auth.decorators import login_required from django.http import JsonResponse from django.views.dec...
#coding = utf-8 import os output = os.popen('ls /tmp') print(output.read()) # encoding:utf-8 import time, os import sys #sys.path import subprocess # 运行命令 def run_cmd(cmd): res = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,) return res def push_video...
import random from agent import Agent from variables import * from random import randint class ProbPredator(Agent): def __init__(self, sim, start_loc = None): random.seed() super().__init__(sim, start_loc) self.nearby_fish = [] self.nearby_predator = [] self.cooldown = 0 ...
from .attribute_dict import * from .dict_merger import *
from ryven.NENV import * #this is important to ensure the path is set to the currect directory so it can find the other nodes import sys import os sys.path.append(os.path.dirname(__file__)) from special_nodes import nodes as special_nodes from MacroNode import MacroNode class NodeBase(Node): def __init__(self, par...
#!/usr/bin/env python # coding: utf-8 """ A script to calculate funnels from various kronos streams that all share the same user-identifying field. example usage: python scripts/funnelator.py --kronos-url http://kronos-url.com:port --user-field userId --start 2013-09-25T10:49:41.5-03:00 --end 2014-09-25T10:49:41.5-0...
def pytest_addoption(parser): parser.addoption("--autoreboot", action="store_true", default=None) parser.addoption("--reboot-time", action="store", default=None) parser.addoption("--origins", action="append", default=None) parser.addoption("--additional-origins", action="append", default=None)
""" YAML Error handling. """ from contextlib import contextmanager from typing import Optional, Iterator from yaml import Mark, Node class YamlError(Exception): def __init__( self, message: Optional[str] = None, mark: Optional[Mark] = None, cause: Optional[Exception] = None, ...
import requests from bs4 import BeautifulSoup # 網址後方加上 MARKET:STOCK_ID 即為個股資訊. e.g, TPE:2330 G_FINANCE_URL = 'https://www.google.com/finance?q=' G_FINANCE_HIS_URL = 'https://www.google.com/finance/historical?q=' def get_web_page(url, stock_id): resp = requests.get(url + stock_id) if resp.status_code != 200:...