text
stringlengths
8
6.05M
from __future__ import print_function from cms.sitemaps import CMSSitemap from django.conf.urls import * # NOQA from django.conf.urls.i18n import i18n_patterns from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib import admin from django.conf import settings from django.http import H...
# 在函数内部调用函数本身 # 求n的阶乘 # 普通实现 # def test(n): # sum = 1 # if n >= 1: # for i in range(1, n+1): # # print(i) # sum *= i # return sum # else: # return n # 递归实现 def jiecheng(n): if n<=1: return n return n*jiecheng(n-1) print(jiecheng(7)) ''' 关于递...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Resize images and copy them to the static folder """ import os, sys import json import shutil from PIL import Image import numpy as np import urllib.parse # for getting dominany color # from colorthief import ColorThief IMAGECUTOFF = 100 try: os.makedirs('artwork...
from __future__ import print_function from mpl_toolkits.mplot3d import axes3d from matplotlib import cm import matplotlib.pyplot as plt import numpy as np import time import keyboard from threading import Thread import linecache class Plot_flow(): def __init__ (self, rx_num, tx_num): print ("Plot 3D") ...
import socket import time sk = socket.socket(socket.AF_INET,socket.SOCK_STREAM) sk.connect(('127.0.0.1', 8800)) while True: inp = input('>>>>>:').strip() sk.send(inp.encode('utf-8')) data = sk.recv(1024) print(str(data,'utf-8'))
class Solution(object): def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead. """ result = list([]) if len(matrix) == 1: return matrix temp_result = [] matrix_transp...
# -*- coding: utf-8 -*- """ Created on Mon Aug 21 14:08:35 2017 @author: breteau """ from fractions import Fraction from math import cos, sin, pi from libGeometry import Pt import numpy as np from multiprocessing import Pool, Array, Lock import ctypes from functools import partial alpha = Fraction(pi / 5.0) phi = ...
""" Django settings for CAS project. Generated by 'django-admin startproject' using Django 2.2.3. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ Before deployment pl...
import os import sys for file in sys.argv[1:]: with open(file, "r") as fp: lines = fp.readlines( ) print (lines[0]) print (lines[-1])
# I collaborated with other students for this homework : Huilan You # ======================================================================== # Copyright 2018 Emory University # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You m...
from postproc.field import read_field, write_field from postproc.settings import * from postproc.research import Task import os class TaskBuilder(object): def __init__(self, execution_host): # so we allow polymorphism by passing Host or RemoteHost self._execution_host = execution_host self._comman...
# -*- coding: utf-8 -*- """ Created on Fri Mar 1 12:50:19 2019 @author: saib """ a = [1,2,3,4,5,6,7] print(a.length)
#!/opt/anaconda2/bin/python import numpy as np import argparse import mrcfile def rand_vol(n, output): """ random a volume of size n x n x n and saves it in output as mrcfile :param n: size of volume :param output: the path the volume is going to be saved to :return: None """ vol = np.ra...
""" Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner. How many such routes are there through a 20×20 grid? """ # NOTE: we're moving along the *edges* of the grid, not from square to square. # Essentially we're being...
#Stack Linked List class StackList: def __init__(self): self.top = None self.size = 0 #return true if stack is empty def isEmpty(self): return self.top is None #returns the num items def __len__(self): return self.size ...
import torch import torch.nn as nn def safe_detach(x): """ detech operation which keeps reguires_grad --- https://github.com/rtqichen/residual-flows/blob/master/lib/layers/iresblock.py """ return x.detach().requires_grad_(x.requires_grad) def weights_init_as_nearly_identity(m): """ i...
#!/usr/bin/env python from distutils.core import setup LONG_DESCRIPTION = \ '''The program reads one or more input FASTA files. For each file it computes a variety of statistics, and then prints a summary of the statistics as output. The goal is to provide a solid foundation for new bioinformatics command line tools...
from collections import deque from math import factorial, isqrt bound = 20000 queue = deque() queue.append(3) found = {3} paths = {3 : 3} sqrts = {3 : 0} while (len(queue)> 0): m = queue.pop() n = factorial(m) i = 0 while (n>3): if (n<bound) and not(n in found): found.add(n) ...
#coding:utf-8 """UserRepository """ class UserRepository(object): def __init__(self, db): self.db = db def find_by_id(self, user_id): pass def find_by_name(self, user): pass def create(self, user): pass def update(self, user): pass def delete(self, user): pass
numero = int(input('Digite um numero: ')) antecessor = numero - 1 sucessor = numero + 1 print('O numero {} tem como antecessor {} e sucessor {}'.format(numero, antecessor, sucessor))
from haystack import indexes from .models import ExtUser class ExtUsereIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) location = indexes.CharField(model_attr='location') first_name = indexes.CharField(model_attr='first_name') last_name = index...
""" define client """ # Copyright 2018-2019 CNRS # 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 agre...
class BaseComponent(object): # Inheriting from object mainly to get access to super and staticmethod pass
factor = lambda n: (i for i in range(1,n+1) if n % i == 0) is_prime = lambda x: list(factor(x)) == [1,x] primes = lambda x: (i for i in range(2, x+1) if is_prime(i)) print(list(primes(100)))
#runs the cython simulation (jury is out on whether this need be it's own file...) import Cython import pyximport pyximport.install() from . import cythonSim #this allows line profiler (via ipython magic %lprun) to profile cython functions from Cython.Compiler.Options import get_directive_defaults get_directive_defau...
# # @lc app=leetcode.cn id=221 lang=python3 # # [221] 最大正方形 # # @lc code=start class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: if not matrix: return 0 max_squre = 0 max_i, max_j = len(matrix), len(matrix[0]) for i, row in enumerate(matrix): ...
from vid_utils import Video, concatenate_videos speed_str = input("輸入速度:") speed = float(speed_str) videos = [ Video(speed=speed, path="output.mp4") ] concatenate_videos(videos=videos, output_file=f"output_sped_up.mp4")
import tkinter as tk #GUI library from tkinter import filedialog, Text, StringVar #GUI options import tkinter.ttk as ttk #GUI table module from tkinter.ttk import Treeview #import table module import os #OS access to open file import interface import sqlite3 def rfidkeytext(): global card_key card_key.set(int...
from django.contrib.messages.constants import ( DEBUG, INFO, SUCCESS, WARNING, ERROR, DEFAULT_TAGS ) STORED_DEBUG = DEBUG + 1 STORED_INFO = INFO + 1 STORED_SUCCESS = SUCCESS + 1 STORED_WARNING = WARNING + 1 STORED_ERROR = ERROR + 1 DEFAULT_TAGS.update({ STORED_DEBUG: 'persisted debug', STORED_INFO: 'pers...
from __future__ import absolute_import from .optimizer import OptimizerPass, register_pass, get_optimizer, optimize_model from .passes.nop import EliminateLinearActivation from .passes.bn_quant import MergeBatchNormAndQuantizedTanh, QuantizeDenseOutput from .passes.dense_bn_fuse import FuseDenseAndBatchNormalization...
miles=float(input("Enter the distance in miles: ")) km= miles*1.609 print("No. Of Kilometers: ", km)
x,y=input().split() a = int(x) b = int(y) aaaa="" for num in range(a,b): if num > 1: for i in range(2,num): if (num % i) == 0: break else: aaaa = aaaa + str(num)+' ' print(aaaa.rstrip())
#!/usr/bin/env python # -*- coding: UTF-8 -*- s=raw_input() chk='AEIOUY' ans=tmp=1 for i in s: if i in chk: tmp=1 else: tmp+=1 ans=max(ans,tmp) print ans
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 15 12:02:19 2020 @author: mha """ import networkx as nx from node2vec import Node2Vec import numpy as np # FILES EMBEDDING_FILENAME = './embeddings.emb' EMBEDDING_MODEL_FILENAME = './embeddings.model' nodes = np.load("nodes.npy") #nodes = { i : no...
# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: ''' Created on 16 Aug 2017 Based on Nipype Configuration file logging options : INFO, DEBUG @author: Gilles de Hollander Edited by SM ''' try: import configparser except: im...
from imutils import face_utils import numpy as np import imutils import dlib import os import cv2 from random import shuffle import tensorflow as tf import tflearn from tflearn.layers.core import input_data, dropout, fully_connected from tflearn.layers.estimator import regression image_directory = r'C:\Users\Dell\Dow...
from Spider import BbcSpider from scrapy.crawler import CrawlerProcess process = CrawlerProcess() process.crawl(BbcSpider) process.start() # the script will block here until the crawling is finished
p = 9223372036854775837 inv = [0,1] invorial = [0,1] factorial = [1,1] for i in range(2,100005): inv.append((p-p//i)*inv[p%i]%p) invorial.append(invorial[i-1]*inv[i]%p) factorial.append(factorial[i-1]*i%p) def comb(n,r): r = min(r,n-r) if r==0: return 1 return factorial[n]*invorial[r]*invorial[...
import matplotlib matplotlib.use("TkAgg") import gym import gridworld from gym import wrappers, logger import numpy as np import copy def ValueIteration(env, gamma=0.99, eps=1e-6, diff=1e-8): states,P = env.getMDP() random_key = list(P.keys())[0] nb_actions = len(P[random_key]) V = np.zeros((len(stat...
#!/usr/bin/env python # coding: utf-8 import re from abc import ABC, abstractmethod from collections import namedtuple from io import StringIO import pandas as pd import numpy as np import requests from bs4 import BeautifulSoup from requests.exceptions import HTTPError from config import URL_BASE, PROXIES, COLUNAS ...
from __future__ import absolute_import # import apis into api package from .about_api import AboutApi from .access_api import AccessApi from .bucket_bundles_api import BucketBundlesApi from .bucket_flows_api import BucketFlowsApi from .buckets_api import BucketsApi from .bundles_api import BundlesApi from .config_api ...
#!/bin/env python2.7 # encoding: utf-8 ''' backup -- Backup script for AWS backup is a script which creates backup images (AMIs) from AWS EC2 and VPC instances. To backup an instance it needs to have a tag 'Backup' (see FILTER_TAG), its value defines the number of images to keep. If there is a tag 'NoReboot' (see NO_R...
""" Represents a pair of congress members. Contains the IDs of both and the data points relevant to calculating the metric between them. Each pair is hashable (the hash is based on the id's of the two members). """ keys = ['votes_same', 'votes_total', 'mutual_sponsorships'] class Pair: """ If a tuple is ...
import tarfile import glob import os import io import string import sys train = sys.argv[0] test = sys.argv[1] # train if (train == True): print('-'*20 + 'train tsv start' + '-'*20) f = open('./data/IMDb_train.tsv', 'w') path = './data/aclImdb/train/pos/' for fname in glob.glob(os.path.join(path, '*....
from django.urls import path, include from . import views urlpatterns = [ path('add/', views.add_formulario, name='add'), ]
"""telegraph URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-bas...
#!/usr/bin/env python3 # # Format a result # import jsontemplate import pscheduler import sys from validate import result_is_valid try: format = sys.argv[1] except IndexError: format = 'text/plain' input = pscheduler.json_load(exit_on_error=True, max_schema=1) valid, message = result_is_valid(input["result"...
from stack import Stack def dec_to_bin(dec): s = Stack() binary="" if dec==0: return 0 while dec>0: s.push(dec%2) dec=dec//2 while not s.isEmpty(): binary=binary+str(s.pop()) return binary print(dec_to_bin(42)) # 回傳 101010 print(dec_to_bin(100)) ...
# Generated by Django 3.0.3 on 2020-03-28 11:55 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app_websites', '0027_auto_20200318_2353'), ] operations = [ migrations.CreateModel( name='meta', field...
import numpy as np from numpy.testing import dec, assert_, assert_raises,\ assert_almost_equal, assert_allclose import matplotlib.pyplot as plt import pdb, os import scipy.sparse as sps from .blocks import get_demo_circuit from .structure import nearest_neighbor from .dataset import gaussian_pdf, barstripe_pdf fro...
#!/usr/bin/env python # -*- coding:utf8 -*- # FIXME demonizar de la manera apropiada activate_this = "/home/fer/.virtualenvs/trytonenv/bin/activate_this.py" execfile(activate_this, dict(__file__=activate_this)) import trytond options = { 'init': {}, 'update': {}, 'configfile': '/home/fer/tryton/trytond.c...
""" Label subscription """ from dataclasses import dataclass from typing import Any, Callable from typeguard import typechecked from .subscriptions import GQL_LABEL_CREATED_OR_UPDATED from ...graphql_client import SubscriptionGraphQLClient @dataclass class SubscriptionsLabel: """ Set of Label subscriptions...
# coding: utf-8 class Solution(object): def maximalSquare(self, matrix): """ :type matrix: List[List[str]] :rtype: int """ if not matrix: return 0 m, n = len(matrix), len(matrix[0]) st = [] for i in range(m): k = [] ...
import datetime import redis from flask import Flask, render_template, jsonify import json # # # # # SITE_SOURCE_MAP = { "lagou": 201, "dajie": 208, "yinguo": 211, "juzi":209, "baidu": 303, "liepin": 202 } # # # # # # class NoAsRedis: def __init__(self, host, port, db): self.init_...
''' Author: James Kasakyan CCNY: CSC 47300 Web Development, Professor Grossberg HW 3 Problem 2. Enlgish-Tutnese decoder/encoder ''' # Imported Libraries import re # Global variables encode_dictionary = { "b":"bub", "c":"coch", "d":"dud", "f":"fuf", "g":"gug", "h":"hash", "j":'jug', 'k...
# -*- coding:UTF-8 -*- import math, datetime, random import requests from django.conf import settings from django.core.cache import cache from weixin.pay import WeixinPayError from rest_framework.generics import get_object_or_404 gd_key = getattr(settings, 'GDKEY') def get_deliver_pay(origin, destination): ret =...
#!/usr/bin/env python # -*- coding:utf8 -*- """ Final exam: Log file analyzer """ import sys import os import psutil def analyzer(path): """ Log files analyzer :type path: root directory to analyze logs """ result = {} comp_stat = {} for root, dirs, files in os.walk(path): for f i...
from typing import Set from wingedsheep.carcassonne.carcassonne_game_state import CarcassonneGameState from wingedsheep.carcassonne.objects.connection import Connection from wingedsheep.carcassonne.objects.coordinate import Coordinate from wingedsheep.carcassonne.objects.coordinate_with_side import CoordinateWithSide ...
from .analyzer import Semantics
# -*- coding: utf-8 -*- """ Created on Fri Nov 30 10:24:14 2018 @author: fuwen """ import pymongo,requests,json,time BilibiliIpUrl = 'https://api.live.bilibili.com/ip_service/v1/ip_service/get_ip_addr' myclient = pymongo.MongoClient('mongodb://fuwenyue:pass4Top@ds029638.mlab.com:29638/socks_proxies') myd...
import numpy as np import matplotlib.pyplot as plt from grassopt import minimize n, p = 20, 4 A = np.random.rand(n, n) A = (A + A.T)/2 def f1(y): return np.sum(np.diag(np.dot(np.dot(y.T, A), y)))*1./2 def f1y(y): return np.dot((A + A.T), y)*1./2 def f1yy(y): B = np.zeros((n*p, n*p)) for j in ra...
#! /usr/bin/env python # -*- coding: utf-8 -*- from datetime import datetime from urlparse import urlparse, parse_qs class mytime: def __init__(self): pass def str2num(self, time): """the format is (xx:xx)""" hour,min = time.split(':') return int(hour)*60 + int(min) d...
#importing the library import numpy as np import pandas as pd #reading the dataset and creating the dataframe dataset = pd.read_csv("data.csv") #converting all string values to nan dataset = dataset.convert_objects(convert_numeric=True) #dividing coloumns between dependent and independent variables x = da...
''' Created on Sep 9, 2015 @author: Jonathan Yu ''' def score(word): return len(word)**2 if __name__ == '__main__': pass
# -*- coding: utf-8 -*- # @Date : 2018-03-19 10:27:48 # @Author : jym # @Description: # @Version : v0.0 import pymongo con = pymongo.MongoClient('localhost',28019) db = con['QiChaCha'] coll = db['users'] coll.ensure_index('user', unique=True) users = [{'user':'18680325804','pwd':'123456789qwe'}, {'user':'1...
def group_by(iterable, key): return assoc(iterable, key=key, value=lambda x: x) def assoc(iterable, key, value): result = {} for item in iterable: k, v = key(item), value(item) if k not in result: result[k] = [] result[k].append(v) return result
import spotipy import spotipy.oauth2 as oauth2 import numpy as np import json import sys import yaml from sklearn import svm from sklearn.model_selection import train_test_split from sklearn.externals import joblib limitOfTracksApiCanProcess = 50 conf = yaml.load(open('conf/application.yml')) CLIENT_ID = conf['client...
import pickle import numpy as np from itertools import chain, product from scipy.stats import multivariate_normal as mvn import scipy.sparse.csgraph as csg from sklearn.base import BaseEstimator, RegressorMixin from sklearn.exceptions import NotFittedError from electromorpho.core.gaussian import gn_params, conditiona...
import streamlit as st import pandas as pd import speedtest from datetime import datetime import pytz st.write("# Internet Connection Speed Test") spd = speedtest.Speedtest() down = spd.download()/1000000 up = spd.upload()/1000000 st.write(f"### Download Speed = {round(down, 2)} mbps") st.write(f"### Upload Speed ...
#========================================================================= # pisa_srl_test.py #========================================================================= import pytest import random import pisa_encoding from pymtl import Bits from PisaSim import PisaSim from pisa_inst_test_utils import * #---------...
/home/miaojian/miniconda3/lib/python3.7/keyword.py
import torch from engine import Engine from utils import use_cuda class GMF(torch.nn.Module): def __init__(self, config): super(GMF, self).__init__() self.num_users = config['num_users'] self.num_items = config['num_items'] self.latent_dim = config['latent_dim'] self.embed...
import cv2 import numpy as np img = cv2.imread('image.jpg') #read image from system gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #Convert to grayscale image edged = cv2.Canny(gray, 170, 255) #Determine edges of objects in an image ret,thresh = cv2.threshold(gray,240,255,cv2.THRESH_BINARY) (contours,_) = ...
''' author: juzicode address: www.juzicode.com 公众号: juzicode/桔子code date: 2020.6.11 ''' print('\n') print('-----欢迎来到www.juzicode.com') print('-----公众号: juzicode/桔子code\n') print('流程控制实验:循环条件') print('类型:',type(range(5))) print('%s'%range(5)) for r in range(5): print('r:',r) print('类型:',type(range(5,10))) prin...
import psutil from operator import itemgetter import collections from collections import Counter socket_connections = psutil.net_connections(kind='tcp') final_dic={} for a in socket_connections: if a.laddr != ('0.0.0.0', 0) and a.raddr != (): laddr_split=list(a.laddr) raddr_split=list(a.raddr) ...
class Solution(object): def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ if needle == '' or haystack == needle:return 0 ne = len(needle) for k in range(len(haystack)-len(needle)+1): if haystack[...
from django.db import DataError, IntegrityError from django.test import TestCase from cars.models import Manufacturer, Car class CarTestWithoutDBConnection(TestCase): def setUp(self): self.car = Car() def test_car_instance(self): self.assertTrue(isinstance(self.car, Car)) def test_car_...
import logging import os.path import Configs if not os.path.exists("logs/"): os.makedirs("logs/") logger = logging.basicConfig(format='%(asctime)s %(message)s', filename='logs/trials.log', level=logging.DEBUG) def log(message): try: if Configs.get_setting('DEBUG', 'log') == '1': ...
import environ from RuasLimpas.config.base import * env = environ.Env() DEBUG = env.bool("DEBUG", False) SECRET_KEY = env("SECRET_KEY") ALLOWED_HOSTS = env.list("ALLOWED_HOSTS") DATABASES = { "default": { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': env('DATABASE_URL'), } ...
W = int(input()) N, K = map( int, input().split()) A = [] B = [] for _ in range(N): a, b = map( int, input().split()) A.append(a) B.append(b) dp = [[[0 for _ in range(N+1)] for _ in range(K+1) ] for _ in range(W+1)] for i in range(1,W+1): for j in range(K+1): for k in range(N+1): a =...
import graphene from models import db, User as UserModel from .validation_error import ValidationError def validate_user_creation(shortname): if not UserModel.query.filter(UserModel.shortname == shortname).first(): return True class User(graphene.ObjectType): shortname = graphene.String() class C...
DEBUG = True # This is debug state flags # SQLALCHEMY_DATABASE_URI = 'mysql+cymysql://root:qingfing@localhost:3306/fisher' SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:qingfing@localhost:3306/fisher' SECRET_KEY = 'FJASDKLJFKADSJKLFJADSKLJKL8979345491327%^&%^&$%^$' # Email configure MAIL_SERVER = 'smtp.qq.com' MAI...
from pyramid.config import Configurator from .models.node import root_factory def main(global_config, **settings): config = Configurator(settings=settings, root_factory=root_factory) config.include('pyramid_tm') config.include('pyramid_sqlalchemy') config.include('pyramid_ji...
class Solution: def sortColors(self, num): if not num: return l, r, i = 0, len(num) - 1, 0 while i <= r: if num[i] == 2: num[i], num[r] = num[r], num[i] r -= 1 elif num[i] == 0: num[i], num[l] = num[l], num[i...
class Solution: def flipAndInvertImage(self, A): """ :type A: List[List[int]] :rtype: List[List[int]] """ if A==[]: return A for index in A: index.reverse() for i in range(len(index)): index[i]=1-index[i] ret...
from django.db import models from django.contrib.auth.models import User import datetime class Pengarang(models.Model): nama = models.CharField(max_length=75) def __str__(self): return self.nama class Meta: verbose_name = "Pengarang" verbose_name_plural = "Data Pengarang" ...
# 3. Longest Substring Without Repeating Characters # # Given a string, find the length of the longest substring without repeating characters. # # Examples: # # Given "abcabcbb", the answer is "abc", which the length is 3. # # Given "bbbbb", the answer is "b", with the length of 1. # # Given "pwwkew", the answer i...
class GameStates: MAIN_MENU = 0 PLAYING = 1 PAUSED = 2 GAME_OVER = 3 TOP_SCORES = 4 SELECT_LEVEL = 5
import uuid from dataclasses import dataclass from datetime import datetime from devices.schemas import Serializable from marshmallow import Schema, fields, post_load, validate class DeviceAttributeSchema(Schema): # pylint: disable=too-few-public-methods value = fields.Str(required=False, default=None) last...
from django.shortcuts import render, render_to_response,redirect from django.template import RequestContext from django.conf import settings import requests import json from helper import JsonResponse # Create your views here. #vista que muestra la pagina de login def show_login_button(request): return render_to_...
import os from numpy import true_divide from selenium.webdriver import Chrome, ChromeOptions from selenium.webdriver import Firefox from selenium.webdriver.firefox.options import Options import time import pandas as pd from bs4 import BeautifulSoup import datetime as dt from selenium import webdriver from webdriver_man...
#!/usr/bin/env python # -*- coding=utf8 -*- import httplib import urllib import urllib2 from datetime import * import time def sendhttp(): data = urllib.urlencode({'u_team_id':'125', 'author':'args1', 'body_pic':'[pic]jfjjfj[/pic]','body_text':'nihaoma daye'}) headers = {"User-Agent": "Mozilla/5.0 (Windows; U...
from django.conf.urls import patterns, include, url from django.conf import settings import views from grades.views import grade_peer_eval, email_user_feedback urlpatterns = patterns('', # NOTE: all these URLs are preceded by "_admin/" #url(r'load-class-list/$', views.load_class_list, name='admin-load-class...
class NumMatrix(object): def __init__(self, matrix): """ initialize your data structure here. :type matrix: List[List[int]] """ ##initiate a sum array here self.matrix = matrix m, n = len(matrix) + 1, len(matrix[0]) + 1 self.sumArray = [[0 for _ in ra...
../../ml/line_fit.py
import pandas as pd import matplotlib.pyplot as plt import numpy as np from sklearn.preprocessing import StandardScaler from imblearn.over_sampling import SMOTE from sklearn.model_selection import train_test_split ## data load data=pd.read_csv('C:/Users/user/Desktop/creditcard.csv') # print(data.head()) # print(data.c...
"""PG-60: Recursion Problems that are built off of subproblems. 1. How many subproblems does `f(n)` depend on? - binary tree: two, linked list: one, regex: number of possible special characters, etc 2. Solve for a "base case". First compute for `f(0) + f(1)` which are hard coded values. 3. Solve for `f(2)` 4. Unders...
import main.DAO.redisDAO as redisDAO dao = redisDAO.redisDAO() count = [] for i in range(1,1683): a = dao.get_item_sim_list(i,0) if len(a) == 0: print i else: count.append((i,a[0][0],a[0][1])) count.sort(key =lambda count:count[2]) print count
"""empty message Revision ID: b7afce71bc6f Revises: 28c51d215b39 Create Date: 2018-04-14 22:47:36.817118 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'b7afce71bc6f' down_revision = '28c51d215b39' branch_labels = None depends_on = None def upgrade(): # ...
# -*- coding: utf-8 -*- import codecs import operator class ngram: def __init__(self): self.words_freq = {} self.max_count = 0 def ishan(self, text): return all(u'\u4e00' <= char <= u'\u9fff' for char in text) def executeNgram(self, text, n): words=[] for w in ...