text
stringlengths
38
1.54M
from collections import defaultdict import pandas as pd from Bio import SeqIO files = ["result/alignment_traD.fas", "result/alignment_traN.fas"] def main(files, result_path): result = defaultdict(lambda: defaultdict(str)) for file in files: for seq_record in SeqIO.parse(file, "fasta"): r...
from django.shortcuts import get_object_or_404 from rest_framework.response import Response # JSON 응답 생성기 from rest_framework.decorators import api_view # require_methods 와 비슷 from .models import Todo from .serializers import TodoSerializer # @api_view(['GET']) # def todo_list(request): # serializer = TodoSerial...
import pytest from homework.homework11.hw1 import * def test_meta_parameters(): assert ColorsEnum.RED == "RED" assert SizesEnum.XL == "XL"
from fabricasqlcnx import Fabricacnx import os __author__ = 'Gabriel Lopes 22/09/15' class Fabricag(Fabricacnx): def __init__(self): Fabricacnx.__init__(self) self.resul_ok = [] self.resul_erro = [] self.printa = None def gravaok(self, grava): for i in self.resul_ok: ...
import pandas as pd import numpy as np data = pd.read_csv('2016-2018.csv') # subset data to fit to table attributes in cashflow table data = data[['Team','League','Year']] data = data.rename(columns = {'Team':'club', 'League':'league', 'Year':'year'}) #clean year column data['year'] = pd.to_numeric(data['year'], d...
string = input() alphabets = digits = special = 0 space=0 for i in range(len(string)): if(string[i].isalpha()): alphabets = alphabets + 1 elif(string[i].isdigit()): digits = digits + 1 elif(string[i]==' '): space=space+1 else: special = special + 1 print(special)
from django.db import models class Movie(models.Model): name = models.CharField(max_length=100, verbose_name='نام') director = models.CharField(max_length=50, verbose_name='کارگردان') year = models.IntegerField(verbose_name='سال تولید') length = models.IntegerField(verbose_name='زمان فیلم') descre...
# package com.gwittit.client.facebook.entities import java from java import * from com.google.gwt.core.client.JavaScriptObject import JavaScriptObject class User(JavaScriptObject): """ Facebook User, basic info. @author olamar72 """ @java.init def __init__(self, *a, **kw): ...
""" Script needs nine parameters to run: 1. Movie poster search URL 2. Movie poster URL 3. Database connection string 4. Database name 5. AWS S3 access key 6. AWS S3 secret key 7. AWS S3 bucket name 8. AWS S3 directory name 9. AWS S3 region """ from pymongo import MongoClient from datetime import datetime import boto3...
#!/usr/bin/env python import time import math import numpy as np from minnow_low_level_control.HeadingControl import * from minnow_low_level_control.SurgeSpeedControl import * class control_system_manager: # This is for standalone troubleshooting of the python code --------------------- desired_speed = 0.0 ...
# -*- coding: utf-8 -*- import re import string import collections def cleanSentence(sentence): sentence = sentence.split(' ') sentence = [word.strip(string.punctuation + string.whitespace) for word in sentence] sentence = [word for word in sentence if len(word) > 1 or (word.lower() == 'a' or word.lower()...
import boto3 from rekognition_image import RekognitionImage class ObjectDetector: """ Represents one Amazon rekognition object detection call and the response of it. Raises botocore.exceptions.ClientError if API call to Rekognition fails. """ def __init__(self, payload, img_name): ...
from .base import * ALLOWED_HOSTS = ['*'] MIDDLEWARE.insert(0, 'config.log.LogMiddleware') CONTENTS_DIR = os.path.join(BASE_DIR.parent, 'django-blog-contents') DATABASES['default']['NAME'] = os.path.join(CONTENTS_DIR, 'db.sqlite3') TEMPLATES[0]['DIRS'] += [os.path.join(CONTENTS_DIR, 'templates')] STATIC_ROOT = os...
# 단방향 연결 리스트(singly linked list)가 주어지면 총 합이 0으로 되는 연결된 노드들을 뺀 뒤 남은 노드의 값을 프린트 하시오. def check(arr): for n in arr: if n < 0: return False return True def solution(linkedList): temp = [] cnt = len(linkedList) + 1 if check(linkedList): return linkedList while ...
from flask import Flask # importing flask from flask_sqlalchemy import SQLAlchemy # helps to use the database as Objects from flask_bcrypt import Bcrypt # for hashing the passwords from flask_login import LoginManager #This is an in-built thing for flask, helps to manage the logining in and out of users from flask_mai...
from collections import deque import copy #<--------------------어려웡-------------------> #노드의 개수 입력받기 v = int(input()) #모든 노드에 대한 진입차수는 0으로 초기화 indegree = [0] * (v+1) #각 노드에 연결된 간선정보를 담기 위한 연결 리스트 (그래프) 초기화 graph = [[] for i in range(v+1)] #각 강의 시간을 0으로 초기화 #가중치를 넣어주기위해 만든다 time = [0] * (v+1) #방향 그래프의 모든 간선정보를 입력받...
from django.core.serializers import json from django.http import HttpResponse from django.shortcuts import render_to_response, RequestContext # Create your views here. from match_service.models import * def match_page(request): context = {} if request.method == 'POST': return render_to_response( ...
# Generated by Django 3.0.8 on 2020-10-11 11:47 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('dashboard', '0004_auto_20201011_0145'), ] operations = [ migrations.CreateModel( name='Result', fields=[ ...
import sys # sys.stdin = open("input.txt", "rt") ''' K번째 큰 수 현수는 1부터 100사이의 자연수가 적힌 N장의 카드를 가지고 있습니다. 같은 숫자의 카드가 여러장 있을 수 있습니다. 현수는 이 중 3장을 뽑아 각 카드에 적힌 수를 합한 값을 기록하려 고 합니다. 3장을 뽑을 수 있는 모든 경우를 기록합니다. 기록한 값 중 K번째로 큰 수를 출력 하는 프로그램을 작성하세요. 만약 큰 수부터 만들어진 수가 25 25 23 23 22 20 19......이고 K값이 3이라면 K번째 큰 값 은 22입니다. ▣ 입력설명 첫 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2017-12-28 16:28:50 # @Author : Your Name (you@example.org) # @Link : http://example.org # @Version : $Id$ import os,sys import json import timetool #当前对象主要为对k线数据分类的神经网络对象,包括数据分类网络训练,和网络保存使用 class KlineNNTool(object): """docstring for KlineNNTool""...
class TripletLoss(nn.Module): def __init__(self, margin=.2, negative='max'): super(TripletLoss, self).__init__() self.margin = margin self.negative = negative def forward(self, anchor, positive): dists = torch.cdist(anchor, positive) p_dists = torch.diag(dists) ...
import peewee, peewee_async from ..config.config import DB_CONFIG from ..common.exceptions import PageNotFound database = peewee_async.PostgresqlDatabase(**DB_CONFIG) class ContentBlock(peewee.Model): name = peewee.CharField(max_length=64) slug = peewee.CharField(max_length=16) video_link = peewee.CharF...
import business_rules from business_rules import run_all, export_rule_data from business_rules.variables import * from business_rules.actions import * from business_rules.fields import * from tngsdk.validation.util import read_descriptor_file from tngsdk.validation import event from tngsdk.validation.storage import Des...
c = [0.8916583583 ,0.9364599092 ,0.9418026692 ,0.9660107754 ,0.9735619037 ,0.9752730086 ,0.9795233774 ,0.9736945491 ,0.983412122 ,0.8847568897 ,0.937049294 ,0.9556460673 ,0.9521823306 ,0.9457192893 ,0.9755469101 ,0.9781225838 ,0.9804915898 ,0.7425709229 ,0.885471973 ,0.8549843111 ,0.9540545879 ,0.9638071451 ,0.9549...
import numpy as np import os import matplotlib.pyplot as plt import warnings import pickle from collections import defaultdict from nltk import pos_tag, word_tokenize warnings.simplefilter("ignore") def dd(): return defaultdict(int) def get_actions(): with open('./Data/vocab.pkl','rb') as f: actions ...
from collections import defaultdict from sugarrush.solver import SugarRush from garageofcode.common.utils import flatten_simple N = 3 def get_state(solver): # one-hot encoding X = [[[solver.var() for _ in range(N**2)] for _ in range(N)] for _ in range(N)] ...
from skmultiflow.core import BaseSKMObject, ClassifierMixin from skmultiflow.utils import get_dimensions from collections import deque import numpy as np class OracleClassifier(BaseSKMObject, ClassifierMixin): """Oracle recommender for testing purposes. Parameters ---------- stream: Stream Th...
import pickle import os def mutex_process(filename): if os.path.exists(filename): return False filemutex = filename+".mutex" try: f = open(filemutex, "x") f.close() return True except FileExistsError: return False def mutex_save(obj, filename): filemutex =...
import re from functools import reduce import nltk import spacy class Preprocessor(object): """ Cleans, removes stopwords and tokenizes lines """ def __init__(self): # Stopwords nltk.download('stopwords', quiet=True, raise_on_error=True) # Sentence Tokenizer nltk.down...
from worker import WorkerThread, Task from scheduler import SchedulerThread from time import sleep class WorkerPool(object): """ maintain asynchronous task distrubution over group ow working threads """ #time to sleep in scheduler when all workers are busy:bsy DEFAULT_TICK = 0.01 DEFAULT_WO...
from typing import List class Solution: def canPartition(self, nums: List[int]) -> bool: tot = sum(nums) if tot & 1: # odd number return False capacity = tot // 2 N = len(nums) dp = [False for j in range(capacity + 1)] dp[0] = True for i in rang...
#import matplotlib.pyplot as plt #import matplotlib.gridspec as gridspec from scipy.spatial.distance import * #import scipy.cluster.hierarchy as sch import numpy as np #from scipy.cluster.hierarchy import linkage, dendrogram import scipy.stats import sys #from plot_pearsons_heatmap_hclust import * # generated the cha...
# Gauss Jordan Elimination # Algorithm to solve linear equations of the kind A * x = b, where A is the matrix, and b is solutions vector # This algorithm was computed using partial pivoting - can be created without pivoting (usually not customary for these # calculations) by deleting the block of code used to swap the ...
import json # parameters filename = '/home/pi/pibs_client/system.json' # functions def getMacAddress(): import netifaces # find the network interfaces available ifaces = netifaces.interfaces() # preference is given to ethernet cord if 'eth0' in ifaces: info = netifaces.ifaddresses('eth0'...
import parse import os def same_params(params1, params2): list1 = params1.split() list2 = params2.split() if len(list2) == len(list1): for idx, val in enumerate(list1): if list2[idx] != val: return False else: return False return True def compare_t...
import networkx as nx def make(name): if name=='eight': G=nx.Graph() # add nodes and edges to the graph G.add_edge(0,1, bw=3, lat=1) G.add_edge(0,2, bw=3, lat=1) G.add_edge(1,3, bw=3, lat=0.4) G.add_edge(2,3, bw=3, lat=1) G.add_edge(3,4, bw=3, lat=1) G.add_edge(3,5, bw=3, lat=0.2) G.add_edge(4,6, ...
# -*- coding: utf-8 -*- """ DON'T TOUCH THIS CLASS Base Class for AI logic. Contains functionality to play a game of battleship. You may modify the two child classes which inherit from this one Created on Sat Mar 21 11:48:51 2020 @author: Kyle """ import numpy as np class AIPlayer: #initializati...
from copy import deepcopy from django import forms from django.contrib import admin from mezzanine.pages import admin as pages_admin from .models import CategoryLink CATEGORY_LINK_FIEDSETS = deepcopy(pages_admin.PageAdmin.fieldsets) CATEGORY_LINK_FIEDSETS[0][1]['fields'].insert(1, 'blog_category') class CategoryLi...
# Copyright (C) 2013-2015 Computer Sciences Corporation # # 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...
# -*- coding: utf-8 -*- """ """ import os, matplotlib.pyplot as plt, numpy as np class PlotGraph: def getBarPlot(self,stockCat, finalList, col, numFeat, folderPath): my_xticks = [item['stock'] for item in finalList] x = np.array([i+1 for i in range(len(my_xticks))]) ...
def bubble_sort(alist): """冒泡排序""" n = len(alist) for j in range(n-1): #外层循环控制走几次,j表示第几次走这个过程,一共走n-1次 count = 0 for i in range(0,n-1-j): #内层循环控制从头走到尾 #构造一个游标i,表示列表的下标 #range()左闭右开 #一共n个元素,下标从0-(n-1),游标到n-2的位置停下,但因为range()是左闭右开,所以range(0...
# coding:utf-8 from flask import Flask, render_template from sqlalchemy import create_engine, MetaData, Table from sqlalchemy.orm import sessionmaker app = Flask(__name__) # 连接数据库 engine = create_engine('sqlite:///smzdm.db') metadata = MetaData(bind=engine) Session = sessionmaker(bind=engine) Item = Table('items', me...
# 标准库 import os # 第三方库 from flask import ( Flask, request, render_template, send_from_directory, redirect, url_for, abort ) from werkzeug.datastructures import FileStorage # 自己写的其他模块 from helper import random_filename, ensure_folder ROOT = os.path.dirname(os.path.abspath(__file__)) app = Flask(__name__) app.u...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals """ Unittests for zimsoap.zobjects """ import unittest from six import text_type, binary_type import zimsoap.utils from zimsoap.zobjects import ( Account, Domain, Identity, Mailbox, Signature, ZObject) from . import samples ...
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy class BossItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() # 定义数据结构 job_name = scrapy.Field() ...
class Card(): """Class handles cards in a deck Attributes: suit -- The possible suits in a deck of cards value -- The possible values in a deck of cards """ suits = [('Heart',1), ('Diamond',2), ('Spade',3), ('Club',4)] values = [('Ace',11),('Two',2),('Three',3),('Four...
# open function is built into python # for more information on built in functions go to http://docs.python.org/lib/built-in-functions.html # Use the file name mbox-short.txt as the file name fname = raw_input("Enter file name: ") fh = open(fname) qty = 0 val = 0 for line in fh: if not line.startswith("X-DSPAM-Conf...
### Group the People Given the Group Size They Belong To - Solution class Solution: def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]: id_and_person = collections.defaultdict(list) for person, id_ in enumerate(groupSizes): id_and_person[id_].append(person) final...
from uuid import uuid4 class Annotation(object): """ A named entity object that has been annotated on a document. Note: The attributes of this class assume a plain text representation of the document, after normalization. For example, `text` will be in lower case, if t...
#!/usr/bin/env pybricks-micropython from pybricks.hubs import EV3Brick from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor, InfraredSensor, UltrasonicSensor, GyroSensor) from pybricks.parameters import Port, Stop, Direction, Button, Color from pybricks.tools import wait, S...
from setuptools._distutils.errors import CompileError as BaseCompileError class MissingGXX(Exception): """ This error is raised when we try to generate c code, but g++ is not available. """ class CompileError(BaseCompileError): """This custom `Exception` prints compilation errors with their ori...
from django.db import models from tracker.models import Daily, Food, Activity, Medication, Supplement import datetime def CreateDaily(energy): d = Daily(date = datetime.datetime.now(), energylevel = energy) d.save()
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse class MybankCreditLoantradeGuarletterApplyQueryResponse(AlipayResponse): def __init__(self): super(MybankCreditLoantradeGuarletterApplyQueryResponse, self).__init__() self....
import pandas as pd import matplotlib.pyplot as plt from io import BytesIO import os file=input('FilePath: ') piv_index=input('Write Your Index: ').split() piv_data=input('Columns to Graph: ').split() extension = os.path.splitext(file)[1] filename = os.path.splitext(file)[0] pth=os.path.dirname(file) newfile=os.path...
import time import numpy as np from scipy.sparse import linalg from scipy.sparse.linalg import spsolve def solve_cgs(k, f, m=None, tol=1e-5): """Solves a linear system of equations (Ku = f) using the CGS iterative method. :param k: N x N matrix of the linear system :type k: :class:`scipy.sparse.csc_matri...
# -*- coding: utf-8 -*- ''' @Author: Lingyu @Date: 2021-10-19 @Description: ''' from .logger import logger,getLogger from .makeresponse import make_response from . import hook def init_app(app): hook.init_app(app)
#!/usr/bin/env python # coding=utf-8 # aeneas is a Python/C library and a set of tools # to automagically synchronize audio and text (aka forced alignment) # # Copyright (C) 2012-2013, Alberto Pettarin (www.albertopettarin.it) # Copyright (C) 2013-2015, ReadBeyond Srl (www.readbeyond.it) # Copyright (C) 2015-2016, A...
from collections import deque class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: q = deque([s]) seen = set() while q: s = q.popleft() # popleft() = BFS ; pop() = DFS for word in wordDict: if s.startswith(word): ...
from django.test import TestCase from users.models import CustomUser from django.urls import reverse class UserLoginViewTest(TestCase): def test_login_view_url_exists_at_desired_location(self): resp = self.client.get('/login/') self.assertEqual(resp.status_code, 200) def test_login_view_url_...
""" https://edabit.com/challenge/76ibd8jZxvhAwDskb """ def tallest_skyscraper(lst): return max(sum(lst[j][i] for j in range(len(lst))) for i in range(len(lst[0]))) print(tallest_skyscraper([ [0, 0, 0, 0], [0, 1, 0, 0], [0, 1, 1, 0], [1, 1, 1, 1] ]) == 3)
""" This module extends the ra.Relation class to allow row_id based get, put and delete operations of the tuples. The tuples are stored as a list of list, where the outer list stores a single list per unique rowid, and the inner list stores multiple versions of the corresponding rowid. The most re...
import numpy as np from scipy.io import loadmat,savemat import os import matplotlib.pyplot as plt Predictions = os.listdir("Allmat/") def perf_measure(y_actual, y_pred): TP = 0 FP = 0 TN = 0 FN = 0 for i in range(0,len(y_pred)): # print(i) if y_actual[i]==y_pred[i]==1: TP += 1 if y_pred[i]==1 and y_...
import random def getrandarray(origsize , number): listoflist = [] while number > 0: print number size = origsize arrayList = [] while size > 0: cnum = getrand(1,34) if cnum not in arrayList: arrayList.append(cnum) size = size - 1 arrayList.sort() if not listcontain(listoflist , arrayList)...
""" Реализовать формирование списка, используя функцию range() и возможности генератора. В список должны войти четные числа от 100 до 1000 (включая границы). Необходимо получить результат вычисления произведения всех элементов списка. Подсказка: использовать функцию reduce(). """ from functools import reduce print(re...
#Find non repeatative word from a string from codecs import StreamReader from collections import Counter def nonrepat(string): for i in string: #get the frquency freq=Counter(string) print (f" \n Strings is {i} and count is {freq} \n ") if freq[i] == 1 : print(f"The fir...
#!/usr/bin/env python """Tests for an ApiCallRouterWithChecks.""" import mock from grr import config from grr_api_client import errors as grr_api_errors from grr.gui import api_auth_manager from grr.gui import api_call_handler_base from grr.gui import api_call_router_with_approval_checks as api_router from grr.gui ...
import os import pytest import copy from microsim.microsim_model import Microsim from microsim.column_names import ColumnNames from microsim.population_initialisation import PopulationInitialisation import multiprocessing # ******************************************************** # These tests run through a whole dumm...
''' Start App ''' import UsConfig as Config from Common.Utilities import centerRoot if __name__ == '__main__': root = Config.ASSEMBLER.assemble("MainApp") root.title("EasyPass") root.iconbitmap(default=r'D:/logo.ico') centerRoot(root) root.mainloop()
#/bin/python from pyb import * from time import sleep x = 0 flag = 0 led1 = LED(1) led2 = LED(2) def onBtnRIGHTPressed(evt): global x,flag x += 10 ExtInt(Pin('RIGHT'), ExtInt.IRQ_FALLING, Pin.PULL_UP, onBtnRIGHTPressed) def onBtnLEFTPressed(evt): global x,flag x += -20 ExtInt(Pin('LEFT'), ExtInt.IRQ_FALLI...
msg = "string in double qutation" msg2 = 'string in single quatation' msg3 = "string \" with escape char" msg4 = """ using triple double qutation to have single ' and " quate as needed """ print(msg) print(msg2) print(msg3) print(msg4)
import warnings import numpy as np import LS_SVM from sklearn import datasets import matplotlib.pyplot as plt warnings.filterwarnings("ignore") X, y = datasets.make_classification(n_samples=50, n_features=2, n_informative=2, n_redundant=0, n_classes=2, random_state=7, class_...
import pandas as pd import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt # file on university type from financial file df_type = pd.read_csv("./../university_financial/university_financial0116.csv", index_col='Unnamed: 0') df_type = df_type[['UNITID', 'TYPE']] # retrieve sfa data df_sfa = pd.re...
# encoding=utf-8 import matplotlib import numpy as np matplotlib.use('agg') import matplotlib.pyplot as plt train_Acc=open('tarin_Acc.txt','r') train_Loss=open('train_Loss.txt','r') val_Acc=open('val_Acc.txt','r') val_Loss=open('val_Loss.txt','r') def ReadTxtName(rootdir): lines = [] with open(rootdir, 'r') a...
# -*- encoding: utf-8 -*- """ @File : add_love_user.py @Time : 2020/2/21 15:55 @Author : Tianjin @Email : tianjincn@163.com @Software: PyCharm """ from lin.core import User from lin.db import db from app.app import create_app from app.models.love import Love_user def main(): app = create_app() with...
''' 公众号:早起Python 作者:陈熹 请在桌面创建一个文件夹并命名为data,然后将测试Excel文件放入data文件夹中! ''' from openpyxl import load_workbook import os import glob import random import pandas as pd import re from openpyxl.styles import Alignment from openpyxl.styles import Side, Border from openpyxl.styles import Font def GetDesktopPath(): return os...
import sys from typing import List class Node: def __init__(self, data, key): self.data = data self.key = key def __lt__(self, other): return self.key < other.key def __repr__(self): return f"data={self.data};key={self.key}" class MinPriorityQueue: def __init__(self...
""" ## Questions : ### 7. [Reverse Integer](https://leetcode.com/problems/reverse-integer/) Given a 32-bit signed integer, reverse digits of an integer. **Example 1:** Input: 123 Output: 321 Example 2: <pre> Input: -123 Output: -321 </pre> Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an en...
# Generated by Django 2.2.1 on 2019-07-08 11:43 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('core', '0009_auto_20190708_1101'), ] operations = [ migrations.AddField( model_name='courseprog...
import numpy as np import matplotlib.pyplot as plt number_of_points = 500 x_point = [] y_point = [] a = 0.22 b = 0.78 for i in range(number_of_points): x = np.random.normal(0.0, 0.5) y = a*x + b + np.random.normal(0.0, 0.1) x_point.append([x]) y_point.append([y]) plt.plot(x_point, y_point, 'o', label='Input Da...
from datetime import datetime from django.http import HttpResponseRedirect, HttpResponse from django.template import RequestContext from django.contrib.auth import authenticate, login, logout from django.shortcuts import render_to_response from django.contrib.auth.decorators import login_required from django.contrib.a...
from django.contrib import admin from .models import Restaurent # Register your models here. admin.site.register(Restaurent)
#coding:utf-8 ''' Created on 2015.12.29 @author: Chunyun ''' import pika import time connection = pika.BlockingConnection(pika.ConnectionParameters('192.168.206.129')) channel = connection.channel() # 创建名字为test的queue,然后可以在server上sudo rabbitmqctl list_queues来查看这个queue channel.queue_declare(queue='queue-1',...
from airflow import DAG from airflow.operators.bash_operator import BashOperator from airflow.operators.sensors import SqlSensor from airflow.operators.hive_operator import HiveOperator from airflow.operators.mysql_operator import MySqlOperator from settings import default_args # - 学生账号 # - 基本信息 # - 设备/环境 (测网) # - ...
#!/usr/bin/env python import requests import json from bs4 import BeautifulSoup #Returns a session to use def login(): #Load login credentials LOGIN_FILE_NAME = 'credentials' with open(LOGIN_FILE_NAME, 'r') as f: personal_info = json.load(f) f.close() #session r = requests.Session() #log in (requires fo...
from django.db import models from django.utils.translation import gettext_lazy as _ class Troop(models.Model): """ Scout troop like a single troop (Stamm) or a district (Bezirk/Diözese) Columns: :number: national scouting ID of the troop :name: name of the troop """ number = models.P...
# python3 # Create date: 2021-06-06 # Author: Scc_hy # Func: 基于百度的开源OCR库进行文本识别 # ================================================================================= import os os.environ['KMP_DUPLICATE_LIB_OK'] = 'True' import numpy as np from PyQt5.QtGui import QImage import time from PIL import Image import time from ...
"""This module provides the main functionality of HTTPie. Invocation flow: 1. Read, validate and process the input (args, `stdin`). 2. Create and send a request. 3. Stream, and possibly process and format, the requested parts of the request-response exchange. 4. Simultaneously write to `stdout`...
import os def dcm2nii(): return def main(): working_dir = "./" for patient in os.listdir(working_dir): if os.path.isdir(os.path.join(working_dir, patient)): print("Working on",patient) for stage in os.listdir(os.path.join(working_dir, patient)): for phase in os.listdir(os.path.join(working_dir, patient...
import numpy as np import os import pandas as pd import datetime from xgboost import XGBRegressor import matplotlib.pyplot as plt def train_test_split(data, perc): data = data.values n = int(len(data) * (1 - perc)) return data[:n], data[n:] def xgboost_predict(train, val, model): train = np.array(trai...
# -*- coding:utf-8 -*- import tensorflow as tf import numpy as np import os import codecs import json import pickle import jieba ConfDirPath = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "conf") DataDirPath = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "dat...
#coding=utf-8 #Version:python3.6.0 #Tools:Pycharm 2017.3.2 # Author:LIKUNHONG __date__ = '2018/7/30 19:14' __author__ = 'Colby' # f =open("testWenJian",'r',encoding='utf-8') # print(f.read()) #测试r+ # f = open("testWenJian",'r+',encoding='utf-8') # # f.write("\n111") # # print(f.readline()) # print(f....
from kivy.app import App from kivy.lang import Builder # The custom App class # Widget creation code is removed # Another example of abstraction at work! class HelloKv(App): def build(self): self.title = "Hello world!" self.root = Builder.load_file('widget.kv') return self.r...
import unittest class TestFraction(unittest.TestCase): """Здесь нужно реализовать тест-методы"""
ranges={} #scannerLocations={} f=open('input/input13.txt') for line in f: s=line.split(': ') ranges[int(s[0])]=int(s[1]) #scannerLocations[int(s[0])]=0 f.close() IamCaught=lambda depth,offset,sRange:(depth+offset)%(2*(sRange-1))==0 severity=0 for k in ranges.keys(): if IamCaught(k,0,ranges[k]): ...
from cassandra.cluster import Cluster hostname = '127.0.0.1' keyspace = 'db1' column_family = 'postInfo' nodes = [] nodes.append(hostname) cluster = Cluster(nodes) session = cluster.connect(keyspace) def createPostInfoCF(): ''' Create the column family 'PostInfo' in the cassandra keyspace :return: ''...
import cv2 import imutils import numpy as np from pyimagesearch.centroidtracker import CentroidTracker class Counter: CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", ...
# 파일 입출력 score_file = open("score.txt", "w", encoding="utf8") print("수학 : 0", file=score_file) print("영어 : 50", file=score_file) score_file.close() # w 처음부터 쓰기 a 이어서 추가쓰기 score_file = open("score.txt", "a", encoding="utf8") score_file.write("과학: 80") score_file.write("\ncoding :100") score_file.close()
from itertools import combinations_with_replacement def solver(sections, darts, score): candidates = filter( lambda solution: sum(solution) == score, combinations_with_replacement(sections, r=darts) ) return ['-'.join(str(s) for s in x) for x in candidates] if __name__ == '__main__': ...
""" module: Notification_DB.py ------------------------------------------------------------------------ Author: David J. Sanders Student No: H00035340 Last Update: 15 December 2015 Update: Revise documentation -----------------------------------------------------------------------...
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html from scrapy.pipelines.images import ImagesPipeline import scrapy class SoPipeline(ImagesPipeline): def get_media_requests(...