text stringlengths 38 1.54M |
|---|
# Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from typing import Optional
from .aws import Action as BaseAction
from .aws import BaseARN
service_name = "Amazon VPC Lattice"
prefix = "vpc-lattice"
class Action(BaseAction):
def __init__(self, a... |
import datetime
def printTimeStamp(name):
print("Автор програми: " + name)
print("Час компіляції: " + str(datetime.datetime.now()),"\n")
printTimeStamp("Valeriy Neroznak")
result = ("")
q = int(input("Введите число: "))
while q != 0:
res = q%2
result =result + str(res)
q = q//2
f=result[::-1]
prin... |
from classes.simulation.abstract.device import AbstractDevice
from models import Object
import requests
class Lamp(AbstractDevice):
"""Basic Lamp device
Arguments:
AbstractDevice {abc} -- Device abstraction
"""
def __init__(self, name, address):
super().__init__(name, address)
... |
# -*- coding: utf-8 -*-
from openerp import api, fields, models
import logging
_logger = logging.getLogger(__name__)
class ProductPrice(models.TransientModel):
_name = 'product.prices'
markup = fields.Float(string='Mark-up', default=10)
@api.multi
def set_prices(self):
context = dict(self.... |
for i in range(101):
result = 0
n = len(str(i))
while(i != 0):
t = i % 10
result = result + t**n
i = i//10
if i == result:
print(i)
|
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import ipdb
fileName = "sub_proba.csv"
fileNameFlip = "sub_proba_dp.csv"
mode = 'r'
resultName = "result"
def readFile(fileName, mode):
arr = []
with open(fileName, 'r') as inputfile:
lines = inputfile.readlines... |
#-------------------------------------------------------------------------------
# Name: Unit test Reverse list recursively
# Purpose:
#
# Author: mmk and emeka
#
# Created: 04/09/2018
# Copyright: (c) mmk 2018
# Licence: <gloriaconcepto>
#----------------------------------------------------... |
# -*- coding: utf-8 -*-
from odoo import http
# class XmartsSdp(http.Controller):
# @http.route('/xmarts_sdp/xmarts_sdp/', auth='public')
# def index(self, **kw):
# return "Hello, world"
# @http.route('/xmarts_sdp/xmarts_sdp/objects/', auth='public')
# def list(self, **kw):
# return ht... |
import requests
from lxml import etree
import time
import csv
# 定义函数抓取每页前30条商品信息
def crow_first(n):
# 构造每一页的url变化
url = 'https://search.jd.com/Search?keyword=%E6%89%8B%E6%9C%BA&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&cid2=653&cid3=655&page=' + str(
2 * n - 1)
head = {'authority': 'search.jd.com',
... |
from cart.models import OrderItem
from django.shortcuts import render , redirect
from django.contrib.auth import login
from django.contrib.auth.decorators import login_required
from .models import Customer,my_balance
from django.utils.text import slugify
from product.models import Product
from .forms import bala... |
# https://codeforces.com/contest/750/problem/B
#coding: utf-8
n = int(raw_input())
cont = 0
answer = True
for i in range(n):
coordinate, direction = raw_input().split()
coordinate = int(coordinate)
if (direction == "South"):
cont += coordinate
elif (direction == "North"):
cont -= coordinate
elif (co... |
import numpy as np
import bem2d
from importlib import reload
import bem2d
import matplotlib.pyplot as plt
bem2d = reload(bem2d)
# List of elements for forward model
n_elements = 2
mu = np.array([3e10])
nu = np.array([0.25])
elements = []
element = {}
L = 10000
# x1, y1, x2, y2 = bem2d.discretized_line(-L, 0, L, 0, n_... |
"""
<중심 극한 정리>
= 모집단이 어떤 분포든지 상관없이 표본의 크기가 충분히 크다면 모든 가능한 표본 평균은 모평균 주위에서 정규 분포를 따른다.
전체 인구 : 모집단(전체 집합) / 모평균 : 모집단(전체 집합)의 평균
전체 인구 중 일부 : 표본(부분 집합) / 표본 평균 : 표본(부분 집합)의 평균
즉, 부분집합(표본 평균)의 평균은 전체 집합의 평균(모평균) 주위에서 정규 분포를 따른다.
만약 모집단 평균이 'mu'이고, 표준 편차가 'sigma'인 정규 분포를 따른다면,
표본 평균의 분포는 평균이 'mu'이고, 분산이 'sigma/sqrt(n)'인... |
def sumoflist( x, y ): #x = [6, 123, 453, 2, 8]
sum = 0
for i in x:
sum = sum + i #sum = ?, ? = 0 + 6 = 6 -> sum. sum = ?, ? = 6 + 123 = 129 -> sum
sum = sum + y
return sum
l = []
l.append(6)
l.append( 123 )
l.append( 453 )
l.append( 2 )
l.append( 8 )
print(... |
# -*- coding: utf-8 -*-
import math
pi = math.pi
def circulo (radio):
resultado = pi*(radio**2)
return resultado
def circulo_peri (diametro):
resultado = pi*(diametro)
return resultado
def triangulo (a,b):
resultador= b*a/2
return resultador
def triangulo_peri (lado_a... |
# 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 agreed to in writing, software
# distributed under t... |
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.models import User, auth
# Create your views here.
def register(request):
if request.method == 'POST':
first_name = request.POST['first_name']
last_name = request.POST['last_name']
u... |
"""
MIT License
Copyright (c) 2023 TheHamkerCat
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 witout limitation the rights
to use, copy, modify, merge, publish, d... |
from . import OAuthSignIn
class OutlookSignIn(OAuthSignIn):
def __init__(self):
super(OutlookSignIn, self).__init__('outlook')
self.service = OAuth2Service(
'microsoft',
consumer_key='Register your app at apps.dev.microsoft.com',
consumer_secret='Register your app at ... |
import numpy as np
import cv2
import os
face_cascade = cv2.CascadeClassifier('cascades/data/haarcascade_frontalface_alt2.xml')
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('trainner.yml')
opened_yet = False
cap = cv2.VideoCapture(0)
while True:
ret,frame = cap.read()
gray = cv... |
#!/usr/bin/env python
"""
_JobEmulator_
"""
__revision__ = "$Id: "
__version__ = "$Revision: "
__all__ = []
|
import collections
from lanedet.utils import build_from_cfg
from ..registry import PROCESS
class Process(object):
"""Compose multiple process sequentially.
Args:
process (Sequence[dict | callable]): Sequence of process object or
config dict to be composed.
"""
def __init__(self,... |
# encoding: utf-8
"""
gites.proprio
Created by mpeeters
Licensed under the GPL license, see LICENCE.txt for more details.
Copyright by Affinitic sprl
"""
import os
import simplejson
from PIL import Image, ImageFile
import zope.interface
from five import grok
from Products.CMFCore.utils import getToolByName
grok.temp... |
from go_core.lambda_goboard import LambdaGoBoard
import random
import time
import sys
def random_move_in_board(go_board, step_to_run):
move_step = 0
is_both_pass = False
black_pass = False
white_pass = False
while True:
black_pass = False
valid_move = go_board.get_valid_mo... |
import numpy as np
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
import pandas as pd
from sklearn.svm import SVR
import matplotlib.pyplot as plt
import pickle
dataframe = pd.read_csv("FOOTBALLL_DATASET.c... |
# Generated by Django 3.2.6 on 2021-08-13 19:20
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUT... |
"""
pygluu.kubernetes.kustomize
~~~~~~~~~~~~~~~~~~~~~~~~~~~
License terms and conditions for Gluu Cloud Native Edition:
https://www.apache.org/licenses/LICENSE-2.0
"""
import base64
import contextlib
import os
import shutil
import socket
import time
from ast import literal_eval
from pathlib import Path
from pygluu.... |
import datetime
from urllib2 import urlopen as uReq
from bs4 import BeautifulSoup
import requests
import webbrowser
import urllib3
urllib3.disable_warnings()
open("info.txt","w").close()
file = open("info.txt","a")
time = str(datetime.datetime.now())
file.write(time + "\n")
with requests.Session() as c:
url = 'https... |
from intel_extension_for_pytorch.nn.utils import _weight_prepack
from intel_extension_for_pytorch.nn.utils import _lstm_convert
from . import _model_convert, _weight_cast
from ._weight_prepack import Apply_TPPLinear_weight_prepack
|
import feature_extraction
import transforming
import numpy as np
import pandas as pd
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import GridSearchCV
class KNN:
def __init__(self, vectorizer='tfidf', n_neighbors=3):
self.vectorizer = feature_extraction.get(vectorizer)
... |
# -*- coding: utf-8 -*-
import scrapy
from ..items import Track
from datetime import datetime
from urllib.parse import urljoin
class NewReleaseSpider(scrapy.Spider):
name = 'new-release'
allowed_domains = ['www.djcity.com']
start_urls = ['http://www.djcity.com/digital/record-pool.aspx']
def parse(sel... |
"""
With this concept of default parameters in mind, the goal of this assignment is to write a single function we are going to name randInt() that takes up to 2 arguments.
If no arguments are provided, the function should return a random integer between 0 and 100.
If only a max number is provided, the function should ... |
import tempfile
import argparse
import logging
import datetime
import threading
import os
import re
from botocore.exceptions import ClientError
from ocs_ci.framework import config
from ocs_ci.ocs.constants import (
CLEANUP_YAML,
TEMPLATE_CLEANUP_DIR,
AWS_CLOUDFORMATION_TAG,
)
from ocs_ci.ocs.exceptions i... |
import csv
import re
from converter.binance import BinanceConverter
from strategy.base import BaseStrategy
BASE_MARKET_CURRENCIES = ['BTC', 'ETH', 'BNB']
class BinanceStrategy(BaseStrategy):
DATE = 'Date(UTC)'
MARKET = 'Market'
TYPE = 'Type'
PRICE = 'Price'
AMOUNT = 'Amount'
TOTAL = 'Total'... |
from tkinter import *
import tkinter as tk
import matplotlib.pyplot
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
#matplotlib.use('TkAgg')
import Adafruit_DHT
from PIL import ImageTk, Image
from datetime import datetime
class Generate_plot():
"""Generates and u... |
from celery import Celery
from django.core.mail import send_mail
from dailyfresh import settings
# 创建celery客户端
# 参数1:自定义
# 参数2:中间人
app = Celery('dailyfresh', broker='redis://127.0.0.1:6379/1')
@app.task
def send_active_mail(username, email, token):
"""发送激活邮件"""
subject = '天天生鲜用户激活' # 标题 不能为空 否则会报错
messa... |
from django.conf.urls import url
from rest_framework import routers
from talentmap_api.common.urls import get_retrieve, patch_update
from talentmap_api.administration.views import aboutpage as views
router = routers.SimpleRouter()
urlpatterns = [
url(r'^$', views.AboutPageView.as_view({**get_retrieve, ** patch_u... |
from urllib.request import urlopen
from urllib.request import Request
from bs4 import BeautifulSoup
# 웃긴대학 메인 페이지
headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0'
}
req = Request(url="http://web.humoruniv.com/main.html", headers=headers)
response = urlopen(re... |
# This one times out. Will have to look for another way. Maybe use Binary Index Trees.
# If you have n intersections, you need to do n shifts to sort the list.
# If we are able to find the number of intersections, we will be able to find the nubmer of shifts that we need.
# If i < j and A[i] > A[j], then this is an arc... |
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def findTarget(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: bool
"""
if root is None or k is None:
... |
from django.shortcuts import render
from django.http import HttpResponse
from django.core.mail import EmailMessage
from django.shortcuts import redirect
# Create your views here.
def index(request):
return render(request, 'main/index.html')
def ajax_send_mail(request):
try:
name = request.GET.get('name')
email... |
import networkx as nx
def load_data(file):
G = nx.Graph()
with open(file, "r") as f:
for line in f.readlines():
G.add_edge(*tuple(map(int, line.split())))
return G
def main():
G = load_data("348.edges.txt")
print(G.number_of_nodes())
b = sum(map(lambda node: len(G.neigh... |
import sqlite3
conn = sqlite3.connect('my_database.sqlite')
cursor = conn.cursor()
print('hi, are you looking for vote')
response = input("enter Y or N ")
if response=='N':
print("Thank you")
else:
aadhar = int(input("Give your adhar number "))
name = input("enter your name")
cursor.execute("SELECT AA... |
# Common utils.
import os
import random
import time
import subprocess
from subprocess import call
import logging
FORMAT_DBG = "%(levelname)-7s **: (%(filename)s:%(lineno)s:%(funcName)s) - %(message)s"
FORMAT_INFO = "%(levelname)-7s **: %(message)s"
# Loggers
logging.basicConfig()
logger = logging.getLogger()
hndlr ... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. 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 cop... |
#All the classes for pieces
#Simply describes how they are drawn
from vpython import*
import numpy as np
import fvector as fvec
class Piece:
'A parent class for all the piece subclasses'
def __init__(self):
self.base = None
self.ogcolor = None
self.boxes = []
def move(self,newPos):
... |
import numpy as np
from graphblas import Matrix, Vector, binary, indexunary, monoid, replace, select, unary
from graphblas.semiring import any_pair, min_plus
from .._bfs import _bfs_level, _bfs_levels, _bfs_parent, _bfs_plain
from ..exceptions import NoPath, Unbounded
__all__ = [
"single_source_bellman_ford_path_... |
import os, sys
import numpy as np
import pathlib
import glob
import scipy.io as sio
def env():
return ('/').join(os.path.abspath(__file__).split('/')[:-1])
class Reader:
def __init__(self):
self.home = env()
self.PATH_PC = '%s/processed_dataset/{}/{}/{}.mat' % self.home
self.PATH_SUMMA... |
import numpy as np
import pandas as pd
import pickle
from flask import Flask, jsonify, render_template, request
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
import h5py
from keras.models import load_model
# load the dataset but only keep the top n words, zero t... |
from common.Converter.FeatureConVerTer import FeatureConVerTer
class FeatureConverTerTest:
def __init__(self):
self.fCverter = FeatureConVerTer()
def TestWordsToFeatures(self, words, messages):
return self.fCverter.cVertMessagesToDict(words, messages)
if __name__ == '__main__':
featureC... |
assignments = []
def cross(A, B):
"Cross product of elements in A and elements in B."
return [s + t for s in A for t in B]
"""Global Variables used in following functions"""
rows = 'ABCDEFGHI'
cols = '123456789'
boxes = cross(rows, cols)
row_units = [cross(r, cols) for r in rows]
column_units = [cross(rows, ... |
import linecache
MAX_LINE = 194
date = []
count = -2
filename='flo_gen_output.txt'
for i in range(MAX_LINE):
count = count + 12
date.append(float(linecache.getline(filename, count).split()[-1]))
print("Minimum: " + str(min(date)))
print("Maximum: " + str(max(date)))
print("Average: " + "{0:.3f}".format(su... |
def remove_dollar_sign(s):
return s.replace("$","")
m = str(input("Nhập chuỗi : "))
t=remove_dollar_sign(m)
print(t)
string_with_no_dollars = remove_dollar_sign("$80% percent of $life is to show $up")
if string_with_no_dollars == "80% percent of life is to show up":
print("Your function is correct")
else:
... |
#!/usr/bin/env python3
text = laba.return_text_value()
import lab3a
text = laba.return_text_value()
print(text)
print(lab3a.return_number_value())
|
True or False """This should be True"""
False and True """This should be False"""
1 == 1 and 2 == 1 """True and False >>> False"""
"test" = "test" """This should True"""
1 ==1 or 2 != 1 """True or True >>> True"""
True and 1 == 1 """True and True >>> True"""
False and 0 != 0 """False and False >>> False"""
True or 1 ==... |
n, m, k = map(int, input().split(" "))
a = list(map(int, input().split(" ")))
for i in range(1, n+1):
if (m-i-1 >= 0 and a[m-i-1] != 0 and k >= a[m-i-1]) or \
(m+i-1 < n and a[m+i-1] != 0 and k >= a[m+i-1]):
print(i*10)
exit()
|
Shop_list=[
("苹果",20),
("香蕉",30),
("草莓",50)
]
User_list=[]
Salary=input("请输入工资:")
if Salary.isdigit():
Salary=int(Salary)
while True:
for index, shop_list in enumerate(Shop_list):
print(index, shop_list)
buy_list = input("请输入要购买的商品序号:")
if buy_list.isdigit():
bu... |
# https://en.wiktionary.org/wiki/%C2%BD
RECIPE_SCHEDULE = [
{
'title': 'Vegetable Lasagna',
'id': 'vegetable_lasagna',
'link': 'https://www.aicr.org/assets/docs/pdf/her/vegetable_lasagna.pdf',
'category': ['Entrée', 'Vegetarian'],
"recipe_nutrition":
... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^vpusti/', include(admin.site.urls)),
url(r'^operator/(?P<washing_id>\d+)/$', 'orders.views.operator'),
url(r'^operator/data/byday/(?P<day>\d+)/month/(?P<month>\d+)/ye... |
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
import time
def pid_plot(ax1, setPoint, processVariable):
sp = setPoint
pv = processVariable
# xs = []
ys = []
for line in pv:
# xs.append(t)
... |
import cv2 as cv
haar_cascades = cv.CascadeClassifier('haarcascade_frontalface_default.xml')
video = cv.VideoCapture(0)
video.set(cv.CAP_PROP_FRAME_WIDTH, 1024)
video.set(cv.CAP_PROP_FRAME_HEIGHT, 576)
while True:
ret, frame = video.read()
if frame is None:
break
frame = cv.flip(frame, 1)
grayscaled_frame = c... |
"""
Test cases for generate facial landmark localization training data
"""
import os
import sys
import random
import unittest
import cv2
from mtcnn.datasets import get_by_name
import mtcnn.train.gen_landmark as gl
from mtcnn.utils import draw
DEFAULT_DATASET = 'CelebA'
here = os.path.dirname(__file__)
class TestG... |
import datetime
import hashlib
import conector.conexion as conexion
connect = conexion.conectar()
database = connect[0]
cursor = connect[1]
class Producto:
def __init__(self, proveedor_id, nombre, precio, cantidad):
self.proveedor_id = proveedor_id
self.nombre = nombre
self.precio = pr... |
print("This program calculates your GPA...have fun")
course_titles = []
credit_load = []
Grade = []
cl = []
name = input('Hi, what is your name? ')
matriculation_number = input('what is your matriculation number? ')
course_num = int(input('How many courses are you offering? Please state: '))
for Courses in ... |
import numpy as np
from scipy.ndimage import interpolation
from ocear.preprocess.utils import clip_borders
MAX_SKEW = 3
SKEW_STEPS = 32
def _skew_angle(image):
"""
Estimate skew angle where the horizontal variance in pixel intensity is
highest; the higher the variance, the "straighter up" the letters sh... |
from a10sdk.common.A10BaseClass import A10BaseClass
class CostCfg(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param cost: {"description": "Interface cost", "minimum": 1, "type": "number", "maximum": 65535, "format": "number"}
:param instance_id: {"description": ... |
#!/usr/bin/python
#-*- coding:utf-8 -*-
#**********************************************************
#Filename: 172_format_number.py
#Author: Andrew Wang - shuguang.wang1990@gmail.com
#Description: ---
#Create: 2016-11-01 22:48:59
#Last Modifieda: 2016-11-01 22:48:59
#***************************************************... |
#encoding: UTF-8
#Autor: Omar Israel Galván García A01745810
#Este programa pregunta al usuario cuantos boletos quiere comprar de cada tipo e imprime el total a pagar.
def calcularPago(asientosA, asientosB, asientosC): # esta funcion toma los valores de A,B,C y los multiplica por el costo
totalPago = (asientosA *... |
import pygame
import time
class Player:
"""
Class player manages the players infomation
about the on going game. This includes which
piece the player is and where their piece are
placed on the game board
"""
def __init__(self,name,color):
self.name = name
self.color = color
... |
# Copyright (C) 2023 Intel Labs
#
# BSD-3-Clause License
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the f... |
import datetime
import hashlib
import re
import time
import requests
import redis
conn = redis.Redis(host='120.78.122.64', password='790623',db=7)
md5 = lambda x:hashlib.md5(x.encode('utf-8')).hexdigest()
url = 'http://api.fanyi.baidu.com/api/trans/vip/translate'
appid = '20200530000477540'
appkey = 'ZpDXdRwvjmGEy... |
__author__ = "Gil Ortiz"
__version = "1.0"
__date_last_modification__ = "12/7/2019"
__notes__ = ''' timecheck_synchronous.py - routine executed in standard synchronous mode
when executed, get_data() will be called synchronously 6x'''
import time
import random
import string
start = time.time()
def get_data():
#... |
from django.contrib import admin
from django.urls import path
# from GilioInventario.views import login, administrador
from superSu.views import *
from login.views import *
from administrador.views import *
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('ad... |
year_start = 2017
year_end = 2018
month_start = 4
month_end = 11
file_name = 'data.xlsx'
import requests
import utils
import numpy
from bs4 import BeautifulSoup
from openpyxl import Workbook
wb = Workbook()
sheet = wb.active
x_data, y_data = [],[]
for year in range(year_start, year_end + 1):
for month in range... |
"""Variational Auto-Encoder
arXiv:1312.6114v10
"""
import matplotlib.pyplot as plt
import torch
import torch.nn.functional as F
from datasets import MyDataset, get_mnist
from functools import reduce
from torch.utils.data import DataLoader
from tqdm import tqdm
from utils import compose
class AutoEncoder(torch.nn.Mo... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
#class Student(models.Model):
# name = models.CharField(max_length = 128,verbose_name = "name")
# work_time = models.CharField(max_length = 128,verbose_name = "work time")
# work_location= models.C... |
n = int(input())
special_numbers = []
for number in range(1111, 10000):
number_string = str(number)
if '0' not in number_string:
if (int(number_string[0]) + int(number_string[1])) == (int(number_string[2]) + int(number_string[3])):
if n % (int(number_string[0]) + int(number_string[1])) == 0... |
import base64
import logging
import os
import asyncio
import signal
import ipaddress
from configparser import ConfigParser
import click
import jinja2
import aiohttp_jinja2
from aiohttp import web
from aiohttp_session import session_middleware
from aiohttp_session.cookie_storage import EncryptedCookieStorage
from crypt... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2017-09-25 19:30
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('companies', '0001_initial'),
]
operations = [
migrations.CreateModel(
... |
from PIL import Image
def decrypt(image, out='decrypted.png'):
"""
:param image: Path to image-like (png, jpeg, ...) to be decrypted
:type image: String
:param out: Name of the file to store the decrypted image in
:type out: String
"""
img = Image.open(image)
img_data =... |
import streamlit as st
import tweepy
from wordcloud import WordCloud
import pandas as pd
import numpy as np
import re
import matplotlib.pyplot as plt
from PIL import Image
import seaborn as sns
#import config
from functions import *
import json
consumerKey = st.secrets["consumerKey"]
consumerSecret =... |
import pandas as pd
import os
folder = "data/"
files = os.listdir(folder)
print("\n", len(files), " files found\n")
states = pd.read_csv(folder + files[0], delimiter=" ", header=1)
del states["Day"]
states = states.columns
errors = pd.DataFrame(index=files, columns = states)
errors.fillna(0, inplace=True)
stat... |
class Board():
def __init__(self,size=3,):
self.size=size
self.board=[]
for r in range(self.size):
self.board.append([])
for c in range(self.size):
self.board[r].append(" ")
def print_board(self):
print("----"*len(self.board[0]))
... |
import sys, os, csv, matplotlib, numpy
from operator import itemgetter
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.backends.backend_pdf import PdfPages
sys.path.append(os.getenv("BC") + '-old')
from constants import CATEGORY_COLORS, ALL_COLORS, DISPLAY_... |
import torch
from torch import nn , optim
import torch.nn.functional as F
from torchvision import datasets, transforms, models
import json
from collections import OrderedDict
def transformations():
data_transforms = {"train_transform" : transforms.Compose([
transforms.RandomRotation(30),
transf... |
import re
text = """one two
three four
five six seven
eight nine
ten"""
# process line by line
# ^..*.$ : at least two char
# . does not match a newline by default
pat = r"^.*$"
m = re.search(pat, text)
if m :
print(m.group())
else:
print("no match")
# pickup the whole paragraph
# re.S : make . match a new line
pat... |
'''
logWithGpsOneXTRA.py - This is a GNSS test using Sixfab's HAT with gpsOneXTRA Assistance Function from Qualcomm that logs the GPS info in a file
Created by Marc Leroy (Pix4D), May 8th 2019
'''
from cellulariot import cellulariot
import time
def main():
node = cellulariot.CellularIoT()
node.setupGP... |
#coding:utf8
import wx
def openFile(x):
fc = open(filepath.GetValue(),'r').read() #获取内容
contents.SetValue(fc)
def savefile(x):
fc = open(filepath.GetValue(),'w')
fc.write(contents.GetValue())
fc.close()
app = wx.App()
win = wx.Frame(None,title="xyb's Notepad") #显示框
bkg = wx.Panel(win)
#添加组件
savebutton = wx.B... |
# ------------------------------------------------------------
# Copyright (c) 2017-present, SeetaTech, Co.,Ltd.
#
# Licensed under the BSD 2-Clause License.
# You should have received a copy of the BSD 2-Clause License
# along with the software. If not, See,
#
# <https://opensource.org/licenses/BSD-2-Clause>
#
# ... |
from copy import deepcopy
################################
### Heap Traversal Functions ###
################################
def left_child_idx(i):
""" Performs the arithmetic to get the left child of a given heap index """
return (i << 1) + 1
def right_child_idx(i):
""" Performs the arithmetic to get the... |
def show(name):
print(f'Przed modyfikacją: {name}')
name[0] = 'Beata'
name[1] = 'Barbara'
name[2] = 'Bogdan'
print(f'Po modyfikacji: {name}')
print(f'Id po modyfikacji: {id(name)}')
data = ['Anna', 'Agnieszka', 'Andrzej']
print(f'Przed wywoładniem funkcji show: {id(data)}')
print()
show(data)
print(f'Po wywołani... |
from django.conf.urls import url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.core.urlresolvers import reverse_lazy
from . import views
app_name='weddings'
urlpatterns = [
# event model
url(r'^$', views.Invite1View.as_view(), name='invite1'),
... |
# REST Endpoint URL: https://ftx.com/api
# Local-Time vs FTX-Servers: https://otc.ftx.com/api/time
# from datetime import datetime
# from ciso8601 import
import os
import time
import hmac
from queue import Queue
from typing import Optional, Dict, Any, List
from requests import Request, Session, Response
from dotenv im... |
import pygame
from pygame.locals import *
class Puntos(pygame.sprite.Sprite):
def __init__(self, valor, x, y, pantalla):
super(Puntos, self).__init__()
self.valor = valor
self.presionada = False
self.x = x
self.y = y
self.pantalla = pantalla
self.circulo = ... |
import os
import numpy as np
import json
import detectron2
from detectron2.utils.logger import setup_logger
setup_logger()
from detectron2.structures import BoxMode
import itertools
from detectron2.data import DatasetCatalog, MetadataCatalog
from detectron2.engine import DefaultTrainer, DefaultPredictor
from detectron2... |
import re
import requests
from bs4 import BeautifulSoup
INSPECTION_DOMAIN = 'http://info.kingcounty.gov'
INSPECTION_PATH = '/health/ehs/foodsafety/inspections/Results.aspx'
INSPECTION_PARAMS = {
'Output': 'W',
'Business_Name': '',
'Business_Address': '',
'Longitude': '',
'Latitude': '',
'City'... |
import inspect
import taichi.lang
from taichi._lib import core as _ti_core
from taichi.lang import impl, ops
from taichi.lang._texture import RWTextureAccessor, TextureSampler
from taichi.lang.any_array import AnyArray
from taichi.lang.expr import Expr
from taichi.lang.matrix import MatrixType
from taichi.lang.struct ... |
class file:
"""
This is a class that represents a file object
Attributes:
id (String): The real part of complex number.
name (String): The imaginary part of complex number.
date (String): The date of the file was created
size(String): The size of the file
url(String... |
# Write a Python program to generate all permutations of a list in Python.
class generatePermutation:
def permutationList(self,List):
for i in range(len(List)):
for j in range(len(List)):
for k in range(len(List)):
if (List[i] != List[j] != List[k]):
... |
'''
def double_it(number):
return(2 * number)
print(double_it(2))
print(double_it(2.2))
print(double_it("hello"))
'''
def calc_hypo(a, b):
if ((type(a) and type(b)) in (int, float)) and a >= 0 and b >=0:
print("a and be are either of type float or int, and positive numbers.")
c = (a*a + ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.