text
stringlengths
38
1.54M
from pdb import set_trace from pprint import pprint as pp def add_player(): return {'id': 'default', 'admin': False, 'credits': 10, 'in_game':True} def get_admin(users): for player in users: #to delete prior admins if player['admin'] == True: player['admin'] = False user_check = False while not user_c...
import numpy as np def q_01(): A = np.random.rand(5, 5) minimum, maximum = A.min(), A.max() print((A - minimum) / (maximum - minimum)) print("") def q_02(): value = 5 B = np.random.rand(30) * 10 print(B) print(value) print(B[np.abs(B - value).argmin()]) print("") def q_03...
from Board import BoardImplementation as Board import numpy as np def build_tree(): branch_number = [] # for branching factor calculation winners = [0, 0, 0] # draw,x,o nodes = [1] # counter of tree nodes init_board = Board() unique_gamestates = set() # unique boards unique_gamestates.add...
""" 34. 「AのB」 2つの名詞が「の」で連結されている名詞句を抽出せよ. 板の間 名詞,一般,*,*,*,*,板の間,イタノマ,イタノマ 木の根 名詞,固有名詞,地域,一般,*,*,木の根,キノネ,キノネ 日の出 名詞,一般,*,*,*,*,日の出,ヒノデ,ヒノデ """ import MeCab from pprint import pprint from n30_execise import maping_morphology from n31_execise import load_mecab_file def define_exception_ofX(): ''' extract_concat_...
import nltk from nltk.corpus import CategorizedPlaintextCorpusReader from pylab import * import plotly.plotly as py import plotly.graph_objs as go corpus_root = "../corpus/lyric_corpus/files/" cat_root = "../categories/" corpus = CategorizedPlaintextCorpusReader(corpus_root, '.*\.txt', cat_file=cat_root+'cat.txt', c...
#filename:handle.py # -*- coding:utf-8 import web class Handle(object): def GET(self,name): try: if name == 'weather': f = open("wea_data") c = f.read() f.close() return c else: return "read failure" except: return "read failure." def POST(self,name): try: if name == "weather"...
# 哔站python学习教程 # 听讲人 cy # 开发时间:2020/10/12 0012 9:49 #创建列表的第一种方式 使用[] lst=['hello','world',98,98] print(lst) print(lst[0],lst[3])
from plotly.graph_objs import Waterfall from plotly.graph_objs import Volume from plotly.graph_objs import Violin from plotly.graph_objs import Table from plotly.graph_objs import Surface from plotly.graph_objs import Sunburst from plotly.graph_objs import Streamtube from plotly.graph_objs import Splom from plo...
import pyproj import shapefile _projections = {} def zone(coordinates): if 56 <= coordinates[1] < 64 and 3 <= coordinates[0] < 12: return 32 if 72 <= coordinates[1] < 84 and 0 <= coordinates[0] < 42: if coordinates[0] < 9: return 31 elif coordinates[0] < 21: r...
def a_c(word): # 결과 통 result = {} # 반복해서, 알파벳 하나씩 for char in word: # 알파벳이 딕셔너리 키에 있으면, +1 if char in result.keys(): result[char] += 1 # 없으면, 1 else: result[char] = 1 # print(type(result.keys())) return result print(a_c('hello')) # : => {...
import pandas as pd import requests from catalog.models import * import re from psycopg2.extras import NumericRange class CurationTemplate(): def __init__(self): self.file_loc = None self.parsed_publication = None self.parsed_scores = {} self.parsed_samples_scores = [] sel...
import numpy as np ''' Mother class for all the models ''' ''' All the models should implements those methods ''' class Model: def __init__(self): pass def computeMatchesProbas(self, data): pass def getTeams(self, data): team = set() for i in range(data.size): t...
import cv2 import matplotlib.pyplot as plt import numpy as np def main(): path = "C:\\Users\\spars\\OneDrive\\Pictures\\Camera Roll\\" imgpath1= path + "WIN_20170902_18_09_13_Pro.jpg" img1 = cv2.imread(imgpath1, 1) img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB) rows, columns, channels =...
from distutils.core import setup setup( name = "PluginLoader", version = "0.1", author = "Agonath", author_email = "Agonath@outlook.com", description = "Loads a module or a class object by the given path. Can be used as plugin loading system.", license = "Do what yout want at your own ri...
class CharStream(object): def open(self): pass def close(self): pass def has_next(self): return False def peek(self): return None def advance(self): return None class StringStream(CharStream): def __init__(self, s): ...
from crispy_forms.layout import Layout, Div USER_CREATE_EDIT_LAYOUT = Layout( Div( Div('email', css_class="col col-12"), Div('password1', css_class="col col-12"), Div('password2', css_class="col col-12"), css_class='col col-12 col-sm-12 col-md-4' ), Div( Div('name', ...
#!/usr/bin/python # -*- coding: utf-8 -*- import requests import json import time from mongodb import db import sys def query(method, args={}, access_token=''): pars = args #pars['access_token'] = unicode(access_token) pars['v'] = args.get('v', '5.14') prefix = 'https://api.vk.com/method/' timeout...
import random import math import networkx as nx import matplotlib.pyplot as plt cities = 10 ants = 20 iterations = 1000 alpha = 6 beta = 4 rate = 0.8 dist_matrix = [[0 for i in range(cities)] for j in range(cities)] for i in range(cities): for j in range(cities): if i != j: d...
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'EmailUser' db.create_table(u'riskgame_emailuser', ( (u'id', self.gf('django.db.m...
from sqlalchemy import BigInteger, Column, DateTime, ForeignKey, Integer, func from models.models import Base, auto_str @auto_str class IgnoredChannel(Base): __tablename__ = "ignored_channels" channel = Column(BigInteger, primary_key=True, nullable=False) user_id = Column(Integer, ForeignKey("users.id")...
import tensorflow as tf import numpy as np import argparse import time import os from lib.episode_generator import EpisodeGenerator from lib.networks import ProtoNet from utils.utils import cross_entropy, tf_acc from lib.params import TRAIN_DATASETS_SIZE, TEST_DATASETS, TEST_NUM_EPISODES from queue import Queue from t...
from app import app from flask import render_template, request from app.models import model, formopener @app.route('/') @app.route('/index') def index(): return render_template('index.html') @app.route('/lyrics', methods=['GET', 'POST']) @app.route('/lyrics.html', methods=['GET', 'POST']) def lyrics(): ma...
from datetime import datetime from flask import (render_template, flash, redirect, url_for, request, g, jsonify, current_app) # g for storing arbitrary attributes from flask_babel import (_, get_locale) from flask_login import (current_user, login_required) from guess_language import guess_language from app import db ...
"""Script to check disk space usage and send alerts if too high. Intended to be added to a crontab, e.g., 0 1,13 0 0 0 python monitor_disk_space.py analytics 90 """ import subprocess import sys import notify USAGE = "%s HOSTNAME [percent usage threshold]" % sys.argv[0] if len(sys.argv) < 2 or len(sys.argv) > 3: ...
import sys from strategypattern.database_strategy import DatabaseStrategy class MongoDbStrategy(DatabaseStrategy): def dbconnection(self, host, user, passwd, db): try: print("connecting to mongodb") print("connected") return True except Exception: p...
from urllib.error import HTTPError from bs4 import BeautifulSoup from pyvirtualdisplay import Display from selenium import webdriver class Parser(object): domain_url = "https://www.vseinstrumenti.ru" def __init__(self, base_url): self.base_url = base_url def get_html(self, url, parent_task): ...
# -*- coding: utf-8 -*- # ------------------------------------------------------------ # TheGroove360 / XBMC Plugin # Canale # ------------------------------------------------------------ import os import xbmc from core import config from core import filetools from core import library from platformcode import logger ...
from bean.file_path import * from keras.preprocessing import sequence # word_index, sens, labels ==> sens_pad, label_pad # 加载句子 def load_sens_labels_ml(file_path): sens = [] labels = [] with open(file_path, encoding='utf8') as f: sen = [] label = [] max_len = -1 for line i...
#!/usr/bin/env python # -*- encoding: utf-8 -*- # __author__ jax777 import nmap import threading import Queue import sys import time from plugins.ftp import * from plugins.ssh import * from plugins.telnet import * from plugins.mongo import * from plugins.mysql import * from plugins.mssql import * from plugins.memcache ...
#!/usr/bin/env/ python3 import re pattern = r'(^|\s)([1,2]?\d)(am|pm|AM|PM)|(^|\s)([1,2]?\d):([0-5]\d)(am|pm|AM|PM)?' # group1: space # group2: hour # group3: am,pm # group4: space # group5: hour # group6: minute # group7: am,pm def calculate_minutes_past_midnight(hours, minutes, meridian): result = 0 if me...
import time import pyautogui print(pyautogui.size()) #进入进度页面 jinduX=411 jinduY=156 pyautogui.moveTo(jinduX,jinduY,0.5) pyautogui.click(jinduX,jinduY) #进入样本页面 yangbenjiaX=127 yangbenjiaY=352 pyautogui.moveTo(yangbenjiaX,yangbenjiaY,0.5) pyautogui.click(yangbenjiaX,yangbenjiaY) #样本时间区间1点击 shijianX1=629 shijainY1=298 pyau...
import eng class TopDrawer: name = 'top drawer' #type = 'Item' visible = False aliases = [] descriptions = {'closedDesc': "It's the top drawer of the filing cabinet. It's identical in appearance to the bottom drawer for the most part.", 'openDescHit': "You look inside the drawer. Bingo! There are some paper...
import pickle import os class Products: def __init__(self,Name,Group,Subgroup,Price): if os.path.isfile("product.pickle"): try: infile = open("product.pickle","rb") prods = pickle.load(infile) infile.close() ids = prods.keys() ...
from django.http import HttpResponse, HttpRequest from django.shortcuts import redirect from django.shortcuts import render_to_response from django.shortcuts import render from forms import MessageForm import math from zipfile import * import shutil import os import requests import json from os import listdir from os.p...
import sqlite3 as sql from actor import Actor, GENDERS, ALIGNMENTS from location import Location class World: def __init__(self, database): self.database = database self._player_actor_id = None def sql_query(self, query_string, parameters=()): with sql.connect(self.database) as conn: ...
import argparse import pandas as pd import glob import os from prediction_utils.util import df_dict_concat, yaml_read, yaml_write parser = argparse.ArgumentParser() parser.add_argument( "--data_path", type=str, default="/share/pi/nigam/projects/sepsis/extraction_200815/", help="The root path where dat...
from rest_framework.viewsets import GenericViewSet from rest_framework.mixins import ListModelMixin from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated from utils.pagination import StanderPageNumberPagination from .models import OperateModel from .serial...
# coding: utf-8 import gym import argparse import torch import torch.nn as nn import time import math import os import random import numpy as np import datetime from utils import (create_logger, set_random_seed, get_device, to_column_batches) from typing import Tuple, Optional from model import CustomTransformer, Cus...
# Generated by Django 2.2.4 on 2020-07-02 10:50 from django.db import migrations, models import uuid class Migration(migrations.Migration): dependencies = [ ('common', '0033_auto_20200630_1352'), ] operations = [ migrations.CreateModel( name='InstitutionConfig', ...
# -*- coding: utf-8 -*- """ /*************************************************************************** attributePainter A QGIS plugin Plugin for easy replication of attributes between features ------------------- begin : 2014-03-1...
import logging import requests import json class Request(): def post(self, url, headers, payload, cookies): self._log_payload(payload) res = requests.post(url, headers=headers, json=payload, cookies=cookies) return self._validate_response(res) def get(self...
matrix = [(1, 2, 3), (4, 5, 6), (7, 8, 9), (10, 11, 12)] print("Original Matrix") for row in matrix: print(row) print("Transpose Matrix") print("\n") t_matrix = zip(*matrix) for row in t_matrix: print(row)
def read_file(csv_file_name): list_of_faculty = [] with open(csv_file_name) as f: list_of_faculty = [line.rstrip('\n') for line in f] list_of_faculty = list(map(lambda x: x.split(','), list_of_faculty)) del list_of_faculty[0] return list_of_faculty def emails(list_of_faculty): list_of...
from typing import List, Any, Dict import copy class Text(): context: Any object_id: Any elems: List max_elem: Any def __init__(self, elems=[], context=None, object_id=None, max_elem=0): if isinstance(elems, str): self.elems = [{'value': v} for v in elems] elif isinst...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'room.ui' # # Created by: PyQt5 UI code generator 5.13.0 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("F...
from typing import List def max_list(a_list: List[int]) -> int: max_so_far = a_list[0] for a in a_list: if a > max_so_far: max_so_far = a return max_so_far print(max_list([0, 4, -6, 9]))
from pwn import * #context.log_level = 'debug' p = process('./level3_x64') #p = remote('node4.buuoj.cn', 25135) elf = ELF('level3_x64') write_got = elf.got['write'] write_plt = elf.plt['write'] vuln_addr = elf.sym['vulnerable_function'] csu_1 = 0x4006aa csu_2 = 0x400690 pop_rdi_ret = 0x4006b3 ret = 0x400499 libc =...
import urllib.request, csv from bs4 import BeautifulSoup def extract_player(link): link = "http://www.uefa.com" + link page = urllib.request.urlopen(link) soup = BeautifulSoup(page, "lxml") player_data = soup.findAll("span", {"class": "profile--list--data"}) name = player_data[0].contents[0] ...
class Node: def __init__(self, data=None): self.data = data self.next = None class LinkedList: def __init__(self): self.head = Node() def append(self, data): new_node = Node(data) cur = self.head while cur.next is not None: cur = cur.next ...
from nbconvert.nbconvertapp import NbConvertApp, nbconvert_aliases, __version__, nbconvert_flags from traitlets import default, observe nbtojekyll_aliases = {} nbtojekyll_aliases.update(nbconvert_aliases) nbtojekyll_aliases.update({ "image-dir": "ImageExtractionPreprocessor.image_dir", "site-dir": "NBToJekyll....
import fileinput import itertools file = fileinput.input("test.txt") def checkexact(S, L): extraset = set() exact = 0 d = 0 i = len(S) while i <= len(L): newl = L[d:i] if newl == S: exact += 1 extraset.add(newl) d += 1 i += 1 ans = [exac...
# -*- coding: utf-8 -*- """ Created on Mon May 27 11:03:59 2019 @author: VIJ Global """ import random, pylab xVals = [] yVals = [] wVals = [] for i in range(1000): xVals.append(random.random()) yVals.append(random.random()) wVals.append(random.random()) xVals = pylab.array(xVals) yVals = p...
import requests import re import utils TAG = 'sina_fans' cookie = '##' header = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, sdch', 'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4', 'Cache-Control': 'max-age=0', ...
import struct ''' frequency: original number where frequency is not used and original number has been decoded. There are 50 commands/second dobot executes (50Hz). So if 50 commands are sent dobot will execute for one second. --== Decoding ==-- Those original numbers can be decoded as follows: 1. Take the number and s...
# -*- coding: utf-8 -*- # @Time : 2020/11/26 15:47 # @Author : liuwei # @File : task_dataset.py import os import json import random import time import torch import numpy as np from torch.utils.data import Dataset from multiprocess import Pool from function.preprocess import sent_to_matched_words_boundaries rand...
from sys import argv import numpy as np import matplotlib.pyplot as plt plt.rcParams["savefig.directory"] = "/home/mathisre/Dropbox/Uni/Images/Proj4" ax = plt.gca() ax.get_yaxis().get_major_formatter().set_useOffset(False) file = open(argv[1], 'r') n = int(float(file.readline())) -1 with file as filename: line...
import numpy as np import pandas as pd from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D def loading(filename): data = pd.read_csv(filename,header=None,sep='\s+') data = data[data[3] != '?'] data = np.array(data) for i in range(len(data)): data...
""" LemmaWithVariants -- OED extended lemma class @author: James McCracken """ import re from lex.lemma import Lemma from lex.oed.variants.combiner import Combiner from regexcompiler import ReplacementListCompiler from stringtools import lexical_sort COMPONENTIZER = ReplacementListCompiler(( (r"('s )", r'@'), ...
import sound import time notes = [] while True: note = input("Note: ") if note == "exit": break delay = float(input("Delay: ")) notes.append((f"piano:{note}", delay)) for note, delay in notes: sound.play_effect(note) time.sleep(delay)
""" wlp_app admin.py Ron Wilton - Started 20/07/2017 """ from django.contrib import admin from wlp_app.models import Location, Photo admin.site.register(Location) admin.site.register(Photo)
from setuptools import find_packages, setup setup( name='src', packages=find_packages(), version='0.1.0', description='Tester cookiecutter på day 1 exxercises.', author='sofie', license='MIT', )
# -*- coding: utf-8 -*- """ Created on Fri Feb 15 14:06:55 2019 @author: nshanbhag """ import pandas as pd Final_Data_Forecasted_Transfer_Capacities_day_ahead = pd.read_excel (r'C:\Users\mrudrappa\Desktop\Hackaton\hackathon\Final_Data_Forecasted_Transfer_Capacities_day_ahead.xlsx') #for an earlier version of Excel, ...
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- class Solution: def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ for start in range(len(matrix) // 2): Solution.inner_swap(matrix...
#!/usr/bin/env python3 """ Module to test papers.py """ __author__ = 'Susan Sim' __email__ = "ses@drsusansim.org" __copyright__ = "2014 Susan Sim" __license__ = "MIT License" __status__ = "Prototype" # imports one per line import pytest from papers import decide from papers import valid_passport_format from paper...
import random from ps1 import savings_after_36_months random.seed(123) lower = 1 upper = 10000 total_cost = 1000000 portion_down_payment = 0.25 tot_to_save = total_cost * portion_down_payment lower_threshold = tot_to_save - 100 upper_threshold = tot_to_save + 100 if __name__ == '__main__': annual_salary = int(in...
from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile (models.Model) : user = models.OneToOneField(User,on_delete= models.CASCADE) image= models.ImageField( default = 'default.jpg', upload_to='profile_pics') def __str__(self,): return f"{self.user.username}'s...
import torch import torchvision import torch.nn as nn def ifgsm(model, X, y, niters=10, epsilon=0.01, visualize=False): X_pert = X.clone() X_pert.requires_grad = True for i in range(niters): output_perturbed = model(X_pert) loss = nn.CrossEntropyLoss()(output_perturbed, y) loss...
import numpy as np import pandas as pd from pandas.errors import DataError import unittest from flasc.optimization import ( find_timeshift_between_dfs, match_y_curves_by_offset ) def generate_dataframes(): # Define a reference signal t = pd.date_range( "2019-01-10 12:15:01", "2019-01-...
import _pickle import gzip import os from copy import deepcopy from ConsoleW import * from HintWindow import * from ModuleManager import * from Project import * from WindowDialog import WindowSaveOnExit wildcard = "EEG Pre Processing Project (*.eppp)|*.eppp" class BaseWindow(wx.Frame): def __init__(self, *args...
import os import pickle import shutil from .const import projectroot, rawroot, logroot, vidroot IDz = {} for dirnm in os.listdir(rawroot): splitted = dirnm.split("_") ID = "_".join((splitted[0], splitted[-1])) os.chdir(rawroot + dirnm) vid = [flnm for flnm in os.listdir(".") if "mp4" == flnm[-3:]][0...
#encoding=utf-8 import web from utils import * #对字符串name进行base64编码,这样做既能规避不能用在文件名中的字符,又能不丢失信息第解码。 def get_file_name(name,ext=".json"): import base64 return cwd(u"static",u"files",u"{}{}".format(base64.b64encode(to_unicode(name).encode('utf-8')),ext)) class model: #GET方法用来显示model.htm def GET(self): params=web.inpu...
# -*- coding: utf-8 -*- import json import settings from monitor import base_class, cache, common #备份 #备份工具mysqldump dumper xtrabackup #备份方式增量还是全量或者全量+增量 #备份时间每日几点 #备份周期几号全量几号增量 #备份完整性检查|检查备份是否完成是否出现错误 #xtrabackup可以重定向日志,然后去检查日志,可以判断备份是否完成 #备份是否可用,需要进行恢复才行,可以手动 #独特的binlog备份 #binlog备份可以使用mysqlbinlog进行 #指定备份计划 #1....
class Solution(object): def findIntegers(self, n): """ :type n: int :rtype: int """ l=0 while n: l+=1 n=n/10 # # res = [0] # self.dfs(n, l, 0, 0, res) # # return res dp=[[0,0] for _ in range(l+1)...
##!/usr/bin/env python3 # Arduino Electronic Speed Controller Driver # Copyright (C) 2014 Simon Howroyd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the ...
import os from scrapy.http import HtmlResponse, Request, TextResponse def file_response(file_name, url=None): """ Create a Scrapy fake HTTP response from a HTML file @param file_name: The relative filename from the tests directory, but absolute paths are also accepted. @param url...
import redis r = redis.Redis(host='localhost', port=6380) r.set("foo", "bar") r2 = redis.Redis(host="46.137.20.245", port=6380) c = r2.get("foo") assert c == "foo"
from tkinter import * import math class Figuras: __pos = [] __canvas, __marco, antx, anty, x, y = None, None, None, None, None, None def __init__(self): self.__marco = Tk() self.__marco.title("Linea") self.__marco.geometry("700x500") self.__canvas = Canvas(self.__m...
"""This exposes form process mapper service.""" from http import HTTPStatus from ..exceptions import BusinessException from ..models import FormProcessMapper from ..models.enums import FormProcessMapperStatus from ..schemas import FormProcessMapperSchema class FormProcessMapperService(): """This class manages f...
import os import cv2 images = os.listdir("./dump") for i in images: img = cv2.imread("./dump/"+i) resized = cv2.resize(img,(100,100)) cv2.imwrite("./dump/100x100 "+i,resized)
from django.conf import settings LAST_SEEN_DEFAULT_MODULE = getattr(settings, 'LAST_SEEN_DEFAULT_MODULE', 'default') LAST_SEEN_INTERVAL = getattr(settings, 'LAST_SEEN_INTERVAL', 60 * 60 * 2) AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
""" Part One Fuel required to launch a given module is based on its mass. Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2. What is the sum of the fuel requirements for all of the modules on your spacecraft? Part Two Fuel itself requires fuel just like ...
from django.http import HttpResponse import datetime, csv from .models import ( Collection, Product, Agency, County, FrameSize, PhotoIndex, ScannedPhotoIndexLink, LineIndex, MicroficheIndex, CountyRelate ) # additional actions in admin console dropdown # export the historical c...
#!/usr/bin/python # # Expose the Hive search engine via a simple web form # from django.template import Context, loader from datetime import datetime, date, time from django import forms from django.http import HttpResponse from hive_job_parser import HiveJobListing import os from whoosh import index as wh_index fro...
import spotipy import spotipy.util as util import pprint username = '1223672875' scope = 'user-read-private user-read-playback-state user-modify-playback-state' token = util.prompt_for_user_token(username, scope, client_id='dbf83f3fa8554986b5ce8e6a0ab700a5', ...
from whoosh.lang.snowball.english import EnglishStemmer from whoosh.lang.snowball.french import FrenchStemmer from whoosh.lang.snowball.finnish import FinnishStemmer from whoosh.lang.snowball.spanish import SpanishStemmer def test_english(): s = EnglishStemmer() assert s.stem("hello") == "hello" assert s....
# Пользователь вводит данные о количестве предприятий, их наименования и # прибыль за четыре квартала для каждого предприятия. Программа должна # определить среднюю прибыль (за год для всех предприятий) и отдельно вывести # наименования предприятий, чья прибыль выше среднего и ниже среднего. from collections import de...
from logAnalyzer.logAnalyzerTypes import CardValue # Used as just a parameter for constructing actual Cards. # This makes it easy to implement every card in the game (more defaults, less writing) # The Card fields not included in CardParams are generated from the given params. class CardParams: def __init__(self...
import sys stdin = sys.stdin ni = lambda: int(ns()) na = lambda: list(map(int, stdin.readline().split())) ns = lambda: stdin.readline() n = ni() t = na() v = na() bound = [0] * (n+1) for i in range(n-1): bound[i+1] = min(v[i], v[i+1], bound[i] + t[i]) for i in range(n-1,0,-1): bound[i] = min(bound[i], v[i],...
def minDepth(self, root: TreeNode) -> int: if root is None: return 0 if root.left == None and root.right != None: return self.minDepth(root.right) + 1 if root.right == None and root.left != None: return self.minDepth(root.left) + 1 return min(self.minDepth(root.left), self.minDep...
import utils import numpy as np wordorg=utils.loadData("./saved_data/train_word.bin") word2=utils.loadData("./saved_data/dev_word.bin") wordorg.update(word2) PAD = 'PAD' UNK = 'UNK' word2Vec_text = utils.read_file('/home/huwenxiang/deeplearn/词向量/英文/谷歌/glove.6B.300d.txt') word2Id = {} Id2Word = {} word2Vec = [] word_dim...
# -*- coding: utf-8 -*- r""" Seaborn example =============== Preview the capture of seaborn styles in plots """ # Author: Michael Waskom # License: BSD 3 clause from __future__ import division, absolute_import, print_function import numpy as np import seaborn as sns # Enforce the use of default set style #sns.set(...
__author__ = 'david' import numpy as np import netCDF4 import pylab import os import shutil import copy import glob import subprocess import nc_copy from scipy.io import netcdf as nc import utils # # This module contains routines for creating # all of the files used in action minimization. # Routines are: # # 1) ini...
# Tipo 'string' x = 'Exemplo de string' print('Valor: ', x) print('Tipo: ', type(x)) print() y = "Outro exemplo de string" print('Valor: ', y) print('Tipo: ', type(y)) z = """ O nome do restaurante é "Mc Donald's" """ print(z) # Usar barra ao contrario ou usar aspas duplas
# Generated by Django 3.1 on 2020-10-12 14:39 import django.core.validators from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('Profile', '0003_auto_20201012_1417'), ] operations = [ migr...
# -- coding: utf-8 -- import MySQLdb string_create_table = """ CREATE TABLE data( trial_id LONGTEXT CHARACTER SET utf8 COLLATE utf8_general_ci, trial_title LONGTEXT CHARACTER SET utf8 COLLATE utf8_general_ci, trial_acronym LONGTEXT CHARACTER SET utf8 COLLATE utf8_general_ci, trial_...
from ibm_watson import SpeechToTextV1, LanguageTranslatorV3 import json from ibm_cloud_sdk_core.authenticators import IAMAuthenticator from pandas import json_normalize url_s2t = '[SPEECH TO TEXT SERVICE URL]' url_lt = '[LANGUAGE TRANSLATOR SERVICE URL]' iam_apikey_s2t = '[SPEECH TO TEXT API KEY]' apikey_lt = '[LANGU...
# Generated by Django 2.0.2 on 2018-02-05 05:29 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('foreignkey', '0001_initial'), ] operations = [ migrations.AlterField( model_name='car', ...
from videos.models import * from rest_framework.response import Response from rest_framework import status from vidwik.settings import BASE_URL import os from django.http import JsonResponse def get_video(id): try: saved_video_details = SavedVideo.objects.get(id=int(id)) data = { "id":...
import random with open('sowpods.txt', 'r') as f: words = [word.strip().lower() for word in f] def get_random_words(length): random_words = random.choices(words, k=length) return random_words def mask_message(message): message = message.split() random_words = get_random_words(len(message)) m...
# -*- coding: utf-8 -*- import logging import os import shutil import gzip import numpy as np import pandas as pd import time from pathlib import Path from dotenv import find_dotenv, load_dotenv from urllib.request import urlopen from Bio import Entrez, SeqIO from Bio.SeqUtils import GC from bx.intervals.intersection i...