text
stringlengths
8
6.05M
import asyncio from asyncio.streams import StreamReader, StreamWriter from concurrent.futures import TimeoutError from os import urandom from hashlib import sha1 from base64 import b64decode from io import BytesIO from struct import pack, unpack from Auth.Constants.AuthStep import AuthStep from Auth.Handlers.LoginChal...
import keras from keras.utils import plot_model from config import MODEL_DIR_PATH restored_keras_model = keras.models.load_model(MODEL_DIR_PATH + 'Emotion_Voice_Detection_Model.h5') plot_model(restored_keras_model, to_file='media/model.png')
#!/usr/bin/env python # coding: utf-8 # In[1]: import sqlite3 import pandas as pd import csv # In[2]: pd.set_option('max_columns', 180) pd.set_option('max_rows', 200000) pd.set_option('max_colwidth', 5000) # In[3]: game = pd.read_csv('game_log.csv', low_memory = False) print(game.shape) print("\n") game.head...
import statistics example_list = [1,2,45,54,23,23,122,1,34,34,34,32] mean = statistics.mean(example_list) print('mean', mean) median = statistics.median(example_list) print('median', median) mode = statistics.mode(example_list) print('mode', mode) sd = statistics.stdev(example_list) print('sd', sd) variance = statist...
from machine import Pin, ADC from time import sleep led = Pin(5,Pin.OUT) ldr = ADC(Pin(34)) while(1) : val = ldr.read() print(val) sleep(0.1) if val <= 3000: led.value(0) else: led.value(1)
import numpy as np from scipy.integrate import ode from math import atan, pi, sqrt, cos, sin, atan2 def x2(x): return -(x-1)**2 + 1 def test(): rho = 1.293 dxdt = 2.0 v = pi * 1.0 c = 0.1 dz = 0.01 Cl = 1.1 Cd = 0.1 beta = 80 *pi/180 z = 1.0 omega = pi # dFvNdFh(rho, z...
''' Original source: https://github.com/Nadock/json_stringify ''' import json def invert_json_string(text: str, indent: str = "\t") -> str: """Either string encode or decode a `str` containing JSON""" if is_json_string(text): # Decode JSON string to raw JSON return json.loads(text) # Encode raw JSON to a JSON...
""" Ejercicio 1 Realice un programa en Python para determinar cuanto se debe pagar por equis cantidad de ĺapices considerando que si son 1000 o mas el costo es de 85 pesos; de lo contrario, el precio es de 90 pesos. """ lapices = int(input("Cantidad de lapices a comprar: ")) if lapices < 1000: costo_total = lap...
from flask_hello_world_app import db, pinCodes districts = ["Adilabad","Hyderabad", "Karim Nagar", "Khammam", "Mahabub Nagar", "Medak", "Nalgonda", "Nizamabad", "K.V.Rangareddy", "Warangal"] for di in districts: try: admin = pinCodes.query.filter_by(district=di).all() for a in admin: ...
from api.views import ProfileAuthedAPIView from db_models.models.personal_record import PersonalRecord from rest_framework import serializers from rest_framework import status from rest_framework.response import Response class PersonalRecordSerializer(serializers.ModelSerializer): class Meta: model = Per...
#!/usr/bin/env python import rospy import math import random import socket import local_pathfinding.msg as msg from utilities import headingToBearingDegrees, measuredWindToGlobalWind try: import aislib as ais import pynmea2 as nmea except ImportError as err: print("ImportError: " + str(err)) print(""...
# -*- coding: utf-8 -*- """ Class used to wrap a neural network class used for a classification task. Implements utility functions to train, test, predict, cross_validate, etc... the neural network. """ import torch from torch import nn from torch import optim from sklearn.model_selection import KFold import os f...
import turtle from random import * #Setting up turtle x = turtle.Turtle() x.hideturtle() turtle.hideturtle() turtle.penup() turtle.goto(-200,-100) turtle.pendown() turtle.speed(9000) #Making the square def square(size): turtle.forward(size) turtle.left(90) turtle.forward(size) turtle....
#import sys #input = sys.stdin.readline def eratosthenes(N): from collections import deque work = [True] * (N+1) work[0] = False work[1] = False # ret = [] for i in range(N+1): if work[i]: # ret.append(i) for j in range(2* i, N+1, i): work[j] = False...
import requests from bs4 import BeautifulSoup as bs import telegram from apscheduler.schedulers.blocking import BlockingScheduler token = "나의 텔레그램 토큰" # 내 텔레그램 토큰 bot = telegram.Bot(token=token) # 변수명 bot 안에다가 내 토근 입력 sched = BlockingScheduler() old_links = [] # 이미 보낸 링크를 집어 넣을 변수 def extrct_links(old_links=[]):...
#!/usr/bin/python #\file box_line_intersection.py #\brief Get an intersection part of a 3D oriented box and a line segment. #\author Akihiko Yamaguchi, info@akihikoy.net #\version 0.1 #\date Mar.03, 2021 import numpy as np from geometry import * from box_ray_intersection import BoxRayIntersection def BoxLineI...
import numpy as np import random import heapq import sys import csv class node: def __init__(self, state, action, pathCost, heuristicCost): self.state=state #state/data, position of all tiles self.action=action #action required to get to this state from parent self.pathCo...
#!/usr/bin/python import sys import os import re from collections import OrderedDict qs = 'av=;a_cat=;a_nm=;a_pub=;aav=;bh=;cd=;co_f=;ct=;dl=;dm=;ets=;ev=;fv=;gc=;hp=;le=;os=;slv=;sr=;sys=;tz=;ua=;ul=;vtid=;vtvs=;ac=;ad=;branch=;cg_n=;cg_s=;mc_id=;mobile=;nv=;pi=;pn=;pn_id=;pn_sku=;rv=;seg_X=;si_cs=;si_n=;si_p=;si_x=...
import firebase_admin from firebase_admin import credentials from firebase_admin import firestore cred = credentials.Certificate("firebase_creds.json") firebase_admin.initialize_app(cred) db = firestore.client() #! CREATE AND UPDATE city1 = { u'city': 'Chicago', u'state': 'Illinois' } city2 = { u'city...
import pickle from gensim.models import Word2Vec import numpy as np from sklearn.cross_validation import train_test_split from collections import Counter def get_data(fname = "features.pickle"): f = open(fname,'rb') data = pickle.load(f) f.close() return data def get_idx_from_tokens(tokens, word_idx...
from bs4 import BeautifulSoup import urllib.request from store import write url = 'http://dwin-335-310-50-d1.language.berkeley.edu/radler/' with urllib.request.urlopen(url) as response: html = response.read() content = BeautifulSoup(html) tags = content.find_all('a')[2:] for _t in tags: index = _t['href']....
#coding:utf-8 #settings.py MIDDLEWARE = [ 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', ] #默认的缓存 { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'u...
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the G...
#!/usr/bin/env python __license__ = 'GPL v3' __author__ = '2010, Gustavo Azambuja <hola at gazambuja.com>' ''' observa.com.uy ''' from calibre.web.feeds.news import BasicNewsRecipe class Noticias(BasicNewsRecipe): title = 'Observa Digital' __author__ = '2010, Gustavo Azambuja <hola at gaza...
import cv2 import numpy as np ## load images img = cv2.imread('smartphone.jpeg' , cv2.IMREAD_GRAYSCALE) cv2.imshow('iPhone' , img) cv2.waitKey(0) cv2.destroyAllWindows() # work with videos cap = cv2.VideoCapture(0) # for video file cv2.VideoCapture('video.mp4') # to save your video # saver = cv2.VideoWriter_fourcc(...
from rovinj_numopt_tut.constraints import rotating_oh from cctbx import xray, uctbx pivot = xray.scatterer(site=(0,0,0), label="C") pivot_neighbour = xray.scatterer(site=(1,1,1), label="O") unit_cell = uctbx.unit_cell((1,2,3,90,90,90)) constraint = rotating_oh(pivot, pivot_neighbour, 0, unit_cell) print constraint.hyd...
# vim:fileencoding=utf-8:noet from weakref import ref from atexit import register as atexit from IPython.terminal.prompts import Prompts from pygments.token import Token # NOQA from powerline.ipython import IPythonPowerline from powerline.renderers.ipython.since_7 import PowerlinePromptStyle from powerline.bindings....
a=int(input()) b=int(input()) c=int(input()) m=max(a,max(b,c)) print(m)
from os import path from scipy.misc import imread import matplotlib.pyplot as plt from wordcloud import WordCloud,STOPWORDS,ImageColorGenerator import codecs import jieba from collections import Counter from .settings import BASE_DIR from tevaluation.models import Comment #文件目录 d = path.dirname('__file__') #print(BASE_...
import pysam import ntpath from helpers import parameters as params from helpers import handlers as handle from helpers import bamgineerHelpers as bamhelp import time from utils import * import logging, sys import random global bases bases = ('A','T','C','G') def initPool(queue, level, terminating_): #This causes...
# Name: Cory Nezin # Date: 01/17/2018 # Task: Perform a greedy gradient attack on a recurrent neural network import tensorflow as tf import numpy as np import review_proc as rp, preprocess, rnn, word2vec import matplotlib.pyplot as plt import plotutil as putil import argparse, os, sys, random, re parser = argparse....
import numpy as np from soupsieve.util import string import pygame import sys import math ROW_CNT = 8 COLUMN_CNT = 9 AQUA = (0, 128, 128) YELLOW = (255, 215, 0) RED = (128, 0, 0) BLACK = (0, 0, 0) def createBoard(): board = np.zeros((ROW_CNT, COLUMN_CNT), dtype=int) return board board = createBoard() print...
#!/usr/bin/env pypy3 # -*- coding: UTF-8 -*- n=int(input()) s=input() ans='' for a,i in enumerate(s): if (a+n)%2: ans+=i else: ans=i+ans print(ans)
import cv2 import numpy as np import imutils import time # Load Yolo net = cv2.dnn.readNet("yolov3_custom_last (2).weights", "yolov3.cfg") classes = ["plate"] layer_names = net.getLayerNames() output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()] colors = np.random.uniform(0, 255, size=(...
import tensorflow as tf import numpy as np import os from tqdm import tqdm import sys sys.path.append("../") from Config import config from Config import tool from Preprocessing import Preprocess from Model.Embeddings import Embeddings from tensorflow.python import debug as tf_debug class AB_CNN(): ...
import json import os import subprocess class EventFinder(object): def __init__(self, username, password): self.splunk_username = username self.splunk_password = password # Checks if a vulnerability event is present in the event set def containsVulnEvent(self, description, host, ...
# mkdir example # You can type multiple non-existent levels of a directory to create them all simultaneously # cd ~ # mkdir -p temp/hello/how/are/you # will work fine with -p (parents) & create all those folders
print("Miles Kilometers Kilometers Miles") for i in range(1,11): if 7<=i<=9: print("{0} {1:>10.3f} {2:>6.0f} {3:>14.3f}".format(i, i*1.609, i*5+15 , (5*i+15)*1.609)) elif i == 10: print("{0} {1:>9.3f} {2:>6.0f} {3:>15.3f}".format(i, i*1.609, i*5+15 , (5*i+15)*1.609)) else: ...
""" Convolutional neural net on MNIST, modeled on 'LeNet-5', http://yann.lecun.com/exdb/publis/pdf/lecun-98.pdf """ import autograd.numpy as np import autograd.numpy.random as npr import autograd.scipy.signal from autograd import grad from autograd.util import quick_grad_check from six.moves import range import gmm_ut...
import mc import jobmanager import time import xbmc class ContainerScrollJob(jobmanager.BoxeeJob): def __init__(self, interval, list): self.interval = interval self.list = list jobmanager.BoxeeJob.__init__(self, "Container Scroll Job", interval) def process(self): self.list.ScrollPageDown() class Local...
#========================================================================= # pisa_srav_test.py #========================================================================= import pytest import random import pisa_encoding from pymtl import Bits from PisaSim import PisaSim from pisa_inst_test_utils import * #--------...
import time import datetime class LOG: def __init__(self, file_name): self.file_name = file_name self.log = file(self.file_name, 'w') def record(self, msg): 'append log with LF' s = str(datetime.datetime.today()) + ' : ' + msg + '\n' self.log.write(s) ...
#!/usr/bin/env python # -*- coding: utf-8 -*- BACKUP_PERMISSIONS_FILE = "smorest_sfs/modules/auth/permissions.bak.py" NEW_PERMISSIONS_FILE = "smorest_sfs/modules/auth/permissions.new.py" PERMISSIONS_FILE = "smorest_sfs/modules/auth/permissions.py" CONFIG_PATH = "config/{config}.toml" NGINX_PATH = "deploy/nginx/flask...
import sys input = sys.stdin.readline Q = 10**9 + 7 def main(): N, K = map( int, input().split()) A = list( map( int, input().split())) ans = 0 for i in range(N): a = A[i] al = 0 after = 0 for i in range(i): if A[i] < a: al += 1 for i...
''' Created on Nov 23, 2015 @author: Jonathan ''' def bestInvitation(first, second): most = 0 for interest in (first + second): shares = first.count(interest) + second.count(interest) if shares > most: most = shares return most if __name__ == '__main__': pass
# coding=utf-8 numbers = [1,2,3,4,5,6,7,8,9,10] print 'Number at 0: ' + str(numbers[0]) print 'Number at 9: ' + str(numbers[9]) print 'Number at -1: ' + str(numbers[-1]) print 'Number at -2: ' + str(numbers[-2]) # 分片包含三个参数,第一个是起始下标,第二个是终止下标,第三个是步长 # 步长是正数时,起始下标对应的元素在整个序列中必须出现在终止下标对应的元素的左侧 # 输出的分片序列中包含起始下标对应的元素,但不包含终...
# -*- coding: utf-8 -*- # auther:gaoshuai # 2018/9/26 上午10:28
from lib.randomizer import * def __get_random_items_data(serial: bool = False, numbers_qty: int = None): random_suffix = get_random_low_string(5, with_digits=True) if serial: quantity = numbers_qty or get_random_int(10, 20) else: quantity = get_random_int(10, 20) data = { 'quan...
n=int(input('Enter the no. of keys')) d={} c=1 for i in range(1,n+1): key=input('Enter the key') value=input('Enter the value') d[key]=value c+=1 x=input('Enter the element to be removed') y=input('Enter the element to be removed') d.pop(x) del d[y] print(d)
import sys import os from goatools.go_enrichment import GOEnrichmentStudy from goatools.obo_parser import GODag from goatools.associations import read_associations """Test that GOEnrichmentStudy fails elegantly given incorrect stimulus. python test_goea_errors.py """ __copyright__ = "Copyright (C) 2016, DV K...
#!/usr/bin/env python girls=['alice','bernice','clarice'] boys=['chris','anorld','bob'] lettergirls={} for girl in girls: lettergirls.setdefault(girl[0], []).append(girl) print [b+'+'+g for b in boys for g in lettergirls[b[0]]]
import finnhub import pandas as pd import os from dotenv import load_dotenv import json from polygon import RESTClient # Get API key from .env file load_dotenv() polygon_api_key = os.getenv("POLYGON_API_KEY") if type(polygon_api_key) == str: print('Polygon API OK') else: print('API NOT OK', type(polygon_api_k...
class Solution: def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ a_stack = [int(ele) for ele in a] b_stack = [int(ele) for ele in b] res = [] carry = 0 while a_stack or b_stack or carry != 0: a_ele = ...
from allauth.account.forms import LoginForm, SignupForm from django import forms from django.core import validators class CustomLoginForm(LoginForm): def __init__(self, *args, **kwargs): super(CustomLoginForm, self).__init__(*args, **kwargs) self.fields['login'].widget = forms.TextInput(attrs={ ...
from DataLoader import NormalTableDatabase from Model import TableInfusing import sys from torch.autograd import Variable import torch import torch.optim as optim from torch import nn import argparse import pandas from transformers import GPT2LMHeadModel, GPT2Tokenizer import math from utils import sample_sequence impo...
#!/usr/bin/env python import rospy import tf import copy from geometry_msgs.msg import Twist, PoseWithCovarianceStamped, Point from sensor_msgs.msg import LaserScan from nav_msgs.msg import OccupancyGrid, Odometry from visualization_msgs.msg import MarkerArray, Marker import numpy as np from Map import * from Robot im...
from flask import Flask, request from flask import jsonify from discord import Webhook, RequestsWebhookAdapter from waitress import serve import re import os app = Flask(__name__) @app.route('/bot', methods=['POST']) def bot_response(): data = request.get_json() if data['name'] != 'discord': if re.ma...
# -*- coding: utf-8 -*- ############################################################################## # # Author: OpenDrive Ltda # Copyright (c) 2013 Opendrive Ltda # # WARNING: This program as such is intended to be used by professional # programmers who take the whole responsibility of assessing all potential # cons...
''' Created on 2011-12-20 @author: 301645 ''' import datetime,time from common.pysvn import pysvn from common.pywincmd import pywincmds import os from common.pyemail import pyemail import pdb workspace = os.getenv("WORKSPACE",r"c:\hudson\workspace\update_style") phase = os.getenv("phase","commit") #压缩程序路径 compress_p...
# -*- coding: utf-8 -*- """ @author: Scott Orr This class is simple a subclass of :class:`str` with a :meth:`~pyCoalesce.utilities.URL_class.__new__` method that adds a check for a valid URL scheme. """ from urllib.parse import urlsplit class URL(str): """ Adds a check to the vanilla string constructor t...
# This Python file uses the following encoding: utf-8 from __future__ import unicode_literals, division from django.db import models from datetime import datetime from django.utils import timezone from django.core.exceptions import ValidationError # Create your models here. class Candidate(models.Model): fir...
class Node: def __init__(self, value=None): self.value = value self.left = None self.right = None def find_path(root:Node, expected_sum): if root is None: return stack = [] sum_ = 0 find_path_helper(root, stack, sum_, expected_sum) def find_path_helper(root:Node, ...
# Generated by Django 2.0.3 on 2018-12-01 16:53 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('deckShare', '0003_auto_20181201_1607'), ] operations = [ migrations.RemoveField( model_name='pr...
#! /usr/bin/python # coding: utf8 """ Talk to the CosmicPi Arduino DUE accross the serial USB link This program has the following functions ... 1) Build event messages and send them to a server or local port Events are any combination of Vibration, Weather and CosmicRays Hence the Arduino can behave as a weather s...
from time import sleep import picodisplay as display BACKGROUND_COLOUR = {"r": 0, "g": 0, "b": 0} space_invader_map = [ [0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1,...
from ED6ScenarioHelper import * def main(): # 迷雾峡谷 山间小屋 CreateScenaFile( FileName = 'C1410 ._SN', MapName = 'Bose', Location = 'C1410.x', MapIndex = 62, MapDefaultBGM = "ed60015", Flags = 0, ...
L=[1,2,3,4,5,6,7,8,9,10] count=0 counter=0 p1=int(input("Player 1, enter number from 1 to 10: ")) while p1 not in L: p1=int(input("make sure the number is in range from 1 to 10: ")) count=count+p1 print ("sum=",count) while True: if counter%2==0: p2=in...
# /usr/bin/env python # -*- coding:utf-8 -*- class Stack: def __init__(self): self.items = [] def size(self): return len(self.items) def push(self, value): self.items.append(value) def pop(self): return self.items.pop() def is_empty(self): return self.it...
import os import re import sys import time import string import shutil import threading import plugins from glob import glob from Queue import Queue class ProjectError(Exception) : pass class Project : STARTED = 0 PREPROCESSING = 1 READY = 2 RUNNING = 3 COMPL...
import json import fnmatch import os.path as op import os import sys import subprocess import shutil import six from jinja2 import Environment, FileSystemLoader try: import urllib.parse as urllib_parse except ImportError: from urllib import urlencode as urllib_parse GH = 'https://github.com' GH_RAW = 'https:...
celda = { "viva": "#", "vacia": "-" } def generar_tablero(): """Genera un tablero vacio""" n = input("introduce numero de filas: ") m = input("introduce numero de columnas: ") tablero = [] for i in range(n): fila = [] for j in range(m): fila.append(celda["vacia"]...
import urllib import urllib.request import os import re import sys import time #http连接有问题时候,自动重连 def conn_try_again(function): RETRIES = 0 #重试的次数 count = {"num": RETRIES} def wrapped(*args, **kwargs): try: return function(*args, **kwargs) except Exception as ...
import numpy as np import cv2 import utils import os import argparse from util_classes import Model, Template, Store from utils import * from PIL import Image from matplotlib.patches import Circle, Wedge, Polygon from matplotlib.collections import PatchCollection import warnings warnings.filterwarnings("ignore") # l...
# 281. Zigzag Iterator # # Given two 1d vectors, implement an iterator to return their elements alternately. # # For example, given two 1d vectors: # # v1 = [1, 2] # v2 = [3, 4, 5, 6] # By calling next repeatedly until hasNext returns false, # # the order of elements returned by next should be: [1, 3, 2, 4, 5, 6]....
answer = input("Скільки буде 2+2?:") answer = int(answer) if answer == 4: # Якщо тут TRUE, -- то виконається print("Bingo!", answer) # цей блок кода!!! else: print( f"{answer}, Ні, не вірно")
""" Stuff """ import os import fbx from brenpy.core import bpDebug from brenpy.core import bpObjects from brenpy.core import bpItems from brenpy.core import bpValueItems from brenfbx.core import bfIO from brenfbx.core import bfCore from brenfbx.items import bfItemValueReferences from brenfbx.utils import bfFbxUtils ...
# Generated by Django 2.0.7 on 2019-01-03 15:14 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('basedata', '0019_material_log_thisid'), ] operations = [ migrations.AddField( model_name='project', name='contract',...
from django.urls import path from .views import * urlpatterns = [ path('cadastro', cadastro, name='cadastro'), path('<int:pk>', view_usuario, name='usuario'), path('amigos', amigos, name='amigos'), path('pedidos-amizade', pedidos_amizade, name='pedidos_amizade'), path('relatorios', relatorios, name...
import unittest from conans.test.utils.tools import TestClient import os from conans.util.files import load class GeneratorsTest(unittest.TestCase): def test_base(self): base = ''' [generators] cmake gcc qbs qmake scons txt visual_studio visual_studio_legacy xcode ycm ''' files = {"conanfile....
# Stability calculation test # Bryan Kaiser # 3/14/2019 # Note: see LaTeX document "floquet_primer" for analytical solution derivation import h5py import numpy as np import math as ma import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import scipy from scipy import signal import functions as f...
# @Title: 分割回文串 (Palindrome Partitioning) # @Author: 2464512446@qq.com # @Date: 2019-12-03 11:48:28 # @Runtime: 92 ms # @Memory: 11.8 MB class Solution: def partition(self, s): res = [] self.helper(s, [],res) return res def helper(self,s, tmp,res): if not s: ...
import math from decimal import * getcontext().prec = 25 # Using Diophantine solver at https://www.alpertron.com.ar/JQUAD.HTM # with 2, 0, -1, 0, 0, 2 # If a(a-1)/(b(b-1)) = 1/2, then b^2-b-2a^2+2a = 0 and b=(1+sqrt(1+8a^2-8a))/2 # Then, the radicand is a perfect square, and a=(2+sqrt(2+2n^2))/4 for integer n # The r...
import numpy as np import struct def read_java_bin_file(Filepath): print(Filepath) # Filepath="D:/dan Java/3ds/316Z_flat.bin" file = open(Filepath, "rb") nx = struct.unpack(">i", file.read(4))[0] ny = struct.unpack(">i", file.read(4))[0] print(nx) print(ny) print(struct...
class Persion(object): def __init__(self): self.name = 'huangyisan' self.age = 28 def get_name(self): print(self.name) def __call__(self, *args, **kwargs): return self.get_name() persion = Persion()()
from dataclasses import dataclass import time import datetime @dataclass class Event: @property def occurred_on(self): return datetime.datetime.fromtimestamp(time.time()).strftime('%H:%M:%S %d-%m-%Y') @property def event_name(self): return type(self).__name__ @dataclass class Wareh...
# -*- coding:utf-8 -*- from bs4 import BeautifulSoup #官方文档:https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/ html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their name...
import sys import os import dj_database_url BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) SECRET_KEY = os.environ.get('SECRET_KEY', 'test') DEBUG = os.environ.get('DEBUG', None) == 'True' TESTING = len(sys.argv) > 1 and sys.argv[1] == '...
#!/usr/bin/env python3 # -*- coding:utf8 -*- import asyncio import orm from models import User, Blog, Comment @asyncio.coroutine def test_save(loop): yield from orm.create_pool(loop=loop, user='root', password='password', dbe='myblog') u = User(name='Test', password='123456', email='test@example.com', image...
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. This would determine the data dis...
import torch import torch.nn as nn import torch.nn.functional as F PRIMITIVES = [ 'none', 'skip', 'comb1', 'comb2', 'comb3' ] NODES_OPS = { 'none': lambda channel, num_nodes: Zero(), 'skip': lambda channel, num_nodes: Skip(), 'feat_aggr' : lambda channel, num_nodes: Feat_aggr(channel)...
#!/usr/bin/env python from __future__ import unicode_literals import sys reload(sys) sys.setdefaultencoding('utf-8') import os import datetime import uuid import tarfile import sqlite3 if len(sys.argv) == 1: print "Usage: sclone <path to backup>" exit(1) root = sys.argv[1] sclonedir = os.path.abspath(os.path.dirn...
"""CSC Electronic Office"""
from django.urls import path from .views import signupview, loginview, listview, detailview, CreateClass, logoutview, evaluationview from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('signup/', signupview, name='signup'), path('login/', loginview, name='login'), ...
# Tuples r immutable # we use parentheses #create tuple t = (1, 2,3) print(f'Type of t is {type(t)}') #check length print(f'Length of t is {len(t)}') #Accessing tuple with index print(f'Item at index 2 of t is {t[2]}') #using count method print(f"Number of 1's in t are {t.count(1)}") #using index method print(f'Ind...
from Tkinter import * from GerberReader import GerberData, GerberLayer from tkColorChooser import askcolor __author__ = 'Thompson' def createTable2(tframe, gerber_data, change_cmd): """ Creates a table for editing visual properties of GerberData layers :type tframe: Frame :type gerber_data: GerberDat...
# Create your models here. import uuid from django.contrib.auth.models import User from django.db import models class College(models.Model): name = models.CharField(max_length=16, unique=True) def __str__(self): return self.name class ElectionStatus(models.Model): batch = models.CharField(max_...
n = int(input()) score = [int(i) for i in input().split(' ')] m = int(input()) alia_score = [int(i) for i in input().split(' ')] ascore = sorted(set(score)) abscore = ascore[::-1] result = abscore print(abscore) print(alia_score) j = len(abscore)-1 for i in alia_score[:]: if i< abscore[-1]: # print(j+2) ...
import json from json import JSONDecodeError from pymongo import HASHED from scrapy import Request from ._base import BaseSpider class ZenodoSpider(BaseSpider): name = 'zenodo' allowed_domains = ['zenodo.org'] # DB specs collections_config = { 'Scraper_zenodo_org': [ [('doi', HA...
#do google auth login first in command line import json from google.cloud import language from google.cloud.language import enums from google.cloud.language import types def move_to_file(data): with open('google_results.json', 'w') as outfile: json.dump(data, outfile,indent=4) def analyze(data): ...
# Generated by Django 3.0.8 on 2020-07-23 08:01 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('profiles', '0019_remove_guideprofile_userprofiles'), ('trips', '0002_auto_20200716_2218'), ] operations = [...