text
stringlengths
38
1.54M
from collections import namedtuple import json # ScrapedData = namedtuple('ScrapedData', 'title code employment_2016 employment_2026 change_number change_percent anual_wage') # s = ScrapedData(title='Management Occupations', code='11-0000', employment_2016='9,533.1', employment_2026='10,411.5', # change_number='878....
""" Created on 12:08, May. 23rd, 2021 Author: fassial Filename: test_inputs.py """ # local dep import stimulus __all__ = [ "test_poisson_input", ] ## define test func # define test_poisson_input func def test_poisson_input(): # get stim stim, _ = stimulus.inputs.poisson_input( duration = 100 )...
#!/usr/bin/python3 """Island_perimeter in python""" def island_perimeter(grid): """That returns the perimeter of the island described in grid""" base_actual = 0 base_max = 0 altura = 0 for row in grid: base_actual = 0 for column in row: if column == 1: ...
from multiprocessing import Process, cpu_count, freeze_support, Queue import numpy as np from math import ceil, floor import time def next(seed): seed = (seed * 0x5deece66d + 0xb) & ((1 << 48) - 1) retval = seed >> (48 - 31) if retval & (1 << 31): retval -= (1 << 32) return retval, ...
from EMAIL import * from fra import * from time import gmtime, strftime import sys import logging import time FILENAME = "MaxaromaNA" Subject = "MaxAroma_NewArrival" def main(): url = "http://www.maxaroma.com/" original = getMaxAroma(url) # dumpToSave(original) sendemail("Started " + FILENAME,Subject) while True: ...
import subprocess def executeCommand(): ''' Read a command from a user input, validate it, and execute it '''
from astral.adapters.Net import TCPServer,errors from base_adapter import ClientAdapter import socket import threading import time class server_adapter(TCPServer): def __init__(self,gameserver,host="127.0.0.1",port=1919): TCPServer.__init__(self) self.gameserver = gameserver self....
# importing dataset from sklearn.datasets import .... as fetch_olivetti_faces faces = fetch_olivetti_faces() img = faces.images M = 400 N = 4096 img2 = np.array([[0 for i in range(N)] for j in range(M)]) # visage moyen = vm vm = [0 for i in range(N)] for a in img: img2 = a.flatten() vm = vm + img2 vm1 = vm...
n=13 L=[ [ 0 for i in range(n) ] for j in range(n) ] k,l=n-1,int((n+1)/2-1) if (n%2!=0): L[k][l]=1 for i in range (1,n**2): if (L[(k+i)%n][(l+i)%n] == 0): L[(k+i)%n][(l+i)%n] = i+1 else: L[(k+i-2)%n][(l+i-1)%n]=i+1 k,l=(k+i-2)%n,(l+i-1)%n for i in range(n): ...
from django.contrib import admin from online_app.models import * # Register your models here. admin.site.register(Repo) admin.site.register(Package)
#!/usr/bin/python3 import xmlrpc.client import time import sys if len(sys.argv) == 1: print("USAGE: %s <server>" % sys.argv[0]) sys.exit(0) s = xmlrpc.client.ServerProxy('http://%s:8000' % sys.argv[1]) pre = time.time() response = s.ping() post = time.time() diff = post - pre print(pre,response,post,diff) ...
#!/usr/bin/env python3 import yaml from jinja2 import Template from datetime import datetime from kubernetes import client, config def main(): kaniko("sidecar", "latest", "git://github.com/kbase/init-sidecar.git") def kaniko(image, tag, repo): # Set image name, and consistent timestamp build_image_name =...
import os import csv import time import imaplib import email from flask import Flask, request, session, g, redirect, url_for, abort, \ render_template, flash, jsonify app = Flask(__name__) app.config.from_object(__name__) app.config.update(dict(DATADIR="data")) app.config.from_envvar('QVTABLE_SETTINGS', silent=Tr...
import urllib2 from pyIEM import iemdb import mx.DateTime i = iemdb.iemdb() coop = i['coop'] mesosite = i['mesosite'] stmeta = {} def parse_lonlat( txt ): tokens = txt.split() lat = float(tokens[0]) + ((float(tokens[1]) + float(tokens[2]) / 60.0) / 60.0) lon = float(tokens[3]) - ((float(tokens[4]) + float(toke...
#! /usr/bin/python import sys scaffoldFile = sys.argv[1] outputFile = "%s_unique.fasta" %(scaffoldFile) infileScaffolds = open(scaffoldFile, "r") outfile = open(outputFile, "w") fastaDict = {} key = 0 fastaDict[key] = [] for line in infileScaffolds: if ">" in line: joinLine = "".join(fastaDict[key]) fastaDict[...
# Generated by Django 3.0.3 on 2020-03-21 14:57 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mywebsite', '0001_initial'), ] operations = [ migrations.AddField( model_name='project', name='desc', fi...
# -*- coding: utf-8 -*- """ Created on Wed Apr 8 18:01:34 2015 @author: Erin """ # An implementation of example 2 from MT-DREAM(ZS) original Matlab code. (see Laloy and Vrugt 2012) # 200 dimensional Gaussian distribution import numpy as np import os from pydream.parameters import FlatParam from pydream.core import ...
def count(valuelist): return_list = [] for a in range(0,len(valuelist)-1): return_list.append(abs(valuelist[a]-valuelist[a+1])) return return_list test_case = int(input()) while(test_case): input_list = list(input()) reversed_input_list = reversed(input_list) input_list = [ord(x) for x i...
import os import random import string import setup_catalog from google.api_core.client_options import ClientOptions from google.cloud.retail_v2 import SearchServiceClient, SearchRequest project_number = "1038874412926" endpoint = "retail.googleapis.com" isolation_filter_key = "INTEGRATION_FILTER_KEY" title_query = "...
from itertools import product import numpy as np from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D from sklearn.gaussian_process import GaussianProcessRegressor from sklearn.gaussian_process.kernels import RBF, ConstantKernel as C X = np.array([[0,0],[2,0],[4,0],[6,0],[8,0],[10,0],[...
import aiohttp_cors from app.api import profile, roadmaps, skills, spec, vacancies def setup_routes(app): """Добавлена точка входа для приложения.""" cors = aiohttp_cors.setup(app, defaults={ '*': aiohttp_cors.ResourceOptions( allow_credentials=True, expose_headers='*', ...
import hashlib import random from string import ascii_uppercase, digits from rest_framework.response import Response from rest_framework import status from rest_framework.viewsets import ModelViewSet, ReadOnlyModelViewSet from .serializers import TransactionModelSerializer from .models import Transaction from rest_fram...
import gtk from System import SystemType current_system = SystemType() class StatusIcon: def __init__(self, parent): self.parent = parent iconpath = "WWU.gif" self.statusicon = gtk.StatusIcon() self.statusicon.set_from_file(iconpath) self.statusicon.connect("button...
import requests import time,random from bs4 import BeautifulSoup from urllib import request def getData(data): string="" time,temp,pict,condi,confort,rain,msg=[],[],[],[],[],[],[] for data_ in data:#取得時間、溫度、天氣狀況、舒適度、降雨機率等資料 time.append(data_.find('th',{'scope':'row'}).text) temp.append(data...
# !/usr/bin/env python # -*- coding: utf-8 -*- # Time : 2017-08-25 14:33 # Author : MrFiona # File : summary_optparse.py # Software: PyCharm Community Edition """ 模块optparse使用类OptionParser来作为命令行选项的解析器;下面是该类的方法: 1、OptionParser(self, prog=None, usage=None, description=None, epilog=None, option_list=None...
from __future__ import absolute_import import re import json import requests from apis.base import BaseAPI, APIException # Flickr API: https://www.flickr.com/services/api/ class FlickrPhotoAPI(BaseAPI): url_format = "https://farm{farm}.staticflickr.com/{server}/{id}_{secret}_m.jpg" per_page = 10 def __in...
from aiohttp import web from docker import Client from .launcher import Launcher async def create_container_handler(request): launch_config = request.app['launch_config'] hostname = await request.app['launcher'].launch(**launch_config) headers = {'Access-Control-Allow-Origin': '*'} return web.Respons...
# Generated by Django 3.1.3 on 2020-11-08 16:02 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0003_auto_20201105_1100'), ] operations = [ migrations.AddField( model_name='game', name='end_date', ...
# -*- coding: utf-8 -*- import itertools import time from flask import Flask, jsonify, request, render_template import os import io import firebase_admin from firebase_admin import db from firebase_admin import credentials, firestore from google.cloud import storage from PIL import Image import requests from io import...
__author__ = 'Li Bai' """the available data are loaded from nordhavn3_april.csv, and the explanatory variables are weather forecasts ('temperature', 'humidity', 'DNI (Direct normal irradiance)', 'windspeed') and the output is heat load. Considering the time-frequency domain analysis, 'Day sin', 'Day co...
import sys from collections import OrderedDict import pandas as pd import numpy as np import operator as op import tensorflow as tf from .common import constructNetwork from .common import constructNetworkWithoutDropout from .common import convertDateColsToInt from .common import arrayToText from .common import cons...
import numpy as np import cv2 import matplotlib.pyplot as plt class Utils(): def __init__(self): pass def get_otsu_threshold(self, image): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.bitwise_not(gray) thresh = cv2.threshold(gray, 0, 255,cv2.THRESH_BINARY | cv2.TH...
from django import template register = template.Library() from video.models import Video @register.inclusion_tag('video/tags/lattest_videos.html', takes_context=True) def lattest_videos(context): lattest_videos = Video.objects.all().filter( galleries__is_public=True).order_by('created')[:6] context['lattest_vide...
import logging from datetime import datetime import requests from common import db_session from configuration import API_KEY from .models import TrainActivity BASE_V2_URL = 'http://realtime.mbta.com/developer/api/v2' logger = logging.getLogger(__name__) def format_mbta_request_url(api_key: str): return '{}/pre...
# coding: utf-8 """ The sum of the squares of the first ten natural numbers is, 1^(2) + 2^(2) + ... + 10^(2) = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^(2) = 55^(2) = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of ...
# -*- coding:utf-8 -*- import os def getPlus(a, b): k1 = len(str(a)) s1 = str(a) k2 = len(str(b)) s2 = str(b) print k1, type(s1), s1, " |--| ", k2, type(s2), s2 p = list() k = 0 for item_b in s2[::-1]: index = k for item_a in s1[::-1]: num = int(item_a) ...
from selenium import webdriver from selenium.common.exceptions import ElementClickInterceptedException, NoSuchElementException from selenium.webdriver.common.keys import Keys import time from password import * driver = webdriver.Chrome("C:\Chromedriver\chromedriver") URL = "https://tinder.com/" driver.get(URL) drive...
"""Helper set of functions to read in and parse multiple types of input sources.""" import sys import os import datetime from bs4 import BeautifulSoup from shapely.geometry.polygon import Polygon def read(ftype, inDir, inSuffix, startTime, endTime): """ Determines the user-specified file type and parses it accordin...
from django.conf.urls import url from django.urls import include, path from fichaArticulo import views as ficha_views from . import views urlpatterns = [ path('', include(([path('', ficha_views.fichaArticulo, name='fichaArticulo')],'fichaArticulo'), namespace='ficha')), path(r'', ficha_views.fichaArticulo, n...
# # MIT License # # Copyright (c) 2018 Matteo Poggi m.poggi@unibo.it # # 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, c...
# encoding: UTF-8 import main from dal import base_dal from test_main.constants import * def test_delete_performance_report(): base_dal.delete_performance_report(YEAR, QUARTER) if __name__ == '__main__': main.setup_logging() test_delete_performance_report()
def exercicio4(): print("Programa de calculo de média final") media1 = int(input("Digite a média do primeiro bimestre: ")) media2 = int(input("Digite a média do segundo bimestre: ")) media3 = int(input("Digite a média do terceiro bimestre: ")) media4 = int(input("Digite a média do quarto bimestre:...
# Generated by Django 3.1.7 on 2021-03-07 15:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('gamma', '0006_merge_20210304_0032'), ] operations = [ migrations.AddField( model_name='post', name='header_image', ...
import csv import subprocess # stdout = subprocess.PIPE, stderr = subprocess.PIPE subprocess.run( ["abaqus", "cae", "noGUI=./abaqusScript/autoParametric2DnoGUI.py"], shell=True) print("*********************") with open('force_output.csv', 'r') as file: reader = csv.reader(file) for row in reader: fo...
# Generated by Django 2.0 on 2018-01-24 07:28 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Coin', fields=[ ('coin_id', models.CharField(...
# coding: utf-8 from flask import Flask, render_template from flask import request import funpy.app as funpy app = Flask(__name__) #インスタンス生成 @app.route('/weather',methods=['GET', 'POST']) def add_numbers(): lat = request.args.get('lat') lng = request.args.get('lng') num = funpy.api(lat,lng) return re...
import os from influxdb_client import InfluxDBClient, Point from influxdb_client.client.write_api import SYNCHRONOUS bucket = os.getenv("INFLUX_BUCKET") host = os.getenv("INFLUX_HOST") port = os.getenv("INFLUX_PORT") org = os.getenv("INFLUX_ORG") token = os.getenv("INFLUX_TOKEN") class HiveData(object): def __i...
from django.contrib import admin from .models import Evento from .models import Professores from .models import Alunos, Cursos admin.site.register(Evento) admin.site.register(Professores) admin.site.register(Alunos) admin.site.register(Cursos)
""" Tests Deploy CLI """ from subprocess import CalledProcessError, PIPE from unittest import TestCase from mock import patch, call from samcli.lib.samlib.cloudformation_command import execute_command, find_executable class TestExecuteCommand(TestCase): def setUp(self): self.args = ("--arg1", "value1...
from Calculator import BasicArithmeticOperation0_1 as BAO # import BasicArithmeticOperation0_1 as BAO import numpy as np import time import matplotlib.pyplot as plt def trapezium_area(top, base, height): area = BAO.multi(1 / 2, (BAO.multi(BAO.add(top, base), height))) return area def integration_simp(equ, st...
from django.db import models from django.utils.text import slugify from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Blog(models.Model): title = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, unique=True) conten...
import os import json def store_string_xml(xml_results, field_values, field_name): '''Format values for writing xml output''' for field_number in range(0, len(field_values)): field_number_name = str(field_number).zfill(2) k = field_name + field_number_name xml_results[k] = field_values...
from rest_framework.exceptions import APIException from rest_framework import status class ConflictError(APIException): status_code = status.HTTP_409_CONFLICT default_detail = 'Conflict' class InternalServiceError(APIException): status_code = status.HTTP_500_INTERNAL_SERVER_ERROR default_detail = 'I...
# Copyright (c) OpenMMLab. All rights reserved. import argparse import glob import os.path as osp import cityscapesscripts.helpers.labels as CSLabels import mmcv import numpy as np import pycocotools.mask as maskUtils from mmengine.fileio import dump from mmengine.utils import (Timer, mkdir_or_exist, track_parallel_pr...
import os import pathlib from unittest.mock import Mock import cv2 import numpy as np from liveprint.lp import Projector, WhiteBackground from liveprint.pose import PosesFactory, Poses, Keypoint, TorsoKeyPoints from liveprint.utils import Apng class FakePosesFactory(PosesFactory): def poses(self, image): ...
# -*- coding: utf-8 -*- """ Created on Wed Jun 3 02:40:45 2020 @author: amk170930 """ import airsim import numpy as np import setup_path import os from datetime import datetime import time class frequencyTest: # connect to the AirSim simulator client = airsim.CarClient() client.confirmConnection() cl...
#!/usr/bin/env python3 # NOTE: NEEDS SYNCHRONIZATION FOR MULTITHREADING import random import string from enum import Enum, auto from abc import ABC,abstractmethod from typing import ( Dict, List, Optional, Tuple ) def _random_id() -> str: ascii = string.ascii_lowercase return "".join(random...
class Solution: def romanToInt(self, s: str) -> int: dictionary = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000 } my_sum = 0 ...
import numpy as np from sklearn.linear_model import LogisticRegression hours = np.array([0.5, 0.75, 1, 1.25, 1.5, 1.75, 1.75, 2, 2.25, 2.5, 2.75, 3, 3.25, 3.5, 4, 4.25, 4.5, 8, 4.75, 5, 5.5]).reshape(-1, 1) approved = np.array([0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1]) lr = LogisticRegression...
__author__ = 'dang' from datetime import datetime import json import redis import configinfo class PubSubModel: ''' A backend for real-time events reporting, every time the receivers send an alert it will be save into redis database, redis will publish the events to event stream consumed by the ...
from rest_framework import serializers from assets.models import * class HostGroupSerializer(serializers.ModelSerializer): class Meta: model = HostGroup fields = ('id', 'name', 'createTime',) class HostSerializer(serializers.ModelSerializer): hostGroup = serializers.PrimaryKeyRelatedField(ma...
#-*- coding: UTF-8 -*- import re from flask import render_template, request, redirect, url_for, json, abort, session from xichuangzhu import app import config from xichuangzhu.models.author_model import Author from xichuangzhu.models.work_model import Work from xichuangzhu.models.collection_model import Collection...
# Generated by Django 3.0.14 on 2022-01-31 20:13 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('machines', '0004_device_invoice_pdf'), ] operations = [ migrations.AlterModelOptions( name='device', options={'orde...
import string import numpy as np import pandas as pd import pytest from matchms import Spectrum from ms2deepscore import SpectrumBinner from ms2deepscore.data_generators import (DataGeneratorAllInchikeys, DataGeneratorAllSpectrums, Data...
from . import base, items def note_class(self, class_, level): if not hasattr(self, 'classes'): self.classes = [] self.classes.append((class_, level)) class _Progression: def __init__(self, list, level): import collections self.x=collections.defaultdict(int) for i in range(...
from math import * import numpy as np import sys def DTW(A, B, window = sys.maxsize, d = lambda x,y: abs(x-y)): # create the cost matrix A, B = np.array(A), np.array(B) M, N = len(A), len(B) cost = sys.maxsize * np.ones((M, N)) ## ''' for i in range(0,M): print(A[i]," ",end='') ...
# from demopackage import data from pkgutil import get_data with open('demopackage/data/datafile.txt') as f: for line in f: try: print(line) except ValueError: print('nothing') # name of the pakage, relative path data = get_data('demopackage', 'data/datafile.txt') print(dat...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
from __future__ import unicode_literals import unittest import mock import requests import time from requests_oauthlib import OAuth2Session from requests_oauthlib.compliance_fixes import facebook_compliance_fix from requests_oauthlib.compliance_fixes import linkedin_compliance_fix from requests_oauthlib.compliance_fi...
import argparse from aoe2_image_gen.generator import aoe2_image_gen def main(): function_map = { "villagers": aoe2_image_gen.generate_villager_dataset, "multi_label": aoe2_image_gen.generate_multi_label_dataset, } parser = argparse.ArgumentParser( description="Generate machine lea...
from django.contrib import admin from .models import Usuario from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import UserChangeForm from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin class MyUserChangeForm(UserChangeForm): class Meta(UserChan...
import time import re import datetime import plotly.graph_objs as go from selenium import webdriver from selenium.webdriver.common.keys import Keys def check_score(old_score): pass def Play(): driver.get('http://www.cl.cam.ac.uk/~yf261/2048/') body = driver.find_element_by_tag_name('body') t0 = dat...
import random from math import log def primecheck(prime): v = 1 n = prime - 1 s = 0 while n%2 ==0: n = n/2 s = s + 1 pot = 100.00 a = random.SystemRandom().randrange(2, int(pot)) for z in range(2, int(pot)): prtest = False for w in range(s): a = z binp = bin((2**w)*n) sig = 1 ...
import vanilla from sys import getsizeof from defconAppKit.windows.baseWindow import BaseWindowController from lib.scripting.codeEditor import CodeEditor try: from plistlib import writePlistToString except ImportError: from plistlib import dumps as writePlistToString from knownKeys import known_keys class UFO...
# controlling the browser using the selenium module # pip install selenium # we must have Firefox and the geckodriver (geckodriver.exe must be added to the PATH) from selenium import webdriver browser = webdriver.Firefox() browser.get('https://automatetheboringstuff.com') # assigning an element ( in this case a link...
# -*-coding:utf-8 -*- #对需要的一些功能进行封装 import hashlib from .wrappers import * from django.core.urlresolvers import reverse from django.shortcuts import redirect from normal_user.models import * import os import time import re import shutil # 密码加密 def password_encryption(password): # 创建加密对象 sha = hashlib.sha256(...
""" CS241 Homework 03 Written by Chad Maceth """ # Start with empty lists odd_numbers = [] even_numbers = [] # Loop until 0 is entered number = 1 while (number != 0): number = int(input("Enter a number (0 to quit): ")) # If number is even (and not 0) then add to even list # if number is odd then add to odd l...
import argparse if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('demo', help='demo how to use argparse') args = parser.parse_args() print args.demo #run: python argparse_usage.py Test #output: Test
import os import pickle import tensorflow as tf from utils import export_dicts_helper, load_vocab class EvalDataLoader: def __init__(self, path_to_vocab_pickle, path_to_data): """ This class is used to load evaluation data and export data to TfRecords. Important Note: Modif...
#Roman Sokolovski #Assignment4 #10185440 import WordLookup def oneLetterDiff(word): alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' ] newList = [] wordList = [] for i in range(len(word)): #loops for len ...
#!/usr/bin/env python # # integration_test.py # # This is a system test that uses a bridge (via the linux socat utility) to # connect a fake tty device with the real system. # # TODO: Complete this script # TODO: Uart Bridge should probably be called something else # # Author(s): Kenny Luong <luong97@hawaii.edu> # Date...
##### 解けた ##### import numpy as np import math N=int(input()) A=np.asarray(list(map(int,input().split(" ")))) # ソフトのリスト print(math.ceil(A[A>0].mean()))
import pyfits as pf import h5py import numpy as np import kmeans_radec import matplotlib.pyplot as plt plt.switch_backend("Agg") import treecorr import seaborn as sns shear_data = ["../../redsequence/data/KiDS_DR3.1_G9_ugri_shear.fits", "../../redsequence/data/KiDS_DR3.1_G12_ugri_shear.fits", "../../redsequence/dat...
import datetime class Employee: # Class variables num_of_employees = 0 raise_amount = 1.04 # Regular variables def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first.lower() + '.' + last.lower() + '@company.com' ...
from typing import Any class TablePlotter: cell_width: Any = ... cell_height: Any = ... font_size: Any = ... def __init__(self, cell_width: float=..., cell_height: float=..., font_size: float=...) -> None: ... def plot(self, left: Any, right: Any, labels: Any = ..., vertical: bool=...) -> Any: ...
import logging """levels: debug 10, general information info 20, confirmation that things are working as expected warning 30, something unexpected happened, there might be problems, default level of logging() error 40, serious problem, program couldn't perform a function critical 50, serious error, the program may no...
#!/usr/bin/python # -*- coding: utf-8 -* from ws4py.client.threadedclient import WebSocketClient import urllib import urllib.request import urllib.parse import json import time import logging import threading class User(object): """ This object class stores all the information needed to keep track of online ...
from keras.models import Model from keras.layers import Conv2D, ZeroPadding2D, BatchNormalization, Input, Dropout, Conv2DTranspose, Reshape, Activation, Cropping2D, Flatten, ReLU, LeakyReLU, Concatenate from functools import partial __all__ = ['BASIC_D', 'UNET_G'] batchnorm = partial(BatchNormalization, momentum=0.9,...
#coding=utf-8 import os # pip2 install pywin32com import win32com.client as win32 import datetime import readConfig import getpathInfo read_conf = readConfig.ReadConfig() subject = read_conf.get_email('subject') #从配置文件中读取,邮件主题 app = str(read_conf.get_email('app')) #从配置文件读取邮件类型 address = read_conf...
import random, machine from fonts import six_by_three_font, seven_by_four_font from time import sleep_ms import gc try: import pyb except ImportError: import machine as pyb #Graduation cap class to control LED matrix functionality class GradCap: def __init__(self): self.data_pin = 18 #pin one-wire interfa...
from __future__ import absolute_import import os import logging from splunk.appserver.mrsparkle.controllers import BaseController from splunk.appserver.mrsparkle.lib.routes import route from splunk.appserver.mrsparkle.list_helpers import generators from splunk.appserver.mrsparkle.lib import util logger = logging.get...
# -*- coding: utf-8 -*- import re fred = re.compile('(.+)(lala)') rainbow = re.compile('(miao\.)(.+)', re.DOTALL) n = int(raw_input()) result = [] for i in xrange(n): sentence = raw_input() freds = fred.match(sentence) rainbows = rainbow.match(sentence) if freds and rainbows: print('OMG>.< I ...
from PIL import Image from tkinter import Tk, PhotoImage, Canvas, NW def algoritm (txtname, imagename, mode, size = (960,540)): size = size[::-1] if format == 1 else size img = Image.new("RGB", size, "white") f = open(txtname,"r") data = f.read().split("\n") for i in range(len(data)-1): ...
from django import forms from Reports.models import * class AuctionQueryForm(forms.ModelForm): class Meta: model = AuctionQuery fields = '__all__'
import pandas as pd import matplotlib import os INPUT_FOLDER = "../preprocessing/aggregated/weekly/classes/" OUTPUT_FOLDER = "../preprocessing/distributions/weekly/classes/" COLUMNS_TO_HISTOGRAM = { "MaxChurnInBurst", "TotalChurnInBurst", "ChurnTotal", "TLOC" } # expects a .csv filename, whose file has ; seperat...
import os from typing import Dict import numpy as np from bert_api.client_lib import BERTClient from cache import load_pickle_from from cpath import data_path, pjoin from cpath import output_path from data_generator.bert_input_splitter import split_p_h_with_input_ids from data_generator.tokenizer_wo_tf import convert...
# -*- coding: latin-1 -*- # ler MNIST em formato mat e pickle it import numpy as np import matplotlib.pyplot as plt import pickle plt.close('all') pName='MNISTsmall.p' D=pickle.load(open(pName,'rb')) X=D['X']*1. y=D['trueClass'] f1=D['foldTrain'] X1=X[:,f1] y1=y[f1] #matriz com AND Cand=np.ones((28,28)).astype('bool')...
from __future__ import unicode_literals from __future__ import print_function from __future__ import absolute_import from fs.errors import FSError from .console import Cell from .compat import text_type, implements_to_string from .reader import DataReader import weakref import re _re_fs_path = re.compile(r'^(?:\{(.*...
''' Generator for the image data ''' import numpy as np from PIL import Image, ImageOps import io from sympy import preview import pandas as pd import click import uuid class create_data: r""" Create a random set of images with a black background and white letters. # Arguments image_size: A tupl...
from StatisticFunctions.StandardDeviation import StandardDeviation from StatisticFunctions.Mean import Mean class samplecorrelation: @staticmethod def samplecorrelation(data1, data2): numerator = 0 n = 0 meanofx = Mean.mean(data1) meanofy = Mean.mean(data2) stdevx = Sta...