text
stringlengths
38
1.54M
def missingWords(s, t): sequence = t.split(' ') idx = 0 ans = [] for w in s.split(): if idx < len(sequence) and w != sequence[idx]: ans.append(w) elif idx > len(sequence): ans.append(w) else: idx += 1 return ' '.join(ans) #print(missi...
#@+leo-ver=5-thin #@+node:pap.20041006184225: * @file old_plugin_manager.py """ A plugin to manage Leo's Plugins: - Enables and disables plugins. - Shows plugin details. - Checks for conflicting hook handlers. - Checks for and updates plugins from the web. """ # This plugins has been disabled until it can be rewritte...
#!/usr/bin/env python def build(bld): bld.recurse('hsp cliutils ioutils strutils zutils stdiowrap')
import cv2 as cv import numpy as np from pynput.mouse import Button,Controller import wx import imutils #from imutils.video import WebcamVideoStream from imutils.video import FPS mouse = Controller() app = wx.App(False) (width, height) = wx.GetDisplaySize() (camx,camy) = (320,240) #camera = WebcamVideoStream(src=0).s...
# KivyMD libraries from kivymd.app import MDApp from kivymd.toast import toast from kivymd.uix.bottomsheet import MDCustomBottomSheet from kivy.lang import Builder from kivy.uix.screenmanager import Screen from kivymd.uix.snackbar import Snackbar # kivy libraries from kivy.factory import Factory # External libraries ...
#!/usr/bin/env python3 # # MIT License # # Copyright (c) 2021 Andrei Rabusov # Derived from matplotlib.animation example for double pendulum # # This script animates (x, t) plot for 1D potential well with # pi x # U (x) = V_0 tg**2 (-----) # 2 a # # Change line No. 34 from E =...
import csv puzInput = list(csv.reader(open('input', 'rb'), delimiter='\t')) checksum = 0 for row in puzInput: for dividend in row: for divisor in row: if ( int(dividend)%int(divisor) == 0 ) and ( int(dividend) != int(divisor) ): print "Found it: %d/%d = %d" %(int(dividend), i...
from Transition import Transition import timeit class ValueIterationSolver: states = {} transitions: dict = {} actions = [] last_run_duration = 0 last_run_v_function = {} last_run_policy = {} initial_v = None def __init__(self, actions_available, states, transitions, initial_v = None)...
#! /usr/local/bin/python3 import unittest, run class TestScript(unittest.TestCase): def test_password_practice(self): self.assertEqual(run.password_practice("testing", "password"), True) self.assertEqual(run.password_practice("testing", "testing"), True) self.assertEqual(run.password_pr...
from django.shortcuts import redirect, render from .models import Post #from models file in current package from .models import Bill #from models file in current package from users.models import Profile from django.contrib.auth.models import User from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTest...
import socket sock = socket.socket() sock.bind(("", 14900)) while True: sock.listen(3) conn, addr = sock.accept() data = conn.recv(16384) user_data = bytes.decode(data) print("Data: " + user_data) conn.send(b"Hello!\n" + b"Your data: " + str.encode(user_data))
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-08-26 12:03 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('joan', '0004_auto_20170826_1158'), ] operations = [ migrations.AlterModelOptions( ...
HEIGHT = 61 def test_cnn(): import torch from models.basic import BidirectionalRNN, CNN import torch.nn as nn cnn = CNN(nc=1) pool = nn.MaxPool2d(3, (4, 1), padding=1) batch = 7 y = torch.rand(batch, 1, HEIGHT, 1024) a, b = cnn(y, intermediate_level=13) new = cnn.post_process(pool...
from django.shortcuts import render, HttpResponse # Create your views here. def index(request): return render(request, 'index.html') # return HttpResponse("this is home page") def about(request): return render(request, 'about.html') #return HttpResponse("we are nothing but everything") def book...
# Generated by Django 3.1.3 on 2020-11-21 02:33 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('loja', '0004_auto_20201120_2317'), ] operations = [ migrations.RemoveField( model_name='produto', name='parcelamento', ...
#Daniel Ogunlana #23/09/2014 #Assignment Statement Spot Check shape_Width= int(input("Please enter the Width of the shape:")) shape_Length= int(input("Please enter the Length of the shape:")) shape_Depth= int(input("Please enter the Depth of the shape:")) mainSectionVolume= shape_Width*shape_Length*shape_Dept...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Dec 31 16:29:31 2015 @author: weindel """ from __future__ import division import os #handy system and path functions from psychopy import core, visual, event, gui, data, monitors import psychopy.logging as logging from datetime import datetime import cs...
# -*- 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 db import database from sqlalchemy.exc import IntegrityError import scrapy from scrapy.pipelines.images import ImagesPipe...
# 鸢尾花识别 成功率预测 饼图展示 # 机器学习基础知识 通过最近距离进行数据分类 import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.spatial.distance import euclidean from sklearn.model_selection import train_test_split data_path = 'C:\\Users\\shine小小昱\\Desktop\\data_ai\\Iris.csv' save_path = 'C:\\Users\\shine小小昱...
# Use UniverseManager to find symbols from the Universe Selection for universe in self.UniverseManager.Values: # User defined universe has symbols from AddSecurity/AddEquity calls if universe is UserDefinedUniverse: continue symbols = universe.Members.Keys
# -*- coding:utf-8 -*- # Modified from https://github.com/tylerneylon/explacy import io from collections import defaultdict from pprint import pprint from phrasetree.tree import Tree def make_table(rows, insert_header=False): col_widths = [max(len(s) for s in col) for col in zip(*rows[1:])] rows[0] = [x[:l] ...
import numpy as np import autoarray as aa class TestNoiseMapFromWeightMap: def test__weight_map_no_zeros__uses_1_over_sqrt_value(self): weight_map = aa.array.manual_2d([[1.0, 4.0, 16.0], [1.0, 4.0, 16.0]]) noise_map = aa.data_converter.noise_map_from_weight_map( weight_map=weight_map....
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField, SubmitField from wtforms.validators import DataRequired, EqualTo, Email, Length ,ValidationError from app_package.models import User import pyotp class RegisterForm(FlaskForm): username = StringField("username", validators...
import turtle from tkinter import messagebox, simpledialog, Tk if __name__ == '__main__': window = Tk() window.withdraw() print("Noah,Andrew,Shivam") num = simpledialog.askstring("Enter a student name", None) if num == ("Shivam"): print("He thinks that Java and Python are cool!") elif num == ("Noah"): p...
# -*- coding: utf-8 -*- from odoo import models, fields, api class City(models.Model): _name = 'oe.city' _description = u'城市' pid = fields.Many2one('oe.province', string='省份') name = fields.Char('名称', requried=True) child_ids = fields.One2many('oe.district', 'pid', string='区') @api.model_...
import time import math from datetime import datetime, timedelta from model.models import VarConfig as VarConfigModel, VarConfigSchema, db import random try: import FaBo9Axis_MPU9250 rasp = True except: rasp = False class Accelerometer(): def __init__(self, socketio): self.runit = False self.socketio = socke...
#!/usr/bin/env python # -*- coding: utf-8 -*- from distutils.core import setup setup(name='django-development-utils', version='0.1', author='Steingrim Dovland', author_email='steingrd@ifi.uio.no', url='http://prettyprinted.net/code/django-development-utils/', packages=['development_utils...
import cv2 import numpy as np # sobel def Sobel(image): image = cv2.imread(path, 0) grad_x=cv2.Sobel(image,cv2.CV_16S,1,0) grad_y=cv2.Sobel(image,cv2.CV_16S,0,1) gradX=cv2.convertScaleAbs(grad_x) gradY=cv2.convertScaleAbs(grad_y) cv2.imshow("grad_x",gradX) cv2.namedWindow('grad_y', 0) ...
#!/usr/bin/env python # coding: utf-8 from Engine.Indexer import Indexer from utils.docreader import DocumentStreamReader from utils.utils import save_obj import sys import traceback COUNT_OF_FILES = 40 def get_reader(): reader = DocumentStreamReader(sys.stdin) return reader def create_indexes(encoding): ...
#!/usr/bin/env python # -*- coding=utf-8 -*- # #import sys #sys.path.append('C:\\Users\\lutomlin\\Dropbox\\Personal\\LalBot') #from lalbot_fake import LalBot from LalBot.lalbot import LalBot from pprint import pprint import time import datetime import threading import random #from citacards import CitaData from Citadel...
""" Given a string s. An awesome substring is a non-empty substring of s such that we can make any number of swaps in order to make it palindrome. Return the length of the maximum length awesome substring of s. Example 1: Input: s = "3242415" Output: 5 Explanation: "24241" is the longest awesome substring, we can form ...
import demistomock as demisto from CommonServerPython import * import json import traceback from typing import Any, Dict def get_entry_context(domains, is_single) -> Dict[str, Any]: urls_to_return = [] if is_single: if domains.startswith('http://') or domains.startswith('https://'): # NOSONAR ...
from django.apps import AppConfig class HeaderPluginConfig(AppConfig): name = 'header_plugin'
import scipy as sp import glob import os, sys, time # Get arguments experiment_dir = sys.argv[1] experiments_file = sys.argv[2] # Get list of timepoints f = open(experiments_file) atoms = f.readline().split() timepoint_names = atoms[2:] f.close() # Load unique seqs into memory experiment_unique_seqs_file = '%s/uniqu...
from flask_wtf import FlaskForm from wtforms import StringField, SubmitField, HiddenField, SelectField, BooleanField from wtforms.validators import DataRequired, Regexp class SignUpForm(FlaskForm): loan_id = HiddenField() gender = SelectField("Gender: ", choices=[('Male', 'Male'), ('...
#!/usr/bin/env python import optparse from rasmus.common import * o = optparse.OptionParser() o.add_option("-t", "--type", default="points") o.add_option("-b", "--buckets", default=20, type="int") conf, args = o.parse_args() if len(args) == 0: infile = sys.stdin else: infile = args[0] data = util.read_deli...
import os from flask import ( Flask, flash, render_template, redirect, request, session, url_for) from functools import wraps from flask_pymongo import PyMongo from bson.objectid import ObjectId from werkzeug.security import generate_password_hash, check_password_hash if os.path.exists("env.py"): import en...
# coding: utf-8 import re from BeautifulSoup import BeautifulSoup regex_cache = {} def search(text, regex): regex_cmp = regex_cache.get(regex) if not regex_cmp: regex_cmp = re.compile(regex) regex_cache[regex] = regex_cmp return regex_cmp.search(text) VALID_TAGS = { 'blockquote': {}...
# -*- coding: utf-8 -*- """ Created on Wed Jul 17 11:10:02 2019 @author: jjohns """ import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import os import openbabel as ob import multiprocessing as mp import time import matplotlib.pyplot as plt #SKlear...
""" ## Question : Easy ### 231. [Power of Two](https://leetcode.com/problems/power-of-two/) Given an integer, write a function to determine if it is a power of two. Example 1: Input: 1 Output: true Explanation: 20 = 1 Example 2: Input: 16 Output: true Explanation: 24 = 16 Example 3: Input: 218 Output: falseOutput: ...
import unittest import rocksdb class TestFilterPolicy(rocksdb.interfaces.FilterPolicy): def create_filter(self, keys): return b'nix' def key_may_match(self, key, fil): return True def name(self): return b'testfilter' class TestMergeOperator(rocksdb.interfaces.MergeOperator): ...
from django.urls import path from django.contrib.auth import views as auth_views from .views import DonorCreateView, DonorDetailView, DonorListView, DonorDeleteView, DonorUpdateView, RecipientCreateView, RecipientDetailView, RecipientListView, RecipientDeleteView, RecipientUpdateView, SignUpView app_name = 'users' ur...
import functools from blessed import Terminal from application.ascii_box import Double, Heavy from application.ascii_drawing import DrawingChar from application.dungeon import Character, Dungeon, Item, Room from application.menu import Button, DungeonEngine, Menu, MessageBox, TextUI def setup_dungeon() -> Dungeon: ...
from django.db import models class Tree(models.Model): ''' Уникалния номер на всяко дърво се образува както следва: - идентификатора на имота в който е дървото + - пореден номер от 1 до 999 за този имот ''' tree_uid = models.CharField(max_length=48, unique=True, help_text='') tree_sp_bg...
# Generated by Django 3.0 on 2020-10-26 09:26 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('lib', '0013_auto_20201026_1416'), ] operations = [ migrations.RenameField( model_name='brecord', old_name='idate', ...
from django.conf.urls import url from blog.views import BlogPosts from blog.models import Post urlpatterns = [url(r'^$', BlogPosts.as_view(model = Post, template_name = 'blog/blog.html'))]
SPELLS_GROUP_ID = 1 BUFFS_GROUP_ID = 2 DEBUFFS_GROUP_ID = 3 TRIGGER_GROUPS_KEY_NAME = 'TriggerGroups' trigger_groups = [ { 'Comments': '', 'EnableByDefault': False, 'GroupId': SPELLS_GROUP_ID, 'Name': 'Spells', 'SelfCommented': False, TRIGGER_GROUPS_KEY_NAME: [ ...
import os,sys,glob datain = sys.argv[1] front = 28477797 #6:28477797-33448354 1725 6:1725:A:G def main(): vcfin = open(datain,"r") vcfout = open(datain.replace(".vcf","_Change.chr.pos.ID.vcf"),"w") while 1: line = vcfin.readline() if line[0] =="#": vcfout.write(line) ...
import sys, os, inspect import numpy as np from scipy.io import loadmat from scipy import optimize import pandas as pd import idx2numpy import matplotlib from matplotlib import pyplot as plt import matplotlib.image as mpimg from matplotlib.image import NonUniformImage from matplotlib import cm plt.style.use('ggpl...
import numpy as np class RNN: def __init__(self, genotype): # dimensions self.n_input = genotype.n_input self.n_hidden = genotype.n_hidden self.n_output = genotype.n_output self.n_net = genotype.n_net # weights self.W = genotype.W # threshold and noi...
#!/usr/bin/python import re from bs4 import BeautifulSoup from robobrowser import RoboBrowser browser=RoboBrowser(history=True) f=open('PDB114set.csv', 'r').readlines()[1:] ids=[(line.split("\t")[15][:4].lower(), line.split("\t")[16]) for line in f] out=open('pdbcoverages.txt', 'w') for id in ids: print id url='ht...
from django.http import HttpResponse from django.views.generic import CreateView from django.views.generic.list import ListView from django.views.generic import DeleteView, UpdateView from .models import Booklist from django.urls import reverse_lazy def index(request): return HttpResponse("Hello, world. You're at...
import numpy as np from robot1 import robot from pprint import pprint as prnt import random import pdb #import pdb import copy from time import clock from time import sleep ini_pose = dict(x=15,y=-20,orientation=0) ini_noise = dict(new_f_noise=0.5, new_t_noise=2*np.pi/180, new_d_noise...
def findMin(nums): """ :type nums: List[int] :rtype: int """ le, ri = 0, len(nums) - 1 while le <= ri: if nums[le] <= nums[ri]: return nums[le] mid = (le + ri) / 2 if nums[mid] < nums[ri]: ri = mid else: le = mid + 1
"""Neural Machine Translation.""" import theano import theano.tensor as T import numpy as np import sys reload(sys) sys.setdefaultencoding('utf8') import codecs import argparse import logging from model import save_model, load_model, get_pretrained_embedding_layer from bleu import get_bleu from data_utils import prepa...
from testing_framwork.fw_log.fw_metrics import metric_decorator class TestObj: def __init__(self): self.name = "bob" @metric_decorator.fw_metric def call_get_my_new_name(self): print("In my method") return self.name test = TestObj() test.call_get_my_new_name()
from django import forms from .models import Question,Choice from groups.models import Group, GroupMember class QuestionForm(forms.ModelForm): choice1 = forms.CharField(label='Choice 1') choice2 = forms.CharField(label='Choice 2') class Meta: model = Question fields = ['group','question_text','choice1','choic...
from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.api import users from google.appengine.ext import db from google.appengine.api import mail from auth import getauth,OAuth,OAuthCallback,OAuthLogout import tweepy import diff import refresh class Main...
# Generated by Django 2.1.1 on 2018-10-13 16:20 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('users', '0002_account_country_code'), ] operations = [ migrations.RemoveField( model_name='account', name='country_code', ...
from __future__ import unicode_literals from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token from django.db import models from django.contrib.auth.models import User class Questions(models.Model): cre...
import uuid import structlog from casualty.casualty_logger import configure_structlog from casualty.constants import HTTP_REQUEST_HEADER class FlaskCorelationMiddleWare(object): """ If request_id header is present bind it to logger else create an ew request_id and bind it to logger It uses structlog...
#!/usr/bin/python import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) PIR_PIN = 12 GPIO.setup(PIR_PIN, GPIO.IN) try: while True: if GPIO.input(PIR_PIN): print 'Motion Detected!' time.sleep(1) except KeyboardInterrupt: print 'Quit' GPIO.cleanup()
from directkeys import DIPressKey,DIReleaseKey,SPACE,A,W,D,X from tkinter import Tk, Label, StringVar, OptionMenu, messagebox from win32gui import GetWindowText, GetForegroundWindow from multiprocessing import Process, Value, freeze_support from pynput import keyboard import time import random import sys #global varia...
import os import re import argparse import pandas as pd from bs4 import BeautifulSoup def lyrics2csv(path, output): ''' Extracts the pure lyrics from all htmls in path and returns a csv file with artist name, song title and lyric. The htmls have to be saved in a separate folder (path) with the following sy...
myList = [0,50,100,205,206,209,210,211,215] available = [] m = max(myList) for i in range(0, max(myList)+1): if i in myList: pass else: available.append(i) print available
def Create_Directory(path): import os folder = os.path.exists(path) if not folder: os.makedirs(path) return True else: return False
bris=int(input()) s1=int(input()) c1=int(input()) if(c1==1): c1=11 elif(c1==3): c1=float(10.5) s2=int(input()) c2=int(input()) if(c2==1): c2=11 elif(c2==3): c2=float(10.5) if s1==s2: if c1>c2: print("VINCE GIOCATORE 1",end="") else: print("VINCE GIOCATORE 2",end="") elif s2!=...
'''The idea here is to only use one enemy class and make them highly extensible/variable based on what they get for adjectives, nouns, and verbs. Color will add even more variety. The best part about this, is that a matching label class can be made to modify the single enemy class instead of creating new enemies fo...
# 4. Программа принимает действительное положительное число x и целое отрицательное число y. # Необходимо выполнить возведение числа x в степень y. Задание необходимо реализовать в виде функции my_func(x, y). # При решении задания необходимо обойтись без встроенной функции возведения числа в степень. # Подсказка: попро...
import sys import os import time configPath = os.path.join(os.path.expanduser('~'), '.autopullconfig') config = { 'username': '', 'password': '', 'repo': '', 'proj': '', } try: with open(configPath, 'r') as CONFIG: for line in CONFIG.readlines(): configItems = line.strip().spli...
#! /usr/bin/env python """Collection of different output functions""" import sys class DataOutput(object): """Output class to handle output of data""" def __init__(self, out_filename=None, print_to_console=True): self.out_file = None self.out_filename = None self.change_file(out_filename) self.print_to_con...
from GUI import GUI from HAL import HAL # Enter sequential code! import cv2 import numpy as np while True: frame = HAL.getImage() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray, (30, 30), 0) #Otsu's Thresholding ret, th = cv2.threshold(blur, 0, 255,cv2.THRESH_BINAR...
import numpy as np import math import tools import time import MLS_2d_eval import mls_2d import traceback def speed_test(): eval_nodes = np.array([ np.array([np.random.randn(1)[0],np.random.randn(1)[0]]) ]) #np.random.randn(1) interval = [-1,1] interval_str = str(interval) file1 = open('./t...
import matplotlib.pyplot as plt import tensorflow as tf from tensorflow import keras import numpy as np import load_data import pathlib tf.enable_eager_execution() def make_model(base_model, dim_new, channel_axes, img_shape, lr=0.001, batch_size=64, initial_epochs=20, tuning_epochs=20, scheduler=True, ...
from bluffinmuffin.protocol.enums import BluffinMessageIdEnum from bluffinmuffin.protocol.interfaces import AbstractGameResponse from .player_sit_out_command import PlayerSitOutCommand class PlayerSitOutResponse(AbstractGameResponse): def __init__(self, table_id, success, message_id, message, jsonCommand): ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # created on 12:07 am 30.03.20, by Yi Zhang, modifications by Narek Andreasyan ' Explore the properties of the graph from facebook. ' __author__ = 'Yi Zhang' import pickle import matplotlib.pyplot as plt import networkx as nx import numpy as np from helper import timer,...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Aug 23 19:10:39 2018 @author: farzam reference: Python Machine Learning by: Sebastian Raschka & Vahid Mirjalili """ import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn.metrics import accuracy_score from sklearn.mod...
# Look for #IMPLEMENT tags in this file. These tags indicate what has # to be implemented to complete the warehouse domain. # You may add only standard python imports---i.e., ones that are automatically # available on TEACH.CS # You may not remove any imports. # You may not import or otherwise source any o...
from flask_wtf import Form from wtforms import TextField, TextAreaField class SerieForm(Form): name = TextField('Name') description = TextAreaField('Description') image = TextField('Image URL')
import cv2 import numpy as np import scipy.special from anchors import ANCHOR OBJ_THRES = 0.7 NMS_THRES = 0.4 VARIANCE = [0.1, 0.2] FACE_DIMENSION = [96, 112] TEMPLATE = np.array([[0.34191607, 0.46157411], [0.65653393, 0.45983393], [0.500225, 0.64050536], [0.37097589, 0.82469196], ...
#!/usr/bin/python ####################################################################### ####################################################################### ## Modified from nf-core/nanoseq script on 27th December 2019 ####################################################################### #################...
#!/usr/bin/env python import os import sys import codecs import docreader import pickle from doc2words import extract_words from collections import defaultdict def save_obj(obj, name): with open(name + '.pkl', 'wb') as f: pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL) sys.stdout = codecs.getwriter('utf8')(...
import os import sys import time import math import json import torch import shutil import logging import scipy.misc import torchvision import numpy as np import torch.nn as nn from io import BytesIO import tensorflow as tf from pathlib import Path import torch.optim as optim import torch.nn.init as init import torch.n...
import stdio import sys # Accept as a command-line argument an integer n which is the first 9 # digits of an ISBN. Compute the final digit, and write the complete # ISBN to standard output. # # An ISBN is legal if it consists of 10 digits and # d1 + 2*d2 + 3*d3 + ... + 10*d10 # is a multiple of 11. For example, 0-2...
# Generated by Django 3.1 on 2020-08-23 22:29 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Task', fields=[ ('id', models.AutoField(auto_...
import asyncio import json from time import sleep from openzwave.network import ZWaveController, ZWaveNetwork, ZWaveNode, dispatcher from openzwave.option import ZWaveOption from Firefly import logging, scheduler from Firefly.components.zwave.package_lookup import get_package from Firefly.core.service_handler import ...
import os from django.contrib.auth.models import User from django.db import IntegrityError from django.test import TestCase from TrecApp.models import Researcher, Track, Run, Task from TrecApp.valueExtractor import trec_eval from TrecEval.settings import STATIC_PATH class ResearcherTests(TestCase): def setUp(se...
import pyautogui import time from Quartz import CGWindowListCopyWindowInfo, kCGWindowListOptionOnScreenOnly, \ kCGNullWindowID, kCGWindowListExcludeDesktopElements, CFArrayRef from PIL import Image from resizeimage import resizeimage import math import os import numpy as np screenWidth, screenHeight = pyautogui.size(...
import os from app import create_app app =create_app(os.getenv("APP_SETTINGS")) if __name__ == '__main__': port= int(os.environ.get('PORT',5000)) app.run(host='0.0.0.0', port=port)
#! /usr/bin/python import subprocess import re import sys import time import random import colors import os class MACChanger(object): def __init__(self, mac_addr=None, interface=None): self.is_root() if mac_addr is None: self.newMAC = self.generateMAC() elif self.validateMA...
from collections import defaultdict class PrintTable(object): COLUMN_MARK = '+' COLUMN_SEP = '|' DASH = '-' PADDING = 1 def __init__(self, headers): # type: (List[str]) -> None self.headers = headers self._rows = [] self._col_widths = [] def add_row(self, row...
import os import wget import zipfile import tarfile import h5py data_cache_dir = "./data" DEFAULT_TRAIN_FILE = "fed_cifar100_train.h5" DEFAULT_TEST_FILE = "fed_cifar100_test.h5" ''' The FedCIFAR100 dataset is taken from FedML repository. For more information regarding this dataset, please refer to https://g...
import sys from quadforlss import forecasting as fore from quadforlss import estimator import opentext import numpy as np from matplotlib import pyplot as plt import scipy import pickle def faa(cgg, dercgg): A = dercgg/cgg tot = 1./2. tot *= A**2. return tot if len(sys.argv) == 1: print('...
class Solution(object): def solveNQueens(self, n): """ :type n: int :rtype: List[List[str]] """ def search(pos, _sum, _dif): row = len(pos) if row == n: result.append(pos) else: for col in xrange(n): ...
from Notes.celery import app from public_tools.data_backup import DataBackup @app.task def backup_task(filename,data): backuper = DataBackup() backuper.backup(filename, data)
#!./bin/python # -*- coding: utf-8 -*- # --------------------------------------------------------------------- # Syslog Collector service # --------------------------------------------------------------------- # Copyright (C) 2007-2019 The NOC Project # See LICENSE for details # ----------------------------------------...
import web3 class spaceShipException(Exception): def __init__(self, value): self.value = value def __repr__(self): return repr(self.value) class spaceShip(object): def __init__(self, provider, address, abi): w3 = web3.Web3(web3.Web3.HTTPProvider(provider)) naddr = web3...
from heapq import heappush, heappop class MedianFinder: def __init__(self): """ initialize your data structure here. """ self.left = [] self.right = [] self.lc, self.rc = 0,0 def addNum(self, num): """ :type num: int :rtype: void ...
import itertools as it from nn.neural_net import SimpleNN from sklearn.datasets import fetch_mldata from sklearn.cross_validation import train_test_split import matplotlib.pyplot as plt import numpy as np def stop_training(num_epochs, error): print "num_epochs: %d" % num_epochs print "error: %f" % error ...
from typing import ( Tuple, Type, TYPE_CHECKING, ) from eth_typing import ( BlockIdentifier, Hash32, ) from eth_hash.auto import keccak from eth.rlp.headers import BlockHeader from p2p.exceptions import MalformedMessage from p2p.protocol import ( Command, ) from trinity.protocol.common.mana...