text stringlengths 2 999k |
|---|
from flask import Flask, abort, request, Response, stream_with_context, \
jsonify
from flask_restx import Api, Resource
from flask_jwt_extended import create_access_token
import os
import requests
import json
import psycopg2
from qwc_services_core.auth import auth_manager, optional_auth, get_auth_user
from qwc_ser... |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.utils.translation import gettext as _
from core import models
class UserAdmin(BaseUserAdmin):
ordering = ['id']
list_display = ['email', 'name']
fieldsets = (
(None, {'fields': ('email', '... |
try:
num1= int(input(" Enter the first number: "))
num2= int(input(" Enter the second number: "))
total = num1 / num2
print("The division is ", total)
except ValueError as msg1:
print("The input is not valid")
except:
print("Default except block")
|
# uncompyle6 version 3.2.4
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)]
# Embedded file name: encodings.cp856
import codecs
class Codec(codecs.Codec):
def encode(self, input, errors='strict'):
return codecs.charmap_e... |
"""
This is the transform file
which include much strategy
for the data augmentation.
"""
import math
import random
import torchvision.transforms as T
from .transforms import RandomErasing
__author__ = ""
def build_transforms(cfg, is_train=True):
"""Here is the function
build a normal transforms
by to... |
"""
Trains a Pixel-CNN++ generative model on CIFAR-10 or Tiny ImageNet data.
Uses multiple GPUs, indicated by the flag --nr-gpu
Example usage:
CUDA_VISIBLE_DEVICES=0,1,2,3 python train_double_cnn.py --nr_gpu 4
"""
import os
import sys
import time
import json
import argparse
import numpy as np
import tensorflow as tf... |
import sys
import copy
from rlpyt.utils.launching.affinity import encode_affinity, quick_affinity_code
from rlpyt.utils.launching.exp_launcher import run_experiments
from rlpyt.utils.launching.variant import make_variants, VariantLevel
args = sys.argv[1:]
assert len(args) == 2
my_computer = int(args[0])
num_computer... |
# coding:utf-8
from smtplib import SMTP
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import os
def myMail(from_email,passwd,to_email,project,content):
SMTPSVR = SMTP('smtp.exmail.qq.com')
to = ','.join(to_email)
msg = MIMEMultipart('al... |
"""
Classic cart-pole system implemented by Rich Sutton et al.
Copied from http://incompleteideas.net/sutton/book/code/pole.c
permalink: https://perma.cc/C9ZM-652R
"""
import math
import gym
from gym import spaces, logger
from gym.utils import seeding
import numpy as np
class CartPoleEnv(gym.Env):
"""
Descri... |
import torch
import pytest
from collections import namedtuple
from functools import partial
from pytorch_lightning.metrics.regression import MeanSquaredError, MeanAbsoluteError, MeanSquaredLogError
from sklearn.metrics import mean_squared_error, mean_absolute_error, mean_squared_log_error
from tests.metrics.utils imp... |
"""Test for RFlink light components.
Test setup of rflink lights component/platform. State tracking and
control of Rflink switch devices.
"""
import asyncio
from homeassistant.components.light import ATTR_BRIGHTNESS
from homeassistant.components.rflink import EVENT_BUTTON_PRESSED
from homeassistant.const import (
... |
from collections import defaultdict
import pandas as pd
from pycocotools.coco import COCO
import numpy as np
class Enhance_COCO(COCO):
def __init__(self, path):
super().__init__(path)
self.classes = defaultdict()
self.reverse_classes = defaultdict()
for category in self.loadCats(sel... |
from collections import defaultdict
from enum import Enum
import numpy as np
import pandas as pd
from pandas.testing import assert_frame_equal
import unittest
from unittest import mock
from pyEpiabm.property import InfectionStatus
from pyEpiabm.utility import StateTransitionMatrix
from pyEpiabm.tests.test_unit.paramet... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import copy
import logging
import re
import torch
from fvcore.common.checkpoint import (
get_missing_parameters_message,
get_unexpected_parameters_message,
)
from fsdet.config import global_cfg
def convert_basic_c2_names(original_keys):
... |
import pygame
class Camera:
def __init__(self, player, level_end):
# Get game window size
screen_width = pygame.display.Info().current_w
screen_height = pygame.display.Info().current_h
# Passed attributes
self.player = player
self.level_end = level_end
# Class attributes
self.screen =... |
# Copyright 2018 The Simons Foundation, 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 required by appli... |
import time
from math import log
from gpiozero import PWMLED
from gpiozero import MCP3008
pot = MCP3008(0)
hall = MCP3008(1)
led = PWMLED(21)
#led.source = pot.values
#led.source = hall.values
while True:
#print(pot.value)
brightness = hall.value + ((hall.value - 0.5151) * 5.0)
if(brightness > 1.0):
... |
from __future__ import absolute_import
from sentry.integrations import Integration, IntegrationFeatures, IntegrationProvider, IntegrationMetadata
from sentry.integrations.atlassian_connect import AtlassianConnectValidationError, get_integration_from_request
from sentry.integrations.repositories import RepositoryMixin
... |
from credmark.cmf.model import Model
@Model.describe(
slug='contrib.neilz',
display_name='An example of a contrib model',
description="This model exists simply as an example of how and where to \
contribute a model to the Credmark framework",
version='1.0',
developer='neilz.eth',
outpu... |
from abc import abstractmethod
from collections import namedtuple
from copy import deepcopy
#
import numpy as np
#from pysurf.logger import get_logger
from ..utils.osutils import exists_and_isfile
from ..database.database import Database
from ..database.dbtools import DBVariable
from ..logger import Logger, get_logger
... |
import asyncio
import logging
import aioredis
from aiohttp.web import Application
from aiohttp_traversal.router import TraversalRouter
from . import resources
from . import views
log = logging.getLogger(__name__)
def includeme(app):
app.router.bind_view(resources.Root, views.Root)
app.router.bind_view(res... |
#!/usr/bin/env python3
# Copyright (c) 2018 The Refnet Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the blocksdir option.
"""
import os
import shutil
from test_framework.test_framework import RefnetTest... |
# -*- coding: utf-8 -*-
"""Click commands."""
from subprocess import call
import click
from flask import current_app
from flask.cli import with_appcontext
from werkzeug.exceptions import MethodNotAllowed, NotFound
from pathlib import Path
from itertools import chain
from flaskshop.random_data import (
create_users... |
import datetime
class CreateHeader:
def __init__(self, comment=u'//'):
self._comment=comment
self._name=''
self._submitDate=''
self._assignment=''
def setName(self, name):
self._name=name
def setSubmitDate(self, date=None):
self._submitDate=date
if date is None:
... |
""" Main optical flow calculations
* :py:func:`calc_optical_flow`: Driver script for optical flow calculation and plotting
* :py:class:`AnalyzeFlow`: Optical flow analysis pipeline class
"""
# Imports
import shutil
import pathlib
from typing import Tuple, List, Optional
# 3rd party
import numpy as np
from scipy.i... |
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views
urlpatterns = [
path('snippets/', views.SnippetList.as_view(), name='snippet-list'),
path('snippets/<int:pk>/', views.SnippetDetail.as_view(), name='snippet-detail'),
path('snippets/<int:pk... |
import unittest
from artifactcli.artifact import BasicInfo
class TestBasicInfo(unittest.TestCase):
def setUp(self):
self.test_data = [
BasicInfo('com.github.mogproject', 'xxx-yyy-assembly', '0.1-SNAPSHOT', 'jar', None),
BasicInfo('com.github.mogproject', 'xxx-yyy-assembly', '0.1.2'... |
from matrix import *
import random
import LED_display as LMD
import threading
import time
import timeit
def LED_init():
thread = threading.Thread(target=LMD.main, args=())
thread.setDaemon(True)
thread.start()
return
def draw_matrix(m):
array = m.get_array()
for y in range(m.get_dy()):
... |
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... |
# -*- coding: UTF-8 -*-
import datetime
import re
from django.contrib.auth.models import Group
from common.config import SysConfig
from sql.models import QueryPrivilegesApply, Users, SqlWorkflow, ResourceGroup
from sql.utils.resource_group import auth_group_users
from common.utils.sendmsg import MsgSender
from common.u... |
from django.contrib.contenttypes.models import ContentType
from rest_framework import serializers
from django.contrib.auth.models import Permission
class PermissionSerializer(serializers.ModelSerializer):
class Meta:
model = Permission
fields = '__all__'
class ContentTypeSerializer(serializers.... |
###############################################################################
#
# The MIT License (MIT)
#
# Copyright (c) Tavendo GmbH
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software with... |
# -*- coding: utf-8 -*-
"""
BIAS CORRECTOR FOR GPM
@ author: SERVIR MEKONG
@ correspondence M.A. LAVERDE-BARAJAS
@ mlaverdeb@gmail.com
"""
import pandas as pd
import numpy as np
from osgeo import gdal,osr
from math import sqrt
from sklearn.metrics import mean_squared_error
try:
from StringIO im... |
import ITlib
print "\nExample 7"
print "1000 videos (1080x720,RGB,25fps) are transmitted in a 60db SNR channel."
print "Available Bandwidth is 1MHz. What is the required compression ratio?\n"
B = 10.0 ** 6
SNRdb = 60
Width = 1080
Height = 720
nChannels = 3
fps = 25
bitsPerSample = 8
R = Width * Height * nChannels * ... |
# -*- coding: utf-8 -*-
###############################################################################
# This file is part of metalibm (https://github.com/kalray/metalibm)
###############################################################################
# MIT License
#
# Copyright (c) 2018 Kalray
#
# Permission is here... |
from tests.utils import W3CTestCase
class TestFlexbox_ItemVerticalAlign(W3CTestCase):
vars().update(W3CTestCase.find_tests(__file__, 'flexbox_item-vertical-align'))
|
# Copyright 2022 The Blqs Developers
#
# 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 ... |
# -*- coding:utf-8 -*-
# https://leetcode.com/problems/insert-interval/description/
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def insert(self, intervals, newInterval):
"""
... |
import argparse
import logging
import subprocess
from argparse import ArgumentParser, Namespace
from pathlib import Path
from typing import Tuple
from src.config import Config
from src.format import DiskFormatter
from src.manager import DiskManager
from src.mount import DiskMounter
def parse_arguments() -> Tuple[Arg... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010-2015 Roberto Longobardi
#
# This file is part of the Test Manager plugin for Trac.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at:
# https://trac-hacks.or... |
"""
Internationalization support.
"""
from __future__ import unicode_literals
import re
from django.utils.encoding import force_text
from django.utils.functional import lazy
from django.utils import six
__all__ = [
'activate', 'deactivate', 'override', 'deactivate_all',
'get_language', 'get_language_from_requ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from wizard_builder import __version__ as version
from setuptools import setup, find_packages
try:
import pypandoc
long_description = pypandoc.convert_file('README.md', 'rst') + \
pypandoc.convert_file('HISTORY.md', 'rst')
except BaseException:
long_d... |
# 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
# d... |
"""
This file defines some constants that
are used across the selfdiff project.
"""
# Third-party dependencies
import numpy as np
# Logic
dtype = "float64" # Default data type used by Tensors.
fuzz = 1e-7 # Small number added to values to prevent
# division by zero, or zero in log.
large... |
#!/usr/bin/env python3
# Copyright (c) 2014-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the importmulti RPC."""
from test_framework.test_framework import BitcoinTestFramework
from test_f... |
# Copyright 2022 The Flax Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
import threading
import psutil
import logging as logger
from time import sleep
from osbot_utils.utils.Files import path_combine, folder_create, file_create
from osbot_utils.utils.Json import json_save_file_pretty, json_load_file, file_exists
from cdr_plugin_folder_to_fold... |
import pytest
from django.contrib import auth
from django.urls import reverse
# pylint: disable=unused-argument
@pytest.mark.django_db
@pytest.mark.parametrize(
"username", ["root", "root@root.root", "management", "management@example.com"]
)
def test_login_success(load_test_data, client, settings, username):
... |
"""
sentry.cache.django
~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from django.core.cache import cache
from .base import BaseCache
class DjangoCache(BaseCache):
def set(... |
import sys
from database import db_session, init_db, init_engine
from Student import Student
init_engine("sqlite:///schooldb.sqlite")
init_db()
def add_user():
first_name = input("Ecrie ton first_name:")
last_name = input("Ecrie ton last_name:")
age = input("Ecrie ton age:")
email = input("Ecrie ton... |
#!/bin/env python
import validators
import random
import uuid
import datetime
import lorem
from random import randint
themesSample = {
"anti_corruption": {
"color": "#3a8789",
"label": "Anti Corruption",
"order": 0,
"value": "anti_corruption"
},
"disease": {
"color":... |
# Copyright 2020 Jigsaw Operations 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 or agreed to i... |
"""
day2-part1.py
Created on 2020-12-02
Updated on 2020-12-20
Copyright © Ryan Kan
"""
# INPUT
with open("input.txt", "r") as f:
lines = [line.strip() for line in f.readlines()]
f.close()
# COMPUTATION
noValid = 0
for line in lines:
# Parse each line
positions, character, password = line.split(" ")... |
from .kheapsort import kheapsort
def test_main():
assert list(kheapsort([3, 2, 1, 5, 4], 2)) == [1, 2, 3, 4, 5]
assert list(kheapsort([5, 4, 3, 2, 1], 4)) == [1, 2, 3, 4, 5]
assert list(kheapsort([1, 2, 3, 4, 5], 0)) == [1, 2, 3, 4, 5]
if __name__ == "__main__":
test_main()
|
import argparse
from argostranslate import package
from argostranslate import settings
"""
Example usage:
argospm update
argospm install translate-en_es
argospm list
argospm remove translate-en_es
"""
def update_index(args):
"""Update the package index."""
package.update_package_index()
def get_available... |
import sst
# Define SST core options
sst.setProgramOption("timebase", "1ps")
sst.setProgramOption("stopAtCycle", "0 ns")
sst.setStatisticOutput("sst.statOutputTXT", {"filepath" : "./L1.SIMPLEDRAM.tc.txt"})
# Define the simulation components
comp_cpu = sst.Component("cpu", "miranda.BaseCPU")
comp_cpu.addParams({
"ver... |
import logging
from datetime import timedelta
from django.db.models import Count, Prefetch
from django.conf import settings
from django.urls import reverse
from dojo.celery import app
from celery.utils.log import get_task_logger
from dojo.models import Alerts, Product, Engagement, Finding, System_Settings, User
from dj... |
from datetime import date
ano = date.today().year
count1 = 0
count2 = 0
for c in range (1,8):
nasc = int(input('Digite o ano de nascimento da {}ª pessoa: '.format(c)))
if ano - nasc < 18:
count1 = count1 + 1
else:
count2 = count2 + 1
print('Ao todo tivemos {} pessoa(s) maior(es) de idade e {... |
# Copyright 2013 OpenStack Foundation.
# 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 requ... |
import json
import os
import shutil
from pathlib import Path
import yaml
from click import exceptions
from ploomber.io._commander import Commander
from ploomber.telemetry import telemetry
import datetime
_SETUP_PY = 'setup.py'
_REQS_LOCK_TXT = 'requirements.lock.txt'
_REQS_TXT = 'requirements.txt'
_ENV_YML = 'env... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from src.envs.gym import GymEnv
from src.envs.atari import AtariEnv
from src.models.dqn_fc import DQNFCModel
from src.models.dqn_cnn import DQNCNNModel
from src.models.drqn_fc import DRQNFCModel
from src.models... |
# MIT License
#
# Copyright (c) 2018 Evgeny Medvedev, evge.medvedev@gmail.com
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# ... |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'college_comission_project.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
... |
'''
Week-2:Exercise-Fourth Power
Write a Python function, fourthPower, that takes in one number and returns that value raised to the fourth power.
You should use the square procedure that you defined in an earlier exercise (you don't need to redefine square in this box; when you call square, the grader will use our de... |
from gui import gui as GUI
# Code to actually run the GitUp app
if __name__ == "__main__":
app = GUI.GitUpApp()
app.mainloop()
|
#! /usr/bin/env python
"""
@file ion/core/unit_test.py
@author Bill French
@brief Base test class for all MI tests. Provides two base classes,
One for pyon tests and one for stand alone MI tests.
We have the stand alone test case for tests that don't require or can't
integrate with the common ION test case.
"""
fr... |
_base_ = [
'../_base_/models/slowfast_r50.py', '../_base_/schedules/sgd_100e.py',
'../_base_/default_runtime.py'
]
model = dict(
cls_head=dict(
num_classes=7,
multi_class=True))
# dataset settings
dataset_type = 'RawframeDataset'
data_root = '/home/deepo/sanofius/TRAINING/dataset/rawframes... |
class PipelineConstructionError(Exception):
pass
class InvalidConfigError(Exception):
pass
class InvalidModuleError(Exception):
pass
|
'''Update handlers for boes_bot.'''
import os
import datetime, calendar
import locale
import json
import pymongo
import pysftp
from pymongo import MongoClient
from telegram import messages
from telegram import types
from telegram import methods
from handlers.section_handler import SectionHandler
locale.setlocale(lo... |
#!/usr/bin/env python3
import sys
import struct
import pandas as pd
import matplotlib
# Must be before importing matplotlib.pyplot or pylab!
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
###############################################
dsize = 16
###################... |
def print_my_info():
print("안녕하세요.")
print("홍길동입니다.")
print("만나서반갑습니다.")
print_my_info() |
"""Config flow for Control4 integration."""
from asyncio import TimeoutError as asyncioTimeoutError
import logging
from aiohttp.client_exceptions import ClientError
from pyControl4.account import C4Account
from pyControl4.director import C4Director
from pyControl4.error_handling import NotFound, Unauthorized
import vo... |
# source https://www.youtube.com/playlist?list=PLEsfXFp6DpzRyxnU-vfs3vk-61Wpt7bOS
import cv2
import os
# source: https://stackoverflow.com/a/44659589
def image_resize(image, width = None, height = None, inter = cv2.INTER_AREA):
# initialize the dimensions of the image to be resized and
# grab the image size
... |
#
# Configuration file for gravity inversion for use by planeGravInv.py
#
# Inversion constants:
#
# scale between misfit and regularization
mu = 1.e-14
#
# used to scale computed density. kg/m^3
rho_0 = 1.
#
# IPCG tolerance *|r| <= atol+rtol*|r0|* (energy norm)
# absolute tolerance for IPCG interation... |
"""
Ray queries using the pyembree package with the
API wrapped to match our native raytracer.
"""
import numpy as np
from collections import deque
from copy import deepcopy
from pyembree import __version__ as _ver
from pyembree import rtcore_scene
from pyembree.mesh_construction import TriangleMesh
from pkg_resourc... |
import pytest
class TestHooks:
@pytest.fixture(autouse=True)
def create_test_file(self, testdir):
testdir.makepyfile(
"""
import os
def test_a(): pass
def test_b(): pass
def test_c(): pass
"""
)
def test_runtest_logreport... |
#!/usr/bin/env python
# Copyright 2020-2022 The Defold Foundation
# Copyright 2014-2020 King
# Copyright 2009-2014 Ragnar Svensson, Christian Murray
# Licensed under the Defold License version 1.0 (the "License"); you may not use
# this file except in compliance with the License.
#
# You may obtain a copy of the Licen... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# 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 ... |
def func():
if cond1:
true1
if cond2:
pass
else:
false2
if cond3:
true3
else:
false3
try:
if cond4:
true4()
else:
false4()
finally:
pass
if cond5:
try:
true5()
except:
... |
# Copyright 2017 Google LLC.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
#... |
from pylab import *
import postgkyl.tools
import scipy.optimize
def lowPass(x, dt, C):
y = 0*x # filtered signal
alpha = dt/(C+dt)
y[0] = x[0]
for i in range(1,x.shape[0]):
y[i] = alpha*x[i] + (1-alpha)*y[i-1]
return y
dat = loadtxt("s3-es-iaw_phiInCell.dat")
T = dat[:,0]
E = dat[:,1]
dt =... |
# (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
from io import open
from os import path
from setuptools import setup
HERE = path.dirname(path.abspath(__file__))
with open(path.join(HERE, 'datadog_checks', 'dev', '__about__.py'), 'r', encoding='utf-8') as f:
... |
import numpy as np
from matplotlib import pyplot as plt
import torch
from torch.utils.data.sampler import Sampler
from torchvision import transforms, datasets
from PIL import Image
# Dummy class to store arguments
class Dummy():
pass
# Function that opens image from disk, normalizes it and converts to tensor
re... |
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
# This line only needed if building with NumPy in Cython file.
from numpy import get_include
from os import system
# compile the fortran modules without linking
ext_modules = [Extension(# module name:
... |
"""
Requires some installed modules:
pip3 install "msal>=0,<2"
pip3 install "requests>=2,<3"
The configuration file would look like this:
{
"authority": "https://login.microsoftonline.com/YOUR_TENANT_ID / SITE ID",
"client_id": "CLIENT_ID",
"scope": [ "https://graph.microsoft.com/.default" ],
"secret": "CLIENT... |
"""Set module shortcuts and globals"""
import logging
from pydicom.uid import UID
from ._version import __version__
_version = __version__.split(".")[:3]
# UID prefix provided by https://www.medicalconnections.co.uk/Free_UID
# Encoded as UI, maximum 64 characters
PYNETDICOM_UID_PREFIX = "1.2.826.0.1.3680043.9.381... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# bachelor-thesis documentation build configuration file, created by
# sphinx-quickstart on Sun Jun 28 20:18:55 2015.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in thi... |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 12 15:45:29 2020
@author: Francesco Conforte
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import sub.minimization as mymin
plt.close('all')
x=pd.read_csv("data/parkinsons_updrs.csv") # read the dataset; xx is a dataframe
x.describe().T # gi... |
# %%
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options # for suppressing the browser
from selenium import webdriver
import warnings
from bs4 import B... |
from django.db import models
class repairOrder(models.Model):
begintime = models.DateField(auto_now_add=True, verbose_name="开始时间")
state = models.BooleanField(verbose_name="完成结果",default=False)
worker = models.ForeignKey("login.User",on_delete=models.CASCADE,related_name='worker',verbose_name="对应工人",defaul... |
import sys
if "" not in sys.path: sys.path.append("")
if "src" not in sys.path: sys.path.append("src")
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class Window(QMainWindow):
def __init__(self):
super().__init__()
# setting title
self.setWindowTitle(... |
from abc import ABC, abstractmethod
class AuthTypeBase(ABC):
"""Base type for all authentication types."""
def __init__(self):
super().__init__()
@abstractmethod
def is_valid_authentication_type(self):
"""Return True if the auth type is valid, e.g. it can return userinfo and username... |
import unittest
import os
import threading
from test.support import EnvironmentVarGuard
from urllib.parse import urlparse
from http.server import BaseHTTPRequestHandler, HTTPServer
from google.cloud import bigquery
from google.auth.exceptions import DefaultCredentialsError
from kaggle_gcp import KaggleKernelCredentia... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
# -*- coding: UTF-8 -*-
# File Name:ada_boost_tf
# Author : Chen Quan
# Date:2019/2/18
# Description : Use TensorFlow to implement AdaBoost Algorithm.
__author__ = 'Chen Quan'
"""
暂未实现
"""
|
"""Tests for algorithms for computing symbolic roots of polynomials. """
from sympy import (S, symbols, Symbol, Wild, Integer, Rational, sqrt,
powsimp, Lambda, sin, cos, pi, I, Interval, re, im, exp, ZZ, Piecewise,
acos, default_sort_key, root)
from sympy.polys import (Poly, cyclotomic_poly, intervals, nroots... |
"""
Tests of printing functionality
"""
from __future__ import absolute_import, print_function, division
import logging
from nose.plugins.skip import SkipTest
import numpy as np
from six.moves import StringIO
import theano
import theano.tensor as tensor
from theano.printing import min_informative_str, debugprint
... |
# -*- coding: latin1 -*-
from __future__ import print_function
"""
.. currentmodule:: pylayers.antprop.rays
.. autosummary::
:members:
"""
import doctest
import os
import sys
import glob
try:
# from tvtk.api import tvtk
# from mayavi.sources.vtk_data_source import VTKDataSource
from mayavi import mlab
e... |
from SPI.BaseTest import SPIBaseTest
class PySysTest(SPIBaseTest):
def execute(self):
self.start()
self.correlator.injectMonitorscript(filenames=['tutorial.mon'])
self.correlator.sendEventStrings('Step(1)')
print "Waiting for rising edge on pin 19"
channel = self.waitForEdge(19, False)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.