text
stringlengths
38
1.54M
from keras.datasets import reuters from keras import models from keras import layers import numpy as np import matplotlib.pyplot as plt from keras.utils.np_utils import to_categorical def main(): (train_data, train_labels),(test_data, test_labels) = reuters.load_data(num_words=10000) x_train = vectorize...
import os import sys import pygame from app.scene.SceneHandler import SceneHandler from app.settings import * if __name__ == '__main__': #Code to check if the code is running from a PyInstaller --onefile .exe if getattr(sys, 'frozen', False): os.chdir(sys._MEIPASS) # Screen screenSize = (SC...
# -*- coding: utf-8 -*- """ Created on Thu Nov 15 10:36:36 2018 @author: MUJ """ import pandas as pd import numpy as np import matplotlib.pyplot as plt #Importing the dataset data=pd.read_csv("customers.csv") features=data.iloc[:,3:].values labels=data.iloc[:,2].values from sklearn.cross_validation import train_te...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Project: Fast Azimuthal integration # https://github.com/pyFAI/pyFAI # # Copyright (C) European Synchrotron Radiation Facility, Grenoble, France # # Principal author: Jérôme Kieffer (Jerome.Kieffer@ESRF.eu) # # This program is free software...
from actualizaciones.api import views from django.urls import path urlpatterns = [ path( "<int:seguimiento_pk>/", views.create_actualizacion, name="actualizacion-create", ), path( "<int:seguimiento_pk>/list/", views.list_actualizacion, name="actualizacion-lis...
# -*- coding: utf-8 -*- import pathlib from itertools import tee import pytest import requirementslib.models.project from .test_requirements import DEP_PIP_PAIRS def pairwise(seq): a, b = tee(seq) next(b, None) return zip(a, b) PIPFILE_ENTRIES = [entry for entry, pip_entry in DEP_PIP_PAIRS] PAIRED_PI...
#!/usr/bin/env python # coding: utf-8 # # ATSA Model # In[1]: import pandas as pd import numpy as np import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import TensorDataset, DataLoader from tensorflow.keras.preprocessing.text import one_hot fro...
from django.db import models from datetime import datetime from django.contrib.auth.models import User, auth # Create your models here. class categories(models.Model): category_name = models.CharField(max_length=255) def __str__(self): return self.category_name class sub_categorie(models.Model): ...
""" Write a program to ask the user to enter their name and two integers where the second integer is less than the first integer. Your program must display the following message: Please enter your first name: The user enters their first name <FirstName> at this point. Your program then displays the message: Hi <Firs...
from dojosandninjas_app import app from dojosandninjas_app.controllers import dojos_controller from dojosandninjas_app.controllers import ninjas_controller if __name__ == "__main__": app.run( debug = True ) # http://127.0.0.1:5000/
class Solution(object): def complexNumberMultiply(self, a, b): """ :type a: str :type b: str :rtype: str """ plus_index = a.find('+') a_real = int(a[:plus_index]) a_image = int(a[plus_index + 1:-1]) plus_index = b.find('+') b_real = int...
from collections import defaultdict def dist(a, b): return abs(a[0] - b[0]) + abs(a[1] - b[1]) def uniq_min_idx(data): uniq = True idx = 0 for i, val in enumerate(data): if val < data[idx]: uniq = True idx = i elif val == data[idx]: uniq = False ...
from torchvision import transforms from datasets.randaugment import * from itertools import permutations def get_data_transforms(purpose='baseline', baseline_flag=0, num_labeled=50): '''Data augmentation and normalization Args: purpose (str): the purpose of the model Returns: data...
# Generated by Django 3.1.2 on 2020-10-28 04:38 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('shop', '0019_auto_20201028_1005'), ] operations = [ migrations.AlterField( model_name='product2', name='pub_date', ...
#!/usr/bin/env python #coding=utf-8 import sys, codecs, json, os, ConfigParser, logging from sklearn.feature_extraction.text import TfidfVectorizer from SPARQLWrapper import SPARQLWrapper, JSON from nltk.corpus import stopwords from nltk.classify import NaiveBayesClassifier from nltk.classify.scikitlearn import Sklearn...
# # @lc app=leetcode id=365 lang=python3 # # [365] Water and Jug Problem # # @lc code=start class Solution: ''' Accepted 28/28 cases passed (28 ms) Your runtime beats 88 % of python3 submissions Your memory usage beats 68.84 % of python3 submissions (14.2 MB) Time complexity : O(log(jug1Capacity * jug2Cap...
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-04-24 08:46 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('survey', '0004_auto_20170424_1038'), ] operations = [ migrations.AlterField...
#!/usr/bin/env python #!/usr/bin/env python """ A chatbot that listens to how peoples' days are going and recommends a Spotify playlist based on it's interpretation of their mood. """ import re import random import string import nltk from nltk.corpus import stopwords from EmoClassifier import emo2vec, model, emotions,...
from pulp import * m = LpProblem(sense=LpMaximize) x = LpVariable("x",lowBound=0) y = LpVariable("y",lowBound=0) m += x+y m += x*x -y ==0 m += 0.5 * x -y +1 ==0 m += y == 1 m.solve() print(value(x),value(y),value(m.objective))
# ENGINE # ------------------------- import random from typing import Iterable, List from core.common import Queuer, Player, max_mmr, min_mmr, Lobby, MatchMaker TEAM_SIZE = 5 class CompositeMatchmaker(MatchMaker): def __init__(self, find_lobby): self._find_lobby = find_lobby def find_lobbies(self,...
my_list = [i * j for i in range(2, 7) for j in range(2, 7)] new_list = [el for el in my_list if my_list.count(el) < 2] print(f'Исходный список {my_list}') print(f'Новый список {new_list}')
from scipy.signal import filtfilt, butter def butterworth(x, order, freq=0.05): b, a = butter(order, freq) return filtfilt(b, a, x)
"""Integration tests using YORM as a persistence model.""" # pylint: disable=missing-docstring,no-self-use,misplaced-comparison-constant import os from expecter import expect import yorm from yorm.types import String # CLASSES ##################################################################### class Config: ...
import tensorflow as tf import numpy as np from .frame import Frame, Twist from .rotation import * from enum import IntEnum class JointType(IntEnum): RotX = 0 RotY = 1 RotZ = 2 RotAxis = 3 NoneT = 4 class Joint(object): def __init__(self, type, origin=None, axis=None, name='', limits=None): self.type = type ...
from dictionary.searchbase import SearchBase import requests from bs4 import BeautifulSoup from random import choice from string import ascii_letters, digits import re import json import time from django.utils.text import slugify import pprint from dictionary import helper import random import threading from dictio...
from django.db import models class Arjun(models.Model): idno=models.IntegerField(primary_key=True) name=models.CharField(max_length=30) designation=models.CharField(max_length=30) salary=models.DecimalField(max_digits=10,decimal_places=2) image=models.ImageField(upload_to="arjun/")
import re from random import choice def get_statistics(text: str, triads: list[str]) -> dict: statistics = {} for triad in triads: ones = f"(?=({triad}1))" zeros = f"(?=({triad}0))" total_ones = len(re.findall(ones, text)) total_zeros = len(re.findall(zeros, text)) stat...
#todo make ##todo make #todo make this more general import maya.cmds as cmds import random #delete existing cubes cubeLs = cmds.ls('myCube*', tr=True) if len(cubeLs) > 0: cmds.delete(cubeLs) #make cube def createCube(): cube = cmds.polyCube(name='myCube#')[0] cmds.move(0,0.5,0, cube, r=True) #make piv...
import numpy as np from dl4nlp.utilities import softmax, tanh_gradient from dl4nlp.preprocessing import build_dictionary, to_indices from dl4nlp.gradient_check import gradient_check from dl4nlp.gradient_descent import gradient_descent from dl4nlp.sgd import bind_cost_gradient, get_stochastic_sampler from dl4nlp.neural_...
from robot.megapi import * right = 1 left = 2 deltaTickRight = 0 def onRead1(level): print("Encoder1 motor speed Value:%f" %level) #if( int(level) > 500): # print("ffffff") #deltaTickRight = level def onRead2(level): print("Encoder2 motor speed Value:%f" %level) #deltaTickRight = ...
# 计算器,当用户输入的不是+-*/会抛出异常,并捕捉这个异常 try: num1 = int(input("请输入整数")) num2 = int(input("请输入整数")) op1 = input("请输入+-*/") if op1 != "+" and op1 != "-" and op1 != "*" and op1 != "/": raise Exception("请输入正确的+-*/") if op1 == "+": print(num1 + num2) elif op1 == "-": print(num1 - num2...
""" Найдите производителей ПК с процессором не менее 450 Мгц. Вывести: Maker """ from queries.models import Product from django.db import connection, reset_queries def run(): result = Product.objects.values('maker').filter(pc__speed__gte=450).distinct() return result def print_result(): reset_queries() ...
from django.conf import settings from redis import Redis from rq import Queue from . import RunnerBase class RedisRunner(RunnerBase): def run(self, func, *args, **kwargs): q = Queue(connection=Redis.from_url(settings.REDIS_URL)) return q.enqueue(func, args=args, kwargs=kwargs) def get(id): ...
from peewee import * import datetime db = SqliteDatabase('proxy.db') class BaseModel(Model): class Meta: database = db class IPInfo(BaseModel): ip_port = CharField(unique=True, help_text='ip地址、端口') http_type = CharField(help_text='协议类型 http/socks') check_total_count = IntegerField(default=0...
#dictionary is an unoredered type of collection # in it key/value pair{key.value} #dictionary_example = {} dictionary_example = {'name':'rachel','test_grade':98} print(dictionary_example.get('name'))
#!/usr/bin/env python3 import requests import sys def url_encode(url): out = '' for c in url: out += '%' + hex(ord(c))[2:].zfill(2) return out ip = sys.argv[1] r = requests.get('http://' + ip + ':9990' + '/' + url_encode(url_encode('../../data/gonclub.db'))) print(r.text, flush=True)
# -*- coding: utf-8 -*- import json from flask import Flask, request, Response, jsonify, send_file from werkzeug.utils import secure_filename from dblite import * import os # prefix = d['SERVER-INFO']['PREFIX'] from dblite import people from dblite import session from dblite.consts import SQL_GET_USER_TEMPLATES from...
""" sampleFunction5 class3 absolute value """ def absoluteValue(valueIn): if valueIn >= 0: valueOut = valueIn else: #valueIn was -ve valueOut = -1 * valueIn return valueOut print(absoluteValue(-3)) print(absoluteValue(4)) print(absoluteValue(0)) print(absoluteValue(1.345)) print(absoluteV...
import csv import sys import asyncio from urllib.request import urlopen from concurrent.futures import ProcessPoolExecutor from pyppeteer import launch from requests_html import HTML def retrieve_jquery_source(): with urlopen('http://code.jquery.com/jquery-latest.min.js') as jquery: return jquery.read()....
# coding:utf-8 ''' Created on 2016年12月6日 @author: hasee test.getmessage.httphandle ''' from HTMLParser import HTMLParser class MyHTMLParserLocation(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.items = [] self.flag = False def handle_startt...
from django.core.validators import RegexValidator, URLValidator from django.utils.translation import gettext_lazy as _ class HostnameValidator(RegexValidator): regex = '^(' + URLValidator.host_re + ')$' message = _('Enter a valid hostname.') class HostnameAddressValidator(RegexValidator): regex = '^(' +...
from pymotifcluster.clusterwindow import * # import pytest # import pytest_benchmark testing_windows = [ "DSSASPEVVSDLPPSSPKGSPDRHDPSTSSP", "VREQAVWALGNVAGDSPKCRDLVLSYGAMTP", "LTSPIPRASVITNQNSPLSSRATRRTSISSG", "VTPCKGSGDRSLGLTSPIPRASVITNQNSPL", "AIKASSLSKEGLLFGSPKLSGGSSLYGKLQQ", "GSFRKNLDTKDAIISSPKLMESGSGKLP...
# Generated by Django 2.1.5 on 2019-03-07 08:59 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('users', '0008_first_year_first_semester_bsba_first_year_second_semester_bsba_fourth_year_first_semester_bsba_fourt'), ] operations = [ migrations.Re...
import tensorflow as tf import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # 不显示警告 tf.compat.v1.disable_eager_execution() # tensorflow2 使用旧版本功能需要调用该方法 def demo1(): # 构建图: a=tf.constant(2,name='a') # 设定常量 b=tf.constant(3,name='b') c=tf.add(a,b,name='c') print(a,'\n',b) print(c) print(a....
import argparse import glob import json import os import time import math import openai import shutil import pathlib languages_to_run = {'C', 'C#', 'C++', 'Go', 'Java', 'JavaScript', 'PHP', 'Python', 'Ruby', 'Rust', 'Scala', 'TypeScript'} # The private OpenAI API key needs to be an environment va...
# -*- coding: utf-8 -*- import os import random trainval_percent = 1 # 用于训练验证的数据比例 train_percent = 0.8 # 用于训练验证的数据中,训练数据所占比例 xmlfilepath = '/PycharmProjects/lx/data/xml' # 标注信息xml文件路径 txtsavepath = '/PycharmProjects/lx/data/Main' # 文件保存路径 total_xml = os...
import random import string import re def random_generator(size=6 , chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for x in range(size)) """ def pruebas(request): # Formulario if request.method == 'POST': form = ProPedidoForm(request.POST) if form.is_...
from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect from home_app.models import CreatedPizzas, Toppings, PizzaSize # Create your views here. def home(request): return render(request, 'home.html') def created_pizza_list(request): access_pz_list = CreatedPizz...
from flask import Flask, make_response, request app = Flask(__name__) xml_o = """<?xml version="1.0" encoding="UTF-8"?> <query xmlns:yahoo="http://www.yahooapis.com/v1/base.rng" yahoo:count="1" yahoo:created="2018-04-21T15:18:32Z" yahoo:lang="en-IN"> <results> <channel> <yweather:units ...
import sys,os sys.path.append(os.path.join(os.path.dirname(__file__), '../..')) sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from django.shortcuts import render from django.http import HttpResponse from django.http import request import nsepy from mrigwebapp.myhtml import myhtml import mrigwebapp.for...
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: result = '' i = 0 while strs: j = 1 if i == len(strs[0]): break else: current = strs[0][i] while j < len(strs): ...
#Dada una secuencia de caracteres sec y un entero r devolver en la variable secRot la secuencia rotada r posiciones a la derecha. Ejemplo: si sec="abbcd" y r=3 entonces en secRot="bcdab" sec = raw_input("Ingrese una secuencia de letras:") N = int(input("Ingrese el numero de rotaciones hacia la derecha: ")) i = 0 newT...
from .base import * DEBUG = True ALLOWED_HOSTS = [] # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'openmind', 'USER': 'oliver', 'PASSWORD': 'yugiho2000', '...
# coding=utf-8 import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import time import os import shutil # 清空log文件 filelist = [] rootdir = "./model/tensorflowlogs/" for f in os.listdir(rootdir): filepath = os.path.join(rootdir, f) if os.path.isfile(filepath): os.remove(filep...
print("*"*5,"Menu Harga Buah-Buahan","*"*5) DaftarBuahBuahan = { "apel" : 5000, "jeruk" : 8500, "mangga" : 7800, "duku" :6500 } print(DaftarBuahBuahan) print("-"*50) def BeliBuah(): memilih = input("Nama buah yang dibeli = ") while True : try: if memilih in D...
import json from django.http import HttpResponse from django.shortcuts import render, redirect, get_object_or_404 from django.views.generic.list import ListView from cafe.models import Cafe from forms.forms import SearchForm, CafeRegistrationForm class CafeleListView(ListView): template_name = 'home.html' m...
import math def solve(goal, searchRange): table = [] i = 0 n = searchRange for i in range(n + 1): if i == 2 or i % 2 == 1: table.append(1) else: table.append(0) maxN = int(math.sqrt(n)) + 1 i = 1 while i < maxN: i += 2 if table[i] == 0...
import sys def snip_special_characters(word): word_new = "" for char in word: if char.isalpha() or char == "-": word_new += char return word_new file_handler = open(str(sys.argv[1])) word_counts = {} for line in file_handler: line = line.rstrip() words = line.split(" ") ...
# Main UIButton Class. Made for subclassing for other buttons # Whole button is being drawn with code, no images in sight! Woo! import pygame from noticer import * from constants import * from UIView import * class UIButton(UIView): def __init__(self, dimensions, parent): cont = constants() UIVi...
import tornado.httpserver import tornado.ioloop import tornado.web import tornado.options import os.path from pymongo import MongoClient import hashlib from tornado.options import define, options define("port", default=8888, help="run on the given port", type=int) def role(array): def _role(method): def ...
''' ---------크롤링의 방법---------- 원하는 웹페이지에 접속 -> html 데이터를 분석한다 받아온 html 데이터를 분석가능한 형채로 가공한다 -> 원하는 데이터를 추출한다. ''' import requests from bs4 import BeautifulSoup from requests_html import HTMLSession # session = HTMLSession() # response = session.get("https://www.naver.com") # print(response.html.links) response = re...
import ui from plistlib import * from random import randrange import speech import sound from time import sleep '''fileName is the plist to import''' fileName = 'Bitsboard.plist' #fileName = 'LPDB00/Bitsboard.plist' class Phototouch (ui.View): def __init__(self): self.name = 'Photo Touch' ...
# Generated by Django 2.0.3 on 2018-04-01 20:50 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('filmsApi', '0002_auto_20180401_2252'), ] operations = [ migrations.AddField( model_name='film', name='actors', ...
# """ Base class for episodic reinforcement learning agents. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from texar.agents.agent_base import AgentBase # pylint: disable=too-many-instance-attributes class EpisodicAgentBase(A...
"""Datasets from metadat.""" import json import os.path as op import pandas as pd from pymare.utils import get_resource_path def michael2013(): """Load a dataset of studies on the persuasive power of a brain image. This dataset was published in :footcite:t:`michael2013non`, and was curated in metadat :...
import numpy as np import cv2 import math h=300 w=300 cap = cv2.VideoCapture(0) SUN_LOC=(200,40) SUN_RSIZE=15 ORBITAL_R=10 def Orbiral(frame,Centerloc,orbit_r,size_r,phi,color): x_orbit=Centerloc[0]+int(orbit_r*np.cos(np.deg2rad(phi))) y_orbit=Centerloc[1]+int(orbit_r*np.sin(np.deg2rad(phi))) ...
# https://leetcode.com/problems/maximum-subarray/description/ # solution: # https://en.wikipedia.org/wiki/Maximum_subarray_problem#Kadane's_algorithm_(Algorithm_3:_Dynamic_Programming) class Solution: def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ ma...
import sys import math # def reverse(num): # return num[::1] def toBaseN(num, base): baseN = [] highestPower = 0 while pow(base, highestPower) < num: highestPower += 1 for i in range (highestPower, -1, -1): baseToPower = pow(base, i) baseN.append(math.floor(num/baseToPower...
""" Build your Deep Neural Network: Step by Step """ import numpy as np import h5py import matplotlib.pyplot as plt from testCases import * from dnn_utils import sigmoid, sigmoid_backward, relu, relu_backward #%matplotlib inline #plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots #plt.rcParams['i...
from logging import getLogger import requests from django import forms from django.conf import settings from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ from friendly_captcha.widgets import FrcCaptchaWidget logger = getLogger('django.friendly_captcha') class...
import math def computeForSevereImpact(data): average_Daily_Income_InUSD = data['region']['avgDailyIncomeInUSD'] average_Daily_Income_population = data['region']['avgDailyIncomePopulation'] time_to_elapse = data['timeToElapse'] reported_cases = data['reportedCases'] total_hospital_beds = data['tota...
import django_rq from django.conf import settings from django.core.mail import send_mail from django.db.models.signals import post_save from django.utils.translation import ugettext_lazy as _ul from tastypie.api import Api from tastypie import fields, utils from tastypie.models import ApiKey from tastypie.utils impor...
import pygame as pg from .. import prepare from .ramp import Ramp, Hill from .windmill import Windmill HOLE_INFO = { 1: {"ramps": [((855, 279, 373, 27), (0, -1)), ((855, 347, 373, 48), (0, 1))], "hills": [], "ball pos": (150, 200), "cup ...
from numba import jit, uint32 import numpy as np from timeit import timeit @jit(nopython=True, cache=True) def go_fast(): # Function is compiled to machine code when called the first time x = np.arange(100, dtype=np.uint32).reshape(10, 10) trace = 0 for i in range(x.shape[0]): # Numba likes loops ...
import os import json import re import datetime def processSource(source, f): posts = open("data2/"+source+"_2.json", mode='r', encoding='utf-8') data1 = json.load(posts) file3 = open('data3/confessions.csv', 'a', encoding='utf-8') for post in data1: month = str(int(post["time"][5:7])) college = post["c...
from django.contrib import admin from .models import Priority, Todo class PriorityAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'order') admin.site.register(Priority, PriorityAdmin) admin.site.register(Todo)
import requests import argparse class RxnormClassMeds(): def __init__(self, classid): self.classid = classid r = requests.get(f'https://rxnav.nlm.nih.gov/REST/rxclass/classMembers.json?classId={classid}&relaSource=ATC') drugs = r.json()['drugMemberGroup']['drugMember'] self.drug_di...
>>> # menentukan bilangan genap >>> genap = lambda x: x%2 == 0 >>> list(filter(genap, range(11))) [0, 2, 4, 6, 8, 10]
def knapsackwithoutrepsbu(weight, count, items): A = [0] * (weight + 1) B = [0] * (weight + 1) A[0] = 1 for i in range(count): for j in range(weight, items[i] - 1, -1): if A[j - items[i]] == 1: A[j] = 1 B[j] = items[i] k = weight while A[...
from random import * l = [] for i in range(50): l.append(randint(1, 100)) print(l) l.sort() print(l[0], l[1]) print(l[-2], l[-1])
import getpass import warnings import netrc import os from .system import SYSTEM from . import config __CACHE__ = None def _filename(filename=None): if filename is None: if SYSTEM == 'win': filename = os.path.join(os.environ.get("USERPROFILE"), "_netrc") else: filename = ...
from .models import Department, User, Question, Answer from django.contrib.auth.admin import UserAdmin from django.contrib import admin from django.utils.translation import gettext, gettext_lazy as _ class UserInlineInDepartment(admin.TabularInline): model = User.departments.through extra = 0 class AnswerInl...
from points import Point from math import sqrt class Triangle: def __init__(self, x1=0, y1=0, x2=0, y2=0, x3=0, y3=0): self.pt1 = Point(x1, y1) self.pt2 = Point(x2, y2) self.pt3 = Point(x3, y3) def __str__(self): output = "[(" + str(self.pt1.x) + ", " + str(self.pt1.y) + "), (...
from PyObjCTools.TestSupport import TestCase import SharedWithYouCore class TestSWAction(TestCase): def test_constants(self): self.assertIsTypedEnum(SharedWithYouCore.SWCollaborationIdentifier, str) self.assertIsTypedEnum(SharedWithYouCore.SWLocalCollaborationIdentifier, str)
import math import os import sys import cv2 import numpy as np class Line(object): def __init__(self, a, b, c): self.a = a self.b = b self.c = c self._norm = (a**2 + b**2) ** 0.5 self._const_arg = None self._const_val = None @classmethod def from_coords(cl...
''' Created on Feb 6, 2019 @author: Arun Sarita ''' import POM import naukari_homepage import time from selenium.webdriver.common.action_chains import ActionChains import login time.sleep(5) main_m=POM.f_xpath('/html/body/div[1]/div/div/ul[2]/li[2]/a/div[2]') action1=ActionChains(POM.driver) action1.move_to_element(m...
from django.apps import AppConfig class StudentRegisterationConfig(AppConfig): name = 'student_registeration'
import sys import math T=int(sys.stdin.readline().strip()) while T : T-=1 K=int(sys.stdin.readline().strip()) papers=list(map(int,sys.stdin.readline().strip().split(' '))) maximum = math.inf matrix = [[maximum] * (K+1) for _ in range(K+1)] subsum=[0] *(K+1) for i in range(1,K+1): ...
import csv from app import app from app.models import db, Category, Dish with app.app_context(): category_entities = [] with open('delivery_categories.csv') as f: reader = csv.reader(f) for category_id, title in reader: if category_id == 'id': continue c...
#!/usr/bin/env python # -*- coding:utf-8 -*- import datetime import re from PIL import Image import numpy as np class ImageConverter: """ 画像変換クラス """ def __init__(self,files=[]): # コンストラクタ self.files = files if self.files is None: print("Error:file is empty") r...
#!/usr/bin/env python3 import numpy as np import tensorflow as tf import sys, os from decimal import Decimal import hm_prep as hm import ms_prep as ms import random ############ Model Selection ############ HM_POS_PATH = 'data/human/omni_polyA_data/positive/' HM_NEG_PATH = 'data/human/omni_polyA_data/negative/' MS_P...
from .abc import BaseModel, MetaBaseModel, db class Measure(db.Model, BaseModel, metaclass=MetaBaseModel): """Model class for measure.""" id = db.Column(db.Integer(), nullable=False, primary_key=True) country_id = db.Column(db.Integer, db.ForeignKey('country.id', ondelete='CASC...
# -*- coding: utf-8 -*- import json import subprocess import time def getLength(filename): command = ["ffprobe", "-loglevel", "quiet", "-print_format", "json", "-show_format", "-show_streams", "-i", filename] result = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subproce...
""" This will autopatch machines using landscape Todo: Look at ways to make systems patched at different times get the same packages. Manage reboots - canonical suggest polling for the need reboot flag (yuck) The configuration.py file should be a copy of configuration.py.template The copy should have the details ...
from flask import abort, jsonify, request from __main__ import app, db from models import StoredImage, User @app.route('/admin/news/add/feature_image', methods=['POST']) def ajax_admin_news_add_feature_image(): # Get the signed in User (if there's one), or None user = User.get_signed_in_user() if user is None: ...
# from django.test import TestCase # from blog.forms import CommentForm # class CommentFormTest(TestCase): # @classmethod # def setUpClass(cls): # cls.valid_data = { # "name": "Subhan", # "email":"subhanrzayev97@gmail.com", # "message":"Write this comment" # ...
#!/usr/bin/python3 import smbus bus = smbus.SMBus(1) # 0 = /dev/i2c-0 (port I2C0), 1 = /dev/i2c-1 (port I2C1) DEVICE_ADDRESS = 0x18 #7 bit address (will be left shifted to add the read write bit) DEVICE_REG_MODE1 = 0x00 DEVICE_REG_LEDOUT0 = 0x1d #Write a single register r = bus.write_byte_data(DEVICE_ADDRES...
from django.contrib import admin # Register your models here. from .models import Person, Book class PersonAdmin(admin.ModelAdmin): # listdisplay设置要显示在列表中的字段(id字段是Django模型的默认主键) list_display = ('id', 'name', 'age', 'email', 'data',) # list_per_page设置每页显示多少条记录,默认是100条 list_per_page = 50 # ordering设...
''' Домашнее задание N8 Создать класс для представления трехмерных векторов (обычных евклидовых). С помощью специальных методов: "__add__", "__mul__", "__abs__", "__bool__", "__str__" - определить сложение векторов, умножение вектора на число, длинна вектора, булево значение (True - если длинна > 0) и строковое предста...
import tushare as ts import datetime import pandas as pd import numpy as np import struct import os import math from statistics import mean from numba import jit from numba.typed import List tushare_token = '1e405fa29516d0c96f66ee71f4f2833b31b566cd6ad4f0faa895c671' #获取上证综指历史数据,含市净率,市盈率 def get_shanghai_from_tushare()...