text stringlengths 8 6.05M |
|---|
import argparse
import re
import glob
import os
import numpy as np
import matplotlib.pyplot as plt
import sys
args = dict()
data = dict()
origDir = os.getcwd()
plt.style.use('ggplot')
# plt.style.use('grayscale')
# plt.style.use('fivethirtyeight')
print plt.style.available
numInst = re.compile('Number of Instructio... |
from django.db import models
# Create your models here.
class Store(models.Model):
store_name = models.CharField(max_length=255)
store_address = models.CharField(max_length=255)
store_phone = models.CharField(max_length=255)
store_website = models.CharField(max_length=255)
store_email = models.Cha... |
#!/usr/bin/env python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import A... |
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import tensorflow as tf
import data.climate.window_generator as wg
# https://www.tensorflow.org/tutorials/structured_data/time_series
mpl.rcParams['figure.figsize'] = (8, 6)
mpl.rcParams['axes.grid'] = False
train_df = pd... |
#!/usr/bin/env python
# Rips Roms from the Steam release of Colecovision Flashback
ROMS = [{'OFFSETS': [0x01740, 0x0573F]},
{'OFFSETS': [0x05740, 0x0973F]},
{'OFFSETS': [0x09740, 0x0D73F]},
{'OFFSETS': [0x0D740, 0x1373F]},
{'OFFSETS': [0x13740, 0x1773F]},
{'OFFSETS': [0x17740, 0x1B73F]},
{'OFFSE... |
# import imp modules
import pygame
import tkinter as tkr
from tkinter.filedialog import askdirectory
import os
#creat music player window
musicplayer = tkr.Tk()
#set a tile fow window
musicplayer.title("my player")
# set the screen dimenson of window
musicplayer.geometry('400x350') # use a quote between on d... |
from testutil import *
import numpy as np
import smat # want module name too
from smat import *
import cPickle as pickle
import os,os.path
####################################################
# GLOBAL VARIABLES USED IN EACH TEST (as read-only)
n,m = 123,21
Z,_Z = None,None # Z = numpy.zeros(n,m), _Z = ... |
import xlrd
import math
class node:
def __init__(self,x,y,z,r):
self.x=x
self.y=y
self.z=z
self.r=r
def dist(self,other):
return math.sqrt((self.x-other.x)**2+(self.y-other.y)**2+(self.z-other.z)**2)
def neighbor(self,other):
dist=self.dist(other)... |
import hashlib
import psycopg2
class User:
conn = psycopg2.connect("dbname=projnew user=postgres")
cur = conn.cursor()
success_messages = []
error_messages = []
ALREADY_SIGNED_IN = ["Hey! You're already signed in :)"]
permission_msgs = {"writer": ["Please, sign in before."], "admin": ["You have not enoug... |
import numpy as np
import pylab as P
import ROOT
from ROOT import gROOT
gROOT.ProcessLine(".L /home/mage/PROSPECT/PROSPECT-G4-build/lib/libEventLib.so")
gROOT.ProcessLine(".L /home/mage/PROSPECT/PROSPECT-G4-Sec/include/Output/Event.hh")
histCell=ROOT.TH2D("Cell Ionization Hits","Cell Ionization Hits",14,0,14,10,0,10)
p... |
# -*- coding: utf-8 -*-
# @Author: Fallen
# @Date: 2020-04-19 14:47:28
# @Last Modified by: Fallen
# @Last Modified time: 2020-04-19 14:51:13
# def fib(num):
# if num == 1: return num
# else: num+fib(num-1)
def fib(num):
if num == 1 or num == 2: return 1
else:
return fib(num-2)+fib(num-1)... |
from survy import AnonymousSurvey
#定义一个问题 并创建一个表示调查的AnonymousSurvey对象
question="What language did you first learn to speak?"
my_survey=AnonymousSurvey(question)
#显示问题并存储答案
my_survey.show_question()
print("Enter 'q' to exit \n")
while True:
response=input("Language:\n")
if response=='q':
break
my_sur... |
'''hopfield.py
Simulates a Hopfield network
CS443: Computational Neuroscience
Ethan, Cole, Alice
Project 2: Content Addressable Memory
'''
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display, clear_output
import preprocessing as prep
class HopfieldNet():
'''A binary Hopfield Net... |
def circle_circuit(diameter, pi = 3.14):
result = 2 * diameter * pi
return round(result, 2)
print(circle_circuit(5))
|
# -*- coding: utf-8 -*-
#from distutils.core import setup
from setuptools import setup
setup(
name = "duckdaq",
packages = ["duckdaq", "duckdaq.Filter", "duckdaq.Device", "duckdaq.Display"],
version = "0.1",
description = "Didactic lab software for the LabJack U3-HV",
author = "Ulrich Leutner",
... |
from sqlalchemy.exc import IntegrityError
from psycopg2.errors import UniqueViolation
from functools import partial
from multiprocess import Pool
from sql_utils import make_session_kw, select
from sys import argv
import gc
import utils
import random
from os import path
from glob import glob
import pandas as pd
from job... |
X=int(input())
if (not X % 4 and X % 100) or not X % 400:
print("Високосный")
else:
print("Обычный") |
# -*- coding: utf-8 -*-
"""
Created on Sat May 16 18:03:03 2015
@author: Martin Nguyen
"""
TimeToVFTest = 11
FirstProgressionTarget = 21.0
SecondProgressionTarget = 18.0
ThirdProgressionTarget = 15.0
AgeNottoSurgery = 85
TimenotSideEffect = 2
from TreatmentBlock1Class import TreatmentBlock1
from TreatmentBlock2Class i... |
# -*- coding: utf-8 -*-
__license__ = """
This file is part of **janitoo** project https://github.com/bibi21000/janitoo.
License : GPL(v3)
**janitoo** is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either vers... |
def checker_board(rows,cols):
board=[]
for j in range(0,rows):
row=[]
for i in range(0,cols):
if j%2==0:
if i%2==0:
row+="*"
else:
row+=" "
else:
if i%2==0:
row+=" ... |
import json
import datetime
import time
import os
import dateutil.parser
import logging
import boto3
import re
import pymssql
region = 'us-east-1'
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
ec2 = boto3.resource('ec2', region_name=region)
ec2_client = boto3.client('ec2')
lex_client = boto3.client('lex-... |
# -*- coding: utf-8 -*-
"""Renderer for JSON API v1.0."""
from collections import OrderedDict
from django.core.urlresolvers import reverse
from django.utils.encoding import force_text
from django.utils.six.moves.urllib.parse import urlparse, urlunparse
from rest_framework.renderers import JSONRenderer
from rest_frame... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import cv2
# import numpy as np
import glob
import os
files = glob.glob(sys.argv[1] + '*.png')
if not os.path.exists(sys.argv[1] + '/rgb/'):
os.makedirs(sys.argv[1] + '/rgb/')
for f in files:
image = cv2.imread(f)
image = cv2.cvtColor(image, cv2.COL... |
class IrreversibleData(object):
"""
Some of the code from templates can't be converted
This class saves information about irreversible code
"""
def __init__(self, fileName, lineStart, lineEnd, type, oldValue):
self.lineStart = lineStart
self.lineEnd = lineEnd
self.fileName =... |
import socket, re, itertools, ssl
from os import strerror
from multiprocessing import Pool, Lock, active_children
from time import sleep
global lock
lock = Lock()
class BrutePlugins(object):
def __init__(self,plugin):
self.plugin = plugin
def run(self):
self.donothing = 0
self.s = socket.socket(socket.AF_INE... |
list1 = ['Tom', 'Jim', 'Mary', 'Tom', 'Jack', 'Rose', 'Jim']
if 'Tom' in list1:
print('call him back')
print(set([x for x in list1 if list1.count(x) > 1]))
student = {'Tom', 'Jim', 'Mary', 'Tom', 'Jack', 'Rose', 'Jim'}
student.add(12)
student.remove('Tom')
print(student)
set1 = set('abracadabra')
set2 = set('ala... |
def main():
word=''
count = 0
infile = open('/Users/Python/Desktop/mypython/mypython-4/employees.txt','r')
for line in infile :
count = count + 1
if count == 1:
word = word + line
else:
word = word +':'+line
if (count % 3) == 0 :
word =... |
# Define here the models for your scraped items
#
# See documentation in=
# https=//docs.scrapy.org/en/latest/topics/items.html
import scrapy
class GameBasicInfo(scrapy.Item):
# define the fields for your item here like=
appid = scrapy.Field()
title = scrapy.Field()
developer = scrapy.Field()
pub... |
import math
from collections import OrderedDict
from functools import partial
from typing import Any, Callable, List, Optional, Sequence, Tuple
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn, Tensor
from torchvision.models._api import register_model, Weights, WeightsEnum
from torc... |
# def main(a):
# if a%2 ==0:
# print('偶数')
# else:
# print('奇数')
# main(10)
# def main(a):
# for i in range(2,a):
# if(a % i) == 0:
# print(a,'不是素数')
# break
# else:
# print(a,'是素数')
# break
# main(7)
# import random... |
# baseline3.py
# Author: Neha Bhagwat
from gutenberg.acquire import load_etext
from gutenberg.cleanup import strip_headers
from gutenberg.query import get_etexts, get_metadata
import nltk
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.tree import Tree
from nltk.chunk import ne_chunk
from it... |
from django.contrib import admin
from django.urls import path, include
from rest_framework_swagger.views import get_swagger_view
from django.conf.urls import url, include
schema_view = get_swagger_view(title='Analytica API')
urlpatterns = [
path('admin/', admin.site.urls),
#path('hho/', include('oauth2_pro... |
import argparse
import math
import os
import random
import time
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
import spacy
import torch
import torch.nn as nn
import torch.optim as optim
from torchtext.data import Field, BucketIterator
from torchtext.data.metrics import bleu_scor... |
from .directory_creator import * |
import math
import numpy as np
from matplotlib.pyplot import figure, savefig, show
import full_henon as fh
def norm_vect(vector):
""" Calculate the norm of a vector. """
values = [i*i for i in vector]
return math.sqrt(sum(values))
def inner_vect(vect1, vect2):
""" Calculate the inner product of two ... |
# API to interact with database
from .models import Assignment, Student, Course
from datetime import datetime
from .google_cal_api import *
import pytz
"""
add_student(student_name)
get_student_calendar(student_name)
add_course(course_data, itr)
add_all_courses()
get_list_students()
get_list_courses()
g... |
from api.libs.base import CoreView
from cmdb.models import DataCenter
from django.contrib.auth.models import User
from account.models import UserProfile
from django.db.utils import IntegrityError
class DataCenterView(CoreView):
"""
数据中心视图类
"""
login_required_action = ["get_list", "post_create", "post_... |
import math
"""
XNoderna måste innehålla både nyckel och värde
X Hashtabellen ska vara lagom stor
XNågon krockhantering måste ingå, t ex krocklistor eller probning
AnvändKeyError för att tala om att en nyckel inte finns
X Skriv en egen hashfunktion
Ska klara testning med hashtest.py ovan
"""
class Hashtabell:
def __in... |
# Generated by Django 3.0.5 on 2020-08-13 10:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('authentication', '0003_auto_20200813_0922'),
]
operations = [
migrations.AddField(
model_name='attendance',
name='nu... |
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import sys
def Round(a):
return int(a+.5)
def init():
glClearColor(0.0,1.0,1.0,0.0)
glColor3f(0.0,0.0,1.0)
glPointSize(2.0)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluOrtho2D(0.0,600.0,0.0,600.0)
def setpixel(x,y):
glBegin(GL_POI... |
import tensorflow as tf
import numpy as np
np_load_old = np.load
# modify the default parameters of np.load
np.load = lambda *a,**k: np_load_old(*a, allow_pickle=True, **k)
xy = np.load("./data/boston.npy")
x_data = xy[0][0]
y_data = xy[0][1]
x_test = xy[1][0]
y_test = xy[1][1]
print(x_data.shape)
print(x_test.sha... |
# radix sort
def countingSort(arr, exp):
n = len(arr)
result = [0 for i in range(n)]
count = [0 for i in range(10)]
for i in range(n):
indx = arr[i] // exp
count[indx % 10] += 1
for i in range(1, 10):
count[i] += count[i - 1]
for i in range(n - 1, -1, -1):
ind... |
def lengthOfLongestSubstring(s):
dict1={}
start=0
maxlen=0
len1=0
if s is None or len(s)==0:
return 0
for i in range(len(s)):
if s[i] not in dict1:
dict1[s[i]]=i
elif s[i] in dict1 and dict1[s[i]]>=start:
start=dict1[... |
# Problem statement :
# Start a knight at a corner sq of an otherwise-empty chessboard. Move the knight at random by choosing uniformly from the legal knight-moves at each step. What is the mean number if moves until the knight returns to the starting square?
from random import randint
# Move a knight from (x, y) to ... |
from model.serializer import JSONSerializable
import datetime
from model.dao import DAO
from model.users.users import UserDAO
import uuid
import logging
class Position(JSONSerializable):
def __init__(self):
self.userId = None
self.name = None
self.id = None
"""
def __init__(self... |
import numpy as np
import pandas as pd
import tensorflow as tf
import sys
import os
print(tf.__version__)
class recommender:
def __init__(self, mode, train_file, outdir, test_file=None,
user_info_file=None, program_info_file=None,
batch_size=32, epochs=500,
le... |
# Preprocessing time series data
import pandas as pd
import numpy as np
from tsfresh import extract_features
df = pd.read_csv('complete_df_7.csv')
df.drop('Unnamed: 0', axis=1, inplace=True)
df['stock_open'] = df['stock_open'].astype(float)
# Create aggregate of sales down to product level
aggregate = df.groupby(['sku... |
# Generated by Django 3.1.5 on 2021-01-21 15:33
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Contas',
fields=[
... |
from numpy import *
from numpy.ma import sqrt, cos, sin
from scipy.constants import pi
from pylab import *
import os
class KnnClassifier(object):
def __init__(self, labels, samples):
""" Initialize classifier with training data. """
self.labels = labels # one label for one sample. can be integ... |
"""Module to run the bot. Executes the work() method of bot that executes the endless loop of reading comments and
submissions and replying to them if the match any response.
"""
from bot.worker import work, logger
from util.logger import setup_logger
__author__ = 'MePsyDuck'
if __name__ == '__main__':
setup_logg... |
import tkinter as tk
from PIL import Image
from tkinter import filedialog
root=tk.Tk()
canvas1=tk.Canvas(root, width=300,height=250,bg='azure3',relief='raised')
canvas1.pack()
label1 = tk.Label(root,text='Images to PDF converter',bg='azure3')
label1.config(font=('helvetica',20))
canvas1.create_window(150,60,window=lab... |
from onnx_chainer.functions.activation import convert_ClippedReLU # NOQA
from onnx_chainer.functions.activation import convert_ELU # NOQA
from onnx_chainer.functions.activation import convert_HardSigmoid # NOQA
from onnx_chainer.functions.activation import convert_LeakyReLU # NOQA
from onnx_chainer.functions.activa... |
#encoding=utf-8
import cv2
img = cv2.imread("./images/baboon2.jpg")
(B, G, R) = cv2.split(img)
cv2.imshow("blue", B)
cv2.imshow("green", G)
cv2.imshow("red", R)
merge = cv2.merge([B, G, R])
cv2.imshow("merge", merge)
cv2.waitKey(0)
|
#############################################################################
# Copyright (c) Members of the EGEE Collaboration. 2006-2010.
# See http://www.eu-egee.org/partners/ for details on the copyright holders.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except... |
# -*- coding: latin1 -*-
"""
/***************************************************************************
ChangementViewer
A QGIS plugin
Temporal evolution viewer for statistical calculations
-------------------
begin : 2012-01-06
... |
import os
class Emp:
def __init__(self,Name,Dept):
self.Name = Name
self.Dept = Dept
def show (self):
print (self.Name, self.Dept)
|
import codecs
import json
import os
import time
from datetime import datetime
from ..utils.matches import is_won_match, get_match_id, is_matchmaking
from ..FaceitApi import get_player_matches
from .elo import get_player_info
DATA_DIRECTORY = os.path.join(os.path.dirname(__file__), '..', '..', 'settings')
D... |
# 每次选择偷或不偷
# 通过一个列表维护上层偷或不偷的结果
class Solution:
def rob(self, root: TreeNode) -> int:
def _rob(root):
if not root: return 0, 0 # 偷,不偷
left = _rob(root.left)
right = _rob(root.right)
# 偷当前节点, 则左右子树都不能偷
v1 = root.val + left[1] + right[1]
... |
import os
import json
import matplotlib.pyplot as plt
with open('all_curve.json', 'r') as f:
file = json.load(f)
x1 = file['gamma0.99']['x']
y1 = file['gamma0.99']['y']
x2 = file['gamma1']['x']
y2 = file['gamma1']['y']
x3 = file['gamma0.75']['x']
y3 = file['gamma0.75']['y']
x4 = file['gamma0.50']['x']
y4 = file['... |
import pickle
import matplotlib.pyplot
import numpy as np
import matplotlib.pyplot as plt
from experiment_setup import loadExperimentFile
#Format is [minSwitchingProb,q1_required,q1])
def calcAbsErrors(minSwitchProfile):
absErrors = []
for perModelVector in minSwitchProfile:
for entry in perModelVe... |
"""
Ref:
- https://tools.ietf.org/html/rfc2617
- https://en.wikipedia.org/wiki/Basic_access_authentication
- https://en.wikipedia.org/wiki/Digest_access_authentication
- https://github.com/dimagi/python-digest/blob/master/python_digest/utils.py
- https://gist.github.com/dayflower/5828503
"""
from base64 import b64enc... |
# Arquivo para efetuar as 10000 execuções para testes
import tarefas
import escalonador
from random import randint
for i in range(0, 100, 1):
# Executando pela n vez
print("Executando pela " + str(i+1) + "vez!")
# Definindo a lista para enviarmos ao sistema.
listaTeste = []
# Aleatoriamente crian... |
# -*- encoding:utf-8 -*-
# __author__=='Gan'
# Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
# If such arrangement is not possible,
# it must rearrange it as the lowest possible order (ie, sorted in ascending order).
# The replacement must be in-p... |
import cv2
import numpy as np
import os
import glob
from clize import run
CHECKERBOARD = (6,9)
subpix_criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.1)
calibration_flags = cv2.fisheye.CALIB_RECOMPUTE_EXTRINSIC + cv2.fisheye.CALIB_CHECK_COND + cv2.fisheye.CALIB_FIX_SKEW
objp = np.zeros((1, CHEC... |
def max_num(num1, num2, num3):
if num1 >= num2 and num1 >= num3:
return num1
elif num2 >= num1 and num2 >= num3:
return num2
else:
return num3
print("You're number is: " + str(max_num(3,20,5))) |
import sys
#input parameters
input_string = "mango";
test_string = "goman";
#SOLUTION: This is an O(n) solution on AVERAGE (where 'n' is the length of the LONGER string)
copy_string = 2*test_string;
if ( (input_string in copy_string) and (len(input_string)==len(test_string)) ):
print("ROTATION DETECTED!"); |
from django.db import models
from slugify import slugify
class Tool(models.Model):
name = models.CharField(max_length=500)
slug = models.SlugField(max_length=500)
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.name)
super(Tool, self).save(*args, *... |
import math
import torch
from torch.nn import functional as F
import argparse
import numpy as np
import pickle
import neural_network as nn
from neural_network import tf, tint
from replay_buffer import ReplayBuffer
from envs import AtariEnv
from ram_annotations import atari_dict
parser = argparse.ArgumentParser()
pa... |
from django.urls import path
from . import views
from jobs.views import app
urlpatterns = [
path('',views.myblog,name='myblog'),
path('app/',app,name='app'),
path('<int:blog_id>/',views.detail,name='detail')
]
|
import cv2
import numpy as np
import utils
path = "fotos/teste2.jpg"
width = 586
height = 826
widthG = 165
heightG = 805
img = cv2.imread(path) #Lendo a imagem
img = cv2.resize(img, (width, height)) #diminuindo a largura e altura da imagem
imgContours = img.copy()
imgBiggestContours = img.copy()
imgGray = cv2.cvtCo... |
'''
Alessia Pizzoccheri - CS 5001 02
Consulted https://stackoverflow.com/questions/22025764/python-check-for-integer-input
to learn how to prevent interpreter from throwing an error message if user
input is not an integer
'''
import hanoi_viz
MIN = 1
MAX = 8
SOURCE = 'Start'
MIDDLE = 'Transfer'
TARGET ... |
# Copyright 2022 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
import csv
from django.db import transaction
from django.test import override_settings
from logging import getLogger
from data_aggregator.models import Report, SubaccountActivity
from data_aggregator.utilities import set_gcs_base_pa... |
# -*- coding: utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSubtree(self, s, t):
if s is None and t is None:
return True
elif s is None and t is not None:
return False
... |
import imap_test
import threading
import threadpool
pool = threadpool.ThreadPool(30)
def write_email(submit):
'''
write dict into txt file
eg: write a dict into a.txt
requires the target file with path and the dict to write in
return nothing,just write content into file
'''
# content = js... |
import random
from collections import defaultdict
def generated_list(number):
random_generated_list = []
while len(random_generated_list) < number:
random_generated_list.append(random.randint(0, 100))
return random_generated_list
def generated_dictionary(numbers_list):
numbers_occurrences =... |
def any(it):
for x in it:
if x:
return True
return False
|
# encoding:utf-8
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import urllib.parse
import urllib.request
import base64
import json
import time
import os
def draw_hands_point(path, savePath, originfilename,hands,resultfilename,pointsize,pointcolor):
from PIL import Image, ImageDraw
image_origin = Image.open... |
# -*- python -*-
# Make Change
#
# You'll probably remember this one from your morning algorithm sessions,
# but I'll explain it just in case you haven't done it yet.
#
# Write a function that takes an amount of money in cents and returns the fewest number of coins possible for
# the number of cents. Here's an example... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 7 15:24:49 2019
@author: HP
"""
str="hiimnaveen"
str=str[0:3]+str[6:7]
print(str) |
import warnings
warnings.filterwarnings("ignore")
from keras.models import Model
from keras.layers import Dense, Activation, Flatten, Input
from keras.layers import Conv2D, Conv2DTranspose
#from keras.layers import UpSampling2D, MaxPooling2D, ZeroPadding2D, AveragePooling2D
from keras.layers import LeakyReLU, Dropout,... |
from .no_arvore_inteiro import NoArvoreInteiro
class Arvore:
def __init__(self, raiz=None):
self.__raiz = raiz
@property
def raiz(self):
return self.__raiz
def inserir_elemento(self, no):
no.no_direito = None
no.no_esquerdo = None
if self.__raiz is None:
self.__raiz = no
else:
self.__inserir(no,... |
import os
from PIL import Image
from matplotlib.widgets import Button
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from img_segmentation import generate_trainig_set, get_neighbours_values
from mlp import MultiLayerPerceptron as MLP
class ImageSegmentation:
def __init__(self, img_path):
s... |
import os
import sys
import mysql.connector
import subprocess
import colors
import requests
from requests.exceptions import HTTPError
import urllib.request
dbName = 'craft_update_test'
dbHost = 'localhost'
dbUser = 'root'
dbPass = 's4mb4lb1J'
adminEmail = "craft@oberon.nl"
adminName = "admin"
adminPass ... |
# -*- coding: utf-8 -*-
import logging
TRACE = 5
logging.addLevelName(logging.FATAL, "FATAL")
logging.addLevelName(logging.WARN, "WARN")
logging.addLevelName(TRACE, "TRACE")
def _trace(self, msg, *args, **kwargs):
self.log(TRACE, msg, *args, **kwargs)
logging.Logger.trace = _trace
class ColorfulFormatter(lo... |
# -*- coding: utf-8 -*-
"""
* @file mtq.py
* @author Gustavo Diaz H.
* @date 22 May 2020
* @brief Simple model of a Magnetorquer actuator
"""
import numpy as np
class MTQ(object):
def __init__(self, R, L, A, N):
self.R = R
self.L = L
self.A = A
self.N = N
self.i = 0
... |
from django.db import models
from django.contrib.gis.db import models
# Create your models here.
class Incidence(models.Model):
name = models.CharField(max_length=30)
location = models.PointField(srid=4326)
objects = models.Manager()
def __str__(self):
return self.name
class Meta:
verbose_name_plural = 'Inc... |
# Test that shows PyObject_GetBuffer does copy when called
from mypybuffer import MyPyBuffer
import os
xtc_file = '/cds/home/m/monarin/lcls2/psana/psana/tests/test_data/dgramedit-test.xtc2'
fd = os.open(xtc_file, os.O_RDONLY)
size = 2643928 # size of dgrampy-test.xtc2
view = bytearray(os.read(fd, size))
offset = ... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 方法一、使用静态方法统计------------------------------------------------
class Spam(object):
numInstances = 0
def __init__(self):
Spam.numInstances += 1
@staticmethod
def printNumInstances():
print('Numbers of instances created: ', Spam.numInstances... |
"""
from autobahn.wamp.exception import ApplicationError
from autobahn.twisted.wamp import ApplicationSession
from twisted.internet.defer import inlineCallbacks
from twisted.python import log
"""
import autobahn
import copy
from model.session.wamp import WampTransport, WampSession
import wamp
class SessionLink:
... |
from flask_classful import FlaskView, route
from flask import Flask
app = Flask(__name__)
class TestView(FlaskView):
def index(self):
return "<h1>Index</h1>"
@route('/hello/<world>/')
def bsicname(self, super):
return f"<h1>hello world {super}</h1>"
TestView.register(app, route_base='... |
import torch
from torch import device
import torch.nn as nn
from torch.utils.data.dataloader import DataLoader
import time
import copy
class AugTrainer:
def __init__(self,
model: nn.Module,
loss_fn: nn.Module,
optimizer: nn.Module,
target_loader: DataLoader,
attack_loader: D... |
import pandas as pd
from sklearn.preprocessing import StandardScaler, MinMaxScaler, Imputer, LabelEncoder
from sklearn.feature_selection import VarianceThreshold
import numpy as np
def data_preprocess(url,feat_cols, lab_cols):
tt = pd.read_csv(url)
for col in feat_cols:
if type(col) == 'float' or t... |
from sklearn.datasets import *
from sklearn.model_selection import train_test_split, cross_val_score
import numpy as np
import math
def lasso_regression_penalty(l1_lambda, feature_weights):
""" l2_lambda is between 0 and positive infinity """
try:
lasso_penalty = l1_lambda * sum(map(lambda x: abs(x), ... |
from resources.employees import Employee
bob = Employee("bob",20000,567)
print(bob.basicSalary)
print(bob.payeTax)
print(bob.nhif)
print(bob.nssf)
print(bob.personal_relief)
print(bob.tax_charged)
|
import argparse
import glob
import os
import random
import sys
import time
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from torch.utils.data i... |
# -*- coding: utf-8 -*-
from typing import List
class Solution:
def pivotIndex(self, nums: List[int]) -> int:
left_sum, total_sum = 0, sum(nums)
for i, num in enumerate(nums):
if left_sum == total_sum - left_sum - num:
return i
left_sum += num
retu... |
# -*- coding: utf-8 -*-
import json
from watson_developer_cloud import VisualRecognitionV3
import argparse
import vr_func
if (__name__ == "__main__"):
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--classifier", type=str, help="id of the classifier to apply (default is 'default')")
parser.... |
# Exercício 8.13 - Livro
def letraValida(op):
str(op.lower())
while True:
v = input('Digite uma letra: ').lower()
if v not in op:
print('Tente novamente!')
continue
else:
break
letraValida('mf')
|
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_excel("../data/data.xlsx", sheetname="US_EU_CPI",
index_col=0, skiprows=[0, 1]).dropna()
dc = df.iloc[:, [1]].pct_change(periods=1)*100*12
dc['yoy'] = df.iloc[:, [1]].pct_change(periods=12)*100
dc['target'] = 2.0
dc.dropna(inplace=Tru... |
__author__ = "Narwhale"
def bubble_sort(alist):
"""冒泡排序"""
n = len(alist)
for j in range(0,n-1):
count = 0
for i in range(0,n-1-j):
if alist[i] > alist[i+1]:
alist[i],alist[i+1] = alist[i+1],alist[i]
count += 1
if count == 0:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.