text stringlengths 38 1.54M |
|---|
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... |
import uuid
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils.datetime_safe import datetime
from model_utils.models import TimeStampedModel
from app.core.storage_backends import MediaStorage
from app.core.utils import storage_path
class User(AbstractUser):
def u... |
'''
Problem:
Given an array of characters, compress it in-place.
The length after compression must always be smaller than or equal to the original array.
Every element of the array should be a character (not int) of length 1.
After you are done modifying the input array in-place, return the new length of the array.
... |
#!/usr/bin/python
from tkinter import *
import cv2
import PIL.Image, PIL.ImageTk
from skimage.transform import *
from skimage import io
from skimage.transform import resize
import pickle
import numpy as np
import keras
from keras.preprocessing.sequence import pad_sequences
from keras.models import model_... |
#%%
import BikeSystem
import pandas as pd
#%%
bs = BikeSystem.DCBikeSystem()
df = bs.load_data()
df.columns
# mp = bs.load_map()
# mp.to_csv("export/{}_Geocoding.csv".format(bs.city))
# cnt_1 = df.startstation.value_counts()
# cnt_2 = df.endstation.value_counts()
# start = df.groupby("startstation")["starttime"].min()
... |
from scapy.all import *
import requests
import pprint
import codecs
import json
import sys
import shutil
from threading import Thread
import time
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1... |
from discord.ext import commands
class Reactions(commands.Cog):
"""Works with Reactions"""
def __init__(self,bot):
self.bot = bot
#Event to give roles with a default reaction
@commands.Cog.listener()
async def on_reaction_add(self, reaction, user):
if reaction.emoji == "👍... |
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if len(strs) == 0: return ""
# longest common prefix
lcp = strs[0]
i = 0
for i in range(len(strs)-1):
while len(lcp) >0:
if strs[i+1].startswith(lcp):
# lcp ... |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
from mysql_credentials import MysqlCredentials as dbc
APP = Flask(__name__)
# APP.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
APP.config['SQLALCHEMY_DATABAS... |
from argparse import ArgumentParser, Namespace
from collections import OrderedDict
from functools import partial
from logging import getLogger
from multiprocessing.pool import Pool
from typing import Dict, Optional, Tuple
from g2p_en import G2p
from ordered_set import OrderedSet
from pronunciation_dictionary import (P... |
"""Load covariance matrix, perform classif, perm test, saves results.
Outputs one file per freq x state
Author: Arthur Dehgan"""
from time import time
from scipy.io import savemat, loadmat
import pandas as pd
import numpy as np
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
from sklearn.m... |
import fileinput
import itertools
def get_inputs(filename=None):
distances = {}
for l in fileinput.input(filename or "inputs.txt"):
parts = l.strip().replace(" to ", " ").replace(" = ", " ").split()
distances[(parts[0], parts[1])] = int(parts[2])
distances[(parts[1], parts[0])] = int(p... |
#!/usr/bin/env python
#coding=utf-8
# vim: set filetype=python ts=4 sw=4 sts=4 expandtab autoindent :
'''
Get username and password from http://www.bugmenot.com/
File: bugmynot.py
Author: notsobad.me
Description:
Created: 2009-11-09 15:23:41
Last modified: 2010.11.25
'''
import optparse
import sys
import urllib2
imp... |
from Crypto.Util.number import *
from random import getrandbits
from flag import flag
flag = bytes_to_long(flag.encode("utf-8"))
flag = bin(flag)[2:]
length = len(flag)
A = []
a, b = 0, 0
for _ in range(length):
a += getrandbits(32) + b
b += a
A.append(a)
p = getStrongPrime(512)
q = getStrongPrime(512)
... |
import matplotlib.pyplot as plt
# Import Dependencies
import numpy as np
import pandas as pd
from sklearn.datasets import load_boston
import tensorflow as tf
features_df = pd.read_csv('ds_midterm2018.csv', usecols=[1,2,3,4,5,6,7,8,9,10,11,12,13])
features_df.head()
features_df.shape
features_df.describe()
labels_df... |
import os
from flask import Flask, render_template, jsonify, request, redirect, Response
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine
from sqlalchemy.ext.automap import automap_base
import pandas as pd
import pymysql
pymysql.install_as_MySQLdb()
app = Flask(__name__)
# **********... |
from __future__ import print_function
import airflow
import pytz
import logging
from datetime import datetime, timedelta
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from airflow.operators.hive_operator import HiveOperator
from airflow.models import Variable
start_date = datetime(20... |
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def startMainPage(request):
# return HttpResponse("welcome")
return render(request, 'home_html.html')
|
import cv2
import numpy as np
import utlis
import os
score = 0
###########################################################
def Process(path, pre, fin, ans, questions, choice):
print(path)
widthImg = 700
heightImg = 700
# questions = 5
# choice = 5
# ans = [1, 2, 0, 1, 4]
print... |
import numpy as np
#import tensorflow as tf
from keras.preprocessing import image
import matplotlib.pyplot as plt
import skimage as skimage
from skimage import data, io, filters, transform
input_size = 512
#random flip
def random_flip(img, mask, u=1):
if np.random.random() < u:
img = image.flip_... |
import Demux4Way
import Demux
class Demux8Way():
def __init__(self):
self.a = [0,]
self.select = [0,0,0,]
self.b = [0,]
self.c = [0,]
self.d = [0,]
self.e = [0,]
self.outa = [0,]
self.outb = [0,]
self.outc = [0,]
self.outd = [0,]
... |
import xarray as xr
import numpy as np
from itertools import product
from functools import reduce
from tools.LoopTimer import LoopTimer
import pandas as pd
import pickle
import matplotlib.pyplot as plt
import sys
def nan_correlate(x,y):
idx = np.logical_and(~np.isnan(x), ~np.isnan(y))
return np.corrcoef(x[idx]... |
import numpy as np
from matplotlib import pyplot as pl
import pandas
from sklearn.linear_model import LinearRegression
from neural_network import FaceNet
from PIL import Image
import matplotlib.patches as patches
data = pandas.read_csv('data.csv', delimiter=' ')
pathes = data[['File']].as_matrix()[:, 0]
rect... |
#!/usr/bin/python3
# -*- coding -*-
# Arthor: NERD
# Data: 2018-6-24
# Version: 1.0
from L298NHBridge import HBridge
from ImageProcess import ProcessData
def Init(self):
Motors = HBridge(19, 26, 23, 24, 13, 21, 22)
speed_run = 0
angle_steer = 0
speed_run, angle_steer = ProcessImage()
... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^contador/', views.contador, name='contador'),
] |
import logging
from django.http import HttpResponse
import json
from myuw.views.rest_dispatch import RESTDispatch, data_not_found
from myuw.dao.finance import get_account_balances_for_current_user
from myuw.dao.notice import get_tuition_due_date
from myuw.logger.timer import Timer
from myuw.logger.logresp import log_da... |
from threading import Thread
from pyfirmata import Arduino, util
import serial
import time
class ArduinoConnection(Thread):
def __init__(self):
Thread.__init__(self)
self.SAMPLING_INTERVAL = 0.100
self.MEAN_INTERVAL = 5
self.MEAN_SAMPLES_NUMBER = round(self.MEAN_INTERVAL/s... |
hardware_config = {
# Micro Controller Unit description (HEAD/arch/<arch>/<mcu_fam>/<vendor> folder)
'mcu_arch' : 'avr',
'mcu_family' : 'avr8',
'mcu_vendor' : 'atmel',
'mcu_cpu' : 'atmega1281',
'mcu_toolchain' : 'GCC',
# Device driver description (HEAD/target/mcu folder)
'mcu' : 'atmega1281',
# Tr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import podium_api
from podium_api.asyncreq import get_json_header_token, make_request_custom_success
from podium_api.types.event import get_event_from_json
from podium_api.types.paged_response import get_paged_response_from_json
from podium_api.types.redirect import g... |
import re
with open('9.input', 'r') as file:
input = file.read()
input = re.sub('!.', '', input)
input = re.sub('<.*?>', '', input)
depth = 0
score = 0
for c in input:
if c == '{':
depth = depth + 1
elif c == '}':
score = score + depth
depth = depth - 1
print(score)
|
# Generated by Django 2.0.13 on 2019-05-17 18:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('capapi', '0013_auto_20181107_2037'),
]
operations = [
migrations.CreateModel(
name='MailingList',
fields=[
... |
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from scipy import signal, misc
fs = 8000
t = np.linspace(0, 1/70, 512, endpoint=False)
x0 = signal.chirp(t, 700, 1/70, 900, method='linear')
x1 = signal.chirp(t, 700, 1/70, 9000, method='linear')
fig, ax = plt.subplots(2)
ax[... |
"""
213. House Robber II
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have security system connected and it ... |
import os
import hashlib
class FileComparator(object):
"""
Class to read in two files and compare them
Can compare for matching lines or matching hashes
TODO: Have it take a function expression for file comparison
"""
def __init__(self, filePath1, filePath2):
"""
Constructor f... |
from .AmountTypes import PaidAmount
from .util import Xmleable, default_document, createElementContent
class ID(Xmleable):
def __init__(self, id, tipo_documento="02"):
self.id = id
self.schemeID = tipo_documento
self.schemeName = "Anticipo"
self.schemeAgencyName = "PE:SUNA... |
# coding: utf-8
# dont add this, request.path is non unicode in python 2.7
# or add it, as request.path shoudl be unicode anyway?!
# from __future__ import unicode_literals
from ..models import Redirect
try:
reload
except NameError:
from importlib import reload
from django.contrib.sites.models import Site
fr... |
import socket
s = socket.socket()
s.bind(("localhost", 1235))
s.listen(0)
c, addr = s.accept()
while True:
command= None
print("Waiting for commands...")
while command is None :
command = c.recv(1024).decode()
print("Command: ",command)
#command execution part
if command== ... |
#coding:utf-8
import unittest
class Test(unittest.TestCase):
u'''测试test01'''
def testAdd(self): # test method names begin with 'test'
a = 1
b = 2
result = a+b #测试结果
ex = 3 #期望结果
self.assertEqual(result,ex) #断言是测试结果与期望结果对比
if result==ex:
print("Tr... |
from base_viewer import BaseViewer
from latextools_utils import get_setting
from latextools_utils.external_command import external_command
from latextools_utils.sublime_utils import get_sublime_exe
import os
import re
import shlex
import sublime
import string
import sys
try:
from shlex import quote
except Import... |
#main() contains a test case for the median finder
#stream(x) streams the next int into the median finder.
#From there, it inserts it into its running list, sorted
#getMedian() will find the median of the current sorted list
import bisect
def main():
stream = [2, 1, 5, 7, 2, 0, 5]
medianFinder = MedianFinder(... |
import csv
from Mining_frequent_closed_itemsets_CLOSET.fpTree.fpTree import FPTree
from Mining_frequent_closed_itemsets_CLOSET.fpTree.frequentItemset import FrequentItemSet
from Mining_frequent_closed_itemsets_CLOSET.itemDictionary import ItemDictionary
class FPTreeBuilder:
def __init__(self, file_name, min_supp... |
import os
Path={}
if __name__ == '__main__':
WorkSpace = os.path.abspath('..\\..')+'\\'
else:
WorkSpace = os.getcwd()+'\\'
Path['bootloader'] = {
'WorkSpace' :WorkSpace,
'BuildRelativePath':'Build\\bootloader\\',
'BuildPath' :WorkSpace+'Build\\bootloader\\',
'BinPath' ... |
class LibraryMethod:
def __init__(self,id,title):
self.id=id
self.title=title
def print_info(self):
print("-----libraryMethod-----")
print("The id is :" + str(self.id))
print("the title is :" + self.title)
class Book(LibraryMethod):
def __init__(self,id,title,author,... |
from django import forms
from .models import User
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth.forms import UsernameField
from allauth.account.forms import SignupForm , LoginForm
from django.utils.translation import ugettext_lazy as _
from phonenumber_field.formfields ... |
from setuptools import setup, find_packages
setup(
name="tootstream",
version="0.5.0",
python_requires=">=3",
install_requires=[line.strip() for line in open('requirements.txt')],
packages=find_packages('src'),
package_dir={'': 'src'}, include_package_data=True,
package_data={
},
a... |
import pdb
from django.http import JsonResponse
from django.shortcuts import render_to_response
from django.views.generic import DetailView, CreateView
from article.models import Article, Comments
# TODO: Add comment pagination
# # For listing cover images ajax view
# @page_template('comments.html') # just add thi... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-01-13 06:29
from __future__ import unicode_literals
from django.db import migrations, models
import student_gallery.models
class Migration(migrations.Migration):
dependencies = [
('student_gallery', '0010_student_info'),
]
operations = [... |
""" Executes python code. Used in some field types, in dynamic roles """
# import os
import sys
# from loguru import logger
from dotmap import DotMap
import backend.dialects as ax_dialects
import backend.misc as ax_misc
this = sys.modules[__name__]
async def aexec(code, localz, **kwargs):
""" This function wrap... |
"""
Run this program in the directory containing the gcode files
you would like to split into 2 files for inserting nuts, etc.
You will be prompted for the file name and the z-height to
stop the print at.
"""
import sys
import re
import time
while True:
filename = raw_input('\nEnter filename: ')
try:
... |
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from scrapy.item import Item, Field
import config
class BrokenItem(Item):
url = Field()
referer = Field()
status = Field()
class BrokenLinksSpider(CrawlSpider):
name = 'BrokenLinksSpider'
rules = (Rule(L... |
from typing import List
# DP problem find the minimum path sum from top left to bottom right corner - LC 64
def min_path_sum(grid: List[List[int]]) -> int:
if grid is None or len(grid )==0:
return 0
R = len(grid)
C = len(grid[0])
result = [[0 for _ in range(C)] for _ in range(R)]
result[0][0] = grid[0][0]
# ... |
from concurrent.futures import ThreadPoolExecutor
import time
import random
from database.common import execute, get_conn
from database.queries import TAKE_TASK, RUN_TASK, FINISH_TASK
from logger import get_logger
LOGGER_NAME_PREFIX = 'worker-{}'
WORKERS_CNT = 2
TEST_TASK_SLEEP_MIN = 0
TEST_TASK_SLEEP_MAX = 10
NO_TAS... |
from dataclasses import dataclass
@dataclass
class Config:
gamma: float
batch_size: int
lr: float
initial_exploration: int
log_interval: int
update_target: int
replay_memory_capacity: int
device: str
sequence_length: int
burn_in_length: int
eta: float
local_mini_batch: ... |
from beamngpy import BeamNGpy, Scenario, Road, Vehicle, setup_logging, StaticObject, ProceduralRing
from BeamHome import getBeamngDirectory
def main():
beamng = BeamNGpy('localhost', 64256,getBeamngDirectory())
scenario = Scenario('smallgrid', 'road_test')
vehicle = Vehicle('LIF_Mobile', model='etkc',... |
from rest_framework import permissions, renderers, viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from Estate.permissions import IsOwnerOrReadOnly, IsMyLike
from Estate.models import Profile, RealEstate, Liked
from Estate.serializers import ProfileSerializer, EstateSe... |
from unittest import TestCase
import requests_mock
from test import file_to_string
from html_to_json.fetch_html import get_html_tree
class TestGetHtmlTree(TestCase):
def test_get_html_tree(self):
with requests_mock.Mocker() as m:
m.get('https://slashdot.org', text=file_to_string('fixtures/in... |
import numpy as np
PATH_TO_TRAIN_SET_CATELOG = ''
PATH_TO_VAL_SET_CATELOG = ''
PATH_TO_TEST_SET_CATELOG = ''
GROUPED_SIZE = 2
IMAGE_SIZE = 224
IMAGE_CHANNELS = 3
NUMBER_OF_CATEGORIES = 2
NO_FIGHT_LABEL = [1., 0.]
FIGHT_LABEL = [0., 1.]
FLOAT_TYPE = np.float32
TIMEOUT_FOR_WAIT_QUEUE = 100
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Test Server Settings
"""
import random
import string
def generate_random(size):
"""Generate random printable string"""
_range = range(size)
_alphabet = string.ascii_uppercase + string.digits + ' _+=\'"~@!#?/<>'
return ''.join(random.choice(_alphabet) ... |
from copy import deepcopy
import random
from DeepPython import Params
class Slice:
def __init__(self, py_datas, group, feed_dict=None):
if feed_dict is None:
feed_dict = {}
self.switcher = {
'Lpack': {'init': self.__init_lpack,
'get_slice': self.__ge... |
from re import match
from rules import name_rules
import pytest
def test_aberP():
# import ipdb; ipdb.set_trace()
found = []
strings = ['rat', 'mouse', 'Aberystwyth', 'Aberdyfi', 'Aberdeen', 'Abergavenny', 'Aberuthven']
for string in strings:
for regex in name_rules['aberP']:
m = m... |
#!python3
import sys
import traceback
import re
from config import parse
import utils
canteen_request = re.compile('/(?P<dirs>([\w-]+/)*[\w-]+)/(?P<file>[\w-]+.(xml|json))')
def handler(eniron, start_response):
prefix = eniron.get('PATH_PREFIX', None)
uri = eniron['PATH_INFO']
if prefix and uri.startswi... |
from RecoHI.HiTracking.hiSecondPixelTripletStep_cff import *
from RecoHI.HiTracking.hiMixedTripletStep_cff import *
from RecoHI.HiTracking.hiPixelPairStep_cff import *
from RecoHI.HiTracking.MergeTrackCollectionsHI_cff import *
hiIterTracking = cms.Sequence(
hiSecondPixelTripletStep
*hiPixelPairStep
*hiGen... |
import qRC.python.quantileRegression_chain_disc as qRCd
import numpy as np
import argparse
import yaml
import root_pandas
def main(options):
stream = file(options.config,'r')
inp=yaml.load(stream)
dataframes = inp['dataframes']
showerShapes = inp['showerShapes']
chIsos = inp['chIsos']
year = ... |
# https://projecteuler.net/problem=55
def is_palindrome(n):
return n == reverse_num(n)
def reverse_num(n):
value = 0
while n > 0:
value = value * 10 + n % 10
n //= 10
return value
def is_lychrel(n, attempts=51):
for _ in range(attempts):
n += reverse_num(n)
if is_palindrome(... |
a = int(input("enter a number: "))
b = int(input("enter another number: "))
print("the sum of two numbers are:", a + b)
print("the difference between two numbers are: ", a - b)
print("the product between two numbers are: ", a * b)
print("the division between two numbers are: ", a / b)
print("the floor division between ... |
import csv
import psycopg2
import os
from random import shuffle
def csv2sql(dirname, filename):
user = ""
connect_str = "dbname={user} user={user} password={user} host='localhost'"
conn = psycopg2.connect(connect_str.format(user=user))
cur = conn.cursor()
with open(dirname + "/" + filename , 'r') ... |
# -*- coding: utf-8 -*-
"""Check for undercoordinated carbons"""
import numpy as np
from ..utils.get_indices import get_c_indices
from .base_missing_check import BaseMissingCheck
from .geometry import _maximum_angle, add_sp2_hydrogen, add_sp3_hydrogens_on_cn1
class UnderCoordinatedCarbonCheck(BaseMissingCheck):
... |
#-*- coding:utf-8 -*
import entity
import time
import character
import movingent
import livingent
import hitbox
import files
void_collision ="0"
random_zone="O"
damage_Zone= "¤"
_wall = "X"
Gostwall = "-"
take_damage = "."
import files
#_____Create____________________________________________________________________... |
# -*- 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 pymongo import MongoClient
from scrapy.exceptions import DropItem
from scrapy.conf import settings
import logging
clas... |
#__author: Think
#date 2019/8/31
import os,configparser,logging
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
config_file = os.path.join(base_dir, 'conf/server.conf')
cf = configparser.ConfigParser()
cf.read(config_file, encoding='utf-8')
####设定日志目录####
if os.path.exists(cf.get('log', 'logf... |
for i in range(0,digits):
# #sort the ones place
# if i == 0:
# if int(reverse[i]) < 4:
# output.append("I"*int(reverse[i]))
# elif int(reverse[i]) == 4:
# output.append("IV")
# elif int(reverse[i]) == 5:
# output.appen... |
"""
-------------------------------------------------------------------------------
CROSS-CORRELATION METHOD: cross_cor_method.py
-------------------------------------------------------------------------------
Oberseminar Regelungstechnik - Auto-tuning PID
--------
"""
from matplotlib.pyplot import plot, grid, show, fi... |
for _ in range(int(input())):
n = int(input())
arr = list(map(int, input().split()))
no = True
zeroth = arr[0]
for i in arr:
if i!=zeroth:
no = False
break
if no:
print('NO')
else:
print('YES')
alr_con = [False]*n
... |
import numpy as np
import tensorflow as tf
from tensorflow.keras.applications import densenet
from .base import SaliencyMap
class GradCam(SaliencyMap):
def get_mask(self, image, last_conv_layer_name, preprocess=True):
"""Computes GradCAM saliency map.
Args:
image (ndarray): Original ... |
from radient import RadientClient
from integration import IntegrationClient
from integration_controller import IntegrationController
from radient_controller import RadientController
from gui import app
|
# Vanessa Dunford
# Github: https://github.com/vanicci
# Linkedin: https://www.linkedin.com/in/vanessa-dunford-08ab7663/
# Youtube: http://bit.ly/JoinMeOnYouTube
# Twitter: https://twitter.com/vaniccilondon
# Table of contents. Write a table of contents program here. Start the program with a list holding all of the in... |
a = 9
b = 8
print(a +b)
def luaspersegi(panjang,lebar):
total = panjang * lebar
print("luasnya adalah ", total)
return total
luaspersegi(10,5)
teks = str(input("siapa namamu ?"))
print ("nama saya adalah", teks)
x=5
while x < 10 :
print(x)
x=x-1 |
import cv2
import numpy as np
class PerspectiveTransform:
''' transforms the image to a bird-eyes view '''
def __init__(self, image):
self.image = image
self.img_size = (image.shape[1], image.shape[0])
self.src = np.float32(
[[(self.img_size[0] / 2) - 65, self.img_size[1] / ... |
from flask import Flask,render_template,url_for,request
import joblib
from textpreprocessing import pre_process
topics = {1:'Computer Science', 2:'Physics', 3:'Mathematics', 4:'Statistics', 5:'Quantitative Biology', 6:'Quantitative Finance'}
app = Flask(__name__)
pipeline = joblib.load('abstract_classification.jobli... |
import os
from django.contrib.gis.db import models
from django.contrib.auth.models import User , Group
from allauth.account.signals import user_signed_up
from django.contrib.sites.models import Site
from django.db.models.signals import post_save ,m2m_changed
from django.dispatch import receiver
from sorl.thumbnail.fie... |
from NeuralNet import buildNeuralNet
truthTable = [([0, 0], [0]),
([1, 0], [1]),
([0, 1], [1]),
([1, 1], [0])]
def buildNet(hiddenLayer=[]):
accuracies = []
for i in range(5):
nnet, accuracy = buildNeuralNet(examples=(truthTable, truthTable), hiddenLayerList=hiddenLayer, maxItr=5000)
accuracies.a... |
# coding=utf-8
"""
@project : algorithmPython
@ide : PyCharm
@file : __init__.py
@author : illusion
@desc :
@create : 2021/6/7 1:56 下午:01
"""
|
#PF-Prac-1
'''
Created on Mar 23, 2019
@author: vijay.pal01
'''
def add_string(str1):
#start writing your code here
n=len(str1)
if(n<3):
return str1
if(str1.endswith("ing")):
str1+="ly"
else:
str1+="ing"
return str1
retur... |
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils import timezone
class User(AbstractUser):
pass
class Post(models.Model):
body = models.CharField(max_length=255, blank=True)
created_on = models.DateTimeField(default=timezone.now)
author = models.Foreig... |
import config.py
#actual function
def cat_feed:
get_weight= food_weight
if food_weight <= 500:
full= false
while full == false:
SetAngle(90)
sleep(5)
SetAngle(-90)
sleep(5)
SetAngle(90)
sleep(5)
pwm.stop()
GPIO.cleanup()
print ("The food weight is now" + get_weight)
sleep (10800... |
# 猫眼电影介绍url
# http://maoyan.com/films/1217236
import requests, time
from fake_useragent import UserAgent
import json, csv, os
import pandas as pd
import datetime
class Spidermaoyan():
headers = {
"User-Agent": UserAgent(verify_ssl=False).random,
"Host": "m.maoyan.com",
"Refere... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2015-08-24 17:41:23
# @Author : Jintao Guo
# @Email : guojt-4451@163.com
import os
import sys
import multiprocessing
import glob
import tempfile
def get_args():
"""Get arguments from commond line"""
try:
import argparse
except ImportE... |
class Solution:
# Do not treat the matrix as a 2d array, multiply m*n and treat it
# as an array
def searchMatrix(self,matrix,target):
if matrix:
return self.binarySearch(0,len(matrix)*len(matrix[0])-1,matrix,target)
else:
return False
def binarySearch(self,low,h... |
__author__ = "Yuzhou_1shu"
number = input("请输入一个不多于5位的正整数:")
if len(number) > 5 or int(number) < 0:
print("Error, 请输入一个不多于5位的正整数:")
else:
print("输入正整数的长度为:", len(number))
print("逆序打印出各位数字", number[::-1]) |
import wx
class MyApp(wx.App):
def OnInit(self):
self.frame = MyFrame(None, title="The Main Frame")
self.SetTopWindow(self.frame)
self.frame.Show()
return True
class MyFrame(wx.Frame):
def __init__(self, parent, id=wx.ID_ANY, title="",pos=wx.DefaultPosition, size=wx.DefaultSize... |
#!/usr/bin/env python
# -*- coding: utf-8 -*
############################################################################
# Joshua R. Boverhof, LBNL
# See LBNLCopyright for copyright notice!
###########################################################################
import sys, unittest
from ServiceTest import main, S... |
from urllib import request
import re
class Croller(object):
def __init__(self):
self.title_pattern = re.compile('')
self.url_pattern = re.compile('')
return self
def yield_article(self):
class AsahiCroller(Croller):
def __init__(self):
self.url = 'http://www.asahi.com/edu... |
import csv
def remove_spaces(ls):
return [elem.strip() for elem in ls]
with open('data.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)
next(csv_reader) # The iterator skips the first line (i.e the headers)
for line in csv_reader:
print(line)
# Copy the contents of th... |
import datetime
from django.db import models
from university.models import *
YEARS = []
for r in range(2021, (datetime.datetime.now().year+2)):
YEARS.append((r,r))
class Susi(models.Model):
class Meta:
verbose_name = '수시전형'
verbose_name_plural = '수시전형'
university = models.ForeignKey(
... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the superReducedString function below.
def superReducedString(s):
i = 0
a = len(s)
b = ""
while True:
if s[i] == s[i+1]:
i += 2
else:
b += s[i]
i += 1
if i+1 =... |
from django.forms import ModelForm
from .models import NoteTitle, Notedetails
class Note_title(ModelForm):
class Meta:
model = NoteTitle
exclude = ()
class Note_details(ModelForm):
class Meta:
model = Notedetails
exclude = () |
#
# Copyright (C) 2019 Luca Pasqualini
# University of Siena - Artificial Intelligence Laboratory - SAILab
#
#
# USienaRL is licensed under a BSD 3-Clause.
#
# You should have received a copy of the license along with this
# work. If not, see <https://opensource.org/licenses/BSD-3-Clause>.
# Import packages
import lo... |
from pymongo import MongoClient
def get_db_connection():
"""Connection au cluster distant mongo atlas. Retour d'un objet client utilisable pour du requêtage."""
client = MongoClient("mongodb+srv://amaury:motdepasse@moncluster.xximx.mongodb.net/<MonCluster>?retryWrites=true&w=majority")
return client
def ... |
from networking_modules.socketfunctions import TCPSocket,UDPSocket
from networking_modules.conversion import *
import threading
import math
import time
import random
class client:
host = '127.0.0.1'
clientaddr = '127.0.0.6'
engageFlag = 1
tcpPort = 9000
udpPort = 9001
udpSend = socket.socket(fa... |
# -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.