text stringlengths 38 1.54M |
|---|
from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
# Create your views here.
"""
request是httprequest的一个对象
request包含一些浏览器的提交信息
"""
def index(request):
# num = "1" + 1
return render(request, 'booktest/index.html')
def show_arg(num):
return HttpResponse(num)
... |
from fonctions.conn_liste import conn
from fonctions.fonction_print_armures import print_armure
import fonctions.fonction_lancement_menu_combat as jeu
def equiper_armure(user, armure) :
update_cursor=conn.cursor()
if armure.type_armure == "casque" :
update_query = ("UPDATE equipement_users SET {0... |
# добавим обработку исключений. ЭТО БАЗОВАЯ ГИГИЕНА ПРОГРАММИСТА, БЕЗ НЕЕ НЕ БЕРУТ НА РАБОТУ
# исключение надо добавлять перед той частью кода, которая выдает ошибку:
# 1) отсоединяемся от интернета ->
# Traceback (most recent call last):
# File "API_and_weather.py", line 31, in <module>
# print(weather_by_city('... |
from rest.api.views import CreateOrGetGame, CreateOrUpdatePlayer
from django.urls import path
app_name = "rest"
urlpatterns = [
path('game/', CreateOrGetGame.as_view(), name='post-create'),
path('player/', CreateOrUpdatePlayer.as_view(), name='post-create-1'),
]
|
import re
import sqlalchemy as sa
from sqlalchemy.ext.declarative import (
declarative_base,
declared_attr,
)
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
relationship,
)
from zope.sqlalchemy import ZopeTransactionExtension
from horus.models import (
GroupMixin,
UserMixin,
... |
"""
Посчитать четные и нечетные цифры введенного натурального числа.
Например, если введено число 34560, то у него 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5)
https://drive.google.com/file/d/1-c9vOMQsLOY7X0w8UF7x7N5d7shKWT_h/view?usp=sharing
"""
def recursion(n):
if n < 10:
if n % 2 == 0:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 23 17:19:26 2018
@author: kazuki.onodera
previous_application
"""
import numpy as np
import pandas as pd
import gc
from multiprocessing import Pool
from glob import glob
import utils
utils.start(__file__)
#========================================... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 8 23:42:51 2013
@author: olgis
Problem:
The series, 1**1 + 2**2 + 3**3 + ... + 10**10 = 10405071317.
Find the last ten digits of the series, 1**1 + 2**2 + 3**3 + ... + 1000**1000.
"""
import time
res = 0
for i in xrange(1, 1001):
res += pow(i,i)
sta... |
search_list = ["a", "b", "c", "d", "e", "f"]
chat_n = "a"
find_num = lambda s_list, n: find_num_fun(s_list, n)
def find_num_fun(s_list, n):
for item in s_list:
if n == item:
print("ok")
break
else:
print("not ok")
return "fuck"
print(find_num(search_list, chat_n))
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-12-01 23:58
#
# Sites migrations because I can't figure out how to set Kloud51 to stop redirecting me to davehub.net
#
#############################################
from __future__ import unicode_literals
from django.db import migrations
import socket
from ... |
import sys
input = lambda: sys.stdin.readline().rstrip()
n = int(input())
arr = list(map(int,input().split()))
arr.sort()
total = sum(arr)
ret = total-n
c = 2
while c**(n-1)<=2*total:
tmp = [-1*(c**i) for i in range(n)]
cand = 0
for i in range(n):
cand += abs(tmp[i]+arr[i])
ret = min(ret,cand... |
"""
本节用一个曲线拟合的例子体现普通训练的 overfitting以及 dropout 的优越性
"""
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
tf.set_random_seed(1)
np.random.seed(1)
# 超参数
N_SAMPLES = 20
N_HIDDEN = 300 # 大网络,过拟合
LR = 0.01
# training data
x = np.linspace(-1 , 1 , N_SAMPLES)[ : ,np.newaxis... |
#671. Second Minimum Node In a Binary Tree
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findSecondMinimumValue(self, root: TreeNode) -> int:
... |
import scrapy
class JobsSpider(scrapy.Spider):
name = 'jobs'
region_url_to_name = {}
start_urls = ['https://geo.craigslist.org/iso/us']
custom_settings = {
'DOWNLOAD_TIMEOUT': 10,
}
def parse(self, response):
region_links = response.css('.geo-site-list a')
for link in... |
for a in range(1,101):
if (a%7)!=0 and (a-7)%10!=0 and (a<70 or a>79):
print(a)
else:
continue
|
# Copyright 2013
# Pramod Dematagoda <pmd.lotr.gandalf@gmail.com>
#
# This software may be freely redistributed under the terms of the GNU
# general public license.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 67... |
#! /usr/bin/env python
#
#This file is used to get the flow and system parameters for the simulation.
import tkMessageBox as tkmb
from Tkinter import Frame, Label, Entry, OptionMenu, Button, Text, \
DoubleVar, StringVar, IntVar
from capsim_object_types import CapSim... |
#!/usr/bin/env python3
from tkinter import Tk, Button, messagebox
def say_hi():
print("They said hello!")
messagebox.showinfo("title", "message")
return 0
root = Tk()
hi = Button(text="hi", command=say_hi) # say_hi no perenthesis
hi.pack(side="top")
quit_win = Button(text="quit", fg="red", command=r... |
from django.db import models
from django.db.models import fields
from django.contrib.auth.models import User
from rest_framework import serializers
from rest_framework.serializers import CurrentUserDefault
from rest_framework.authtoken.models import Token
from .models import Task
class TaskSerializer(serializers.Mod... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 3 15:50:49 2019
@author: simsim
"""
from system import *
# choose the path with a failure at the beginning
def create(model):
plant = process("plant",["s1","s2","s3"],[],[],"s1")
environment = process("environment",["e1","e2","e3... |
import tkinter
import tkinter.colorchooser
import tkinter.filedialog
class UserInput:
def __init__(self,master,engine, username, updateWindow,windowType = None):
self.updateWindow = updateWindow
self.engine = engine
self.userInput = tkinter.Toplevel(master)
self.userInput.geometry("... |
"""
"""
from maya import cmds
from mamprefs import config
__all__ = ['script_output']
def script_output(direction):
"""
Script output dock for layouts.
"""
dock_control = config['WINDOW_SCRIPT_OUTPUT_DOCK']
dock_window = config['WINDOW_SCRIPT_OUTPUT']
if cmds.dockControl(doc... |
import json
def error(message, code=500):
print("Error: %s" % message)
return response(message, code)
def response(message, code=200, data=None):
resp = {"statusCode": code, "body": {"message": message}}
if data:
resp["body"]["data"] = data
resp["body"] = json.dumps(resp["body"])
ret... |
from django.contrib import admin
from leaflet.admin import LeafletGeoAdmin
from models import Message, Msgtype
# Register your models here.
class MessageAdmin(LeafletGeoAdmin):
list_display = ('name', 'email', 'show_location', 'created',)
map_height = '300px'
zoom = 13
admin.site.register(Message, Messa... |
from Rule import Rule
from Grammar import Grammar
def create_Grammar(file_name: str, type: str):
with open(file_name, 'r') as f:
lines = f.readlines()
f.close()
for i in range(4):
lines[i] = lines[i][:lines[i].find('#')].strip()
Vt = lines[0].split()
Vn = lines[1].split()
S = li... |
import unittest
from conans.test.utils.tools import TestClient
from conans.util.files import load
from conans.paths import CONANINFO
import os
from conans.test.utils.conanfile import TestConanFile
class PackageIDTest(unittest.TestCase):
def setUp(self):
self.client = TestClient()
def _export(self, n... |
# Copyright 2014 Google Inc. 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 required by applicable law or agre... |
# -*- coding: utf-8 -*-
# ---
# @Software: PyCharm
# @File: treading_run_sql.py
# @Author: Leslie Cheung
# @E-mail: leslieswr0820@gmail.com
# @Site:
# @Time: 2020/9/15 11:48
# ---
from threading import Thread
from NTRMYY.util.account import PgSQLContextManager
from NTRMYY.util.Dict_date import *
from NTRMYY.util.LogUi... |
# do_tvice takes a function object as an argument
# and calls it twice
def do_twice(f, k): # f=print_spam, k=2
f(k) # print_spam()
f(k)
def print_spam(v):
print('spam')
do_twice(print_spam, 1)
# Runs a function twice
# func: functional object
# arg: argument passed to the function
def do_twice(fun... |
import pytest
import pandas as pd
from sqlalchemy import create_engine
from pandas import DataFrame
# read in csv file from pandas library
input = pd.read_csv("../data/movie_metadata.csv")
# initiate sqlit in-memory database
engine = create_engine('sqlite://', echo=False)
# load file to local database
db = input.to_sq... |
# by Liana Hill
# last updated October 21, 2019
# this program plays a number guessing game with the user
import random
def main():
# this while True loop allows the user to play the game multiple times
while True:
# this while True loop asks the user if they want to play a number guessing game
... |
from setuptools import setup, find_packages
with open('trix/version.py') as f:
code = compile(f.read(), "trix/version.py", 'exec')
exec(code)
setup(
name='trix',
description='Next generation Trix. Detailed task control and statistics app for better'
' learning outcome.',
version=__version__, ... |
# food program
import random
from docx import Document
from datetime import date
import ast
import re
"""
This is a food menu program designed to create cooking menus, you can store recipes, add ingredients and more!
"""
class MenuMaker:
def import_dinner_dict(self):
'''
Input : NA
O... |
#am10182
#database project : please read documentaion.txt for more info
#IMPORTS
import operator
import sys
import re
import numpy as np
import time
from BTrees.OOBTree import *
# GLOBAL DB VARIABLES
tables = {} #entire database
hashtIndexes = {} #global hashtable indexes
btreeIndexes = {} #global btree indexes
# ... |
from formula_gen import FormulaGen
from formula import Formula
class DPLL():
def __init__(self, target_file):
self.target_file = target_file
def dpll(self, mode):
temp = FormulaGen(self.target_file)
temp.gen_formula()
temp.make_variables()
temp.make_clauses()
t... |
import tkinter as tk
from api import AppCache
# 用户信息
class UserDialog(tk.Toplevel):
def __init__(self, root, line=None):
super().__init__()
self.title('我的信息')
self.attributes("-topmost", True)
self.resizable(False, False)
self.desc = {
"uuid": "uuid",
"u... |
import asyncio
import pytest
import aiotools
@pytest.mark.asyncio
async def test_timer():
"""
Test the timer functionality.
"""
vclock = aiotools.VirtualClock()
with vclock.patch_loop():
count = 0
async def counter(interval):
assert interval == 0.1
nonloc... |
from .my_plots import *
from .latex2png import latex2png
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.offsetbox import TextArea, DrawingArea, OffsetImage, AnnotationBbox
import pyvista as pv
from io import BytesIO
from PIL import Image
class EnergyLevels:
"""
Generates energy level diagra... |
print('Chamamos as funções pelo nome seguido de parenteses com ou sem argumentos.')
print('a função type(42) retornará o tipo do parâmetro passado.')
print(type(42))
print()
print('Outro exemplo é a função int() que retornará o valor inteito relativo a um parâmetro.')
print('int ("32") retornará:')
print(int("32"))
pr... |
from turtle import *
#funkcja testuj() do testowania rozwiązania
def testuj(n):
a=499
b=796
reset()
tracer(0)
if n==1:
kwiat()
if n==2:
tetki(2)
if n==3:
motyw(3)
pu(); home(); pd()
pu();fd(b/2);pd()
lt(90)
color("red")
for i in range(2):
... |
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
class Sensor:
def __init__(self, echo_l, echo_m, echo_r, trig_l, trig_m, trig_r):
self.echo_l = echo_l
self.echo_m = echo_m
self.echo_r = echo_r
self.trig_l = trig_l
self.trig_m = trig_m
... |
def condicion (num):
mil=num//1000
num=num%1000
centena=num//100
num=num%100
decena=num//10
num=num%10
unidad=num
if unidad+centena== mil+decena:
return True
else:
return False
def main():
for v in range(1000,10000):
if condicion(v):
print... |
import numpy as np
from scipy.sparse import csr_matrix
from sklearn.linear_model import LogisticRegression
from GNNs import GNN
def load_data(data_file):
graphs = pickle.load(open(data_file, 'rb'))
node_types = set()
label_types = set()
for graph in graphs:
#print(graph)
# raise TypeErr... |
import numpy as np
import pandas as pd
from ols import OLS
# from ..utils.log import logger
def load_data():
train = pd.read_csv("data/reg_train.csv")
test = pd.read_csv("data/reg_test.csv")
X_train, X_test = train.drop("OUTCOME", axis=1), test.drop("OUTCOME", axis=1)
y_train, y_test = train["OUTCOME"]... |
from django.shortcuts import render
from contatos.models import ContatoModel
from contatos.forms import AgendaForm
def contato(request):
if request.method == 'POST':
form = AgendaForm(request.POST)
if not form.is_valid():
contexto = {
'contatos': ContatoModel.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
newServer.py
The server is started when newServer.py is run from the command line:
> python newServer.py
See the usage string for more details.
> python newServer.py --help
@author: Yuhan Liu 802997 University of Melbourne
@version: 1.41
@Date: March - May, ... |
#!/usr/bin/python
"""
This code parses the MUD JSON file and extracts the ACL.
"""
import json
import socket
def ACL():
"Parse the JSON MUD file to extract Match rules"
with open('/usr/local/etc/controller/lighting-example.json') as data_file:
d = json.load(data_file)
#print(d)
acl = d[... |
from glob import glob
import os
import shutil as sh
import numpy as np
from tqdm import tqdm
from bs4 import BeautifulSoup as bs
import argparse
DESCRIPTION = ("Convert the HTML generated by the Data 8 textbook repository "
"into a form that can be hosted with the Data 8 course website "
... |
import app
import ui
import os
#Colors
COLOR_NORMAL = 0xffa08784
COLOR_HOVER = 0xfff8d090
COLOR_LOGIN_TEXT = 0xffcbab9d
global REGBUTTON
global FORGOTPASS
#Login Redirect Links
REGBUTTON = "https://just4metin.ro/"
FORGOTPASS = "https://twix-work.com/"
#LOGIN Interface
ID_LOGIN = "Numele Contului / ID"
PW_LOGIN = "... |
import logging
import operator as op
import typing as t
from functools import reduce
from itertools import product, filterfalse, starmap, chain, combinations
from warnings import warn
import numpy as np
import pandas as pd
from protmc.common.base import AminoAcidDict
from protmc.common.utils import scale
from .base i... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findFrequentTreeSum(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
# SMTP发送邮件
# SMTP是发送邮件的协议,Python内置对SMTP的支持,可以发送纯文本邮件、HTML邮件以及带附件的邮件。
# Python对SMTP支持有smtplib和email两个模块,email负责构造邮件,smtplib负责发送邮件。
# # 首先,我们来构造一个最简单的纯文本邮件:
# from email.mime.text import MIMEText
# msg = MIMEText('Hello, send by Python...', 'plain', 'utf-8')
# # 注意到构造MIMEText对象时,第一个参数就是邮件正文,第二个参数是MIME的subtype,
# # 传入'p... |
import entityx
import math
from mouse import MouseFollower
from _entityx_components import Destroyed, Renderable, Body, Physics, Stats, b2BodyType, CollisionCategory, Sound
from gamemath import vector2
from follower import Orbital
from spawner import MagicSpawner
from eventur import EventController, Event, EVENT_TEXTS
... |
from app import app, socketio
if __name__ == '__main__':
socketio.run(app,
host="0.0.0.0",
debug=app.config["ENV"] == "development",
use_reloader=False,
log_output=True)
|
def missing_char(word):
return [f"{word[:i]}{word[i+1::]}" for i in range(len(word))]
def main():
word = "ornery"
print(f"\nWord: {word}")
print("\nWith chars missing: ")
[print(i) for i in missing_char(word)]
main() |
import cProfile
import time
import gc
import globals
print globals()
def a():
i = i + 5
def tester():
counter = 0
for i in range(1000000000):
counter = i + 1
a()
#These profile function use exec
#This is the recommended function
#cProfile.run("tester")
def timeme(method):
def wrapper(*args, **kw):
... |
try:
raise IndexError('spam')
except IndexError:
print('except IndexError')
print('raise with nothing')
raise
|
"""
Just a regular `setup.py` file.
Author: Nikolay Lysenko
"""
import os
from setuptools import setup, find_packages
current_dir = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(current_dir, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='gpn',
versi... |
"""Enables the command line execution of multiple modules within src/
This module combines the argparsing of each module within src/ and enables the execution of the corresponding scripts
so that all module imports can be absolute with respect to the main project directory.
Current commands enabled:
To create a data... |
import os
import random
charList = [
'a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z'
]
FlagText = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-widt... |
# Amount of food and number of people
tons_of_food = float(input("How many tons of food are available?"))
num_people = int(float(input("How many people are there?")))
# Determine how much food each person gets
tons_of_food_per_person = tons_of_food / num_people
print(tons_of_food_per_person)
# Ask the user how much f... |
"""
Returns number cubed
:param num: int
:return: int result of num to the power of 3
"""
def cubed(num):
return num ** 3
|
import random
options2 = ['r', 'p', 's']
max_games = 3
games_played = 0
player_score = 0
my_choice = ""
def pc():
return random.choice(options2)
def myoption():
rps = str(input("rock, paper or scissors?")).lower()
if rps in options2:
return rps
else:
print("invalid, try again")
myoption()
# Def... |
import pytest
from includer import IncluderMixin, _IncluderWrapper
@pytest.fixture(scope='function')
def obj():
class Obj(IncluderMixin, list):
pass
return Obj()
def test__includeme(obj):
obj.include('tests.for_include')
assert len(obj) == 1
assert obj[0][0] == 'includeme'
assert i... |
from django.shortcuts import render
from rest_framework_simplejwt.views import TokenObtainPairView
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import CustomUserSerializer
from rest_framework_simplejwt.tokens import RefreshToke... |
# Name: Ryan Gelston (rgelston)
# Filename: WriteToFile.py
# Assignment: Term Project
# Description: Outputs various data structures to a file
import numpy as np
def token_count(tokenCounter, outFile):
""" Writes the token counts to a csv file """
if type(tokenCounter) != list:
tokenCounter = [(k, v) for... |
# ---- 1. 엑셀 파일 만들고 저장하기 ----
#
# import openpyxl
#
# wb = openpyxl.Workbook()
# wb.save('text.xlsx')
# ---- 2. 엑셀 시트 & 셀에 접근하고 수정하기 ----
# import openpyxl
#
# wb = openpyxl.Workbook()
# sheet = wb.active
#
# sheet['D5'] = 'hello world'
# sheet.cell(row=2,column=2).value= '3, 3'
# sheet.append([1,2,3,4,5])
#
#
# wb.... |
numbers = input().split()
y = int(numbers[0]) * int(numbers[1]) * int(numbers[1]) + \
int(numbers[2]) * int(numbers[1]) + int(numbers[3])
print(y)
|
# -*- coding: utf-8 -*-
"""
Created on Tue May 12 14:34:37 2020
@author: ajaybkumar
"""
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 15 15:37:54 2020
@author: ajaybkumar
"""
import sys
from tika import parser
import re
import requests
from bs4 import BeautifulSoup
# from urllib.request import... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
FlyScan for Sector 2-BM
'''
from __future__ import print_function
import sys
import json
import time
from epics import PV
import h5py
import shutil
import os
import imp
import traceback
from datetime import datetime
import numpy as np
import pathlib
import libs.a... |
#!/usr/bin/python3
if __name__ == "__main__":
import hidden_4
print(''.join([i + '\n' for i in dir(hidden_4)
if "__" not in i[:2]]), end="")
# for item in dir(hidden_4):
# if "__" not in item[0:2]:
# print(item)
|
import concurrent
import socket
import threading
import time
from abc import ABC
from concurrent.futures import ThreadPoolExecutor
from typing import Optional, Dict, Tuple
import pygame
from requests import get
from database.server_communicator import ServerCommunicator
from menus.button import Button
from menus.text... |
import os, sys
import subprocess
def bash_command(cmd):
subprocess.Popen(['/bin/bash', '-c', cmd])
cmd = 'echo hi'
for i in range(3,11):
cmd += '; mv output_8_10_%d'%i+'/* outputfiles/output_8_10_%d'%i
for i in range(0,11):
cmd += '; mv output_8_11_%d'%i+'/* outputfiles/output_8_11_%d'%i
print cmd
... |
def find(idx):
global ans
selected[idx] = 1
Q = []
for i in range(1, n+1):
if i == idx: continue
if applications[idx][i] == 1 and selected[i] == 0:
selected[i] = 1
Q.append(i)
while Q:
nidx = Q.pop(0)
for j in range(1, n+1):
if j ==... |
"""
Miscellaneous utilities
"""
import sys
from ..exceptions import GMTOSError, GMTCLibError
def clib_extension(os_name=None):
"""
Return the extension for the shared library for the current OS.
.. warning::
Currently only works for OSX and Linux.
Returns
-------
os_name : str or N... |
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 14 19:13:12 2019
"""
num1 = 4
if(num1>=0 and num1<=5):
print("Buen ingreso")
else:
print("Mal ingreso")
if(num1<0 or num1>5):
print("Mal ingreso")
else:
print("Buen ingreso") |
'''
Python 9일차 실습#1
1. 50개 이내의 단어, 품사, 뜻을 저장한 단어장을 구성한 후
단어장을 출력하는 프로그램을 class를 이용하여 작성한다.
( 단어가 '0'이면 단어 입력 종료 )
( 단어는 최대 20자, 품사는 최대 10자, 뜻은 최대 50자 )
'''
class Wordbook1():
def __init__( self, word_name = None, word_class = None, word_meaning = None ):
self.word_name = wo... |
from ingestion.cleansing import Cleansing
from ingestion.validation import Validation
class EnforcementActionReport:
def __init__(self):
pass
# Get log files that should be displayed in this EAR
def get_log_files(self, source):
pass
# Get cleansing status to display in EAR
def g... |
# Date and text manipulation
import time
from coltrane import utils
from django.utils.encoding import smart_unicode
# Local application
from coltrane.models import Link
import logging
logger = logging.getLogger(__name__)
class DiggClient(object):
"""
A minimal Digg client.
"""
def __init__(self, us... |
#!/usr/bin/env python
# MATH 481 HW4 problem 2
import numpy as np
import matplotlib
import matplotlib.pylab as plt
import sys
def compute(N):
out = np.zeros(N+1)
t = np.zeros(N + 1)
# define derivative functions for expansion
def d1(x):
return -(np.e ** x) + 2*x + 2
def d2(x):
re... |
from bs4 import BeautifulSoup
from contracts import contract
from contracts.utils import check_isinstance, raise_desc, indent
from mcdp.exceptions import DPInternalError
from mcdp_report.html import ATTR_WHERE_CHAR, ATTR_WHERE_CHAR_END
class NoLocationFound(DPInternalError):
pass
@contract(html=bytes, returns=by... |
from string import Template
from graphene.test import Client
from django.test import TestCase
from ipam.models import VLAN
from netbox_graphql.schema import schema
from netbox_graphql.tests.utils import obj_to_global_id
from netbox_graphql.tests.factories.ipam_factories import VLANFactory, RoleFactory
from netbox_g... |
from analisador_lexico import Analisador_Lexico
from analisador_sintatico import Parser
text_input = """
program teste1
declare
integer a := 2;
begin
write(3 / 2);
write(3 * 3);
write(9 - 5);
%write(a);
if(9 = 1) then
write(3);
else
if(9 <> 3) then
write(10);
... |
# -*- coding: utf-8 -*-
# author: ysoftman
# python version : 3.x
# desc : pandas test
import numpy as np
import pandas as pd
print("load olympics.csv ... ")
print()
# csv 파일 읽기
# 첫 2줄을 건너뛰고 로딩(skiprows 0번째 라인 인덱스부터 시작)
# csv 파일의 나라명(첫번째)을 인덱스로 한다.
df = pd.read_csv('olympics.csv', skiprows=1, index_col=0)
print("df.... |
from flask import Flask, render_template, request, redirect
import os
from selenium import webdriver
import time
from flask import Blueprint
from bs4 import BeautifulSoup as soup
import logging
from logging.handlers import RotatingFileHandler
from flask import current_app
flask_app = Blueprint('flask_app', ... |
import preprocessing
import classification
# Perform the standard pre-processing algorithm
result = preprocessing.execute('abcd',
features_to_remove=[0, 1, 2],
features_to_extract=[4, 5])
classifier = classification.build(dataset_id='abcd',
... |
import lxml.html as html
import scrapy
CARDS_ITEMS = '//a[@class="card-text text-grid-item"]'
COLLECTIONS_URLS = '//tbody/tr/td[1]/a/@href'
# .replace('\n', '').strip()
COLLECTION_NAME = '//h1[@class="set-header-title-h1"]/text()'
# CARDS = '//a[@class="card-grid-item-card"]/@href'
# .replace('\n', '').strip() empty... |
Min = 6
def main():
password = get_password(Min)
print('*' * len(password))
def get_password(Min):
password = input("Enter password with {} or more charaters".format(Min))
while len(password) < Min:
print("Enter again")
password = input("Enter password with {} or more charaters".form... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# If extensions (or module... |
#!/usr/bin/python
# -*- coding: utf8 -*-
import datetime
import time
import tushare as ts
import pandas as pd
'''
https://www.jb51.net/article/213955.htm
日K 转换为 周K
'''
def test1():
df = ts.pro_bar(ts_code='300068.SZ', start_date='20190628', end_date='20210823', ma=[50, 300])
# 进行转换,周线的每个变量都等于那一周最后一个交易日的变... |
#coding: utf-8
from casino.models import Casino
from common.models import Language
from django.db import models
from django.utils.translation import ugettext as _
# from utilites.funcs import easy_upload_path
class News(models.Model):
"""
News model. Have some categories
"""
CATEGORY = ((1, _(u"Общее"... |
if False:
from typing import Dict, List, Tuple, Union, Optional
def MFnParticleSystem_lifespan(*args, **kwargs): pass
def uIntPtr_assign(*args, **kwargs): pass
def MFnAirField_inheritVelocity(*args, **kwargs): pass
def MFnFluid_toGridIndex(*args, **kwargs): pass
def MnCloth_setInputMeshAttractDamping(*args,... |
# Copyright 2016 The TensorFlow Authors. 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 required by applica... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 2 07:20:02 2020
@author: Aniket Maity
"""
N = 9999
arr = []
T = input()
N = int(T)
while(N !=0):
newStr = ''
newStr = '%02d' %(int(T[0])*int(T[1])) + '%02d' %(int(T[1])*int(T[2]))
sumLastPart ='%02d' %((int(T[0])*int(T[1])) + (int(T[1])*int(T[2])))... |
'''
The MIT License (MIT)
Copyright (c) 2017 Thunderclouding.com - exhesham
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, co... |
import sys
import math
import numpy
from PyQt5 import QtWidgets, QtGui
from PyQt5.QtWidgets import QMessageBox
from behinesazan.gas.station.software.view.GasInformationInputForm.base import BaseGasInformationInputForm
from behinesazan.gas.station.software.model.gas.Gas import Gas
# from behinesazan.gas.station.sof... |
import random
from allauth.account.models import EmailAddress
from allauth.account.utils import sync_user_email_addresses
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.core.management.base import BaseCommand, CommandError
from faker import Factory
from xSACd... |
import pandas as pd
import os.path
xlfile = "sample.xlsx"
if os.path.exists(xlfile):
print("dd") |
from flask import request, render_template, jsonify, url_for, redirect, g
from flask_socketio import SocketIO, emit
from .models import User
from index import app, db
import redis
from sqlalchemy.exc import IntegrityError
import time
from .utils.auth import generate_token, requires_auth, verify_token
r = redis.StrictR... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.