content
stringlengths
0
894k
type
stringclasses
2 values
# Parent Class class Shape: sname = "Shape" def getName(self): return self.sname # child class class XShape(Shape): # initializer def __init__(self, name): self.xsname = name def getName(self): # overriden method return (super().getName() + ", " + self.xsname) circle =...
python
# encoding: utf8 from __future__ import print_function, unicode_literals from io import BytesIO import re from unicodedata import combining, normalize from aspen.resources.pagination import parse_specline, split_and_escape from aspen.utils import utcnow from babel.core import LOCALE_ALIASES from babel.dates import fo...
python
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import unittest from vissl.utils.hydra_config import compose_hydra_configuration, convert_to_attrdict from vissl.utils.test_utils import ( ...
python
#!/usr/bin/env python3 # coding:utf-8 def fib(n): yield 0 x, y = 0, 1 yield x for i in range(n-1): x, y = y, x + y yield x ''' fib() 可以简化 简化 1 def fib(n): x, y = 0, 1 for i in range(n): yield x x, y = y, x + y 简化 2 def fib(n): x, y = 0, 1 for i in range(...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Copyright (c) 2013 Qin Xuye <qin@qinxuye.me> 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
import matplotlib.pyplot as plt import tensorflow as tf import keras as keras def print_elapsed_time(total_time): ''' Prints elapsed time in hh:mm:ss format ''' hh = int(total_time / 3600) mm = int((total_time % 3600) / 60) ss = int((total_time % 3600) % 60) print( "\n** Total Elapsed ...
python
#!/usr/bin/env python # encoding: utf-8 import re import sys import gzip import pysam #import itertools import mimetypes from collections import OrderedDict #,defaultdict class VCF(object): """docstring for VCF""" def __init__(self, input, output=None, popu...
python
""" Создать класс Car. Атрибуты: марка, модель, год выпуска, скорость (по умолчанию 0). Методы: увеличить скорости (скорость +5), уменьшение скорости (скорость -5), стоп (сброс скорости на 0), отображение скорости, задния ход (изменение знака скорости). """ class Car: def __init__(self, brand, model, year, speed)...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import sys import importlib import itertools from string import Formatter from adapt.intent import IntentBuilder from adapt.engine import DomainIntentDeterminationEngine from padatious import IntentContainer from padatious.util import expand_parentheses clas...
python
""" This is companion code to Project 4 for CSEP576au21 (https://courses.cs.washington.edu/courses/csep576/21au/) Instructor: Vitaly Ablavsky """ # ====================================================================== # Copyright 2021 Vitaly Ablavsky https://corvidim.net/ablavsky/ # # Permission is hereby granted, f...
python
# Mikaela Uy (mikacuy@cs.stanford.edu) import argparse import os import sys import torch import torch.nn as nn import torch.nn.functional as F import datetime import time import sys import importlib import shutil import numpy as np BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(BASE_DIR) # model...
python
# Generated by Django 3.0.4 on 2020-04-22 13:38 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tutors', '0007_auto_20200416_1433'), ] operations = [ migrations.AddField( model_name='postanad', name='views', ...
python
import configparser import os config = configparser.ConfigParser() config.read(os.path.join(os.path.dirname(__file__), '../config.ini')) STEAM_ACCOUNT = config['steam']['account_name'] STEAM_PASSWORD = config['steam']['password'] driver_path = config['selenium']['driver_path'] if config['selenium']['driver_path'].st...
python
# Author: Guilherme Aldeia # Contact: guilherme.aldeia@ufabc.edu.br # Version: 1.0.0 # Last modified: 05-29-2021 by Guilherme Aldeia r"""Interaction Transformation Evolutionary Algorithm for **regression** This sub-module implements a specialization of the base classes ``BaseITEA`` and ``BaseITExpr`` to be...
python
from Tkinter import * from tkMessageBox import * def komunikaty(): if askyesno('Podaj odpowiedz!', u'Czy wiesz co robisz?'): showwarning('Tak', u'Jak widze wiesz co robisz.') else: showinfo('Nie', 'Nie przejmuj sie, nie ty jeden.') Button(text=u'Koniec', command=komunikaty).pack(fill=X) Button(text=u'Blad', co...
python
import json from typing import TYPE_CHECKING from django.urls import reverse from telegram import Bot as TelegramBot, Update from telegram.ext import Updater from ..dispatcher.setup import setup_dispatcher if TYPE_CHECKING: from django.http import HttpRequest from telegram.ext import Dispatcher from ..mo...
python
import os import xml.etree.ElementTree as ET from shutil import copyfile import paths def get_all_laws(): counter=0 wrd = "".join(os.getcwd()) laws_dir=wrd+"\\akn" for root,subFolder,files in os.walk(wrd): for item in files: if(item.endswith("main.xml")): dst = wrd +...
python
# Licensed to the Apache Software Foundation (ASF) 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 u...
python
from typing import Union, List, Tuple, Callable, Dict, Optional import numpy as np from medsearch.models.base import TorchModelBase from medsearch.models.utils import cosine_similarity from medsearch.datasets.dataset import SemanticCorpusDataset from sentence_transformers import SentenceTransformer class SentenceTran...
python
from itertools import product import numpy as np from astropy import units as u from astropy.io import fits from astropy.table import Table from astropy.visualization import quantity_support from scipy.ndimage.measurements import label as ndi_label from gammapy.extern.skimage import block_reduce from gammapy.utils.inte...
python
from .shi import Shi from .ni import Ni from .mi import Mi from .i import I from ._diacritic import Ji __all__ = [ "Shi", "Ni", "Mi", "I", "Ji", ]
python
from fido2.ctap1 import ApduError from yubikit.core import TRANSPORT from yubikit.management import CAPABILITY from yubikit.core.smartcard import SW from ykman.fido import fips_change_pin, fips_verify_pin, fips_reset, is_in_fips_mode from . import condition import pytest @pytest.fixture(autouse=True) @condition.fips...
python
import random from utils import cosine_distance import numpy as np class IterativeCondensedNN: def __init__(self): self.y_index = {} def fit(self, X_train,y): for idx, observation in enumerate(X_train): self.y_index[observation.tostring()] = idx samples = [] _r...
python
import autograd.numpy as np from autograd.scipy.special import gammaln def sigmoid(a): return 1. / (1. + np.exp(-a)) def logit(a): return np.log(a) - np.log(1-a) def mvn_diag_logpdf(x, mean, log_std): D = len(mean) qterm = -.5 * np.sum((x - mean)**2 / np.exp(2.*log_std), axis=1) coef = -.5*D *...
python
from bs4 import BeautifulSoup import urllib.request import csv web_page = urllib.request.urlopen('https://en.wikipedia.org/wiki/List_of_Super_Bowl_champions') soup = BeautifulSoup(web_page, "html.parser") super_bowl_table = soup.find_all('table', {'class': 'wikitable'})[1] in_file = open("result.csv", 'w') csv_writer...
python
import factory from app.utils import db from app.models.category import Category from factories.department_factory import DepartmentFactory class CategoryFactory(factory.alchemy.SQLAlchemyModelFactory): class Meta: model = Category sqlalchemy_session = db.session category_id = factory.Sequenc...
python
game_logic = True winner = None curr_player = "X" board = [["-","-","-"], ["-","-","-"], ["-","-","-"]] def compTurn(): bestScore = -999 move = None for x in range(3): for y in range(3): if board[x][y] == "-": board[x][y] = "O" score = min...
python
class task_status: """ Descriptive backend task processing codes, for readability. """ SCHEDULED = 0 PROCESSING = 1 FINISHED = 4 FAILED = -1 CANCELLED = 9 EXPIRED = 8 # only for ResultsPackage WAITING_FOR_INPUT = 2 # only for RunJob RETRYING = 11 # only for WorkflowRun ...
python
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name = "taxon_parser", version = "0.2.3", author = "Augustin Roche", author_email = "aroche@photoherbarium.fr", description = "A library to parse taxon names into elementary compon...
python
import logging from urllib.parse import urlparse import prometheus_client import requests import six from bs4 import BeautifulSoup as bs if six.PY3: from json import JSONDecodeError else: from simplejson import JSONDecodeError logger = logging.getLogger(__name__) class DataFetcher(object): def __ini...
python
import json import requests from fabric.colors import red def publish_deploy_event(name, component, environment): url = environment.fab_settings_config.deploy_event_url if not url: return token = environment.get_secret("deploy_event_token") if not token: print(red(f"skipping {name} ev...
python
class Data: def __init__(self, data_dir="data/FB15k-237/", reverse=False): self.train_data = self.load_data(data_dir, "train", reverse=reverse) self.valid_data = self.load_data(data_dir, "valid", reverse=reverse) self.test_data = self.load_data(data_dir, "test", reverse=reverse) ...
python
import os import yaml from google.cloud import storage from google.oauth2 import service_account from .storage import Storage class GcsStorage(Storage): def __init__(self, bucket, path, project=None, json_path=None): if bucket is None: raise ValueError('Bucket must be supplied to GCS storage...
python
from django.shortcuts import render from rest_framework.decorators import api_view from django.http import JsonResponse import json from .models import Wine from .serializers import WineSerializer from .constants import PAGE_SIZE # Create your views here. @api_view(["GET"]) def wines(request): pageParam = int(requ...
python
# Copyright 2020 kubeflow.org. # # 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,...
python
# Api view of grades from home.models import Grade # from Serializers.GradeSerializer import FlatGradeSerializer from api.services import handelFileSubmit, sendEmail, createTmpFile, getUserGrades from rest_framework import viewsets from rest_framework.response import Response from rest_framework.decorators impo...
python
#!/usr/bin/env python3 import os import sys import time sys.path.append(os.getcwd()+'/CPDP') sys.path.append(os.getcwd()+'/JinEnv') sys.path.append(os.getcwd()+'/lib') import copy import time import json import numpy as np import transforms3d from dataclasses import dataclass, field from QuadPara import QuadPara from Q...
python
""" https://adventofcode.com/2020/day/2 """ from collections import namedtuple import logging logger = logging.getLogger(__name__) Rule = namedtuple("Rule", ["letter", "f_pos", "s_pos"]) def check_password(rule, password): f_letter = password[rule.f_pos - 1] s_letter = password[rule.s_pos - 1] return ...
python
# #!/usr/bin/env python ################################################################ ## contains code relevant to updating simulation ## e.g. physics, integration ################################################################ from local.particle import * # step particle simulation def simStep(particles, k, d...
python
#!/usr/bin/env python # This script counts the number of PAM import regex as re import sys data_infile = sys.argv[1] # add 3 to account for PAM nt_overlap_threshold = int(sys.argv[2]) + 3 PAM_plus = re.compile(r'[ACTG]GG') PAM_minus = re.compile(r'CC[ACTG]') with open(data_infile, 'r') as infile: for line in in...
python
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import argparse import json import itertools import sys parser = argparse.ArgumentParser(description='Check interop reports.') parser.add_argument('--required', type=str) parser.add_argument('--regressions') p...
python
#! /usr/bin/env python """Give a string-oriented API to the generic "diff" module. The "diff" module is very powerful but practically useless on its own. The "search" and "empty_master" functions below resolve this problem.""" ################################################################################ __author_...
python
from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth from django.contrib import messages from django.contrib.auth.decorators import login_required from content.models import BlogPost, Category from .models import Profile, Contact def register(request): if request.method =...
python
#!/usr/bin/env python3 import argparse import base64 import sys import time import requests def main(): print("Starting Pelion requests") # command line parser = argparse.ArgumentParser(description="Pelion device interactions") parser.add_argument("-a", "--apikey", type=str, help="User api key") ...
python
from sklearn.cluster import KMeans, SpectralClustering, AffinityPropagation import numpy as np def clustering(X=None, model_name='KMeans', n_clusters=3, **param): if model_name == 'KMeans': # K均值 model = KMeans(n_clusters=n_clusters, **param) elif model_na...
python
from typing import List, Optional, Union from lnbits.helpers import urlsafe_short_hash from . import db from .models import createLnurldevice, lnurldevicepayment, lnurldevices ###############lnurldeviceS########################## async def create_lnurldevice( data: createLnurldevice, ) -> lnurldevices: lnu...
python
#!/usr/bin/python3 import bs4 import json import requests import http import re import pandas as pd from datetime import datetime import argparse import pathlib from enum import Enum MSG_LBL_BASE = '[PARSER]' MSG_LBL_INFO = f'{MSG_LBL_BASE}[INFO]' MSG_LBL_FAIL = f'{MSG_LBL_BASE}[FAIL]' def parse_args(): parser...
python
import cv2 import numpy as np # 直方图均衡 def hisEqulColor(img): ycrcb = cv2.cvtColor(img, cv2.COLOR_BGR2YCR_CB) channels = cv2.split(ycrcb) # print len(channels) cv2.equalizeHist(channels[0], channels[0]) cv2.merge(channels, ycrcb) cv2.cvtColor(ycrcb, cv2.COLOR_YCR_CB2BGR, img) return img # ...
python
#!/usr/bin/env python3 import argparse import subprocess import TEST_LOG import TEST_SETUP_IBOFOS import TEST def parse_arguments(args): parser = argparse.ArgumentParser(description='Test journal feature with SPO') parser.add_argument('-f', '--fabric_ip', default=TEST.traddr,\ help='Set target IP...
python
""" Primitive operations for 3x3 orthonormal and 4x4 homogeneous matrices. Python implementation by: Luis Fernando Lara Tobar and Peter Corke. Based on original Robotics Toolbox for Matlab code by Peter Corke. Permission to use and copy is granted provided that acknowledgement of the authors is made. @author: Luis Fe...
python
import matplotlib.pyplot as plt def plot(activity,lon,lat,lonsmooth,latsmooth) : fig = plt.figure(facecolor = '0.05') ax = plt.Axes(fig, [0., 0., 1., 1.], ) ax.set_aspect('equal') ax.set_axis_off() fig.add_axes(ax) #plt.plot(lonsmooth, latsmooth, '-', lon, lat, '.') #, xp, p(xp), '-') plt....
python
import argparse from bothub_nlp_rasa_utils.train import train_update as train from bothub_nlp_rasa_utils.evaluate_crossval import evaluate_crossval_update as evaluate_crossval import os if __name__ == '__main__': PARSER = argparse.ArgumentParser() # Input Arguments PARSER.add_argument( '...
python
from pathlib import Path import csv __all__ = ["text_writer", "str_file_read", "file_locate"] def str_file_read(file_path, encoding="utf-8"): """ Returns a file's contents as a string. Parameters ---------- file_path : str Path to GCA file to read encoding : str Encoding met...
python
import pytest from seqeval.scheme import (BILOU, IOB1, IOB2, IOBES, IOE1, IOE2, Entities, Entity, Prefix, Token, Tokens, auto_detect) def test_entity_repr(): data = (0, 0, 0, 0) entity = Entity(*data) assert str(data) == str(entity) @pytest.mark.parametrize( 'data1, data...
python
def model_snippet(): from pathlib import Path from multilevel_py.constraints import is_str_constraint, is_float_constraint, \ prop_constraint_ml_instance_of_th_order_functional from multilevel_py.core import create_clabject_prop, Clabject from multilevel_py.constraints import ReInitPropConstr ...
python
''' Parser for the ConstantsDumper variables. ''' import re from typing import Optional, Text from ..parser import Context, ParserBase from ..cpp.types import parse_value class ConstantsParser(ParserBase): ''' Parses the constants outputted by the ConstantsDumper clang plugin. ''' VALUE_MATCHER = r...
python
""" Author: Param Deshpande Date created: Fri Jul 10 23:48:41 IST 2020 Description: plots individual piecewise spline curves according to the timestamps in the splineCoeffs.txt License : ------------------------------------------------------------ "THE BEERWARE LICENSE" (Revision 42): Param Deshpande wrote t...
python
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # ----------------------------------------------------------------------------- # # P A G E B O T N A N O # # Copyright (c) 2020+ Buro Petr van Blokland + Claudia Mens # www.pagebot.io # Licensed under MIT conditions # # Supporting DrawBot, www.drawbot.com # ---...
python
def configure(conf): conf.env.ARCHITECTURE = 'mips64el' conf.env.VALID_ARCHITECTURES = ['mips64el', 'mipsel64'] conf.env.ARCH_FAMILY = 'mips' conf.env.ARCH_LP64 = True conf.env.append_unique('DEFINES', ['_MIPS', '_MIPS64', '_MIPSEL', '_MIPSEL64', '_MIPS64EL', '_LP64'])
python
# -*- python -*- # pymode:lint_ignore=E501 """Common settings and globals.""" from sys import path import os from django.contrib.messages import constants as message_constants from django.core.exceptions import ImproperlyConfigured from django.utils.translation import ugettext_lazy as _ from os.path import abspath, b...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Dynamic inventory script for ansible that works with ymir data. # See also: http://docs.ansible.com/ansible/intro_dynamic_inventory.html # import os from ymir import load_service_from_json YMIR_SERVICE_JSON = os.path.abspath( os.environ.get( 'YMIR_SERVICE_J...
python
from collections import namedtuple import subprocess import os import sys from test_cases import Test from utils import pipe_read class RedundancyTest(Test): Config = namedtuple('Config', ['spatial_read_files', 'spatial_read_reds', 'spatial_write_files', 'spatial_write_reds', '...
python
"""Module to preprocess detection data and robot poses to create usable input for ML model""" from copa_map.util import hist_grid, rate_grid, util import numpy as np from dataclasses import dataclass from termcolor import colored import os from matplotlib import pyplot as plt import pickle from matplotlib.widgets impo...
python
# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the NiBabel package for the # copyright and license terms. # ### ### ### #...
python
import sys from PyQt5 import QtGui, QtCore, QtWidgets from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from time import sleep from view import Scene class Inventory(QWidget): def __init__(self, parent=None): super(Inventory, self).__init__(parent) self.setup_wind...
python
# Copyright 2015 Yelp 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 agreed to in writing, so...
python
from django.urls import path from app.file_writer.views import FileWriterView urlpatterns = [ path('write/', FileWriterView) ]
python
#!/usr/bin/python3 """ Functional Test: STABILITY Written by David McDougall, 2018 This verifies basic properties of the Stable Spatial Pooler. This generates a new artificial dataset every time. The dataset consists of randomly generated SDRs which are fed into the system as a timeseries. The dataset represents ob...
python
import unittest from docx2md import DocxMedia class FakeDocxFile: def __init__(self, text): self.text = text def rels(self): return ( b'<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships>' + self.text + b"</Relationships>" ...
python
# -*- coding: utf-8 -*- """ Created on Mon Jan 25 15:21:34 2021 @author: crtjur """ import tkinter as tk from PIL import Image, ImageTk root = tk.Tk() root.title("Title") root.geometry("280x350") root.configure(background="black") class Example(tk.Frame): def __init__(self, master, *pargs): tk.Frame.__i...
python
""" WGAN-applicable Fully Convolutional Neural Network """ import tensorflow as tf from tensorflow.keras.layers import Input, Conv2D, Conv2DTranspose, AveragePooling2D, UpSampling2D, Concatenate, Dropout, LeakyReLU, BatchNormalization from architectures.activations import UV_activation from architectures.layers imp...
python
from prometheus_client import start_http_server from prometheus_client.core import REGISTRY from collector import ElasticBeanstalkCollector import time import datetime def main(): port = 9552 print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3], "Starting exporter on :", port) try...
python
import os import csv import datetime from flask import Flask, render_template, redirect, url_for app = Flask(__name__) file_data_list = [] def convert_to_timestamp(epoch_time='0'): return datetime.datetime.fromtimestamp(int(float(epoch_time))).strftime('%Y-%m-%dT%H:%M:%S') def cache_file_data(): global fil...
python
"""Jenkins test report metric collector.""" from datetime import datetime from typing import Dict, Final, List, cast from dateutil.parser import parse from base_collectors import SourceCollector from collector_utilities.functions import days_ago from collector_utilities.type import URL from source_model import Entit...
python
from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from __future__ import print_function from builtins import str as unicode from quark_runtime import * _lazyImport.plug("inheritance.pets") import quark.reflect class Pet(_QObject): def _init(self): ...
python
#! /usr/bin/env python import numpy as np import random from time import sleep from curses import wrapper def two_dim(pos, width): ''' Return 2d co-ordinates represented as 1d array. pos: position in one dimension width: total width of 2d array(columns) ''' width += 1 return pos//width, p...
python
""" UrlCanonicalizerMiddleware A spider middleware to canonicalize the urls of all requests generated from a spider. imported from http://snipplr.com/view/67007/url-canonicalizer-spider-middleware/ # Snippet imported from snippets.scrapy.org (which no longer works) # author: pablo # date : Sep 07, 2010 """ from sc...
python
from .diophantine import diophantine, classify_diop, diop_solve __all__ = [ 'diophantine', 'classify_diop', 'diop_solve' ]
python
# Generated by Django 3.1.7 on 2021-04-14 16:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0012_auto_20210414_1252'), ] operations = [ migrations.AlterField( model_name='post', name='additional_addre...
python
""" DELL SDP P-Search API """ try: import xml.etree.cElementTree as ET except ImportError: import xml.etree.ElementTree as ET class SDPException(Exception): pass class SDPApi(object): """ SDP API Calls """ def __init__(self, sdpclient, logger, response_json=None): ...
python
#!Venv/bin python3 # -*- coding: utf-8 -*- import sqlite3 from urllib.request import urlopen import numpy as np import pandas as pd from bs4 import BeautifulSoup html = urlopen('https://www.opap.org.cy/el/page/joker-results').read() html = html.decode('utf-8') soup = BeautifulSoup(html, features='html.parser') colu...
python
import torch from torch import nn class RNN_LSTM(nn.Module): def __init__(self, input_dim, hidden_dim, n_lyrs = 1, do = .05, device = "cpu"): """Initialize the network architecture Args: input_dim ([int]): [Number of time steps in the past to look at for current prediction] ...
python
# Copyright (C) 2020 Arm Limited or its affiliates. All rights reserved. # # SPDX-License-Identifier: Apache-2.0 # # 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 # # www.apache.org/licenses/LICE...
python
import argparse import json import os import pickle import numpy as np from nasbench_analysis.search_spaces.search_space_1 import SearchSpace1 from nasbench_analysis.search_spaces.search_space_2 import SearchSpace2 from nasbench_analysis.search_spaces.search_space_3 import SearchSpace3 from nasbench_analysis.utils im...
python
from pylab import * def imhist(img): rows, cols = img.shape h = np.zeros((256, 1), dtype=np.double) for k in range(255): h[k] = 0 for i in range(rows): for j in range(cols): if img[i,j] == k-1: h[k] = h[k]+1 return h def My...
python
import tensorflow as tf import optotf.nabla import unittest class Nabla2d(tf.keras.layers.Layer): def __init__(self, hx=1, hy=1): super().__init__() self.op = lambda x: optotf.nabla.nabla_2d(x, hx=hx, hy=hy) def call(self, x): if x.dtype == tf.complex64 or x.dtype == tf.complex128: ...
python
# -*- coding: utf-8 -*- """Top-level package for skipchunk.""" __author__ = """Max Irwin""" __email__ = 'max_irwin@yahoo.com' __version__ = '0.1.0'
python
from django.contrib import admin from .models import User, EmailSender from django.core.mail import send_mass_mail import smtplib admin.site.register(User) class EmailSenderAdmin(admin.ModelAdmin): actions = ['send_email'] @admin.action(description='Send mass email') def send_email(self, request, query...
python
from django.contrib import admin from bookings.models import Booking # Register your models here. admin.site.register(Booking)
python
from .utils import cached_property from .utils.types import is_list, get_link, validate, is_nullable from .resource import Resource from .conf import settings from .expression import execute from .schemas import FieldSchema from .exceptions import TypeValidationError def is_resolved(x): if isinstance(x, Resource)...
python
#!/usr/bin/env python3 # Copyright 2017 Johns Hopkins University (Shinji Watanabe) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) # This code is ported from the following implementation written in Torch. # https://github.com/chainer/chainer/blob/master/examples/ptb/train_ptb_custom_loop.py """Language m...
python
# !/usr/bin/env python # -*- coding: utf-8 -*- # Copyright(c) 2019 Nippon Telegraph and Telephone Corporation # Filename: EmLoggingTool.py ''' Log tool for EM. ''' import logging.handlers import time import gzip import os import re import shutil import GlobalModule class Formatter(logging.Forma...
python
import pytest from pipet.core.shop_conn.wc import * from pipet.core.transform.model_to_wc import * from pipet.core.transform.wc_to_model import * from pprint import pprint
python
def maxMultiple(divisor, bound): return (bound // divisor) * divisor
python
#Kyle Sizemore #2/7/2020 # pull historical data from the market for backtesting purposes and output to a # csv file on our mySQL database import warnings warnings.simplefilter(action='ignore', category=FutureWarning) import datetime import pandas as pd import pandas_datareader as web import csv import pymysql from sql...
python
import pypro.core import os class CreateConfig(pypro.core.Recipe): def __init__(self, source, destination): self.source = source self.destination = destination def run(self, runner, arguments=None): # Read the template file content = '' with open(self.source, 'r') as ...
python
import random import numpy as np import torch import torch.utils.data as data import data.util as util import os.path as osp class LQGT_dataset(data.Dataset): ''' Read LQ (Low Quality, here is LR) and GT image pairs. If only GT image is provided, generate LQ image on-the-fly. The pair is ensured by 'so...
python
""" byceps.services.ticketing.dbmodels.archived_attendance ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2014-2022 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from datetime import datetime from ....database import db from ....typing import PartyID, UserID from...
python
#!/usr/bin/env python3 """nargs=+""" import argparse parser = argparse.ArgumentParser( description='nargs=+', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('files', metavar='FILE', nargs='+', help='Some files') args = parser.parse_args() files = args.files print('number = {}'....
python
""" @authors: Filip Maciejewski, Oskar Słowik, Tomek Rybotycki @contact: filip.b.maciejewski@gmail.com REFERENCES: [0] Filip B. Maciejewski, Zoltán Zimborás, Michał Oszmaniec, "Mitigation of readout noise in near-term quantum devices by classical post-processing based on detector tomography", Quantum 4, 257 (2020) [0...
python