text stringlengths 8 6.05M |
|---|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
import seaborn as sns
from sklearn.preprocessing import scale
import sklearn.linear_model as skl_lm
from sklearn.metrics import mean_squared_error, r2_score
import statsmodels.api as sm
import statsmodels.for... |
from json import loads
from pathlib import Path
from typing import Union
from django.contrib.auth.models import ( # type: ignore
Permission,
Group,
)
from django.contrib.contenttypes.models import ContentType # type: ignore
from django.core.management.base import BaseCommand # type: ignore
from toolz import ... |
from threading import Thread
import urllib
def th(ur):
htmltext = urllib.urlopen(ur).read() # open the parameter as an argument
print htmltext[0:100] # print the first 100
urls = "http://google.com http://cnn.com http://yahoo.com".split() # create an array of urls
threadlist = [] # you need a data structure so ... |
from django.db import models
from datetime import datetime
from django.contrib.auth.models import User
class Category(models.Model):
parent = models.ForeignKey('self', blank=True, null=True,
related_name='children')
name = models.CharField(max_length=300)
slug = models.SlugFie... |
import random
inputFileName = 'data.csv'
outputFileName_train = inputFileName[:-4] + '_train.csv'
outputFileName_test = inputFileName[:-4] + '_test.csv'
headers = True
f_w_train = open(outputFileName_train, 'w')
f_w_test = open(outputFileName_test, 'w')
p = 0.3
f = open(inputFileName, 'r')
nrows = 0
for line in f:
... |
from sys import argv
script, filename = argv
target = open(filename).read()
print(target) |
from . import Anime
from . import Games
from . import Members
from . import Pets
from . import Utils
|
from django.shortcuts import render,redirect
from django.http import HttpResponse
from .models import todos
from .forms import listform
# Create your views here.
def index(request):
if request.method=="POST":
form=listform(request.POST or None)
if form.is_valid:
form.save()
... |
import Fortuna as rng
class Weapon:
weapons = rng.TruffleShuffle([
'Cutlass', 'Hook', 'Steam Powered Flint Lock', 'Knife', 'Cannon',
'Musket', 'Black-powder Blunderbuss', 'Dagger', 'Scimitar',
'Boarding Axe',
])
def __init__(self):
self.name = self.weapons()
def __str... |
# -*- conding:Utf-8 -*-
def add(a,b):
print("ADDING %d +%d" % (a,b))
return a + b
def subtract(a,b):
print("SUBTRACTING %d -%d" % (a,b))
return a - b
def multiply(a,b):
print("MULTIPLYING %d * %d" % (a,b))
return (a*b)
def divide(a,b):
print("DIVIDING %d /%d" % (a,b))
return (a/b)
p... |
from time import sleep
from unittest import mock
from gitrack import config
from .helpers import repo_data_dir, ProviderForTesting
class TestStart:
def test_basic(self, cmd):
result, repo_dir = cmd('start')
assert result.exit_code == 0
store = config.Store.get_for_repo(repo_dir)
... |
import os
from setuptools import setup
import re
import sys
MIN_PYTHON_VERSION = (2, 5)
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'requestflow'))
from version import VERSION
if __name__=="__main__":
if sys.version_info < MIN_PYTHON_VERSION:
args = (NAME, VERSION, ".".join([str(x) for ... |
import FWCore.ParameterSet.Config as cms
source = cms.Source("PoolSource",
fileNames = cms.untracked.vstring(
'/store/user/skaplan/noreplica/MinBiasBeamSpotPhi0R4_HISTATS/outfile14TeVSKIM_100_1_PyU.root',
'/store/user/skaplan/noreplica/MinBiasBeamSpotPhi0R4_HISTATS/outfile14TeVSKIM_101_1_icZ.root',
'/store/user... |
# standard imports
import os
# RootTools
from RootTools.core.standard import *
# Logging
import logging
logger = logging.getLogger(__name__)
dir = "/scratch/rschoefbeck/"
TTZ_200PU = Sample.fromDirectory("TTZ_200PU", texName = "ttZ (200PU)", directory = [os.path.join( dir, "TTZ", "200PU")], treeName =... |
class ResponseError(Exception):
pass
class ResponseCodeError(Exception):
pass
class AutoCodeConfigError(Exception):
pass
|
from tkinter import *
import tkinter as Tk
import tkinter as ttk
import matriz
from tkinter import messagebox
matr = matriz.matriz()
class Interfaz:
def __init__(self):
self.root = Tk.Tk()
self.entries = []
def ejecutarInicioMatriz(self):
matr.crearMatriz()
... |
#coding: utf8
import csv
from ftplib import FTP
import os
import os.path
import re
from urlparse import urlparse
from invoke import run, task
import requests
open_data_licenses = [
'http://data.gc.ca/eng/open-government-licence-canada',
'http://donnees.ville.montreal.qc.ca/licence/licence-texte-complet/',
'htt... |
from datetime import datetime
from haystack import indexes
from zhihu.news.models import News
from zhihu.articles.models import Article
from zhihu.qa.models import Question
from django.contrib.auth import get_user_model
from taggit.models import Tag
class ArticleIndex(indexes.SearchIndex, indexes.Indexable):
'''... |
import py
import pytest
import io
from atsim.potentials.config import Configuration
from atsim.potentials.config._config_parser import ConfigParser
from .._runlammps import needsLAMMPS, extractLAMMPSEnergy, runLAMMPS, lammps_run_fluorite_fixture, lammps_run_fixture
from .._rundlpoly import needsDLPOLY, runDLPoly, e... |
import tensorflow as tf
# tf.concat 除合并轴维度之外 的 其他轴维度 必须一致。
a = tf.ones([4,35,8])
b = tf.ones([2,35,8])
c = tf.concat([a,b], axis=0) # axis=0 合并0轴, 1轴(35) 和 2轴(8) 必须相等
print(c.shape)
# In[]:
a = tf.ones([4,35,8])
b = tf.ones([4,35,8])
c = tf.concat([a,b], axis=1) # axis=1 合并1轴, 0轴(4) 和 2轴(8) 必须相等
print(c.shape)
d = tf... |
# -*- coding: utf-8 -*-
import scrapy
import os
from iachina.items import IachinaItem
class IachinaSpiderSpider(scrapy.Spider):
name = "iachina_spider"
allowed_domains = ["iachina.cn"]
start_urls = (
'http://old.iachina.cn/product.php?action=company&ttype=2',
)
headers = {
'accept... |
import logging
from collections import Counter
from antlr4 import *
from tptp_grammar.cnf_formulaLexer import cnf_formulaLexer as Lexer
from tptp_grammar.cnf_formulaParser import cnf_formulaParser as Parser
from tptp_grammar.cnf_formulaListener import cnf_formulaListener as Listener
from questions.utils import timer
... |
# -*- coding: utf-8 -*
import numpy as np
import matplotlib.pyplot as plt
#
#ВнИМАНиЕ!111
#используес python 2.7
def calcilate_parametrs(result):
tp=0
tn=0
fp=0
fn=0
for i in range(len(result)//2):
#True Negative
if result[i]==0:
tn+=1
#Fasle Negative
els... |
import os
os.system("find ./apps/ -type d -name 'migrations' -exec rm -rf {} +")
os.system("find ./apps/ -type d -name '__pycache__' -exec rm -rf {} +")
|
from rest_framework.response import Response
from rest_framework import (generics,
viewsets,
mixins,
filters)
from rest_framework.permissions import (IsAuthenticatedOrReadOnly,
IsAuthenticat... |
from django.db import models
# Create your models here.
from movie_app.models import DateBaseModel
class AllUser(DateBaseModel):
first_name = models.CharField(max_length=32)
last_name = models.CharField(max_length=32, blank=True, null=True)
phone = models.CharField(max_length=20, blank=True, null=True)
... |
import sys
import re
import requests
import spacy
def main(args):
if len(args) == 0:
print("usage: \n" + sys.argv[0] + " <url> [url...]")
exit(0)
nlp = spacy.load('en')
for url in args:
text = extract_text(url)
doc = nlp(text)
for ent in doc.ents:
if e... |
#!/usr/bin/env python3
# Copyright (c) 2016 Anki, Inc.
#
# 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 in the file LICENSE.txt or at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unles... |
# PROBLEM 3
#
# Modify the below functions acceleration and
# ship_trajectory to plot the trajectory of a
# spacecraft with the given initial position
# and velocity. Use the Forward Euler Method
# to accomplish this.
import numpy
import matplotlib.pyplot
h = 5.0 # s
EARTH_MASS = 5.97e24 # kg
GRAVITATIONAL_CONSTANT... |
# https://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list-in-reverse/problem
# sol1
# using an array
def reversePrint(head):
result = []
if head is None:
return
if head.next is None:
print(head.data)
return
temp = head
while temp is not None:
result.... |
from random import randint
from ai import tah_pocitace, tah
def vyhodnot(pole):
if 'xxx' in pole:
return 'x'
elif 'ooo' in pole:
return 'o'
elif '-' not in pole: # Nikdy nepouzivejte not '-' in pole, je to mene citelne
return '!'
else:
return '-'
def tah_hrace(pol... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.conf.urls import url
from . import views
from django.contrib.auth.decorators import login_required
app_name = 'coffee'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^list_all/',
login_required(views.list_all),
name='list_... |
from flask import Flask, redirect, url_for, request, render_template
from werkzeug.utils import secure_filename
from scapy.all import *
app = Flask(__name__)
# app.config['UPLOAD_FOLDER'] = '/uploads'
@app.route('/uploader', methods = ['POST', 'GET'])
def uploader():
if request.method == 'POST':
if 'file' not in r... |
from random import choice, sample
from flask import Flask, render_template, request
# "__name__" is a special Python variable for the name of the current module
# Flask wants to know this to know what any imported things are relative to.
app = Flask(__name__)
AWESOMENESS = [
'awesome', 'terrific', 'fantastic', ... |
#!/usr/local/bin/python
import sys
import pycurl
from string import maketrans
import cStringIO
import re
import urllib
import glob
import os
# Set Your MC directory
minecraftHome = "/home/minecraft/"
projectHome = []
plugin_versions = []
new_plugin = ""
plugsList = []
plugsName = []
plugsHome = []
plugSearch = []
clas... |
import serial
import serial.tools.list_ports
import sys
from datetime import datetime
import os
class SerialWrapper:
def __init__(self):
self.ser = serial.Serial()
#get file name
now = datetime.now()
time = now.strftime("%Y-%m-%d-%H:%M:%S")
fileName = "tel-" + time
... |
# def haha(x,y):
# return x*y
a = lambda x,y:x*y
print(a(4,3))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import handin6
test1 = handin6.fasta_to_dict("test1.fasta")
test2 = handin6.fasta_to_dict("test2.fasta")
for item1 in test1:
if not item1 in test2:
print item1 |
from operator import itemgetter
class playerSort(object):
def __init__(self, playerList):
playerList = sorted(playerList, key=itemgetter('projection'), reverse=True)
self.positionList = set( [player['position'] for player in playerList] )
self.byPosition = {}
self.prunedByPosition =... |
#·······························································#
#· UNIVERSIDAD NACIONAL SAN ANTONIO ABAD DEL CUSCO #
#· Escuela Profesional de Ingenieria Informatica y de Sistemas#
#· Robotica y Procesamiento de Señales #
#· Reconocimiento de objetos por medio del histograma ... |
""" Contains upgrade tasks that are executed when the application is being
upgraded on the server. See :class:`onegov.core.upgrade.upgrade_task`.
"""
from onegov.core.upgrade import upgrade_task
from onegov.core.utils import linkify
from onegov.org.models import Organisation
from onegov.people import Agency
@upgrade... |
# -*- coding: utf-8 -*-
import logging
from openerp import pooler
from openerp.tools.translate import _
_logger = logging.getLogger(__name__)
from openerp.osv import osv, fields
from openerp import netsvc
class rel_ifrs_tributario(osv.osv):
_name = 'rel.ifrs.tributario'
_columns = {
'ifrs_id': fie... |
def merge_sorted_list(arr1, arr2):
# m = len(arr1), n = len(arr1)
# since we know arr1 is always greater or equal to (m+n)
# we compare arr2[i] with arr1[j] element and check if it
# should be placed there
i, j = 0, 0
while i < len(arr1) and j < len(arr2):
if arr2[j] == arr1[i] or arr2[... |
# User input DNA sequence
try:
DNA_sequence = input("Please enter the DNA sequence below: \n")
except:
print("Invalid, please enter a valid DNA sequence.")
# DNA sequence to uppercases
DNA = DNA_sequence.upper()
# check for the nucleotides AT and GC and calculate the proportion
count_AT = 0
count_GC = 0
for nuc... |
"""
Div-conforming B-spline discretization of 3D Taylor--Green flow, using the
method of subgrid vortices.
"""
from tIGAr import *
from tIGAr.compatibleSplines import *
from tIGAr.BSplines import *
from tIGAr.timeIntegration import *
import math
import ufl
# Re-ordering of DoFs causes FunctionSpace creation to slow d... |
# File_name: stop_eks.py
# Purpose: Stop load balancers that are running
# Problem: botocore.exceptions.ClientError: An error occurred (AccessDeniedException) when calling the ListClusters operation: Account 015670528421 is not authorized to use this service
# Author: Søren Wandrup-Bendixen
# Email: soren.wandrup-Bendi... |
from mesh_server import *
from boundarycondition_server import *
from tqdm import tqdm # status bar
import os
import subprocess
import numpy as np
import matplotlib as mpl
if os.environ.get('DISPLAY','') == '':
print('no display found. Using non-interactive Agg backend')
mpl.use('Agg')
import matplotlib.pyplot ... |
from django.shortcuts import render, get_object_or_404
from django.utils import timezone
from .models import Project, Task, Comment
from .forms import ProjectForm, UserForm, UserProfileForm, TaskForm, CommentForm
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
# Create y... |
import random
n = 10
print n
for _ in range(n):
print random.choice([0,1]),
|
#Schreiben Sie ein Programm,
#das alle durch 3 und 7 teilbaren Zahlen zwischen j und k (k > j) ermittelt.
j=int(input("Please select min:"))
k=int(input("Please select max:"))
def finder (j,k):
while j<=k:
if j%3==0 and j%7==0 :
j+=1
else:
j+=1
retur... |
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=100, verbose_name='分类')
def __str__(self):
return self.name
class Tag(models.Model):
name = models.C... |
#!/usr/bin/python
import linkedlist
L = linkedlist.LinkedList()
L.insert_at_head(1)
print("The value of the head is {0}".format(L.head.data))
L.insert_at_head(2)
print("The value of the head is now {0}".format(L.head.data))
L.insert_at_head(3)
print("The value of the head is now {0}".format(L.head.data))
a = L.del... |
from stdmodandoption import *
import cameron_functions as CF
import collections
def kslaw(ssdict):
nested_dict = lambda: collections.defaultdict(nested_dict)
plotdict = nested_dict()
runtodo=ssdict['runtodo']
wanted=ssdict['wanted']
print 'wanted', wanted
startno=ssdict['startno']
Nsnap=ssd... |
from django.conf.urls.defaults import patterns, include
from api.resources import CurrencyItemResource
from tastypie.api import Api
v1_api = Api(api_name='v1')
v1_api.register(CurrencyItemResource())
urlpatterns = patterns('',
(r'^api/', include(v1_api.urls)),
) |
from flask import Flask , request , render_template
from flask_cors import CORS ,cross_origin
from Log_Writer.logger import App_Logger
from Raw_Data_Formatter.data_formatter import formatter
from Data_Validator.data_validator import Validator
from Preprocessing.preprocessor import Preprocessor
from Get_Model_for_Cluste... |
import os
from pyFG import FortiOS
from cloudify.decorators import operation
from cloudify.state import ctx_parameters as inputs
TEMPLATE_CONFIG_FILE = 'portConfig.conf'
CONFIG_FILE = 'portConfig'
FIREWALL_FILE = 'firewall.conf'
TMP_CONFIG_FILE = '/tmp/portConfig'
portIdToSearch = 'portX'
portIpToSearch = 'PORTIP'
po... |
import brownie
import pytest
DEADLINE = 99999999999
storage_bytecode = "0x6080604052600560005534801561001557600080fd5b5060ac806100246000" \
"396000f3fe6080604052348015600f57600080fd5b5060043610603257600035" \
"60e01c806360fe47b11460375780636d4ce63c146053575b600080fd5b605160"... |
import numpy as np
from sklearn.datasets import load_iris
from sklearn.preprocessing import MinMaxScaler, StandardScaler
from sklearn.model_selection import train_test_split, KFold, cross_val_score
from sklearn.metrics import accuracy_score
from sklearn.svm import LinearSVC, SVC
from sklearn.neighbors import KNeighbor... |
"""This program will print out the input as output method"""
def reverseinput():
"""This main function will print out input provided."""
var_x = int(input())
print(var_x)
print(var_x + 5)
print(var_x - 17)
print(var_x * 32)
print((5 * var_x ** 2) + (10 * 5 * var_x) + 3)
reverseinput... |
#! /usr/bin/env python3
# -*- coding:utf-8 -*-
__author__ = 'wjq'
from peewee import *
from playhouse.db_url import connect
import datetime
import json
import bson
db = connect('mysql://root:123456@localhost:3306/cms_dev')
class Info(Model):
id = PrimaryKeyField()
rhost = CharField()
rport = IntegerField(... |
import numpy as np
import cv2
import glob
import matplotlib.pyplot as plt
import random
# Calibrate camera
def calibrate(img, objpoints, imgpoints):
# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# Find corners of the chessboard
ret, corners = cv2.findChessboardCorners(gray, (... |
#!/usr/bin/env python
import sys
import rospy
import math
from std_msgs.msg import Float64
from local_pathfinding.msg import AISMsg, GPS, path, latlon, windSensor
from utilities import *
from Sailbot import *
from matplotlib import pyplot as plt
from matplotlib import patches
import time
# Constants
VISUALIZER_UPDATE_... |
from ED6ScenarioHelper import *
def main():
# 柏斯
CreateScenaFile(
FileName = 'C1211_1 ._SN',
MapName = 'Bose',
Location = 'C1211.x',
MapIndex = 1,
MapDefaultBGM = "ed60010",
Flags = 0,
Ent... |
# Tuples are like lists & dictionaries BUT they are IMMUTABLE!
# Once an element is inside a tuple, it CANNOT be reassigned
# Tuples use parenthesis
t = (1, 2, 3)
print(type(t))
# <class 'tuple'>
my_list = [1, 2, 3]
print(type(my_list))
# <class 'list'>
t = ('one', 2)
print(t)
# ('one', 2)
print(t[0])
# one
print... |
# coding: utf-8
# In[4]:
from http.server import HTTPServer, SimpleHTTPRequestHandler
import ssl
httpd = HTTPServer(('localhost',8888), SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket(httpd.socket, server_side=True, certfile='cert.pem', keyfile='key.pem')
httpd.serve_forever()
|
from typing import List
from fastapi import APIRouter, Depends, FastAPI, File, UploadFile, BackgroundTasks
from sqlalchemy.orm import Session
from starlette.requests import Request
from Scripts.fastapp.common.consts import UPLOAD_DIRECTORY, USING_MODEL_PATH
from Scripts.fastapp.database.conn import db
from Scripts.fa... |
ans = ""
for i in range(1, 101):
out = ""
if (i % 3 == 0):
out += "Fizz"
if (i % 5 == 0):
out += "Buzz"
if (out == ""):
out += str(i)
ans += out + "\n"
correct = ""
for i in range(1, 101):
correct += str(("Fizz" * (i % 3 == 0) + "Buzz" * (i % 5 == 0) or i)) + "\n"
print... |
#!/usr/bin/env python
import sys
sys.path.insert(0, '..')
import models.model as model
import gaModel.gaModel_Yuri as ga
import numpy as np
def execGaModel(year, region, qntYears=5, times=1):
"""
Creates the GAModel with JMA catalog
"""
observations = list()
means = list()
for i in range(qntYe... |
#!/usr/bin/python3
def inherits_from(obj, a_class):
"""Check if ihnerits but not the same"""
if type(obj) is a_class:
return False
else:
if issubclass(type(obj), a_class):
return True
else:
return False
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
File Name: hello_async.py
Description:
Created_Time: 2016-09-27 11:13:06
Last modified: 2016-09-27 11时29分27秒
'''
# event loop 是核心,主要有一下的作用。
# 1. 注册,执行,取消执行以及延时调用。
# 2. 为服务端和客户端提供transport
# 3. 为子进程和其他进程通信提供transports
# 4. 线程池函数调用授权
# 例子,简单调用
_author = 'arron'
_em... |
from shorthand.utils.config import CONFIG_FILE_LOCATION
from shorthand.web.app import create_app
default_app = create_app(CONFIG_FILE_LOCATION)
|
from django.contrib import admin
from .models import mileStone
admin.site.register(mileStone) |
from .main import RateLimit as RateLimit
from .redis import RedisInterface as RedisInterface, redisinterface as redisinterface
__all__ = ("RateLimit", "RedisInterface", "redisinterface")
__author__ = "PredaaA"
__version__ = "0.1.23"
|
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request, 'news/index.html')
def search(request):
return render(request, 'news/search.html')
|
from heapq import heappush, heappop, heapify
def solution(q, k):
heapify(q)
answer = 0
while len(q) > 1:
food1 = heappop(q)
if food1 >= k:
return answer
food2 = heappop(q)
heappush(q, food1 + 2*food2)
answer += 1
return answer if q[0] >= k else -1
... |
import datetime
import requests
import configparser
from bot_handler import BotHandler
config = configparser.ConfigParser()
config.read('config.ini')
myTelegramToken = config['Data']['telegram_token']
bot = BotHandler(myTelegramToken)
# This tuple contains greeting keywords
user_greetings = ('hello', 'hi', 'whats u... |
import requests
from lxml import etree
def fetch_links(url):
res=requests.get(url).text
return res
def in_page(url):
r=requests.get(url).text
re=etree.HTML(r)
img_urls=re.xpath('//div[@class="x-loaded"]/img/@src')
data=[]
for img_url in img_urls:
img_url='http:%s' %img_url
... |
import numpy as np
chosen_pixel = [127, 255, 0]
available_pixels = {'red':[255,0,0], 'green':[0,255,0], 'blue':[0,0,255], 'magenta':[255,0,255],
'tomato':[255, 99, 71], 'lawn green':[124,252,0], 'steel blue':[70,130,180]}
distances = []
for key, value in available_pixels.items():
a1 = np.asarr... |
# -*-coding:utf-8-*-
from flask import g, current_app
from flask_restful import reqparse
from albumy.common.restful import RestfulBase, success_response, raise_400_response, raise_404_response
from albumy.extensions import login_required
from albumy.models import User
from albumy.utils.tokens import generate_confirm_t... |
# Generated by Django 2.2.11 on 2020-06-01 13:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('order', '0010_auto_20200406_1707'),
]
operations = [
migrations.AlterField(
model_name='productinbasketmodel',
name... |
#
# Kiwi - An open source application framework
# Copyright (C) 2012-Today Thibaut DIRLIK <thibaut.dirlik@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of ... |
"""
We will use this script to learn Python to absolute beginners
The script is an example of BMI_Calculator implemented in Python
The BMI_Calculator:
# Get the weight(Kg) of the user
# Get the height(m) of the user
# Caculate the BMI using the formula
BMI=weight in kg/height in meters*height in me... |
#coding:utf8
from collections import OrderedDict
from goods.models import GoodsChannel
def get_categories():
# 初始化存储容器
categories = OrderedDict()
# 获取一级分类
channels = GoodsChannel.objects.order_by('group_id', 'sequence')
# 对一级分类进行遍历
for channel in channels:
# 获取group_id
group_i... |
from rest_framework import serializers
from kratos.apps.configuration.models import Configuration
from kratos.apps.app.serializers import AppSerializer
class ConfigurationSerializer(serializers.ModelSerializer):
appinfo = AppSerializer(read_only=True, source='app')
class Meta:
model = Configuration
... |
import ixcom
import time
import sys
import struct
import argparse
import socket
import io
import os
class TextFileParser(ixcom.parser.MessageParser):
def __init__(self, outputfile, skip_parameter=list(), print_request = True):
super().__init__()
self.ignore_output = False
self.outputfile =... |
import pygame
class Following:
def __init__(self, top_left_corner,color):
width = 13
height = width
# self.color = pygame.Color("#000000")
self.color = color
self.rect = pygame.Rect(top_left_corner, (width, height))
self.top_left_corner = top_left_corner
... |
# modules
import webbrowser
from win10toast_click import ToastNotifier
# function
page_url = 'http://github.com/'
def open_url():
try:
webbrowser.open_new(page_url)
print('Opening URL...')
except:
print('Failed to open URL. Unsupported variable type.')
# initialize
toaster = To... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
n=input()
l=[int(i) for i in n]
ans=[sum(l),n]
for i in range(len(n)-1):
t0=0
t1=""
for j in range(len(n)-1):
if i==j:
t0+=l[j]-1
t1+=str(l[j]-1)
t0+=9*(len(n)-j-1)
t1+="9"*(len(n)-j-1)
break... |
from django.contrib import admin
from . models import Brand, Accordion, ProductOrder, Cart
class AccordionAdmin(admin.ModelAdmin):
list_display = ('model_name', 'brand', 'price')
class ProductCartAdmin(admin.ModelAdmin):
list_display = ('product', 'quantity')
class CartAdmin(admin.ModelAdmin):
list_di... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset=pd.read_csv("hours.csv")
X=dataset.iloc[:,:-1].values
y=dataset.iloc[:,1].values
dataset.head()
from sklearn.linear_model import LinearRegression
regressor=LinearRegression()
regressor.fit(X,y)
#LinearRegression(copy_X=Tr... |
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA256
from Crypto.Hash import RIPEMD
import random
import binascii
import sys
# Copyright (C) 2011 Sam Rushing
# Copyright (C) 2013-2014 The python-bitcoinlib developers
#
# This file is part of python-bitcoinlib.
#
# It is subject to the license terms in the ... |
from ophyd.controls import EpicsMotor, PVPositioner, EpicsSignal
# M1A
kwargs = {'act': 'XF:23IDA-OP:1{Mir:1}MOVE_CMD.PROC',
'act_val': 1,
'stop': 'XF:23IDA-OP:1{Mir:1}STOP_CMD.PROC',
'stop_val': 1,
'done': 'XF:23IDA-OP:1{Mir:1}BUSY_STS',
'done_val': 0}
m1a_z = PVPos... |
#-------------------------------------------------------------------------------
# Name: Flappy Mario v1.4
# Purpose:
#
# Author: Gabriel
#
# Created: 12/07/2014
# Copyright: (c) Gabriel 2014
# Licence: <your licence>
#------------------------------------------------------------------------------... |
# Hint: You may not need all of these. Remove the unused functions.
from hashtables import (HashTable,
hash_table_insert,
hash_table_remove,
hash_table_retrieve,
hash_table_resize)
class Ticket:
def __init__(self, s... |
from enum import Enum
class Strategy(Enum):
DISTRESSED = 0
GROWTH = 1
INDUSTRY_FOCUSED = 2
VENTURE_CAPITAL = 3
MIDDLE_BUYOUT = 4
LARGE_BUYOUT = 5
|
#!/usr/bin/env python3
""" Logistic regression for prediction of satisfying assignments """
import os
import os.path
from dataset import load_dataset
import tensorflow as tf
features = []
for sign in ["x", "-x"]:
for phi in ["phi_1", "phi_2", "phi_3", "phi_4", "phi_horn", "phi_cohorn", "phi"]:
features +=... |
import os
import pandas as pd
import cv2
import torch
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from torch import optim, nn
from efficientnet_pytorch import EfficientNet
from tqdm import tqdm
from sklearn.model_selection import train_test_split
class AptosDataset(Dat... |
# excel sheet column number
import math
def solution(s):
result = 0
for i in range(len(s)):
result += (ord(s[i])-64)*math.pow(26, len(s)-i-1)
return int(result)
if __name__ == '__main__':
print(solution('AA')) |
def partial(func : Callable, *args, **kwargs):
'''
partial
Simple implementation for false currying
:: func :: Function to curry
:: *args :: Positional arguments
:: **kwargs :: Keyword arguments
'''
def p_func(*p_args, **p_kwargs):
return func(*args, *p... |
from django.db import models
class Movie(models.Model):
title = models.CharField(max_length=200)
year = models.IntegerField(default=0)
trailer_id = models.URLField(max_length=200)
poster_url = models.URLField(max_length=200)
budget = models.IntegerField(default=0)
rating = models.FloatField(def... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.