content
stringlengths
5
1.05M
import keras from keras import Model import numpy as np import keras.backend as K from keras.models import load_model import pickle as pickle from keras.layers import Dense, Activation, Dropout, Layer TerminationLength = 10 THRESHOLD = 0 VECSIZE = [0] FEANUM = 134 BIT = 2 class RuleStructure(): def __init__(se...
import pytest from django.conf import settings from model_mommy import mommy from rest_framework import status from usaspending_api.common.helpers.fiscal_year_helpers import ( current_fiscal_year, calculate_last_completed_fiscal_quarter, get_final_period_of_quarter, ) url = "/api/v2/reporting/agencies/ov...
# # 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 ...
from typing import List from bitcoin_coin_selection.selection_algorithms.branch_and_bound import select_coins_branch_and_bound from bitcoin_coin_selection.selection_algorithms.knapsack_solver import select_coins_knapsack_solver from bitcoin_coin_selection.selection_algorithms.single_random_draw import select_coins_sin...
# "Tiled" TMX loader/renderer and more # Copyright 2012 Richard Jones <richard@mechanicalcat.net> # This code is placed in the Public Domain. # TODO: support properties on more things import os import sys import struct from xml.etree import ElementTree from rect import Rect import kivy kivy.require('1.8.0') from k...
# -*- coding: utf-8 -*- import pymssql import time # 连接数据库 conn = pymssql.connect(server='LAPTOP-EEVLKGR0\SQL', user='MicrosoftAccount\linking1997@live.com', password='91088300.l', database='test') # 打开游标 cursor = conn.cursor() if not cursor: ra...
# -*- coding: utf-8 -*- from web3 import Web3, HTTPProvider from web3.contract import ConciseContract import json class Web3Wrapper(object): DEFAULT_CONF = { 'chainId': 3, 'url': 'https://ropsten.infura.io/4gmRz0RyQUqgK0Q1jdu5', #'privatekey_path': 'keystore/UTC--2018-01-14T18-46-20.32187...
# -*- coding: utf-8 -*- # -*- author: JeremySun -*- # -*- dating: 21/4/9 -*- """贪心解活动选择问题""" def activity_select(a): a.sort(key=lambda x: x[1]) # 需要保证传入的活动集a是排序好的 res = [a[0]] for i in range(1, len(a)): # 如果当前活动的开始时间小于等于最后一个入选活动的结束时间则不冲突 if a[i][0] >= res[-1][1]: ...
from simplefit.cleaner import cleaner import pandas as pd import numpy as np import pytest from pytest import raises def df(lower_case=True): dataf = pd.DataFrame({'num_legs': [2, 4, 8, 0], 'num_ wings ': ['bad', 'Good', None, 'bad'], 'Num specimen seen ': [10, 2, 1, 8]}, ...
"""View specific certificate.""" from censys.search import CensysCertificates c = CensysCertificates() res = c.view("82689890be745aef821ee4a988a0b81331f714d7301b288976fab36219b1f493") print(res)
from __future__ import absolute_import from celery import Celery celery = Celery('managr.celery', broker='amqp://', backend='amqp://') # Optional configuration, see the application user guide. celery.conf.update( CELERY_TASK_RESULT_EXPIRES=3600, ) @celery.task def add(x, y): ...
''' Author: hiocde Email: hiocde@gmail.com Start: 3.3.17 Completion: 3.5.17 Original: Unfortunately, the former input.py is aborted by me , Yesterday I found it's not working and not a auto-pipeline in fact. However I have a new idea to build the pipeline now and I believe I'll succeed, And the interface for upper la...
from __future__ import absolute_import, division, print_function, with_statement, unicode_literals import oz import oz.testing import oz.blinks @oz.test class BlinkMiddlewareTestCase(oz.testing.OzTestCase): def get_handlers(self): class BlinkHandler(oz.testing.FakeCookiesHandler, oz.blinks.BlinkMiddleware...
__all__ = ['ner', 'spacy_ner'] from ner.spacy_ner import SpacyNamedEntityRecognizer
_base_ = "./FlowNet512_1.5AugCosyAAEGray_AggressiveV2_Flat_Pbr_01_ape_lmo_test.py" OUTPUT_DIR = "output/deepim/lmPbrSO/FlowNet512_1.5AugCosyAAEGray_AggressiveV2_Flat_lmPbr_SO/holepuncher" DATASETS = dict(TRAIN=("lm_pbr_holepuncher_train",), TEST=("lmo_test",))
import logging import azure.functions as func from azure.cli.core import get_default_cli def login(): az_cli = get_default_cli() az_cli.invoke(['login', '--service-principal', '-u', '', '-p', '', '--tenant', '']) return az_cli def start_vm(): az_cli = login() az_cli.invoke(['vm', 'start', '-g', '...
'''ResNet in PyTorch. For Pre-activation ResNet, see 'preact_resnet.py'. Reference: [1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun Deep Residual Learning for Image Recognition. arXiv:1512.03385 ''' import torch import torch.nn as nn import torch.nn.functional as F from .seed_conv import SeedConv2d from ma...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import hashlib def hash_sha384(s): sha384 = hashlib.sha384() sha384.update(s.encode('utf-8')) return sha384.hexdigest() def hash_sha384_encode(s): sha384 = hashlib.sha384() sha384.update(s.encode('utf-8')) return sha384.hexdigest() def hash_sh...
# -*- coding: utf-8 -*- from .constants import pi def convert_temperature(val, old_scale="fahrenheit", new_scale="celsius"): """ Convert from a temperatuure scale to another one among Celsius, Kelvin and Fahrenheit. Parameters ---------- val: float or int Value of the temperature to b...
from celery import Celery from celery.schedules import crontab from celery.utils.log import get_task_logger logger = get_task_logger(__name__) # Array of all URLs for partner api endpoints urls = ["https://f21c7154-fa77-4f81-89f1-2f254714f45c.mock.pstmn.io/api"] app = Celery("tasks") app.conf.broker_url = "redis:/...
"""Functions to convert tabular data to popular python graph structures """ import os def to_igraph(vdf, edf, pmax, comms=None, peak=None, save_dir=None, ext='gml'): """Convert Data from (Geo)DataFrames to python-igraph's Graph class Each commodity gets its own graph. Weights are derived from built capaci...
import re from etlt.condition.FalseCondition import FalseCondition from etlt.condition.GlobCondition import GlobCondition from etlt.condition.PlainCondition import PlainCondition from etlt.condition.RegularExpressionCondition import RegularExpressionCondition from etlt.condition.TrueCondition import TrueCondition cl...
import logging from abc import ABC, abstractmethod, ABCMeta import decimal from typing import List import math ctx = decimal.Context() ctx.prec = 17 logger = logging.getLogger('iir') def float_to_str(f): """ Convert the given float to a string without scientific notation or in the correct hex format. ...
import seaborn as sns import matplotlib.pyplot as plt plt.rc("font", size=14) sns.set(style="white") sns.set(style="whitegrid", color_codes=True) def plot_data(data): # barplot for the depencent variable sns.countplot(x='y', data=data, palette='hls') plt.show() # check the missing values print(d...
# Copyright 2018 Google LLC. # Copyright 2017-2020 Palantir Technologies, Inc. # Copyright 2021- Python Language Server Contributors. """Linter plugin for pylint.""" import collections import logging import sys import re from subprocess import Popen, PIPE from pylint.epylint import py_run from pylsp import hookimpl, ...
import utils from fillings import Company from analysis import Analysis if __name__ == '__main__': specs = utils.read_specs("./firms.xlsx") for spec in specs: cik = spec[0] target_name = spec[1] golden_doc = spec[2] acq_name = spec[5] try: company = Company(ci...
try: import pbkdf2,pymysql,secrets,pyaes,PIL,pyperclip from tkinter import * import os.path import Signup_system import pymysql from tkinter import messagebox from PIL import ImageTk, Image except : import install_dependencies from tkinter import * import os.path ...
#!/usr/bin/env python # coding: utf-8 '''Run often used Machine Learning Algorithms. Classes: analysis() Functions: linear_regression decision_tree() decision_tree_balanced(int) ''' # used to store and manipulate data import pandas as pd import numpy as np # used to plot data import seaborn as sn...
import asyncio import logging import random from asyncio.locks import Lock from datetime import timedelta, datetime from typing import Union, Optional import discord from discord.ext.commands import is_owner, Greedy from discord.ext.commands.cooldowns import CooldownMapping, BucketType from numpy.random import choice ...
# 各スイッチにSSH接続し、取得した出力からホスト名のリストを生成する。 # vtp statusも取得する。 import datetime as dt import json import pandas as pd import netmiko from netmiko.ssh_autodetect import SSHDetect from netmiko.ssh_dispatcher import ConnectHandler input_folder = '../input/' output_folder = '../output/' nodes_path = input_folder + '.nodes.csv' ...
import os import uuid import json import shutil from dvc.system import System from dvc.remote.base import RemoteBase from dvc.state import State from dvc.logger import Logger from dvc.utils import remove, move from dvc.config import Config class RemoteLOCAL(RemoteBase): scheme = '' REGEX = r'^(?P<path>(/+|.:...
from __future__ import absolute_import from __future__ import unicode_literals from django.test import SimpleTestCase from corehq.apps.case_importer.do_import import _check_owner from corehq.apps.case_importer.exceptions import InvalidOwnerId from corehq.apps.users.models import CommCareUser, DomainMembership, WebUser ...
from flask import Flask,request,jsonify import pickle from flask_restful import reqparse from nltk.stem import WordNetLemmatizer import nltk from nltk.corpus import wordnet import string from nltk import pos_tag app = Flask(__name__) @app.route('/') def hello(): return 'Up and running' @app.route('/p...
import re # regular expression library from random import random, choice # for random strategy from operator import itemgetter import numpy as np from scipy.sparse import csgraph from scipy.spatial import distance import pickle # import matplotlib.pyplot as plt def vectorize(M): temp = [] for i in range(M....
import os from django import template from django.utils.http import urlencode from django.utils.safestring import mark_safe from taggit.utils import edit_string_for_tags register = template.Library() @register.simple_tag def filter_on_tag(querydict, tag): d = querydict.copy() d.setlist('tag', [tag]) return d.urle...
# -*- coding: utf-8 -*- import unittest from unittest.mock import Mock, patch from certleak.actions.webhookaction import WebhookAction class TestWebhookAction(unittest.TestCase): def setUp(self): self.url = "https://example.com" self.action = WebhookAction(url=self.url) def test_init(self):...
#!/usr/bin/env python # -*- coding: utf-8 -*- import tweepy, sys from keys import * from random import choice from mastodon import Mastodon mastodon = Mastodon( api_base_url='https://mastodon.social', client_id = '/Users/vgan/twoot/twoot_clientcred.txt', access_token = '/Users/vgan/twoot/twoot_...
__source__ = 'https://leetcode.com/problems/student-attendance-record-i/' # Time: O() # Space: O() # # Description: 551. Student Attendance Record I # # You are given a string representing an attendance record for a student. # The record only contains the following three characters: # # 'A' : Absent. # 'L' : Late. # '...
from sse_starlette.sse import ServerSentEvent __version__ = "0.5.2" __all__ = ["ServerSentEvent"]
"""Module to calculate everything for a fiber. TBD: - overlap intergrals don't deal with complex arrays right now """ from scipy.integrate import simps import numpy as np class V_parameter(object): """Houses all the functions that calculate the V parameter for a circular step index fiber.""" def V_fr...
"""[ runs the program ]""" # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope t...
"""messages.slack tests.""" import pytest import requests import messages.slack from messages.slack import SlackWebhook from messages.slack import SlackPost from messages._eventloop import MESSAGELOOP ############################################################################## # FIXTURES #########################...
from random import shuffle, randint import pytest from ioflo.aid import getConsole from plenum.common.keygen_utils import initNodeKeysForBothStacks, tellKeysToOthers from plenum.common.util import randomString from stp_core.loop.eventually import eventually from stp_core.common.log import getlogger from plenum.common...
import re import sys import tempfile from math import ceil from typing import List, Tuple import yaml import logging from git import Repo, Commit from cargo import cargo_build, check_for_ice, cargo_clean logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", handlers=[...
def parse_CLPI_file(br, ip): # Import standard modules ... import os # Import sub-functions ... from .CLPI.load_header import load_header from .CLPI.load_ClipInfo import load_ClipInfo from .CLPI.load_ClipMark import load_ClipMark from .CLPI.load_CPI import load_CPI from .CLPI.load_Exten...
def part_1(data): instructions = data.split(',') progs = list('abcdefghijklmnop') for ins in instructions: if ins[0] == 's': amount = int(ins[1:]) progs = progs[-amount:] + progs[:-amount] if ins[0] == 'x': pos1, pos2 = map(int, ins[1:].split('/')) ...
# type: ignore from .network import NetworkEndpoint from .player import PlayerEndpoint from .guild import GuildEndpoint from .territory import TerritoryEndpoint from .search import SearchEndpoint from .ingredient import IngredientEndpoint from .leaderboard import LeaderboardEndpoint from .recipe import RecipeEndpoint ...
import logging from celery import shared_task from django.conf import settings from requests.exceptions import RequestException from grandchallenge.publications.models import Publication logger = logging.getLogger(__name__) @shared_task(**settings.CELERY_TASK_DECORATOR_KWARGS["acks-late-2xlarge"]) def update_publi...
#!/usr/bin/python3 from elasticsearch import Elasticsearch import os, logging, requests, uuid, time class ElastiClient(object): """ Clase para gestionar la base de datos """ def __init__(self, host = 'localhost', port = 9200, usr_table = 'users', num_table = 'numbers'): """ Con...
from leveler.abc import CompositeMetaClass from .backgrounds import Backgrounds from .badge import Badge from .debugging import Debugging from .economy import Economy from .roles import Roles from .settings import Settings from .users import Users class LevelAdmin( Backgrounds, Economy, Roles, Settings, Users, B...
'''This script demonstrates how to build a deep residual network using the Keras functional API. get_resnet50() returns the deep residual network model (50 layers) Please visit Kaiming He's GitHub homepage: https://github.com/KaimingHe for more information. The related paper is 'Deep Residual Learning for Image Reco...
from typing import List from typing_extensions import Annotated from alpyro_msgs import RosMessage, duration from alpyro_msgs.geometry_msgs.transform import Transform from alpyro_msgs.geometry_msgs.twist import Twist class MultiDOFJointTrajectoryPoint(RosMessage): __msg_typ__ = "trajectory_msgs/MultiDOFJointTraject...
# Copyright 2017 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file acc...
import curses import collections class game: """[game initialization module for drawing canvas / basic game logistic information] """ def __init__(self, nlines, ncols, begin_y, begin_x): self.nlines = nlines self.ncols = ncols self.begin_y = begin_y self.begin_x = begin_x ...
import sublime import subprocess from os import path INTERVAL = 5 # interval in seconds to do new cycle check PACKAGE = path.splitext(path.basename(__file__))[0] def logToConsole(str): print(PACKAGE + ': {0}'.format(str)) class Settings(): def __init__(self, onChange=None): self.loaded = False ...
from unittest.mock import Mock, patch import pytest from globus_sdk import AccessTokenAuthorizer, AuthAPIError from globus_sdk.response import GlobusHTTPResponse from globus_action_provider_tools.authentication import ( AuthState, TokenChecker, identity_principal, ) from globus_action_provider_tools.error...
from tr_option.base import KWTR from copy import deepcopy # [ OPT10071 : 시간대별전일비거래비중요청 ] class Opt10071(KWTR): def __init__(self, core): super().__init__(core) self.rq_name = self.tr_code = 'opt10071' self.record_name_multiple = '시간대별전일비거래비중' self.header_multiple = [ ...
#!/usr/bin/env python # # convert assets to binary formats that # can be understood by firmware # import sys, datetime, os, ConfigParser import itertools from cStringIO import StringIO from PIL import Image, ImageFont, ImageDraw DISPLAY_WIDTH = 320 DISPLAY_HEIGHT = 240 class Palette: ''' our look up table of 1...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # vim:ts=4:sw=4:expandtab 2 # Copyright 2016, 2017 juga (juga at riseup dot net), MIT license. """DCHP client implementation of the anonymity profile (RFC7844).""" import argparse import logging import logging.config from lockfile.pidlockfile import (PIDLockFile, Already...
from typing import List class Solution: def findOcurrences(self, text: str, first: str, second: str) -> List[str]: res = [] # 特判 text_arr = text.split() size = len(text_arr) if size < 3: return res flag = 0 for i in range(size): if f...
import logging import subprocess as sub # needed for softreload to pull from git kekw import sys from importlib import reload from re import split # for cmd handling from time import sleep import discord from discord.errors import Forbidden # api library import botlogger import commandhandler # module for command...
def main(j, args, params, tags, tasklet): page = args.page logpath = args.requestContext.params.get('logpath') templatepath = args.requestContext.params.get('templatepath') installedpath = args.requestContext.params.get('installedpath') metapath = args.requestContext.params.get('metapath') dom...
import django_filters from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework import viewsets from users.models import User from users.serializers import UserSerializer class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be view...
import torch.nn as nn __all__ = ['SE'] class SE(nn.Module): def __init__(self, channel, reduction=8): super().__init__() self.fc = nn.Sequential( nn.Linear(channel, channel // reduction, bias=False), nn.ReLU(inplace=True), nn.Linear(channel // reduction, channe...
# coding: utf-8 import pprint import re import six class OrderLineItemV3: """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is...
print() ################################################################################################### # Demonstração de que cada instância está ciente da classe de onde veio. class MinhaClasse(object): pass # Criando instâncias da classe 'MyClass' this_obj = MinhaClasse() that_obj = MinhaClasse() # Ins...
# 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
import os, shutil, re import markdown2 from _common import * import _template_renderer as tr import _controllers as con from datetime import datetime as dtdt settings = None class SiteGenerator(object): def __init__(self, output = None): global settings settings = get_settings() if output: ...
# Copyright (c) 2012 Bronto Software Inc. # Licensed under the MIT License """ Convert Java syntax tree nodes to string representations. """ import javalang from util import StringBuilder # The order for displaying modifiers __modifiers_order = ('public', 'protected', 'private', 'static', 'abstract', 'final', ...
# This file is part of Bug-reproducer Assistant # The tool has been designed and developed by Gervasio Andres Calderon Fernandez, of Core Security Technologies # # Copyright (c) 2011, Core Security Technologies # All rights reserved. # # Redistribution and use in source and binary forms, with or without modifica...
import datetime import functools import json import warnings from decimal import Decimal from enum import Enum, IntEnum from typing import TYPE_CHECKING, Any, Callable, Optional, Type, TypeVar, Union from uuid import UUID, uuid4 from pypika import functions from pypika.enums import SqlTypes from pypika.terms import Te...
# #!/usr/bin/env python # #-*- coding:utf-8 -*- # # #VersionNo: 1.0 # #Author: fhh # #DateTime: 2020/5/19 14:47 # #Describe: MQ发送信息 # #Function: # #Journal: # # import pika # import json # import logging # # # RABBIT_MQ_USER_NAME = 'admin' # RABBIT_MQ_PASSWORD = '123456' # RABBIT_MQ_IP = '192.168.10.2...
# Copyright (c) 2014, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. from __future__ import absolute...
class ProcessError(Exception): """ The base class for the exception occurred in the process """ def __init__(self, process_name, message): """ Constructor @param process_name The name of the process in which the error occurred @param message The error message ""...
# Copyright (c) 2012-2018 SoftBank Robotics. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the COPYING file. def test_simple(qipy_action, record_messages): qipy_action.add_test_project("a_lib") qipy_action.add_test_project("big_project") qipy_acti...
from __future__ import print_function from ipywidgets import interact, interactive, fixed, interact_manual import ipywidgets as widgets from gc import set_threshold import sys, traceback import cv2 as cv import os import re import numpy as np import argparse import string from plantcv import plantcv as pcv import glob...
from CAS.Tokenizer import *; from CAS.Errors import UserError, EvaluationError; from CAS.data import PRECEDENCES; from CAS.Manipulator import Manipulator; import math; PARENTHESIS_WEIGHT = max(PRECEDENCES.values()) + 1; class ParseTree(): """ A parse tree of a mathematical expression """ def __init__(self...
import lunzi.nn as nn import lunzi as lz import tensorflow as tf class MinQFunction(nn.Module, lz.rl.BaseQFunction): def __init__(self, dim_state, dim_action, qfns): super().__init__() self.qfns = nn.ModuleList(qfns) self.dim_state = dim_state self.dim_action = dim_action def ...
""" Copyright 2020 Google LLC 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 https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software di...
""" DRS De-Registration Imeis Model package. Copyright (c) 2018 Qualcomm Technologies, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met: * Redis...
"""Heap Load Balancer. Based on the heap balancer from finagle, see (https://github.com/twitter/finagle/blob/master/finagle-core/src/main/scala/com/twitter/finagle/loadbalancer/HeapBalancer.scala) The heap load balancer maintains all nodes in a min-heap. The heap is adjusted as the load on a node increases or decrea...
from django.core.serializers.json import DjangoJSONEncoder from django.db import models try: import json # json module added in Python 2.6. except ImportError: from django.utils import simplejson as json # https://bitbucket.org/offline/django-annoying class JSONField(models.TextField): """ JSONField...
''' 399 REGN 5.016115 459 UNH 5.150879 107 CI 5.276706 78 BMY 5.651378 7 AMD 5.781002 419 SWKS 5.869410 48 AAPL 6.083879 20 AGN 6.312075 242 HUM 6.329243 39 AMGN 6.460227 ''' import pandas as pd from pandas_datar...
import time from basetestcase import BaseTestCase from membase.api.rest_client import RestConnection from bucket_utils.Bucket import Bucket from remote.remote_util import RemoteMachineShellConnection class DeleteBucketTests(BaseTestCase): def setUp(self): super(DeleteBucketTests, self).setUp() se...
def get_rules(endpoint_name=None): """ :param endpoint_name: if specified, only return the available rules to that endpoint :return: A list of the current rules in the attached Flask app """ from lemonadefashion_flask_monitoringdashboard import config try: rules = config.app.url_map.ite...
import unittest import numpy as np import numpy.testing as npt from . import dense_permutations as dp class TestDensePermutations(unittest.TestCase): tol = 0.00001 def test_get_sort_permutation(self): vector = [0.3, 0.2, 0.4, 0.1] npt.assert_allclose([2, 0, 1, 3], dp.get_sort_permutation(ve...
from unittest import TestCase from gitbarry import constants class ConstantsTests(TestCase): def test_constants_exists(self): self.assertIsNotNone(constants.START_ACTION) self.assertIsNotNone(constants.STOP_ACTION) self.assertIsNotNone(constants.FINISH_ACTIONS) def test_finish_actions...
# -*- coding: utf-8 -*- import torch import torch.nn as nn from torch.optim import Adam import torch.nn.functional as functional from torch.utils.data import DataLoader import numpy as np from tqdm import tqdm import matplotlib.pyplot as plt from config import Config from dataset import Vocabulary, DualNovelD...
#!/usr/bin/env python import sys from twisted.protocols import amp from twisted.internet import reactor from twisted.internet.protocol import ServerFactory from twisted.python import usage from twisted.cred.checkers import FilePasswordDB from twisted.cred.portal import Portal from twisted.cred import credentials fro...
""" Copyright [2009-2017] EMBL-European Bioinformatics Institute 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 a...
# AIRDNA EndPoints import os from dotenv import load_dotenv import requests import numpy import json import pandas as pd import sys import psycopg2 import os from dotenv import load_dotenv import os # Load API Key load_dotenv() AIRDNA_TOKEN = os.getenv("AIRDNA_TOKEN") # Same for All API Calls HEADERS = {"access_token...
import unittest from baseline.utils import dictionary as D class DictionaryTestCase(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_initialize(self): unk_symbol = "$$UNK$$" dictionary = D.BasicDictionary(unk_symbol=unk_symbol) self.ass...
import numpy as np from xarray import Dataset def test_from_cat(): import os import intake cat_path = os.path.join( os.path.dirname(__file__), "../intake_informaticslab/cats/ukv_timeseries_cat.yaml", ) cat = intake.open_catalog(cat_path) ds = cat.ukv_daily_timeseries.read_chu...
from tkinter import * import math root = Tk() root.title("JayCalc 3.0") plus = False minus = False times = False divide = False sqrt = False expo = False print("Copyright (c) 2021 Jacob Schmidt") print("Calculation History:") def button_click(num): current = e.get() e.delete(0, END) e.insert(0, str(curr...
import uuid import json import logging import time from be.model import db_conn from be.model import error from be.model.error import error_code from be.table.new_order import New_Order from be.table.new_order_detail import New_Order_Detail from be.table.user import User from be.table.store import Store from be.table.u...
"""IO methods for segmotion output. --- DEFINITIONS --- segmotion (or w2segmotionll) = storm-tracking algorithm in WDSS-II. WDSS-II = Warning Decision Support System -- Integrated Information, a software package for the visualization and analysis of thunderstorm-related data. """ import os import glob import gzip i...
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-10 08:15 from __future__ import unicode_literals from django.db import migrations from django.conf import settings class Migration(migrations.Migration): forward = [ """ CREATE SCHEMA IF NOT EXISTS campusonline; """, ...
from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class FetchRun(models.Model): STARTED = 0 FINISHED = 1 ERRORED = 2 STATUS_CHOICES = ( (STARTED, 'Started'), (FINISHED, 'Finished'), (ERRORED, 'Errored'), ) ...
import nltk grammar = nltk.grammar.DependencyGrammar.fromstring(""" 'savings' -> 'small' 'yield' -> 'savings' 'gains' -> 'large' 'yield' -> 'gains' """) sentence = 'small savings yield large gains' dp = nltk.parse.ProjectiveDependencyParser(grammar) for t in sorted(dp.parse(sentence.split())): print(t) t.draw...
#!/usr/bin/env python import rospy from threading import Thread, Event from tug_observers_msgs.msg import observer_info class PluginBase(): """ Base class for plugins. It lists all required defines. """ def __init__(self, plugin_type): """ Constructor for base plugin. :param p...