text
stringlengths
38
1.54M
# -*- coding: utf-8 -*- """ Created on Sat May 29 19:22:47 2021 @author: rashe """ import pandas as pd import numpy as np def Get_Mahalanobis(dataframe): dataframe = dataframe.reset_index(drop=True) nunique = dataframe.apply(pd.Series.nunique) if dataframe.shape[1] >= 15: cols_to_drop = nuni...
#!/usr/local/bin/python3 import requests, json api_key = "9ba6fc1b788596955f9cda5396fb080a" base_url = "https://api.openweathermap.org/data/2.5/weather?" # Change this to be your city city = "4668054" URL = base_url + "id=" + city + "&appid=" + api_key + "&units=imperial" response = requests.get(URL) #print(URL) ...
import random from collections import defaultdict from ..evaluation import Scoresheet from ..util import all_pairs from .base import Predictor __all__ = ["Community", "Copy", "Random"] class Community(Predictor): def predict(self): # pylint:disable=E0202 """Predict using community structure If...
#!/usr/bin/python # -*- coding: utf-8 -*- # In Debian, install `apt install python-crypto` __all__ = ['AESCipher', 'RSACipher', 'Checksum'] from Crypto import Random from Crypto.Cipher import AES from base64 import b64encode, b64decode try: import gmpy2 _bitLength = gmpy2.bit_length _divMod = gmpy2.f_di...
import ROOT ROOT.gSystem.Load("RooUnfold/libRooUnfold") from ROOT import gRandom, TH1, cout, TH2, TLegend, TFile from ROOT import RooUnfoldResponse from ROOT import RooUnfold from ROOT import RooUnfoldBayes from ROOT import TCanvas from ROOT import RooUnfoldSvd from optparse import OptionParser parser = ...
import json import re import httpretty import pytest from social.apps.django_app.default.models import DjangoStorage from social.backends.google import GoogleOAuth2 from social.p3 import urlparse from social.strategies.django_strategy import DjangoStrategy from social.utils import parse_qs def handle_state(backend,...
#!/usr/bin/python #ab environment ban gya fir teminal me jakr ./filename # ! she bang / hash bang and non technically it is called environment provider # ! /usr/bin/env python -> ek aur tareeka x=10 y=20 print x+y print type(x) t=(4,6,78) print len(t)
from a10sdk.common.A10BaseClass import A10BaseClass class Sip(A10BaseClass): """Class Description:: Change LSN SIP ALG Settings. Class sip supports CRUD Operations and inherits from `common/A10BaseClass`. This class is the `"PARENT"` class for this module.` :param sip_value: {"optional": tr...
''' CONSOLE COMMAND: Add Return Date of Activity REQUEST FOR CHANGE: 658 ISSUE: 1029 CMD: python scripts/add_return_doa.py | tee -a logs/rfc_0658_20210519T1000.log Update Return Running Sheet entries to set Date of Activity to date added. ''' import os import sys import django proj_path = '/app' sys.path.append(proj_...
import functools from typing import Callable, Iterable, Tuple, Union import numpy as np from matplotlib import animation, pyplot as plt from matplotlib.animation import FuncAnimation from scipy.integrate import odeint mpl_lim = Union[float, Tuple[float, float]] def plot_ode( func: Callable, initial_conditio...
import logging import dbus logger = logging.getLogger(__name__) class DbusDevice(object): ## The constructor processes the tree of dbus-items. # @param bus Session/System bus object # @param name the dbus-service-name. def __init__(self, bus, name, eventCallback): self._dbus_name = name self._dbus_conn = bus ...
""" ================================================================================ pypolar: Analysis of polarization using the Jones and/or the Mueller calculus ================================================================================ http://github.com/scottprahl/pypolar Usage: import pypolar.jones as j...
# -*- coding: utf-8 -*- import csv import sys from model import * COMUNIDAD = 0 PROVINCIA = 2 MUNICIPIO = 4 POBLACION = 5 CENSOTOTAL = 7 VOTOSTOTALES = 8 VOTOSVALIDOS = 9 VOTOSCANDIDATURA = 10 VOTOSBLANCO = 11 VOTOSNULO = 12 class Provincia: def __init__(self): self.poblacion = 0 self.censoTotal ...
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html from scrapy.exporters import CsvItemExporter from scrapy.conf import settings #import pymongo # class MongoProductPipeline(o...
from PIL import Image from matplotlib import pyplot as plt import os import math import numpy as np from utils.dir import dir_dict DIR = dir_dict["VOC_DIR"] SETS = [('2012', 'train'), ('2012', 'val'), ('2007', 'train'), ('2007', 'val'), ('2007', 'test')] CLASS_LIST = ["aeroplane", "bicycle", "bird", "boat", "bottl...
import sys import warnings if not sys.warnoptions: warnings.simplefilter('ignore') import json import pickle import os import tensorflow as tf from ._utils._utils import check_file, load_graph from . import home from ._utils._paths import PATH_TOXIC, S3_PATH_TOXIC from ._models._sklearn_model import TOXIC from ._...
from flask import jsonify from app.server import app from app.models import DataValidationError from flask_api import status BAD_REQUEST_ERROR = 'Bad Request.' METHOD_NOT_ALLOWED_ERROR = 'Method Not Allowed' NOT_FOUND_ERROR = 'Not Found.' UNSUPPORTED_MEDIA_TYPE_ERROR = 'Unsupported media type' INTERNAL_SERVER_ERROR = ...
# -*- coding: utf-8 -*- from yapsy.PluginManager import PluginManager from yapsy.IPlugin import IPlugin class Help(IPlugin): def execute(self, channel, username, command): manager = PluginManager() manager.setPluginPlaces(["plugins"]) manager.collectPlugins() plugins = [] ...
# http://codeforces.com/contest/282/problem/A n = int(input()) statements = [input() for x in range(n)] x = 0 for line in statements: if line == 'X++' or line == '++X': x += 1 else: x -= 1 print(x)
import numpy as np import pandas as pd import sys import csv import time from PIL import Image from sklearn.model_selection import train_test_split import torch import torch.nn as nn from torch.utils.data import Dataset, DataLoader import torchvision.transforms as transforms use_cuda = torch.cuda.is_available() torch...
print('You are in Bananas branch!') # #int k = 5 # #string t = 'Ana' # #float f = 5.67 print('You are in Coconuts Branch!') #int-float a = 2 b = 54 c = 13.5 print(a+b+c) x = 13 z = 23.5 y = x + z print (y % x) a = 2.5 p = 1 q = a + 3 print(q ** 13 //a) #string a = "Hello" b = "Coconut" print(a + b) reddish = 1 l...
import torch.utils.data import random import scipy.misc import numpy as np import os import math import utils from tqdm import tqdm from point_cloud import Depth2BEV, get_visibility_grid import time import pandas as pd class SubsetSampler(torch.utils.data.sampler.Sampler): def __init__(self, indices): sel...
from nltk.corpus import wordnet as wn import os for s in wn.all_synsets(): print "insert into WN.Synsets (ID,Definition,POS) values ('" + s.name + "','" + s.definition.replace("'","''") + "','" + s.pos + "')" print "GO" for l in s.lemmas: print "insert into WN.Lemmas (ID,Lemma) values ('" + s....
class Home: def __init__(self): self.__parking = False self.__lights = [False for i in range(5)] self.__doorlock = False self.__temperature = 0.0 self.__energy = 100 @property def parking(self): return self.__parking def setParking(self, parking): ...
""" Umweltbundesamt: Meeresumweltdatenbank (MUDAB) Meeres-Monitoringdaten von Küstenbundesländern und Forschungseinrichtungen # noqa: E501 The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 from deutschland....
class Solution(object): def wordPattern(self, pattern, s): """ :type pattern: str :type s: str :rtype: bool """ d = {} words = s.split(' ') n = len(pattern) if (n != len(words)): return False for ...
"""Script to pre-compile chameleon templates to the cache. This script is useful if the time to compile chameleon templates is unacceptably long. It finds and compiles all templates within a directory, saving the result in the cache configured via the CHAMELEON_CACHE environment variable. """ import os import sys imp...
# Generated by Django 3.1.7 on 2021-04-19 04:23 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('hoosfit', '0012_auto_20210419_0023'), ] operations = [ migrations.AlterField( model_name='profile', ...
from streamer import streamer import cv2 #redis server host:port HOST = "0.0.0.0" PORT = 6379 #webcam ID DEVICE = 0 WIDTH = 1280 HEIGHT = 720 QUALITY = 70 s = streamer(host=HOST, port=PORT) cap = cv2.VideoCapture(DEVICE) cap.set(3,WIDTH) cap.set(4,HEIGHT) #mjpeg cap.set(6,1196444237.0) while True: ret, frame =...
import sys import numpy as np def squareMatrixBenchmark(n): m1 = np.random.random([n,n]) m2 = np.random.random([n,n]) m3 = m1 @ m2 if __name__ == "__main__": if(len(sys.argv) != 2): print("usage: python numpyBenchmark.py n") exit() n = int(sys.argv[1]) np.random.seed(0) ...
import re import csv import matplotlib.pyplot as plt import numpy import operator import epubreader as er import rangefreq as rf import multiprocessing as mp def comp_vari(freqlist): ## Compute coefficient of variation freqnp = numpy.array(freqlist) if numpy.mean(freqnp) == 0: return 0 else: ...
# -*- coding: utf-8 -*- from django.conf import settings if settings.DATABASE_ENGINE=='pool': settings.DATABASE_ENGINE=settings.POOL_DATABASE_ENGINE from django.core.management.base import BaseCommand, CommandError import os import time import sys from mysite.iclock.constant import REALTIME_EVENT, DEVICE_POST_DATA im...
# -*- coding: utf-8 -*- from __future__ import print_function from matplotlib import pyplot as plt import matplotlib.image as mpimg import numpy as np import scipy.misc import random import os import imageio ############################# # global variables # ############################# root_dir = "/ho...
""" This file is for test blockus_data.py """ import numpy as np import torch as tr import unittest as ut import blockus_data as bd import blockus_game as bg class BlockusDataTestCase(ut.TestCase): def test_encode(self): state = bg.initial_state(board_size=2) actual = bd.encode(state) expe...
class Course: def __init__(self,name): self.name=name self.graduated=False def graduateCourse(self): self.graduated=True def getGraduateStatus(self): return self.graduated def getCourseName(self): return self.name
# BASIC DATA TYPES # STRINGS: # in python, there are certain ways to express information like numbers and words # to express letters or words use single or double quotation marks around the words. # If you don't use single or double quotation marks python will assume that you're just writing a variable name # and wil...
from Stack import Stack def infToPost(exp): posexp=[] opstack=Stack() prec={"(":1,"*":3,"+":2,"-":2,"/":3,"**":3} tokenList=exp.split() print(tokenList) for token in tokenList: if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "1234567890": posexp.append(token) eli...
#!/usr/bin/env python def r8lib_test ( ): #*****************************************************************************80 # ## R8LIB_TEST tests the R8LIB library. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 24 May 2015 # # Author: # # John Burkardt # from ...
from django.urls import path from .views import launch_giveaway app_name = 'giveaway' urlpatterns = [ path('giveaway/launch', launch_giveaway, name='launch_giveaway') ]
import os DIR = '../../fluffed_data/news/fluffed' str_lookup = input('What are you looking for? ') for f in os.listdir(DIR): file_path = os.path.join(DIR, f) with open(file_path, 'rb') as text: content = text.read().decode('ascii') if str_lookup in content.lower(): print(content) if input('is this what ...
#https://www.hackerrank.com/challenges/the-grid-search T = int(input()) for _ in range(T): R, C = map(int, input().split()) G = list(list(map(int, input())) for i in range(R)) r, c = map(int, input().split()) P = list(list(map(int, input())) for i in range(r)) found = False for i in range...
__author__ = '184766' """ Multiple inheritance example 2 demonstrates the diamond inheritance pattern ....breadth first search is used because a diamond inheritance pattern creates ambiguity """ class A(object): def dothis(self): print "doing this in A" class B(A): pass class C(A): def dot...
import unittest from problem import * class Test(unittest.TestCase): def tests(self): self.assertEqual(add(2,11), 13) self.assertEqual(add(0,1), 1) self.assertEqual(add(0,0), 0) self.assertEqual(add(16,18), 214) self.assertEqual(add(26,39), 515) self.assertEqual(add(...
from osgeo import ogr import matplotlib.pyplot as plt source = ogr.Open('/home/nlibassi/Geodesy/Thesis/Project/Vector/ITRF96TM30/ProfilePoints/2001_2015_ProfilePtsEdited.shp') layer = source.GetLayer() profNames = ['pr0000106', 'pr4000106', 'pr3000106', 'pr7770106', 'pr7000106', 'pr2000106', 'pr6000106', 'pr1000106',...
# Write a program that accepts sequence of lines as # input and prints the lines after making all characters # in the sentence capitalized. lines = [] while True: s = raw_input() if s: lines.append(s.upper()) else: break for sentence in lines: print sentence
#!/usr/bin/env python3 # A simple http server that accepts GET and POST requests sendt as JSON data # It will write the "hostname" and "flag" fields from JSON to a txt-file from http.server import BaseHTTPRequestHandler, HTTPServer from urllib.parse import urlparse import json class RequestHandler(BaseHTTPRequestHan...
import sys import webbrowser if len(sys.argv) < 2: sys.exit(0) youtube = 'https://www.youtube.com/results?search_query=' it = '+'.join(sys.argv[1:]) webbrowser.open(youtube + it)
from django import forms from . import models class formcreate(forms.Form): sno = forms.IntegerField() name = forms.CharField() testtext = forms.URLField(widget=forms.Textarea) class modelFormcreate(forms.ModelForm): class Meta: model=models.User fields = "__all__"
import unittest import os from utils.rbag.joints import JointsBagLoader, JointsBagSaver from utils.pdt.trajectory import PtpTrajectory class Test(unittest.TestCase): def test_loadJoints(self): loader = JointsBagLoader() loader.read(os.path.dirname(os.path.realpath(__file__)) + "/ptp-traject...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import load_library from tensorflow.python.platform import resource_loader greedy_assignment_ops = load_library.load_op_library( resource_loader.get_path_to_datafile('_gree...
#!/usr/bin/env python """ Project_Name: main, File_name: master_alt_mpi Aufthor: kalabharath, Email: kalabharath@gmail.com Date: 3/03/18 , Time:10:05 AM """ # sys.path.append('../../main/') import argparse import time import traceback from mpi4py import MPI from ranking.NoeStageRank import * import alt_smotif_searc...
# This sample tests assignment expressions used within # arguments import collections class NearestKeyDict(collections.UserDict): def _keytransform(self, key): a = len(candidate_keys := [k for k in sorted(self.data) if k >= key]) # This should generate an error because walrus operators #...
from flask_restful import Resource, Api, reqparse, abort from flask import Response from Logger.Control import global_control import datetime, time, json, requests, redis # # SuperClass. # ---------------------------------------------------------------------------- class Log_Control(object): __controller = None ...
# Your company delivers breakfast via autonomous quadcopter drones. And something # mysterious has happened. # Each breakfast delivery is assigned a unique ID, a positive integer. When one of # the company's 100 drones takes off with a delivery, the delivery's ID is added # to a list, delivery_id_confirmations. When...
# encoding:utf-8 import os import shutil import struct import binascii import pdb class Baidu(object): def __init__(self, originfile, txt_file): self.originfile = originfile self.lefile = originfile + '.le' self.txtfile = txt_file self.buf = [b'0' for x in range(0, 2)] self...
from networkn import NdexGraph def create_two_egfr(): G = NdexGraph() n1 = G.add_named_node('EGFR') n2 = G.add_named_node('X1') n3 = G.add_named_node('X2') G.add_edge_between(n1,n2) G.add_edge_between(n1,n3) n4 = G.add_named_node('EGFR') n5 = G.add_named_node('Y1') n6 = G.add_nam...
#!/usr/bin/env python # RADIOLOGY --------------------------------------------------- # This is an example script to upload images to Google Storage # and MetaData to BigQuery. Data MUST be de-identified import os # Start google storage client for pmc-stanford from som.api.google.bigquery import BigQueryClient as Cl...
from time import time import warnings import os import subprocess from DataHelper import ConfigManager import cv2 import numpy as np from math import sqrt import tensorflow as tf from scipy import interpolate def getTFsess(): return tf.Session(config=tf.ConfigProto(gpu_options=tf.GPUOptions(allow_growth=True))) ...
#numbers=["3","34","64"] """ for i in range(len(numbers)): numbers[i]=int(numbers[i]) numbers[2]=numbers[2]+1 print(numbers[2]) """ #it is very lengthy #so here we use map , for loop ki jgh pr """numbers=list(map(int,numbers)) numbers[2]=numbers[2]+1 def sq(a): return a*a num=[2,3,4,5,6,7] square=...
# ************************************************************************** # Author: João V. Tristão # Date: 16/12/2019 # Problem: Digit factorial chains # Approach: # - Brute force # # ************************************************************************** import numpy as np import math as mt def fact_sum...
try: from django.conf.urls.defaults import patterns, url except ImportError: from django.conf.urls import patterns, url urlpatterns = patterns("notification.views", url(r"^settings/$", 'notice_settings', name="notification_notice_settings"), url(r"^mark_seen/(?P<notice_id>\d+)/$", 'mark_seen', name="n...
#TRON by Taylor Poulos #AndrewID: tpoulos #email: poulos.taylor.w@gmail.com #Created in Nov-Dec 2012 #15-112 Term Project #These functions create the cycles on the board #################### #IMPORTS #################### import pygame from pygame.locals import * import config import random #################### #Game...
import tarfile import os with tarfile.open('/opt/bacnobackup/backup.sql.tar.gz', "w:gz") as tar: tar.add('/opt/bancodump/backup.sql', arcname=os.path.basename('/opt/bancodump/backup.sql'))
import tables class EventIndex(tables.IsDescription): """An IOTile Stream (timeseries data).""" timestamp = tables.Int64Col() event_id = tables.Int64Col() event_index = tables.Int64Col()
import zmq import time import socket import struct class TokenBucket(object): """An implementation of the token bucket algorithm from http://code.activestate.com/recipes/511490-implementation-of-the-token-bucket-algorithm/ >>> bucket = TokenBucket(80, 0.5) >>> print bucket.consume(10) True >>> pr...
from flask import url_for from flask import render_template from flask import Flask from flask import request from flask import redirect from flask import session from flask import g import sqlite3 from flask import flash DATABASE = "blog.db" app = Flask(__name__) app.secret_key = b'7H{&\xa3\x92\...
import os from flask import request, Blueprint, make_response from sqlescapy import sqlescape from bcrypt import checkpw import jwt from ..models import db, User from util import have login_routes = Blueprint('login', __name__) @login_routes.route('/login', methods=['POST']) def login(): data = request.json ...
from flask import Flask, render_template, redirect, request, flash app = Flask(__name__) app.secret_key= 'sfljk32fn' @app.route('/') def index(): return render_template("index.html") @app.route('/process', methods=['POST']) def create_user(): print "Got User" name=request.form['namey'] location=reque...
#!/usr/bin/python cols = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'] cols1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] txt = open("color.htm", "w") txt.write("""<html> <head><title>Color Chart</title></head> <body> <center><h1>Color Chart</h1></center><br><br...
# token_services/token_services.py #import sys import random from itsdangerous import URLSafeTimedSerializer #from myApp import app def generate_confirmation_token(parWhat): #MAIL_userName = os.environ['APP_MAIL_userName'] #MAIL_PASSWORD = os.environ['APP_MAIL_PASSWORD'] #secret_key=app.config['SECRET_KEY...
from zipfile import ZipFile import shutil, json, os import tempfile import lib.filewalker import lib.interpreter import subprocess class KuanzaProto: def __init__(self, zipfile): self.zipfile = zipfile zip = ZipFile(zipfile) self.zip = zip self.info = json.loads( zip.read( 'prototyp...
#!/usr/bin/python import time import csv import bluetooth import os, sys import datetime import smtplib import string import select from pprint import pprint class MyDiscoverer (bluetooth.DeviceDiscoverer) : def pre_inquiry (self): self.done = False def device_discovered(self, address, device_class, n...
import os import re import pydantic from ansible_collections.nhsd.apigee.plugins.module_utils.models.manifest.manifest import ( Manifest, ) def correct_namespace(name, api_name, env_name) -> bool: """ Checks that a name of a thing we want to create in Apigee matches our namespacing conventions. e.g. ...
# File requires working python.pcl import os import sys import glob from math import isclose import numpy as np import skimage.io as io from skimage.viewer import ImageViewer from skimage.viewer.canvastools import RectangleTool import matplotlib.pyplot as plt relative_utils_path = '../../../utils' utils_path = os....
import subprocess, shutil, io, os import pandas def run_one(*, Tstar, segment_density, chain_length): if not isinstance(Tstar, float): Tstar = float(Tstar) # Build the chain import chain_builder as cb; cb.build_chain(segment_density=segment_density, Nchains=320, chain_length=chain_length, ofname=...
import requests import os import urllib import urllib2 from sendmail import send_mail_function from flask import Flask, render_template, request app = Flask(__name__) @app.route('/') def index(): return "Email Service Active" @app.route('/test') def test(): send_mail_function("jplservice00@gmail.com", "Test ema...
vowel=["a","e","i","o","u"] for i in vowel: word=i for j in vowel: word+=j print (word)
from PyQt4 import QtGui, QtCore class AddStationDialog(QtGui.QDialog): def __init__(self, parent): QtGui.QDialog.__init__(self) self.signal = "addstation" # parent.setEnabled(False) self.setParent(parent) self.radio_name = QtGui.QLineEdit() self.radio_adress = QtGui.QLineEdit() self.radio_name.setPlac...
''' Created on Sep 29, 2014 @author: mendt ''' import unittest, logging, time from georeference.settings import DBCONFIG_PARAMS from georeference.utils.tools import loadDbSession from georeference.georeferenceupdate import runningResetJobs, runningNewJobs, runningUpdateJobs, lookForUpdateProcess from vkviewer.python....
import sys from django.http import JsonResponse from django.views import View from django.db.models import Sum, Q from .models import Product, ProductSize, Image, ProductContent, Category, Country class ProductCategories(View): def get(self, request): result = { 'categories' : [ { ...
import torch.nn.functional as F import torch.nn as nn import torch import numpy from locked_dropout import LockedDropout class LayerNorm(nn.Module): def __init__(self, features, eps=1e-6): super(LayerNorm, self).__init__() self.gamma = nn.Parameter(torch.ones(features)) self.beta = nn.Pa...
import os BASE_URL = "https://api.setlist.fm/rest/1.0" API_BASE = 'https://accounts.spotify.com' REDIRECT_URI = "http://localhost:5000/api_callback" SCOPE = 'playlist-modify-private,playlist-modify-public,user-top-read' API_KEY = os.environ.get('SETLIST_API_KEY') SPOTIFY_CLIENT_ID = os.environ.get('SPOTIFY_CLIENT_ID...
import struct from common.exception import MessageHeaderError from common.constants import ERR_MSG_HDR_BAD_MSG_LEN class KeepAlive(object): MSG_KEEPALIVE = 4 @staticmethod def parse(msg): if len(msg) == 0: raise MessageHeaderError(sub_error=ERR_MSG_HDR_BAD_MSG_LEN,data='') @stat...
print("rajeev", 5) # separator between arguments, end can change print ending print("rahul ", " king", sep="@", end="") print(" and great") # input function # returns string of characters name = input("Enter your name : ") print(name) year = input("In what year were you born? ") print(type(year)) # use split() met...
class Drone(object): """Drone Virtual representation of a drone bot to help with logic processing. """ states = [ 'Idle', duration 'Deploying', complete duration 'Searching', tracking duration 'Relocating' duration 'Attacking', duration distance prey_tracker_state capture...
import pygame ''' @class Sprite @abstract ''' class Sprite: ''' Constructor. ''' def __init__(self): pass ''' Draw this Sprite. @param Surface screen ''' def onDraw(self, screen): pass ''' Execute a single step for this Sprite. ''' def onStep(self): pass
import copy import random class Assembler(): def __init__(self,fragments): self.fragments = {} for idx, fragment in enumerate(fragments): self.fragments[idx] = list(fragment) def _fragment_matcher(self, top_fragment, bottom_fragment): ''' compares two fragments and...
# # Converted to Python by Eric Shen <ericshen@berkeley.edu> # # import cv2 import numpy as np import os import argparse import logging log_format = '%(created)f:%(levelname)s:%(message)s' logging.basicConfig(level=logging.DEBUG, format=log_format) # log to file filename='example.log', TAG = "laplace-recog:" def m...
from __future__ import print_function from __future__ import division import sys import time import numpy as np import tensorflow as tf from tensorflow.contrib.rnn import BasicLSTMCell, GRUCell import properties as p class ModelSentiment(): def __init__(self, word_embedding=None, max_input_len=None, using_c...
# Generated by Django 2.2.3 on 2019-08-19 19:03 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blacklist', '0003_auto_20190813_1039'), ] operations = [ migrations.AddField( model_name='modelblacklist', name='end...
# stdlib from typing import Optional # relative from .....common.message import ImmediateSyftMessageWithoutReply from .....common.serde.serializable import serializable from .....common.uid import UID @serializable(recursive_serde=True) class RegisterChildNodeMessage(ImmediateSyftMessageWithoutReply): __attr_all...
# # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # """ Base class for remote file shares. """ import logging from abc import ABCMeta, abstractmethod from typing import Any, Dict, Optional from mlos_bench.services.base_service import Service from mlos_bench.services.types.fileshare_type impo...
# girilen iki sayının en küçük ortak katını bulacak. # "... ve ... sayılarının EKOKu = ...." şeklinde sonucu söyleyecek. # İPUCU : önce iki sayıdan hangisinin daha küçük olduğunu bulup, ordan başlanabilir. sayı1 = int(input("bir sayı giriniz")) sayı2 = int(input("bir sayı daha giriniz")) sayac = 0 kucuksayı = 0 buyuk...
from pymata_aio.constants import Constants from Lib import Leonardo import sys import time board = Leonardo.Leonardo() SERVO_PIN = 10 def setup(): board.servo_config(SERVO_PIN) board.sleep(0.2) board.analog_write(SERVO_PIN, 0) board.sleep(0.5) def loop(): print("Servo sweep ( 0 to 180 degr...
import pytest from polyglotdb import CorpusContext def test_generate_hierarchy(acoustic_config): with CorpusContext(acoustic_config) as c: h = c.generate_hierarchy() assert (h._data == c.hierarchy._data) def test_generate_hierarchy_subannotations(subannotation_config): with CorpusContext(su...
import unittest from entity.manufacturer import Manufacture class ManufactureTestCase(unittest.TestCase): def setUp(self) -> None: self.manufacture = Manufacture() self.name = "Lol" def test_name(self): self.manufacture.set_name(self.name) self.assertEqual(self.name, self.manu...
#!/usr/local/bin/python3 import unittest from report_processor import ReportProcessor # Full integration test that runs the latest two reports. # class IntegrationTest(unittest.TestCase): def test1(): url = "http://reports.ieso.ca/public/TxLimitsOutage0to2Days" reportProcessor = ReportProcessor(url) ...
from typing import Callable from random import choice class Board: """Tic-Tac-Toe board""" __board: [str, ...] = ['_', '_', '_', '_', '_', '_', '_', '_', '_'] wins_combinations: ((int, int, int), ...) = ( (0, 1, 2), (3, 4, 5), (6, 7, 8), # row...
# --*-- coding : utf-8 --*-- # Project : python_lemon_作业 # Current file : lemon_190920_作业.py # Author : 大壮 # Create time : 2019-09-20 22:14 # IDE : PyCharm # TODO 成长很苦,进步很甜,加油! import openpyxl # 第一:excel类封装需要提供以下功能: # 1、选择表单功能 # 2、读取一个单元格的数据功能 # 3、读取一行数据 功能 # 4、读取表单中所有数据功能 # 5、往单元格中写入数据功能 # 6、保存数据...
from datetime import timedelta from unittest.mock import Mock import visiology_py.datacollection as dc from visiology_py.decorators import cached, retried, decorate_api def exp(x: int) -> float: return float(0.1 * (2 ** x)) decorate_api( dc.ApiV2, retried(max_tries=1, timeout_function=exp), ) def tes...