text stringlengths 38 1.54M |
|---|
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... |
#from webapi.rug_manage_gpio import start_timer
#import django,os,sys
#print("starting timer..............")
#project_path = os.path.dirname(os.path.realpath(__file__))
#os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangorug.settings")
#sys.path.append(project_path)
#django.setup()
#start_timer()
|
import psycopg2
import psycopg2.extras
import config
class Dbase:
def __init__(self):
self.database = config.database
self.user = config.user
self.password = config.password
self.host = config.host
self.port = config.port
self.conn = psycopg2.connect(database = self.d... |
# imports
from nodes import *
from transactions import *
from threading import Thread
from topology.graph import Graph
from scipy.stats import dgamma
import os
import json
import sys
class Topology(Graph):
def __init__(self, initial_nodes=number_of_nodes):
Graph.__init__(self)
# creates nodes and m... |
class RPS:
ROCK = "rock"
PAPER = "paper"
SCISSOR = "scissor"
def get_choice(self):
return (self.ROCK, self.PAPER, self.SCISSOR)
|
import pickle
import sys
import matplotlib.pyplot as plt
class CustomHistory:
def __init__(self, training_loss, validation_loss):
self.history = {}
self.history["loss"] = training_loss
self.history["val_loss"] = validation_loss
# Plot history over epochs to see if the model overfits
def p... |
#!/usr/bin/python
#
# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Unit tests for cros_build_lib."""
import mox
import os
import tempfile
import unittest
import cros_build_lib
class CrosBuild... |
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Items
class ItemsView(APIView):
def get(self,request):
if 'name' in request.GET:
data=Items.objects.filter(name=request.GET['name']).values('name','price... |
Python 3.9.7 (tags/v3.9.7:1016ef3, Aug 30 2021, 20:19:38) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> 2 + 2
4
>>> 3 * 10
30
>>> 100 - 10
90
>>> 25 / 5
5.0
>>> 10 / 3
3.3333333333333335
>>> 10 // 3
3
>>> print('Mijn naam is Faiss')
Mijn naam is Faiss
... |
from django.shortcuts import render
import pandas as pd
import math
dict = {'PM2.5': None,
'PM10': None,
'SO2': None,
'NO2': None,
'CO':None,
'O3':None}
def home_view(request,*args, **kwargs):
df = pd.read_csv('Data.csv')
pm25 = df['PM2.5'].tolist()
pm... |
from pynput.mouse import Button,Controller
from PIL import ImageGrab
from time import sleep
bbox = (180,185,710,730)
mouse = Controller()
sleep(0.5)
for j in range(336,550):
for i in range(0,6):
print(i)
mouse.position = (1500, 200)
mouse.press(Button.left)
mouse.position ... |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 29 17:53:25 2017
@author: 5558
"""
import urllib3 as ul
from bs4 import BeautifulSoup
import os
import time
#import requests
#import urllib2
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.sup... |
import turtle
tom = turtle.Turtle()
canvas = turtle.Screen()
tom.speed(10)
tom.penup()
tom.goto(-400,100)
tom.pendown()
tom.fillcolor("yellow")
tom.begin_fill()
tom.right(90)
tom.forward(300)
tom.left(90)
tom.forward(800)
tom.left(90)
tom.forward(150)
tom.left(90)
tom.forward(200)
tom.right(90)
tom.forward(150)
tom... |
from morse.builder import *
# Adding the Robot ATRV
robot = ATRV()
robot.translate(x=0.8, z=0.2)
robot.rotate(x=0.0, y=0.0, z=3.14)
# Adding the Robot's differential drive actuator
motion_vw = MotionVW()
robot.append(motion_vw)
# Adding a waypoint Actuator
waypoint = Waypoint()
waypoint.properties(ObstacleAvoidance... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-22 16:18
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('filmApp', '0016_auto_20170221_2247'),
]
operations = [
migrations.AddField(... |
from greeter_client import ApiClient, Configuration, DefaultApi, Person
configuration = Configuration()
client = ApiClient(configuration)
api = DefaultApi(client)
me = Person(name='bryan')
greeting = api.greet(me)
print(greeting.message)
|
from spotty.commands.writers.abstract_output_writrer import AbstractOutputWriter
from spotty.deployment.abstract_cloud_instance.abstract_instance_deployment import AbstractInstanceDeployment
from spotty.deployment.container.docker.docker_commands import DockerCommands
from spotty.deployment.utils.print_info import rend... |
# This is the multi-wall model optimization porblem generator
# Created by: Salaheddin Hosseinzadeh
# Created on: 01.06.2018
# Last revision:
# Notes:
#####################################################################################
import numpy as np
def multiWallOptim(txPower, lossExp = 1,losDistance,LoS... |
#!/usr/bin/env python
from ROOT import *
import sys
import os
#import optparse
import shutil
analysisParamsXML = """
<analysis name=\"@ANALYSISNAME@\">
<ntuple>@NTUPLENAME@</ntuple>
<branches>control/branch_list_@NTUPLENAME@.txt</branches>
<tree>@TREENAME@</tree>
<histograms>control/histograms_@ANALYSISNAME@.... |
from time import time
def primes(limit=100000000):
sub_lim=int(limit**.5)
flag=[0,0]+[1]*(limit-2)
for x in range(3,limit,2):
if not flag[x]:
continue
if ispan(x):
yield x
if x<=sub_lim:
for y in range(x*x,limit,x<<1):
flag[y]=0
de... |
# -*- coding: utf-8 -*-
from odoo import fields, models
class HrEmployeePrivate(models.Model):
_inherit = 'hr.employee'
providient_pay_line_ids = fields.One2many('hr.payslip.line', 'employee_id', string='', domain=[('salary_rule_id.is_providient_found', '=', 'True'), ('slip_id.state', '=', 'done')])
cont... |
import bpy;
__author__="ashok"
__date__ ="$Mar 23, 2015 8:16:11 PM$"
class GenericLandmarksMessageBox(bpy.types.Operator):
bl_idname = "genericlandmarks.messagebox"# unique identifier for buttons and menu items to reference.
bl_label = "Message Box" # display name in the interface.
bl_spac... |
"""
Copyright 2013 Rackspace
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
dist... |
import pytest
import climpred
@pytest.mark.parametrize("cross_validate", [False, True])
def test_seasonality_remove_bias(hindcast_recon_1d_dm, cross_validate):
"""Test the climpred.set_option(seasonality) changes bias reduction."""
hindcast = hindcast_recon_1d_dm
hindcast._datasets["initialized"] = (
... |
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/discuss/755030/Super-Short-Python3-Beats-90
class Solution:
def getTarg... |
'''
作者:lg
日期:2019/8/31
文件描述:字符串常见方法
缺陷:
'''
# 切记,字符串是不可变对象,任何操作对原字符串都没有影响,都是生成新的字符串了
# 1、大小写转来转去
s1 = "python"
# 第一个字母变成大写
ret1 = s1.capitalize()
print(ret1)
# ⼤⼩写的转换
ret = s1.lower() # 全部转换成⼩写
print(ret)
ret = s1.upper() # 全部转换成⼤写
print(ret)
# 应用于验证码
# verify_code = 'aBcDe'
# user_code = input('请输入验证码:')
# if ... |
# NumPy
# An essential library used for scientific computing in Python.
# Holds data in N-dimensional array (ndarray) objects,
# which can store data in multiple dimensions.
# Supports performing efficient array operations through
# Broadcasting feature.
# Each data element of a ndarray is of fixed size.
# All elem... |
from PIL import Image
from os import walk, rename
def get_filenames(path):
files = [x[2] for x in walk(path)]
files = files[0]
return files
def resize_images(files, src, dest, code):
count = 0
for img in files:
print(img)
count += 1
im = Image.open(src+img)
... |
import random, time
# 单行注释 快捷键:ctrl+/
print('星魂')
# ▼
# 算数运算符:+ - * / //:取整 % **:次方
#
print(4//3)
print(4/3)
print(2**3)
# 变量 python严格区分大小写 eg:A a python中变量:单词小写,多个单词间使用下划线;项目名使用大驼峰
name = '大司命'
print(name)
price = 8.5
weight = 7.5
total_price = price*weight
print(total_price)
# ▼1
# 数据类型... |
print("Welcome to Hangman")
word = "python is fun"
# python is fun
# ------ -- ---
total_guesses = 10
guesses = ""
while total_guesses > 0:
not_guessed = 0
for char in word:
if char in guesses:
print(char, end='')
elif char == ' ':
print(' ', end='')
else:
print("-", end='')
not_guessed += 1
... |
# Auto Wifi Connector
# Process Of Working:
'''
1. Check the saved networks in the system.
2. Find active or available network from it.
3. Ask user to connect to which network out of those.
4. Disconnect present or current network if connected.
5. If connection fails or is denied, exit the program.
6. If its accessed, ... |
import pandas as pd
import pickle
import json
import numpy as np
import math
import matplotlib.pyplot as plt
import matplotlib.colors as clr
import matplotlib as mpl
def oddRatioMap(finalConfusionMat):
outfile = "featureLabel.npy"
featureLabel = np.load(outfile)
confusionMatFlat = finalConfusionMat.flatten()
a ... |
# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name: 有效的山脉数组
# Author: Nino
# Date: 2020/11/3
# Note:
# -------------------------------------------------------------------------------
class Solution:
def validMountainArray(self, A)... |
import pandas as pd
from fastai.vision import Path, ClassificationInterpretation, models
from fastai.metrics import accuracy_thresh, fbeta
from utils import my_cl_int_plot_top_losses, get_data_augmentation_transforms, get_frequency_batch_transforms, create_cnn
from functools import partial
from audio_databunch import A... |
import datetime as dt
import pandas as pd
from pytest import raises, fixture
from bgbb.sql.sql_utils import to_sql_list, mk_time_params
mod_win1 = 90
mod_win2 = 120
ho_win1 = 14
ho_win2 = 21
@fixture
def r1():
return mk_time_params(
HO_WIN=ho_win1, MODEL_WIN=mod_win1, ho_start="2018-08-01"
)
@fi... |
from controller.phases import Phase
from controller.events import StartTurn
from model.board_state import BoardState
from model.purchaser import Purchaser
from datetime import datetime, timedelta
import time
class Controller:
def __init__(self, net_players, rnd_units):
self.phase = Phase.INIT
self... |
from django.contrib import admin
from .models import (
Param,
)
class ParamInline(admin.TabularInline):
model = Param
fields = ('code', 'name', 'value_type', 'value', 'active')
extra = 0 |
from db import *
from db.models import *
from collections import OrderedDict
import click
@transactional
def address(session=None, address_id=5571):
"""Test joining tbladdress to tlkpaddressaccessibility"""
address = session.query(Address).filter_by(id=address_id).one()
return_value = "Address {} is '{}'".form... |
#!/usr/bin/env python3
'Unit test for trepan.processor.command.break'
import os, unittest
from import_relative import import_relative
Mcmdbreak = import_relative('processor.cmdbreak', '...trepan')
Mbreak = import_relative('processor.command.break', '...trepan')
class TestBreakCommand(unittest.TestCase):
def ... |
from django.db import models
from froala_editor.fields import FroalaField
# Create your models here.
class News(models.Model):
NEWS_TYPE = (
(1, '公司新闻'),
(2, '行业新闻'),
)
title = models.CharField(max_length=30, verbose_name="文章标题", blank=False)
newsType = models.IntegerField(choices=NEW... |
#! /usr/bin/env python3
# really simple assembler for dcpu
def convert_to_number(s):
s = s.strip()
sign = 1
if s[0] == '+':
s = s[1:]
elif s[0] == '-':
sign = -1
s = s[1:]
if s[0] == '$':
num = int(s[1:],16)
elif s[0:2].upper() == "0X":
num = int(s[2:], ... |
from collections import OrderedDict
from django import forms
from django.conf import settings
from django.contrib import admin, messages
from django.contrib.admin.widgets import FilteredSelectMultiple
from django.contrib.auth import get_user_model
from django.shortcuts import get_object_or_404, redirect, render
from d... |
import psycopg2
from datetime import date
from mainConfiguration import shouldUpdateOrInsert as crud_op, stock_table_all_data_query
class database:
connection = 0
cursor = 0
allStocks = []
allStatusStocks = []
allStockTableStocks = []
def __init__(self):
try:
self.connect()
... |
from rest_framework import viewsets
from fitness_app.serializers import ProgramSerializer
from fitness_app.models import Program
class ProgramViewSet(viewsets.ReadOnlyModelViewSet):
"""
Program view set
"""
queryset = Program.objects.select_related('teacher_v2').all()
serializer_class = ProgramS... |
import cv2
import easyocr
file = open('output.txt', 'r')
names = file.readlines()
file_name = names[0].split('\n')[0]
img = cv2.imread(file_name)
frame_thickness = 3
color = (255, 0, 0)
number_plate = []
for i in range(1, len(names)):
lines = names[i]
line = lines.split(" ")
top_left = (int(line[0]), int(line[... |
#!/usr/bin/env python
# coding:utf-8
"""
数组 & 链表
Array & Linked List
"""
# ================================================================================
"""
LeetCode 206
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
"""
# Definition for singly-linked list.
class ListNode(object):
def __init... |
$NetBSD: patch-Lib_test_test__posix.py,v 1.1 2020/11/17 19:33:26 sjmulder Exp $
Support for macOS 11 and Apple Silicon (ARM). Mostly backported from:
https://github.com/python/cpython/pull/22855
--- Lib/test/test_posix.py.orig 2020-08-15 05:20:16.000000000 +0000
+++ Lib/test/test_posix.py
@@ -1502,9 +1502,239 @@ clas... |
import pandas as pd
def group_columns(dataset):
"""
a function to group together columns
returns a dictionary
keys refer to the question number
values refer to the actual column names
"""
# locating the columns to be reorganised
cols = dataset.columns[6:(len(dataset.columns)-1)]
# setting vars to represent... |
from django.conf.urls import patterns, url
from cron import views
from players import views as players_views
urlpatterns = patterns('',
url(r'registration/$', players_views.register, name='players_registration'),
url(r'registration/([-\w]+)', players_views.activate, name='players_activation'),
#url(r'chan... |
#!/bin/python
#import global_variables as gv
from pca import pca_X
import numpy as np
global train_labels
train_labels=np.loadtxt('dataset/dorothea_train.labels')
class_indices = []
class_indices.append(np.where(train_labels==-1))
class_indices.append(np.where(train_labels==1))
#replace class label -1 with 0 for eas... |
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request, "BootGridApp/signIn.html")
def signIn(request):
return render(request, "BootGridApp/signIn.html")
def signUp(request):
return render(request, "BootGridApp/signUp.html")
|
# -*- coding: utf-8 -*-
print abs(100)
print abs(-20)
print abs(12.34)
print cmp(1, 2)
print cmp(2, 2)
print cmp(2, 1)
print int('123')
print int(12.34)
print float('12.34')
print str(1.23)
print unicode(100)
print bool('')
print bool('1')
a = abs
print a(-20)
|
# By Tom Driessen. Some more helper functions to keep the jupyter notebooks less cluttered.
import pandas as pd
import numpy as np
from os import listdir
import matplotlib.pyplot as plt
from scipy import stats
import pickle
def save_obj(obj, name, path = 'obj/'):
with open(path + name + '.pkl', 'wb') as f:
... |
def calculation_factorial(n):
result = 1
for num in range(1, n + 1):
result *= num
return result
number_1 = int(input())
number_2 = int(input())
factorial_number_1 = calculation_factorial(number_1)
factorial_number_2 = calculation_factorial(number_2)
res = factorial_number_1 / factori... |
base_infor = input() #輸入城鎮 基地台數 有效距離
info =base_infor.split() #將輸入分割為清單
townnum = int(info[0])
machinenum = int(info[1])
distance = int(info[2])
# townnum = 8 #城鎮數量
# machinenum = 3 #基地台數量
# distance = 3 #基地台有效範圍
xyp = [[0 for i in range(3)] for j in range(townnum)]
for i in range(townnum):
base_xyp = input()
base_x... |
from random import randrange, randint, seed
from traffic_generator import TrafficGenerator
import numpy as np
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
import csv
seed(314)
def get_digits(n):
digits=0
while(n>0):
digits+=1
n=n//10
return digits
NUMBER... |
# A file which contains a basic click and drag bounding box as a callback
# function for a window.
import cv2
import numpy as np
drawing = False
ix, iy = -1, -1
fx, fy = -1, -1
# Image callback function
def drawBox(event, x, y, flags, param):
global ix, iy, fx, fy, drawing
if event == cv2.EVENT_LBUTTONDOWN:
draw... |
# WAP find all each occurance of a vowel count from the given string
a = 0
e = 0
i = 0
o = 0
u = 0
str1 = "hyderabad-banaglore-india"
for ch in str1:
if ch == 'a':
a = a+1
elif ch == 'e':
e = e+1
elif ch == 'o':
o = o+1
elif ch == 'i':
i = i +1
eli... |
__author__ = 'mikeknowles'
"""
Strain-specific probe idenification through:
BLASTing at different e-values
Masking of the resultant
"""
import time, Queue, threading, cStringIO, os, re, sys
from GeneSeekr import makedbthreads
from shutil import copy
from Bio.Blast.Applications import NcbiblastnCommandline
from Bio impo... |
import json
from django.shortcuts import render
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from django.http import HttpResponse
from django.contrib.auth.decorators import user_passes_test
from main.forms import SignInForm
import main.management.commands.generate_no... |
#importing libraries
import numpy as np
import pandas as pd
import keras
from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasClassifier
import torch.nn as nn
import torch.nn.parallel
import torch.utils.data
import torch.optim as optim
from torch.autograd impo... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from tree_node_lib import *
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
if not root:
return 0
def dfs(ro... |
import os
def remove_file(filename):
try:
os.remove(filename)
except FileNotFoundError:
pass
def main():
input_file = 'backup.txt'
output = 'output/2.csv'
remove_file(output)
# i = open(input_file, 'r')
new_file = {}
for i in open(input_file, encoding="utf8").readli... |
name = str(input("Please Enter your name: "))
print(name[0] + ' ' + 'ASCII value is ' + str(ord(name[0])))
for c in range(4):
print("%s ASCII value is %d"%(name[c],ord(name[c])))
|
import unittest
import json
from healthcheck import create_app, db
from healthcheck.data.models import Projects
header = {'content-type': 'application/json'}
content_type = 'application/json'
data = {'name': 'test project',
'email': 'test@rackspace.com',
'description': 'A test project',
'depen... |
# -*- coding: utf-8 -*-
import numpy as np
import cv2
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
DRIVER = './chromedriver'
FILE_NAME = 'capture.jpg'
options = Options()
options.add_argument('--headless')
options.add_argument('--disable-gpu')
options.add_argument('--start-ful... |
"""Twitter routes (FLASK)."""
from flask import Blueprint, render_template, request, url_for
from twitoff.basilica_service import basilica_api
from twitoff.models import Tweet, Tweeter, db
from twitoff.twitter_service import get_timeline, get_user, twitter_api
twitter_routes = Blueprint('twitter_routes', __name__)
... |
# From: 'cat Documents/History | grep Release'
# Added afterwards
versions_list = ([
"v1.0.0",
"v1.1.0",
"v1.1.1",
"v1.1.2",
"v1.1.3",
"v1.2.0",
"v1.2.1",
"v2.0.0",
"v2.1.0",
"v2.2.0",
"v2.2.1",
"v2.3.0",
"v2.4.1",
"v2.5.0",
"v2.6.0",
"v2.7.0",
"v3.0.0... |
from database import userLensBag
from lensStats import getLensStats, getTotalLensInstances
from lensOps import getLens
from google.appengine.ext import db
from google.appengine.api import memcache
def userBagCacheKey(userID, lensID=None):
if lensID is not None:
return userID + lensID + 'bagInstance'
else:
return... |
from m5stack import *
from m5stack_ui import *
from uiflow import *
import wifiCfg
import urequests
import time
import json
import unit
screen = M5Screen()
screen.clean_screen()
screen.set_screen_bg_color(0xffffff)
Watering_1 = unit.get(unit.WATERING, (26,35))
env2_1 = unit.get(unit.ENV2, unit.PORTA)
light_1 = unit.g... |
import io
from text import cmudict
test_data = '''
;;; # CMUdict -- Major Version: 0.07
)PAREN P ER EH N
'TIS T IH Z
ADVERSE AE0 D V ER1 S
ADVERSE(1) AE1 D V ER2 S
ADVERSE(2) AE2 D V ER1 S
ADVERSELY AE0 D V ER1 S L IY0
ADVERSITY AE0 D V ER1 S IH0 T IY2
BARBERSHOP B AA1 R B ER0 SH AA2 P
YOU'LL Y UW1 L
'''
... |
# ******************************************************
# * Copyright © 2016-2023 - Jordan Irwin (AntumDeluge) *
# ******************************************************
# * This software is licensed under the MIT license. *
# * See: LICENSE.txt for details. *
# ********************************... |
yourWeight = 100.0
for i in range (0,10):
moonWeight = yourWeight / 6
print(moonWeight)
yourWeight = yourWeight + 1 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-03-28 01:10
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('custome... |
#!/usr/bin/env python3
import glob, os
#
# Changes the file extensions of files in a directory
#
# param1: filename with full path
#
def replace_whitespace_with_delimeter(fullpath_filename, delimiter, new_delimiter):
path = os.path.split(os.path.abspath(fullpath_filename))[0]
split_filename = os.path.split(os.... |
# -*- coding: utf-8 -*-
"""
练习:九九乘法表
"""
for row in range(1, 10):
for col in range(1,row+1):
print(f'{row} * {col} = {row * col}', end=' ')
# 为了控制换行
print() |
from configparser import ConfigParser
from os import environ
default_config_if_error = {
'host': '0.0.0.0',
'port': 8080,
'debug': True,
'reloader': True
}
config = ConfigParser(default_config_if_error)
config.read('project_root.ini')
try:
if environ['BOTTLE_ENVIRON'] == 'dev':
default_co... |
class Alarm:
def __init__(self):
months = {'January': 1, 'February': 2, 'March': 3, 'April': 4, 'May': 5, 'June': 6,
'July': 7, 'August': 8, 'September': 9, 'October': 10, 'November': 11, 'December': 12}
|
import math
angle = math.radians(int(input()))
print(round(math.cos(angle) / math.sin(angle), 10))
|
#import pigpio
#pi = pigpio.pi()
# this is a module in which the intializations of the motor and its direction of motion
class addmotor:
def __init__ (self ,gpiopin) :
self.pin = gpiopin
#pi.set_servo_pulsewidth(self.pin,1500) #intializing the motor to stop signal to triger the esc... |
# O(n) algorithm.
class Solution(object):
""" This is an O(n) greedy algorithm. The idea is that whenever we see a
increasing/descreasing sequence, we select the last element of this
sequence (i.e. the largest/smallest element of the sequence). For example,
for an array of ``[1, 2, 3, 4, 3, 5, 4, 3]`, w... |
from course_registration_api.domain.shared.value_object import ValueObject
from course_registration_api.domain.shared.exceptions \
import InvalidPeriodException
def _is_valid_period(value: int) -> bool:
if not isinstance(value, int):
return False
elif value < 1 or value > 8:
return False
... |
import cherrypy
import db
import loader
class info:
@cherrypy.expose
def index(self):
raise cherrypy.HTTPRedirect('/user/login')
@cherrypy.expose
def user_status(self,id_user):
a = db.query_select("select * from user where id_user = "+str(id_user)+"")
if a[10] == 0:
st... |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 22 05:24:10 2019
@author: chilton
This code collects images from the airsim simulator and stores them to disk.
"""
import airsim
import pprint
import os
from pathlib import Path
import numpy as np
import time
from PIL import Image
def SimCoordinate... |
import pygame
WHITE = (255, 255, 255)
class Spaceship(pygame.sprite.Sprite):
def __init__(self, x, y, color):
super().__init__()
self.image = pygame.Surface([x, y])
self.image.fill(WHITE)
self.image.set_colorkey(WHITE)
pygame.draw.rect(self.image, color, (x,y, 50, 50))
... |
# 包(目录) 模块(文件) 类
# 如果想然让一个目录成为一个包的话, 必须在包下面加添一个 __init__.py 文件
# 导入模块
import common.t_import
import common.t_import as alias_name
print(alias_name.a)
# 避免过长的引用名称
from common import t_import
print(t_import.a)
from common.t_import import a
print(a)
# 可以使用 import *, 在模块中定义 * 的行为 __all__ = ['b', 'c']
from common.t_i... |
import socket
#FOR TCP
#Max bytes can be sent so ESP can forward that also to next host then max bytes to be sent is 1460
#Otherwise it can recieve max of 2920 bytes
byteCount=1460
data="#"*byteCount
sender=socket.socket(socket.AF_INET,socket.SOCK_STREAM,0)
sender.connect(("192.168.4.1",9999))
sender.send(data)
|
score = input("Enter Score: ")
s = float(score)
if 0.0 <= s <= 1.0:
if s >= 0.9:
print ("A")
if 0.8 <= s < 0.9:
print ("B")
if 0.7 <= s <= 0.8:
print ("C")
if 0.6 <= s <= 0.7:
print ("D")
if s < 0.6:
print("F")
else: print("Error")
score = inpu... |
'''
Excel
install:
pip install openpyxl
pip install pandas
pip install xlrd
'''
import collections
import openpyxl
from openpyxl.chart import BarChart, Reference
import pandas as pd
''' ファイル読み込み '''
excel_bookname = 'file/Book1.xlsx'
df_master = pd.read_excel(excel_bookname, sheet_name='マスターデータ')
df_data = pd.r... |
# import your app modules here
import streamlit as st
from PIL import Image
from apps import home, data_stats, agendamentos, especialidades, pacientes, unidades, sandbox
from multiapp import MultiApp
#from apps import home, data_stats, agendamentos
app = MultiApp()
# adicionar aplicações aqui - pasta APPS
app.add_ap... |
def get_magic_triangle(n):
triangle = []
if n == 1:
triangle.append([1])
elif n == 2:
triangle.append([1])
triangle.append([1, 1])
else:
triangle = [[1], [1, 1]]
while len(triangle) < n:
current_row = triangle[len(triangle) - 1]
new_row = [... |
def T(x):
'''Recursive Definition'''
if x == 1:
return 2
elif x > 1:
return (T(x-1))+(x*x)+x
def R(x):
'''Closed Form Solution'''
return 2 + ((((2*x*x*x)+(3*x*x)+(x))/6)-1)+((((x*x)+x)/2)-1)
def main():
strline = "{0:<3} | {1:<6} | {2:<6}\n"
for i in ... |
# *_*coding:utf-8 *_*
import os
path='E:\\mywork\\school\\test_case\\'
caselist=os.listdir(path) #获取指定目录中的内容
for a in caselist:
s=a.split('.')[1] #选取后缀名为 py 的文件
if s=='py': #此处执行 dos 命令并将结果保存到 log.txt
os.system('E:\\mywork\\school\\test_case\\%s 1>>log.txt 2>&1'%a) |
import time
import os
def fun17():
print ("17 Pick the display screen")
def fun18():
print ("18 Place it on the PCB 1 board")
def fun19():
print ("19 Fix the position of display screen")
def solder4():
print ("4 Move the robot arm to the work bench from starting position")
def solder... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from textlabs_agent_gym.envs.utils import vocab_from_env
from textlabs_agent_gym.configs import root_path
if __name__ == "__main__":
save_path = root_path.parent.parent / 'lstm_dqn_baseline' / 'vocab.p'
env_id = 'tl_medium_level9_gamesize1000_step60_seed11344_tra... |
#################################################################
## Elevation on demand provisioners
## Ashish Anand
#################################################################
from django.db import models
from subprocess_logging import subprocess_call_with_output_returned
import datetime
import os
import textw... |
# Operasi Aritmatika
a = 24
b = 4
# operasi tambah +
hasil = a + b
print(a, '+', b, ' = ', hasil)
# operasi pengurangan -
hasil = a - b
print(a, '-', b, ' = ', hasil)
# operasi perkalian *
hasil = a * b
print(a, '*', b, ' = ', hasil)
# operasi pembagian /
hasil = a / b
print(a, '/', b, ' = ', hasil)
# operasi eks... |
#usage :python landmarkPredict.py predictImage testList.txt
# the point:
#0-15, left face edge (top to bottom)
#16-17, the bottom point
#18-33, right face edge (bottom to top)
#34-43, left eye brow (left to right)
#44-53, right eye brow (left to right)
#54-72,nose
#73-96, two eyes;
#97-136, the mouth
#to get the mos... |
from enum import Enum
class MarkerNames(Enum):
def __repr__(self) -> str:
return '{}'.format(self.name)
def __str__(self) -> str:
return '{}'.format(self.name)
def __new__(cls):
value = len(cls.__members__) + 1
obj = object.__new__(cls)
obj._value_ = value
... |
from setuptools import setup
setup(name='Soundex-Plus',
version='0.1',
description='A more accurate version of the traditional Soundex algorithm',
url='http://github.com/sreejithr/soundex_plus',
author='Sreejith R',
author_email='sreejith.r44@gmail.com',
license='MIT',
package... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.