content
stringlengths
0
894k
type
stringclasses
2 values
from .regressor import CrossLgbRegression
python
from django.urls import path, include from django.contrib import admin from django.contrib.auth import views as auth_views admin.autodiscover() import autobot.views # To add a new path, first import the app: # import blog # # Then add the new path: # path('blog/', blog.urls, name="blog") # # Learn more here: https:/...
python
# This imports all that is listed in __init__.py of current directory: from __init__ import * #-------------------------------------------------------------------------------------- MAIN WINDOW CLASS ----------------------------------------------------------------------------------# class Window(QtGui.QMainWindow): ...
python
import os # Database connection setup class Config(object): SERVER = '' DATABASE = '' DRIVER = '' USERNAME = '' PASSWORD = '' SQLALCHEMY_DATABASE_URI = f'mssql+pyodbc://{USERNAME}:{PASSWORD}@{SERVER}/{DATABASE}?driver={DRIVER}' SQLALCHEMY_TRACK_MODIFICATIONS = False DEBUG = True S...
python
import os import sys filename = __file__[:-5] + '-input' with open(filename) as f: lines = f.read().splitlines() lines = list(map(lambda s: s.split('-'), lines)) connections = {} for line in lines: if line[0] not in connections and line[1] != 'start' and line[0] != 'end': connections[line[0]] =...
python
import numpy as np from . InverterException import InverterException from . InputData import InputData class Image(InputData): """ This class represents a camera image and can be used as input to the various inversion algorithms. Images can be created directly, or by importing and filtering a video. ...
python
"""Support for Avanaza Stock sensor."""
python
import os import re import codecs def isValidLine(line): if re.search('include \"', line) == None or line.find('.PSVita') != -1 or line.find('.PS4') != -1 or line.find('.Switch') != -1 or line.find('.XBoxOne') != -1: return True return False class CreateHeader: def __init__(self): self.lines = [] def addLine...
python
from __future__ import annotations from typing import List, Tuple import ujson import os.path as path import stargazing.pomodoro.pomodoro_controller as pomo_pc CONFIG_FILE_PATH = f"{path.dirname(path.abspath(__file__))}/../config/settings.json" def get_saved_youtube_player_urls() -> List[str]: with open(CONFIG_...
python
OUTPUT_ON = b'1' OUTPUT_OFF = b'0' OUTPUT_PULSE = b'P' OUTPUT_CURRENT = b'O' INPUT_DELTA = b'D' INPUT_CURRENT = b'C' TURNOUT_NORMAL = b'N' TURNOUT_REVERSE = b'R' IDENTIFY = b'Y' SERVO_ANGLE = b'A' SET_TURNOUT = b'T' GET_TURNOUT = b'G' CONFIG = b'F' ACKNOWLEDGE = b'!' STORE = b'W' ERRORRESPONSE = b'E' WARNINGRESPONSE = ...
python
import tensorflow as tf # Stolen from magenta/models/shared/events_rnn_graph def make_rnn_cell(rnn_layer_sizes, dropout_keep_prob=1.0, attn_length=0, base_cell=tf.contrib.rnn.BasicLSTMCell, state_is_tuple=False): cells = [] for num_units in rnn_layer_sizes: cell = base_cell(num_units, stat...
python
from block import Block from transaction import Transaction from Crypto.PublicKey import RSA from Crypto.Hash import SHA256 import bitcoin class BlockChain: def __init__(self): self.chain = [] self.tx_pool = [] self.bits = 2 self.reward = 50 genesis_block = Block(None, sel...
python
''' Nombre de archivo: +procesamientodatos.py Descripción: +Librería con funciones para el procesamiento de los datos Métodos: |--+cargar_datos |--+generar_tablas |--+almacenar_tablas ''' #librerías necesarias import sys, os, glob, datetime as dt from pyspark.sql import SparkSession, functions as F, window ...
python
"""VIC Emergency Incidents feed entry.""" from typing import Optional, Tuple import logging import re from time import strptime import calendar from datetime import datetime import pytz from aio_geojson_client.feed_entry import FeedEntry from geojson import Feature from markdownify import markdownify from .consts impo...
python
import networkx as nx from . import utils # ===== asexual lineage metrics ===== def get_asexual_lineage_length(lineage): """Get asexual lineage length. Will check that given lineage is an asexual lineage. Args: lineage (networkx.DiGraph): an asexual lineage Returns: length (int) of ...
python
import tqdm from multiprocessing import Pool import logging from dsrt.config.defaults import DataConfig class Filter: def __init__(self, properties, parallel=True, config=DataConfig()): self.properties = properties self.config = config self.parallel = parallel self.init_logger() ...
python
import os import numba import torch import torch.nn as nn from torch.optim.lr_scheduler import ReduceLROnPlateau from optimizer import * from trainer_callbacks import * from utils import * #%% #################################### Model Trainer Class #################################### class ModelTrainer(...
python
from backend.stage import ready_stage from backend import message from backend import helpers class JobStage(ready_stage.ReadyStage): stage_type = 'Job' def __init__(self, game) -> None: super().__init__(game) self._job_selected = {} # facility selected indexed by player @classmethod ...
python
""" Robot http server and interface handler Approach to operations: This http server module is conceptualized as a gateway between a robot, with private, internal operations, and the web. Incoming requests for actions to be executed by the robot and requests for information such as telemetry data arriv...
python
""" How plugins work ---------------- From a user's perspective, plugins are enabled and disabled through the command line interface or through a UI. Users can also configure a plugin's behavior through the main Kolibri interface. .. note:: We have not yet written a configuration API, for now just make sure ...
python
# -*- coding: utf-8 -*- """ Base classes for Models. """ import typing as tp from uuid import UUID ModelType = tp.TypeVar("ModelType", bound='ModelBase') class Model(tp.Protocol): """ Interface for base model class. """ uid: tp.Optional[UUID] class ModelBase(object): """ Model storage ultim...
python
# pylint doesn't know about pytest fixtures # pylint: disable=unused-argument import datetime import os import time import uuid import boto3 import pytest from dagster_k8s.test import wait_for_job_and_get_raw_logs from dagster_k8s_test_infra.integration_utils import ( can_terminate_run_over_graphql, image_pull...
python
from __future__ import annotations import src.globe.hexasphere as hexasphere if __name__ == "__main__": hs = hexasphere.Hexsphere(50, 1, 0.8) print(hs)
python
import itertools from matplotlib import cm import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Rectangle from rllab.envs.base import Env from rllab.misc import logger from rllab.spaces import Box from rllab.spaces import Discrete from utils import flat_to_one_hot, np_seed class Discre...
python
from distutils.core import setup import setuptools setup( name="turkishnlp", version="0.0.61", packages=['turkishnlp'], description="A python script that processes Turkish language", long_description=open('README.md', encoding="utf8").read(), long_description_content_type='text/markdown', u...
python
"""Frontend for spectra group project""" __author__ = """Group01""" __version__ = '0.1.0'
python
#!/usr/bin/env python # 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...
python
import os import csv import json import torch import pickle import random import warnings import numpy as np from functools import reduce from typing import Dict, List, Tuple, Set, Any __all__ = [ 'to_one_hot', 'seq_len_to_mask', 'ignore_waring', 'make_seed', 'load_pkl', 'save_pkl', 'ensure...
python
import os import boto3 AMI = os.environ["AMI"] INSTANCE_TYPE = os.environ["INSTANCE_TYPE"] KEY_NAME = os.environ["KEY_NAME"] SUBNET_ID = os.environ["SUBNET_ID"] REGION = os.environ["REGION"] INSTANCE_PROFILE = os.environ["INSTANCE_PROFILE"] ec2 = boto3.client("ec2", region_name=REGION) def create_instance(event, ...
python
# coding: utf-8 """Pytest fixtures and utilities for testing algorithms.""" import gym import torch import torch.nn as nn import torch.distributions as distrib import pytest from irl.algo.value_methods import TensorQValues class ProbPolicy(nn.Module): """A simple test probabilistic policy.""" def __init__...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: © 2021 Massachusetts Institute of Technology. # SPDX-FileCopyrightText: © 2021 Lee McCuller <mcculler@mit.edu> # NOTICE: authors should document their contributions in concisely in NOTICE # with details inline ...
python
from __future__ import print_function, division, absolute_import from distributed.compatibility import ( gzip_compress, gzip_decompress, finalize) def test_gzip(): b = b'Hello, world!' c = gzip_compress(b) d = gzip_decompress(c) assert b == d def test_finalize(): class C(object): pas...
python
# ActivitySim # See full license in LICENSE.txt. import logging import pandas as pd from activitysim.core import tracing from activitysim.core import config from activitysim.core import pipeline from activitysim.core import inject from activitysim.core.util import assign_in_place from activitysim.abm.models.trip_pu...
python
# pytest file that runs the things in shell-sessions/ import codecs import os import pathlib import re import shutil import sys import time import pytest import asdac.__main__ sessions_dir = pathlib.Path(__file__).absolute().parent / 'shell-sessions' @pytest.fixture def shell_session_environment(tmp_path): os....
python
#!/usr/bin/env python import asyncio import websockets isExit = False async def client(uri): global isExit async with websockets.connect(uri) as websocket: while True: content = await websocket.recv() print(content) await asyncio.sleep(0.1) if isExit: ...
python
## # This software was developed and / or modified by Raytheon Company, # pursuant to Contract DG133W-05-CQ-1067 with the US Government. # # U.S. EXPORT CONTROLLED TECHNICAL DATA # This software product contains export-restricted data whose # export/transfer/disclosure is restricted by U.S. law. Dissemination # to ...
python
from actors.actions.action import Action class DelayedAction(Action): def __init__(self, action, delay_remaining=1): self.action = action self.delay_remaining = delay_remaining def on(self, actor, tile, root): delay_remaining = self.delay_remaining - 1 return root, (DelayedAc...
python
# -*- coding: utf-8 -*- # # Copyright (C) 2019 Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG), # acting on behalf of its Max Planck Institute for Intelligent Systems and the # Max Planck Institute for Biological Cybernetics. All rights reserved. # # Max-Planck-Gesellschaft zur Förderung der Wissens...
python
#!/usr/bin/env python """ Script to calculate the mean and std Usage: ./scripts/cal_deepfashion_ds_meanstd.py """ import os.path import sys cur_path = os.path.realpath(__file__) cur_dir = os.path.dirname(cur_path) parent_dir = cur_dir[:cur_dir.rfind(os.path.sep)] sys.path.insert(0, parent_dir) # -------------------...
python
''' This function returns the first longest word from the input string ''' def LongestWord(sen): max=0 st="" for c in sen: if c.isalnum(): st=st+c else: st=st+" " words=st.split(" ") for word in words: if len(word) > max: max=len(word) ...
python
from django.urls import NoReverseMatch, reverse from django.utils.html import format_html from django.utils.translation import ugettext as _ from django.utils.translation import ugettext_noop from django.views import View from memoized import memoized from dimagi.utils.parsing import string_to_utc_datetime from dimag...
python
"""Base class for module overlays.""" from pytype import datatypes from pytype.abstract import abstract class Overlay(abstract.Module): """A layer between pytype and a module's pytd definition. An overlay pretends to be a module, but provides members that generate extra typing information that cannot be expres...
python
import cplex import numpy as np names = ["x11", "x12", "x13", "x14", "x21", "x22", "x23", "x24", "x31", "x32", "x33", "x34", "y11", "y12", "y13", "y14", "y21", "y22", "y23", "y24", "y31", "y32", "y33", "y34"] T = np.array([[3.0, 2.0, 2.0, 1.0], [4.0, 3.0, 3.0...
python
"""Main entry point for the pixelation tool.""" import sys from .constants import SUCCESS from .core import PixelArt from .parser import build_parser, parse_args def main() -> None: """Parses the command line arguments and runs the tool.""" arg_parser = build_parser() args = parse_args(arg_parser) ...
python
"""Classes for defining instructions.""" from __future__ import absolute_import from . import camel_case from .types import ValueType from .operands import Operand from .formats import InstructionFormat try: from typing import Union, Sequence, List, Tuple, Any, TYPE_CHECKING # noqa from typing import Dict # n...
python
#!/usr/bin/env python3 """ Abstract base class for data Readers. """ import sys sys.path.append('.') from logger.utils import formats ################################################################################ class Reader: """ Base class Reader about which we know nothing else. By default the output form...
python
import os import shutil from codecs import open from os import path from setuptools import setup, Command here = path.abspath(path.dirname(__file__)) name = 'sqe' version = '0.1.0' class CleanCommand(Command): description = "custom clean command that forcefully removes dist and build directories" user_optio...
python
from datetime import date, datetime, timedelta from django.test import TestCase from projects.models import Project, Invoice from inspectors.models import Inspector class ProjectModelTest(TestCase): def setUp(self): date_1 = date.today() date_2 = date_1 + timedelta(days=10) p1 = Project....
python
# coding: utf-8 """ vloadbalancer Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from ncloud_vloadbalancer.api_client import ApiClient class V2Api(object): ...
python
from selenium import webdriver import logging import os logging.getLogger().setLevel(logging.INFO) def lambda_handler(event, context): logging.info("python-selenium-chromium-on-lambda started") chrome_options = webdriver.ChromeOptions() prefs = {"download.default_directory": "/tmp", "safebrowsing.enable...
python
# # PySNMP MIB module WHISP-BOX-MIBV2-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WHISP-BOX-MIBV2-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:29:30 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
python
from setuptools import setup setup(name='safygiphy', version='1.1.1', description='API Wrapper for the online Gif library, Giphy', url='https://code.tetraetc.com/SafyGiphy/', author="TetraEtc", author_email="administrator@tetraetc.com", install_requires=[ 'requests' ...
python
from mypy import api from redun.tests.utils import get_test_file def test_task_types() -> None: """ mypy should find type errors related to redun task calls. """ workflow_file = get_test_file("test_data/typing/workflow_fail.py.txt") stdout, stderr, ret_code = api.run( [ "--sh...
python
from collections import Counter l = [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8] # print(Counter(l)) s = 'aaassssvvvveeeeedddddccccccceeelllll' # print(Counter(s)) word = 'How many times does each word show up in this sentence word word show up' words = word.s...
python
"""Process ACL states""" from __future__ import absolute_import import logger from utils import dict_proto from proto.acl_counting_pb2 import RuleCounts LOGGER = logger.get_logger('aclstate') class AclStateCollector: """Processing ACL states for ACL counting""" def __init__(self): self._switch_co...
python
from sqlalchemy.orm import joinedload from FlaskRTBCTF.utils.models import db, TimeMixin, ReprMixin from FlaskRTBCTF.utils.cache import cache # Machine Table class Machine(TimeMixin, ReprMixin, db.Model): __tablename__ = "machine" __repr_fields__ = ( "name", "os", ) id = db.Column(db....
python
# This file is part of Peach-Py package and is licensed under the Simplified BSD license. # See license.rst for the full text of the license. from enum import IntEnum class FileType(IntEnum): # No file type null = 0 # Relocatable file object = 1 # Executable file executable = 2 # Fixed...
python
from requests.exceptions import ConnectionError, HTTPError, SSLError from sentry.exceptions import PluginError from django.utils.translation import ugettext_lazy as _ from sentry_youtrack.forms import VERIFY_SSL_CERTIFICATE from sentry_youtrack.youtrack import YouTrackClient class YouTrackConfiguration(object): ...
python
class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
python
import signal import sys import time from collections import deque import traceback from picrosolve.game.cell import CellList from .strategies.all import ALL_STRATEGIES class Solver(object): def __init__(self, board, strategies=None, debug=False): self._board = board if not strategies: ...
python
#!/usr/bin/python # -*- coding: utf-8 -*- import aredis import asyncio import pytest import sys from unittest.mock import Mock from distutils.version import StrictVersion _REDIS_VERSIONS = {} async def get_version(**kwargs): params = {'host': 'localhost', 'port': 6379, 'db': 0} params.update(kwargs) key...
python
import urllib2 from bs4 import BeautifulSoup import re response = urllib2.urlopen("http://www.baidu.com") # html_doc = response.read() html_doc = '<div id="u_sp" class="s-isindex-wrap s-sp-menu"> <a href="http://www.nuomi.com/?cid=002540" target="_blank" class="mnav">糯米</a> <a href="http://news.baidu.com" target="_bla...
python
from kapteyn import maputils from matplotlib import pylab as plt header = {'NAXIS': 2 ,'NAXIS1':100 , 'NAXIS2': 100 , 'CDELT1': -7.165998823000E-03, 'CRPIX1': 5.100000000000E+01 , 'CRVAL1': -5.128208479590E+01, 'CTYPE1': 'RA---NCP', 'CUNIT1': 'DEGREE ', 'CDELT2': 7.165998823000E-03 , 'CRPIX2': 5.100000000000E+01, 'CRV...
python
import neptune.new as neptune import os from GTApack.GTA_hotloader import GTA_hotloader from GTApack.GTA_Unet import GTA_Unet from GTApack.GTA_tester import GTA_tester from torchvision import datasets, transforms from torch.optim import SGD, Adam from torch.optim.lr_scheduler import (ReduceLROnPlateau, CyclicLR, ...
python
# -*- coding: utf-8 -*- import json import re import requests import urllib import logging logger = logging.getLogger('nova-playlist') class YouTubeAPI(object): clientID = 'CLIENTID' clientSecret = 'CLIENTSECRET' refreshToken = 'REFRESHTOKEN' accessToken = None def get_access_token(self): ...
python
import asyncio import datetime def get_time(): d = datetime.datetime.now() return d.strftime('%M:%S') async def coro(group_id, coro_id): print('group{}-task{} started at:{}'.format(group_id, coro_id, get_time())) await asyncio.sleep(coro_id) # 模拟读取文件的耗时IO return 'group{}-task{} done at:{}'.form...
python
import cv2 def draw_yolo_detections(image, detections, color=(0,255,0)): img = image.copy() with open("..//Data//model//yolov4/coco.names", 'rt') as f: classes = f.read().rstrip('\n').split('\n') for detect in detections: bbox = detect[1] category = classes[int(detect[0])] ...
python
import dataclasses import vk_api from vk_api import VkUpload from vk_api.bot_longpoll import VkBotLongPoll from vk_api.longpoll import VkLongPoll, VkEventType from vk_api.utils import get_random_id @dataclasses.dataclass class __cfg__: """ Bot config is struct for every bot. Easy to use because of fields """ ...
python
# F2x installation script (setup.py) # # Copyright 2018 German Aerospace Center (DLR) # # 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 # # Un...
python
from hashlib import md5 def part_1(data): i, p = 0, "" while True: if len(p) == 8: break hash = md5((data + str(i)).encode()).hexdigest() if hash[:5] == "00000": p += hash[5] i += 1 return p def part_2(data): i, p = 0, "________" while True...
python
import logging from typing import Iterable from septentrion import core, db, files, migration, style, versions logger = logging.getLogger(__name__) def initialize(settings_kwargs): quiet = settings_kwargs.pop("quiet", False) stylist = style.noop_stylist if quiet else style.stylist settings = core.initi...
python
# Copyright (c) 2020, Huawei Technologies.All rights reserved. # Licensed under the BSD 3-Clause License (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://opensource.org/licenses/BSD-3-Clause # # Unless required by applicable...
python
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Date string field.""" from __future__ import absolute_import, print_function imp...
python
import unittest import numpy as np from modem.util.channel import Channel def get_random(samples=2048): """Returns sequence of random comples samples """ return 2 * (np.random.sample((samples,)) + 1j * np.random.sample((samples,))) - (1 + 1j) class test_channel(unittest.TestCase): def setUp(s...
python
# !/usr/bin/env python3 # -*- coding: utf-8 -*- import urllib.request requestUrl = 'http://www.tvapi.cn/movie/getMovieInfo' webhead = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0', 'charset':'utf-8'} urlRequest = urllib.request.Request(url = requestUrl, headers = webhea...
python
import ckan.logic as logic import ckan.model as model import unicodedata import ckanext.hdx_users.model as umodel import ckanext.hdx_user_extra.model as ue_model import ckanext.hdx_theme.tests.hdx_test_base as hdx_test_base class TestAboutPageController(hdx_test_base.HdxBaseTest): #loads missing plugins ...
python
# -*- coding: utf-8 -*- """ Utilities for analysis Author: G.J.J. van den Burg License: See LICENSE file. Copyright: 2021, The Alan Turing Institute """ from collections import namedtuple Line = namedtuple("Line", ["xs", "ys", "style", "label"]) def dict2tex(d): items = [] for key, value in d.items(): ...
python
""" Dexter Legaspi - dlegaspi@bu.edu Class: CS 521 - Summer 2 Date: 07/22/2021 Term Project Main view/window """ import tkinter as tk from tkinter import messagebox, filedialog from PIL import ImageTk, Image as PILImage import appglobals from appcontroller import AppController from appstate import AppState from image ...
python
import typing import pytest from energuide import bilingual from energuide import element from energuide.embedded import code from energuide.exceptions import InvalidEmbeddedDataTypeError @pytest.fixture def raw_wall_code() -> element.Element: data = """ <Code id='Code 1'> <Label>1201101121</Label> <Layer...
python
__doc__ = """ 样例: 传给topic_metadata函数的内容 args = { 'pattern' : "https://mirrors.tuna.tsinghua.edu.cn/help/%s", 'themes' :["AOSP", "AUR","CocoaPods" , "anaconda","archlinux","archlinuxcn" ,"bananian","centos","chromiumos","cygwin" ,"docker","elpa","epel","fedora","git-repo" ,"git...
python
"""This module demonstrates basic Sphinx usage with Python modules. Submodules ========== .. autosummary:: :toctree: _autosummary """ VERSION = "0.0.1" """The version of this module."""
python
#!/usr/bin/env python3 # pyreverse -p contexts_basecontext_basecontext ../Lib/pagebot/contexts/basecontext/basecontext.py # dot -Tpng classes_contexts_basecontext_basecontext.dot -o classes_contexts_basecontext_basecontext.png import os import subprocess def getDirs(root): return [d for d in os.listdir(root) if ...
python
#!/usr/bin/env python3 # # Copyright 2021 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
python
# from django.contrib.oauth.models import User from rest_framework import authentication from rest_framework import exceptions import logging log = logging.getLogger(__name__) import json, re from django.core.cache import cache from django.conf import settings class TokenAuthentication(authentication.BaseAuthentic...
python
# Input: a list of "documents" at least containing: "sentences" # Output: a list of "documents" at least containing: "text" from .simplifier import Simplifier class SimplifierByKGen: def __init__(self, parameters): # some prepartion # no parameter is needed print("Info: Simplifier By KGe...
python
from django.conf import settings from django.core.files.storage import get_storage_class from storages.backends.s3boto3 import S3Boto3Storage # if settings.DEBUG: # PublicMediaStorage = get_storage_class() # PrivateMediaStorage = get_storage_class() # else: from config.settings import dev class PublicMediaSto...
python
######### # Copyright (c) 2015 GigaSpaces Technologies Ltd. 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...
python
""" Represents a square stop. """ from BeamlineComponents.Stop.StopRectangle import StopRectangle class StopSquare(StopRectangle): def __init__(self, side_length): StopRectangle.__init__(self, side_length, side_length) def sideLength(self): return self.lengthVertical()
python
import urllib, json from jwcrypto import jwt, jwk class OpenIDTokenValidator: def __init__(self, config_url, audience): """ Retrieve auth server config and set up the validator :param config_url: the discovery URI :param audience: client ID to verify against """ # ...
python
""" Tests for attention module """ import numpy as np import theano import theano.tensor as T import agentnet from agentnet.memory import GRUCell from agentnet.memory.attention import AttentionLayer from lasagne.layers import * def test_attention(): """ minimalstic test that showcases attentive RNN that reads...
python
# coding: utf-8 # $Id: $ from celery import Celery from celery.utils.log import get_task_logger, get_logger CELERY_CONFIG = { 'BROKER_URL': 'amqp://guest@localhost/', 'CELERY_RESULT_BACKEND': "redis://localhost/0", 'CELERY_TASK_SERIALIZER': "pickle", 'CELERY_RESULT_SERIALIZER': "pickle", 'CELERYD_...
python
from pyparsing import * import act topnum = Forward().setParseAction(act.topnum) attacking = Forward().setParseAction(act.attacking) blocking = Forward().setParseAction(act.blocking) tapped = Forward().setParseAction(act.tapped) untapped = Forward().setParseAction(act.untapped) enchanted = Forward().setParseAction(a...
python
import functools import numpy as np import pytest from ansys import dpf from ansys.dpf.core import examples from ansys.dpf.core import misc NO_PLOTTING = True if misc.module_exists("pyvista"): from pyvista.plotting import system_supports_plotting NO_PLOTTING = not system_supports_plotting() @pytest.fixtu...
python
import os.path as osp from .builder import DATASETS from .custom import CustomDataset @DATASETS.register_module() class Combine(CustomDataset): """PascalContext dataset. In segmentation map annotation for PascalContext, 0 stands for background, which is included in 60 categories. ``reduce_zero_label`` i...
python
<CustButton@Button>: font_size: 32 <SudGridLayout>: id = sudoku cols: 9 rows: 9 spacing = 10 BoxLayout: spacing = 10 CustButton: text: = "7" CustButton: text: = "8"
python
#!/usr/bin/env python # Returns a list of datetimes ranging from yesterday's # date back to 2014-03-30 or if passed a first argument # back to the first argument import sys import datetime yesterday = (datetime.datetime.today() - datetime.timedelta(days=1)) opening_date = datetime.datetime(2014, 03, 30) if len(sys....
python
from patchify import patchify, unpatchify from matplotlib import image as mpimg from matplotlib import pyplot as plt import cv2 as cv from PIL import Image import numpy as np from patchfly import patchfly, unpatchfly import os # ---------------------- # get a image from internet # ---------------------- # url = "htt...
python
from unittest import TestCase from moff.parser import Parser from moff.node import VideoNode, SourceNode, ParagraphNode, LinkNode, TextNode class TestReadVideo (TestCase): def test_parse1(self): parser = Parser() node1 = parser.parse_string("@video example.mp4") node2 = VideoNode( ...
python
#!/usr/bin/python import json import sys from datetime import datetime from pprint import pprint def dateconv(d): return datetime.strptime(d, "%Y-%m-%dT%H:%M:%S.%fZ").strftime("%Y-%m-%d %a %H:%M") def printtask(task, lev): print("%s %s %s" % ( lev, ("DONE" if task["completed"] else "TODO"), ...
python
import unittest from mitama._extra import _classproperty class TestClassProperty(unittest.TestCase): def test_getter(self): class ClassA: @_classproperty def value(cls): return "hello, world!" self.assertEqual(ClassA.value, "hello, world!")
python