content
stringlengths
0
894k
type
stringclasses
2 values
def palindrome(number): return number == number[::-1] if __name__ == '__main__': init = int(input()) number = init + 1 while not palindrome(str(number)): number += 1 print(number - init)
python
import unittest from bdflib import reader import charset class JISTest(unittest.TestCase): def test_jis(self): with open('bdf/jiskan24-2003-1.bdf', 'rb') as f: bdf = reader.read_bdf(f) cconv = charset.JIS() single_cp = 0 multi_cp = 0 for cp in bdf.codepoints(...
python
""" This is the main program file for the DDASM assembler. It will read a DDA program file and convert it to a VHDL \ description of a ROM file. This ROM file serves as the program memory for the LDD mark II processor. DDASM = Digital Design Assmebly LDD = Lab Digital Design Digital Design refers to the Digital Design ...
python
# 短信验证码 过期时间 SMS_CODE_EXPIRETIME = 300 # 手机号码在redis中的过期时间,解决短时间内 向同一手机号重复发送短信 的问题 MOBILE_EXPIRETIME = 60 # 标识某一属性在 redis 中的使用次数,解决类似于抽奖次数的问题 MOBILE_FREQUENCY = 1
python
import os import threading from cheroot import wsgi from wsgidav.wsgidav_app import WsgiDAVApp from powerhub.directories import WEBDAV_RO, WEBDAV_BLACKHOLE, \ UPLOAD_DIR, WEBDAV_DIR from powerhub.args import args import time from watchdog.observers import Observer from watchdog.events import FileSystemEventHand...
python
#!/usr/bin/env python3 import os import time import subprocess import shutil import datetime import tempfile def main(): TMPROOT = r'/Volumes/RAM Disk' REPO = r"/Volumes/RAM Disk/redis/" SIT_BIN = r"/Users/abcdabcd987/Developer/sit/bin/sit" report = open('stress_test_%s.csv' % datetime.datetime.today()...
python
# ##################################################################################################################### # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # # ...
python
from vstutils.models import BQuerySet, BModel, Manager, models class HostQuerySet(BQuerySet): def test_filter(self): return self.filter(name__startswith='test_') class Host(BModel): objects = Manager.from_queryset(HostQuerySet)() name = models.CharField(max_length=1024) class HostGroup(BModel)...
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import mptt.fields class Migration(migrations.Migration): dependencies = [ ('publication_backbone', '0006_auto_20160224_1345'), ('fluent_contents', '0001_initial'), ] operations = [ ...
python
import time import pygame from pygame.locals import * # The individual event object that is returned # This serves as a proxy to pygame's event object # and the key field is one of the strings in the button list listed below # in the InputManager's constructor # This comment is actually longer than the class defin...
python
from interface import GameWindow from PyQt5.QtWidgets import QApplication import sys if __name__ == "__main__": app = QApplication(sys.argv) demo = GameWindow() demo.update() demo.showMaximized() sys.exit(app.exec_())
python
# Okta intel module - Group import json import logging from typing import Dict from typing import List from typing import Tuple import neo4j from okta.framework.ApiClient import ApiClient from okta.framework.OktaError import OktaError from okta.framework.PagedResults import PagedResults from okta.models.usergroup impo...
python
import time import requests from models.states import OrderSide class DeribitExchangeInterface: def __init__(self, key, secret, base_url, api_url, instrument): self.key = key self.secret = secret self.base_url = base_url self.api_url = api_url self.url = base_url + api_url ...
python
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation DT = 0.01 FRAMERATE = 60 N_ROWS = 64 SECONDS = 10 def read_field_file(file_path, type): if type != 'scalar' and type != 'vector': raise ValueError('type must be scalar or vector') file_str = open(file_path, 'r...
python
import requests from abc import ABC, abstractmethod from collections import OrderedDict from coronacli.config import OWID_DATA_URL class BaseScraper(ABC): """ Abstract scraper class defining common functionality among all scrapers and abstract methods to implement """ def __init__(self): super().__...
python
from __future__ import print_function import collections import os os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # The GPU id to use, usually either "0" or "1" os.environ["CUDA_VISIBLE_DEVICES"]="3" import tensorflow as tf from keras.models import Sequential, load_model from keras.utils import multi_gpu_model from kera...
python
from gym_trading.envs.trading_env import TradingEnv from gym_trading.envs.Testing_Env import TestingEnv
python
import unittest import numpy as np from materialscoord.einstein_crystal_perturbation import perturb_einstein_crystal from pymatgen.core.structure import Structure class EinsteinTest(unittest.TestCase): """Test einstein perturbation functionality.""" def test_perturb(self): # basic test to check str...
python
class Config(object): DEBUG = False TESTING = False class DevConfig(Config): DEBUG = False
python
class MyPolynomialDecay: """ Class to define a Polynomial Decay for the learning rate """ def __init__(self, max_epochs=100, init_lr=1e-3, power=1.0): """ Class constructor. :param max_epochs (int): Max number of epochs :param init_lr (float): Initial Learning Rate ...
python
import tensorflow as tf from niftynet.application.base_application import BaseApplication from niftynet.engine.application_factory import \ ApplicationNetFactory, InitializerFactory, OptimiserFactory from niftynet.engine.application_variables import \ CONSOLE, NETWORK_OUTPUT, TF_SUMMARIES from niftynet.engine....
python
import numpy as np import os import tensorflow as tf from tensorflow.contrib.framework import nest def loop_tf(loop_fn, inputs, persistent_initializer, transient_initializer, n=None, time_major=False): def create_tensor_array(initial_tensor: tf.Tensor): return tf.TensorArray(initial_tensor.dtype, size=n, ...
python
# import to namespace from .base import IRRBase # noqa from .native import IRRClient # noqa
python
# Generated by Django 3.1.1 on 2020-09-19 21:11 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Contact', fields=[ ('id', models.AutoField(...
python
import numpy as np import tensorflow as tf from .utils import * class Graph2Gauss: """ Implementation of the method proposed in the paper: 'Deep Gaussian Embedding of Graphs: Unsupervised Inductive Learning via Ranking' by Aleksandar Bojchevski and Stephan Günnemann, published at the 6th Internati...
python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the Licen...
python
from django.test import TestCase from django.contrib.auth import get_user_model from django.urls import reverse from rest_framework.test import APIClient from rest_framework import status from core.models import User from .utils import create_user CREATE_USER_URL = reverse('api:user_create') ME_URL = reverse('api:u...
python
import os import shutil import sys import argparse import time import itertools import numpy as np import torch import torch.nn as nn import matplotlib.pyplot as plt import torch.optim as optim import torch.nn.functional as F from sklearn.metrics import confusion_matrix import scikitplot as skplt from torch.backends i...
python
from sh import gmkproject from sh import gchproject from sh import gchuser from sh import glusers from sh import gstatement from cloudmesh.accounting.AccountingBaseClass import AccountingBaseClass class GoldAccounting(AccountingBaseClass): """The gold accounting implementation class""" def project_usage(se...
python
from django.db import models from django.dispatch import receiver from django.db.models.signals import post_save from django.contrib.auth.models import User from rest_framework.authtoken.models import Token # Create your models here. @receiver(post_save, Sender = User) def create_auth_token(sender, instance=None, cre...
python
# This file is part of the GhostDriver project from Neustar inc. # # Copyright (c) 2012, Ivan De Marino <ivan.de.marino@gmail.com / detronizator@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions a...
python
# doit automatically picks up tasks as long as their unqualified name is prefixed with task_. # Read the guide: https://pydoit.org/tasks.html from dodos.action import * from dodos.behavior import * from dodos.benchbase import * from dodos.ci import * from dodos.forecast import * from dodos.noisepage import * from dodo...
python
C_CONST = 0.375 MC_ITERATION_COUNT = 100 D_MAX = 100
python
from typing import Tuple from NewDeclarationInQueue.processfiles.customprocess.search_lines_in_pages import SearchLinesInPage from NewDeclarationInQueue.processfiles.customprocess.search_text_line_parameter import SearchTextLineParameter from NewDeclarationInQueue.processfiles.process_messages import ProcessMessages...
python
# Generated from Mu.g4 by ANTLR 4.7.1 # encoding: utf-8 from antlr4 import * from io import StringIO from typing.io import TextIO import sys def serializedATN(): with StringIO() as buf: buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3&") buf.write("\u0082\4\2\t\2\4\3\t\3\4\4\t\4\4\5\...
python
import numpy as np from tensorflow.examples.tutorials.mnist import input_data import json with open('config.json') as config_file: config = json.load(config_file) k = config['k'] codes_path = config['codes_path'] codes = [] for i in range(k): codes.append([float(i)/(k-1)*255]) codes = np.array(codes) print('#...
python
# Check dla a module w a set of extension directories. # An extension directory should contain a Setup file # oraz one albo more .o files albo a lib.a file. zaimportuj os zaimportuj parsesetup def checkextensions(unknown, extensions): files = [] modules = [] edict = {} dla e w extensions: setu...
python
"""A basic focus script for slitviewers (changes will be required for gcam and instruments). Subclass for more functionality. Take a series of exposures at different focus positions to estimate best focus. Note: - The script runs in two phases: 1) If a slitviewer: Move the boresight and take an exposure. T...
python
passages = { 'The Money Beat (Drumming)' : """Let me tell you how you can play the money beat on your drums. To get this beat going start with one part at a time. This way you can part your mind, and feel the groove a lot better. With you hi hat, play constant eight notes. We will add in some accents in the future,...
python
from django.db import models from django.contrib.auth.models import AbstractUser from django_countries.fields import CountryField # Create your models here. class Degree(models.Model): degree_id = models.CharField(max_length=9, verbose_name='Degree ID', primary_key=True) degree = models.CharField(max_length=20...
python
from setuptools import setup import os def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="fastly-python", version="1.0.4", author="Chris Zacharias", author_email="chris@imgix.com", description=("A Python client libary for the Fastly API."), license="BSD", keywords...
python
#!/usr/bin/env python3 """Utility class for logging. This class is a wrapper around the original logging module :py:mod:`logging` and can be used to apply the `panda_autograsp <https://github.com/rickstaa/panda_autograsp>`_ formatters, filters and handlers to the logging object. """ # Make script both python2 and pyth...
python
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import...
python
"""Test AdsConnection class. :author: Stefan Lehmann <stlm@posteo.de> :license: MIT, see license file or https://opensource.org/licenses/MIT :created on: 2018-06-11 18:15:58 """ import time import unittest import pyads import struct from pyads.testserver import AdsTestServer, AmsPacket from pyads import constants fr...
python
# coding: utf-8 """ Unit tests for the args module. """ import argparse from datetime import datetime import pytest from ..src.args import parse_date, parse_args, parse_file_arg def test_parse_date_invalid(): """Ensure that invalid dates fail to parse.""" with pytest.raises(argparse.ArgumentTypeError, match...
python
from vk_bot.core.modules.basicplug import BasicPlug class Texttobits(BasicPlug): doc = "Зашифровать сообщение в бинарный код" command = ("бинарный0",) def main(self): text = ' '.join(self.text[1:]) bits = bin(int.from_bytes(text.encode('utf-8', 'surrogatepass'), 'big'))[2:] encode = ...
python
import torch import numpy as np class ReplayBuffer(object): def __init__(self, buffer_mem, num_states, num_actions): self.switch = 0 self.buffer_mem = buffer_mem self.count_mem = 0 self.num_states = num_states self.num_actions = num_actions self.state = t...
python
import torch import torch.nn as nn import torch.nn.functional as F import zipfile import numpy as np class BaseModel(nn.Module): def __init__(self, args, vocab, tag_size): super(BaseModel, self).__init__() self.args = args self.vocab = vocab self.tag_size = tag_size def save(se...
python
# -*- coding: utf-8 -*- """ Created on Mon Nov 25 18:28:27 2019 @author: Arthur """ pass
python
from .preprocess import * from . import preprocess_utils from .epipolarloss import * from .kploss import *
python
import csv import sys import urllib3 as ulib import pandas as pd import datetime from bs4 import BeautifulSoup as bs ulib.disable_warnings() try: #Create csv file only with column headers columnNames = ['CompanyName','Year','Ergebnis je Aktie (unverwaessert, nach Steuern)','Ergebnis je Aktie (verwaessert, nach...
python
import os import numpy as np import argparse from sklearn.model_selection import StratifiedKFold #from data.image_folder import make_dataset #from tensorflow.keras.preprocessing.image import ImageDataGenerator import tensorflow as tf import json import pandas as pd import numpy as np import os, sys import glob import...
python
# Return some system information # Because the universe will never have enough scripts that do this # It's only going to work on fairly recent *NIX platforms import os, socket uname_ = os.uname() system = uname_[0] host = socket.gethostname() kernel = uname_[2] release = uname_[3] processor = uname_[4]
python
## Copyright 2004-2007 Virtutech AB ## ## The contents herein are Source Code which are a subset of Licensed ## Software pursuant to the terms of the Virtutech Simics Software ## License Agreement (the "Agreement"), and are being distributed under ## the Agreement. You should have received a copy of the Agreem...
python
import numpy as np from sklearn.ensemble import RandomForestRegressor from sklearn.externals import joblib sgids = joblib.load('sgids.pkl') sgdiv = joblib.load('data/sg_div_tr_ns.pkl') params = joblib.load('params.pkl') dt = dict.fromkeys(sgids) sgid = sgids[0] for i, sgid in enumerate(sgids): print(f'{sgid} ({i...
python
#-*-coding utf-8 -*- #Affine Transformation import numpy as np import cv2 from matplotlib import pyplot as plt img=cv2.imread('resimler/sudoku.png') rows,cols,ch=img.shape pts1 = np.float32([[50,50],[200,50],[50,200]]) pts2=np.float32([[10,100],[200,50],[100,250]]) M = cv2.getAffineTransform(pts1,pts2) ...
python
# /usr/bin/env python3 # -*- coding: utf-8 -*- """ This file contains the implementation to the HTTP server that serves the web API for the Serial port. """ import logging import threading import typing as t import flask import flask_restful import waitress from flask_cors import CORS from . import connection # fo...
python
""" Version information for PyBioMed, created during installation. Do not add this file to the repository. """ import datetime version = '1.0' date = 'Nov 7 9:17:16 2016' dev = False # Format: (name, major, min, revision) version_info = ('PyBioMed', '1', '0', None) # Format: a 'datetime.datetime' instance date_i...
python
#!/usr/bin/python # -*- coding: UTF-8 -*- import requests import os import zipfile import urllib import dirconfig import logging from autobuild import autobuild,git_pull import commands import os from githubdownload import GithubDownload from repositories import repositories from ziptool import ZipTool logging.basi...
python
""" Unit test for LocalProcessMemoryConsumption measurement. """ import os import time import pytest import threading import subprocess from mlte._private.platform import is_windows, is_nix from mlte.measurement.memory import LocalProcessMemoryConsumption from mlte.measurement.memory.local_process_memory_consumption ...
python
from .emonet import EmoNetPredictor __version__ = '0.1.0'
python
"""Utilities for building command-line interfaces for your daemons""" import inspect from functools import wraps import click from .core import Daemon from .helpers import MultiDaemon def _parse_cli_options(func): """Parse click options from a function signature""" options = [] for param in inspect.sig...
python
"""This module provide multiple test of ingestion services""" import logging from conftest import ValueStorage import time from server_automation.configuration import config from server_automation.functions import executors from server_automation.postgress import postgress_adapter _log = logging.getLogger("server_auto...
python
import jax from absl import app from absl import flags flags.DEFINE_string('server_addr', '', help='server ip addr') flags.DEFINE_integer('num_hosts', 1, help='num of hosts' ) flags.DEFINE_integer('host_idx', 0, help='index of current host' ) FLAGS = flags.FLAGS def main(argv): jax.distributed.initialize(FLAGS.ser...
python
""" This script prepares the files that populate the databases, such as adding headers to them and removing a couple of noun phrases that do not belong there. """ def prepare_data(file): """ Prepares the argument file for SQL insertion """ with open(file, 'r', encoding='utf-8') as infile: inf...
python
# # This file is part of Brazil Data Cube Validation Tools. # Copyright (C) 2020 INPE. # # Python Native import os import time import sys # 3rdparty import gdal import numpy as np def diff_sum_abs(image_path1,image_path2, output_folder): ''' documentar para sair automaticamente ''' # get o stk de banda...
python
from django import forms class LoginForm(forms.Form): email = forms.EmailField(required = True, error_messages = {"required": "邮箱不能为空"}) password = forms.CharField(required = True, min_length = 6, max_length = 20, error_messages={ "min_length": "密码应该大于等于6个字符", "max_length": "密码应该小于等于20个字符", }) class Registe...
python
''' This code is for head detection for PAN. ''' import torch import torch.nn as nn import math __all__ = ['PA_Head'] class PA_Head(nn.Module): def __init__(self, in_channels, hidden_dim, num_classes): super(PA_Head, self).__init__() self.conv1 = nn.Conv2d(in_channels, hidden_dim, kernel_size=3, s...
python
#!/usr/bin/python # -*- coding: UTF-8 -*- # # Copyright 2011 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...
python
import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = "0xdeadbeefdeadbeef" DEBUG = True INSTALLED_APPS = [ "django_jsonfield_backport", "tests", ] DATABASES = { "default": { "ENGINE": "django.db.backends.%s" % os.getenv("DB_BACKEND"), "NAME": os.get...
python
# Given a linked list which might contain a loop, implement an algorithm that returns the node at the beginning of the loop (if one exists) from utils import Node first_node = Node(1) second_node = Node(2) third_node = Node(3) fourth_node = Node(4) fifth_node = Node(5) sixth_node = Node(6) # Visual [1, 2, 3, 4, 5, ...
python
#!/usr/bin/env python # Plots Sigmoid vs. Probit. import matplotlib.pyplot as pl import numpy as np from scipy.special import expit from scipy.stats import norm x = np.arange(-6, 6, 0.1) l = np.sqrt(np.pi/8); pl.plot(x, expit(x), 'r-', label='sigmoid') pl.plot(x, norm.cdf(l*x), 'b--', label='probit') pl.axis([-6, ...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys from PySide6 import QtCore, QtWidgets class MyWidget(QtWidgets.QWidget): def __init__(self): super().__init__() self.text = QtWidgets.QLabel("Hello World", alignment=QtCore.Qt.AlignCenter) self.layout = QtWidgets.QVBoxLayout(self)...
python
# Author: Bohua Zhan import unittest from kernel.type import boolT, TVar, TFun from kernel.term import Term, Var from kernel.thm import Thm from kernel.proof import ProofItem from logic.proofterm import ProofTerm, ProofTermAtom from logic import basic from logic.logic import conj, disj, mk_if from logic.nat import na...
python
# -*- coding: utf-8 -*- # # 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 requir...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 27 18:11:58 2021 @author: TSAI, TUNG-CHEN @update: 2021/10/05 """ import numpy as np from .nn import get_network from .utils import get_inputs, print_prediction # ============================================================================= # # =...
python
"""Mock callback module to support device and state testing.""" import logging _LOGGER = logging.getLogger(__name__) # pylint: disable=unused-argument # pylint: disable=too-many-instance-attributes class MockCallbacks(): """Mock callback class to support device and state testing.""" def __init__(self): ...
python
# This file will grab the hashes from the file generation and compare them to # hashes gotten from user-given files. Can return positive (files that do match) # or negative (files that don't match) hash results import argparse import os import sys from file_object import FileObject def log_and_print(log_file...
python
''' Get the hottest news title on baidu page, then save these data into mysql ''' import datetime import pymysql from pyquery import PyQuery as pq import requests from requests.exceptions import ConnectionError URL = 'https://www.baidu.com/s?wd=%E7%83%AD%E7%82%B9' headers = { 'User-Agent':'Mozilla/5.0 (Windows NT...
python
'''1. 游戏编程:按以下要求定义一个乌龟类和鱼类并尝试编写游戏。 (初学者不一定可以完整实现,但请务必先自己动手,你会从中学习到很多知识的^_^) 假设游戏场景为范围(x, y)为0<=x<=10,0<=y<=10 游戏生成1只乌龟和10条鱼 它们的移动方向均随机 乌龟的最大移动能力是2(Ta可以随机选择1还是2移动),鱼儿的最大移动能力是1 当移动到场景边缘,自动向反方向移动 乌龟初始化体力为100(上限) 乌龟每移动一次,体力消耗1 当乌龟和鱼坐标重叠,乌龟吃掉鱼,乌龟体力增加20 鱼暂不计算体力 当乌龟体力值为0(挂掉)或者鱼儿的数量为0游戏结束 ''' import random...
python
salario = float(input('Qual é o salário do Funcionário? R$')) aumentoSalario = salario + (salario * (5 / 100)) print(f'Um funcionário que ganhava R${salario:.2f}, com 15% de aumento, passa a receber R${aumentoSalario:.2f}')
python
import bs4 # type: ignore[import] from .activity import _parse_subtitles, _parse_caption, _is_location_api_link # bring into scope from .comment import test_parse_html_comment_file # noqa: F401 from .html_time_utils import test_parse_dt # noqa: F401 def bs4_div(html: str) -> bs4.element.Tag: tag = bs4.Beauti...
python
from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import import unittest import pytest from builtins import open from future import standard_library #standard_library.install_aliases() from builtins import * from freezegun imp...
python
from PIL import ImageGrab from PIL import BmpImagePlugin from aip import AipOcr from win10toast import ToastNotifier import sys, os import keyboard import time, datetime import random from os import path from multiprocessing.dummy import Pool as ThreadPool PIC_DIR = r"C:\Users\hytian3019\Pictures\ocr" #百度云账号设置 APP_...
python
""" targetstateinfidelity.py - This module defines a cost function that penalizes the infidelity of an evolved state and a target state. """ import autograd.numpy as anp import numpy as np from qoc.models import Cost from qoc.standard.functions import conjugate_transpose class TargetStateInfidelity(Cost): """ ...
python
#Micro codes for checking the Pandas # Read CSV in chunks data_read = pd.read_csv('Filename.csv',chunksize=x,encoding = "any encoding format for eg :ISO-8859-1") data = pd.concat(data_read,ignore_index=True) # Split the dataframe based on the numeric and categorical values # Numeric Split clean...
python
import numpy as np import tensorflow as tf class Weights: def __init__(self, initializer, depth): self.initializer = initializer self.depth = depth def __call__(self, num_inputs, num_outputs): x = tf.Variable(self.initializer(shape=(num_inputs, self.depth))) y = tf.Variable(...
python
#!/usr/bin/env python3 # ============================================================================================= # # Distributed dynamic map fusion via federated learning for intelligent networked vehicles, # # 2021 International Conference on Robotics and Automation (ICRA) # # ...
python
import argparse import csv import torch import torch.nn as nn import torch.nn.functional as F #from models.gatedconv import InpaintGCNet, InpaintDirciminator from models.sa_gan import InpaintSANet, InpaintSADirciminator from models.loss import SNDisLoss, SNGenLoss, ReconLoss from data.inpaint_dataset import InpaintData...
python
from flask import Flask,jsonify,request from flask_sqlalchemy import SQLAlchemy from sqlalchemy import Column,Integer,Float,String import os from flask_marshmallow import Marshmallow from flask_jwt_extended import JWTManager,jwt_required,create_access_token from flask_mail import Mail,Message app=Flask(__name__) based...
python
# -*- coding: utf-8 -*- import numpy as np from math import factorial, exp, trunc from linear_congruential_generator import LinearCongruentialGenerator lcg = LinearCongruentialGenerator() def poisson(lambda_value, random_number): return round(((lambda_value ** random_number) * (np.e ** (-lambda_value))) / factor...
python
import rclpy from rclpy.node import Node import numpy as np from .handeye_4dof import Calibrator4DOF, robot_pose_selector from .handeye_4dof import transformations as tf from geometry_msgs.msg import PoseArray from geometry_msgs.msg import Pose from std_srvs.srv import Empty from ament_index_python.packages import g...
python
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). # You may not use this file except in compliance with the License. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in ...
python
from __future__ import unicode_literals import os import json from functools import wraps from datetime import datetime, date from contextlib import contextmanager from threading import RLock, Condition, current_thread from collections import Sized, Iterable, Mapping, defaultdict def is_listy(x): """ returns ...
python
""" Copyright (c) 2020 COTOBA DESIGN, Inc. 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 to use, copy, modify, merge, publish, distri...
python
from dataclasses import dataclass, field import backtrader as bt from models.Analyzers.CustomReturns import CustomReturns_analyzer from models.Analyzers.ReturnsVolatility import ReturnsVolatility_analyzer from models.Analyzers.TradesInfo import TradesInfo_analyzer from models.Analyzers.CalmarRatio import CalmarRatio_a...
python
def unorder_search(item, items: list): if not isinstance(items, list): print(f'The items {items} MUST be of type list') return for i in range(0, len(items)): if item == items[i]: return i return None data = [87, 47, 23, 53, 20, 56, 6, 19, 8, 41] print(unorder_search...
python
# -*- coding: utf-8 -*- import re from xkeysnail.transform import * define_keymap(lambda wm_class: wm_class != 'Gnome-terminal', { K('LSuper-V'): K('C-V'), K('LSuper-X'): K('C-X'), K('LSuper-C'): K('C-C'), K('LSuper-A'): K('C-A') }, 'non-terminal') define_keymap(re.compile('Gnome-terminal'), { K(...
python
# -*- coding: utf-8 -*- """ Created on Thu Apr 2 14:24:56 2020 @author: rucha """ import pandas as pd import numpy as np from sklearn.naive_bayes import MultinomialNB from sklearn.model_selection import train_test_split, cross_val_score from sklearn.metrics import confusion_matrix, accuracy_score, classification_rep...
python
from django.contrib import admin from django import forms from django.db import models from django.utils.translation import ugettext as _ from medicament.models import * class GroupAdmin(admin.ModelAdmin): fieldsets = [(None, {'fields': ['name', 'adverse_reaction']})] list_display = ('name', 'adverse_reactio...
python