text
stringlengths
38
1.54M
import graphics.rectangle from graphics.dgraphics import sphere print("area of rectangle:",graphics.rectangle.area(3,4)) print("perimeter of rectangle:",graphics.rectangle.perimeter(3,4)) from graphics.circle import * print("area of circle:",area(2)) print("perimeter of circle",perimeter(2)) from graphics.dg...
print('가속도(m/s²) = ',end='') a=input() print('처음 속도(m/s) = ',end='') v0=input() print('나중 속도(m/s) = ',end='') v=input() print('시간(s) = ',end='') t=input() print('거리(m) = ',end='') s=input() print('질량(kg) = ',end='') m=input() print('알짜힘(N) = ',end='') F=input() print() print('알고 싶은것은? : ',end='') answer...
from nltk.tokenize import sent_tokenize import os from allennlp.predictors.predictor import Predictor from allennlp.models.archival import load_archive from typing import List import subprocess sentence = [ "New Delhi 's government district is still under a lockdown . New Delhi (CNN) -- Police continue...
import serial #from library PySerial import keyboard import json configFile = open("pedalConfig.json").read() configData = json.loads(configFile) numPedals = configData["numPedals"] #press actions (order in array is index of pedal) onKey = configData["onKey"] onKeySHIFT = configData["onKeySHIFT"] def P...
# test for mesh.py import numpy as np import pyeit.mesh as pm def test_shape_circle(): """unit circle mesh""" def _fd(pts): """shape function""" return pm.shape.circle(pts, pc=[0, 0], r=1.0) def _fh(pts): """distance function""" r2 = np.sum(pts**2, axis=1) return ...
""" Charachters project for coding dojo """ # pylint: disable=c0103 #def odd_even(start, end, step): #for i in range(start, end, step): #if i % 2 != 0: #print "number is " + str(i + 1) + ". This is an odd number." #else: #print "number is " + str(i + 1) + ". This is an even...
''' 3章の改良 Inningのデータをリストで持つように変更したりScoreBoardの導入などクラスの責務を整理した ''' import random import math class Team: def __init__(self, name, attack, defense): self.name = name self.__attack = attack self.__defense = defense @classmethod def create(cls, name): attack = random.randint(...
""" Flights API""" from flask import Blueprint, Response, request, g from bson import json_util from api.auth import jwt_required JSON_MIME_TYPE = 'application/json' BP = Blueprint('flights', __name__) COL_FLIGHTS = g.db.flights def get_all_flights(): """ Get all flights """ res = COL_FLIGHTS.find() f...
__author__ = 'malbert' from dependencies import * trackTimes = range(100) tracks=tracking.trackObjects(b.segregpredmic(trackTimes),minTrackLength=len(trackTimes),memory=2) # miccalc,outercalc,motility = [],[],[] # containers,containercs,containerbs = [],[],[] # for itrack,track in enumerate(tracks): # print itra...
import barPlot as bp df = [["label1", "label2", "label3" ], [5,6,8], [9,10,2], [6,3,8]]; bp.barPlot(df);
import io from unittest import SkipTest from mock import call, Mock, patch from jirafs.utils import run_command_method_with_kwargs from .base import BaseCommandTestCase class TestPushCommand(BaseCommandTestCase): def setUp(self): super(TestPushCommand, self).setUp() def test_push_no_changes(self):...
#-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*- from bes.cli.cli_options import cli_options from ..system.check import check from bes.script.blurber import blurber from .softwareupdater_error import softwareupdater_error class softwareupdater_options(cli_options): def __...
#!/usr/bin/env python # # License: BSD # https://raw.githubusercontent.com/splintered-reality/py_trees/devel/LICENSE # ############################################################################## # Documentation ############################################################################## """ A library of fundamen...
#!/usr/bin/python3 #coding=utf-8 import os import sys import subprocess import re import time tokent_master_tmp = subprocess.getstatusoutput("kubeadm token create --print-join-command") tokent_master = tokent_master_tmp[1] print(tokent_master)
""" Autor: Daniel de Souza Baulé (16200639) Disciplina: INE5452 - Topicos Especiais em Algoritmos II Atividade: Segundo simulado - Questoes extra-URI União de Conjuntos - Versão para testes """ from src.UniaoDeConjuntos.No import No from pprint import pp def test(n, conjuntos, m, operacoes, test_number='X'): ...
from typing import Tuple, List from enum import Enum, auto class Rectangle: def __init__(self, left, top, right, bottom): self.left = left self.top = top self.right = right self.bottom = bottom class IDCardFieldTypeEnum(Enum): TEXT = auto() TEXT_NAME = auto() TEXT_CIT...
from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode from django.template.loader import render_to_string from django.contrib.sites.shortcuts import get_current_site from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils import six from django.ut...
import tensorflow as tf import numpy as np import pandas as pd import requests import shutil import matplotlib.pyplot as plt from tensorflow.keras.layers import Dense, Input, Conv1D, GlobalMaxPooling1D from tensorflow.keras.layers import MaxPooling1D, Embedding from tensorflow.keras.models import Model from tensorflow....
from dashboards.models import DietPlan from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_photo = models.ImageField( upload_to='media/profiles/', default='profiles/default.jpg') ...
#pylint:disable=R0914 if __name__ == "__main__": import random import charsets import warnings import errors else: import random import warnings from noise import charsets from noise import errors class Noise: def __init__(self): self.fallback = { "charset": charsets.charset_alpha(), "stringlen": 4, "s...
import json import validictory from validictory.validator import FieldValidationError from cellcounter.keyboardapi.defaults import TEST_POST_KEYBOARD_MAP from django.core.exceptions import ValidationError class ValidJSONValidator(object): schema = { "patternProperties": { "[a-z]": { ...
import numpy as np import matplotlib.pyplot as plt from numpy.polynomial import Chebyshev as T np.random.seed() x = np.linspace(0, 2*np.pi, 20) y = np.sin(x) + np.random.normal(scale=.2, size=x.shape) p = T.fit(x, y, 15) plt.plot(x, y, 'o') xx, yy = p.linspace() plt.plot(xx, yy, lw=2) plt.show()
#crie um sistema de caixa eletronico e mostre quantas notas a pessoa vai sacar considerando notas de 100, 50, 10, 5 e 1 from time import sleep s = 1 while s == 1: print('-' * 30) print(' Caixa Eletronico') print('-' * 30) valor = int(input('Quanto Deseja Sacar: ')) if valor > 600: print...
import sys, heapq def alloc(i, t): if t not in desu: heapq.heappush(access, t) desu[t] = set() desu[t].add(i) used[i] = t def delloc(i): if used[i] in desu: desu[used[i]].remove(i) def gc(t): while len(access) > 0 and access[0]+600 <= t: min_t = heapq.heappop(access) if min_t in desu: ...
from netCDF4 import Dataset, date2num, num2date import numpy as np import urllib2 from datetime import timedelta def get_local(path_src, target_folder): nc = Dataset(path_src, 'r') to_local(nc, 'wib', target_folder) to_local(nc, 'wita', target_folder) to_local(nc, 'wit', target_folder) def to_local(...
# -*- coding: UTF-8 -*- from __future__ import unicode_literals from tutorials.catalog.models import Product from north.dbutils import babel_values def P(en,de,fr): return Product(**babel_values('name',en=en,de=de,fr=fr)) def objects(): yield P("Chair","Stuhl","Chaise") yield P("Table","Tisch","Table") ...
import os import tempfile import cv2 import numpy as np import pytest from otx.mpa.det.inferrer import DetectionInferrer, replace_ImageToTensor from otx.mpa.utils.config_utils import MPAConfig from tests.test_suite.e2e_test_system import e2e_pytest_unit from tests.unit.algorithms.detection.test_helpers import ( D...
# -*- coding: utf-8 -*- from django.shortcuts import render,redirect,HttpResponse # import sys # sys.path.append('..') # Create your views here. from database import models from functools import wraps from public_function_blog import * @login_check def category_list(request): # 数据库查询 uid=request.COOKIES.g...
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('course', '0012_timelabel_end_time'), ] operations = [ migrations.RenameModel( old_name='TimeLabel', new_name='Event') ]
import pytest from postproject import app from postproject import routes @pytest.fixture def client(): client = app.test_client() return client #pytest for app URLs def test_home_route(client): url = '/' response = client.get(url) assert response.status_code == 200 def test_login_route(clien...
#Acknowledgement #Acknowledge to this shell file developed by Team 18 of COMP90024 of The University of Melbourne, under Apache Licence(see LICENCE). import time import boto from boto.ec2.regioninfo import RegionInfo import json ''' Create a instance and a "size" GB volumn, return the volumn ''' def crea...
def max (c,d,e): if c > d and c > e: print c elif d > c and d >e: print d elif e >c and e > d : print e max (2,4,3)
t = int(input()) while t > 0: n = int(input()) arr = list(map(int,input().split())) l = min(arr) flag = 1 flag1 = 1 for i in range(n): if arr[i] == l: min_in = i break for i in range(0,min_in-1): if arr[i+1] < arr[i]: flag = 0 for i in...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class VehicleInfoDto(object): def __init__(self): self._brand_name = None self._cert_hash = None self._cert_result = None self._cert_type = None self._certificat...
import numpy as np import matplotlib.pyplot as plt def allocate_probe(grid_size, volume): # grid_size (x_dim, y_dim, z_dim) # volume (x_min, x_max, y_min, y_max, z_min, z_max) # # out: (x, y, z, pos) grid_size_x, grid_size_y, grid_size_z = grid_size x_min, x_max, y_min, y_max, z_min, z_max = v...
# 分类:法师:火女 冰女 战士:德玛西亚 诺克莎斯 坦克:住美 雷霆战机 fa_shi = ['火女','冰女'] zhan_shi = ['德玛西亚','诺克莎斯'] tan_ke = ['猪妹','雷霆咆哮'] hero = {'法师':fa_shi,'战士':zhan_shi,'坦克':tan_ke}
#!/usr/bin/env python # -*- coding: utf-8 -*- # @author: x.huang # @date:18-1-4 def ensure_int_or_default(num, default=0, is_abs=False): try: new_num = int(num) if is_abs: return abs(new_num) return new_num except ValueError: return default
# menu from time import sleep n1 = float(input('Digite um valor: ')) n2 = float(input('Digite outro: ')) op = 0 while op != 5: op = int(input('''O que deseja fazer? [ 1 ] Somar [ 2 ] Multiplicar [ 3 ] Maior Número [ 4 ] Novos números [ 5 ] Sair do programa Sua opção: ''')) i...
import pandas as pd import numpy as np import pandas_datareader.data as pdr tickers = ['IOC.NS','ICICIBANK.NS','LT.NS','HDFCBANK.NS','TCS.NS','BHARTIARTL.NS','TATACOMM.NS','COALINDIA.NS','ONGC.NS','SBIN.NS','TATASTEEL.NS','VEDL.NS','NTPC.NS','M&M.NS','PNB.NS','RELIANCE.NS','ITC.NS','BPCL.NS','HINDPETRO.NS','HINDAL...
p = float(input('Digite o preço do produto: ')) valor_desconto = 5 res = p - (p * valor_desconto / 100) # no parentese se calcula a porcentagem e depois tira a diferença # formula porcentagem ... preço - ( preço * desconto / 100 ) print('O produto que custava R${} com desconto de {} por cento ficará R${} '.format(p,v...
# -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-06-16 13:54 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('user', '0002_auto_20180614_2013'), ] operations = [ migrations.AddField( ...
#!/usr/bin/python3 import hidden_4 if __name__ == "__main__": for x in dir(hidden_4): if not x.startswith("__"): print("{}".format(x))
from __future__ import division import healpy as hp import matplotlib.pyplot as mp import numpy as np from numpy import sin, cos, pi from pyoperators import Rotation3dOperator from pysimulators import FitsArray from qubic import ( QubicInstrument, create_random_pointings, equ2gal, gal2equ, map2tod, tod2map_all...
#!/bin/python3 import os import sys # # Complete the gradingStudents function below. # def gradingStudents(grades): return [g+(5-g%5) if g+(5-g%5)-g<3 and g>=38 else g for g in grades] if __name__ == '__main__': f = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) grades = [] for _ in rang...
from urllib import urlencode try: import json as simplejson except ImportError: try: import simplejson except ImportError: from django.utils import simplejson from social_auth.backends import BaseOAuth2, OAuthBackend from social_auth.utils import dsa_urlopen INSTAGRAM_SERVE...
def login(): with open('passwd') as f: lines = f.readlines() lines = [line.split() for line in lines] pwds = dict(lines) i = 0 #三次登录验证 while i<3: username=input('username:') #获取 用户名 if username not in pwds: #用户名不存在 print('invalid username') ...
# %matplotlib inline # %load_ext autoreload # %autoreload 2 #Name model modelname = 'heterog_1000' import os from pathlib import Path import sys import numpy as np import flopy import SGD import config import datetime print(sys.version) print('numpy version: {}'.format(np.__version__)) print('flopy version: {}'.fo...
budget = float(input()) season = input() expenses = 0 sleep = "" if budget <= 100: destination = "Bulgaria" if season == "summer": expenses = 0.3 * budget sleep = "Camp" elif season == "winter": expenses = 0.7 * budget sleep = "Hotel" elif 100 < budget <= 1000: destinatio...
import json import re import pandas as pd from channels.generic.websocket import AsyncWebsocketConsumer def csv_to_dict(csv_url): print(csv_url) df = pd.read_csv(csv_url) return df.to_dict(orient='records') class ChatConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): su...
""" Detect single-character XOR One of the 60-character strings in this file has been encrypted by single-character XOR. Find it. (Your code from #3 should help.) """ from base64 import b16encode from ..utils import decode_hex, xor_hex from .chal3 import select_most_englishest, simple_score, single_letter_xor_plain...
#!/usr/bin/python """A [GNU Units][gnu-units] compatible exchange rates currencies updater If you have ever used [GNU units][gnu-units], you may have enjoyed it's very smooth user interface and command line arguments interpretation. `units` also provides exchange rates currency conversions. It does so by reading the f...
import unittest import os import shutil from datetime import datetime import core today = datetime.today class TestEstimatingJob(unittest.TestCase): def setUp(self): core.disconnect_db() # ensure database objects aren't interfered with core.EstimatingJob.yaml_filename = '' core.EstimatingJob._dump_lock = Tr...
''' ******************************************************** * The model shows a Benders Decomposition for a stochasitic programming coffee machine management problem.* * The original MIP is decomposed into two problems. * * The subproblem is using the dual formulation. * * Fo...
import json import unittest import webtest from google.appengine.ext import testbed, ndb import main from src.news.storage import Category CATEGORY_TITLE = 'Category' TITLE = 'Article' URL = 'www.url.com' LINES = [{'line': 'I like cats.'}] ARTICLES = [{'url': URL, 'title': TITLE, 'lines': LINES}] class NewsApiTest...
#!/usr/bin/env python #Read in a RTL file, do synthesis and placement, route #Example usage: python python_files_than_a_size.py -f /home/user1/simulations/65nm/LFSR/spice_decks_1 import optparse import re,os,glob import fileinput,shutil import subprocess, time from optparse import OptionParser import sys parser = Op...
import main import foursquareAPI import picker from user import User commands = ['quit','help','categories','search','new user','show users','delete user','pick location'] users = list() if __name__ == '__main__': print("Venue Picker\n") command = str(input("What would you like to do\n")).lower() while com...
#Write a Python program to read specific columns of a given CSV file and print the content #of the columns. import csv with open('1.csv', 'r') as file: reader = csv.reader(file) for row in reader: print(row[0]+" "+row[1])
import binascii # import struct import pandas as pd # data = pd.read_excel(r'C:\Users\ZKTT\Desktop\wkl\tc-parse.xls', sheet_name='整星动中-数传天线固定站') # f = open(r'C:\Users\ZKTT\Desktop\wkl\指令文件20201014\totianta\遥控\码字核对\BJBFDZ_2020-09-24-20_10_57', 'rb') # for row in data.values: # print('{}{}{}'.format(row[0], " ", bi...
parent = {} rank = {} # Mapping buildings to integer IDs; Union Find; size of set def find(v): if v not in parent.keys(): rank[v] = 1 parent[v] = v return v elif parent[v] == v: return v else: p = find(parent[v]) parent[v] = p return p def union(a,b...
# Copyright (c) 2016 IBM Corporation # Copyright (c) 2013 Red Hat, 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 at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
import os import sys import logging import config class Logger(object): def __init__(self, path): self.base_path = config.SETTINGS['LOG_DIR'] self.path = os.path.join(self.base_path, path) self.make_dirs(self.path) self.logs = {} def make_dirs(self, path): try: ...
# -*- coding: utf-8 -*- from Bio import Entrez, Medline import contextManager as cm import requests import os # returns an array containing title, authors(array), abstract, ontologis, and date (url still needs to ne added) def getPubmedArticles(disease, ammount=10): Entrez.email = "fc44949@alunos.fc.ul.pt" ...
# ! /usr/bin/python3 # @Djavan Sergent from random import shuffle from utils.function import check_dir, list, check_vlc from interface.views import EvalView, RecapView, IdView, TrueFalseView from media.evaluator import Evaluator, Evaluation from media.params import Params from media.player import Player from media.reco...
#encoding=utf-8 ######################################################################### # File Name: test.py # Author: GuoTianyou # mail: fortianyou@gmail.com # Created Time: 五 2/24 23:02:37 2017 ######################################################################### import hadoop import multiprocessing as mp def...
#!/usr/bin/env python2.6 # -*- coding: utf-8 -*- import json import gzip import codecs import sys from collections import defaultdict #import lzma class TweetParser(object): def __init__(self, filename): self.filename = filename self.hashtags = dict(defaultdict(list)) def extract_hashtags(self, juser): #...
from __future__ import print_function import os import rospkg import rospy from python_qt_binding import loadUi from python_qt_binding.QtWidgets import QWidget from rqt_gui_py.plugin import Plugin import kr_mav_manager.srv import std_srvs.srv class MavManagerUi(Plugin): def __init__(self, context): super(Mav...
from logging import basicConfig, getLogger, DEBUG from pprint import pprint logger = getLogger(__name__) OBJECT = 'DFW' MODULE = 'Services' def get_list(client, sectionId=None): """ """ if not sectionId: request = client.__getattr__(MODULE).ListSections() response, _ = request.result() ...
def perm(visit,arr,now=[]): if False not in visit: print(now) return for i in range(len(arr)): if not visit[i]: visit[i] = True perm(visit,arr,now+[arr[i]]) visit[i] = False perm([False,False,False],[1,2,3])
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import datetime class Migration(migrations.Migration): dependencies = [ ('cms', '0007_auto_20150525_1630'), ] operations = [ migrations.AddField( model_name='impression',...
# Create your views here. import facebook from django.contrib.auth.models import User from rest_framework import viewsets from rest_framework.decorators import list_route, detail_route from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.status import H...
#David Kartchner #March 24, 2016 import pandas as pd import numpy as np from sklearn import preprocessing from sklearn.ensemble import RandomForestClassifier from matplotlib import pyplot as plt data = pd.read_csv('train.csv') pd.set_option('expand_frame_repr', True) pd.set_option('max_columns',200) for i in data.se...
import Priors class Parameter(object): def __init__(self,name,initValue,minValue,maxValue,delta,**kwargs): self.name = str(name) self.value = initValue self.minValue = minValue self.maxValue = maxValue self.delta = delta se...
class counter: def __init__(self): self.tweetsAdded = 0 self.classifiedTweets = {"violentExtremism" : 0, "nonViolentExtremism" : 0, "radicalViolence" : 0, "nonRadicalViolence" : 0} self.trainedTweets = {"violentExtremism" : 0, "nonViolentExtremism" : 0, "radicalViolence" : 0, "nonRadicalViolence" : 0}
def len(s): count = 0 for char in s: count += 1 print('The total length of the string is: ', count) ustr = input() len(ustr)
# Generated by Django 2.2.4 on 2019-09-19 07:40 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('income', '0001_initial'), ] operations = [ migrations.AlterField( model_name='income', name='total', fie...
from django.db import models from django.db.models.deletion import CASCADE, ProtectedError, SET_NULL from user.models import User from product.models import Product # Create your models here. class Cart(models.Model): user = models.ForeignKey(User, on_delete=CASCADE) product = models.ForeignKey(Product, blank...
import cv2 as cv import numpy as np import serial import os import time #设置静态变量 这里没有用到 def f(): if not hasattr(f, 'x'): f.x = 0 print(f.x) f.x += 1 #亮度和对比度调节函数 a是当前亮度背书,g加上的对比度 def contrast_brigthless_image(src1, a, g): h, w, ch = src1.shape src2 = np.zeros([h, w, ch], src1....
#!/usr/bin/env python import sys, os from opentreetesting import test_http_json_method, config DOMAIN = config("host", "apihost") SUBMIT_URI = DOMAIN + "/v3/study/pg_10/tree/tree3.tre" data = {"tip_label": "ot:ottTaxonName"} r = test_http_json_method( SUBMIT_URI, "GET", data=data, expected_status=200, ...
species( label = 'C=C([O])C1[CH]C=CCC=C1(2240)', structure = SMILES('C=C([O])C1[CH]C=CCC=C1'), E0 = (226.409,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([2950,3100,1380,975,1025,1650,2750,2807.14,2864.29,2921.43,2978.57,3035.71,3092.86,3150,900,928.571,957.143,985.714,1014.29,1042.86,10...
#!/usr/bin/env python # encoding: utf-8 """ @author: dstch @license: (C) Copyright 2013-2019, Regulus Tech. @contact: dstch@163.com @file: Bert-base TF2.0 (minimalistic) III.py @time: 2019/12/18 8:57 @desc: fork from https://www.kaggle.com/khoongweihao/bert-base-tf2-0-minimalistic-iii """ """ Update 1 (Commit 7): ...
# import requests # import re # # def test(a, b): # for f in re.findall(r'<a href="(.*)">', requests.get(a).text): # if b in re.findall(r'<a href="(.*)">', requests.get(f).text): # return 'Yes' # return 'No' # # print(test(input(), input())) # print(requests.get(input()).text) # if __name_...
import numpy as np import torch import torch.nn.functional as F import torch.nn as nn import torch.optim as optim import nets train_pts = \ np.load('/Users/jonpvandermause/Research/CV/nlfe/nlfe/nn/train_pts.npy') train_labels = \ np.load('/Users/jonpvandermause/Research/CV/nlfe/nlfe/nn/train_labels.npy') test_...
''' Function: 简单的评论数据可视化 Author: Charles 微信公众号: Charles的皮卡丘 ''' import os import re import jieba import pickle from wordcloud import WordCloud '''词云''' def drawWordCloud(words, title, savepath='./results'): if not os.path.exists(savepath): os.mkdir(savepath) wc = WordCloud(font_path='simkai....
from collections import Counter import csv with open('height-weight.csv',newline='') as f: reader=csv.reader(f) file_data=list(reader) file_data.pop(0) new_data=[] for i in range(len(file_data)): n_num=file_data[i][1] new_data.append(float(n_num)) data=Counter(new_data) mode_data_fo...
import re def is_valid_email(email: str) -> bool: """Checks if a string is a valid email. Args: email: Possible email to be validated. Returns: True when `email` is a valid email, False otherwise. """ email_re = re.compile(r"^[^@]+@[^@$]+$") return email_re.m...
#--------order_sources IOS= "iOS" ANDROID= "Android" WEB= "Web" ORDER_SOURCE = [IOS, ANDROID, WEB] ORDER_SOURCE_CHOICES = [(a,a) for a in ORDER_SOURCE] #------------Order_status INCOMPLETE= "Incomplete" PLACED= "Placed" ON_HOLD= "On Hold" SHIPPED="Shipped" OUT_FOR_DELIVERY="Out for Delivery" DELIVERED="Order Deliver...
# from django.core.mail import send_mail import datetime as dt def year(request): """ Добавляет переменную с текущим годом. """ year = dt.datetime.now().year return { 'year': year } # send_mail( # 'Тема письма', # 'Текст письма.', # 'from@example.com', # Это пол...
# -*- coding: utf-8 -*- import time import unittest from selenium import webdriver class TestCnblogs(unittest.TestCase): def setUp(self): print u"自动化测试用例执行开始" #self.driver = webdriver.Firefox(executable_path="D:/ProgramFiles/Firefox/firefox.exe") #self.driver = webdriver.Chrome() se...
from utils import utils import matplotlib.pyplot as plt import termcolor path = 'input.txt' A, B, C, D, E, F, X, U, N, Y, T = utils.build_model(path) print(termcolor.colored(utils.stability(A), 'blue')) x_history, y_history = utils.calculate_model(A, B, C, D, E, F, X, U, N, Y, T, non_stationary=False) utils....
import matplotlib.pyplot as plt import numpy as np x = np.linspace(-1,100,50)#从(-1,100)均匀取50个点 y = 2 * x plt.figure plt.plot(x,y) plt.show() x1 = np.linspace(-1,1,50)#从(-1,1)均匀取50个点 y1 = 2 * x1 plt.figure plt.plot(x1,y1) plt.show()
# Generated by Django 2.1.7 on 2019-05-29 07:37 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='MMIM', fields=[ ('id', models.AutoField(aut...
def findSmilest(arr): smallest = arr[0] smallest_index = 0 for i in range(len(arr)): if arr[i] < smallest: smallest_index = i return smallest_index def selectionSort(arr): newArr = [] for i in range(len(arr)): smallest = findSmilest(arr) newArr.append(arr.po...
import os from chrono import Chrono from simu import make_simu_from_params from policies import BernoulliPolicy, NormalPolicy, SquashedGaussianPolicy, DiscretePolicy, PolicyWrapper, BetaPolicy from critics import VNetwork, QNetworkContinuous from arguments import get_args from visu.visu_critics import plot_critic from ...
import pickle import googlemaps as gmaps import googlemaps.geocoding as geocoding import dotenv dotenv.load() def get_geocode(client, city: str) -> tuple: data = geocoding.geocode(client, city) return data[0]['geometry']['location']['lng'], data[0]['geometry']['location']['lat'] def run(cities): try: ...
from libs.db_conn import _mysql_config import MySQLdb class Im(object): def __init__(self): self.db_master = _mysql_config["im"]["master"] pass def save_msg_to_db(self, msg): result = self.db_master.insert("im_message_copy", json_data=msg) return result def add_im_user_inf...
import pymysql conn = pymysql.connect(host='localhost', user='root',password ='root', db='test', charset='utf8', cursorclass=pymysql.cursors.DictCursor) c = conn.cursor() t =('ibm',) sql = 'select * from stocks where symbol = %s' c.execute(sql, t) print(c.fetchall()) # items = [ # ('2020-0...
from _collections import defaultdict import codecs import glob import json from multiprocessing import freeze_support, Manager import multiprocessing import os import urllib2 from pyreadline.logger import file_handler from create_seed_vectors import PATTERN_FILE from create_seed_vectors.create_seed import...
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import twython from twython import Twython from twython import TwythonError import pandas import time t = Twython(app_key='UA0nzn84w89guYmC51LRauSXP', #REPLACE 'APP_KEY' WITH YOUR APP KEY, ETC., IN THE NEXT 4 LINES app_secret='UPC7z...
# 임의의 수열이 주어졌을 때 스택을 이용해 그 수열을 만들 수 있는지 없는지, # 있다면 어떤 순서로 연산을 수행해야 하는지 계산하기 n = int(input()) # n개의 줄에 수열을 이루는 1이상 n이하의 정수가 주어진다 def stack_sequence(n): stack = [] output = [] # 출력값 cnt = 1 for i in range(n): # n개의 줄 num = int(input()) # 1이상 n이하의 정수 입력 while cnt <= num: ...
"""\ 1. Say hi In this mission you should write a function that introduce a person with a given parameters in attributes. Input: Two arguments. String and positive integer. Output: String. Example: say_hi("Alex", 32) == "Hi. My name is Alex and I'm 32 years old" ...