text stringlengths 38 1.54M |
|---|
import keras
import time
from keras.datasets import cifar10
from keras.models import Sequential
from keras import optimizers
from keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense
from pathlib import Path
from matplotlib import pyplot as plt
# Loading CIFAR-10 data sets
(x_train, y_train), (x_test, y_t... |
# In the most cases it is enough to train ones with fixed sn and sf (b were assumed to be always fixed)
# and optional S, U depending on the data-set with about 50 to 100 iterations
owd = 'C:/Users/flo9fe/Desktop/GIT_IP/python_ip'
#owd = '/usr/local/home/GIT_IP/python_ip'
import os;
os.chdir(owd)
from LVMvSSG... |
import objc
import sys
from PyObjCTools.TestSupport import TestCase, skipUnless
NSObject = objc.lookUpClass("NSObject")
NSArray = objc.lookUpClass("NSArray")
class TestGenericClasses(TestCase):
@skipUnless(sys.version_info[:2] >= (3, 9), "Feature requires python 3.9")
def test_generic_classes(self):
... |
# code for image segmentation and detection
#by tamilselvan
#02,July 2018
#importing necessary libraries.
import cv2
import numpy as np
import os
import time
from PIL import Image
from matplotlib import pyplot as plt
import csv
#for writing into csv file.
f = open('Sample-Output.csv','w')
f.write('FileName,GCPLocatio... |
# 二分搜索变形之:查找target在升序变形数组中的位置
def t003(nums,target):
def search_one(nums, target):
l = 0
r = len(nums) - 1
while l <= r:
mid = l +(r-l) // 2
if nums[mid] == target:
return mid
if nums[mid] >= nums[l]:
if nums[mid]>target>... |
import time
import copy
import numpy as np
import pandas
class matrix():
def __init__(self,x=None,row_names=None,col_names=None):
self.col_names,self.row_names = col_names,row_names
self.x = x
if x is not None:
if row_names is not None:
assert len(row_names) == x... |
N = 1010
n, m = map(int, input().split())
f = [[0] * N for _ in range(N)]
a = ' ' + input()
b = ' ' + input()
for i in range(1, n + 1):
for j in range(1, m + 1):
f[i][j] = max(f[i-1][j], f[i][j-1])
if a[i] == b[j]: f[i][j] = max(f[i][j], f[i-1][j-1] + 1)
print(f[n][m])
|
import sys
from collections import deque
while True:
balanced = True
line = sys.stdin.readline().rstrip()
if line==".":
exit()
stack = deque()
i = 0
while line[i]!=".":
if ((line[i]=="(") | (line[i]=="[")):
stack.append(line[i])
elif ((line[i]==")") | (line[i... |
class BaseBatchfile:
def __init__(self, filename):
self.filename = filename
self.__dict = {"filename": filename}
def set(self, key, value):
self.__dict[key] = value
def get(self, key, default = None):
if key in self.__dict:
return self.__dict[key]
return... |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 7 23:23:39 2020
@author: Avdhesh Kumar
"""
import os
import time
import requests
import sys
def retrieve_html():
for year in range(2013, 2018):
for month in range(1,13):
if(month < 10):
url='http://en.tutiempo.net/climate/0{}-{}... |
from google.appengine.api import background_thread
from threadtest import TestThreadIF
class TestBackgroundThread(TestThreadIF, background_thread.BackgroundThread):
def __init__(self, name):
background_thread.BackgroundThread.__init__(self, name=name)
self.name = name
if __name__ == '__... |
number=int(input("Please enter the number: "))
for i in range(1,number+1):
print(i, "X",number,"=",i*number) |
def weareintrouble(a_smiles,b_smiles):
if a_smiles ==True and b_smiles== True:
return True
elif a_smiles == False and b_smiles==False:
return True
else:
return False
def int_sum(a,b):
if a==b:
return (2*(a+b))
else:
return a+b
def hours(h):
... |
import nltk
import time # For estimate time complexity
import math # For score system
import csv # For output
import os.path # For storing data, which take much time at birth CONVENIENCE
import pickle # For storing data, which take much time at birth CONVENIENCE
import random # For diverse phrase
from nltk.cor... |
# Generated by Django 3.1.1 on 2020-09-29 14:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fichero_alumnos', '0010_auto_20200929_1115'),
]
operations = [
migrations.AlterField(
model_name='alumno',
name='deu... |
import numpy as np
from easydict import EasyDict as edict
cfg = edict()
cfg.test_ratio=0.1
cfg.train_list = ["training.txt"]
cfg.test_list = "validation.txt"
cfg.data_dir='crop'
|
from urllib.parse import urlencode, quote_plus, unquote
from urllib.request import urlopen, Request
import dateutil.parser
import xmltodict
from rest_framework.response import Response
from rest_framework.views import APIView
from config.settings import config
from .models import Content
decode_key = unquote(config[... |
BASE_QUANTITY = 48
SUGAR_CUPS = 1.5
BUTTER_CUPS = 1
FLOUR_CUPS = 2.75
num_cookies = int(input("Enter the number of cookies you want to make: "))
sugar_needed = num_cookies * SUGAR_CUPS / BASE_QUANTITY
butter_needed = num_cookies * BUTTER_CUPS / BASE_QUANTITY
flour_needed = num_cookies * FLOUR_CUPS / BASE_QUANTITY
print... |
import re
from .stringbuilder import StringBuilder
OPTION_REGEX = re.compile(' -[a-zA-Z]+')
FLAGS_REGEX = re.compile('-')
SPACE_REGEX = re.compile(' ')
EMPTY_REGEX = re.compile('')
NUMERIC_REGEX = re.compile('\d+(?:\.\d+)?')
#replace occurances of a substring from the back
def rreplace(s, old, new, occurrence):
li... |
from django.contrib import admin
from enrol.models import Enrol,Pay
# Register your models here.
class EnrolAdmin(admin.ModelAdmin):
list_display = ('student','course','enroldate')
class PayAdmin(admin.ModelAdmin):
list_display = ('pnumber','paymethod')
admin.site.register(Enrol, EnrolAdmin)
admin.sit... |
"""
Copyright (c) 2017 Columbia University.
Network Security Lab, Columbia University, New York, NY, USA
This file is part of HVLearn Project, https://github.com/HVLearn/.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"),... |
# -*- coding: utf-8 -*-
"""
pyB64Pic
~~~~~~~~
Powered by AnClark
A simple toolkit to deal with image used on the Web among files, byte streams, and Base64 strings.
Also, it can support convert image into a DATA URL. Data URL is popular since HTML5 was born.
:copyright: (c) 2017 by AnClark Liu... |
from django.db import models
from django.contrib import admin
from apps.tenants.models import *
from apps.users.models import User
class Anken_Karte_DispConfig(TenantBaseModel):
"""
案件カルテ表示設定のテーブル
[更新説明]
・案件カルテ画面で、各カードの位置情報を変更した際に更新する。
・user_idでDeleteした後、Insertを行う。
"""
class Meta:
db_table = 'ds_an... |
from src.cryptography import encrypt, decrypt, address, messages
from src.check import operations, connect_reply, command_reply, download_reply, encryption_reply, OK
from hashlib import sha256
import time
import sqlite3 as sql
import ConfigParser
import getpass
import socket
import os
import requests
import os.path
de... |
import os
import json
from click.testing import CliRunner
from flask_jsondash import model_factories
from flask_jsondash.settings import CHARTS_CONFIG
from conftest import read
_db = model_factories.adapter
def test_get_random_group():
conf_vals = CHARTS_CONFIG.values()
data = model_factories.get_random_gr... |
import string
import random
menu = ("1: Print List\n"
"2: Add To Head\n"
"3: Add To Tail\n"
"4: Remove From Head\n"
"5: Remove From Tail\n"
"6: Find Index of Value\n"
"7: Remove Node of Value\n"
"0: Exit\n")
def switch_menu(argument, listHead):
switcher = {... |
# -*- coding:utf-8 -*-
# 如何读物excel文件
# 使用pip安装。pip install xlrd xlwt
# 使用第三方库xlrd和xlwt,这两个库分别用于excel的读和写
import xlrd
book = xlrd.open_workbook('demo.xlsx')
book.sheets()
sheet = book.sheet_by_index(0) # 第一个sheet
print sheet.nrows # 行数
print sheet.ncols # 列数
cell = sheet.cell(0, 0)
print cell.ctype #类型
print cell.... |
#
# Copyright (c) 2010-2017 Fabric Software Inc. All rights reserved.
#
class Visibility(object):
public = 0
protected = 1
private = 2
|
import tkinter as tk
import mysql.connector
#Connects to the database
mydb = mysql.connector.connect(
host = "localhost",
user = "root",
passwd = "sD6G7Bx@f8cve$i3",
database = "forum"
)
#Allows editing of the database
mycursor = mydb.cursor()
#Displays the change password page UI
def displayUI(window, usern... |
from django import forms
from . models import Customer
from django.forms.widgets import PasswordInput
class SignupForm(forms.Form):
user_name = forms.CharField()
email = forms.EmailField()
password = forms.CharField(widget=forms.PasswordInput)
class SignupModelForm(forms.ModelForm):
class Meta:
... |
#문제: 두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.
#입력: 입력은 여러 개의 테스트 케이스로 이루어져 있다.각 테스트 케이스는 한 줄로 이루어져 있으며, 각 줄에 A와 B가 주어진다. (0 < A, B < 10)
#출력:각 테스트 케이스마다 A+B를 출력한다.
A,B=1,1
while A>0 and B<10:
try:
A,B=map(int,input().split())
print(A+B)
except:
break
#try는 밑에거를 바로 실행하... |
# vague
import time
from requests_html import HTMLSession
session = HTMLSession()
r = session.get('http://monstersvault.com/')
rand_page=list(r.html.find('#random-article')[0].links)[0]
print(rand_page)
r = session.get(rand_page)
# TODO Find a way to check if the element exists without using try/except and use it for... |
#coding: utf-8
import select
import socket
import os
import Queue
# 回显服务器:
# 服务器:python ./server.py
# 客户端:telnet 127.0.0.1 8888
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
server.bind(("0.0.0.0", 8888))
server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
server.listen(100)
# 连接进来的客户端
connectio... |
# Leetcode 740. Delete and Earn
# Time Complexity : O(n) where n is the largest number of the array
# Space Complexity : O(n)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach: Create a value array that holds the values of the nums array in a sorted order... |
# -*- coding: utf-8 -*-
#script containing all pertinent tasks to prepare for software termination.
#successful completion of this process at last runtime, will skip extra validation
#steps on next run
def shutdown(config,interinput,interoutput):
#check for lingering runtime errors
#finishing writing log queu... |
# coding: utf-8
import numpy as np
from scipy.signal import get_window
from scipy.signal import fftconvolve
import audioproc as ap
# generate swept-sine signal
def gentsp(n=18):
N = 2 ** n
m = N // 4
SS = np.r_[
np.exp(-1.j * np.pi / N * np.arange(0, N // 2 + 1) ** 2),
np.exp(1.j * np.pi /... |
import autoarray as aa
import numpy as np
class TestDataVectorFromData:
def test__simple_blurred_mapping_matrix__correct_data_vector(self):
blurred_mapping_matrix = np.array(
[
[1.0, 1.0, 0.0],
[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[... |
from django.shortcuts import render, redirect, reverse, HttpResponse
from django.contrib import messages
from products.models import Product
from Profile.models import Profile
# Create your views here.
def shopping_bag(request):
"""A view to show the shopping bag"""
user = Profile.objects.filter(user=request... |
import datetime
import smtplib
from email.mime.text import MIMEText
import pandas as pd
import pymysql
import requests
print("核心数据自动发送邮箱")
class getFromDataBase():
def __init__(self):
self.con_mall = pymysql.connect(host='106.75.233.242', port=28306, user='leizhen',
... |
from django.urls import path
from . import views
urlpatterns =[
path('', views.my_cart, name='shopcart-index'),
path('add_to_cart/<int:id>', views.add_to_cart, name='add_to_cart'),
path('delete_from_cart/<int:id>', views.delete_from_cart, name='delete_from_cart')
] |
#!/usr/bin/python3
from Crypto.Cipher import AES
import itertools
import random
from util import get_random_bytes, chunk, pkcs7_pad, pkcs7_unpad, slurp_base64_file, hexquote_chars
from s1 import xor_buf
from base64 import b64decode
from random import randrange
def main():
c16()
def c16():
block_size = 16
... |
from django.shortcuts import render, redirect
from django.utils import timezone
from .models import Rating, Album
from .forms import SearchForm, SearchResult, RatingForm
import requests
import json
# Create your views here.
def ratings_list(request):
ratings = Rating.objects.all().order_by('-updated')
return render(... |
import vlc
import time
addr = '172.14.1.194'
url = f"rtsp://{addr}/live"
# The cameras appear to restart WiFi if they don't receive an RTCP Receiver Report regularly.
# FFMpeg and anything that depends on this don't appear to send these enough?
#Basic Recording
# cvlc rtsp://172.14.1.194/live --sout file/ts:stream.m... |
# -*- coding: utf-8 -*-
# @Author: Li Qin
# @Date: 2020-02-24 09:06:23
# @Last Modified by: Li Qin
# @Last Modified time: 2020-02-24 10:14:19
import compileall
import glob
import re
import timeit
def show(title):
print(title)
for filename in glob.glob('example/**', recursive=True):
print(f' {file... |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
import numpy as np
from ._segmentation import _ve_step, _interaction_energy
TINY = 1e-300
NITERS = 20
BETA = 0.2
VERBOSE = True
def print_(s):
if VERBOSE:
print(s)
def gauss_dist(x, mu, s... |
from flask import Flask, request
from flask_cors import CORS
import json
app = Flask(__name__)
CORS(app)
explanations = [
{
'title': 'What does it mean?',
'body': 'Green vines attached to the trunk of the tree had wound themselves toward the top of the canopy. Ants used the vine as their private ... |
#!/usr/bin/python
# Args are:
# change id
# number
# workname
import sys
import utils
utils.recheck(sys.argv[1], sys.argv[2], workname=sys.argv[3])
|
# importing pandas
import pandas as pd
# making dataframes from lists using pandas
names = ['United States', 'Australia', 'Japan', 'India', 'Russia', 'Morocco', 'Egypt']
dr = [True, False, False, False, True, True, True]
cpc = [809, 731, 588, 18, 200, 70, 45]
# making dictionary from above lists
my_dict= {'country... |
from django.shortcuts import render, get_object_or_404
from django.views import generic
from django.views.generic import FormView
from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponseRedirect
from .models import Post, Comment, Category
from .forms import CommentForm
class IndexView(ge... |
from collections import Counter
from matplotlib import pyplot as plt
import numpy as np
import cv2
class matcher:
"""
Class for finding candidate map for each image
Obtain homography matrix between an image pair based on candidate map
"""
def __init__(self, img_pts_dict, m_candidate, lowe_ratio, ... |
# -*- coding: utf-8 -*-
import maya.cmds as cmds
import sys
import os
import json
import codecs
from functools import partial
#######################################
import os.path
import shutil
import datetime
import xgenm as xg
#######################################
class Tt_FileBackUp:
ExFrame... |
from copy import deepcopy
from typing import List
from typing import Dict
def shipment(items: List[Dict], drone: Dict, trip: int = 1, initial: bool = True) -> None:
if initial:
# sort items by weight from heavier to lighter
# do this only for the first function call (initial=True)
items.s... |
import cv2
import numpy as np
import math
import json
from skimage.feature import hog
#### Cropping functions ####
BOUNDING_BOX_FACTOR = 4/3
RESIZE_IMG_SIZE = (96, 96)
NUMBER_OF_BINS = 9
CELL_SIZE = (16, 16)
BLOCK_SIZE = (2, 2)
count = 0
def crop_image(img, x1, y1, x2, y2):
# (x1, y1) is top-left corner of where i... |
# Create your views here.
from django.contrib.auth import login, authenticate, logout
from django.views.generic.base import View
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
class login(View):
def get(self,request):
return render(this, "login.html")
def p... |
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 18 03:21:31 2018
@author: yahia
"""
def pancakeSort(arr, n):
Current_Stack = n
while Current_Stack > 1:
mi = arr[:Current_Stack].index(max(arr[:Current_Stack]))
if mi != Current_Stack-1:
arr[:mi+1] = arr[:mi+1][::-1]
arr[:... |
# encoding: utf-8
from __future__ import unicode_literals, print_function
__all__ = ['gen']
from string import Template
from src.parse import parse
from src.vm import instructions, pExpr
try:
from io import StringIO
except ImportError:
from StringIO import StringIO
prologue = Template('''#include <stdio.h>... |
me0 = "test_etaCas"
import numpy as np
import scipy as sp
from scipy.optimize import curve_fit
from matplotlib import pyplot as plt
from matplotlib.ticker import MaxNLocator, NullLocator
import os, optparse, glob, time
from LE_Utils import filename_par, fs, set_mplrc
from LE_CSim import force_mlin
set_mplrc... |
#!/usr/bin/python3
import random
class pageInfo:
def __init__(self, k):
self.hist = [0] * k
self.last = 0
self.CRP = 0;
def getHist(self):
return self.hist
def getLast(self):
return self.last
def getCRP(self):
return self.CRP
... |
def swap(brickor, i, d):
temp = inverted([brickor.pop(i) for _ in range(2)])
return brickor + temp if d else temp + brickor
def unswap(brickor, i, d):
for b in reversed(inverted([brickor.pop(p if d else 0) for p in range(-2, 0)])):
brickor.insert(i, b)
return brickor
def inverted(r):
return ... |
#!/usr/bin/python3
"""
This module defines save_to_json_file function.
"""
import json
def save_to_json_file(my_obj, filename):
"""
writes an Object to a text file, using a JSON representation
"""
with open(filename, "w") as myfile:
json.dump(my_obj, myfile)
|
import cv2
import numpy as np
import matplotlib.pyplot as plt
import os
import sys
def line_seg(path,filename):
# Image sectioning
image = cv2.imread(path+'/'+filename)
height, width = image.shape[:2]
image.shape
# Let's get the starting pixel coordiantes (top left of cropped bottom)
start_row... |
from tests.integration.api_test_suite import APITestSuite
class TestITRegistrationAPI(APITestSuite):
async def test_register_a_new_user(self):
response = await self.register_user()
self.assertEqual(201, response.status)
self.assertEqual(self.JSON, response.content_type)
b... |
# def test(N):
# if N == 0:
# return -1
# result = [_ for _ in xrange(10)]
# for i in xrange(1, 10001):
# k = N * i
# m = str(k)
# for s in m:
# temp = int(s)
# if temp in result:
# result.remove(int(s))
# if len(result) == 0:
#... |
#!usr/bin/env python
# -*- coding : utf-8 -*-
# 本课概要
# • 浏览器伪装技术原理
# • 浏览器伪装技术实战
# 浏览器伪装技术原理:在 header中加入user-agent伪装成为浏览器
# 我们可以试试爬取csdn博客,我们发现会返回403,因为对方服务器会
# 对爬虫进行屏蔽。此时,我们需要伪装成浏览器才能爬取。
# 浏览器伪装我们一般通过报头进行,接下来我们通过实战分析一下
# 浏览器伪装技术实战
# 由于urlopen()对于一些HTTP的高级功能不支持,所以,我们如果要修
# 改报头,可以使用urllib.request.build... |
import json
import io
from Ironscales import fetch_incidents
def util_load_json(path):
with io.open(path, mode='r', encoding='utf-8') as f:
return json.loads(f.read())
def test_ironscales_fetch_incident(mocker):
incidents_mocked_data = util_load_json('test_data/test_get_open_incidents.json')
las... |
# make sure pickle is imported
import pickle
class Dataset(object):
"""An abstract class representing a Dataset.
All other datasets should subclass it. All subclasses should override
``__len__``, that provides the size of the dataset, and ``__getitem__``,
supporting integer indexing in range from 0 to ... |
class Solution(object):
def majorityElement(self, nums):
"""
给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在众数
---
:type nums: List[int]
:rtype: int
"""
dict = {}
n = len(nums)
flg = n//2
i = 0
while i < n:
if nums[i] in dict:
dict[nums[i]] += 1
if dict[num... |
# coding: utf-8
from django.conf import settings
from django.db import models
from django.db.models import signals
from django import dispatch
from pg_fts.fields import TSVectorField
from market.core import models as core_models
class VendorSearch(models.Model):
"""Model pointing to the original searched model.""... |
import os
import tensorflow as tf
import numpy as np
class TextFiles(tf.data.Dataset):
def __init__(self, directory, glob, shuffle=True):
self._directory = os.path.realpath(directory)
self._glob = glob
dataset = tf.data.Dataset.list_files(os.path.join(self._directory, self._glob),
... |
import sys
number1 = int(input("Enter the first number: "))
number2 = int(input("Enter the second number: "))
try:
print(number1/number2)
except ZeroDivisionError:
print("You can not divide a by zero!!!!")
except OverflowError:
print("You can not divide by a number so small")
except ValueEr... |
from django.conf import settings
# Mailing
from django.contrib import messages
from django.core.mail import send_mail, EmailMessage
# Vistas
from django.core.exceptions import ObjectDoesNotExist
from django.shortcuts import render, redirect, HttpResponseRedirect, get_object_or_404, get_list_or_404
from django.views.g... |
from django.db import models
from datetime import datetime
from django.contrib.auth.models import AbstractUser
# class Category(models.Model):
# name = models.CharField(max_length=100)
# date_created = models.DateField(auto_now_add=True)
# slug = models.SlugField()
# def __str__(self):
# return self.name
# def... |
class NoTransformation:
"""
Implements basic parameter transformation strategy -
prameter is left unmodified.
"""
def eval(self, value):
return value
class FormatTransformation:
"""
Implements basic interpolation transformation startegy.
Parameter value is transformed through ... |
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import pandas as pd
ini = pd.read_excel('3ini.xlsx')
il = ini[0].values.tolist()
gmail_user = il[0]
gmail_password = il[1]
subject = il[2]
body = il[3]
df = pd.read_excel('2send.xlsx').iloc[:,0:... |
try:
from pyscreenshot import grab
except ImportError as e:
print str(e)
def screenshot():
try:
im=grab()
im.save('scr.png')
except Exception:
pass
#screenshot()
|
import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
import time
import random
from discord import Game
Client = discord.client
client = commands.Bot(command_prefix = '!')
Clientdiscord = discord.Client()
@client.event
async def on_member_join(member):
... |
import sys
import numpy as np
from sklearn.metrics import average_precision_score
def mean_average_precision(sort_data):
#to do
count_1 = 0
sum_precision = 0
for index in range(len(sort_data)):
if sort_data[index][1] == 1:
count_1 += 1
sum_precision += 1.0 * count_1 / (i... |
# Generated by Django 3.0.5 on 2020-05-07 16:09
from django.db import migrations
import wagtail.contrib.table_block.blocks
import wagtail.core.blocks
import wagtail.core.fields
import wagtail.images.blocks
class Migration(migrations.Migration):
dependencies = [
('base_pages', '0004_auto_20200506_1628'),... |
#!/usr/local/bin/python3.8
# polyFitter.py
# 6/21/2021
# Aidan Gray
# aidan.gray@idg.jhu.edu
#
# This script reads in a csv file containing calibration data and
# fits a Polynomial Series to it.
from matplotlib import pyplot as plt
from polyFit import polyFit
import numpy as np
import sys
import csv
import os
### How... |
# Python 3
import sys
class Rectangle:
def __init__(self, x1, y1, x2, y2):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
def pointWithin(self, x, y):
if x >= self.x1 and x <= self.x2:
if y >= self.y2 and y <= self.y1:
return Tru... |
from django.urls import path, re_path
from . import views
app_name = "encyclopedia"
urlpatterns = [
path("", views.index, name="index"),
re_path(r"^wiki/(?P<title>\w*)/$", views.wiki, name="wiki"),
path("search", views.search, name="search"),
path("new", views.new, name="new"),
path("edit/<str:tit... |
class NiceFormatter(object):
def print(self, triples):
previous_page_url = None
previous_link_type = None
for page_url, link_type, link_url in triples:
if page_url != previous_page_url:
print(page_url)
previous_page_url = page_url
if l... |
from fastapi.encoders import jsonable_encoder
from fastapi.exception_handlers import request_validation_exception_handler
from fastapi.exceptions import RequestValidationError
from starlette.requests import Request
from starlette.responses import JSONResponse
from .responses import fhir_rest_response
from fhirpath.util... |
from unittest import mock
import json
from django.http import JsonResponse
from django.template.response import TemplateResponse
from django.test import Client, modify_settings
def test_get_request_graphiql():
client = Client()
response = client.get(
'/graphql',
)
assert isinstance(response, ... |
from csv import DictReader
from collections import defaultdict
from sys import maxsize
class Purchase:
def __init__(
self, city, zipcode, state, beds,
baths, sq__ft, home_type, sale_date, price,
latitude, longitude):
self.longitude = longitude
self.latitude = la... |
# Elaborar um programa que efetue a leitura de um número inteiro e apresentar uma mensagem informando
# se o número é par ou ímpar.
print('Este app identifica se o numero é par ou impar')
a=int(input('Digite um número: '))
if a%2==0:
print ('Este numero e PAR')
else:
print('Este numero e IMPAR') |
# Generated by Django 3.0.8 on 2020-07-15 02:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('foods', '0005_auto_20200715_0154'),
]
operations = [
migrations.AddField(
model_name='food',
name='cover',
... |
import json
import numpy as np
import time
import imageio
import uuid
from AliSdkApp import AliSdkApp
class HandKeypointResult:
__slots__ = ['kps_conf', 'box_conf', 'kps', 'box', 'applied_wh', 'im_wh']
def __init__(self, d: dict=None):
self.kps_conf = None
self.box_conf = None
self.kp... |
import pandas as pd
import numpy as np
from typing import Dict, List
import csv
import torch
def get_glove_vectors(path):
df = pd.read_csv(path, sep=' ', header=None, engine='python',
quoting=csv.QUOTE_ALL, error_bad_lines=False)
token2id = {t: i for i, t in enumerate(df.iloc[:, 0])}
... |
import pygame
import sys
screen_width = 1000
screen_height = 1000
block_size = 50
minigameID = 5
class Player:
def __init__(self,player_nmbr,network):
self.net = network
self.body = []
self.moved = True
self.apple = (-50, -50)
self.player_nmbr = player_nmbr
if(player_nmbr == 0):
self.direction = pyga... |
"""
Created on 14:04, June. 4th, 2021
Author: fassial
Filename: __init__.py
"""
# numba_backend model
from . import numba_backend
# tensor_backend model
from . import tensor_backend
from .tensor_backend import AlphaSyn
from .tensor_backend import ExpSyn
from .tensor_backend import GapJunction
from .tensor_backend imp... |
# Dos vectores son ortogonales cuando son perpendiculares entre sí. Para determinarlo
# basta calcular su producto escalar y verificar si es igual a 0. Ejemplo:
# A = (2,3) y B = (-3,2) => 2 * (-3) + 3 * 2 = -6 + 6 = 0 => Son ortogonales
# Escribir una función que reciba dos vectores en forma de tuplas y devuelva un... |
import numpy as np
import matplotlib.pyplot as plt
X = []
Y = []
for line in open('data_1d.csv'):
x, y = line.split(',')
X.append(float(x))
Y.append(float(y))
X = np.array(X)
Y = np.array(Y)
denom = X.dot(X) - X.mean() * X.sum()
a = (X.dot(Y) - Y.mean() * X.sum()) / denom
b = (Y.mean() * X.dot(X) - X.m... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import os, sys, logging, datetime, json
from sklearn import preprocessing
starttime = datetime.now()
log_filename = datetime.now().strftime("log\%Y%m%d-%H%M%S.log")
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(name)-... |
# CODE BY: Luna Jiménez Fernández
###########
# IMPORTS #
###########
from agents.old.dql_agent_old import DQLAgentOld
# General imports
from collections import deque
import numpy as np
import random
import csv
from os import mkdir
from os.path import exists, join
# Keras related imports
from keras.layers import De... |
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE','curdproject1.settings')
import django
django.setup()
from curdapp.models import *
from faker import Faker
from random import *
faker=Faker()
def populate(n):
for i in range(n):
fno=randint(1001,9999)
fname=faker.name()
fsal=randin... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r"^$", views.IndexView.as_view(), name="index"),
url(r"^commit/(?P<pk>[0-9]+)/$", views.CommitView.as_view(), name="commit"), # TODO better name in URL than "commit/"?
url(r"^result/(?P<pk>[0-9]+)/$", views.ResultSetView.as_view(), n... |
# using python3.6.10
# need to install numpy and pandas
# HC Data H_k:
"""
(1, 'p1_distance') Empirical error: 0.9713846153846143 True error: 0.5543076923076925
(1, 'p2_distance') Empirical error: 0.9712307692307681 True error: 0.5515384615384619
(1, 'p_inf_distance') Empirical error: 0.9713846153846143 True error: 0.... |
[actor] @dbtype:mem,fs
"""
Operator actions for handling interventsions on a computenode
"""
method:setStatus
"""
Set the computenode status, options are 'ENABLED(creation and actions on machines is possible)','DISABLED(Only existing machines are started)', 'HALTED(Machine is not availa... |
import re
camel_pat = re.compile(r'([A-Z])')
under_pat = re.compile(r'_([a-z])')
def camel_to_underscore(name):
return camel_pat.sub(lambda x: '_' + x.group(1).lower(), name)
def underscore_to_camel(name):
return under_pat.sub(lambda x: x.group(1).upper(), name)
def dict_keys_underscore_to_camel(d):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.