text
stringlengths
38
1.54M
#!/usr/bin/env python __author__ = "Sreenivas Bhattiprolu" __license__ = "Feel free to copy, I appreciate if you acknowledge Python for Microscopists" # https://youtu.be/VHIM2FKGLzc """ @author: Sreenivas Bhattiprolu Sharpness Estimation for Document and Scene Images by Jayant Kumar , Francine Chen , D...
# from pyspark import SparkContext # myrange = SparkContext.range(0,1000).toDF("number") # print (myrange) from pyspark import SQLContext from pyspark import SparkContext #from pyspark import SparkSession # sc = SparkContext() # myrange = sc.range(1000).toDF("number") # print (myrange) from pyspark import SparkContex...
import pytest from day_15.part_one import speak_n_say def test_speak_n_say_one(): nums = [1, 3, 2] assert speak_n_say(nums, 30000000) == 2578 def test_speak_n_say_two(): nums = [2, 1, 3] assert speak_n_say(nums, 30000000) == 3544142 def test_speak_n_say_three(): nums = [1, 2, 3] assert sp...
""" 1. Создать класс TrafficLight (светофор) и определить у него один атрибут color (цвет) и метод running (запуск). Атрибут реализовать как приватный. В рамках метода реализовать переключение светофора в режимы: красный, желтый, зеленый. Продолжительность первого состояния (красный) составляет 7 секунд, второго (желты...
import pygame from pygame.locals import * pygame.init() color = (15, 200, 100) color_2 = (155, 200, 99) colorCirculo = (150, 56, 78) ventana = pygame.display.set_mode((400, 600)) pygame.display.set_caption('pygame en py ') pygame.draw.circle(ventana, colorCirculo,(250, 100), 89 ) corriendo = True #fuentes fuente = ...
# coding: utf-8 """ Fecha de creacion 3/18/20 @autor: mjapon """ import datetime import logging from sqlalchemy import Column, Integer, String, TIMESTAMP, Text from fusayrepo.models.conf import Declarative from fusayrepo.utils.jsonutil import JsonAlchemy log = logging.getLogger(__name__) class TParams(Declarative,...
#encoding=utf-8 from chapt_15.DataDrivenFrameWork.testScripts.TestMail126AddContacts import * if __name__ == '__main__': test126MailAddContacts() #测试执行
# -*- coding: utf-8 -*- """ Created on Fri May 31 04:10:06 2019 @author: Stacy controller program for testing spacy nlp features rem: use case: convert us date to uk date """ # IMPORTS ------------------------------ # py files import sys sys.path.append('jellyfish-mods/') sys.path.append('spacy-mods/') sys.path...
# -*- coding: utf-8 -*- """ /*************************************************************************** LandsatQATools A QGIS plugin Decode Landsat QA bands. ------------------- begin : 2017-05-17 git sha : $Fo...
""" Description : Slot-action prediction model. Finetunes bert-base-uncased model on slot-action prediction data. Run Command: python train_slot_act.py -in=<path of the input data> -path=<output dir> -src_file=<name of the python script> """ #-------------------------------------------- import torch import torchtext....
from page_objects import PageElement, PageObject class LoginPage(PageObject): username = PageElement(name='email') password = PageElement(name='password') login_button = PageElement(css='input[type="submit"]') facebook_button = PageElement(css='.btn-facebook')
#Text-Based Tic Tac Toe (Computer Makes Moves Randomly) #Using https://repl.it/languages/python3 #Author: Robert Beckett from random import randint #This function prints the board. (View section) def PrintBoard(): print(a1, a2, a3) print(b1, b2, b3) print(c1, c2, c3) print("\n") #This function checks whether e...
a = { "năm phát hành" : 2018, "diễn viên" : "abc", "Nhân vật tham gia" : "xyz", } b = { "năm phát hành" : 2019, "diễn viên" : "ghik", "Nhân vật tham gia" : "lmn", } c = { "năm phát hành" : 2020, "diễn viên" : "123456", "Nhân vật tham gia" : "98765", } d = [a, b, c] for x in d: g ...
from ossConfig import ossConfig import Oss access_key = 'XXXXXXXXX' secret_key = 'XXXXXXXXXXXXXXXXXXX' endpoint_url = 'http://XXXXXXXXXXXXXXXXX.com' config = ossConfig(access_key, secret_key, endpoint_url) bucket_name = 'test1' # get_website_configuration get_website_configuration = Oss.get_bucket_website(config, bu...
"""Viết chương trình đếm các chuỗi trong một list thỏa mãn: + Độ dài từ 2 trở lên + Ký tự đầu tiên và cuối cùng của chuỗi đó giống nhau""" def demchuoi(list): dem=0 for i in range(len(list)): if len(list[i])>=2: if list[i][0]==list[i][len(list[i])-1]: dem+=1 print...
from collections import defaultdict from typing import List, Callable, Tuple, Iterable, Dict from data_generator.tokenize_helper import TokenizedText from list_lib import lmap, dict_value_map from misc_lib import group_by, get_first, get_second, get_third def assert_token_subword_same(idx, entries, t_text): subw...
#WHILE LOOPS ''' i=1 while i<=10: print('*'*i) i+=1 print ('Done') ''' #GUESSING GAME '''secret_number=9 guess_count=0 guess_limit=3 while guess_count<guess_limit: guess=int(input('Guess: ')) guess_count+=1 if guess == secret_number: print('You won!!!') break else...
from django.conf.urls import patterns, url, include from administration import urls as auth_urls from paparazzi import views urlpatterns = patterns( url(r'^auth/', include(auth_urls)), url(r'^$', views.api_root), # /photos/ url(r'^photos/$', views.ListCreatePhoto.as_view(), name='photos'), )
import os from django.shortcuts import render, redirect, reverse, HttpResponseRedirect, get_object_or_404 from .forms import SearchForm from .models import JobAPI, JobPost from .utils.api_runner import api_main def index(request): searches = JobAPI.objects.all() context = { "searches": searches, ...
import argparse import os import shutil import time import sys import csv import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim import torch.utils.data import dataloader.data_utils as data_utils from dataloader.data_utils import get_dataloader from metric...
import zipfile import datetime import os import json import salt.client import django import django.template from django.contrib import auth import integralstor_gridcell from integralstor_gridcell import gluster_volumes, system_info from integralstor_utils import config, audit, alerts, lock, db import integral_vie...
from sales import calc_shipping, calc_tax # now what we are calling are the functions import sales # now what we call after sales.method is called METHOD sales.calc_shipping() sale.calc_tax() calc_shipping() calc_tax()
import json as jsonlib import operator import re from abc import ABC from enum import Enum from functools import reduce from http.cookies import SimpleCookie from types import MappingProxyType from typing import ( Any, Callable, ClassVar, Dict, List, Optional, Pattern as RegexPattern, Se...
from __future__ import (absolute_import, division, print_function, unicode_literals) import numpy as np from matplotlib import pyplot as plt from astropy.io import fits from photutils import CircularAperture from astroscrappy import detect_cosmics from astropy.convolution import convolve_fft...
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # #...
# Exercício 5 #Criar dicionário com 5 alunos #cada aluno precisa ter Nome; data de nascimento; curso; cadeiras #Escrever função para apagar determinado aluno da base #Escrever função para inserir alunos na base #base aluno1 = {"nome": "Anah", "dt_nasc": "02/02/2002", "curso": "biologia", "cadeiras": ["ab", "cd", "ef"]...
import streamlit as st import numpy as np # from handcalcs.handcalcs import handcalc # st.write('## Create your transition matrix:') # text_input = st.text_input('Transition Matrix',help="Separate entries by commas, rows by semicolons") # if text_input is not None: # A = np.matrix(text_input) # st.code(A) # ...
import promote import newspaper from schema import Schema from newspaper import Article import nltk nltk.download('punkt') USERNAME = "colin" API_KEY = "your_api_key" PROMOTE_URL = "http://promote.c.yhat.com/" p = promote.Promote(USERNAME, API_KEY, PROMOTE_URL) @promote.validate_json(Schema({'url': str})) def Articl...
from django.db import models from equipment_accounting_NOF.models import BaseModelAbstract, BaseDictionaryModelAbstract from locations.models import Locations from technical_equipments.models import TechnicalEquipments class SwitchPorts(BaseModelAbstract): port_num = models.PositiveIntegerField(verbose_name='Номе...
#coding=utf-8 import re def main(): email = input("请输入邮箱") print ("您输入的邮箱是:%s" %email) rec = re.match(r"[a-z0-9A-Z]{1,20}@163\.com$",email) #此处 需要反斜杠进行转义 #print (rec.group()) if rec: print ("您输入的邮箱是:%s*********符合规则" %email) else: print ("您输入的邮箱是:%s,**********不符合规则" %email) if __name__ == "__main...
#!/usr/bin/python '''Implement the cipher/decipher sytems using AES in either CBC or CTR mode. In CTR mode, the IV (initialization vector) is incremented one each time. ''' __author__ = "Jin Zhang(zj@utexas.edu)" __version__ = "$Version: 1.0 $" __date__ = "$Date: 2014/07/14 00:12:15" __copyright__ = "Copyright: (c...
# user interface that people will use to interact with library # import filters library into this script from PIL import Image # Rename this file to be "filters.py" # Add commands to import modules here. # Define your load_img() function here. # Parameters: The name of the file to be opened (string) # R...
from datetime import date from django.core.exceptions import ValidationError from django.test import TestCase from animals.models import Animal, Breed, Pet class AnimalModelTest(TestCase): fixtures = ['animals.json',] def test_animal_string(self): animal_name = "Dog" animal = Animal.objects...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = "Vinícius Madureira" __copyright__ = "Copyright 2020, Vinícius Madureira" __license__ = "Creative Commons Zero 1.0 Universal" __version__ = "0.01a" __maintainer__ = "Vinícius Madureira" __email__ = "viniciusmadureira@outlook.com" __status__ = "Testing" from ...
import numpy as np import pandas as pd import pickle from models import static_clf, dynamic_clf from sklearn.metrics import f1_score,precision_score,recall_score def load_data(filepath): data = pd.read_csv(filepath) data = data.sample(frac=1) # data.reset_index(drop=True) <-- this will reset shuffle ...
# @author Nayara Souza # UFCG - Universidade Federal de Campina Grande # AA - Basico n = int(input()) e = list(map(int,input().split())) s = list(map(int,input().split())) j = 0 i = 0 count = 0 f = set() while len(f) < n: if e[i] == s[j]: f.add(s[j]) j += 1 i += 1 ...
import random def play_game(away_team, home_team): def play(away_team, home_team): def calc_event(player, team_defense): d_sample = random.sample(team_defense, 3) d_sum = sum(player.get_defense() for player in d_sample) i = random.randint(0,d_sum) if(i < player.get_offense()): return (1, player.ge...
from django.contrib import admin # Register your models here. from .models import Patient_Directory, Doctor_Directory, Assigned_Patient, Assigned_Doctor, Instance class Assigned_DoctorAdmin(admin.ModelAdmin): list_display = ('last_name', 'first_name', 'specialty', 'age', 'display_assigned_patient') pass # ...
__all__ = ["interface", "models", "database", "db_registry"] from registry.models import * from registry.interface import Registry from registry.database import DbConnection, connect from registry.db_registry import DbRegistry, ConflictError
# TAGS map, partition, equivalence classes, pythonic import collections class Solution: def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ m = collections.defaultdict(list) for s in strs: ss = str(sorted(s)) ...
from turtle import Screen from snake import Snake from scoreboard import Scoreboard from food import Food import time screen=Screen() screen.setup(width=600,height=600) screen.bgcolor("black") screen.title("Snake Game") screen.tracer(0) game_is_on=True score=0 snake=Snake() scoreboard=Scoreboard(scor...
import numpy as np import cPickle import matplotlib.pyplot as plt # Open data f = open('EthEur.p','rb') A = cPickle.load(f) dataShape = A.shape f.close() (nRows, nCols)= dataShape print A[nRows-1,:] nb_data=nRows init_ind=100 initial_time = A[init_ind,2]#1438945790 final_time = A[nRows-1,2] price=A[:,0] volume=A[:...
#!/usr/bin/env python # addressBook.py: a very simple email address book program # By: Fadel Berakdar # Date: 26 Jan 2016 from optparse import OptionParser import re import shelve import configparser config = configparser.RawConfigParser() config.read("/Users/Phoenix/Dropbox/Projects/Code/Python3/12_OptParse/Addres...
import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim import torch.utils.data import torchvision.transforms as transforms import torchvision.datasets as datasets import torchvision.models as models import numpy as np from torch.nn.init import normal, constan...
#!/usr/bin/env python3 import os import json import base64 import lzma import black import dis from flask import ( Flask, render_template, request, send_from_directory, render_template_string, redirect, url_for, ) app = Flask(__name__) def compress_state(data): compressed = lzma.comp...
# recebe chaves do twitter e o id do usuario e limite de followers para coleta import conf import helpers.manipulador_de_listas as mani import logging import os import socket import sys import tweepy consumer_key = sys.argv[1] consumer_secret = sys.argv[2] acess_token = sys.argv[3] access_token_secret = sys.argv[4] id...
"""Top-level package for softshark.""" __author__ = """Soft Shell""" __email__ = 'kumarcalif@gmail.com' __version__ = '0.1.0'
#PIP ver='1.0.0' #github.com/smcclennon/Toolbox import os os.system('title PIP') while True: print('Please enter a package name (e.g. "requests" or "psutil")') package=input(str('> ')) print('\n>>> pip install '+package+' --user') os.system('pip install '+package+' --user') print('\n\n\n')
import nsq import tornado.ioloop import time def pub_message(): writer.pub('my_topic', time.strftime('%H:%M:%S'), finish_pub) def finish_pub(conn, data): print data writer = nsq.Writer(['127.0.0.1:4150']) tornado.ioloop.PeriodicCallback(pub_message, 1000).start() nsq.run()
from flask_migrate import MigrateCommand from flask_script import Manager from APP import appname app = appname() manager = Manager(app) manager.add_command('db',MigrateCommand) if __name__ == '__main__': manager.run()
import unittest from SwiftFormat.Syntax import * class IdentifierTest(unittest.TestCase): def testImplicitParameter(self): parser = identifier() assert parser.parse(u"$0") assert parser.parse(u"$0")[0].meta.type == SwiftTypes.IMPLICIT_PARAMETER assert parser.parse(u"$1") as...
#!/usr/bin/python import math def conv(n,k): c = 1 result = 0 sn = str(n)[::-1] for i in range(len(sn)): result += c * int(sn[i]) c *= k return result def prime(num): res = 0 pr = True for i in range(2, int(math.sqrt(1 + num)) + 1): if num % i == 0 and i != num : res = i pr = False break ...
from django.contrib.auth.models import User from django.test import Client, TestCase from django.urls import reverse from .models import Employee from .utils import createEmployee class UserTest(TestCase): def setUp(self): my_test_user = User.objects.create_user('temporary', ...
import scanpy as sc from utils import plot c_map = 'Purples' base_path = '/Users/zhongyuanke/data/' fig_size = (20, 3) title = ['CD34', 'CD14', 'NKG7', 'CD4', 'CD19'] bar = ['silver', 'r'] file_orig = base_path+'merge_result/merge5.h5ad' file_scxx = base_path+'result/merge5_scxx_z2.h5ad' file_mse = base_path+'result...
# frame => a rectangular container to group and hold widgets from tkinter import * window = Tk() window.geometry("200x200") frame = Frame(window, bg="pink", bd=5,relief=SUNKEN) frame.place(x=30, y=50) Button(frame, text="W", font=("Consolas", 15), width=3).pack(side=TOP) Button(frame, text="A", font=("Cons...
import constants from plate import Plate class SubmissionCounter(): def __init__(self, world, x, y): self.__world = world self.x = x self.y = y def put_on_chef_held_item(self, chef): if isinstance(chef.held_item, Plate): plate = chef.held_item chef.held...
#!/usr/bin/python import numpy as np import pandas as pd from dataReductionAndSampling import DialogueActSample from gensim.models import KeyedVectors from keras.callbacks import EarlyStopping from keras.layers import Dense, Dropout from keras.models import Sequential from keras.optimizers import Adam from sklearn.dec...
def prj_import(com_import, dst_user_dir, file_name): com_import.g_target = dst_user_dir com_import.g_file = file_name com_import.g_target = dst_user_dir assert com_import.g_target is dst_user_dir com_import.Execute() def prj_dgs_import(com_import, dst_user_dir, file_name, name, template=None): ...
from django import forms from .models import Post,Client,Vendor,Match,NumberOfPhases from django.forms.models import inlineformset_factory class PostForm(forms.ModelForm): class Meta: model=Post fields='__all__' class ClientForm(forms.ModelForm): class Meta: model=Client fields='...
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.permissions import IsAuthenticatedOrReadOnly from rest_framework import status from api.models import Comment from api.serializers import CommentSerializer class CommentListAPIView(APIView): permission_class...
from django.db import models from core.models import User class StudentProfile(models.Model): student_profile_id = models.UUIDField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE)
from django.contrib import admin from podminer.models import Ranking, RankingHistory, UpdateTaskResult, UserMetrics, GlobalTop100,GenreTop100,RegionTop100,CountryTop100,PowerRankingHistory # Register your models here. admin.site.register(Ranking) admin.site.register(RankingHistory) admin.site.register(UpdateTaskResul...
#!/usr/bin/env python3 import sys from sys import argv import re import copy from Bio.PDB import * from Bio.PDB.MMCIF2Dict import MMCIF2Dict """ # pachinam_obj.py To be used from within PyMOL, right after cif files have been loaded into objects Uses the already defined objects to pull pairs of chain identif...
import os import json import numpy as np import tensorflow as tf import experiments from db import db from config import Config from argparse import ArgumentParser from utils import logger from utils import py_utils from ops import data_loader from ops import model_utils from ops import loss_utils from ops import eval_...
import numpy as np import dill def get_fun(name): input_file = open(name, 'rb') return dill.loads(dill.load(input_file)) def is_valid(X, k, n): K = np.zeros((n, n)) for i in range(n): for j in range(i, n): k_i_j = k(X[i], X[j]) k_j_i = k(X[j], X[i]) if k_i...
from sample import getReport import argparse def main(): ap = argparse.ArgumentParser() ap.add_argument('extension') args = ap.parse_args() print("\n".join(getReport(args.extension))) if __name__=='__main__': main()
import re def get_half(seq): ssr_obj = re.search(r'([ATCG]+)\1', seq) if ssr_obj: return ssr_obj.group(1) else: return None def check_tail(block, sequence, terminal): block_len = len(block) potential_tail = sequence[terminal: (terminal + block_len)] if potential_tail == block...
import math num = float(input('Digite um número real: ')) numint = math.trunc(num) print('A porção inteira de {} eh: {}'.format(num, numint))
import numpy from pandas import read_csv from sklearn.utils import resample from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import accuracy_score from matplotlib import pyplot # load dataset data = read_csv('pima-indians-diabetes.data.csv', header=None) values = data.values # configure bootstrap n_...
import os import sys import platform import numpy as np import sklearn.linear_model as sl import sklearn.model_selection as sm import matplotlib.pyplot as mp def make_data(): x = np.array([ [4, 7], [3.5, 8], [3.1, 6.2], [0.5, 1], [1, 2], [1.2, 1.9], ...
import string import pango, gtk import gnoetics, tilemodel class TileTextView(gtk.TextView, tilemodel.TileModelListener): def __init__(self, model): gtk.TextView.__init__(self) tilemodel.TileModelListener.__init__(self, model) self.set_editable(0) self.set_curs...
firstname = input("Enter first Name : ") lastname = input("Enter the last Name : ") tmp = [firstname,lastname] tmp.reverse() print(tmp)
#8.4 Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. #The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. #When the program completes,sort a...
from __future__ import annotations from typing import NamedTuple class Config(NamedTuple): username: str channel: str oauth_token: str client_id: str youtube_api_key: str youtube_playlists: dict[str, dict[str, str]] airnow_api_key: str @property def oauth_token_token(self) -> str...
from Transmitter import Transmitter class InputMethod: def __init__(self): self.motor_speeds = [0, 0, 0] # Init transmitter self.t = Transmitter() def doListenLoop(self): while True: self.getInput() self.t.send(self.motor_speeds) def getInput(self): pass
number_element_of_dict = int(input("Nhập số phần tử của Dictionary (lớn hơn 3): ")) number_element_of_list = int(input("Nhập số phần tử của Value List (lớn hơn 5): ")) my_dict = {} if number_element_of_dict <= 3 or number_element_of_list <= 5: print("Giá trị nhập không đúng") else: for i in range(1, number_elem...
#!/usr/bin/env python3 """ DrugCentral PostgreSql db client. """ import os,sys,argparse,re,time,logging from .. import drugcentral from ..util import yaml as util_yaml ############################################################################# if __name__=='__main__': parser = argparse.ArgumentParser(description=...
from eval import * import os import numpy as np from sklearn.linear_model import Perceptron import pandas as pd from utils import tokenize_sentences, MMR from table import Table from sklearn.calibration import CalibratedClassifierCV from sklearn.ensemble import RandomForestClassifier from sklearn.neural_network import ...
# Generated by Django 2.2.6 on 2019-11-04 08:21 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("cases", "0015_auto_20191003_1323")] operations = [ migrations.AddField( model_name="image", name="timepoints", field=...
from thefuck.rules.cd_cs import match, get_new_command from thefuck.types import Command def test_match(): assert match(Command('cs', 'cs: command not found')) assert match(Command('cs /etc/', 'cs: command not found')) def test_get_new_command(): assert get_new_command(Command('cs /etc/', 'cs: command n...
# coding: utf-8 # In[1]: import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt import networkx as nx from subprocess import check_output get_ipython().run_line_magic('matplotlib', 'inline') # In[122]: df=pd.read_csv('C:\\Users\\p860n111\\Desktop\\data science\\Hw2\\Shakesp...
#!/usr/bin/env python # coding:utf-8 ''' Created on: @author: 张晓宇 Email: 61411916@qq.com Version: 1.0 Description: Help: ''' from core import core if __name__ == '__main__': core.run()
#!/usr/bin/env python """Script to check that a commit message is valid""" # noqa import argparse import os.path import re import shutil import sys from collections import defaultdict from colorama import Fore, Style from git import Repo def check(message): """Ensure the message follow some rules. This i...
from typing import Callable, Type, TypeVar from uuid import UUID from eventsourcing.application import Repository from eventsourcing.domain import AggregateEvent E = TypeVar("E", bound=AggregateEvent) def assert_contains_event( repository: Repository, board_id: UUID, type_: Type[E], assertions: Call...
import pandas as pd import matplotlib.pyplot as plt from sklearn.cluster import KMeans from kneed import KneeLocator import numpy as np from scipy.spatial.distance import cdist iris = pd.read_csv('C:/Users/jhunjhun/Downloads/iris.csv') iris = iris.iloc[:,[2,3]] sse = [] K = range(1,10) for k in K: kmeanModel = KMe...
# INPUT cliente=input("Ingrese el nombre del cliente:") RUC=int(input("Ingrese el numero de RUC:")) relojes=int(input("Ingrese la cantidad de relojes:")) pulseras=int(input("Ingrese la cantidad de pulseras:")) cadenas=int(input("Ingrese la cantidad de cadenas:")) precio_de_un_reloj=float(input("Ingrese el precio de un ...
#!/usr/bin/python3 # -*- coding: utf-8 -*- # Autor: Ingmar Stapel # Date: 20141229 # Version: 1.0 # Homepage: www.raspberry-pi-car.com import sys, tty, termios, os from L298NHBridge import HBridge speedrun = 0 anglesteer = 0 Motors = HBridge(19, 26, 23, 24, 13, 21, 22) # Instructions for when the user has a...
''' Created on Jun 29, 2017 @author: Xueping ''' from sklearn.decomposition import LatentDirichletAllocation import pandas as pd import numpy as np def load_Preprocess(): df = pd.read_csv("~/data/hab_test.csv", dtype={'hab_test.tot_visit': np.float32,'hab_test.tot_visit_ed': np.float32,'hab_test.tot_visit_a...
# -*- coding: utf-8 -*- """Test base.""" #------------------------------------------------------------------------------ # Imports #------------------------------------------------------------------------------ import logging import numpy as np from pytest import fixture from ..base import BaseVisual, GLSLInserte...
import random import time with open("words.txt") as f: words = f.read().splitlines() class Game: def __init__(self, name): self.name = name red_first = True self.colors = self.init_colors(red_first) self.selections = [False] * 25 self.last_touched = time.time() ...
import django.shortcuts from .models import Author # Create your views here. def authors_list(request): # print(request) # return HttpResponse('<h1>Hello!</h1>') authors = Author.objects.all() return django.shortcuts.render(request, 'project_first_app/index.html', context={'authors': authors}) def ...
from eso_bot.backend.helpers import command_invoked from discord.ext.commands import Cog, command class Admin(Cog, name="Admin commands"): """ Admin commands. """ def __init__(self, bot): self.bot = bot self.admins = [391583287652515841] @command(name="stop") async def resta...
import numpy as np def identify_quant_cols( # TODO: add any arguments here ): # TODO: write code that will return a list of the quantitative columns in a dataframe pass def make_col_positive( #identify the smallest negative number, and add that to the entire dataset to shift everything into ...
from tkinter import * from tkintertable import TableCanvas, TableModel from PIL import ImageTk,Image import os import csv import cv2 import time from functools import partial from utils import decode_video, get_image class get_labels_single(): def __init__(self,labels_csv,): def read_csv(t...
import itertools w, h, k = map(int, input().split()) C = [input() for _ in range(h)] I = [f'i{i}' for i in range(h)] J = [f'j{i}' for i in range(w)] combi = [] for i in range(w+h): combi.extend(itertools.combinations(I + J, i))
# # Ghost_evade w/ standard DQN at work. # # import gym import numpy as np import time as time import tensorflow as tf import tf_util_rob as U import models as models import build_graph_rob3 as build_graph from replay_buffer import ReplayBuffer, PrioritizedReplayBuffer from schedules import LinearSchedule import matplo...
# Generated by Django 2.2 on 2019-04-21 21:24 from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Racer', fields=[...
# -*- coding: utf-8 -*- """ Created on Sat Sep 28 09:29:06 2019 @author: Aaron """ import pandas as pd file_one = "Resources/election_data.csv" file_one_df = pd.read_csv(file_one, encoding="ISO-8859-1") title = "Election Results\n \n------------------------" print(title) #Find Total Votes total_votes = file_one_d...
# -*- coding: utf-8 -*- """ Created on Apr 11 2020 @author: Felix Brinquis Description: este programa recibe como parametro un fichero en formato TCX Garmin, lee el contenido del mismo y lo convierte en un dataframe. """ # Importacion de librerias from lxml.etree import parse as lxml_parse from dateutil.parser impor...
import pygame import time import random pygame.init() display_width = 800 display_height = 600 black = (0,0,0) white = (255,255,255) red = (255,0,0) car_width = 74 global_speed = 0 #speed everything falls at, increase to make things faster speed_counter = 0 gameDisplay = pygame.display.set_mod...