text stringlengths 38 1.54M |
|---|
def removeValor(numeros, valor):
retorno = []
tamNumeros = len(numeros)
for cont in range(tamNumeros):
elemento = numeros[cont]
if(elemento != valor):
retorno.append(elemento)
return retorno
print(removeValor([1,2,4,5,6,3,2,4,5,12,2,3,2,4,5,2], 2))
|
class Car:
def __init__(self, pMake, pModel, pColor, pPrice):
self.make = pMake
self.model = pModel
self.color = pColor
self.price = pPrice
def __str__(self):
return 'Make = %s, Model = %s, Color = %s, Price = %s' %(self.make, self.model, self.color, self.price)
... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from getpass import getpass
phantomjs_exe = ".\\bin\\phantomjs.exe"
username = input("ENTER USERNAME - ")
if username == "":
f = open(".\\bin\\one_cred.txt")
cred = f.read().splitlines()
f.close()
username = cred[0]
pas... |
import re
#import csv
tag = re.compile(r'nav-\w+')
with open ('/Users/ymccarter/PycharmProjects/Mihon/Make-Life-Easy/DefCreation/awsdef4.yaml', 'r') as myfile:
data = myfile.readlines()
print(tag.search('My number is Value: nav-navigatorauthgateway'))
fw = open('deftag.txt', 'w')
deftag = []
for line in data:... |
import sys
import math
from elevator import *
DOOR_OPEN_TIME = 10
FLOORS_PER_SECOND = 1
INITIAL_FLOOR = 1
WAIT_TIME = 1
INFINITY = 9999
BUSY_FLOORS = {0:0, 1:1, 10:0, 100:0} #key is each floor, value specifies whether an elevator has been assigned to that floor or not
class Guest(object):
def __init__(self, id, star... |
list_of_numbers = []
def adding_to_list():
number_of_numbers = 5
order = 0
suffix = ""
while number_of_numbers > 0:
number_of_numbers = number_of_numbers - 1
order = order + 1
if order == 1:
suffix = "st"
elif order == 2:
suffix = "nd"
el... |
__author__ = 'gkour'
from simulator import Simulator, SimState
from visualization.dashboard import Dashboard
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import tkinter as tk
from tkinter import ttk, Scale
import matplotlib.pyplot as plt
from config import ConfigPhysics
import sys
from queue import ... |
# 物料编号申请模块
import json
from base_api.base import Base
from utils.get_pass_day import get_pass_date
from utils.get_today import get_today_date
class MatCodeApply(Base):
def search_by_order_no(self, order_no):
"""
根据单号查询
:param order_no: 单号
:return:
"""
url = self.ip... |
from __future__ import division # Use floating point for math calculations
from CTFd.plugins import register_plugin_assets_directory
from CTFd.plugins.flags import get_flag_class
from CTFd.utils.user import get_current_user
from CTFd import utils
from CTFd.models import (
db,
Solves,
Fails,
Flags,
... |
import os,time
Tree=[]
Incomplete_Paths=[]
def Is_File(Path):
return os.path.isfile(Path)
def File_Path_Handler(Dir):
Branches=List_Items_In(Dir)
for branch in Branches:
Path=Dir+'/'+branch
if Is_File(Path):
Tree.append(Path.lower())
else:
Incomplete_Paths.append(Path)
def List_Items... |
#!/usr/bin/env python
# pylint: disable=bare-except
import sys
from glob import glob as _glob
from pathlib import Path
import re
from subprocess import run
import os
import logging
from rich.panel import Panel
from rich.padding import Padding
from rich.console import Console
try:
from clavier import log as loggi... |
from functools import partial
from mmcv.runner import get_dist_info
from mmcv.parallel import collate
from torch.utils.data import DataLoader
import numpy as np
# https://github.com/pytorch/pytorch/issues/973
import resource
rlimit = resource.getrlimit(resource.RLIMIT_NOFILE)
resource.setrlimit(resource.RLIMIT_NOFILE... |
from geopy import geocoders
from pandas import merge, DataFrame
import time
def geocoder (df):
'''Takes a string of location information and geocodes the info into lat/long
coordinates and creates a string of locations of each specimen.'''
#Library for geocoding
#Change to match the geocoding column
locatio... |
from django.urls import path
from .views import IndexView, PostDetailView, ArchivesView, CategoryView, TagView, search
app_name = 'blog'
urlpatterns = [
path('', IndexView.as_view(), name='index'),
path('post/<int:pk>/', PostDetailView.as_view(), name='detail'),
path('archives/<int:year>/<int:month>/', A... |
from django.contrib.auth.base_user import BaseUserManager
from django.db import models
from db.base_model import BaseModel
from django.contrib.auth.models import AbstractUser
# Create your models here.
class UgcUserManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, username, password... |
import cv2
import numpy as np
import imutils
imag = cv2.imread('/home/frkn/Desktop/fotolar/solalt.png')
image = cv2.cvtColor(imag,cv2.COLOR_BGR2GRAY)
imag = imutils.resize(imag,width=750)
image = imutils.resize(image,width=750)
filtered_image= cv2.bilateralFilter(image,11,17,17)
canny = cv2.Canny(filtered_image,100,15... |
#!/usr/bin/env python
import rospy
from roslib import message
import rosbag
import std_msgs.msg
import sensor_msgs.point_cloud2 as pc2
from sensor_msgs.msg import PointCloud2, PointField
import numpy as np
# require the installation of ros-kinetic-tf2_sensor_msgs
from tf2_sensor_msgs.tf2_sensor_msgs import do_transfor... |
import requests
import os
import io
import json
import time
import configparser
def main():
# 1. Define raw directory, max length of the json message raw and the number of api units
# 2. For each json file in the directory
# 3. build single string of text
# 4. make sure its within the size limit
... |
from zoom.component import DynamicComponent
class ProgressWidget(DynamicComponent):
"""ProgressWidget
>>> progress = ProgressWidget()
>>> component = progress.format(
... title='Widget Title',
... hint='Widget hint',
... percent=75,
... color='blue',
... )
"""
... |
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options
class EdurekaOrg(unittest.TestCase):
def setUp(self):
options = Options();
options.headless = True;
... |
#-*- encoding: gb2312 -*-
import ConfigParser
import string, os, sys
import datetime
import time
class HbcIni:
def __init__(self,confpath = 'hbc.conf'):
self.confpath = confpath
self.cf = ConfigParser.ConfigParser()
self.cf.read(self.confpath)
def str2time(self,timestr):
t = ti... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2018/10/21 21:13
# @Author : Administrator
# @Site :
# @File : Python练习实例71.py
# @Software: PyCharm
"""
题目:
编写input()和output()函数输入,输出5个学生的数据记录。
-----------------------------------------------------
思路:
-----------------------------------------------... |
#!/usr/bin/python
#coding:utf-8
from django.conf.urls import url
from . import searchroute as route
urlpatterns = [
url(r'^$', route.indexpage, name='search'),
url(r'^searchmain/$', route.mainpage, name='searchmain'),
url(r'^searchdetail/$', route.detailpage, name='searchdetail'),
] |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 13 15:31:22 2017
@author: nooteboom
"""
from parcels import (ParticleSet, JITParticle, AdvectionRK4_3D,
ErrorCode, ParticleFile, Variable, Field)
from datetime import timedelta as delta
from datetime import datetime
import numpy as np
from glob impo... |
#!/usr/bin/python
""" A Python implementation of Load.js.
See Load.js's documentation for more details on what many of the properties do, as well as how the system works. This
module provides many methods of that package in Python with the same names and signatures.
"""
import os
from os import path
from sys import ... |
# Generated by Django 2.2.7 on 2019-12-02 17:03
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import utils.mixins
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MO... |
for i in range(5):
print(('*'*(5-i)) + (" "*i*2) + ('*'*(5-i)))
for i in range(1,6):
print(('*'*i) + (" "*2*(5-i)) + ('*'*i))
|
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
#Author D4RK5H4D0W5
C0 = "\033[0;36m"
C1 = "\033[1;36m"
G0 = "\033[0;32m"
G1 = "\033[1;32m"
W0 = "\033[0;37m"
W1 = "\033[1;37m"
R0 = "\033[0;31m"
R1 = "\033[1;31m"
try: import requests, sys, os, json
except: os.system('pip2 install requests')
try:
os.system('clear')
print... |
__copyright__ = """
Copyright (C) 2013 Andreas Kloeckner
Copyright (C) 2016 Matt Wala"""
__license__ = """
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 without li... |
from django.urls import path
from Personas.api.views.person_views import *
urlpatterns = [
path("create-person/", CreatePerson.as_view(), name='create-person'),
path("get-legal-entity/", GetLegalEntity.as_view(), name='get-legal-entity'),
path("get-natural-person/", GetNaturalPerson.as_view(), name='get-na... |
from config.base_config import BaseConfig
class SqlConfig(BaseConfig):
def __init__(self):
super().__init__()
self.file = 'sql.ini'
|
import RPi.GPIO as GPIO
import time
glue_sensor = 9
stamp_sensor = 19
buzzer = 19
GPIO.setmode(GPIO.BCM)
GPIO.setup(glue_sensor,GPIO.IN)
GPIO.setup(stamp_sensor,GPIO.IN)
GPIO.setup(buzzer,GPIO.OUT)
GPIO.output(buzzer,False)
print("IR Sensors are Ready.....")
print(" ")
try:
while True:
if GPIO.input(gl... |
def UltimaSifra(x):
xs="{0}".format(x)
Tamaño = len(xs)
print (Tamaño)
def rotar(xs=[]):
Pr=xs[0]
xs.pop(0)
xs.append(Pr)
return xs
def rotarN(n,xs=[]):
for i in range(0,n):
Pr=xs[0]
xs.pop(0)
xs.append(Pr)
return xs
def Rango(xs=[]):
xs.append(min(xs))... |
import re
txt="""
abcd
bfcd
352-980-879
123.436.908
675*576*894
800-980-879
900-980-879
Mr.Dragon
Mr.Cheetah
Mr. Tiger
Mr L
Ms.Divya
Mrs Savithri
arunbond30@skype.com
arunbond30@skype*com
arun.s.kumar@techmahindra.com
arun&43@example.com
arun... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
def solveIt():
"Return a string that is the screen name you would like."
return 'wkschwartz'
if __name__ == '__main__':
print('This script submits the screen name:', solveIt())
|
'''
Created on 14 nov. 2012
@author: naamane.othmane
'''
from django.contrib.auth.models import User
from django import forms
from django.utils.translation import ugettext_lazy as _
from my_forum.models import Thread,Post
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Submit, HTML... |
from sys import stdin
def pairSum0(l,n):
# Write your code here
d = {}
for i in l:
d[i] = d.get(i,0) + 1
count = 0
for j in d:
if j == 0:
k = d[j]
count = count+(k*(k-1)//2)
else:
if -j in d:
p = ... |
from pprint import pprint
from pymongo import MongoClient
from urllib.parse import quote_plus
import datetime
isinpackage = not __name__ in ['db', '__main__']
if isinpackage:
from .log import log
from .settings import settings
else:
from settings import settings
def log(module, msg):
print(modul... |
s=input()
res=[0]*len(s)
begin=0
s=list(s)
n=len(s)
index=0
while begin<n:
index=begin+s[begin:].index('L')
if index!=len(s)-1 and s[index+1]=='R':
if (index-begin+1)%2==0:
res[index]=(index-begin+1)//2
res[index-1]=(index-begin+1)//2
else:
res[index]=index-be... |
# coding=utf-8
import json
# 列表,相当于java的数组
# 最长应用场景:存储相同类型的数据,然后通过迭代遍历,再循环体内部,
# 针对列表中的每一项元素,执行相同的操作
name_list = ["zhangsan", "lisi", "wangwu"]
print (name_list)
# 通过索引取出列表中的数据,以索引从0开始
print (name_list[1])
# 1.取值和取索引,且注意不要超出索引范围
print (name_list[0])
# 根据列表中的内容取索引值,但是如果输入的内容列表中没有会报错
print (name_list.index("lisi"))
# ... |
import os
import time, datetime
import xlrd
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.utils.http import urlquote
from django.views.decorators.csrf import csrf_protect
from django.core.paginator import Paginator
from yqry import settings
from .models import yqdx_f... |
#!/usr/bin/env python
"""
triarbot: Simple triangular arbitrage bot
Python 3+
(C) 2018 SurgeonY, Planet Earth
Donate ETH: 0xFA745708C435300058278631429cA910AE175d52
Donate BTC: 16KqCc4zxEWf7CaerWNZdGYwyuU33qDzCv
"""
from threading import Thread, Event
import time
import logging
from exchange_apis.exmo_api import Exm... |
import requests
import re, lxml.html
import time, random
from excel_utils.excel_write import write_to_excel, append_to_excel
import os
res = []
# 国内所有省份url获取
start_url = 'http://www.tjcn.org/tjgb/'
header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
... |
from isis.dialog_search_text import Dialog_Search_Text, Data_Table_Model
from sarah.acp_bson import Client
class Search_Account(Dialog_Search_Text):
def __init__(self, parent=None):
Dialog_Search_Text.__init__(self, parent)
self.agent_caroline = None
def searching(self, e):
if self.ag... |
_base_ = 'mask-rcnn_regnetx-3.2GF_fpn_1x_coco.py'
model = dict(
backbone=dict(
dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False),
stage_with_dcn=(False, True, True, True),
init_cfg=dict(
type='Pretrained', checkpoint='open-mmlab://regnetx_3.2gf')))
|
__author__ = 'kic'
thread_create_response = {
"code": "",
"response": {
"date": "",
"forum": "",
"id": "",
"isClosed": "",
"isDeleted": "",
"message": "",
"slug": "",
"title": "",
"user": ""
}
}
|
import logging
from typing import Union
import virtool.errors
import virtool.http.proxy
import virtool.utils
logger = logging.getLogger(__name__)
BASE_URL = "https://api.github.com/repos"
EXCLUDED_UPDATE_FIELDS = (
"content_type",
"download_url",
"etag",
"retrieved_at"
)
HEADERS = {
"Accept": "... |
import os
import sys
import pygame
import requests
map_file = None
spn_number = [0.01, 0.02, 0.03, 0.05, 0.09, 0.18, 0.35, 0.7, 1.4, 2.8, 5.6, 11.1, 21.65, 40]
spn_count = 0
spn = 0.01
def draw():
global map_file
map_params = {
"ll": "37.530887,55.703118",
"spn": str(spn)... |
s = input("string de entrada: ")
sv = ""
for i in range(len(s)):
if(s[i] != "a" and s[i] != "A"):
sv = sv + s[i]
print(sv)
|
#!/usr/bin/env python
# encoding: utf-8
# package
'''
@author: yuxiqian
@license: MIT
@contact: akaza_akari@sjtu.edu.cn
@software: electsys-api
@file: /interface/__init__.py
@time: 2019/1/9
'''
from .interface import *
__all__ = ['ElectCourse', 'PersonalCourse',
'PersonalExam', 'PersonalScore', 'CourseDet... |
# Generated by Django 3.0.5 on 2020-09-16 15:03
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0002_pokemon_xp'),
]
operations = [
migrations.AddField(
model_name='pokemonteam',
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2020/6/11 6:05 下午
# @Author : Johny Zheng
# @Site :
# @File : autoAddFollower.py
# @Software: PyCharm
# Running based on python3.6.2 environment
from github import Github
import requests
import logging
import re
import base64
import config
class Ini... |
from typing import *
def repostaje(N: int, d: List[int]) -> List[int]:
res = [0]
km = N
for i, gdist in enumerate(d):
if gdist > km:
res.append(i)
km = N
km -= gdist
res.append(len(d))
return res
print(repostaje(150, [130, 23, 45, 62, 12, 110, 130]))
|
import time
import os
import argparse
import sys
import datetime
import platform
from libnyumaya import AudioRecognition
from libnyumaya import SpeakerVerification
if platform.system() == "Darwin":
from cross_record import AudiostreamSource
else:
from record import AudiostreamSource
fingerprints=[]
enrolling = 5
... |
class Solution:
def largestPerimeter(self, A):
A.sort(reverse=True)
for a , b , c in zip(A, A[1:], A[2:]):
if b + c > a:
return a + b + c
return 0 return 0
|
import pygame
from Character import Character
pygame.init()
screen = pygame.display.set_mode([2000, 1200])
c1 = Character(1000, [10-20])
c2 = Character(1100, [8-18])
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((25... |
import sys
import random
import string
import hashlib
import argparse
def proof_of_work(prototype, level=1, verbose=False):
if not prototype:
prototype = random_prototype()
count = 0
while True:
for y in range(0, 256):
for x in range(0, 256):
h = hashlib.sha256(b... |
import tkinter as tk
from tkinter import filedialog
from PIL import Image
root = tk.Tk()
canvas1 = tk.Canvas(root, width=300, height=250, bg='azure3', relief='raised')
canvas1.pack()
label1 = tk.Label(root, text="Image Converter", bg='azure3')
label1.config(font=('helvetica', 20))
canvas1.create_window(150, 60, windo... |
from skdecide.builders.discrete_optimization.generic_tools.result_storage.result_storage import ResultStorage, result_storage_to_pareto_front
from typing import List, Tuple, Dict, Union, Set, Any, Optional
from skdecide.builders.discrete_optimization.generic_tools.do_problem import Problem
from skdecide.builders.discre... |
weight = eval(input("Input you weight in KG\n"))
height = eval(input("Input you Height in CM\n"))
BMI = (weight/(height*height))
print("Your BMI is =", BMI) |
class Habit:
def __init__(self, name, quota , period):
self.name = name
self.quota = quota
self.period = period
def __repr__(self):
return "Habit('{}', '{}', {})".format(self.name, self.quota, self.period) |
"""Convert raw PASCAL VOC dataset to TFRecord for object detection.
The Example proto contains the following fields:
image/encoded: string, containing JPEG image in RGB colorspace
image/height: integer, image height in pixels
image/width: integer, image width in pixels
image/format: string, specifying ... |
"""
Copright © 2023 Howard Hughes Medical Institute, Authored by Carsen Stringer and Marius Pachitariu.
"""
import sys, os, time, string, shutil
from natsort import natsorted
from glob import glob
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
import mxnet as mx
import matplotlib.pyplot as... |
#!/usr/bin/env python
from __future__ import (absolute_import, division, print_function, unicode_literals)
s = raw_input("Please eneter a string: ")
z = [x for x in s]
z.reverse()
if s == "".join(z):
print ("The string is a palindrome")
else:
print( "The string is not a palindrome")
|
#使用deque判断回文数
from pythonds.basic.deque import Deque
def fixhwnum(string):
numlist=[num for num in string]
qe=Deque()
for i in numlist:
qe.addFront(i)
while qe.size()>1:
if qe.removeFront()!=qe.removeRear():
return False
return True
print(fixhwnum('abcdcba'))
print(fixhwnum('afdefdfa')) |
class Solution:
def search(self, nums: List[int], target: int) -> int:
left , right = 0, len(nums) -1
while left <= right:
middle = int((left + right) /2)
if nums[middle] == target:
return middle
else:
if nums[middle] < nums[rig... |
#
# Copyright (c) 2022, Gabriel Linder <linder.gabriel@gmail.com>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS"... |
scores = [ ]
for i in range(5) :
value = int( input("성적입력 : ") )
scores.append(value)
print(scores) # 입력 받은 리스트 출력
sum = 0
for i in range(5) :
sum += scores[i]
print("합계: ", sum)
print("평균: ", (sum/5))
|
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 29 23:44:31 2021
@author: -
"""
# -- coding:utf-8 --
import pandas as pd
import numpy as np
import os
from os.path import join as pjoin
# from utils import is_number
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
import xgboos... |
# encoding=utf-8
# Date: 2018-10-14
# Author: MJUZY
# Important Referrence:
# https://blog.csdn.net/zpalyq110/article/details/80432827
# https://github.com/Freemanzxp/Image-category-understanding-and-application/blob/master/main/MedicalLargeFine_tuning.py
import os
from keras.preprocessing.image import Image... |
from django.db import models
from django.utils import timezone
# Create your models here.
class City(models.Model):
name = models.CharField(max_length=25)
def __str__(self):
return self.name
class Meta:
verbose_name_plural = 'cities'
class Data(models.Model):
name = f'{str(timezone... |
import numpy as np
import cv2
#creating a function to convert the RGB image to Grayscale
def RGBtoGray(image):
return cv2.cvtColor(image,cv2.COLOR_RGB2GRAY)
#creating a function for Smoothing the Grayscale image
def smoothing(image,kernel_size):
return cv2.GaussianBlur(image,(kernel_size,kernel_size),0)
#th... |
import numpy as np
from scipy import interpolate
import pandas as pd
import os
import time
import multiprocessing
import matplotlib.pyplot as plt
import sys
lower_T=1500
lower_T*=1000
paths = [r"a05",r"a10",r"a20",r"a40"]
file_end = '.txt'
def tt(files):
dir_path = os.path.join(path, files[1])
print(dir_path, f... |
from bottle import route, run, static_file, response, template
import bottle
import boto
import json
import boto.sqs
import string
import uuid, time
import boto.dynamodb2 as ddb
from boto.dynamodb2.fields import HashKey
from boto.dynamodb2.table import Table
import base64, hmac, hashlib
import urllib2
from boto.sqs.mes... |
__author__ = "Navratan Bagwan"
import all_stats
import pdb
import numpy
import os
import glob
def ptmClassifier(listofpaths, sigmafIle, Outfilename):
print (sigmafIle)
#sigmaValue = float(all_stats.sigmaFinder(sigmafIle))
outpath = os.path.dirname(listofpaths)
assignationFile = glob.glob(os.path.join... |
__author__ = 'ardila'
import numpy as np
def feature_split_large(n_features, n_samples, n_bootstrap):
"""
Generate a set of indexes which subsample features of sizen_features
start at n_features/2
get a linear space of n_samples up to n_features.
resample each one n_bootstrap times
"""
as... |
#!/usr/bin/env python
import math
import random
import shutil
import subprocess
import tempfile
import time
from os import getcwd
from pathlib import Path
from sys import exit
from pydub import AudioSegment
MUSIC_DIR = Path("/home/kajm/media/music") # change to directory with mp3 files
MP3_FILES = list(MUSIC_DIR.g... |
from energydiagram import ED
from matplotlib.backends.backend_pdf import PdfPages
diagram = ED()
diagram.add_level(-646.499346248,'Closed Shell Molecule')
diagram.add_level(-645.842343146,'C3 unrelaxed')
diagram.add_level(-645.852575856,'C4 unrelaxed','last')
diagram.add_level(-645.852440887,'C5 unrelaxed','last')
... |
import plotly
import plotly.graph_objs as go
import numpy as np
import colour
d65 = colour.ILLUMINANTS['CIE 1931 2 Degree Standard Observer']['D65']
def sRGB2Lab(rgb):
return colour.XYZ_to_Lab(colour.sRGB_to_XYZ(rgb / 255, illuminant=d65), illuminant=d65)
gridN = 9
grid = np.linspace(0,256,gridN,True)... |
#! /usr/bin/env python
if __name__ == '__main__':
import sys
sys.path.insert(0, '/home/mininet/pox')
import pox.boot
pox.boot.boot()
|
import logging
import random
import time
from selenium import common
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import... |
#!/usr/bin/python
# makes a LPD8806 LED strip mimic a sunrise as an alarm clock
# uses the https://github.com/adammhaile/RPi-LPD8806 project for led helpers
import sys
sys.path.insert(0, './vendor/led-strip/RPi-LPD8806')
from bootstrap import *
# setup colors to loop through for fade
# colors use cls.cc standards
co... |
"""Implementation of Apache VFS schemes and URLs."""
import os
import sys
import re
from fiona.compat import urlparse
# Supported URI schemes and their mapping to GDAL's VSI suffix.
# TODO: extend for other cloud plaforms.
SCHEMES = {
'ftp': 'curl',
'gzip': 'gzip',
'http': 'curl',
'https': 'curl',
... |
import warnings
from itertools import chain
class IRMeta(type):
def __init__(cls, *args, **kwargs):
selector = 'return visitor.visit{}(self)'.format(cls.__name__)
accept_code = "def accept(self, visitor):\n\t{}".format(selector)
l = {}
exec(accept_code, globals(), l)
setattr... |
from transformers import GPT2LMHeadModel, GPT2Tokenizer, GPT2Config
import torch
import torch.nn
import torch.distributions
import torch.nn.functional as F
import random
import numpy as np
import pickle
from utils import rand_gen_first_token
import h5py
END_TOKEN = '<|endoftext|>'
fname = 'sampling.txt'
MAX_LENGTH = 9... |
import cv2 as cv
import numpy as np
import datetime
import mysql.connector
from centroid import CentroidTracker
from trackable import TrackableObject
Down1 = 0
Up1 = 0
Down2 = 0
Up2 = 0
def main():
whT = 320
confidenceThres = 0.4
nmsThreshold = 0.3
cap = cv.VideoCapture("test.mp4")
... |
import pandas as pd
import numpy as np
import seaborn as sns
from pandas import ExcelWriter
import will as w
df_stint = pd.read_pickle("stint.txt")
#df_business = pd.read_pickle("business.txt")
#df_review = pd.read_pickle("review.txt")
#df_student = pd.read_pickle("student.txt")
#df_studentavailability = pd.read_pickl... |
#!/usr/bin/env python
"""Custom Qt Widgets."""
from __future__ import division, print_function
from .playmat import PlayMat
from .viewer import Viewer
__all__ = ["Playmat", "Viewer"]
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# check to see if all parameters are set on the command line
# if they are, then don't open GUI interface
from math import *
import sys
#from Tkinter import *
#import tkMessageBox
#import tkFileDialog
#from FileDialog import *
from osrefl.loaders.reduction import *
import osr... |
import torch
from torch.autograd import Variable
import numpy as np
import time, math, glob
import scipy.io as sio
import matplotlib.pyplot as plt
from ssim import ssim
from lapsrn import LapSrnMS
def PSNR(pred, gt, shave_border=0):
height, width = pred.shape[:2]
pred = pred[shave_border:height - shave_borde... |
#!/usr/bin/python3
import queue
from collections import defaultdict
class Graph():
def __init__(self, n):
self.n = n
self.edges = defaultdict(lambda: [])
def connect(self, x, y):
self.edges[x].append(y)
self.edges[y].append(x)
def find_all_distances(self, s):
resu... |
from sys import argv
fname = argv[1]
with open(fname) as f:
lines = f.readlines()
layer = -1
comp_time = 0
cum_comp_time = 0
in_size = 0
out_size = 0
trans_time = 0
thresh = 0
cum_thresh = 0
is_check = False
for line in lines:
if line.startswith("Layer Number"):
num = int(line.split(":")[1].strip())... |
from flask import Flask
from redis import Redis
from flask import jsonify
from flask import request
import requests
import json
import re
import copy
app = Flask(__name__)
movies = [ {
'ID' : '0',
'Title' : 'Avengers: Infinity War',
'Release_date' ... |
def Multi( arg1=0, arg2=0 , *vartuple ):
"""Multiplica todos los argumentos"""
produc=arg1*arg2
for var in vartuple:
produc=produc*var
return produc
def Fib(n):
"""Recibe un entero n, y entrega una lista con los números de fibonacci menores que n"""
result = []
a, b = 0, 1
... |
# -*- coding: utf-8 -*-
"""An example describing EGF's effect on cellular processes.
.. code-block:: none
SET Citation = {"PubMed","Clin Cancer Res 2003 Jul 9(7) 2416-25","12855613"}
SET Evidence = "This induction was not seen either when LNCaP cells were treated with flutamide or conditioned medium were pre... |
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.Qsci import *
import json
import re
import platform
lexers = {
"py": QsciLexerPython,
"css": QsciLexerCSS,
"cs": QsciLexerCSharp,
"coffee": QsciLexerCoffeeScript,
"json": QsciLexerJSON,
"html": QsciLexerHTML,... |
# 7. Receba os valores do comprimento, largura e altura de um paralelepípedo.
# Calcule e mostre seu volume.
def paralelepipedo():
try:
c = int(input("Digite o comprimento do paralelepípedo: "))
l = int(input("Digite a largura do paralelepípedo: "))
h = int(input("Digite a altura do parale... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# monitorradio.py
import logging
import wx
import os, sys
from datetime import date
from time import ctime
from tombo.configfile import ConfigFile
from serialcommands import SerialCommands
#from tombo.timedstatusbar import TimedStatusBar
import elecraft
''' Responses from t... |
tc = input('Informe (A) para Alcool ou (G) para Gasolina: ').upper()
ql = float(input('Informe a quantidade de litros: '))
if (tc == 'A'):
valor = 1.9
if (ql <= 20):
desc = 3
else:
desc = 5
else:
valor = 2.5
if (ql <= 20):
desc = 4
else:
desc = 6
total = (valor ... |
import os
from datetime import datetime
import pandas as pd
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from src.models.users import User
class UserController:
"""
Provides functionality to retrieve and send user data from/to the database
"""
@staticmethod
def g... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.