content
stringlengths
5
1.05M
# -*- coding: utf-8 -*- """ @author: Youye """ import torch import torch.nn as nn import torch.nn.functional as F #%% Define the ResNet block class ResNetBlock(nn.Module): def __init__(self,inter_channel = 128): super(ResNetBlock, self).__init__() ...
"""JS/CSS bundles for theme.""" from flask_assets import Bundle from invenio_assets import NpmBundle css = NpmBundle( Bundle( 'scss/styles.scss', filters='node-scss, cleancss', output="gen/cd2hrepo.local.styles.%(version)s.css", depends=('scss/*.scss', ), ), Bundle( ...
import base64 import json configs = [{ "v": "2", "ps": "ibm", "add": "v2ray_ip", "port": "30080", "id": "18ad2c9c-a88b-48e8-aa64-5dee0045c282", "aid": "0", "net": "kcp", "type": "wechat-video", "host": "", "path": "", "tls": "" }, { "v": "2", "ps":...
from flask import Flask, request import db_utils import email_utils import git_utils app = Flask(__name__) @app.route('/publish', methods=["GET", "POST"]) def publish_to_cloud(): key = request.json['key'] msg = email_utils.fetch_raw_email_from_aws(key) filepath = '_posts/' + email_utils.fetch_filename(m...
#!/usr/bin/env python3 import re ''' Example rules: * light red bags contain 1 bright white bag, 2 muted yellow bags. * dark orange bags contain 3 bright white bags, 4 muted yellow bags. * bright white bags contain 1 shiny gold bag. * muted yellow bags contain 2 shiny gold bags, 9 faded blue bags. * shiny gold bags c...
from abc import abstractmethod import logging import functools logger = logging.getLogger(__name__) # GLOBALS METHODS_MAP_CODE = {} METHODS_MAP_DATA = {} class SerializerBase(object): """ Adds shared functionality for all serializer implementations """ def __init_subclass__(cls, *args, **kwargs): ...
#!/usr/bin/env python3 import random from math import sqrt import numpy as np #--------------------------------------------------------------- # Data to be generated # (1) number of phrases # (2) number of total words # (3) words per phrase (2/1) # (4) number of non-function words # (5) non-functio...
from django.conf.urls import url from .. import views urlpatterns = [ url( regex=r'^users/?$', view=views.UserList.as_view(), name='user_list' ), url( regex=r'^users/(?P<pk>\d+)/?$', view=views.UserDetail.as_view(), name='user_detail' ), ]
import os from flask import Flask import urllib.parse from combien import Combien app = Flask(__name__) @app.route("/") def hello(): return "Hello World" @app.route("/price/<path:url>") def price(url): c = Combien(urllib.parse.unquote(url)) return c.price() if __name__ == "__main__": app.run(debug=True)
from selenium import webdriver import pickle import json import os from process import process def do_login(browser, url): browser.get(url) cookies = browser.get_cookies() with open('cookies.pickle', 'wb') as f: pickle.dump(cookies, f) input('Login in the browser, then press Enter to continue h...
import logging import urllib logger = logging.getLogger("municipal_finance") class ApiClient(object): def __init__(self, get, api_url): self.get = get self.api_url = api_url + "/cubes/" def api_get(self, query): if query["query_type"] == "aggregate": url = self.api_url ...
#!usr/bin/env python """ Postprocessor subclass. """ from collections import namedtuple import general_utils import rapid_config from postproc import postproc from postproc import postproc_options from robotmath import transforms # PARAMS __a1 = 'A1' __a2 = 'A2' __a3 = 'A3' __a4 = 'A4' __a5 = 'A5' __a6 = 'A6' __e1 ...
__author__ = 'Tristan Watson' # Keystroke Dynamic software that covers the following key functionality: # 1. User File management # 2. Input gathering and management (including storage) # 3. Plotting of keystrokes taking into consideration both up events and down events. import pyHook import pythoncom import...
import cv2 from face_recognizer import FaceRecognizer LIBRARY_FOLDER_PATH = "#PATH TO THE LIBRARY FOLDER#" IMAGE_PATH = "#PATH TO THE IMAGE THAT NEEDS TO BE ANALYZED#" faces_names, image = FaceRecognizer(LIBRARY_FOLDER_PATH).classify(IMAGE_PATH) cv2.imshow('image', image) cv2.waitKey(0)
import time import vk def get_members(api: vk.API, group_id: int, fields: str = "", delay: float = 0.4): spy_requests = api.groups.getMembers(group_id=group_id, fields=fields) count = spy_requests["count"] members = set(spy_requests["items"]) if count > 1000: for i in range(1, (count // 1000) + 1): time.sle...
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% from IPython import get_ipython # %% import matplotlib.pyplot as plt import pandas as pd import seaborn as sns get_ipython().run_line_magic('matplotlib', 'inline') import numpy as np train = pd.read_csv('Train1.csv') train.head(...
# Copyright (c) Facebook, Inc. and its affiliates. # The following script requires Java 1.8.0 and pycocotools installed. # The pycocoevalcap can be installed with pip as # pip install git+https://github.com/flauted/coco-caption.git@python23 # Original pycocoevalcap code is at https://github.com/tylin/coco-caption # bu...
"""Define fixtures available for all tests.""" from unittest.mock import Mock, patch from pytest import fixture MOCK_AREAS_0 = [ {"bank": 0, "name": "Area 1", "sequence": 30, "status": "Ready"}, ] MOCK_AREAS_1 = [ {"bank": 0, "name": "Area 1", "sequence": 31, "status": "Not Ready"}, # A dummy invalid ban...
#!/usr/bin/env python """Inspecting the call stack. """ #end_pymotw_header import inspect def show_stack(): for level in inspect.stack(): frame, filename, line_num, func, src_code, src_index = level print '%s[%d]\n -> %s' % (filename, line_num, ...
from django.conf.urls import url from .views import (index, upload_resume, upload_profilepic, profile, edit_personalinfo, edit_profile_description, edit_professionalinfo, add_language, edit_language, delete_language, add_experience, edit_experience, delete_experience, add_educati...
from pydantic import BaseModel import toml class TomlModel(BaseModel): @classmethod def load(cls, file): with open(file, "r") as f: return cls.parse_obj(toml.load(f)) def dump(self, file): with open(file, "w") as f: toml.dump(self.dict(), f) class WebserialConfig...
#This file contains a series of functions to generate the necessary #wires to drive the storage grid. The standards for the wires are laid out #in make_store_cell #takes in the output file manager, the number of entries, the number of bits #and the number of reads #Matthew Trahms #EE 526 #4/20/21 def make_store_grid...
from datetime import datetime from openapi.db import CrudDB async def test_upsert(db: CrudDB) -> None: task = await db.db_upsert(db.tasks, dict(title="Example"), dict(severity=4)) assert task["id"] assert task["severity"] == 4 assert task["done"] is None task2 = await db.db_upsert( db.tas...
#13-1 pandas とmodelのやり取りを行う import pandas as pd import numpy as np #dataframe を numpy 配列に直す data = pd.DataFrame(~) data.values #array(~) df2 = pd.DataFrame(data.values,columns = [~]) data.loc[:,["a","b"]].values #範囲を指定 dummies = pd.get_dummies(data.category,prefix="~") #~列をdummieにする data_with_dummies = data.drop("~",a...
from typing import Optional, Any from StructNoSQL.utils.types import TYPED_TYPES_TO_PRIMITIVES def make_dict_key_var_name(key_name: str) -> str: return f"$key$:{key_name}" def try_to_get_primitive_default_type_of_item(item_type: Any): item_default_primitive_type: Optional[type] = getattr(item_type, '_defaul...
try: from maya import cmds except ImportError: print("Must be in a maya environment!") raise from rig.maya.dag import get_positions def create_line(objects, attach=True, attachParents=[], name=""): """ Creates a line between objects, that optionally attaches to each """ if not name: ...
from __future__ import print_function import numpy as np weights = np.load("pspnet101_voc2012.npy", encoding="latin1").item() settable_weights = 0 for layer, value in weights.items(): print(layer) for attrib, vals in weights[layer].items(): if attrib == "weights": print("weights: "...
from sipTransportConnection import SIPTransportConnection class UDPSIPTransportConnection(SIPTransportConnection): def __init__(self, bind_address_string, remote_address_string, bind_port_integer, remote_port_integer): self.twistedProtocol = None super(UDPSIPTransportConnection, self).__init__(bin...
""" Registrador de eventos. """ from logging import INFO, FileHandler, Formatter, StreamHandler, getLogger from typing import TYPE_CHECKING from ..auxiliar import Singleton from ..constantes import LOG_PATH if TYPE_CHECKING: from logging import Logger class LectorLogger(metaclass=Singleton): """ Clase...
import sys import data_IO import json if len(sys.argv) < 3: print("Number of provided arguments: ", len(sys.argv) - 1) print("Usage: python testKPIreaderJSON.py <desiredMetrics.json> <outputDir> ") sys.exit() kpiFileAddress = sys.argv[1] outputDir = sys.argv[2] # Read the desired outputs/metrics from ...
# -*- coding: utf-8 -*- """ updater enumerations module. """ from pyrin.core.decorators import class_property from pyrin.core.enumerations import CoreEnum class UpdaterCategoryEnum(CoreEnum): """ updater category enum. """ CONTENT_RATE = 'content_rate' COUNTRY = 'country' GENRE = 'genre' ...
from django.shortcuts import render from django.http import HttpResponse def index(request) -> HttpResponse: """FAQs index view """ return render(request, "faqs/index.html") def section(request, section_title: str) -> HttpResponse: """FAQs section view - FAQ lists for participants, organizers, phot...
class Solution(object): def numberToWords(self, num): """ :type num: int :rtype: str """ to19 = 'One Two Three Four Five Six Seven Eight Nine Ten Eleven Twelve ' \ 'Thirteen Fourteen Fifteen Sixteen Seventeen Eighteen Nineteen'.split() tens = 'Twenty Thirt...
import pytest from pygraphblas import * from pygraphblas import lib def test_options_set(): opts = options_get() iz = lambda name, typ: isinstance(opts.get(name), typ) assert iz("nthreads", int) assert iz("chunk", float) assert iz("burble", int) assert iz("format", int) assert iz("hyper...
class Base1(object): def __init__(self): self.str1 = "anum" print "Base1" class Base2(object): def __init__(self): self.str2 = "sharma" print "Base2" class Derived(Base1, Base2): def __init__(self): # Calling constructors of Base1 # and Ba...
import time import Box2D import Box2D.b2 import gym from gym import spaces from gym.utils import colorize, seeding, EzPickle import numpy as np env = gym.make('Box2D:BipedalWalkerHardcore-v3') observations = env.reset() reward = 0 import neural_network_NE_agent_2 neural_network_NE_agent_2.Evolution.simulate_gener...
FULLNODE = "http://node.deviceproof.org:14265" # FULLNODE = "http://node10.puyuma.org:14265" SEED = 'AMRWQP9BUMJALJHBXUCHOD9HFFD9LGTGEAWMJWWXSDVOF9PI9YGJAPBQLQUOMNYEQCZPGCTHGVNNAPGHA'
from sklearn.model_selection import train_test_split from utils.data_util import get_stocks def prepare_data(company_symbol, result_feature, features, forecast_out, test_size, random_state): """ Method will shift data values by given 'forecast_out' amount. Basically, we will be predicting 'n' values in th...
import os from glob import glob import hickle import numpy as np from datasets.phys import Phys from utils.config import _C as C from utils.misc import tprint plot = False class PHYRE(Phys): def __init__(self, data_root, split, template, image_ext='.jpg'): super().__init__(data_root, split, template, im...
"""Helpers for working with Recurly's recurly.js packge""" from django.template.loader import render_to_string from django_recurly.conf import SUBDOMAIN, DEFAULT_CURRENCY from django_recurly.utils import recurly, dump def get_signature(obj): return recurly.js.sign(obj) def get_config(subdomain=SUBDOMAIN, curren...
from .conf import * __version__ = "1.1"
import FWCore.ParameterSet.Config as cms muonIsolations = cms.EDProducer("ValeMapFloatMerger", src = cms.VInputTag(cms.InputTag("goodMuonIsolations"), cms.InputTag("goodTrackIsolations"), cms.InputTag("goodStandAloneMuonTrackIsolations")) )
{%- set klass = cookiecutter.project_slug.capitalize() -%} {%- set obj = cookiecutter.project_slug.lower() -%} {%- set is_open_source = cookiecutter.open_source_license != 'Not open source' -%} # -*- coding: utf-8 -*- # # This file is part of the {{ cookiecutter.project_name }} project # # Copyright (c) {% now 'local',...
from .bloom_filter import BloomFilter, Response __all__ = ["BloomFilter", "Response"]
""" This file solves the second Advent of Code 2020 puzzle. https://adventofcode.com/2020/day/2 """ def parse_line(line: str) -> dict: """ This function inelegantly gets all the parts of the password policy and password and stores them in a dictionary. :param line: The line containing the password pol...
from .order.suggested import SuggestedOrder from .portfolio import Portfolio from .price_parser import PriceParser class PortfolioHandler(object): def __init__( self, initial_cash, events_queue, price_handler, position_sizer, risk_manager ): """ The PortfolioHandler is designed...
from .utils import encode_attr from .control import Control class Item(Control): def __init__(self, text=None, id=None, secondary_text=None, url=None, new_window=None, icon=None, icon_color=None, icon_only=None, split=None, divider=None, onclick=None, items=[], width=None, height=None, pad...
# Do not edit this file directly. # It was auto-generated by: code/programs/reflexivity/reflexive_refresh load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file") def mpmcQueue(): http_archive( name = "mpmc_queue", build...
# Advent of Code - Day 10 def parse(input): return [[char for char in row] for row in input] def corrupt_closer(open_and_shut, row): """Returns boolean indicating corruptness and first corrupt closer""" openers = open_and_shut.keys() closers = open_and_shut.values() openers_stack = [] for ...
import sys from PyQt5 import QtCore, QtWidgets from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget from PyQt5.QtCore import QSize class HelloWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.setMinimumSize(QSize(280, 120)) self.setWindowTitle("Olá, ...
# Copyright 2021 MosaicML. All Rights Reserved. from __future__ import annotations from dataclasses import MISSING, fields from enum import Enum from typing import TYPE_CHECKING, List, NamedTuple, Optional, Type, get_type_hints import yahp as hp from yahp.utils.interactive import query_with_options from yahp.utils.i...
import sqlite3 import os history_limit = 30 home = os.path.join(os.path.expanduser('~'), ".piepresto") os.makedirs(home, exist_ok=True) lite_db = os.path.join(home, "history.db") history_table = """ CREATE TABLE IF NOT EXISTS history( sql TEXT PRIMARY KEY, update_time datetime default current_time...
import abc from nesim.frame import Frame from typing import Dict, List from pathlib import Path from nesim.devices.send_receiver import SendReceiver from nesim.devices.cable import DuplexCableHead from nesim.devices.device import Device class MultiplePortDevice(Device, metaclass=abc.ABCMeta): """Representa un dis...
# Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import webapp2 from frontend.handlers import cracas_dashboard from frontend.handlers import crash_config from frontend.handlers import crash_handler from fr...
from dataclasses import dataclass, field from enum import Enum from typing import Optional from xsdata.models.datatype import XmlDuration __NAMESPACE__ = "NISTSchema-SV-IV-atomic-duration-enumeration-2-NS" class NistschemaSvIvAtomicDurationEnumeration2Type(Enum): P2030_Y06_M26_DT21_H55_M47_S = XmlDuration("P2030...
from rest_framework import serializers from bullet_point.models import BulletPoint, Endorsement, Flag, Vote from user.serializers import UserSerializer from utils.http import get_user_from_request class EndorsementSerializer(serializers.ModelSerializer): bullet_point = serializers.PrimaryKeyRelatedField( ...
# Loads configuration file from ConfigParser import ConfigParser cfg = ConfigParser() cfg.readfp(open('apps.cfg')) # General variables COINSCOPED_API_ADDR = cfg.get('general', 'coinscoped_api_addr') COINSCOPED_API_PORT = int(cfg.get('general', 'coinscoped_api_port')) # Nethealth MAINNET_PORT = 8333 TESTNET_PORT = 18...
# Generated by Django 2.1.5 on 2019-02-11 16:40 from django.db import migrations class Migration(migrations.Migration): dependencies = [("iert_news", "0004_auto_20190211_1631")] operations = [migrations.RenameModel(old_name="news", new_name="new")]
import os import warnings import pytest from ...utils import LightkurveDeprecationWarning, LightkurveError from ... import PACKAGEDIR, KeplerTargetPixelFile, TessTargetPixelFile from .. import read def test_read(): # define paths to k2 and tess data k2_path = os.path.join(PACKAGEDIR, "tests", "data", "test-...
import re from eth_utils import ( is_string, is_list_like, ) from .events import ( construct_event_topic_set, construct_event_data_set, ) from web3.utils.validation import ( validate_address, ) def construct_event_filter_params(event_abi, contract_address=None,...
from app import app def run(): print(""" +===================================+ ¦ Parkwood Vale Harriers Webapp ¦ +===================================+ ¦ Stop the application by either ¦ ¦ closing the console window, or ¦ ¦ pressing CTRL+C. ¦ +================...
default_app_config = "pinaxcon.registrasion.apps.RegistrasionConfig"
from control import * emergency()
#!/usr/bin/env python # # (c) Copyright Rosetta Commons Member Institutions. # (c) This file is part of the Rosetta software suite and is made available under license. # (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. # (c) For more information, see http://www.rosettacommons.or...
import streamlit as st from streamlit_player import st_player import cv2 import numpy as np import tempfile import time from PIL import Image ############################################################ ############################################################ import os import collections # comment out below line t...
from prisma.models import Profile # TODO: more tests async def order() -> None: # case: valid await Profile.prisma().group_by( ['country'], order={ 'country': 'desc', }, ) await Profile.prisma().group_by( ['country', 'city'], order={ 'c...
urls = { "ETL-1": None, "ETL-2": None, "ETL-3": None, "ETL-4": None, "ETL-5": None, "ETL-6": None, "ETL-7": None, "ETL-8B": None, "ETL-8G": None, "ETL-9B": None, "ETL-9G": None }
import random import math import copy import itertools import torch import numpy as np from utils import jsonl_to_json, remove_duplicate, flatten_list, remove_nonascii def make_bert_batch(tokenizer, data, **kwargs): data = jsonl_to_json(data) sentences = data['target'] sentences = [tokenizer.encode(t) f...
# -*- coding: utf-8 -*- # @Time : 2018/11/27 18:42 # @Author : yag8009 # @File : for_notchongfu.py # @Software: PyCharm """ 题目:有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少? 1程序分析: 可填在百位、十位、个位的数字都是1、2、3、4。 组成所有的排列后再去掉不满足条件的排列 """ class notchong: def __init__(self, data): self.data = data def notchon...
""" Taken from the networkx source code and modified to process IOCall classes. See original at https://github.com/networkx/networkx/blob/main/networkx/readwrite/gexf.py """ """Read and write graphs in GEXF format. .. warning:: This parser uses the standard xml library present in Python, which is in...
import argparse from anagram_matcher import AnagramMatcher parser = argparse.ArgumentParser() parser.add_argument('-A', "--anagram", type= str) parser.add_argument('-E', '--encoded_messages', nargs='+') parser.add_argument('-W', '--wordlist', type=str) args = parser.parse_args() anagram = args.anagram encoded_messa...
import sublime, sublime_plugin import webbrowser CHECKOUT = "mozilla-central" # maybe make this configurable? BASE = "https://searchfox.org/" + CHECKOUT PATH_MARKER = "@" REGEXP_MARKER = "rrr" SELECTION = 1 PATH = 2 QUERY = 3 def get_url(text, t): if t == SELECTION: return "{}/search?q={}".format(BASE...
# # SPDX-License-Identifier: Apache-2.0 # # Copyright 2020 Andrey Pleshakov # # 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 requi...
# -*- coding: utf-8 -*- # -------------------------------------------------------------------------- # Copyright Commvault Systems, 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 a...
def in_array(array1, array2): result=[] for word_one in set(array1): for word_two in array2: if word_one in word_two: result.append(word_one) break result.sort() return result
# Tudor Berariu, 2016 import math from random import randint from sys import argv from zipfile import ZipFile import matplotlib.markers import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D from scipy.cluster import hierarchy from scipy.spatial.distance import euclidean def get...
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license """asyncio library query support""" import socket import asyncio import dns._asyncbackend import dns.exception def _get_running_loop(): try: return asyncio.get_running_loop() except AttributeError: # pragma: no cover ...
#class SVNRepo: # @classmethod # def isBadVersion(cls, id) # # Run unit tests to check whether verison `id` is a bad version # # return true if unit tests passed else false. # You can use SVNRepo.isBadVersion(10) to check whether version 10 is a # bad version. class Solution: """ @param n:...
from pytest import mark, raises import quirinius as qu import numpy as np import warnings pctl50 = np.array([.5]) class Test_ValAtQtl: def test_bounds(self): nvals = 11 vals = np.linspace(0., 1., nvals) cumul_qtl = (np.linspace(1., nvals, nvals) - 0.5) / nvals qtl = np.array([0....
import subprocess import sys import pkg_resources try: pkg_resources.get_distribution("httpx") except pkg_resources.DistributionNotFound: hyper_dist = "hyper@https://github.com/Lukasa/hyper/archive/development.tar.gz" subprocess.check_call([sys.executable, "-m", "pip", "install", "--upgrade", hyper_dist, ...
# License: license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.utils import flt, getdate def execute(filters=None): if not filters: filters = {} columns = get_columns(filters) item_map = get_item_details(filters) iwb_map = get_item_warehouse_map(filters) data = [] ...
#! /usr/bin/env python # -*- coding: utf-8 -*- """ Module that contains triangles validation implementation """ from __future__ import print_function, division, absolute_import __author__ = "Tomas Poveda" __license__ = "MIT" __maintainer__ = "Tomas Poveda" __email__ = "tpovedatd@gmail.com" import tpDcc as tp impor...
def show_figure(prob_Q_A_left, prob_E_A_left, prob_AD_A_left, prob_Q2_A_left): import matplotlib.pyplot as plt plt.ylabel('% left actions from A') plt.xlabel('Episodes') x_ticks = np.arange(0, 301, 20) y_ticks = np.arange(0, 1.1, 0.1) plt.xticks(x_ticks) plt.yticks(y_ticks, ['0%', '10%', '20...
# -*- coding: utf-8 -*- """ This module provides an abstract base class for invocation plugins. """ # Future from __future__ import absolute_import, division, print_function, \ unicode_literals, with_statement # Standard Library from abc import ABCMeta, abstractmethod class BasePlugin(object): """ Abst...
import groups from base import OcgFunction, OcgCvArgFunction, OcgArgFunction import numpy as np from ocgis.util.helpers import iter_array class SampleSize(OcgFunction): ''' .. note:: Automatically added by OpenClimateGIS. This should generally not be invoked manually. n: Statistical sample ...
count = 0 for i in range(6): k = float(input()) if k > 0: count += 1 print("{0} valores positivos".format(count))
#from distutils.core import setup import setuptools setuptools.setup(name='target_chembl', version='0.0.7', scripts=['patho_chembl/chembldb_pfam_mech.py', 'patho_chembl/chembldb_pfam_assay.py', 'patho_chembl/mol_trg.py', 'patho_chembl/pfam_df_update.py', 'patho_chembl/pfam_mol_assay.py', 'patho_chembl/pfam_m...
# Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import datetime import unittest import webapp2 import webtest from google.appengine.ext import ndb from dashboard import benchmark_health_report from dash...
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Access the Chandra archive via the arc5gl tool. """ import six import pexpect import os # Should put in a watchdog timer to exit from arc5gl after a period of inactivity import ska_helpers __version__ = ska_helpers.get_version(__name__) class Arc5...
import argparse import cPickle as pickle import numpy as np import os import matplotlib.pyplot as plt import chainer from chainer import optimizers from chainer import serializers import net import trainer import time class CifarDataset(chainer.datasets.TupleDataset): def __init__(self, x, y, augment=None): ...
import pandas as pd import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation plt.style.use('seaborn-notebook') def animation(_): data = pd.read_csv('data.csv') x = data['x'] y1 = data['y1'] y2 = data['y2'] plt.cla() plt.plot(x, y1, label='channel 1', col...
from tensorflow.keras.layers import Conv2D, Conv2DTranspose, UpSampling2D from tensorflow.keras.layers import BatchNormalization, Activation, Input, ZeroPadding2D from tensorflow.keras.layers import Add, Concatenate from tensorflow.keras.models import Model from ...layers import ReflectPadding2D, InstanceNormalization...
import io import solve def test_count_increases_empty_list(): depth_list = [] increases = solve.count_increases(depth_list) assert 0 == increases def test_count_increases_single_increase(): depth_list = [0, 100] increases = solve.count_increases(depth_list) assert 1 == increases def te...
from django.apps import AppConfig class RepairandbuyerConfig(AppConfig): name = 'repairANDbuyer' verbose_name = '蓝快维修与采购'
import os import sys from multiprocessing import Process, Queue from django.conf import settings from django.core.management.base import BaseCommand, CommandError from couchdbkit import ResourceConflict, ResourceNotFound from six.moves.urllib.parse import urlparse from dimagi.utils.couch.database import iter_docs # ...
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ @Time : 2019-09-21 19:54 @Author : Wang Xin @Email : wangxin_buaa@163.com @File : __init__.py.py """
import torch from torchaudio_unittest.common_utils import PytorchTestCase from .torchscript_consistency_impl import Functional, FunctionalComplex class TestFunctionalFloat32(Functional, PytorchTestCase): dtype = torch.float32 device = torch.device('cpu') class TestFunctionalFloat64(Functional, PytorchTestC...
import os root_dir = os.path.expanduser("~") root_dir = os.path.join(root_dir, "Desktop") print_interval = 100 save_model_iter = 1000 train_data_path = os.path.join(root_dir, "Reinforce-Paraphrase-Generation/data/twitter_url/chunked/train_*") eval_data_path = os.path.join(root_dir, "Reinforce-Paraphrase-Generation/d...
import math from linked_list import LinkedList, Node # Time complexity: O(N) # Space complexity: O(N) def palindrome(s_list: LinkedList): current_node = s_list.head new_list = LinkedList() while current_node: new_list.unshift(current_node.value) current_node = current_node.next retur...
import os import json import logging from datetime import date, datetime import boto3 import botocore # logger logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) def lambda_handler(event, context): class CrawlerThrottlingException(Exception): pass class CrawlerRunningException(Exception): pa...