text stringlengths 8 6.05M |
|---|
#! /usr/bin/env python3
# -*- coding:utf-8 -*-
__author__ = 'wjq'
from apscheduler.schedulers.blocking import BlockingScheduler
from methods.RedisInfo import *
import multiprocessing
def start():
scheduler = BlockingScheduler()
scheduler.add_job(monitor , 'interval', seconds=60)
scheduler.start()
def tas... |
import pyttsx3
import datetime
import speech_recognition
import wikipedia
import webbrowser
import os
import random
engine = pyttsx3.init("sapi5")
voices = engine.getProperty("voices")
engine.setProperty("voice", voices[0].id)
def speak(audio):
engine.say(audio)
engine.runAndWait()
def wishMe():
hour =... |
from bs4 import BeautifulSoup
import bs4
import requests
from operation import Operation
import pandas as pd
def mount_references(bs4_source):
refs = bs4_source.find_all('cite')
j_refs = {}
for item in refs:
_id = item.parent.parent.attrs['id']
_link = None
for c in item.contents:
... |
from onegov.ballot.models.vote.mixins import DerivedAttributesMixin
from onegov.ballot.models.vote.mixins import DerivedBallotsCountMixin
from onegov.core.orm import Base
from onegov.core.orm.mixins import TimestampMixin
from onegov.core.orm.types import UUID
from sqlalchemy import Boolean
from sqlalchemy import Column... |
#!/usr/bin/env python
import numpy as np
import time
import math
import csv
import sys
#from misvmio import parse_c45, bag_set
import misvm
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from sklearn import svm
from sklearn import datasets
def disp_results(th... |
import certifi
import morepath
import ssl
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
from elasticsearch import ConnectionError # shadows a python builtin!
from elasticsearch import Elasticsearch
from elasticsearch import Transport
from elasticsearch import TransportError
from elas... |
#!/usr/bin/env python
"""
Update the MYSQL_USER and MYSQL_PASSWORD variables below.
"""
import subprocess
import re
import sys
"""
This script runs /usr/bin/mysqladmin status and cuts up the output into Nagios format.
You may need to update the MYSQL_USER and MYSQL_PASSWORD with an account that can connect.
"""
MYSQ... |
#!/usr/bin/env python
import sys
from twython import Twython
import os
import time
import serial
import RPi.GPIO as GPIO
CONSUMER_KEY = 'YOUR USER DATA'
CONSUMER_SECRET = 'YOUR USER DATA'
ACCESS_KEY = 'YOUR USER DATA'
ACCESS_SECRET = 'YOUR USER DATA'
api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET... |
"""added electricity use
Revision ID: f64c62f21745
Revises: bc6d06c013a1
Create Date: 2021-07-06 12:08:22.934817
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = 'f64c62f21745'
down_revision = 'bc6d06c013a1'
branch_labels = N... |
# Função: Calcular peso com o IMC
# Autor: Roberta de Lima Ribeiro
print("CALCULAR PESO")
peso = int(input("Digite peso"))
altura = float(input("Digite a altura"))
imc = peso/(altura**2)
print("Seu IMC: ", imc)
if (imc<18.5):
print("Abaixo do peso")
elif (imc>25):
print("Acima do peso")
else :
... |
class Employee:
company = "google"
@staticmethod
def greet():
print("Hello Good Morning ! ")
|
# Generated by Django 2.1.7 on 2019-03-30 12:57
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('core', '0006_auto_201903... |
import sys
from PyQt5 import QtCore, QtWidgets, QtGui
from dis import Ui_MainWindow
class MY_Window(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.pushButton.clicked.connect(self.open_File)
... |
m = input("Introduce un numero: ")
print "Numeros primos: ",
for i in range(2, m+1):
primo = True
for x in range(2, i):
if i%x == 0:
primo = False
if primo == True:
print i,
|
from BSTIterator import BSTIterator
from BSTNode import BSTNode
# Class name: BST
# Instance Variables: root (the root of the BST)
# isize (number of elements in BST)
# iheight (height of BST)
# Description: Implements a BST
# Methods: init, insert, find, begin, first, end, trav... |
# coding: utf8
import json
import configparser
import html.parser
import urllib, urllib.request, urllib.parse
# 读取URL获得验证码的路径HTML解析类
class LoginRandCodeParser(html.parser.HTMLParser):
def __init__(self):
self.randCodeUrl = ""
self.rand = ''
html.parser.HTMLParser.__init__(self)
def han... |
import csv
from datetime import datetime
def parseCSV(lot_number,periods):
cp = []
parking_available = []
numbers_list = []
all_carpark = []
time_list=datetime.strptime('19/04/2021 10:59', '%d/%m/%Y %H:%M')
with open('carpark.csv') as csvfile:
rows = csv.reader(csvfile)
res = l... |
# There is a
# collection
# of
# strings(There
# can
# be
# multiple
# occurences
# of
# a
# particular
# string ).Each
# string
# 's length is no more than characters. There are also queries. For each query, you are given a string, and you need to find out how many times this string occurs in the given collection of... |
import pya
# create a unique representation of the application (klayout program)
app = pya.Application.instance()
# create the main window of the program
# (that include the menus, the tool panels, the layout views...)
mw = app.main_window()
# create a layout view, which is a representation of a layout tab
# can be ... |
from .base import *
class User(Base):
__tablename__ = 'user'
__table_args__ = {'extend_existing': True}
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(250), nullable=False)
nama = db.Column(db.String(250), nullable=False)
genre = db.Column(db.String(250))
... |
#input
# 8
# 62 53
# 96 7
# 104 97
# 90 7
# 109 7
# 103 7
# 75 8
# 113 7
def factorial(n):
if n <= 1:
return 1
else:
return n * factorial(n-1)
def c(n, k):
result = factorial(n) / (factorial(k) * factorial(n - k))
return int(result)
n = int(input())
for i in range(0, n):
(n, k) = (int(x) for x in i... |
from .database import Database
class EmailResultHelper(Database):
def __init__(self, *args):
super(EmailResultHelper, self).__init__(*args)
def create_email_result(self, list_id, list_segment_id, templates_id, result,
result_description, campaign_id=None,
... |
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, Aer, execute
from random_bin import random_bin
class channel:
def __init__(self, n):
self.channel = QuantumCircuit(n, name="Channel")
self.backend = Aer.get_backend("qasm_simulator")
def get_channel(self):
return ... |
"""Advent of Code Day 18 - Like a GIF For Your Yard"""
def light_show(part_two=False):
lights = {}
for num, line in enumerate(light_lines):
for pos, light in enumerate(line):
lights['{},{}'.format(pos, num)] = light
steps = 0
while steps < 100:
new_lights = {}
for l... |
#import sys
#input = sys.stdin.readline
from math import gcd
def main():
a, b, c = map( int, input().split())
if a == b == c:
if a%2 == 1:
print("0")
else:
print("-1")
return
ans = 0
bi = 2
while a%bi == 0 and b%bi == 0 and c%bi == 0:
a, b, c =... |
# Generated by Django 2.2.1 on 2019-07-27 07:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('faculty', '0018_auto_20190727_1212'),
]
operations = [
migrations.AddField(
model_name='leave',
name='leave_type',
... |
def main():
openfile = open("Presidents.txt", "w")
openfile.write("Bill Clinton\n")
openfile.write("George Bush\n")
openfile.write("Barak Obama\n")
openfile.close()
openfile = open("Presidents.txt", "a")
openfile.write("\nPython is interpreted\n")
openfile.close()
openfile = open... |
def solve(marble_set, balance_scale):
return [1,2] |
#code
t = int(input())
for _ in range(t):
n,m = map(int,input().split())
if n==1:
n=2
print(*[p for p in range(n,m+1) if 0 not in [p%d for d in range(2,p)]]) |
class TeamMember:
def __init__(self, name, rating, bkiller):
self.name = name
self.rating = rating
self.bkiller = bkiller
def to_string(self):
return "%s,%s,%s" % (self.name, self.rating, self.bkiller)
|
# -*- coding: utf-8 -*-
import itertools
import time
from collections import defaultdict
from functools import partial
import numpy as np
from joblib import Parallel, delayed, logger as joblib_logger
from scipy.stats import rankdata
from sklearn.base import BaseEstimator, is_classifier, clone
from sklearn.model_select... |
from src.vision.camera_parameters import CameraParameters
from src.vision.transform import Transform
class TableCameraConfiguration:
def __init__(self, id: int, cam_param: CameraParameters, world_to_camera: Transform):
self.id = id
self.camera_parameters = cam_param
self.world_to_camera = ... |
#!/usr/bin/python -u
#
# CS3700, Spring 2015
# Project 2 Starter Code
#
import sys
import socket
import time
import datetime
import select
import json
import random
def log(string):
sys.stderr.write(datetime.datetime.now().strftime("%H:%M:%S.%f") + " " + string + "\n")
# MSG_SIZE = 1500
MSG_SIZE = 20000
TIMEOUT ... |
from config.config import PATH_TO_QUERIES, PATH_TO_DOMAINS
from app.typing import T_QUERIES, T_DOMAINS, T_DOMAIN, T_BASE_URL, T_QUERY, T_URL
def get_queries() -> T_QUERIES:
return sorted(list(set(PATH_TO_QUERIES.read_text().splitlines())))
def get_domains() -> T_DOMAINS:
"""
Get unique domains
"... |
import os
def createfile():
filename = input('Please input the filename you want to create: ')
i = 1
lines = []
while True:
line = input('Please input the %d line: ' % i)
if line == 'ENDLINE':
break
else:
lines.append(line)
i += 1
f = open... |
"""
musicinformationretrieval.com/realtime_spectrogram.py
PyAudio example: display a live log-spectrogram in the terminal.
For more examples using PyAudio:
https://github.com/mwickert/scikit-dsp-comm/blob/master/sk_dsp_comm/pyaudio_helper.py
"""
import librosa
import numpy
import pyaudio
import time
import socket
i... |
#coding:utf-8
https://docs.djangoproject.com/en/1.10/ref/contrib/admin/admindocs/
需要docutils这个模块的支持.下载地址是: http://docutils.sf.net/
INSTALLED_APPS
django.contrib.admindocs
(r'^admin/doc/', include('django.contrib.admindocs.urls'))
|
#!/usr/bin/env python
import random
import sys
if len(sys.argv) == 2:
N = int(sys.argv[1])
else:
N = 10
for _ in xrange(N):
print random.randint(0, 1000000)
|
# 多颜色多模板匹配示例
#
# 这个例子显示了使用OpenMV的多色跟踪。
import sensor, image, time
from image import SEARCH_EX, SEARCH_DS
from pyb import UART
from error_color import color_track
# 颜色跟踪阈值(L Min, L Max, A Min, A Max, B Min, B Max)
# 下面的阈值跟踪一般红色/绿色的东西。你不妨调整他们...
#blue=[(34, 40, 10, 18, -60, -40)]
#green=[(36, 58, -39, -24, -3, 19)]#gre... |
LAST_SAFE_CONTRACT = '0x34CfAC646f301356fAa8B21e94227e3583Fe3F5F'
LAST_DEFAULT_CALLBACK_HANDLER = '0xd5D82B6aDDc9027B22dCA772Aa68D5d74cdBdF44'
LAST_MULTISEND_CONTRACT = '0x8D29bE29923b68abfDD21e541b9374737B49cdAD'
|
#palindrome
n=int(input("Enter number:"))
copy=n
rev=0
while copy>0:
rev=rev*10+copy%10
copy//=10
if rev==n:
print("Palindrome")
else:
print("Not")
|
from time import sleep, strftime, time
from datetime import datetime
import src.database_tools
from src.entities.Temperature import Temperature
from src.TemperatureSlave import TemperatureSlave
from src.database_tools.TemperatureDataService import TemperatureDataService
from src.database_tools.GlobalSettingsAda... |
#
# core
#
import pygame
from pygame.locals import *
class Zect:
def __init__(self,
id = '',
pos=(0, 0),
dims=(32, 32),
text='',
color=(255,255,255, 255*0.2),
tag='',
children=[],
... |
from math import hypot
# from math import hypot, pow, sqrt
cateto_adjacente = float(input('Qual o valor do cateto adjacente? '))
cateto_oposto = float(input('Qual o valor do cateto oposto? '))
# hipotenusa = (cateto_oposto ** 2 + cateto_adjacente ** 2) ** (1 / 2)
# hipotenusa = hypot(sqrt(pow(cateto_adjacente, 2)), sq... |
from django.conf.urls import include
from django.contrib.auth import views as auth_views
from . import views
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.user_account.as_view(), name='login'),
path('logout/', auth_views.... |
from tkinter import *
import pandas as pd
import numpy as np
from pandas import DataFrame as df
from tkinter import filedialog
from tkinter import messagebox, ttk
import tkinter as tk
from datetime import datetime
#-----------------------------------------------CLASSES
class ToolTip(object):
def __init__(self, w... |
from django.db import models
# Create your models here.
# class Program(models.Model):
# nama_program = models.CharField(max_length = 255)
# images = models.CharField(max_length = 255)
# deskripsi = models.CharField(max_length = 1000)
# def __str__(self):
# return self.nama_program |
"""
This is the test suite for cspsolver.py.
"""
import os, sys
import collections
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from unittest import TestCase, main, skip
from teachercourse_csp import pref_handler, assign_days_for_course, maps_day_to_class, hours_for_prof, profs_for_co... |
import requests
import googlemaps
import json
import re
import getKey
def bytesIO_to_obj(bytesIO):
return json.loads(bytesIO.read().decode('UTF-8'))
def get_api_result(start, destination, mode=None):
gmaps = googlemaps.Client(key=getKey.googleKey())
result = gmaps.directions(start, destination, mode=mod... |
import numpy as np
from sklearn.datasets import load_breast_cancer
# 1. 데이터
datasets = load_breast_cancer()
print(datasets.DESCR)
print(datasets.feature_names)
x = datasets.data
y = datasets.target
print(x.shape) # (569, 30)
print(y.shape) # (569,)
# print(x[:5])
# print(np.max(x), np.min(x))
# print(y)
... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from warnings import warn
import csv
import sys
import codecs
import re
from collections import defaultdict
from collections import Counter
from itertools import zip_longest
from operator import itemgetter
from array import array
class defaultlist(list):
def __setitem__(... |
from __future__ import unicode_literals
from django import forms
from django.utils.translation import ugettext_lazy as _
import select2rocks
from testproj.testapp.models import Beach, SelectedBeach
class SelectedBeachForm(forms.ModelForm):
class Meta:
exclude = []
model = SelectedBeach
... |
from secrets import randbelow
from math import factorial
from math import log2 as ln
"""EUA passwords must...
- start with a letter
- have at least one number
- have at least one lowercase and one uppercase
- be EXACTLY 8 charcters long (WHYYY)
"""
PP_LENGTH = 3
ASCII_PWD_LENGTH = 8
TRIALS = 10
EUA = ... |
from django import template
register = template.Library()
@register.filter(name = "check")
def check(value,arg):
if value in arg.all():
return True
else:
return False
|
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
from matplotlib.mlab import griddata
import matplotlib as mpl
import numpy as np
import scipy.ndimage as ndimage
from mpl_toolkits.mplot3d import art3d
fig = plt.figure()
ax = fig.gca(projection='3d')
#amp_phase = np.ge... |
from enum import Enum
class GameControls(Enum):
"""
"""
UP = "⬆", 0
DOWN = "⬇", 1
LEFT = "⬅", 2
RIGHT = "➡", 3
SWORDS = "⚔", 4
SHIELD = "🛡", 5
FLAG = "🏳", 6
HEARTH = "💗", 7
WORLD = "🗺", 8
@classmethod
def all_emojis(cls):
return_list = []
for e... |
__author__ = 'timothyahong'
import re
def extract_cap_values(data_parameters, data_file):
return data_file[:_num_cap_values(data_parameters) - 1]
def extract_other_sensors(data_parameters, data_file):
return data_file[_num_cap_values(data_parameters):]
def _num_cap_values(data_parameters):
count = 0
... |
from pyspark import SparkContext, HiveContext
sc = SparkContext(appName = "test")
sqlc = HiveContext(sc)
sqlc.sql("create table if not exists asdf1(id string, name string)")
#sqlc.sql("insert into asdf select * from (select stack(3, 1.1, 'A', 1.2, 'b', 1.3, 'C')) t")
#sqlc.sql("insert into asdf select * from (select ... |
from flask import Flask, render_template, redirect, request, url_for, session, flash, send_from_directory
from flask_pymongo import PyMongo
from pymongo import MongoClient
from werkzeug.utils import secure_filename
import os
from os.path import join, dirname, realpath
#Uploading folders Configurations
ALLOWED_EXTENSIO... |
import uuid
from django.contrib.gis.db import models
from django.contrib.gis.geos import Point
from users.models import UserProfile
class Source(models.Model):
userprofile = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
source_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable... |
#=========================================================================
# pisa_sra_test.py
#=========================================================================
import pytest
import random
import pisa_encoding
from pymtl import Bits
from PisaSim import PisaSim
from pisa_inst_test_utils import *
#---------... |
# -*- coding: utf8 -*-
import os
import time
import requests
import datetime
import json
import selenium
from e_postman import send_mail
from selenium import webdriver
from selenium.webdriver.common import desired_capabilities
log_time = (datetime.datetime.utcnow() + datetime.timedelta(hours=+8)).strftime("%Y-%m-%d_%... |
"""empty message
Revision ID: 25ef2c40583c
Revises: bc92eafed48b
Create Date: 2019-03-06 20:19:18.238849
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '25ef2c40583c'
down_revision = 'bc92eafed48b'
branch_labels = None
depends_on = None
def upgrade():
# ... |
from subsf2net import settings
VBULLETIN_CONFIG = {
'tableprefix': settings.cfgTablePrefix,
'superuser_groupids': settings.cfgSuGids,
'staff_groupids': settings.cfgStaffGids,
'standard_groupids': settings.cfgStandardGids,
'paid_groupid': settings.cfgPaidGid,
'not_paid_groupid': settings.cfgNotP... |
import pygame
from pygame.sprite import Group
import game_functions as gf
from settings import Settings
from ship import Ship
from game_stats import Game_stats
from button import Button
from scoreboard import Scoreboard
# def check_events():
# #check for keypress and mouse events
def run_game():
# intializ... |
# q5
# list1=['one','two','three','four','five']
# list2=[1,2,3,4,5]
# # k=[]
# # i=0
# # while i<len(list1):
# # k.append([list1[i],list2[i]])
# # i+=1
# # l={}
# # l.update(k)
# # print(l)
# # second method
# k={}
# for i in range(len(list1)):
# k.update({list1[i]:list2[i]})
# print(k)
d=["keemaya","17",... |
class Node(object):
def __init__(self, my_id, my_node_coordinates, my_demand):
self.id = my_id
self.coordinates = my_node_coordinates
self.demand = my_demand
self.visited = False
def __eq__(self, other):
if not isinstance(other, Node):
print("you tried to co... |
'''
Copyright (C) 2017-2020 Bryant Moscon - bmoscon@gmail.com
Please see the LICENSE file for the terms and conditions
associated with this software.
'''
import sys
from setuptools import setup
from setuptools import find_packages
from setuptools.command.test import test as TestCommand
ld = None
try:
import pyp... |
# -*- coding: utf-8 -*-
import time
from datetime import datetime
from dateutil.relativedelta import relativedelta
from openerp.osv import fields, osv
import openerp.addons.decimal_precision as dp
from tools.translate import _
class account_asset_asset_depreciar(osv.osv):
_name = 'account.asset.asset.depreciar' ... |
#!/usr/bin/env python
def try_to_change(n):
n = 'Green George'
name = 'Emma Friord'
try_to_change(name)
print name
|
N, M = map( int, input().split())
A = [ list( map( int, input().split())) for _ in range(N)]
A.sort()
ans = 0
now = 0
for i in range(N):
if now + A[i][1] <= M:
ans += A[i][0]*A[i][1]
now += A[i][1]
else:
ans += A[i][0]*(M - now)
break
print( ans)
|
from lib.randomizer import get_random_first_name, get_random_last_name
REGISTRATION_DATA = {
'first_name': get_random_first_name(),
'last_name': get_random_last_name(),
'company_name': 'Test Company',
'country': 'Україна',
'city': 'Test city',
'phone': '0000000000',
'template': 'Ремонт моби... |
#!/usr/bin/env python
# coding: utf-8
# # 이거 뭐하는 거지...?
#
# - 주피터 노트북에서 텐서플로우를 사용해본데...
# In[1]:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import tensorflow as tf
a = tf.constant(100)
b = tf.constant(50)
add_op = a + b
v = tf.Variable(0)
let_op = tf.assign(v, add_op)
# In[2]:
ses... |
import hashlib
from onegov.activity.models import Activity, Attendee, Booking, Occasion
from onegov.user import User
from sqlalchemy import func
class Scoring:
""" Provides scoring based on a number of criteria.
A criteria is a callable which takes a booking and returns a score.
The final score is the s... |
from model.user_account import UserAccount
class Guest(UserAccount):
def __init__(self, name, pwd):
UserAccount.__init__(self, name, "guest", pwd, "guest", 2)
|
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 18 22:28:27 2017
@author: Gavrilov
"""
class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, other): #methods ways of manipulating attributes
#we need to have the fi... |
#!/usr/bin/env python
"""Implementation of soccer goal detection
Goal is represented by 2 orange/red cones (pylons)
"""
# For Python2/3 compatibility
from __future__ import print_function
from __future__ import division
import sys
import os
import math
import rospy
import angles
import tf
from cv_bridge import Cv... |
import cv2
# read the image
img = cv2.imread("20190417_143055.jpg")
# resize the image to 500 x 500
img = cv2.resize(img, (500, 500))
# convert BGR to greyscaale image
grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# invert the grey image
grey_inv = 255 - grey
# add guassian blur to it
grey_inv_blur =... |
import os.path
def download_file(url, filepath=None):
if filepath:
if filepath.endswith('/'):
filename = url.split('/')[-1]
filepath = os.path.join(filepath, filename)
else:
filepath = url.split('/')[-1]
r = requests.get(url, stream=True)
with o... |
#!/usr/bin/python3
# -*- coding:utf8 -*-
# Author : Arthur Yan
# Date : 2019-02-16 15:50:14
# Description : 百钱百鸡
# cocks 1-5
# hens 1-3
# chickens 3-1
# cocks + hens + chickens = 100
# 5*cocks + 3*hens + 1/3*chickens =100
cocks = 100 // 5
hens = 100 // 3
chickens = 100
for cock in range(cocks)... |
#character identification
ch=input("Enter a character:")
asc=ord(ch)
if asc>=48 and asc<=57:
print("%c is a digit"%(ch))
elif asc>=65 and asc<=90:
print("%c is a capital letter"%(ch))
elif asc>=97 and asc<=112:
print("%c is a small letter"%(ch))
else:
print("%c is a special symbol"%(ch))
|
def solution(x,y):
ans = ''
nowx, nowy = 0,0
preX = [0]*31
preY = [0]*31
for i in range(31):
if nowx < x:
nowx += 2**(30-i)
preX[i] = 1
else:
nowx -= 2**(30-i)
preX[i] = -1
if nowy < y:
nowy += 2**(30-i)
... |
from src.image_processing import histogram
#######
# Inputs
#######
grey_scale = 8
matrix_str = """
4 5 5 7
7 5 7 8
4 5 6 5
8 6 5 7
"""
#######
# Solution
#######
if __name__ == '__main__':
histogram.resolve(matrix_str, grey_scale)
|
#!/usr/bin/env
############################################
# exercise_8_basic.py
# Author: Paul Yang
# Date: June, 2016
# Brief: handling valueError exception
############################################
############################################
# print_file()
# open file by the filepath user input
# inputs: No... |
import pytest
def test_endpoint(client):
response = client.post(
'/analyze_slack',
content_type="application/json",
json={'text': 'test __eou__ another'}
)
payload = response.get_json()
print(payload)
for field, value_type in [
('conf_speech_acts', list),
('... |
from gemlibapp import create_app # since this exists in __init__.py it can be found and imported
app = create_app()
if __name__ == "__main__":
app.run(debug=True, host='localhost')
|
""" For use in dumping single frame ground truths of EuRoc Dataset
Adapted from https://github.com/ClementPinard/SfmLearner-Pytorch/blob/0caec9ed0f83cb65ba20678a805e501439d2bc25/data/kitti_raw_loader.py
You-Yi Jau, yjau@eng.ucsd.edu, 2019
Rui Zhu, rzhu@eng.ucsd.edu, 2019
"""
from __future__ import division
import num... |
# -*- coding: utf-8 -*-
import numpy as np
from framework.modules import Module
class LossMSE(Module):
"""Implements the MSE loss computation"""
def forward(self, output, target):
"""
Carries out the forward pass for backpropagation.
INPUT
output: Tensor with output of the... |
#!/usr/bin/env python
"""Update the circulation manager server with new books from OPDS 2.0 import collections."""
import os
import sys
bin_dir = os.path.split(__file__)[0]
package_dir = os.path.join(bin_dir, "..")
sys.path.append(os.path.abspath(package_dir))
from core.scripts import OPDSImportScript
from core.model... |
import argparse
from pathlib import Path
from cheffu.tokenize import tokenize
from cheffu.validate import validate
from cheffu.graph import generate_graph
from cheffu.shopping_list import shopping_list
from cheffu.format import format_standard
if __name__ == "__main__":
arg_parser = argparse.ArgumentParser(descr... |
#-*- encoding=utf8 -*-
#!/usr/bin/env python
import sys, operator, string,re,Queue,threading
path_to_stop_words = 'BasicData/stop_words.txt'
path_to_text = 'BasicData/Pride_And_Prejudice.txt'
word_space = Queue.Queue()
freq_space = Queue.Queue()
stop_words = set(open(path_to_stop_words).read().split(','))
# for w ... |
#!/home/mumaxbaby/anaconda3/envs/pmp/bin/python
"""
Author: Jialun Luo
Calculate time resolved field propagation of some photonic crystal structure
Note: on a different machine, check the #! statement at the beginning of the file
Parameters:
sidebankThickness,
separation - the distance between the centers of air cyli... |
#!/usr/bin/env python
import rospy
import tf
import threading
import time
from numpy import *
import sys
import std_msgs
class ViconTracker(object):
Xx = 0
Yy = 0
Oo = 0
def __init__(self, name):
#init_node()
#rospy.init_node('Whatever')
self.target = 'vicon/' + name + '/' + name
self.x = 0
self.y ... |
import pandas as pd
import numpy as np
from ortools.linear_solver import pywraplp
import ortools
import torch
import torch.nn as nn
import torch.utils.data
import utils_new as ut
sigmoid_inverse = lambda x : torch.log(x/(1-x))
class MLP(nn.Module):
def __init__(self, D_in, hidden):
super(MLP,self).__init__()
... |
"""
MetaGenScope-CLI is used to upload data sets to the MetaGenScope web platform.
"""
import os
import sys
from setuptools import find_packages, setup
from setuptools.command.install import install
from metagenscope_cli import __version__
dependencies = [
'click',
'requests',
'configparser',
'pand... |
import requests
from bs4 import BeautifulSoup
import json
from urllib import request, parse
import pandas as pd
import os
import time
import shutil
import csv
from pprint import pprint
import pymongo as pm
import datetime
class MongoOperator:
def __init__(self, host, port, db_name, default_collection):... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
将结果写入web接口
"""
import os
BASEDIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.path.join(BASEDIR)
ERROR_LOG_FILE = os.path.join(BASEDIR, "log", 'error.log')
RUN_LOG_FILE = os.path.join(BASEDIR, "log", 'message.log')
# MQ_SERVER = "192.168.0.1"
# MQ_P... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-10-18 00:40
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('evesde', '0008_invcategory'),
]
operations = [
migrations.AlterField(
... |
"""Communicate from server to raspberry pi"""
import socket
import sys
import queue
import serial
import syslog
import time
import math
import threading
'''from TopsidesGlobals import GLOBALS
#import topsidesComms
# Change IP addresses for a production or development environment
if ((len(sys.argv) > 1) and (sys.argv[1... |
# Copyright (c) 2020 Dell Inc. or its subsidiaries.
# 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 requi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.