text stringlengths 38 1.54M |
|---|
# Copyright (c) 2021 PaddlePaddle Authors. 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 appli... |
import csv
from django.core.cache import cache
from django.shortcuts import render
from django.conf import settings
from django.core.cache.backends.base import DEFAULT_TIMEOUT
from django.views.decorators.cache import cache_page
from django.http import JsonResponse, HttpResponse
from .utils import get_data, get_detai... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# filename: __logger.py
# Tencent is pleased to support the open source community by making Tars available.
#
# Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License"); you may not use this fil... |
def binarySearch(page, goal):
first_p, last_p, cnt = 1, page, 0
while first_p != goal and last_p != goal:
md_p = int((first_p+last_p)/2)
if goal >= md_p:
first_p = md_p
else:
last_p = md_p
cnt += 1
return cnt
for tc in range(int(input())):
p, a, b... |
from amuse.community.distributed.interface import DistributedAmuse, Pilot, Resource, Pilots, Resources
from amuse.test.amusetest import TestCase
from amuse.support import exceptions, options
from amuse.units import units
from amuse.rfi.channel import DistributedChannel
from amuse.community.bhtree.interface import ... |
'''Formats Biopython's Structure object as keras-compatable dataset.'''
import numpy as np
from package.dwt import DWT as DWT
class BatchManager():
def __init__(self, data, wavelet_size=4, verbose=False):
'''Manages a moving window over the dataset based on the given wavelet size.
Paramet... |
# -- encoding:utf-8 --
from pyimagepreprocess.datasets.Simpledatasetloader import datasetLoader
from pyimagepreprocess.preprocessing.simplepreprocessor import Simplepreprocessor
from pyimagepreprocess.preprocessing.imagetoarraypreprocessor import ImagetoArrayPreprocessor
from keras.models import load_model
from imutils... |
from django.contrib.auth import get_user_model
from django.test import TestCase
from ..models import Group, Post
User = get_user_model()
class GroupModelTest(TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.test_group = Group.objects.create(
title='lev_nikola... |
# Generated by Django 3.2.5 on 2021-08-05 09:16
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('polls', '0005_testrunquestion'),
]
operations = [
migrations.RemoveField(
model_name='testrunqu... |
__author__ = 'Alex'
from twisted.internet.protocol import Protocol # is instantiated per connection
from twisted.internet.protocol import Factory # saves persistent configuration
from twisted.internet.endpoints import TCP4ServerEndpoint
from twisted.internet import reactor
from twisted.protocols.basic import LineRec... |
from ZeroScenarioHelper import *
def main():
CreateScenaFile(
"m1090.bin", # FileName
"m1090", # MapName
"m1090", # Location
0x0072, # MapIndex
"ed7304",
0x00080000, # Flags
... |
#Tipos de elementos que son iterables
iterCadena = iter('cadena')
iterLista = iter(['l', 'i', 's', 't', 'a'])
iterTupla = iter(('t','u','p','l','a'))
iterConjunto = iter({'c','o','n','j','u','n','t','o'})
iterDiccionario = iter({'d': 1,'i': 2,'c': 3,'c': 4,'i': 5,'o': 6,'n': 7,'a': 8,'r': 9,'i': 10,'o': 11,})
print(i... |
# Written: 16-Jan-2020
# https://www.hackerrank.com/challenges/s10-weighted-mean/problem
# Enter your code here. Read input from STDIN. Print output to STDOUT
N = int(input())
X = list(map(int, input().split()))
W = list(map(int, input().split()))
xiwi = wi = 0
for i in range(N):
xiwi += (X[i] * W[i])
wi += ... |
from PIL import Image
import imagehash
import os
from pydub import AudioSegment
from tempfile import mktemp
import numpy as np
import os
import pylab
import librosa
import librosa.display
import sklearn
import matplotlib.pyplot as plt
from operator import itemgetter
from math import *
def getWavFromMp3(mp3filePath):
... |
import cv2
from PIL import ImageFont, ImageDraw, Image
capture = cv2.VideoCapture(0)
capture.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
while True:
ret, frame = capture.read()
#np_frame = Image.fromarray(frame)
#s_np_frame = cv2.resize(np_frame, (150, 200))
#frame ... |
def solution(phone_number):
answer = ''
leng = len(phone_number)
phone_number = phone_number[leng - 4:]
answer += '*' * (leng - 4) + phone_number
return answer |
import face_recognition
from PIL import Image,ImageDraw
import pymysql
import base64
import json
from sshtunnel import SSHTunnelForwarder
import face_recognition
SSH_PWD = base64.b64decode("MTMwNzEzMDc=").decode()
DB_PWD = MYSQL_PWD = base64.b64decode("MTIzNDU2").decode()
with SSHTunnelForwarder(
... |
import os
import sys
from time import sleep
from threading import Thread, Event
from pygsched.gssession import GSSession
import datastreams.pydsui as dsui
class ExampleThread(Thread):
LOOP_COUNT = 100000
def __init__(self, suffix, syncevent):
Thread.__init__(self, name='pyThread-%s'%suffix)
s... |
from rest_framework import serializers
from ..models import ClinicReview
class ReviewSerializer(serializers.ModelSerializer):
name = serializers.SerializerMethodField('get_name')
user_id = serializers.SerializerMethodField('get_user_id')
def get_name(self, obj):
return obj.user.user.name
def... |
# PEP 440 - version number format
VERSION = (0, 6, 1, 'dev0')
# PEP 396 - module version variable
__version__ = '.'.join(map(str, VERSION))
default_app_config = 'compressor_toolkit.apps.CompressorToolkitConfig'
|
#!/usr/bin/env python3
# função dict([]) - recebe tuplas, o primeiro item é a chave
myDict = dict([('nome', 'Fabio'), ('idade', 44)])
print(myDict)
# copiando dicionario
outroDict = myDict.copy()
print(outroDict)
print(id(myDict))
print(id(outroDict))
myDict['Tel']='99998888'
print(myDict)
myDict.update({'email... |
from .provider_base import ProviderConfig, ProviderBase, ProviderResult
from qgis.PyQt.QtCore import QUrl, QUrlQuery, QDateTime
from qgis.PyQt.QtNetwork import QNetworkRequest
from functools import partial
import os
import shutil
import re
import json
import logging
log = logging.getLogger('JRodos3 Plugin')
class Ca... |
"""asproject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
C... |
def insert_header(f):
f.write("""@@include('_head.html')
@@include('_nav.html', {
"navActiveItem": "examples"
})
<div class="auto wrap">
""")
def insert_section_start(f, label):
f.write("""<h2 class="mx20 f16" style="margin:16px 0 10px 95px;"><strong>{}</strong></h2>
<section ... |
import subprocess as sb
import re
import pdb
import threading
import time
import sys
fin = open('slurm_test.sh','r')
origlines = fin.readlines()
fin.close()
print origlines
fin = open('slurm_test.sh','w+')
fin.writelines(origlines[0:13])
lines = fin.readlines()
fin.close()
print lines
list = ['string1','string2','st... |
import time
from math import ceil
import geohash
import redis
from . import config
from .pipeline import preprocess_query
from .textutils.default import make_fuzzy, compare_ngrams, string_contain
from .utils import haversine_distance, km_to_score
DB = redis.StrictRedis(**config.DB_SETTINGS)
def token_key(s):
... |
#!/usr/bin/python3
def read_file(filename=""):
with open(filename, encoding='utf-8') as a_file:
for line in a_file:
print("{:s}".format(line), end="")
|
from enum import Enum
from firmware.firmware import Firmware
from network.remote_system import RemoteSystem
from router.memory import RAM, Flashdriver
class Mode(Enum):
"""
The Router can be in two modes: normal and configuration.
If the mode changes also the ip-address changes.
"""""
normal = 1
... |
import uuid
from app.db import db
from datetime import datetime
from sqlalchemy.orm import relationship
results = db.Table('results',
db.Column('domain_id', db.Integer, db.ForeignKey(
'domains_csv.id'), primary_key=True),
db.Column('search_id', db.String(256... |
# coding=utf-8
""" gw_functions.py
Variable (Giraldez and Woolhiser's)
L (L) : hillslope length (m)
alpha (alpha) : coefficient expressing surface conditions for the flow
t_rain : storm duration (s)
rain : rainfall intensity (m/s)
Ks : saturated hydraulic conductivity (m/s)
Ao ... |
# define routes
from app.api_2_0 import api
from app.api_2_0 import views
api.add_resource(views.UserSignup, '/auth/register')
api.add_resource(views.UserLogin, '/auth/login')
api.add_resource(views.CreateRide, '/users/rides')
api.add_resource(views.ManipulateRides, '/rides/<int:ride_id>')
api.add_resource(views.Reque... |
#!/usr/bin/env python3
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from faker import Faker
import json
from pathlib import Path
def start():
parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument(
"-n", "--number", dest="number", default=1000... |
repeat_time = raw_input()
repeat_word = raw_input()
for i in range(0,int(repeat_time)):
print(repeat_word)
|
import os, base64, hou
from Qt import QtCore, QtWidgets, QtCompat, QtGui
from Qt.QtWidgets import QFileDialog
sessID = ''
class debugWindow(QtWidgets.QMainWindow):
def __init__(self, rootPath, sessID,parent=None):
super(debugWindow, self).__init__(parent, QtCore.Qt.WindowStaysOnTopHint)
global sessID1
... |
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
ser = Series(np.arange(3.))
data = DataFrame(np.arange(16).reshape(4,4),index=list('abcd'),columns=list('wxyz'))
# [ ]切片
# 列选择,根据列索引,注意不能进行某个范围的多列选择比如data[['w':'z']],而只能指定某几列的多列选择data[['w','z']]
print( data['w'] ) #选择表格中的'w'列,使用类字典属... |
import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import time
from stockfish import Stockfish
stoc... |
import unittest
import random
from kombu_redis_priority.scheduling.weighted_prioritized_levels_with_round_robin import \
WeightedPrioritizedLevelsWithRRQueueScheduler
class TestPrioritizedLevelsWithRRQueueScheduler(unittest.TestCase):
BASE_CONFIG = {
0: ['TimeMachine', 'FluxCapacitor'],
1: ['19... |
# -*- coding:utf-8 -*-
import cv2
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
from funs import plotGrayHist,grayTransform,CLAHE
from funs import img3 as img
from funs import homofilter_s as homofilter
img=cv2.medianBlur(img, 3)
img[img<50]=np.min(img[img>0])
img=CLAHE(img... |
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
# Create your models here.
class Chat(models.Model):
user = models.ForeignKey(User)
message = models.CharField(max_length=300)
def __unicode__(self):
return self.message
|
def n_slices(n, list_):
for i in xrange(len(list_) + 1 - n):
yield list_[i:i+n]
def isSublist(sub_list, list_):
for slice_ in n_slices(len(sub_list), list_):
if slice_ == sub_list:
return True
return False
'''
read the line
get hand1, hand2
essayer les fonctions sur hand1, ha... |
import re
import ngram
import time
import random
starttime = time.time()
tweets = ""
t = ""
with open("mergfeih_tweets_small.txt","r",encoding = 'utf-8') as f1: #tweets
lines = f1.readlines()
interval = int(len(lines)*0.001)*10
i = interval
#print(interval)
randomline = []
while... |
nom=input("Quin és el teu nom?")
edat=input("Quina és la teva edat?")
print("Sòc",nom, "i tinc", edat, "anys") |
class Komentator:
def _powiadomOSmierci(self,organizm):
print(f"{organizm._getNazwa()} zginal")
def _rozmnazanieWiadomosc(self,organizm):
print(f"{organizm._getNazwa()} rozmnozyl sie") |
import os
"""
EXERCICE 1
1) Définition de liste en python:
une liste est un type de variable dans lequel on insert des éléments qui peuvent
être tout autre type de variables et même encore une liste
Correction: Une liste est une structure de donnees dans laquelle on ranger plusieurs
donnees ou vale... |
def extractLatLongFromNodes(node1, node2):
lats, longs = [], []
lats.append(node1.lat)
lats.append(node2.lat)
longs.append(node1.long)
longs.append(node2.long)
return lats, longs
class Path:
def __init__(self, path="", lat=None, long=None, node1=None, node2=None):
#Ini... |
import socket
import threading
class RequestSender(threading.Thread):
def prepare(self, host, port, message):
self.host = host
self.port = port
self.socket = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
self.data = message
def run(self):
self.socket.connect( (self.host, self.port) )
self.s... |
import re
import urllib
from time import sleep
import json
import pandas as pd
from itertools import chain
# This method finds the urls for each of the rosters in the NBA using regexes.
def build_team_urls():
# Open the espn teams webpage and extract the names of each roster available.
f = urllib.request.urlop... |
#!/usr/bin/env python
import X11
from X11 import display, window, wm
dpy = X11.Open()
root, parent, child, count = dpy.root.QueryTree()
assert root.value == dpy.root.value
for index in range(count):
print child[index].name
|
#!/usr/bin/env python3
# coding: utf-8
# File: check_redis.py
# Author: lxw
# Date: 5/31/17 9:41 PM
import redis
class CheckRedis:
REDIS_HOST = "192.168.1.29"
# REDIS_HOST = "127.0.0.1"
REDIS_PORT = 6379
REDIS_KEY_DOC_ID = "DOC_ID_HASH"
REDIS_KEY_TASKS = "TASKS_HASH"
REDIS_KEY_CNKI = "CNKI_PA... |
from django.conf import settings
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import IsAuthenticated
from ..serializers import (
FilletSerializer,
Fillet... |
import unittest
from unittest.mock import Mock
import sys
sys.path.insert(0, './rplugin/python3/deoplete')
sys.modules['sources.base'] = __import__('mock_base')
from sources import deoplete_elm # noqa
class SourceTest(unittest.TestCase):
def setUp(self):
self.source = deoplete_elm.Source(Mock())
... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '.\01_button_clicked.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
... |
import sys
_module = sys.modules[__name__]
del sys
calc_metrics = _module
dataset_tool = _module
generate = _module
metrics = _module
projector = _module
style_mixing = _module
custom_ops = _module
bias_act = _module
conv2d_gradfix = _module
conv2d_resample = _module
fma = _module
grid_sample_gradfix = _module
upfirdn2... |
import os
from dotenv import load_dotenv
load_dotenv()
IMAP_HOST = os.getenv('IMAP_HOST')
IMAP_USERNAME = os.getenv('IMAP_USERNAME')
IMAP_PASSWORD = os.getenv('IMAP_PASSWORD')
SMTP_HOST = os.getenv('IMAP_HOST')
SMTP_USERNAME = os.getenv('IMAP_USERNAME')
SMTP_PASSWORD = os.getenv('IMAP_PASSWORD')
S3_KEY = os.getenv(... |
import numpy as np
import cv2
# reads every single frame from the camera.
lf = cv2.VideoCapture(0)
#continue the displaying the video until user press key 'q' on keyboard.
while True:
# reads the frame.
sf_img_frm_ret, frame = lf.read()
#changing the width of the video captured.
width = int(... |
class Solution:
def addDigits(self, num: int) -> int:
if num // 10 <= 0:
return num
else:
digits = []
while num:
digits.append(num % 10)
num //= 10
next_num = sum(digits)
return self.addDigits(next_num)
t =... |
import sqlite3
import os.path
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
db_path = os.path.join(BASE_DIR, "companies.db")
with sqlite3.connect(db_path) as db:
cursor = db.cursor()
#resposta_db = db.execute('Select * from Equipment_Details')
#cursor.execute("INSERT INTO teste VALUES('Luciano', ... |
# """
# Plotting
# """
### pair plot ###
## plot the pairplot
#initial_pairs = sns.pairplot(model,diag_kind='kde')
# ### heatmap ###
# #correlation matrix
# corr = model.corr()
# # #initialize figure
# # fig, ax = plt.subplots(1,1, figsize = (1, 5), dpi=300)
# # plot the heatmap
# sns.heatmap(corr, annot = True,
... |
def solve(arr):
for x in range(max(arr)+1):
while arr.count(x)>1:
arr.remove(x)
return arr
def solve2(arr):
return list(dict.fromkeys(arr[::-1]))[::-1]
|
print('hello world')
print('this is my first try of git')
print('I first clone the project to my file')
print('then I git add, git status, git commit -m, git push')
print('finanlly, I have the access')
print('now i am using the github to process the code')
print('i would like to know the process and the difference')
... |
import datetime
import typing
import kubernetes.client
class V1TokenRequestSpec:
audiences: list[str]
bound_object_ref: typing.Optional[kubernetes.client.V1BoundObjectReference]
expiration_seconds: typing.Optional[int]
def __init__(
self,
*,
audiences: list[str],
bound_... |
"""
Calculo del volumen de un cilindro dados su altura y diametro.
"""
import math
diametro = float(raw_input('Introduzca el diametro (m): '))
altura = float(raw_input ('Introduzca la altura (m): '))
print 'El volumen del cilindro es:', math.pi * math.pow(diametro/2,2) * altura
|
from htmlgen.element import Element
class Division(Element):
"""An HTML division (<div>) element.
<div> elements are block-level elements without semantic meaning. They are
containers for styling or scripting.
>>> div = Division("Initial text. ")
>>> div.id = "my-block"
>>> div.a... |
#
# owid_cache.py
#
# Helpers for working with our cache in DigitalOcean Spaces.
#
from os import path
import logging
from typing import Optional
import boto3
from botocore.exceptions import ClientError
from owid.walden.ui import log, bail
SPACES_ENDPOINT = "https://nyc3.digitaloceanspaces.com"
S3_BASE = "s3://wa... |
# -*- coding: utf-8 -*-
# Setup
## Import Modules
# Commented out IPython magic to ensure Python compatibility.
## Import Packages
import pandas as pd
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import seaborn as sns
import time
from tensorflow import keras
from sklearn.neural_network ... |
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.views.generic.simple import direct_to_template
from google.appengine.api.images import Image
from upload.forms import UploadForm
from... |
#coding:utf-8
import sys
import lib.util as util
def start():
util.clear()
util.banner()
print(" HELP\n")
print("This software can convert positive numbers from a base to another base.\n")
print("1. Enter the base your want to use")
print("2. Enter the number you want to convert")
pr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 3.6.0-bd605d07 (http://hl7.org/fhir/StructureDefinition/SearchParameter) on 2018-12-20.
# 2018, SMART Health IT.
from . import domainresource
class SearchParameter(domainresource.DomainResource):
""" Search parameter for a resource.
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import tkinter
class MyApp(tkinter.Frame):
def __init__(self, master=None):
super().__init__(master)
self.pack()
self.eintraege = ["Berlin", "London", "Moskau", "Ottawa", "Paris", "Rom", "Tokio", "Washington DC"]
self.lb = tkin... |
import torch
import numpy as np
import torch.nn as nn
import torch.optim as optim
import networks.networks as net
import torchvision as tv
from torchvision import transforms
from torch.utils.data import DataLoader
from data.idadataloader import DoubleDataset
import torch.nn.functional as F
root = '/home/fcdl/dataset/'... |
import argparse
import numpy as np
from sklearn.cluster import KMeans
import sklearn.decomposition
from mnist import load_mnist
import gmm
import classifier
import kmeans as kmeans_
parser = argparse.ArgumentParser(
prog='em',
description='train model with em'
)
parser.add_argument('--path', default='/home/... |
# Module Player.py
# Receives player input
# integrate user mouse input eventually with PyMouse
# https://stackoverflow.com/questions/25848951/python-get-mouse-x-y-position-on-click
if __name__ == "__main__":
import os
print("Do not run {0}".format(os.path.basename(__file__)))
raise ImportError
else:
... |
# encoding=utf-8
import jieba
import jieba.posseg
import os
class ContentParser:
def __init__(self, diction=None, content=None):
self.diction = diction or "assets/location.dict"
self.content = content or ""
jieba.load_userdict(self.diction)
def getLocations(self):
seg_list = j... |
'''
Experimentation.
Intuitively, we have 10^n/a + 10^n / b = p,
so 10^n / a and 10^n / b need to have the same denominator in their fully reduced form.
Call this denominator x and write a = dx, b = ex.
then d | 10^n and e | 10^n.
So we look at all numbers that are 10^n over something, then all pairwise sums of s... |
x, y, z = map(int, input().split())
a, b, c = map(int, input().split())
argument = a >= x and b + a >= x + y and a + b + c >= x + y + z
print('YES' if argument else 'NO')
|
class Product():
def __init__(self, name, stock_price, final_price):
self.name = name
self.stock_price = stock_price
self.final_price = final_price
def profit(self):
return self.final_price - self.stock_price
class Laptop(Product):
def __init__(self, name, stock_price, fin... |
n,k=map(int,input().split())
ten=1
i=1
temp=str(n)
while(len(temp)-len(temp.rstrip('0'))<k):
ten=10*i
temp=str(n*ten)
i+=1
print(temp) |
import hmac, base64, struct, hashlib, time
def get_hotp_token(secret, intervals_no):
key = base64.b32decode(secret, True)
#decoding our key
msg = struct.pack(">Q", intervals_no)
#conversions between Python values and C structs represente
h = hmac.new(key, msg, hashlib.sha1).digest()
o = o = h[19... |
class Solution(object):
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums = sorted(nums)
self.ans = []
self.generate(nums, [])
return self.ans
def generate(self, nums, result):
if not nums:
... |
import pygame,random
pygame.init()
display_height = 600
display_width = 800
display = pygame.display.set_mode((display_width,display_height))
block = 10
clock = pygame.time.Clock()
def randomColor(bricks):
color = []
for i in bricks:
color.append((random.randrange(30,255),random.randrange(30,255),random.randra... |
import os
import numpy as np
from datetime import datetime
def run(input_filename):
input = open(input_filename).read()
input = input.split('\n')
n_cases = int(input[0])
result_dict = {}
for case in range(1, n_cases + 1):
start = int(input[case])
last_number = count_sheep(start... |
import torch
from torch import nn
import transformers
from config import config
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.titles_model = transformers.AutoModel.from_pretrained(config.MODEL_PATH)
self.abstracts_model = transformers.AutoModel.from_pretra... |
from vpython import *
#display(width = 1300, height = 1000)
projectile = sphere(pos=vector(-5,0,0),
radius = 0.1,
color = color.red,
make_trail= True)
projectile.speed = 3.2
projectile.angle = 75 * 3.141459 / 180 #initial angle from x axis
projectile.velocity =... |
from __future__ import print_function
from collections import defaultdict
import collections
from datetime import datetime
import os
import json
import logging
import numpy as np
import torch
from torch.autograd import Variable
##########################
# Torch
##########################
def detach(h):
if typ... |
import jdatetime, math
class Projects:
ProjectCount = 0
def __init__(self):
Projects.ProjectCount += 1
def __del__(self):
Projects.ProjectCount -= 1
def initial_Data(self):
self.ProjectID = None
self.ProjectName = None
self.Client = None
self.Supervisor =... |
#!/usr/bin/env python
"""
MIT License
Copyright (c) 2017 Raphael "rGunti" Guntersweiler
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the right... |
import pandas as pd
from sklearn import metrics
import numpy as np
df = pd.read_csv("D:/coursera/7/classification.csv")
clf_table = {"tp": (1, 1), "fp": (0, 1), "fn": (1, 0), "tn": (0,0)}
#Заполнение таблицы ошибок классификации
for name, res in clf_table.items():
clf_table[name] = len(df[(df["true"] == res[0]) ... |
import collections
import json
import operator
import os
import pytest
from resolvelib.providers import AbstractProvider
from resolvelib.resolvers import Resolver
Requirement = collections.namedtuple("Requirement", "container constraint")
Candidate = collections.namedtuple("Candidate", "container version")
INPUTS_... |
import csv,itertools
def cmp(t1, t2):
return sorted(t1) == sorted(t2)
def findsubsets(S,m):
return set(itertools.combinations(S, m))
trans=[]
items=[]
with open('sample123.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
for row in readCSV:
trans.append(row)
... |
"""
File: ejemplo_inicial.py
"""
import turtle
window = turtle.Screen()
t = turtle.Turtle()
t.forward(50)
t.left(90)
t.forward(50)
t.left(90)
t.forward(50)
t.left(90)
t.forward(50)
t.left(90)
turtle.mainloop()
|
def test_h1_css(self):
self.browser.get('http://localhost:8000')
h1 = self.browser.find_element_by_tag_name("h1")
print (h1.value_of_css_property("color"))
self.assertEqual(h1.value_of_css_property("color"), "rgb(255, 192, 203)") |
class Piece:
def __init__(self, suit, number=0):
self.number = number
self.suit = suit
def name(self):
return ("" if self.number == 0 else (str(self.number) + " ")) + self.suit |
from django.shortcuts import render
from createPost.models import createDBPost
from .forms import createPost
from django.core.files.storage import FileSystemStorage
from django.views.generic import TemplateView
#création de la page de création de posts
class create(TemplateView):
template_name='createPost/create.h... |
"""
Parse DX cluster telnet spots and print to STDOUT on:
* Match against pre-defined list of watched calls.
* Match against missing DXCC entities in ClubLog.
"""
import sys
import telnetlib
import time
import re
from urllib.request import urlopen
import json
from configparser import ConfigParser
import argpa... |
from binary_tree import *
def level_order_bottom(root):
if root is None:
return None
q = []
q.append(root)
res = []
while q:
data = []
for _ in range(len(q)):
node = q.pop()
data.append(node.val)
if node.left:
q.insert(0... |
from django.db import models
# Create your models here.
class Factura(models.Model):
numero_factura = models.AutoField(primary_key=True)
anio = models.IntegerField()
fecha_emision = models.DateField(auto_now_add=True)
cliente_nombre = models.CharField(max_length=30)
cliente_direccion = models.Ch... |
# TEXT ANALYSIS ----------- CREATING A CLASS WITH METHODS
# You have been recruited by your friend, a linguistics enthusiast,
# to create a utility tool that can perform analysis on a given piece of text.
# Complete the class 'analysedText' with the following methods -
class analysedText(object):
# Constructor - Tak... |
from PIL import Image as img
from sys import argv
path = argv[1]
try:
image = img.open(path, "r")
except:
print("Image might be missing or in an unknown format")
quit()
squares_list = []
for a in range(image.height):
for b in range(image.width):
c = image.getpixel((a, b))
color = "{0}, {1}, {2}".forma... |
import time
import numpy as np
import src.problem.H1 as H1
import src.problem.H2 as H2
import src.problem.H3 as H3
import src.problem.H4 as H4
import src.problem.H5 as H5
import src.problem.H6 as H6
import src.problem.H7 as H7
import src.problem.H8 as H8
import src.problem.H9 as H9
import src.problem.H10 as H10
import ... |
from django.db import models
from django.db import IntegrityError
from django.core.validators import MinValueValidator, MaxValueValidator
from django_countries.fields import CountryField
n_situ = 12
n_items = n_situ * 5
# Create your models here.
class Subject(models.Model):
SEX_CHOICES = (
('0', 'Muje... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.