content
stringlengths
0
894k
type
stringclasses
2 values
from dataclasses import dataclass from bindings.csw.animate_type import AnimateType __NAMESPACE__ = "http://www.w3.org/2001/SMIL20/Language" @dataclass class Animate1(AnimateType): class Meta: name = "animate" namespace = "http://www.w3.org/2001/SMIL20/Language"
python
import unittest import electricity class VersionTestCas(unittest.TestCase): def test_version(self): self.assertEqual(electricity.__version__, '0.1')
python
from keris.layers.merge import Concatenate, Sum from keris.layers.core import Input, Dense from keris.layers.convolution import Conv2D from keris.layers.dropout import Dropout from keris.layers.pool import MaxPooling2D, GlobalAveragePooling2D
python
from functools import wraps def tags(tag_name): def tags_decorator(func): @wraps(func) def func_wrapper(name): return "<{0}>{1}</{0}>".format(tag_name, func(name)) return func_wrapper return tags_decorator @tags("p") def get_text(name): """returns some text""" retur...
python
import os import torch import numpy as np from torch.autograd import Variable from .base_trainer import BaseTrainer from model import networks from model.loss import AttnDiscriminatorLoss, AttnGeneratorLoss, KLLoss from utils.util import convert_back_to_text from collections import OrderedDict dirname = os.path.dirname...
python
import os from setuptools import setup from pip.req import parse_requirements # parse requirements reqs = [str(r.req) for r in parse_requirements("requirements.txt", session=False)] # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README fi...
python
from packetbeat import BaseTest """ Tests for trimming long results in pgsql. """ class Test(BaseTest): def test_default_settings(self): """ Should store the entire rows but only 10 rows with default settings. """ self.render_config_template( pg...
python
# Generated by Django 2.0.3 on 2018-03-16 19:42 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('nps', '0021_auto_20180316_1239'), ] operations = [ migrations.RenameField( model_name='rawresults', old_name='role_type', ...
python
# Import Abaqus and External Modules from abaqusConstants import * from abaqus import * import random import regionToolset import mesh import step import part randomSeed=[41557] for eachModel in range(0,1): # # Create Model Database VerFile=Mdb(pathName="MStructure") VerModel=VerFile.models['Model-1']...
python
''' @author: Jakob Prange (jakpra) @copyright: Copyright 2020, Jakob Prange @license: Apache 2.0 ''' import sys import json import argparse as ap from pathlib import Path from .mode import Mode argparser = ap.ArgumentParser() mode = argparser.add_subparsers(help='mode', dest='mode') def str2bool(v): if isinst...
python
# SPDX-FileCopyrightText: 2020 Melissa LeBlanc-Williams, written for Adafruit Industries # # SPDX-License-Identifier: Unlicense """ `adafruit_matrixportal.network` ================================================================================ Helper library for the MatrixPortal M4 or Adafruit RGB Matrix Shield + Met...
python
"""Tests for the NumericValue data class.""" from onyx_client.data.animation_keyframe import AnimationKeyframe from onyx_client.data.animation_value import AnimationValue from onyx_client.data.numeric_value import NumericValue class TestNumericValue: def test_create(self): expected = NumericValue( ...
python
from .config_diff import Config import yaml def save(filename: str, config: Config): """Save configuraion to file""" with open(filename, 'w') as fh: yaml.dump(config, fh, default_flow_style=False)
python
import os SPREEDLY_AUTH_TOKEN = os.environ.get('SPREEDLY_AUTH_TOKEN','asdfasdf') SPREEDLY_SITE_NAME = 'jamesr-c-test'
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Advent of Code 2020 Day 25, Part 1 """ def main(): with open('in.txt') as f: card_key, door_key = map(int, f.readlines()) subject_number = 7 value = 1 card_loop = 0 while True: card_loop += 1 value *= subject_number ...
python
import threading from time import sleep lock = threading.Lock() # funcao que espera 1 segundo def wait(): global lock while True: sleep(1) lock.release() def LerVelocidade(): global lock while True: lock.acquire() print('Leitura da Velocidade') print('cheguei'...
python
print('gunicorn hook') hiddenimports = ['gunicorn.glogging', 'gunicorn.workers.sync']
python
from unittest import mock from bx_py_utils.test_utils.datetime import parse_dt from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db.utils import IntegrityError from django.test import TestCase from django.utils import timezone from bx_django_utils.models.m...
python
import bge scn = bge.logic.getCurrentScene() def CamAdapt(cont): lum = scn.objects['und.lum1'] nab = scn.objects['Naball_gerUnderground'] def LoadPart1(cont): loadObj = []
python
#!/usr/bin/env python3 '''Written by Corkine Ma 这个模块的大部分是子类化了一个QDialog,用来接受用户的输入,并且将其保存到daily.setting文件夹中 除此之外,还有一个函数,这个函数负责从daily.setting读取数据,并且使用checkandsend.py模块中的 两个函数来判断在数据库位置是否存在监视文件夹中符合正则表达式规则的文件,如果文件夹中有这样的文件 但是数据库中没有,就判定是一篇新日记,然后调用邮件发送程序发送邮件,其会返回一个bool值,大部分情况, 只要参数文件和日志文件不出问题,返回的都是true,至于发送邮件出错,依旧会返回true(因为考虑到可...
python
from flask import Blueprint from flask import Blueprint from flask_sqlalchemy import SQLAlchemy from sqlalchemy import or_,and_ from .form import * from utils import * from decorators import admin_required, permission_required # from .. import app from flask import current_app from wtforms import ValidationError, vali...
python
#!/usr/bin/env python from distutils.core import setup import uritemplate base_url = "http://github.com/uri-templates/uritemplate-py/" setup( name = 'uritemplate', version = uritemplate.__version__, description = 'URI Templates', author = 'Joe Gregorio', author_email = 'joe@bitworking.org', url = base_ur...
python
# # Copyright (C) 2019 Luca Pasqualini # University of Siena - Artificial Intelligence Laboratory - SAILab # # # USienaRL is licensed under a BSD 3-Clause. # # You should have received a copy of the license along with this # work. If not, see <https://opensource.org/licenses/BSD-3-Clause>. # Import scripts from .pass...
python
from appcontroller import AppController class CustomAppController(AppController): def __init__(self, *args, **kwargs): AppController.__init__(self, *args, **kwargs) def start(self): print "Calling the default controller to populate table entries" AppController.start(self) def sto...
python
import json import os, re import numpy as np import pandas as pd from scipy.stats import describe from tqdm import tqdm # Open a file path = "/home/ubuntu/model-inference/rayserve/gpt-optim" dirs = os.listdir(path) # This would print all the files and directories latency_list = [] requests = {} for file in dirs: ...
python
# Crei um programa que mostre na tela todos os números pares que estão no intervalo entre 1 e 50. """for contador in range(1, 51): if contador % 2 == 0: if contador == 50: print(f'{contador}.') else: print(f'{contador}, ', end='') """ for contador in range(2, 51, 2): ...
python
from functools import partial from copy import copy import numpy as np from PyQt5.QtWidgets import ( QGridLayout, QHBoxLayout, QVBoxLayout, QGroupBox, QCheckBox, QComboBox, QScrollArea, QLabel, QSlider, ) from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg from matplotl...
python
# # PySNMP MIB module RFC1407-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RFC1407-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:48:41 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, 0...
python
# coding: utf8 """语音结果和指令比对""" from aip import AipNlp from nlp.configs import APP_ID, API_KEY, SECRET_KEY def match(voice2text, command): """匹配指令""" client = AipNlp(APP_ID, API_KEY, SECRET_KEY) nlp_result_grnn = client.simnet(voice2text, command, {"model": "GRNN"}) if nlp_result_grnn.get("score", 0.5...
python
from setuptools import setup setup(name='Numpyextension', version='1.1.1', description='A library focused functions that only require numpy.', url='https://www.github.com/pmp47/Numpyextension', author='pmp47', author_email='phil@zeural.com', license='MIT', packages=['numpyextension'], install_requires=['numpy==...
python
from cfg import * import socket import re from commands import commands def send_message(message): s.send(bytes("PRIVMSG #" + NICK + " :" + message + "\r\n", "UTF-8")) s = socket.socket() s.connect((HOST, PORT)) s.send(bytes("PASS " + PASS + "\r\n", "UTF-8")) s.send(bytes("NICK " + NICK + "\r\n", "UTF-8")) s.send...
python
from db_facts.jinja_context import pull_jinja_context import unittest from unittest.mock import patch from .mock_dbcli_config import mock_dbcli_config @patch('db_facts.env_jinja_context.os') class TestEnvJinjaContext(unittest.TestCase): def test_with_env_set(self, mock_os): config = { 'jinja_c...
python
# Generated by Django 3.1.2 on 2020-10-11 09:14 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('trainer', '0025_user_data_adaptivity'), ] operations = [ migrations.AddField( model_name='user', name='gamification'...
python
#!/usr/bin/env python """ Gaussian Distribution based two-tail error data reduction data-processing pipeline for dataframes """ # imports import matplotlib.pyplot as plt import numpy as np from scipy import stats __author__ = "Rik Ghosh" __copyright__ = "Copyright 2021, The University of Texas at Austin" __credi...
python
""" Module for version router Contains functions and api endpoints for version listing """ import sys from operator import attrgetter from typing import List from fastapi import APIRouter from tracktor.error import ItemNotFoundException from tracktor.models import VersionModel router = APIRouter(prefix="/versions",...
python
import argon2 import b64 from typing import Optional, Dict, Union, List from securerandom import rand_bytes from kdfs.kdf import Kdf class Argon2Kdf(Kdf): @staticmethod def sensitive(): return Argon2Kdf(12, 2 * 1024 * 1024, 8, argon2.Type.ID, rand_bytes(32)) @staticmethod def fast(): ...
python
#!/usr/bin/env python from __future__ import print_function import subprocess as sp import argparse import os import re def get_paths(root, extension): # scan directories paths = [] for root, dirs, files in os.walk(root): for name in files: if name.endswith(extension): ...
python
from class_names import CLASS_NAMES import json import numpy as np import scipy import re FEATURES = [ 'calls_to_batchCancelOrders', 'calls_to_batchFillOrKillOrders', 'calls_to_batchFillOrders', 'calls_to_batchFillOrdersNoThrow', 'calls_to_cancelOrder', 'calls_to_cancelOrdersUpTo', # 'calls...
python
import argparse import base64 from googleapiclient import discovery from oauth2client.client import GoogleCredentials def get_args(): """ Collect command-line arguments and return the argument values :return: A set of three values: image file name (and path), the operation mode, and the max number of res...
python
"""Data is typically multi-dimensional. :class:`~smif.metadata.spec.Spec` is used to describe each dataset which is supplied to - or output from - each :class:`~smif.model.model.Model` in a :class:`~smif.model.model.CompositeModel` """ from collections import defaultdict from smif.metadata.coordinates import Coordinat...
python
#!/usr/bin/env python # Copyright 2021 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...
python
""" Transport for communicating with the LaunchKey API of HTTP""" import requests from .. import LAUNCHKEY_PRODUCTION from .base import APIResponse, APIErrorResponse class RequestsTransport(object): """ Transport class for performing HTTP based queries using the requests library. """ url = LAUN...
python
# Copyright (c) IOTIC LABS LIMITED. All rights reserved. Licensed under the Apache License, Version 2.0. from typing import Callable import base58 from iotics.lib.identity.api.advanced_api import AdvancedIdentityLocalApi from iotics.lib.identity.crypto.identity import make_identifier from iotics.lib.identity.crypto....
python
import re # machine snapshot platforms LINUX = "LINUX" MACOS = "MACOS" WINDOWS = "WINDOWS" ANDROID = "ANDROID" IOS = "IOS" IPADOS = "IPADOS" TVOS = "TVOS" PLATFORM_CHOICES = ( (LINUX, 'Linux'), (MACOS, 'macOS'), (WINDOWS, 'Windows'), (ANDROID, 'Android'), (IOS, 'iOS'), (IPADOS, 'iPadOS'), ...
python
from __future__ import absolute_import, print_function, division, unicode_literals import sys import os from subprocess import Popen, PIPE from time import time import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn import datasets from mlfromscratch.util import ( ...
python
''' Module defining the toolkit in use. Created on Feb 13, 2019 @author: albertgo ''' import os # determine toolkit to be used when loading o molecules TOOLKIT = os.environ.get("CDDLIB_TOOLKIT",None) if not TOOLKIT: # default is openeye but try falling back on rdkit if oe is not available try: import ...
python
__all__ = ['HighCardinalityStringIndexer'] import json import logging from typing import Dict, List import pyspark.sql.functions as F from pyspark import SparkContext, keyword_only from pyspark.ml import Estimator, Transformer from pyspark.ml.feature import IndexToString, StringIndexer from pyspark.ml.param import Pa...
python
from pathlib import Path import pandas as pd import ibis import ibis.expr.operations as ops import ibis.expr.types as ir from ibis.backends.tests.base import BackendTest, RoundHalfToEven class TestConf(BackendTest, RoundHalfToEven): check_names = False additional_skipped_operations = frozenset({ops.StringSQ...
python
from selenium import webdriver # https://askubuntu.com/questions/870530/how-to-install-geckodriver-in-ubuntu def start_firefox(): my_browser = webdriver.Firefox() # send the browser to a specif URL my_browser.get('https://pitpietro.github.io/') # simulate the click on a link (and redirect to that lin...
python
from indice_pollution.extensions import db class Zone(db.Model): __table_args__ = {"schema": "indice_schema"} id = db.Column(db.Integer, primary_key=True) type = db.Column(db.String) code = db.Column(db.String) @classmethod def get(cls, code, type_): return Zone.query.filter_by(code=...
python
from django import template import datetime from cart.cart import Cart from cart.settings import CART_TEMPLATE_TAG_NAME register = template.Library() @register.simple_tag(takes_context=True, name=CART_TEMPLATE_TAG_NAME) def get_cart(context, session_key=None): """ Make the cart object available in template. ...
python
import unittest #import env from canvas import Canvas from color import Color class TestCanvas(unittest.TestCase): def test_canvas(self): c = Canvas(10, 20) self.assertEqual(c.width, 10) self.assertEqual(c.height, 20) def test_write_pixel(self): c = Canvas(10, 2...
python
""" Collect email information """ import os import subprocess import json import base64 from flask import current_app from pathlib import Path from ..functions import get_python_path class Email: """ Set up an email """ config_path = None __addresses = [] __ccs = [] __files = ...
python
__version__ = "0.0.10" from .core import *
python
""" Program to classify the snps based on the following: 1. whether are at stop codons 2. where are located on a functional gene sequence 4. whether are synonymous (S) or non-synonymous (N) 5. whether are fourfold degenerate sites (S) or non-degenerate sites (N) and count the number the number for each of the class, an...
python
from typing import List def _get_data_array(filename: str) -> List[int]: lines = open(filename, 'r').readlines() ints = [int(i.strip()) for i in lines] return ints def _validate(factors: List[int], target: int) -> bool: sorted_factors = sorted(factors) left = 0 right = len(sorted_factors) - 1 ...
python
class Solution: @lru_cache(None) def allPossibleFBT(self, n: int) -> List[Optional[TreeNode]]: if n % 2 == 0: return [] if n == 1: return [TreeNode(0)] ans = [] for leftCount in range(n): rightCount = n - 1 - leftCount for left in self.allPossibleFBT(leftCount): for...
python
from pypy.lang.smalltalk import objspace space = objspace.ObjSpace() def ismetaclass(w_cls): # Heuristic to detect if this is a metaclass. Don't use apart # from in this test file, because classtable['w_Metaclass'] is # bogus after loading an image. return w_cls.w_class is space.classtable['w_Metaclas...
python
import numpy as np import pandas as pd df = pd.DataFrame(np.arange(5*4).reshape(5,4)) df sampler = np.random.permutation(5) sampler df.take(sampler) sampler_col = np.random.permutation(4) sampler_col sampler_col = np.random.permutation(4) sampler_col df[sampler_col] df.sample(3) df.sample(3, axis=0) df.sample(3, axis=...
python
'''save/load from S3 routines ------- ''' from __future__ import print_function, division, unicode_literals from .omas_utils import * from .omas_core import save_omas_pkl, load_omas_pkl, ODS def _base_S3_uri(user): return 's3://omas3/{user}/'.format(user=user) # -------------------------------------------- #...
python
""" Pascal sections to be inserted in code. Copyright (C) 2019, Guillaume Gonnet This project is under the MIT license. """ from typing import List, Text def gen_bird_array(envs: List, name: Text): "Generate a static array for bird directions / species." upper = name.capitalize() count = sum(int("sam...
python
from __future__ import annotations from typing import TYPE_CHECKING, Optional from ._base import TelegramObject if TYPE_CHECKING: # pragma: no cover from .photo_size import PhotoSize class VideoNote(TelegramObject): """ This object represents a video message (available in Telegram apps as of v.4.0). ...
python
import datetime from django.db import models from django.utils import timezone #My comments: #Each model is represented by a class that subclasses django.db.models.Model. #Each model has a number of class variables, each of which represents a database field in the model. #Each field is represented by an instance of...
python
''' Class to access documents and links stored in the hdf5 file. ''' import h5py class CorpusHDF5(): def __init__(self, path): self.f = h5py.File(path, 'r') def get_article_text(self, article_id): return self.f['text'][article_id] def get_article_title(self, article_id): retur...
python
str1 = 'Hello' print(str1.endswith('e', 0, 2)) print(str1.endswith('o', 0, 4)) #True (substring 'He' (0 to 1 index) ends with 'e') #False (substring 'Hell' (0 to 3 index) does not end with 'o')
python
# # Copyright 2015, 2016 Human Longevity, 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 agr...
python
# coding=utf-8 """ OneForAll默认配置 """ import pathlib import warnings # 禁用所有警告信息 warnings.filterwarnings("ignore") # 路径设置 relative_directory = pathlib.Path(__file__).parent.parent # OneForAll代码相对路径 module_dir = relative_directory.joinpath('modules') # OneForAll模块目录 third_party_dir = relative_directory.joinpath('thir...
python
import logging import math import sys from datetime import timedelta from typing import TextIO, Sequence, Tuple, NoReturn import attr import httpx from cached_property import cached_property from fire import Fire @attr.s(auto_attribs=True, kw_only=True) class BaseCommand: stream: TextIO = sys.stdout def _pr...
python
#!/usr/bin/python3 import rospy from std_msgs.msg import Int16MultiArray, String, Bool import numpy as np import pickle import os import yaml import h5py from utils.audio import get_mfcc from utils.model import get_deep_speaker from utils.utils import batch_cosine_similarity, dist2id n_embs = 0 X = [] y = [] def sav...
python
#!/user/bin/env python '''containsAlternativeLocations.py This filter return true if this structure contains an alternative location ''' __author__ = "Mars (Shih-Cheng) Huang" __maintainer__ = "Mars (Shih-Cheng) Huang" __email__ = "marshuang80@gmail.com" __version__ = "0.2.0" __status__ = "Done" class ContainsAlte...
python
import cv2 import gym import numpy as np from gym import spaces from PIL import Image from gym.wrappers.monitoring.video_recorder import VideoRecorder # https://github.com/chris-chris/mario-rl-tutorial/ class MyDownSampleWrapper(gym.ObservationWrapper): def __init__(self, env, image_size): super(MyDownSam...
python
from CameraOrMarker import * class Scenarios: def __init__(self, scenario): self.num_generated_samples = 217 self.std_corners_f_image = 0.3 self.marker_len = 0.162717998 # generate_solve_pnp_inputs options self.use_sigma_points = False self.use_dist_params = True...
python
"""Test SQL database migrations.""" from pathlib import Path from typing import Generator import pytest import sqlalchemy from pytest_lazyfixture import lazy_fixture # type: ignore[import] from robot_server.persistence.database import create_sql_engine from robot_server.persistence.tables import ( migration_tabl...
python
# coding: utf8 from __future__ import unicode_literals from ...symbols import LEMMA, PRON_LEMMA MORPH_RULES = { "PRON": { "jeg": {LEMMA: PRON_LEMMA, "PronType": "Prs", "Person": "One", "Number": "Sing", "Case": "Nom"}, "mig": {LEMMA: PRON_LEMMA, "PronType": "Prs", "Person": "...
python
# vim: set sw=4 ts=4 expandtab : from const import * import math from scipy import stats def teller(state, nstate): nchain = nstate['chain'] # mimic network unpredictability using random variable df = int(math.log10(nchain['txpending'] + 10)) rv = stats.chi2(df) #lazy_txs = int(0.01 * nchain['txp...
python
from mechanize import Browser from bs4 import BeautifulSoup import sys import re br = Browser() br.set_handle_robots(False) br.addheaders = [("User-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4275.0 Safari/537.36")] def product_search(keyword): br.open("ht...
python
from .test_languages import TestLanguages from .test_translator import TestTranslator
python
from setuptools import setup, find_packages PACKAGES = find_packages() with open("README.md", "r") as fh: long_description = fh.read() setup(name='python-neurostore', version='0.1', description='NeuroStore API wrapper', long_description=long_description, long_description_content_type="text...
python
#!/usr/bin/env python # ---------------------------------------------------------------------------- # Pyglet GLSL Demo Dot3 Bumpmap Shader on http://www.pythonstuff.org # pythonian_at_inode_dot_at (c) 2010 # # based on the "graphics.py" batch/VBO demo by # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights re...
python
""" The wntr.metrics.hydraulic module contains hydraulic metrics. """ import wntr.network from wntr.network.graph import _all_simple_paths #from wntr.metrics.misc import _average_attribute import numpy as np import pandas as pd import networkx as nx import math from collections import Counter import logging logger = ...
python
import asyncio from typing import Union from pynput.keyboard import Key, KeyCode, Listener from core_modules.macro_handler import MacroHandler from core_modules.tray import Tray from global_modules import logs class KeyboardHandler: def __init__(self, macro_handler: MacroHandler, tray: Tray, loop: asyncio.Abstr...
python
import requests from slack.web.classes import messages def webhook_response(response_url: str, json=None): return requests.post(response_url, json=json) def basic_responder_response(text: str) -> messages.Message: return messages.Message(text=text)
python
from sly import Lexer, Parser from os import path from defs import * global curr_file, curr_text, error_occurred, curr_namespace, reserved_names def syntax_error(line, msg=''): global error_occurred error_occurred = True print() if msg: print(f"Syntax Error in file {curr_file} line {line}:")...
python
#!/usr/bin/env python # coding: utf-8 # # ML Pipeline Preparation # Follow the instructions below to help you create your ML pipeline. # ### 1. Import libraries and load data from database. # - Import Python libraries # - Load dataset from database with [`read_sql_table`](https://pandas.pydata.org/pandas-docs/stable/g...
python
#!/usr/bin/python # The templating engine and the parser for the dllup markup language are hereby # released open-source under the MIT License. # # Copyright (c) 2015 Daniel Lawrence Lu # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files ...
python
import argparse from datetime import datetime, timedelta import logging import os import pprint import random from config import DATETIME_FORMAT, EXPORT_PATH, GENDER_PREF_FUNCTIONS, AGE_PREF_FUNCTIONS,\ AGE_YOUNG_MID, AGE_MID_OLD, DEPARTMENTS, VENDORS, CATEGORIES, CATEGORIES_UNIQUE, DEVELOPMENT from converters.sum...
python
from pathlib import Path class DocsTranslateBaseException(Exception): pass class UnknownServiceError(DocsTranslateBaseException): def __init__(self, service_name: str) -> None: super().__init__(f'{service_name} service is unknown') class ConfigurationError(DocsTranslateBaseException): def __in...
python
# Copyright (c) Microsoft. All rights reserved. # Licensed under the MIT license. See LICENSE.md file in the project root # for full license information. # ============================================================================== import os, sys import numpy as np from cntk.device import set_default_device abs_p...
python
from __future__ import absolute_import, unicode_literals import logging import os import pytest from psd_tools.psd.filter_effects import (FilterEffects, FilterEffect, FilterEffectChannel, FilterEffectExtra) from ..utils import check_write_read, check_read_write, TEST_ROOT logger = logging.getLogger(__name__) @pyt...
python
from django import template from backoffice.models import * register = template.Library() @register.simple_tag def number_of_authors(request): qs = Author.objects.all() return qs.count() @register.simple_tag def number_of_questions(request): qs = Question.objects.all() return qs.count() @register....
python
#/usr/bin/python3 # -*- coding: utf-8 -*- import sys import getopt import re from itertools import * import time import json import csv import codecs import random as r import time import random import pandas as pd ##此程序用来将csv文件转成json格式
python
import logging import typing import ckan.plugins.toolkit as toolkit logger = logging.getLogger(__name__) @toolkit.side_effect_free def dcpr_request_list(context: typing.Dict, data_dict: typing.Dict) -> typing.List: logger.debug("Inside the dcpr_request_list action") access_result = toolkit.check_access( ...
python
""" Unit testing ============ Note: Tests for `ensemble.control.operational.reference` """ # ============================================================================ # STANDARD IMPORTS # ============================================================================ import pytest import numpy as np fr...
python
"""Test parallel deployment.""" # pylint: disable=redefined-outer-name from __future__ import annotations import platform import shutil from pathlib import Path from typing import TYPE_CHECKING, Generator import pytest from runway._cli import cli if TYPE_CHECKING: from click.testing import CliRunner, Result CU...
python
import unittest from mock import patch from todo import Todo, TodoManager class TestTodo(unittest.TestCase): def test_default(self): todo = Todo('foo') self.assertEqual(todo.task, 'foo') self.assertFalse(todo.done) def test_default_done(self): todo = Todo('bar', True) ...
python
from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences import os import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) from tqdm import tqdm import math from sklearn.model_selection import train_test_split import pickle...
python
import scrapy from scrapy.crawler import CrawlerProcess class VersionSpider(scrapy.Spider): name = 'versions' custom_settings = { "FEED_FORMAT": "json", "FEED_URI": "data/%(name)s/%(time)s.json" } start_urls = ['https://docs.hortonworks.com/HDPDocuments/HDP3/HDP-3.1.0/release-notes...
python
from typing import Dict, Optional, Union from pyspark.sql import SparkSession, Column, DataFrame # noinspection PyUnresolvedReferences from pyspark.sql.functions import col from pyspark.sql.types import ( ArrayType, LongType, StringType, StructField, StructType, TimestampType, DataType, ) ...
python
""" The MIT License (MIT) Originally in 2020, for Python 3.x Copyright (c) 2021 Panos Achlioptas (ai.stanford.edu/~optas) & Stanford Geometric Computing Lab """ import torch import numpy as np import pandas as pd from PIL import Image from torch.utils.data import Dataset, DataLoader from ..evaluation.emotion_alignment...
python
""" Last edited: November 12 2020 |br| @author: FINE Developer Team (FZJ IEK-3) """ from FINE.component import Component, ComponentModel from FINE import utils from tsam.timeseriesaggregation import TimeSeriesAggregation import pandas as pd import numpy as np import pyomo.environ as pyomo import pyomo.opt as opt impor...
python