text stringlengths 38 1.54M |
|---|
import os
import torch
from torch import nn
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
import torch.optim as optim
from torchsummary import summary
import segmentation_models_pytorch as smp
from catalyst.dl.runner import SupervisedRunner
from catalyst.dl.callbacks impor... |
#!/usr/bin/python
__author__="Paulo Victor Maluf"
__date__ ="$27/10/2014 13:35:12$"
from connection import Connect;
class Postgres(object):
def __init__(self, dsn=None):
self.dsn = dsn
self.connect()
def connect(self):
conn = Connect(self.dsn)
self.cursor = conn.cur()
... |
# 經由亂數發撲克牌(52張),分為四組列印出來。
import random
list_four_suits = ['♠', '♥', '♦', '♣']
list_number = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
def produce_poker_list():
list_poker = []
for i in range(len(list_four_suits)):
for j in range(len(list_number)):
list_poker.appen... |
######################################
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
#__author__="lili36"
#__date__="2017-03-24"
######################################
"""
This module provide argv implementation
"""
import os
import sys
import logging
import json
from optparse import OptionParser
from optparse import I... |
# Сумма младшего разряда целой и старшего разряда дробной частей x
# является четным числом или 1-й разряд целой части больше 1-го
# разряда дробной части.
a = float(input())
b = a % 10
c = (a * 10) % 10
isSpecial = False
if (a + b) % 2 == 0:
isSpecial = True
elif b > c:
isSpecial = True
print(isSpecial)
|
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import os
from urllib.request import urlopen
# from scrapy.pipelines.images import ImagesPipeline
from imgdb import settings
cl... |
from django.contrib import admin
from .models import Address, Order, Table, Booking, Category, Product, ProductOrder
# Register your models here.
admin.site.register(Address)
admin.site.register(Order)
admin.site.register(Table)
admin.site.register(Booking)
admin.site.register(Category)
admin.site.register(Product)
a... |
from robot import Pid, Robot, LineEdge, LineSensor
from pybricks.hubs import EV3Brick
from pybricks.ev3devices import (Motor, ColorSensor,
GyroSensor)
from pybricks.parameters import (Port, Stop, Direction, Color,
SoundFile, Button)
from pybricks.tools impo... |
from matplotlib.dates import DateFormatter, HourLocator
from matplotlib.ticker import AutoMinorLocator
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import math as mt
import datetime
import glob
import csv
import os
class ProcessISMR():
def __init__(sel... |
import tensorflow as tf
from tensorflow.keras import optimizers
from tensorflow.keras.layers import InputSpec, Dense, Wrapper, Input, concatenate
from tensorflow.keras.models import Model
import numpy as np
class ConcreteDropout(Wrapper):
"""This wrapper allows to learn the dropout probability for any given input... |
import socket
#My laptop is name 'Guinsly-thinkpad-lenovo'
if 'guinsly' in socket.gethostname():
from .development import *
from django.core.urlresolvers import reverse_lazy
LOGIN_REDIRECT_URL = reverse_lazy('dashboard')
LOGIN_URL = reverse_lazy('login')
LOGOUT_URL = reverse_lazy('logout')
prin... |
from __future__ import print_function, division
from lib import *
from run import *
def testcnl(x):
def f(x) : return x**2 + 3*x + 1
def g(x) : return 3*x + 3
return abs(f(x) - g(x))
print(testcnl(-1.39356))
class CurveAndLine(Function):
def cells(i):
return Have(#T = Time(),
x = Aux('... |
#!/usr/bin/env python
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# ---------------------------------------------... |
import pysam,re
import numpy as np
import pandas as pd
from collections import Counter
from operator import itemgetter
NOCLUST = 999
DEFAULTCI= [0.025,0.975] #95%
def addHPtag(inBAM,outBAM,clusterMap,noCluster=NOCLUST,dropNoClust=False):
'''clusterMap is map of {readname:cluster::int}'''
with pysam.Alignment... |
#
# Performs a REST call to controller (possibly localhost) of latest farm status.
#
import datetime
import http
import json
import os
import requests
import socket
import sqlite3
import traceback
from flask import g
from common.config import globals
from api.commands import chia_cli, chiadog_cli, plotman_cli
from ... |
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from customer.views import CustomersViewSet
customer_list = CustomersViewSet.as_view({
'get': 'list',
'post': 'create'
})
customer_detail = CustomersViewSet.as_view({
'get': 'retrieve',
'put': 'update',
'pa... |
import random
import itertools
import iterators
import readPuzzle
def borderGen(coords):
borders = []
for coord in coords:
neighbors = [neighbor for neighbor in gridNeighbors(coord, readPuzzle.rows, readPuzzle.cols)
if neighbor not in coords]
borders += (((r, c), coord) fo... |
import pandas as pd
from bs4 import BeautifulSoup
from src.helpers.consts import WINOGRAD_PT_HTML_SCHEMAS_FILE, MISSING_TRANSLATION_INDEXES
def join_content(item):
content = [it.strip().replace(' ', ' ') for it in item.text.split('\n') if it.strip() != '']
return content
def clean_tags_for_schema_and_snip... |
from util import *
from util import raiseNotDefined
import time, os
import traceback
try:
import boinc
_BOINC_ENABLED = True
except:
_BOINC_ENABLED = False
#######################
# Parts worth reading #
#######################
class Agent:
"""
An agent must define a getAction method, but may also define t... |
from typing import Any, List, Optional
from src.domain.userManagment.userSchema import UserCreateSchema, UserDBSchema, UserUpdateSchema
class UserService:
def __init__(self, user_queries: Any):
self.__user_queries = user_queries
async def create_user(self, user: UserCreateSchema) -> UserDBSchema:
... |
"""
Main program parser
"""
import textwrap
from argparse import ArgumentParser, RawTextHelpFormatter
from enum import Enum, unique
from nspawn.support.typing import enum_name_list
from nspawn import with_merge_parser
def attach_engine(parser:ArgumentParser):
required = parser.add_argument_group('required argu... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
_/ _/ _/_/_/ _/ _/ _/_/_/
_/_/ _/ _/ _/ _/ _/
_/ _/ _/ _/ _/_/_/_/ _/
_/ _/_/ _/ _/ _/ _/
_/ _/ _/_/_/ _/ _/ _/_/_/
https://github.com/TW-NCHC/functionality-scenario-test-A-2018
This progr... |
hpzl ={
'大型汽车':'//*[@id="vhpzl"]/option[1]',
'小型汽车':'//*[@id="vhpzl"]/option[2]',
'大型新能源汽车':'//*[@id="vhpzl"]/option[3]',
'小型新能源汽车':'//*[@id="vhpzl"]/option[4]',
'使馆汽车':'//*[@id="vhpzl"]/option[5]',
'领馆汽车':'//*[@id="vhpzl"]/option[6]',
'境外汽车':'//*[@id="vhpzl"]/option[7]',
'外籍汽车':'//*[@id... |
#!/usr/bin/python
import multiprocessing
msjs = ["Hola", "Que tal?", "Chau"]
def enviar(conn, msjs):
for msj in msjs:
conn.send(msj)
conn.close()
def recibir(conn):
while 1:
msj = conn.recv()
if msj == "Chau":
break
print(msj)
padre_conn, hijo_conn = multipro... |
from lib import *
from app import *
import pprint
class tvEpisode:
def __init__(self, serieData):
self.seriesTitle = None
self.seriesSeason = None
self.seriesEpisode = None
self.seriesEpisodeName = None
self.seriesDescription = None
self.seriesRating = None
self.seriesAirDate = None
self.seriesN... |
#!/usr/bin/env python
import rospy
import roslib
import rostopic
import gdp
import pickle
import zlib
import sys
import argparse
from threading import Lock
from std_msgs.msg import String, Float64
from rospy.msg import AnyMsg
def _parse_args():
"""returns arguments passed to this node"""
# setup argument par... |
import numpy as np
from crepe import normal
import matplotlib.pyplot as plt
n = normal.optimize()
# Importing data
data = np.loadtxt('data.dat',float,usecols=(0,1))
N = len(data[:,0])
# Function to be simulated
def f(x,a,b):
return a*np.exp(b*x)
# The performance function: just a simple sum of the squared diffe... |
#!/usr/bin/env python
import sys, os, re, glob
try:
import io
except ImportError:
import cStringIO as io
def usage():
sys.stdout.write(
"""usage: mdoc.py set group file [files...]
Add the tag "\\ingroup group" to all the doxygen comment with a \\class
tag in it.
usage: mdoc.py check group f... |
def multipes():
toplam = 0
for i in range(1000):
if i%3==0 or i%5==0:
toplam=i+toplam
print toplam
multipes()
|
#
# Copyright 2017 Google Inc.
#
# 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... |
from paddlenlp.data import Stack, Pad, Tuple, np
from paddlenlp.datasets import load_dataset
from paddlenlp.transformers import ErnieGramTokenizer, ErnieTokenizer
from lib.base_data_module import BaseDataModule
class ReadingComprehensionDataModule(BaseDataModule):
def __init__(self, batch_size=32, max_seq_lengt... |
import os
from collections import Counter
from random import shuffle
from typing import List
from tqdm.autonotebook import tqdm
from dataloader.data import MIMICDataset, TabularFeature, get_tables
from dataloader.utils import Event
def extract_sentences(dataset, tables: List[TabularFeature], event_class=Event, suff... |
from django.apps import AppConfig
class TweetGeneratorConfig(AppConfig):
name = 'Tweet_Generator'
|
#!/usr/bin/env python
##### !/usr/local/bin/python
##### !/usr/bin/python # for DPH mac
import numpy as np
import math
import os
import matplotlib.pyplot as plt
import sys
import glob
from math import log10, floor
from decimal import *
import matplotlib.cm as cm
import random
from scipy.interpolate import interp1d
fro... |
import ast_node
class TagReference(ast_node.AstNode):
def __init__(self, ref_name):
self.ref_name = ref_name
def get_value(self):
return '%placeholder_value%'
def execute(self, tag_context):
return tag_context.get_tag_value(self.ref_name)
def set_value(self, tag_context, val... |
# 进程池
from multiprocessing.pool import Pool
import multiprocessing
import time
import os
import random
'''
def run(name):
print('{}子进程开始运行, 进程id是{}'.format(name, os.getpid()))
start_time = time.time()
time.sleep(random.choice([1,2,3,4]))
stop_time = time.time()
print('{}子进程结束, 进程id是{},运行时间:{}'.for... |
import numpy as np
import math as m
import os.path
import subprocess
import cosmolopy as cosmos
import multiprocessing as mp
# --- Local ---
from Spectrum import data as spec_data
from Spectrum import fft as spec_fft
from Spectrum import spec as spec_spec
from Spectrum import fortran as spec_fort
def bisp_wrapper(i_m... |
#!/usr/bin/python
bytelist = [x.strip() for x in open('bytes.txt','r').readlines()]
lin = open('linear_eqs.py','w')
lin.write("#!/usr/bin/python\nfrom z3 import *\n")
for i in range(26):
lin.write("var_"+str(i)+" = Int('var_"+str(i)+"')\n")
lin.write("solve(")
def replacelabel(bytenum):
firstbyte = 0x805F4... |
import base64
account_username = 'email.address@gmail.com'
account_pass = base64.b64decode('dfshfksdjkhfgdsjkhgsdjk')
special_message_sender = 'secret.squirrel@gmail.com'
magic_subject_words = ['file', 'available']
wait_time_in_seconds = 10
file_source = 'localhost:/tmp/test_sourcedir'
file_dest = '/tmp/test_destdir'... |
# Author Sven Koppany
# This implements the a-star search algorithm
import numpy as np
import scipy.io
import random
from matplotlib import pyplot as plt
from matplotlib import animation
class astar:
def __init__(self, worldMap, matlabMap = False, startAndGoalCoords = ((0,0),(4,4)), randomCoords = False):
#Conv... |
import json
import os
import time
from flask import Flask, Response, request
app = Flask(__name__, static_url_path='', static_folder='public')
app.add_url_rule('/', 'root', lambda: app.send_static_file('index.html'))
@app.route('/api/todo/list', methods=['GET', 'POST'])
def og_handler():
# Open the json file for ... |
import numpy as np
import os
import skimage.io as io
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
from shapely.geometry import Polygon as Pgon
def show_gt_mask(bbox_img, polygons, colors):
"""Show ground truth object segmentation mask
... |
# -*- coding: utf-8 -*-
"""
参考链接:
python初步实现word2vec:http://blog.csdn.net/xiaoquantouer/article/details/53583980
Google Word2vec 学习手札: http://blog.csdn.net/MebiuW/article/details/52295138
"""
import sys
import chardet
import re
text_path = "/Users/sunlu/Documents/数据集/搜狗实验室/搜狐新闻数据(SogouCS)/news_sohusite_xml.smarty.da... |
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# DNSServer model
# ---------------------------------------------------------------------
# Copyright (C) 2007-2013 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------... |
from utils import read_input
import math
raw = read_input.read_input_strings('day18')
def evaluate_precedence(expression):
return math.prod([sum([int(number) for number in group.split('+')]) for group in expression.split('*')])
def evaluate_sequential(expression):
result = 0
pointer = 0
operator = ... |
## Goal: get the thread that is top 100 popular: by views, by replies
## Write function to sort by reviews or replies
## .csv file to contain: link_to_thread, name_of_thread, views, replies, last_post_time, last_post_date
import time
import datetime as dt
import pandas as pd
from selenium import webdriver
from sele... |
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
left = matrix[0][0]
right = matrix[-1][-1]
while left < right:
middle = (left + right) // 2
i = len(matrix) - 1
j = n = 0
while i >= 0 and j < len(matrix[0]):
... |
from graphene import relay
from graphene_sqlalchemy import SQLAlchemyObjectType
from crm.apps.organization.models import Organization
class OrganizationType(SQLAlchemyObjectType):
class Meta:
model = Organization
interfaces = (relay.Node,)
name = model.__name__
|
"""
Udemy "Interactive Python Dashboards with Plotly and Dash Course
10/25/2020
"""
import numpy as np
# NumPy crash course.
mylist = [1, 2, 3, 4, 5, 6, 7]
print(np.array(mylist))
print(type(mylist))
# makes an array out of a list.
arr = np.array(mylist)
print(arr)
print(type(arr))
a = np.arange(0, 10)
print(a)
... |
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2016
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as publish... |
import random
import math
import numpy
import operator
from deap import creator, base, tools, algorithms, gp
from GAToolbox import get_toolbox
def main():
# list all the functions to analyse
functions = [math.sin]
# create the toolbox
toolbox = get_toolbox(functions[0])
random.seed(318)
# create a new populat... |
# -*- coding: UTF-8 -*-
import ast
import json
import logging
import pathlib
import sys
import threading
import time
from pprint import pformat as pf
from typing import Any # noqa: F401
import click
import pretty_cron
from appdirs import user_cache_dir
from tqdm import tqdm
import miio # noqa: E402
from miio.click_... |
import os
import time
import numpy as np
import pandas as pd
from util import util
from datasets import save_file
from torch.utils.tensorboard import SummaryWriter
class Visualizer:
"""
This class print/save logging information
"""
def __init__(self, param):
"""
Initialize the Visuali... |
# coding=utf-8
# 我的想法是
# 我随机选一个人,然后看这个人是否know anyone in potential group
# 如果他知道其中任何一个人,那么他就不可能是要找的那个人,
#
# The knows API is already defined for you.
# @param a, person a
# @param b, person b
# @return a boolean, whether a knows b
# def knows(a, b):
from random import randint
class Solution(object):
def findCe... |
import csv
import re
import sys
import tweepy
from textblob import TextBlob
# Step 1 - Autenticacion con el api de twiter
consumer_key = 'OoKtdnkn2PhPdVopgcPPVszBL'
consumer_secret = 'zJCI08nnQ7wGiosCOe7Udbu4PlpchanXFbjytZZJFkontr2wOC'
access_token = '572213920-pfExxBDxG4W7gu6ke8Yh1xexYcypE9QOddfvpY6u'
access_token_... |
from rest_framework import serializers
from .models import Car, Cart, UserCars
class CarSerializer(serializers.ModelSerializer):
class Meta:
model = Car
fields = "__all__"
class CartSerializer(serializers.ModelSerializer):
class Meta:
model = Cart
fields = "__all__"
class UserCarsSerialize... |
from django_filters import rest_framework as filters
from apps.django.main.course.public import model_names as course_names
from apps.django.main.timetable.mixins import LessonFilterSetMixin
from ...models import Material
__all__ = [
"MaterialFilterSet"
]
class MaterialFilterSet(LessonFilterSetMixin):
class... |
from django.urls import path
from . import views
urlpatterns = [
path('words/', views.WordSet.as_view()),
path('las/', views.LaSet.as_view()),
path('cards/', views.CardSet.as_view()),
path('intros/', views.IntroSet.as_view()),
path('grammar-cards/', views.GrammarCardSet.as_view()),
path('grammar-cards/(<pk... |
import datetime
now = datetime.datetime.now()
year = now.year
month = now.month
day = now.day
hour = now.hour
minute = now.minute
second = now.second
print("{}년 {}월 {}일 {}시 {}분 {}초".format(year, month, day, hour, minute, second))
if hour < 12:
print("현재 시각은 {}:{} \'오전\' 입니다.".format(hour, minute))
if hour >= 12... |
# -*- encoding: utf-8 -*-
import re
from pyparsing import *
from datetime import datetime
import time
def Ignore_files(url):
if '.' in url[url.rfind('/'):]:
#print(url)
return False
return True
def Ignore_www(url):
i = url.find('www.')
if i == -1:
return url
url = url.repla... |
import numpy as np
import sys
from neural_gas_marconi import NeuralGasNode
from numpy import *
from PIL import Image
import datetime
from random import shuffle
import os
import errno
#import sys
start_time= datetime.datetime.now()
'''
Training input file can be selected by properly specifying n_cats a... |
import os
import sys
import re
import subprocess
import re
import time
from time import sleep
from datetime import datetime
from cmds import CMDS
class SAMPLE_Test():
def __init__(self, uuid, divide_window=10):
super().__init__()
self.cmd = CMDS(uuid, divide_window)
# self.display_flag = ... |
"""Unit tests for recordclass.py."""
import unittest, doctest, operator
from recordclass.typing import RecordClass
import pickle
import typing
import sys as _sys
class CoolEmployee(RecordClass):
name: str
cool: int
class CoolEmployeeWithDefault(RecordClass):
name: str
cool: int = 0
class XMeth(Recor... |
import psycopg2
from datetime import datetime
from .todo_controller import TodoController
class GoalController:
def __init__(self, connection, list, todo_list):
self.connection = connection
self.list = list
self.tag = "all"
self.controller = TodoController(connection, todo_list)
... |
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://www.pythonscraping.com/pages/warandpeace.html")
bs0bj = BeautifulSoup(html,"html.parser")
'''
nameList = bs0bj.findAll("span",{"class":"green"})
for name in nameList:
print(name.get_text())
headList = bs0bj.findAll({"h1","h2",... |
from concurrent import futures
import grpc
from .generated import meterusage_pb2_grpc
from .meterusage.service import MeterUsageService
class Server:
@staticmethod
def run():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
meterusage_pb2_grpc.add_MeterUsageServiceServicer_to_... |
'''
This script read AJHG table and convert it into a bed file,
listing 20kbp region around the eQTL site.
'''
import sys
from itertools import islice
def main(filename):
fileout = open(filename + "_converted.bed","w")
#print filename
filein = open(filename,"r")
count = 0
for line in islice(filein, 1, None)... |
# import logging
# import os
#
# import pandas as pd
# import pytest
#
# import core.finance as fin
# import helpers.git as git
# import helpers.system_interaction as si
# import helpers.unit_test as hut
# import vendors.cme.reader as cmer
# import vendors.core.base_classes as etl_base
# import vendors.core.config as e... |
# -*- coding: utf-8 -*-
# Copyright 2018 ICON Foundation Inc.
#
# 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 ... |
from __future__ import annotations
from typing import final, Final, Tuple, Dict, Optional, List
from Core import Token, TypeSystem
from Operator import Operator
class BoolOp(Operator.Op):
__ARGC: int = 2
def __new__(cls, *args, **kwargs) -> None:
raise NotImplementedError
@classmethod
def ... |
#!/usr/bin/python
import hashlib
import hmac
import time
import os
import urllib
import urllib2
try:
import simplejson as json
except ImportError:
import json
class Auth:
def __init__(self,apiKey):
self.apiKey = apiKey
return None
def hmac(
self,
url,
httpMethod="GET",
queryParameters=None... |
#single page crawl
import scrapy
import logging
from scrapy.contrib.spiders import Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from scrapy import Request, Spider
from scrapy.exceptions import CloseSpider
from scrapy.selector import Selector
from... |
import os
import random
import asyncio
import aiohttp
num_of_drivers = int(os.environ['DRIVER_NUMBER'])
time_interval = int(os.environ['POSITION_SEND_INTERVAL'])
service_host = os.environ['SERVICE_HOST']
def generate_position(driver_id):
return {
'driver_id': driver_id,
'latitude': round(random.u... |
"""Provides `ParamsManager` class for managing parameters folder."""
import os
import json
def _load(path):
with open(path, 'r') as f:
params = json.load(f)
return params
def _save(path, params):
with open(path, 'w') as f:
json.dump(params, f)
class ParamsManager(object):
"""A clas... |
'''
Created on Mar 11, 2016
@author: s3cha
'''
import os
import sys
import cPickle as pickle
import pysam
# input_bam_filename = "/media/s3cha/MyBook/VU/bam/UNCID_1580578.35e535d8-7265-4271-a503-5e1728cd5209.sorted_genome_alignments.bam"
# s = open('/home/s3cha/data/SpliceDB/NEW_IG_Graph/KmerTest/temp_unmapped_read_l... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-08-13 07:07
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 = [
('viewflow... |
import socket,requests
hostname = socket.gethostname()
local_ip = socket.gethostbyname(hostname)
print(local_ip)
req = requests.get('https://pastebin.com/mRqFXTH9').text
if local_ip in req:
pass
else:
print("-------------------------------------")
print("Your Not Member Send The Id to Owner")
print("---... |
import os, sys
from grid import Grid
import pygame
from pygame.locals import *
from shape import Shape
import copy
def main():
pygame.init()
screen = pygame.display.set_mode([300, 720])
white = 255, 255, 255
black = 0, 0, 0
purple = 155, 0, 155
cleared = []
current_shape = Shape()
grid = Grid()
lost = False
... |
class Composition:
class __Other:
def __init__(self, string):
self.string = string
def retrieve_string(self):
return self.string
def result(self):
return self.__Other('Hello').retrieve_string() + ' world!'
composition = Composition()
print(composition.result()... |
#!/usr/bin/env python
import RPi.GPIO as GPIO
import time
LIGHT1 = 23
LIGHT2 = 25
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(LIGHT1,GPIO.OUT)
GPIO.setup(LIGHT2, GPIO.OUT)
#GPIO.output(LIGHT1, GPIO.HIGH)
def drawLed():
GPIO.output(LIGHT2, GPIO.HIGH)
time.sleep(1)
GPIO.output(LIGHT2, GPIO.LOW)
... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
gender = ["Male","Female"]
income = ["Poor", "Middle Class", "Rich"]
gender_data = []
income_data = []
n = 500
for i in range (0, n):
gender_data.append(np.random.choice(gender))
income_data.append(np.random.choice(income))
height = 16... |
import os
import math
from datetime import datetime
from getpass import getuser
from sqlalchemy import create_engine, or_
from sqlalchemy.event import listen
from sqlalchemy.sql import select, func
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import OperationalError
from importlib import import_module
f... |
# @Author : Shusheng Wang
# @Time : 2021/2/2 6:17 下午
# @Email : lastshusheng@163.com
from enum import Enum
class ErrorCode(Enum):
ParamsError = -3
Success = 0
class ErrorCodeHelper:
@classmethod
def transform_error_msg(cls, err_code):
msg = ""
if err_code == ErrorCode.ParamsE... |
import pygame
from ..._gid import Gid
from ..._gevent import GEvent
from ..._color import Color
from ..._move import Move
from ._collision_box import CollisionBox
class Shape(Gid):
"""Shape represents a collection of cells to be displayed in a grid board.
"""
def __init__(self, name, x, y, xcells, ycells... |
from batch_main import get_readings_by_date, build_csv, run
from test.fixtures import BaseTest
from run import run as main_run
import datetime
class TestBatch(BaseTest):
"""Test the batch functionality."""
def setUp(self):
"""Setup the sensors and run the sensors."""
super().setUp()
m... |
# This file is part of Adblock Plus <https://adblockplus.org/>,
# Copyright (C) 2006-present eyeo GmbH
#
# Adblock Plus is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# Adblock Plus is distributed... |
from ctypes import *
class __sha1_context(Structure):
_fields_=[
("startCharOffset", c_uint16),
("endCharOffset", c_uint16),
("fontID", c_uint16),
("style_flags", c_char),
("font_size", c_char),
("text_color", c_int)
] |
import random
from itertools import count
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
plt.style.use('fivethirtyeight')
x_vals = []
y_vals = []
index = count()
# def animate(i):
# x_vals.append(next(index))
# y_vals.append(random.randint(0, 5))
# ... |
# -*- coding: utf-8 -*-
from odoo import models, fields, api
import time
import logging
_logger = logging.getLogger(__name__)
import datetime
class Asset(models.Model):
_name = 'account.asset.asset'
_inherit = ['account.asset.asset','mail.thread']
pengadaan = fields.Selection(
selection=[
('PO... |
from django import forms
from . import models
class PalavraForm(forms.ModelForm):
class Meta:
model = models.Palavra
fields = ['palavra']
labels = {
'palavra': 'Palavra',
} |
# Importing all needed Flask classes
from flask import Flask, session, flash, redirect, url_for
# Importing wraps
from functools import wraps
# Creating logged in required function
def login_required(f):
@wraps(f)
def wrap(*args, **kwargs):
if 'account' in session:
return f(*args, **kwarg... |
import csv
import matplotlib.pyplot as plt
from datetime import datetime
filename = 'chennai_reservoir_rainfall.csv'
fields = []
Date = []
POONDI = []
CHOLAVARAM = []
REDHILLS = []
CHEMBARAMBAKKAM = []
with open(filename, 'r') as csvfile:
csvreader = csv.reader(csvfile)
fields = next(csvreade... |
from numpy import *
from math import log
import operator
######################################################################
#
# 说明:
# 计算信息熵
# 参数:
# datas[in][list]:输入数据集
#
def calc_shannon_ent(datas):
# 计算数据集中各分类数目
classes = {}
for line in datas:
class_type = line[-1]
classes[class... |
import csv
from clasemanejadorpersona import manejadorpersona
from clasemanejadortaller import manejadortaller
from clasemanejadorinscrip import manejadorins
def menu():
print('1 - añadir persona')
print('2 - buscar dni y mostrar taller y lo que adeuda')
print('3 - buscar id taller listar persona')
print('4 - i... |
# -*- coding: utf-8 -*-
def cubes_with_x_digits(x):
from math import ceil, floor
lower = floor((10 ** (x - 1)) ** (1. / 3))
upper = ceil((10 ** x - 1) ** (1. / 3))
for i in range(lower, upper):
yield i ** 3
def sort_digits(n):
return ''.join([str(x) for x in sorted(str(n))])
digits = 3
... |
#!/usr/bin/python
import sys
import pickle
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
sys.path.append("../tools/")
from feature_format import featureFormat, targetFeatureSplit
from tester import dump_classifier_and_data,test_classifier
from sklearn.pipeline import Pipeline,FeatureUnion
fro... |
# GUI Application automation and testing library
# Copyright (C) 2006-2017 Mark Mc Mahon and Contributors
# https://github.com/pywinauto/pywinauto/graphs/contributors
# http://pywinauto.readthedocs.io/en/latest/credits.html
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# ... |
import socket
import time
UDP_IP = 'localhost'
UDP_PORT = 12000
MESSAGE = "PING"
# Set up the UDP client socket
clientSocket = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP protocol
# Set timeout on socket blocking operations (e.g recvfrom())
clientSocket.settimeou... |
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import pytest
import params
from optparse import OptionParser
df_ec = pd.read_csv("t2_ec 20190619.csv")
df_registry = pd.read_csv("t2_registry 20190619.csv")
df_registry = df_registry[ df_registry.SVPERF == 'Y' ]
df_registry = df_regist... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2019-01-25 17:16:34
# @Author : Raymond Wong (jiabo.huang@qmul.ac.uk)
# @Link : github.com/Raymond-sci
from tensorboardX import SummaryWriter as TFBWriter
from ..config import CONFIG as cfg
class TFLogger():
@staticmethod
def require_args():
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.