text stringlengths 8 6.05M |
|---|
from distutils.core import setup
setup(
name='Filepath',
version='',
packages=['MagicPath'],
package_dir={'': 'MagicPath'},
url='',
license='',
author='ivans',
author_email='',
description=''
)
|
from tkinter import *
from time import *
fnameList = ['gifimage.gif', 'gifimage3.gif', 'gifimage4.gif',
'gifimage5.gif']
photoList = [None] * 9
num = 0
def clickNext():
global num
num += 1
if num >= len(fnameList):
num = 0
photo = PhotoImage(file=fnameList[num])
pLabel.config... |
#!/usr/bin/python3
"""
Python script that takes in a string and sends a search
request to the Star Wars API
"""
import sys
import requests
if __name__ == "__main__":
data = {'search': sys.argv[1] if sys.argv.__len__() > 1 else ""}
url = 'https://swapi.co/api/people/'
response = requests.get(url, params=dat... |
# -*- coding: utf-8 -*-
"""
@author: Duy Anh Philippe Pham
@date: 21/04/2021
@version: 2.00
@Recommandation: Python 3.7
@revision: 11/06/2021
@But: Centroide
"""
import sys
sys.path.insert(1,'../../libs')
import centroide
hemi='L'
source1='../../data/'+hemi
source2='../../variables/'+hemi
#Attention adapter la foncti... |
# python 直接对MongDB数据库操作
from pymongo import MongoClient
from datetime import datetime
class TestMongo:
def __init__(self):
self.client = MongoClient()
self.db = self.client['blog']
def add_one(self):
# 新增一条数据
post = {
'title': '标题',
'content': ' 内容',
... |
__author__ = 'Dell'
import csv
from datetime import datetime
favoritesreader = csv.reader(open("flickr-all-photo-favorite-markings.txt", "r"), delimiter='\t')
photosreader = csv.reader(open("flickr-all-photos.txt", "r"), delimiter = '\t')
photo_owner = dict((int(row[0]),int(row[2])) for row in photosreader)
infavgr... |
import pandas as pd
import numpy as np
## Takes offense data and calculates defensive allowances of opponent by week (sums offense)
## Calculates season-to-date averages and merges with defense data to show season performance vs actual performance
## Calculates various ranks as well as fantasy points specific to passi... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from spider.zhihu import ZhiHu
__author__ = 'l'
if __name__ == "__main__":
zhihuspider = ZhiHu(thread_number=10, encoding="utf8", timeout=5)
zhihuspider.run()
|
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_ds():
return 'Hello DS'
@app.route('/Data')
def hello_world():
return 'Hello World'
|
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt
from tensorflow.keras.applications.inception_resnet_v2 import InceptionResNetV2
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.imagenet_utils im... |
from flask import Response, request
from flask_restful import Resource, reqparse
from sqlalchemy.sql import text
from app import db
from models.model import Child, Parent
from serializers.Child import Child_schema, Children_schema
from util.common import notfound, deleted
class ChildListApi(Resource):
def get(se... |
from tkinter import *
from tkinter.ttk import Combobox, Checkbutton
window = Tk()
window.geometry('800x600')
window.title("Welcome to new window")
txt = Label(window, bg="green", fg="black", width=30, text="0 0")
txt.grid(column=0, row=0)
txt2 = Label(window, bg="blue", fg="white", width=30, text="1 0 ")
txt2.grid(co... |
import sys
sys.path.append('Class/')
sys.path.append('Functions/')
sys.path.append('Config/')
import config
import convert_datetime, datetime, functions
import cls_DataFactory_DS, cls_AssemblyWorker, cls_GSS
def return_dict_data(sta_date, end_date):
sql_update_data_fixed = """ SELECT MIN(ord_id), MAX(ord_id) FROM ord... |
# Generated by Django 2.2 on 2019-09-15 10:59
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('home', '0001_initial'),
]
operations = [
migrations.DeleteModel(
name='Student',
),
]
|
#!/usr/bin/env python3
from tkinter import *
from tkinter.ttk import *
from tkinter import messagebox
import time
import requests
root = Tk()
root.geometry("1200x600")
root.resizable(0,0)
root.title("Station3.v1.web-server")
tree = Treeview(root)
tree["columns"] = ('Percent', 'Status', 'Start', 'End')
tree.column(... |
import pytest
from raincoat.match.pypi import PyPIMatch
from raincoat.color import Color
@pytest.fixture
def match_module():
return PyPIMatch(
filename="filename",
lineno=12,
package="umbrella==3.2",
path="path/to/file.py",
element=""
)
@pytest.fixture
def match():
... |
from flask_restful import Resource, reqparse
from processors.data_management import extract_data, upload_to_aws, save_pickle
from sklearn.model_selection import train_test_split
from pipeline import model
from instances import config
import pandas as pd
from processors.data_management import load_pickle
class Train(Re... |
#!/usr/bin/python3
"""
Contains the State Class
"""
from models.base_model import BaseModel
class State(BaseModel):
""" State class has public attributes """
name = ""
|
import json
import django
from django import forms
from django.core.exceptions import ValidationError
from django.urls import reverse
from django.template import loader
from django.utils.encoding import force_text
from select2rocks.settings import SELECT2_OPTIONS, SELECT2_ATTRS
class Select2TextInput(forms.TextInpu... |
# -*- coding: utf-8 -*-
# _Author_: xiaofengShi
# Date: 2018-03-18 18:59:05
# Last Modified by: xiaofengShi
# Last Modified time: 2018-03-18 18:59:05
from net import net_tiny
import tensorflow as tf
import config as cfg
import os
import time
import datetime
from dataset.data_to_tfrecord import run_dataset_tfre... |
from Classes.polygon import Polygon
# Considering origin to be top left
class Tile(Polygon):
def __init__(self, size, x, y, label=""):
self.size = size
# Top left corner
self.x1 = x
self.y1 = y
# Bottom right corner
self.x2 = self.x1 + self.size
self.y2 = sel... |
from ColoredGraph import ColoredGraph
from itertools import permutations
import sys
from util import argmin
# Maximum number of vertices in graph for which brute force method is used
MAX_BRUCE_FORCE = 10
# Number of instance graphs provided by staff
NUM_INSTANCES = 495
def find_path(graph):
"""Given GRAPH, retur... |
#Implement Queue using Stacks
class QueueStack:
def __init__(self):
self.s1 = []
self.s2 = []
self.size = 0
def enqueue_stack(self , val):
self.s1.append(val)
self.size += 1
print("Queue pushed: " , self.s1)
... |
from tasks import add
add.delay(4,4,3)
|
import csv
from nltk.probability import FreqDist
from nltk.classify import SklearnClassifier
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_selection import SelectKBest, chi2
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import Pipeline
print 2
|
def knapsack_max_value(array, max_capacity):
'''
input:
- a list of tuples of initial goods: [(weight_1, value_1), (weight_2, value_2), ...]
- given capacity of the knapsack
output:
- a list of goods, maximizing the total value of knapsack, not exceeding max_capacity restriction
''... |
import sys
import argparse
import numpy as np
from .utils.interpolation import cubic_spline
import matplotlib.pyplot as plt
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('--points-num', type=int, default=21)
parser.add_argument('--periodic', type=bool, default=False)
return ... |
from graph_tools.bipartite_utils import simple_divide_vertices, extract_bipartite_adjacency, move_vertex
__author__ = 'Alexey'
def build_max_cut(adjacency):
left, right = simple_divide_vertices(adjacency.keys())
bipartite_adjacency = extract_bipartite_adjacency(adjacency, left, right)
v = find_vertex(adj... |
#-*- coding:utf8 -*-
from django.contrib import admin
from django.db import models
from django.forms import TextInput, Textarea
from shopback.orders.models import Order,Trade
class OrderInline(admin.TabularInline):
model = Order
fields = ('outer_id','outer_sku_id','title','buyer_nick','price','payment','n... |
"""TICCLAT version."""
# Don't forget version in CITATION.cff
__version__ = '0.2.2'
|
for row in range(7):
for col in range(5):
if (col==0) or ((col==4 or col==6) and row>=3) or (row==0) or ((row==3) and (col>=2)) or ((row==6) and (col<=3)) :
print("*",end="")
else:
print(end=" ")
print()
|
"""
一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为 “Start” )。
机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为 “Finish” )。
问总共有多少条不同的路径?
示例 1:
输入:m = 3, n = 7
输出:28
示例 2:
输入:m = 3, n = 2
输出:3
解释:
从左上角开始,总共有 3 条路径可以到达右下角。
1. 向右 -> 向下 -> 向下
2. 向下 -> 向下 -> 向右
3. 向下 -> 向右 -> 向下
示例 3:
输入:m = 7, n = 3
输出:28
示例 4:
输入:m = 3, n = 3
输出:6
... |
#!/usr/bin/env python
"""Implement a variant of Nim Game played by the computer and a human opponent.
Author: GuangXIONG
Email: gx239@nyu.edu
Time: 04:07PM Feb/10/15
"""
import sys
import random
def main():
# Initialize a list of heaps.
created_heaps = random_selector((3, 5, 7))
list_heaps = range(created_heaps)... |
import numpy as np
import sys
import math
import operator
import csv
import glob,os
import xlrd
import cv2
import pandas as pd
import os
import glob
from sklearn.svm import SVC
from collections import Counter
from sklearn.metrics import confusion_matrix
import scipy.io as sio
import pydot, graphviz
from keras.utils im... |
#Speeding up motif finding
##foreach p[K] is the longest substring of prefix.note!prefix,starting from the start.
from Bio import SeqIO
record = SeqIO.read('/home/cyagen1/Downloads/rosalind_revp.txt', 'fasta')
sequence = list(record.seq)
F_array = [0] * len(sequence)
k = 0
for i in range(2, len(sequence) + 1):
w... |
import MySQLdb
import time
# 云端数据库测试代码
# 打开数据库连接
db = MySQLdb.connect("62.234.154.66", "root", "123456", "internetofthings", charset='utf8' )
# 使用cursor()方法获取操作游标
con = db.cursor()
con.execute("insert into computer values ('11','1','2020-6-13 08:00:00','1','30','50','80')")
con.execute("insert into temperature values (... |
from indice_invertido_refinado import IndiceRefinado
index = IndiceRefinado("oi.txt")
print index.criaIndiceInvertido()
|
from moneynumber import *
from mlang import *
from compoundtreasure import *
from treasure import *
def check(obj):
print(id(obj))
def strtype(obj):
return "<" + str(type(obj))[8:-2].split(".")[-1] + ">"
def _debuginfo4CompoundTreasure(obj):
assert(type(obj) == CompoundTreasure)
ct = obj
print... |
from .jwt import JwtProvider
|
# Generated by Django 2.1.1 on 2018-09-27 19:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('catalogo', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='pessoa',
name='nascimento',
... |
#!/usr/bin/env python
import datetime
import sys
from boto.ec2 import cloudwatch
AWS_REGION = 'us-east-1'
AWS_KEY = ''
AWS_SECRET = ''
RDS_INSTANCE_ID = ''
### Real code
metrics = {"BinLogDiskUsage": {"type":"float", "value":None, "uom":"B"},
"CPUUtilization":{"type":"float", "value":None, "uom":"%"},
... |
#!/usr/bin/python
# Path to file with TEXT inputs.
file_path = './text.txt'
f = open(file_path, 'r')
# Trim out the quotation mark in the string
def trimQuo(sen):
for i in range(0,len(sen)):
if sen[i] == '"':
new_sen = sen[0:i]+sen[i+1:len(sen)]
return trimQuo(new_sen)
return sen
# Give an array of senten... |
import pandas as pd
train = pd.read_csv('train.csv')
test = pd.read_csv('test.csv')
train = train.drop("dropoff_datetime",axis = 1)
import numpy as np
import time
import datetime
#Convert test time to timestamp(unix code)
def convert_to_timestamp2(date):
date_as_string = str(date).strip()
return time.mktime(... |
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Fish
from .forms import FeedingForm
# Define the home view
def home(request):
return render(request,'home.html')
def about(request):
return render(request, 'about.html')
def fishlist(request):
fish = Fish.... |
import numpy as np
import matplotlib.pyplot as plt
from seaborn import kdeplot
import matplotlib.patheffects as mpe
import utils
from sklearn.metrics import precision_score, recall_score, roc_auc_score, label_ranking_average_precision_score
from sklearn.metrics import label_ranking_loss, confusion_matrix, average_pre... |
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout
from . forms import SignUpForm, UpdateForm, ContactForm, ImageForm
from accounts.models import User
from home.models impor... |
import os
class ExecSuite(object):
arg = None
"""docstring for ExecSuite"""
def __init__(self, arg = None):
super(ExecSuite, self).__init__()
self.arg = arg
def execAllure(self):
try:
os.system(" cd C:/python37/projects/<project>/src/Test/funcionais")
os.system(
"behave --f allure_behave.for... |
import poplib, getpass
from email import parser
def mail_connection():
pop_conn = poplib.POP3_SSL(input('Mail server: '))
pop_conn.user = input('Mail user: ')
pop_conn.pass_ = getpass.getpass('Mail password: ')
return pop_conn
def mail_fetch(delete_after=False):
pop_conn = mail_connection()... |
# 1. oper_num 이라는 변수에 1부터 10사이의 랜덤값을 추출하여 대입한다.
import random
oper_num = random.randint(1, 10)
print("랜덤값: ", oper_num) #랜덤값을 확인하기 위한 출력문
a = 300
b = 50
# 추출된 값이 1이거나 6이면 덧셈 연산을 처리한다.
if oper_num == 1 or oper_num == 6:
c = a + b
# 추출된 값이 2이거나 7이면 뺄셈 연산을 처리한다.
elif oper_num == 2 or oper_num == 7:
c = a - b
# 추출된... |
#import sys
#input = sys.stdin.readline
from itertools import accumulate
Q = 10**9+7
def getFactorials(N):
ret = [0]*(N+1)
ret[0] = 1
for i in range(1, N+1):
ret[i] = ret[i-1]*i%Q
return ret
def getInv(N):
inv = [0] * (N + 1)
inv[1] = 1
for i in range(2, N + 1):
inv[i] = (-... |
nums = []
def fizzbuzz(start, end, nums=None):
"""
Recursive Fizzbuzz
"""
if visit is None:
nums = []
# when this ends
if start == end + 1:
return nums
if start % 3 == 0 and start % 5 == 0:
nums.append('fizzbuzz')
return fizzbuzz(start+1, end)
elif s... |
import cv2
import numpy as np
def preprocess(img, params):
if params["hist_eq"]:
imgYuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)
imgYuv[:, :, 0] = cv2.equalizeHist(imgYuv[:, :, 0])
img = cv2.cvtColor(imgYuv, cv2.COLOR_YUV2BGR)
if params["gaussian_blur"]:
img = cv2.GaussianBlur... |
from flask import Flask
from flask import request, jsonify
from controller import Controller
app = Flask(__name__)
@app.errorhandler(404)
def page_not_found(e):
return "<h1>404</h1><p>The resource could not be found.</p>", 404
@app.route("/api/v1/bus_sec", methods=['GET'])
def bus_sec():
if request.method ... |
"""
REQUEST SCHEMA
"""
#pylint: disable=too-few-public-methods
#pylint: disable=bad-whitespace
#pylint: disable=import-error
from werkzeug.datastructures import FileStorage
from flask_restplus import reqparse
class UserRequestSchema:
"""Define all mandatory argument for creating User"""
parser = reqparse.RequestPar... |
# Generated by Django 3.0.6 on 2020-06-11 14:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Home', '0014_timedeal'),
]
operations = [
migrations.AlterField(
model_name='timedeal',
name='deal_name',
... |
import cv2
import numpy as np
img = cv2.imread('SOfaOutput_img.png')
LegInImg = cv2.imread('sofawithleg.jpg')
LegInImgRight = cv2.flip(LegInImg, 1)
list = [LegInImgRight,LegInImg]
Repleg = cv2.imread('leg.jpg')
for i in list:
res = cv2.matchTemplate(img, i, cv2.TM_CCOEFF_NORMED)
loc = np.where (res >= 0... |
'Python连接到 MySQL 数据库及相关操作(基于Python3)'
import pymysql.cursors
class Database:
connected = False
__conn = None
conf = {}
# 构造函数,初始化时直接连接数据库
def __init__(self,host='',port=3306,db='',user='',passwd='',charset='utf8'):
self.conf['host'] = host
self.conf['port'] = port
self.co... |
'''
Created on Nov 17, 2015
@author: cphurley
'''
import logging
import os
import re
import random
import json
import time
import webapp2
import jinja2
from google.appengine.ext import ndb
from lib.mtg.setutil import SetUtil
from lib.db.user import User
from lib.db.draft import Draft
from lib.db.drafter import Draft... |
from django.db import models
from account.models import Customer
from product.models import Product
from django.core.validators import MinLengthValidator
# from phonenumber_field.modelfields import PhoneNumberField
# Create your models here.
class Order(models.Model):
name = models.CharField('name', max_length=5... |
# Generated by Django 2.2.4 on 2019-08-20 06:34
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('marketing', '0003_auto_20190820_0234'),
('crm', '0006_pylead_user_id'),
]
operations = [
migrations... |
'''
author: juzicode
address: www.juzicode.com
公众号: 桔子code/juzicode
date: 2020.8.1
'''
print('\n')
print('-----欢迎来到www.juzicode.com')
print('-----公众号: 桔子code/juzicode \n')
import sys
from ctypes import *
pyt = CDLL('pytest.dll')
print()
print('指针:int')
pyt.modify_i.restype=c_int
pyt.modify_i.argtypes=(POI... |
def calculate_credit_card_number_check_digit(card_no):
total = 0
# start from last digit from credit card number
for position,digit in enumerate(card_no[::-1]):
num_digit = int(digit)
# position is even as credit card digit has a missing number
if position % 2 == 0:
multi... |
# Generated by Django 2.1 on 2019-05-15 12:47
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Article',
fields=[
... |
from . import api, check, constants, context, storage, types, util
from ._logging import set_logger
from .__version__ import __version__
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib.error
from time import sleep
from xml.etree import ElementTree
from dotmap import DotMap
from src.librecatastro.domain.cadaster_entry.cadaster_entry_html import CadasterEntryHTML
from src.librecatastro.scrapping.parser import Parser
from src.librecatastro.s... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable as Var
from copy import deepcopy
from ignite.metrics import Metric
from ignite.exceptions import NotComputableError
# These decorators helps with distributed settings
from ignite.metrics.metric import sync_all_reduc... |
from rest_framework import serializers
from rest.serializers import RabbitSerializer
from .models import Rabbit
import time
class Heap(object):
"""
Heap object handles sorting operation for database queries.
"""
def __init__(self, binary_tree):
self.tree = binary_tree
self.sort_time ... |
# coding: utf-8
# In[1]:
# Import relevant libraries
import numpy as np; np.random.seed(42); import tensorflow as tf; tf.set_random_seed(42);
import matplotlib.pyplot as plt; import pylab; import cv2;
import os; from os import listdir; from os.path import isfile, join
from Architecture import *
get_ipython().run_l... |
__author__ = 'lyk-py'
class UtilException(Exception):
pass
def is_palindrome(string):
return string == string[::-1]
def gen_word(letters, count):
from random import choice
r_list = []
for i in range(count):
r_list.append(choice(letters))
return "".join(r_list)
def is_url(string):... |
from django.shortcuts import get_object_or_404, render, redirect
from django.contrib.auth import login as auth_login, authenticate, logout as auth_logout
from django.contrib.auth.forms import AuthenticationForm
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.con... |
from orun.db import models
from orun.utils.translation import gettext_lazy as _
import base.models
class User(base.models.User):
user_sales_team = models.ForeignKey('sales.team', verbose_name=_("User's Sales Team"))
class Meta:
override = True
class Partner(base.models.Partner):
sales_team = mo... |
from dataclasses import dataclass
@dataclass
class Comprador:
nome: str
|
#!/usr/bin/env python3
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
'''
How to Run this script:
python iterative_reranking_v3.py --use_cache --gold ../../worldtree_corpus_textgraphs2019sharedtask_withgraphvis/questions/ARC-Elementary+EXPL-Dev.tsv --eval -... |
from .binary_rdf_results_table_parser import BinaryQueryResultParser
from .binary_rdf_parser import BinaryRDFParser
|
"""
smorest_sfs.modules.auth.helpers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
auth辅助文件
"""
from datetime import datetime
from typing import Dict, Optional
from flask_jwt_extended import decode_token
from sqlalchemy.orm.exc import NoResultFound
from .models import TokenBlackList
def _epoch_utc_to_datetime(epoch_... |
from django.http import HttpResponse
from django.shortcuts import render
from loginapp.models import User,Employee,Department
# Create your views here.
def login(request):
return render(request,"login.html")
def logincheck(request):
name = request.POST.get("username")
biao = request.POST.get("bi... |
from dataclasses import dataclass
from pymongo.collection import Collection
from filemanager.utils.uuid import generate_uuid
@dataclass
class File:
file_name:str
_id:str=None
description:str=None
# fresid:str=None
def __post_init__(self):
if not self._id:
self._id = generate_... |
"""
封装request
"""
import os
import random
import requests
from Common import Log
from Common.Consts import *
class Request:
def __init__(self):
"""
:param env:
"""
self.log = Log.MyLog()
self.headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) Appl... |
from copy import deepcopy as dc
import numpy as np
#distord each value by a gaussian and add it to snippets
#no return
def data_augmentation(snippets, data_gen_config):
#first distord each value by a gaussian with percent_varianz varianz
distortet_snippets = []
perc_dist = float(data_gen_config["percent_va... |
class Solution(object):
def palindromePairs(self, words):
"""
:type words: List[str]
:rtype: List[List[int]]
"""
word_mapping = {w:i for i, w in enumerate(words)}
rv = []
for i, word in enumerate(words):
for prefix_length in range(len(word)+1):
... |
"""Scrape top 100 authors"""
import logging
import requests
from bs4 import BeautifulSoup
from multiprocessing.pool import ThreadPool
from typing import List, Generator, Dict, Union
class ScraperGutenburg:
"""
Collect this list of yesterday's top 100 authors.
For each author, gather their unique ebook for... |
# Copyright (c) 2021 War-Keeper
import os
import sys
from discord.ext import commands
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import db
# -----------------------------------------------------------
# This File contains commands for voting on projects,
# displaying which groups hav... |
""" The *definition* of an action in a tool bar or menu. """
# Enthought library imports.
from traits.api import Str
# Local imports.
from location import Location
class Action(Location):
""" The *definition* of an action in a tool bar or menu. """
#### Action implementation ##############################... |
"""Test myi public API."""
import numpy as np
import pytest
from myia import myia
from myia.operations import random_initialize, random_uint32
@pytest.fixture(params=[pytest.param("pytorch"), pytest.param("relay")])
def _backend_fixture(request):
return request.param
EXPECTED = {
"pytorch": (
np.a... |
############################################################
# CIS 521: Homework 8
############################################################
student_name = "Yu-Ning Huang"
############################################################
# Imports
############################################################
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 匿名函数
# 当我们在传入函数时,有些时候,不需要显式地定义函数,直接传入匿名函数更方便
# 在Python中,对匿名函数提供了有限支持。还是以map()函数为例,计算f(x)=x2时,除了定义一个f(x)的函数外,还可以直接传入匿名函数
print(list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])))
# 通过对比可以看出,匿名函数lambda x: x * x实际上就是
def f(x):
return x * x
# 关键字lambda表示匿名函数,冒号前面的x表... |
#the following is the function to calulate all the factors of the users awnser.
def factorformula(n):
x = 1
while x <= n:
if n % x == 0:
print(x)
x = x + 1
else:
x = x+1
factorformula(24) |
import os, random, json
from pprint import pprint
from flask import Flask, url_for, render_template, request, redirect
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/projects')
def projects():
return 'Projects page'
@app.route('/projects/strawpoll')
def get_st... |
from flask import jsonify, request, session
from models import db
from models.index import Collection, Comment,CommentLike
from . import news_blu
@news_blu.route("/news/collect", methods=["POST"])
def news_collect():
# 1.提取参数
news_id = request.json.get("news_id")
action = request.json.get("action")
#... |
import os
import tarfile
import subprocess
import pprint
from six.moves import urllib
# import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.preprocessing import Imputer
from sklearn.preprocessing import LabelBinarizer
from sklea... |
# judge circle, count the operations
def judge_circle(moves):
ver_num, hor_num = 0, 0
for i in moves:
if i == 'U':
ver_num += 1
elif i == 'D':
ver_num -= 1
elif i == 'L':
hor_num -= 1
else:
hor_num += 1
if ver_num == 0 and hor_... |
import os, sys, glob
#### run like: python OpenLog.py <output root file name>
outputFileName = sys.argv[1]
count = 0
os.system('bash MakeLib.sh')
os.system('ls *.tgz > file75V.txt')
fileName = 'file75V.txt'
with open(fileName) as textFile:
for line in textFile.readlines():
### untar the main file
os... |
#!/usr/bin/env python
from random import randint
import random
import copy
import numpy as np
import math
from sets import Set
import time
from random import shuffle
import task_classes
import string_operations
Gamma=.98
C=1.
def check_variables_task_init(Q,N,Na,s,t):
if N.get(s) == None:
N[s] = 1.
else:
N[s]... |
from ED6ScenarioHelper import *
def main():
# 封印区域
CreateScenaFile(
FileName = 'C4300 ._SN',
MapName = 'Grancel',
Location = 'C4300.x',
MapIndex = 216,
MapDefaultBGM = "ed60035",
Flags = 0,
... |
from test_plus.test import TestCase
from bm.users.models import User
from bm.users.utils import import_class
class TestUserURLs(TestCase):
def test_import_class(self, value="bm.users.models.User"):
self.assertEqual(import_class(value), User)
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
import re
x = int(input())
# regex_num = r'^(?=([a-zA-Z]*(?:\d[a-zA-Z]*){3,}$))'
# regex_alpha = r'^(?=([a-z0-9]*(?:[A-Z][a-z0-9]*){2,}$))'
# https://stackoverflow.com/questions/51358885/regex-no-character-should-repeat
# https://stackoverflow.com/qu... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
## 存储数据
class Test20191225Item(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
# pass
# company_code=... |
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
#input
# 29
# 49 1.40
# 92 1.67
# 103 2.21
# 70 1.71
# 67 1.47
# 46 1.96
# 50 1.44
# 71 1.65
# 88 2.10
# 46 1.26
# 115 2.60
# 94 2.22
# 44 1.35
# 60 1.52
# 45 1.54
# 120 2.74
# 111 1.99
# 41 1.21
# 44 1.45
# 53 1.59
# 51 1.73
# 76 2.05
# 102 1.76
# 107 2.31
# 55 1.25
# 43 1.75
# 51 1.30
# 73 2.14
# 57 1.40
def BMI(wei... |
# Copyright (c) 2022 Dell Inc. or its subsidiaries.
# All Rights Reserved.
#
# 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 requi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.