text
stringlengths
8
6.05M
import operator from bert_serving.client import BertClient import configparser import json import numpy as np def create_2_freq(): config = configparser.ConfigParser() config.read("paths.cfg") with open(config["paths"]["triple_string_cpnet_json"], "r", encoding="utf8") as f: triple_str_json = jso...
#!/usr/bin/python #qplot -x -3d -s 'set xlabel "x";set ylabel "y";set view equal xy' outcmaes_obj.dat w l outcmaes_res.dat ps 3 data/res000{0,1,2,3,5,6}.dat -showerr #TEST to use stored solutions and scores data import cma import numpy as np def fobj1(x,f_none=None): assert len(x)==2 #if (x[0]-0.5)**2+(x[1]+0.5)**...
import z3 from functools import * MODE_ACC = False # enum input for higher acc def portType(group, func): if group == 'Y' or group == 'CO' or (group == 'S' and (func == 'ADDF' or func == 'ADDH')): return 'output' return 'input' class Logic: """ rules: class1: ...
#!/usr/bin/python # -*- coding:utf-8 -*- # Author: Eason def str(var1,*vartuple): print var1 for var in vartuple: print var print "=" * 20 print "输出定义的变量:" print "=" * 20 str(10) print "=" * 20 print "输出所有未定义的变量:" print "=" * 20 str(20,30,40) print "=" * 20
# Import yfinance import yfinance as yf import pandas as pd data = yf.download("ABEV3.SA", start="2020-08-01", end="2020-08-30") print(type(data)) print(data) print(data['High']) print(data[['Low']]) print(data.iloc[1]) print(data.iloc[1][0]) tickers = {"F", "WFC", "GM"} for ticker in tickers: ticker_yahoo = y...
class Node: def __init__(self, data, next_node=None): self.data = data self.next = next_node def find_circle_head(head): seen_nodes = set() while head is not None: if head in seen_nodes: return head seen_nodes.add(head) head = head.next if __name__ == '_...
import requests # Importing requests url = "https://api.tellonym.me/accounts/forgotpassword" # Check Email Linked API URL headers = { "Host": "api.tellonym.me", "Content-Type": "application/json", "Accept": "application/json", "Connection": "keep-alive", "tellonym-client": "ios:2.65.0:488:14:iPhone13,3", "User...
import random import sys n=6 row=1 col=0 pos=0 col_s=0 f=0 d=0 roll_again = "yes" flag=[[0 for j in range(n)] for i in range(n)] def check( flag ): count=0 for i in range(n): count=0 for j in range(n): if(flag[i][j]==1): count=count+1 if(count==n): print ("The row %d was...
from flask import Flask, session, request, redirect, render_template import random app=Flask(__name__) app.secret_key='macbook' @app.route('/') def index(): return render_template('index.html') @app.route('/win') def win(): return render_template('win.html', win=session['win'], lose=session['lose'], tie=sessi...
from django.shortcuts import render, get_object_or_404, redirect, reverse import os from django.utils import timezone from .models import Feature, Comment from .forms import AddFeatureForm, AddFeatureCommentForm from django.conf import settings import stripe import datetime stripe.api_key = settings.STRIPE_SECRET_KEY....
from keras.initializers import RandomNormal from keras.models import Model from keras.models import Input from keras.layers import Conv2D, Conv2DTranspose, UpSampling2D from keras.layers import LeakyReLU from keras.layers import Activation from keras.layers import Concatenate from keras_contrib.layers.normalization.ins...
''' https://gist.github.com/Tofull/49fbb9f3661e376d2fe08c2e9d64320e ''' ## Modules # Elementary modules from math import radians, cos, sin, asin, sqrt import copy # Graph module import networkx # Specific modules import xml.sax # parse osm file from pathlib import Path # manage cached tiles def haversine(lon1, lat...
from datetime import datetime import sys f = sys.argv[1] node_map = {} with open('../all_knls.sinfo.nodes.map',"r") as fin: for line in fin: (node, platform) = line.rstrip().split('\t') node_map[node] = platform d1p=None d2p=None node=None start = None end = None counter = 0 nodes = {} with open...
#Queens attack 1d def queenAttack(board , qr , qc): n = len(board) obs = False count = 0 #right for i in range(qr + 1 , n): print('r: ' ,i) if board[i] == 0: count += 1 #board[i] = 'q' #left ...
import json from flask import Flask from flask import request from flask.helpers import make_response from flask.json import JSONDecoder, jsonify from torch.utils import data from BFT.utils import cuda_variable from flask_cors import CORS from BFT.handlers import DecoderPrefixHandler app = Flask(__name__) CORS(app) ""...
# Copyright 2019 Intel, 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 a...
"""Message View tests.""" # run these tests like: # # FLASK_ENV=production python -m unittest test_message_views.py import os from unittest import TestCase from models import db, connect_db, Message, User, Follows # BEFORE we import our app, let's set an environmental variable # to use a different database for ...
import os import string import sys import requests import json from xml.etree import ElementTree class cwatchAPI(object): def __init__(self,usr,passwd): self.sess = requests.session() self.url = 'https://www.fusionvm.com/rest/v2/api/' self.url2 = 'https://api.fusionvm.com/' self.us...
symb_rem = ['AABA','DJ30', 'HKG50', 'SGCG.DE','HKG50','ETO.L','SHPG','CELG','ECA','AKS','LK','UTX','AKRX','FTR', 'JCP','BRK.B','GNC','ASNA','CHK','SPN','OGZDL.RU','AGN','MYL','WUBA','SE.ST','HTZ','DF','XLM','TMK', 'CHINA50','NSDQ100','KVW.NV','AUS200','GEBN.ZU','CYBG.L','DLPH','WORKS','AMTD','ET...
import time n = list(range(1, 6))[::-1] def insertionSort(n): for i in range(1, len(n), 1): key = n[i] j = i - 1 while j >= 0 and key < n[j]: n[j+1] = n[j] j -= 1 n[j+1] = key print("ARRAY : {0}".format(n)) return n start = time.perf_counter(...
import json import argparse from abstraction.abstraction import AbstractionManager from dataset_creation.dataset_mining import DatasetMining from token_extraction.token_extraction import TokenExtraction from utils.settings import init_global def read_file(filepath): # read generic file try: with open(f...
for i in range(0, 10, 1): print(i) print "Cero!"
from pyhdf.SD import SD import hdf4 import scipy.io import numpy as np import formatNum as fN import re import pandas as pd import extract import update from collections import namedtuple header_file_aerosol = '../../projects/aerosol/products/MIL2ASAE/' header_data = '../../projects/aerosol/cache/data/' PixelData = n...
#!/usr/bin/env python # -*- coding: utf-8 -*- # ˅ from behavioral_patterns.interpreter.node import Node # ˄ class CommandList(Node): # ˅ # ˄ def __init__(self): self.__nodes = [] # ˅ pass # ˄ def parse(self, context): # ˅ # Write here to avoid circ...
import requests import app_config as app_config import json base_url = 'https://youtube.googleapis.com/youtube/v3/' channels_url = base_url + 'channels' playlist_url = base_url + 'playlistItems' search_url = base_url + 'search' videos_url = base_url + 'videos' ht = '%23' pipe = '%7C' verbose = True ...
import argparse import time import os import subprocess import cv2 as cv import numpy as np FLAGS = None VID = 'video' IMG = 'image' meanX = 103.939 meanY = 116.779 meanZ = 123.680 def nothing(v): print('hello ' + v) def predict_all(img, values, h, w): blob = cv.dnn.blobFromImage(img, 1.0, (w, h), (...
import warnings warnings.simplefilter("ignore", UserWarning) # Import the necessary python library modules import numpy as np from matplotlib import pyplot as plt from scipy.optimize import minimize import os import sys import pdb # Add my local path to the relevant modules list sys.path.append('/Users/Daniel/Github...
import os import copy import json import logging from typing import Optional, TypedDict, NewType from shorthand.types import ExecutablePath, FilePath, DirectoryPath, RelativeDirectoryPath class ShorthandFrontendConfig(TypedDict): view_history_limit: int map_tileserver_url: str class ShorthandConfig(TypedDic...
from . import views from django.conf.urls import url from django.urls import path, include app_name = "main" urlpatterns = [ url(r'^$',views.homepage, name="homepage"), url(r'^loan_type/$', views.loan_types, name='loantype'), url(r'^client/$',views.apply_loan, name="applyloan"), url(r'^settings/$',vie...
import math import numpy as np def batches(batch_size, features, labels): """ Create batches of features and labels :param batch_size: The batch size :param features: List of features :param labels: List of labels :return: Batches of (Features, Labels) """ assert len(features) == len(la...
import layer_creater as lc import neural_network_creater as nnc import numpy as np import tensorflow as tf #训练数据准备 x_data = np.linspace(-1, 1, 300)[:, np.newaxis] #(300, 1) noise = np.random.normal(0, 0.05, x_data.shape) y_data = np.square(x_data) - 0.5 + noise #定义数据节点 xs = tf.placeholder(tf.float32, [None, 1]) ys = ...
import Queue, threading, random, time, socket, os, struct class Attacks(threading.Thread): def __init__(self, attack_q, input_q, probe_1, probe_2, rate_q, application_mon_q, flag_q, http_treshold_q_rep): threading.Thread.__init__(self) # Required for thread class self.attack_Q = attack_q se...
#!/usr/bin/python3 import os import sys import numpy as np import matplotlib import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from scipy.io import wavfile from scipy import signal def D1(Y, Yhat): NormYhat = (Yhat / np.sqrt(np.sum(Yhat**2))) NormY = (Y / np.sqrt(np.sum(Y**2))) return...
from django.db import models from transaction.models import ChartOfAccount import datetime from django.contrib.auth.models import User from user.models import Company_info from inventory.models import Add_products class CompanyUser(models.Model): user_id = models.IntegerField() company_id = models.ForeignKey(C...
from django.core.management.base import BaseCommand, CommandError from django.core.exceptions import ObjectDoesNotExist from filmmap.models import Film, FilmLocation, FilmActor from decimal import * import re import csv from datetime import datetime class CSVParser(object): def __init__(self, filename): ...
import pytest import os import pandas as pd from ticclat.utils import chunk_df, read_json_lines, write_json_lines, \ json_line, iterate_wf, chunk_json_lines, read_ticcl_variants_file from . import data_dir def test_chunk_df_smaller_than_num(): data = pd.DataFrame({'number': range(5)}) i = 0 for c ...
__author__ = 'sidney'
class Solution: def fractionToDecimal(self, numerator, denominator): n, r = divmod(abs(numerator), abs(denominator)) sign = '-' if numerator*denominator < 0 else '' res = [sign + str(n), '.'] stack = [] while r not in stack: stack.append(r) n, r = divm...
from exceptions import Exception # An entity of 'model' with the unique 'field' already exists class FieldExistsError(Exception): def __init__(self, model, field): self.model = model self.field = field def json_dict(self): return {'field_exists_error': {'model': self.model, 'field': s...
"""Maze generation and path finding Emir Farid MOHD RODZI """ from random import shuffle, randrange class Cell: """ Cell objects represent a single maze location with up-to 4 walls. The .N, .E, .S, .W attributes represent the walls in the North, East, South and West directions. If the attribute is T...
# -*- coding: utf-8 -*- # This file as well as the whole tsfresh package are licenced under the MIT licence (see the LICENCE.txt) # Maximilian Christ (maximilianchrist.com), Blue Yonder Gmbh, 2016 import warnings from builtins import range from unittest import TestCase import numpy as np import numpy.testing as npt i...
import numpy as np from scipy.sparse import coo_matrix from scipy.signal import convolve2d, convolve, gaussian def fastkde(x, y, gridsize=(200, 200), extents=None, nocorrelation=False, weights=None, adjust=1.): """ A fft-based Gaussian kernel density estimate (KDE) for computing the KDE on a r...
def calcslope(A,B,C,D,E,F,G,H): try: s=(D-B)/(C-A) s2=(H-F)/(G-E) y1=B-(s*A) y2=F-(s2*E) x=(y2-y1)/(s-s2) y3=s*x+y1 return("The point of intersection is ("+str(round(x,3))+", "+str(round(y3,3))+").") except(ZeroDivisionError): return("Error 001: Ve...
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2016-09-14 13:48 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0025_auto_20160908_1035'), ] operations = [ migrations.AlterField( ...
import os import numpy as np import ipywidgets as widgets import pandas as pd import qgrid from natsort import natsorted from IPython.display import display import plotly import plotly.graph_objs as go import mod_common_utils def figures_in_path(my_path, figures=None, ext='.jpg'): if figures is None: f...
import requests import json import time import math from boto.s3.connection import S3Connection from boto.s3.key import Key tournament_name = 'The Masters' year = 2015 # get tournament schedule from AWS c = S3Connection('AKIAIQQ36BOSTXH3YEBA','cXNBbLttQnB9NB3wiEzOWLF13Xw8jKujvoFxmv3L') b = c.get_bucket(...
from wargame.attackoftheorcs import AttackOfTheOrcs # Main类 if __name__ == '__main__': game = AttackOfTheOrcs() # 开始游戏 game.play()
import urllib import json from bs4 import BeautifulSoup from flask import Flask statDims = { "Blocks Mined": "blocks_mined", "Time Between Blocks": "time_between_blocks", "Bitcoins Mined": "bitcoins_mined", "Total Transaction Fees": "total_transaction_fees", "No. of Transactions": "num_transactions", "Total Output Vol...
#web scrapping using html parser method from bs4 import BeautifulSoup as bs import requests link='https://www.flipkart.com/portronics-harmonics-216-bluetooth-headset/product-reviews/itm56304ccc8e996?pid=ACCFHHWUEXCFBMST&lid=LSTACCFHHWUEXCFBMSTGHSLHL&marketplace=FLIPKART' page=requests.get(link) page page.cont...
#!/usr/bin/python import Tkinter as tk import ImageTk import bisect import numpy as np from PIL import Image import random import rospy import tf import math import Queue import itertools import colorsys from threading import Timer from nav_msgs.msg import Odometry from sensor_msgs.msg import LaserScan from p2os_msgs...
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals import os import time import pytest from selenium import webdriver @pytest.fixture(scope='module') def webfront(agent): return agent.context().lookup('webfront') @pytest.fixture(scope='module') def server...
#-*- coding:utf-8 -*- from django.db import models from django.contrib.auth.models import User from shopback.base.fields import BigIntegerAutoField ROLE_CHOICES = ( ('seller',u'卖家'), ('buyer',u'买家') ) RESULT_CHOICES = ( ('good',u'好评'), ('...
import os import numpy as np import json import struct import open3d # data_set_file = os.getcwd()+'\\data_set\\lidar_semantic_bboxes\\' def read_file(file_name=os.getcwd()+'\\data_set\\lidar_semantic_bboxes\\'): # 输入为数据集绝对路径 # 输出为.npz文件和.json文件位置 npz_dir = [] _3D_label_dir = [] dirs ...
from speedycloud.products.cloud_server import CloudServerAPI api = CloudServerAPI('F8592B402380432895EA8C12BEBF2222', '0eb7bc8c4aa154ce6abb799e4149417ca9b90a5eeb82789d2326082a5b5d2222') # print api.get_available_zone() # print api.get_support_isps('SPC-HK-2-A') # print api.get_os_images('SPC-HK-2-A') # print api.list...
#-*- coding: utf-8 -*- import wx import win32api import sys, os import logging from FileListTable import * from APDFTool import APDFTool APP_TITLE = u'PDF Document Merge Tool' APP_ICON = 'pdf_maker.ico' class mainFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, APP_TIT...
# Enthought library imports. from traits.api import HasTraits, Instance, Vetoable # Local imports. from task_window import TaskWindow class TaskWindowEvent(HasTraits): """ A task window lifecycle event. """ # The window that the event occurred on. window = Instance(TaskWindow) class VetoableTaskWi...
# 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: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
import face_API as face import pymysql as pl import pre_process as pp import json infodict = {} def entercourse(coursename):# Tested db = pl.connect(host="rm-m5ec899sxqwx2rc9tgo.mysql.rds.aliyuncs.com", user="root", password="Aa123456", db="classroom", charset='utf8') cur = db.cursor() fi...
def checkInitialisationMC(solverWrapperDictionary,positionMaxNumberIterationsCriterion=None,tolerances=None): checkInitialisationSolverWrapper(solverWrapperDictionary) if ("asynchronous" in solverWrapperDictionary): if (solverWrapperDictionary["asynchronous"] is True): checkMaxNumberIteratio...
import sys import pygame from pygame.sprite import Sprite, Group def fire_bullet(screen, bullets, rocket): """Fire a bullet if limit not reached yet.""" # Create a new bullet and add it to the bullets group if len(bullets) < 4: new_bullet = Bullet(screen, rocket) bullets.add(new_bullet) ...
# Reverse Integer # Given a 32-bit signed integer, reverse digits of an integer. # # Example 1: # # Input: 123 # Output: 321 # Example 2: # # Input: -123 # Output: -321 # Example 3: # # Input: 120 # Output: 21 # Note: # Assume we are dealing with an environment which could only hold integers within the 32-bit signed...
import requests import random # location_types = [ # "Blue", # "AllGender", # "Water", # ] type_dict = { "Blue": "Blue Light", "AllGender": "Bathroom", "Water": "Water", } def get_img_url(ltype): img_idx = random.randint(0, 2) url_dict = { "Blue": f"https:/...
# coding=utf-8 import os import sys import time import json import gevent import logging import requests from utils import save_items, get_items_from_file, add_item_fields, log_init, save_items_with_json reload(sys) sys.setdefaultencoding('utf8') # 速码(www.eobzz.com) # 账号/密码: hbbhbb(rfM#!EzZU%!3s7*kxbTy) # 平台接口前缀: 'h...
#047: Expected Number of Restriction Sites #http://rosalind.info/problems/eval/ #Given: A positive integer n (n=1,000,000), a DNA string s of even length at most 10, and an array A of length at most 20, containing numbers between 0 and 1. n = 10 s = 'AG' A = [0.25, 0.563, 0.422] #If parsing from file: #f = open('ro...
""" 문제 N개의 숫자가 공백 없이 쓰여있다. 이 숫자를 모두 합해서 출력하는 프로그램을 작성하시오. 입력 첫째 줄에 숫자의 개수 N (1 ≤ N ≤ 100)이 주어진다. 둘째 줄에 숫자 N개가 공백없이 주어진다. 출력 입력으로 주어진 숫자 N개의 합을 출력한다. 예제 입력 1 1 1 예제 출력 1 1 예제 입력 2 5 54321 예제 출력 2 15 """ a=int(input()) N=input() def sum_c(a): L=[] result=0 for i in range(0, len(a)): L.append(a[i])...
import logging import sys from io import StringIO logger = logging.getLogger('test') logger.setLevel(logging.DEBUG) buffer_stream = StringIO() buffer_handler = logging.StreamHandler(stream=buffer_stream) console_handler = logging.StreamHandler(stream=sys.stdout) buffer_handler.setLevel(logging.DEBUG) console_handler...
import json from flask import request from requirementmanager.app import app from requirementmanager.mongodb import ( requirement_collection, archive_requirement_collection ) from requirementmanager.dao.requirement_list import RequirementListMongoDBDao from requirementmanager.dao.archive import ArchiveRequirement...
import aiml # Create the kernel and learn AIML files mybot=aiml.Kernel() #mybot.setbotpredicate("name","Armin") mybot.learn('AIMLData.aiml') mybot.respond("SK1 BotMaster") mybot.respond("SK2 Student") mybot.respond("SK3 Floki") mybot.respond("SK4 Robot") mybot.respond("SK5 Egypt") mybot.respond("SK6 Male") mybot.resp...
import pandas as pd import json from boto.s3.connection import S3Connection from boto.s3.key import Key year = 2015 tournament = 'Valero Texas Open' # create connection to bucket c = S3Connection('AKIAIQQ36BOSTXH3YEBA','cXNBbLttQnB9NB3wiEzOWLF13Xw8jKujvoFxmv3L') # create connection to bucket b = ...
from core.renderers import CoreJSONRenderer class TopicRenderer(CoreJSONRenderer): object_label = 'topic' pagination_object_label = 'topics' pagination_count_label = 'topicsCount' class PreferenceRenderer(CoreJSONRenderer): object_label = 'preference' pagination_object_label = 'preferences' p...
# while-loop 循环:一直执行代码,知道判断条件为 False 才停止 # 可以用来做循环任务 # 使用建议 # 1.尽量少用 while-loop ,大部分时候使用 for-loop 是更好的选择 # 2.重复检查 while 语句, 确定测试布尔表达式 最终会变成 False # 3.如果不确定,就在 while-loop 的结尾打印测试值, 看看结果 i = 0 numbers = [] while i < 6: print "At the top i is %d" % i numbers.append(i) i += 1 print "Numbers now: ", numb...
#!/usr/bin/env python #-*-coding:utf-8-*- ''' In England the currency is made up of pound, £, and pence, p, and there are eight coins in general circulation: 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p). It is possible to make £2 in the following way: 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p How many differen...
from django.urls import path from .views import (dashboard, team_members, profile, create_team, leave_team, membership_request, cancel_request, accept_request, ...
from detect import YOLO from PIL import Image import imutils import cv2 import os yolo = YOLO() files = os.listdir('./test/') for file in files: if file.endswith('jpg') or file.endswith('bmp'): image_path = './test/' + file image = cv2.imread(image_path) boxes = yolo.detect_image(Image.op...
__author__ = 'Stuart' from flask import jsonify, request, g, abort, url_for, current_app from .. import db from ..models import Post, Permission from . import api from .decorators import permission_required from .errors import forbidden @api.route('/posts/') def get_posts(): """ Contains data items in a page,...
from datetime import datetime from mongoengine import * from db.config import _MongoengineConnect from db.sentences.sentence import Sentences connect(_MongoengineConnect) class Comments(Document): belongsto_sentence = ReferenceField((Sentences))#,dbref=True content = StringField(max_length=50) love = ...
""" A simple guess-that-number game. Players take turns guessing a secret number between lower and upper (normally 0 and 100). After a guess, all players are informed of the guess as well as if the secret number was lower or higher. The game ends when some player guesses the secret number correctly. That player is t...
#from .fitting import circuit_fit, computeCircuit, calculateCircuitLength #from .plotting import plot_nyquist import matplotlib.pyplot as plt import numpy as np ### to find confidence intervals for fit parameters: # SE(Pi) = sqrt[(SS/DF) * conv(i,i)] # Pi : ith adjustable parameter # SS: sum of squarewd residuals # DF...
import mmh3 import sys def add_one_to_each(item, queue, big_list): for i in range(0, len(item)): item[i] += 1 queue.append(list(item)) big_list.append(list(item)) item[i] -= 1 def generate_variations(message, m_list, num_variations): split_list = message.split() queue = [...
import select import socket from threading import Thread from authenticate import Authenticate from connection import Connection from connection_state import ConnectionState from connections import Connections from const import Consts from protocol import ProtoLogin, ProtoBroadcast from user import User from users imp...
#!/usr/bin/env python # coding: utf-8 # In[2]: import struct import socket import codecs import time import matplotlib.pyplot as plt import pylab import random import numpy as np import sys import csv import numpy as np import matplotlib.pyplot as plt import matplotlib import math import serial # In[433]: def ct...
#!/usr/bin/env python ''' Count the number of occurrences in a list ''' import numpy as np def count(sequence, item): total = 0 for i in range(len(sequence)): if sequence[i] == item: total += 1 return total alist = [np.random.randint(0,10) for _ in range(25)] print(count(alist,alist...
def get_num_ecgs_with_feature(json_data, binary_feature_name): """Смотрим, у скольки пациентов датасета в разделе докторсокого стуктурированного диагноза (т.е. в "StructuredDiagnosisDoc") находится True """ counter = 0 for case_id in json_data.keys(): if(json_data[case_id]["StructuredDiagno...
from flask import Blueprint, render_template, request, session, url_for from werkzeug.utils import redirect import src.models.users.decorators as decorators from src.models.sked.sked import Sked sked_blueprint = Blueprint('skeds', __name__) @sked_blueprint.route('/new', methods=['GET','POST']) @decorators.requires_l...
#!/usr/bin/python import math def print_map_to_file(d_grid, filename): with open(filename, "w+") as grid_file: for row in reversed(d_grid): for cell in row: grid_file.write("1") if cell else grid_file.write("0") grid_file.write("\n") def create_occupancy_grid(my_...
from app import db from app.authenticate import generate_hash,check_passwd from app.auxiliar import AutoAttributes class Cadastro(db.Model,AutoAttributes): __tablename__ = 'cadastro_usuario' id_cadastro = db.Column(db.Integer,primary_key = True) senha = db.Column(db.Text, nullable=False) usuario_id = d...
#!/usr/bin/env python # Funtion: # Filename: import select, socket, queue class Slectors_server(object): def __init__(self, HOST): self.server = socket.socket() self.server.bind(HOST) self.server.listen(1000) self.server.setblocking(False) def push(self, Recv_dict): ...
# @Title: 从上到下打印二叉树 III (从上到下打印二叉树 III LCOF) # @Author: 2464512446@qq.com # @Date: 2020-06-28 17:17:15 # @Runtime: 40 ms # @Memory: 13.8 MB # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution:...
# # u n c o m m e n t . p y # # javascript comments, both /* ... */ and // to eol # import sys, re prog = list(sys.stdin.read()) + [None,None,None] x = 0 while prog[x] != None : #print "top of loop:", x, prog[x] if prog[x]=='/' and prog[x+1]=='/' : while prog[x] != '\n' : if prog[x] ==...
import requests #requests 라이브러리 가져오기 from bs4 import BeautifulSoup #크롤링을 쉽게 해주는 라이브러리 from pprint import pprint from pymongo import MongoClient # pymongo를 임포트 하기 client = MongoClient('localhost', 27017) # mongoDB는 27017 포트로 돌아갑니다. db = client.dbsparta # 'dbsparta'라는 이름의 db를 만듭니다. # 타겟 u...
import numpy as np from matplotlib import pyplot from scipy.misc import toimage import json import keras from keras.datasets import cifar10 from keras.utils import np_utils from keras.optimizers import SGD from keras.regularizers import l2, activity_l2 from keras.layers.normalization import BatchNormalization from ke...
import requests requests.packages.urllib3.disable_warnings() import sys # from bs4 import BeautifulSoup from decimal import Decimal # import json # import lxml import threading import time import smtplib from email.mime.text import MIMEText from email.header import Header # 第三方 SMTP 服务 mail_host="smtp.163.com" #设置服务器...
import tensorflow as tf import numpy as np from tensorflow.keras import layers import matplotlib.pyplot as plt import time import TTT board = TTT.Board(3); board.place_piece(1, 1, 1); board.place_piece(1, 0, 1); board.place_piece(1, 2, 1); if(1 != board.has_won()): print("BOARD WIN ERROR 1") board.remove_piece(1...
#!/usr/bin/env python3 # encoding: utf-8 """ selection_sort.py Created by Jakub Konka on 2011-11-01. Copyright (c) 2011 University of Strathclyde. All rights reserved. """ import sys import random as rnd def selection_sort(array): '''This function implements the standard version of the selection sort algorithm. ...
def sum(num): sum = 0 i = 0 while i <= num: sum = sum + i i = i + 1 print(sum) sum(4)
if __name__ == "__main__": n = int(input()) for i in range(n): word = list(input()) guess = list(input()) M = ["G" if w == b else "B" for w, b in zip(word, guess)] print("".join(M))
''' Extraire le dosage La forme galenique Le volume (nb de gelules) Calculer l'equivalent traitement ''' import pandas as pd import requests import re url = "https://www.open-medicaments.fr/api/v1/medicaments?limit=100&query=paracetamol" jsonData = requests.get(url).json() #ICS = [f'https://www.open-medicaments.fr...
""" 一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。 现在考虑网格中有障碍物。那么从左上角到右下角将会有多少条不同的路径? 网格中的障碍物和空位置分别用 1 和 0 来表示。 示例 1: 输入:obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]] 输出:2 解释: 3x3 网格的正中间有一个障碍物。 从左上角到右下角一共有 2 条不同的路径: 1. 向右 -> 向右 -> 向下 -> 向下 2. 向下 -> 向下 -> 向右 -> 向右 示例 2:...
from Q = 10**9+7 N, M = map( int, input().split()) A = list( map( int, input().split())) B = list( map( int, input().split())) G = [(0,0)]*N R = [(0,0)]*M for i, m in enumerate(A): G[i] = (m,i) for j, m in enumerate(B): R[j] = (m,j) G.sort() R.sort() ans = 1 A.sort() B.sort() for i in range(N): if A[i] < M...
from PyQt4 import QtGui from TimePad import Ui_Dialog import ShiftPopUp class TimePadPopUp(QtGui.QDialog): a = float() # Total hours counter variable #sender = str() def __init__(self, StAM, FinAM, BrkAM, StPM, FinPM, BrkPM): super(TimePadPopUp, self).__init__() QtGui.QWidget.__init__(se...