text stringlengths 38 1.54M |
|---|
import _webiopi.GPIO
import time
GPIO = _webiopi.GPIO
# GPIO, status, time
data = [[num, 0, 0.0] for num in [17, 27, 22]]
for n in data:
print(n[0], n[1], n[2])
GPIO.setFunction(n[0], GPIO.IN)
while True:
for n in data:
status = GPIO.digitalRead(n[0])
if n[1] == 0 and status:
... |
# -*- coding: utf-8 -*-
'''Low-level interface to libopus.'''
from __future__ import unicode_literals, absolute_import
__all__ = [
'strerror',
'get_version_string',
'encoder_get_size',
'encoder_create',
'encoder_init',
'encode',
'encode_float',
'encode... |
import simpleaudio
from time import sleep
class Instrument:
def __init__(self, inst, octaves=[i for i in range(8)]) -> None:
self.type = inst
self.octaves = octaves
self.notes = {}
self.playing = {}
notes = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
for o in octav... |
import argparse
sample_dataset = (
"AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC"
)
sample_output = "20 12 17 21"
def count_nucleotides(dna_string):
nucleotides = ["A", "C", "G", "T"]
counts = [str(dna_string.count(nucleotide)) for nucleotide in nucleotides]
return " ".join(... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# petla4.py
def main(args):
start = int(input("pobierz tą liczbę 1 helpppppp: "))
stop = int(input("podaj liczbę 2: "))
while start >= stop:
print("za mała druga liczba: ")
stop = int(input("pobierz ponownie drugą liczbę: "))
if... |
# -*- coding: utf-8 -*-
import trademarks.algorithm
def metricOfWords(pattern, word, vFine = 50.0, cFine = 5.0):
u'''
@version: Version 1.1 from 16.04.2014
@author: Alex Kuzmin
@return: double, the distance between input words
u'''
if pattern == u"" or word == "":
return -1... |
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 7 18:42:57 2018
@author: Meron
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cross_decomposition import PLSRegression
import sklearn.datasets
from sklearn.exceptions import NotFittedError
from sklearn.linear_model i... |
#!/usr/bin/python
import itertools
import sys
__version__ = "1.0"
# -------------------------------------------------------------
def generate_anagram(word):
"""
Generate all possible combination of the given string/word
provided as parameter.
@type word: [str]
@rtype: [str]
"""
return_list = [... |
import os
import sys
import re
import requests
"""
For test run: python my_dl https://www.youtube.com/watch?v=wb0n-6LiXNc
"""
def qualtiy_show(vid_link):
"""shows all formats available to download
:param vid_link: link of the youtube video
:return: None
"""
try:
print(os.s... |
from experiment_test_base import ExperimentTestCase
from pages.homepage import Homepage
from test_utils import generate_timestamp
import os
from test_utils import *
class TestEnsemble(ExperimentTestCase):
def test_ensemble_SDM(self):
homepage = Homepage(self.driver)
login_page = homepage.click_lo... |
import urllib
import json
langs = {'en': 'English',
'sv': 'Swedish',
'nl': 'Dutch',
'de': 'German',
'fr': 'French',
'war': 'Waray-Waray',
'ru': 'Russian',
'ceb': 'Cebuano',
'it': 'Italian',
'es': 'Spanish'
}
lang_codes = sorted(langs.ke... |
""" This file defines the base agent class. """
import abc
import copy
import time
from gps.agent.config import AGENT
from gps.proto.gps_pb2 import ACTION
from gps.sample.sample_list import SampleList
class Agent(object):
"""
Agent superclass. The agent interacts with the environment to
collect samples.
... |
import time
from datetime import datetime
from django.http import Http404, HttpResponse
from django.conf import settings
from google.appengine.runtime import DeadlineExceededError
from app.models import (Activity, Message, Vote, Thread, Role, Game,
Profile, VoteSummary, role_vanillager)
from ap... |
def entity_tagging(nlp,txt):
import re
"""This function will do the entity tagging and replace the characters and entities with proper names"""
txt=txt.decode('utf8')
doc=nlp(txt)
txt=""
for ent in doc:
if len(ent.ent_type_)==0:
txt=txt+ent.text+" "
elif ent.text.uppe... |
import paho.mqtt.client as mqtt
import time
import json
import socket
import yaml
from datetime import datetime
import shutil
import sys
import threading
class communication:
def start(self,config):
raise NotImplementedError('users must define start(configuration) to use this base class')
def s... |
for i in range(1,8):
print (i)
# range
l = ["Sujan",2,4,5]
for item in l:
print(item)
else:
print("Done")
# for with else |
import random
import os
import esp
import gc
import network
import time
from machine import unique_id, Pin, Signal
try:
import ubinascii as binascii
except:
import binascii
try:
import usocket as socket
except:
import socket
try:
import ure as re
except:
import re
try:
import ujson as js... |
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 12 13:31:36 2021
@author: LocalAdmin
"""
import pyvisa
import time
import numpy as np
class MagnetSupply(pyvisa.resources.GPIBInstrument):
"""
This is a child class of the pyvisa GPIB instrument class. it contains a
series of methods and functons to connect ... |
#Import the modules
import requests
import json
# Get the feed
r = requests.get("http://gdata.youtube.com/feeds/api/standardfeeds/top_rated?v=2&alt=jsonc")
r.text
# Convert it to a Python dictionary
data = json.loads(r.text)
# Loop through the result.
for item in data['data']['items']:
print "Video Title: %s" %... |
"""Defines the greylist table. """
from sqlalchemy import *
from sqlalchemy.orm import *
from spamfilter.model import meta
greylist_table = Table(
'greylist', meta,
Column('id', Integer, Sequence('greylist_id_seq'), primary_key=True),
Column('classc', String(11), nullable=False),
Column('mail_from', S... |
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256
from Crypto import Random
from base64 import b64encode, b64decode
from Crypto.Cipher import AES
def genNonce():
return RNG.new().read(AES.block_size)
def genKey(... |
#
# __ _,--="=--,_ __
# / \." .-. "./ \
# / ,/ _ : : _ \/` \
# \ `| /o\ :_: /o\ |\__/
# `-'| :="~` _ `~"=: |
# \` (_) `/
# .-"-. \ | / .-"-.
# .-----{ }--| /,.-'-.,\ |--{ ... |
# Intorduction to Programming
# Author: Shane Gilsenan
# Date: 8/29/17
def main():
print("Hello, instructor!")
print ("Good-Bye!)
main()
|
#!/usr/bin/python
import rospy
# import pickle
import message_filters
from sensor_msgs.msg import Joy, Image
from nav_msgs.msg import Odometry
from viewer import Viewer_class
from detect_obj import Detect_class
from timeit import default_timer as timer
coco_class = [
'BG', 'person', 'bicycle', 'car', 'motorcycl... |
# -*-coding:Utf-8 -*
from threading import Thread
import re
import requests
import urllib.request
import os
from bs4 import BeautifulSoup
class ScrapCategory(Thread):
"""Thread used to get all books data in one category and create the correspondent csv file"""
def __init__(self, url_list, category_name, tar... |
import cv2
face_cascade = cv2.CascadeClassifier(r"haarcascade_frontalface_default.xml")
eye_cascade = cv2.CascadeClassifier(r"haarcascade_eye_tree_eyeglasses.xml")
cap = cv2.VideoCapture(0) #To capture video from webcam.
while True:
_, img = cap.read() #Read the frame
gray = cv2.cvtColor(img,... |
# encoding: utf-8
class Solution:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
left = 0
right = len(nums) - 1
while left <= right:
if nums[right] == val:
right -= 1
... |
# import openpyxl module
import openpyxl
# Call a Workbook() function of openpyxl
# to create a new blank Workbook object
wb = openpyxl.Workbook()
# Get workbook active sheet
# from the active attribute.
sheet = wb.active
# writing to the cell of an excel sheet
sheet['A1'] = 'SAMPLE CALCULATION... |
# Soltn of t-dependent Sch Eqt fro HO with animation
from visual import *
dx = 0.04; dx2 = dx*dx; k0 = 5.5*pi; dt = dx2/20.0; xmax = 6.0
xs = arange(-xmax,xmax+dx/2,dx)
g = display(width=500, height=250, title='Wave packet in HO Well')
PlotObj = curve(x=xs, color=color.yellow, radius=0.1)
... |
import datetime
import json
import time
from flask import request, jsonify
from app import app
from . import client
from .. import db
from ..lib.tencent_api import search_face
from ..models import Teacher, Course, StuCourse, Student
@client.after_request
def cors(environ):
environ.headers['Access-Control-Allow-... |
#!/usr/bin/python -S
"""Unit test utils for experiment.py."""
import logging
import os
import shutil
import tempfile
import experiment
logger = logging.getLogger(__name__)
def enable(name):
"""Enable an experiment. For unit tests only."""
open(os.path.join(experiment.EXPERIMENTS_TMP_DIR, name + '.available')... |
from Include.work_json import remember_data, get_remember_data
# pach_file_train_dataset = "data/traindataset.json"
pach_file_remember = "data/memory.json"
def remember_data_write(pach_file_remember = pach_file_remember, **kwargs):
del kwargs['arr_text_input'][0]
str = kwargs['arr_text_input'][0] + ' ' + kw... |
from django.db import models
from django.urls import reverse
from django.utils.translation import pgettext_lazy
from mptt.managers import TreeManager
from mptt.models import MPTTModel
from versatileimagefield.fields import VersatileImageField
from saleor.core.permissions import MODELS_PERMISSIONS
from saleor.seo.mod... |
"""empty message
Revision ID: a2aeb71e3351
Revises:
Create Date: 2020-08-15 19:07:35.552634
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'a2aeb71e3351'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gene... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 29 22:39:29 2020
@author: simransetia
This program is used to calculate the network parameters of all the merged networks.
"""
import networkx as nx
from union_graph import Hu,Huw
from union_graph1 import Hud,H1
from xlwt import Workbook
import num... |
from django.urls import path,re_path
from . import views
app_name = 'cme'
urlpatterns = [
path('', views.index, name='index'),
path('<slug:urlshortOrganization>/events/', views.events, name='events'),
path('events/<slug:urlshortEvents>', views.event_sessions, name='event_sessions'),
path('event_Evalua... |
# Laba lists
numlist=[1, 2, 3, 4, 5, 6, 7]
print (numlist)
numlist.append("Python")
print (numlist)
print(numlist[0])
print(numlist[len(numlist)-1])
print(numlist[1:4])
print(numlist[1:4])
print(len (numlist))
print(numlist.index(6))
numlist.remove('Python')
#Laba Dictionaries
catalog_weather = {
"city": "Moscow",
"... |
from django.db import models
from product.models import Product
# Create your models here.
class Bug(models.Model):
Product = models.ForeignKey('product.Product',on_delete = models.CASCADE,null = True)
bugname = models.CharField('Bug名称',max_length = 64)#bug名称
bugdetail = models.CharField('Bug详情',max_length... |
# To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %%
import math
import random
# creating a base plater classs
class Player:
# self is a parameter used to access the current instance of the class, passing itself.
def __init__(self, letter):
# letter is either x or ... |
import asyncio
import pytest
import time
from promise import Promise
@pytest.mark.asyncio
@asyncio.coroutine
def test_await():
yield from Promise.resolve(True)
@pytest.mark.asyncio
@asyncio.coroutine
def test_await_time():
def resolve_or_reject(resolve, reject):
time.sleep(.1)
resolve(True)
... |
# Generated by Django 3.0.5 on 2020-04-16 21:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('contact_form', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='contactrequest',
name='message',... |
import pandas as pd
train=pd.read_csv('train.csv',index_col=0)
test=pd.read_csv('test.csv',index_col=0)
#print(train['Attrition'].value_counts())
# 处理Attrition字段
train['Attrition']=train['Attrition'].map(lambda x:1 if x=='Yes' else 0)
from sklearn.preprocessing import LabelEncoder
# 查看数据是否有空值
#print(train.isn... |
import sys
epgService = '/ds/epg/service.asmx'
server = 'ivsmedia.iptv-distribution.net'
ContentService = '/ContentService.svc/soap'
sid = '/ClientService.svc/soap'
siteId = '5'
appName = 'XBMC Plugin (' + sys.platform + ')'
streamService = '/ds/cas/streams/generic/stream.a... |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 03 11:50:01 2015
@author: Yang
"""
import pandas as pd
stock_data=pd.read_csv('D:/Wind/data/000001.SZ.marketDay.csv',parse_dates=[9])
stock_data.sort('TIME', inplace=True)
print stock_data
ma_list = [5, 20, 60]
for ma in ma_list:
stock_data['MA_' + str(ma)] = pd.roll... |
ASSET_FIELDS = ("author_payout_scr_value",
"author_payout_sp_value",
"beneficiary_payout_scr_value",
"beneficiary_payout_sp_value",
"curator_payout_scr_value",
"curator_payout_sp_value",
"from_children_payout_scr_value",
... |
# -*- coding: utf-8 -*-
import codecs
# Extract ehownet Specific domain terms!
class Extract:
def __init__(self):
self.ehownet = codecs.open('resultSimple.csv', 'r', encoding = 'utf-8')
self.location_set = set()
self.location = ["世界", "省", "區", "市", "國都", "縣", "縣", "居民區", "鄉", "ChinaTown", "大陸", "非洲", "美洲", "亞洲"... |
# -*- coding: utf-8 -*-
###############################################################################
# Copyright (c), The AiiDA-CP2K authors. #
# SPDX-License-Identifier: MIT #
# AiiDA-CP2K is hosted on GitHub at https://github.com/c... |
numbers = range(1,50)
print ("'y' is odd numbers and 'x' is even numbers")
x = [n for n in numbers if n%2 != 0]
y = [n for n in numbers if n%2 == 0]
print("y =", y)
print("x =", x)
|
import numpy as np
import pandas as pd
from tensorflow import keras
# from sklearn.externals import joblib
import joblib
class PrintDot(keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs):
if epoch % 100 == 0: print('')
print('.', end='')
class Model(object):
def __init__(self):
... |
# francois auxietre conversion analogique en python 3 pour la lecture d'un anémometre
# pip install pyserial
# The anemometer is designed to output voltage between 0.4V and 2V.
# A value of 0.4V represents no wind and 2V represents a wind speed of 32.4 m/s.
# The relationship between voltage and wind speed is linear,... |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 10 13:15:28 2017
@author: Saicharan.S
"""
import pandas as pd
df = pd.DataFrame({'id':[1,2,3], 'fare':[13, 15.7, 25]})
type(df)
df.shape
df.info()
df['fare']
df.iloc[0:2] |
import unittest
from zserio.bitfield import (getBitFieldLowerBound, getBitFieldUpperBound, getSignedBitFieldLowerBound,
getSignedBitFieldUpperBound)
from zserio.exception import PythonRuntimeException
class BitFieldTest(unittest.TestCase):
def testGetBitFieldLowerBound(self):
... |
#!/usr/bin/env python
# coding: utf-8
# # Práctica 1 Vectorización
# ## Calculo de integrales mediante el metodo de Monte Carlo
# Importamos las librerias que nos harán falta:
# + matplotlib para hacer gráficas <br>
# + numpy para generar números aleatorios y operaciones con arrays <br>
# + time para calcular el tiem... |
import pytest
from oidcendpoint.endpoint_context import EndpointContext
from oidcendpoint.user_authn.authn_context import INTERNETPROTOCOLPASSWORD
from oidcmsg.key_jar import init_key_jar
from oidcop.cookie import CookieDealer
KEYDEFS = [
{"type": "RSA", "key": '', "use": ["sig"]},
{"type": "EC", "crv": "P-25... |
#!/usr/bin/env python3
"""
MIT License
Copyright (c) 2020 Paul G Crumley
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 limitation the rights
to use, copy,... |
#-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*-
from bes.system.log import logger
from .string_lexer import string_lexer, string_lexer_options
class string_list_parser(object):
_log = logger('string_list_parser')
def __init__(self, options = 0):
self._options = o... |
from sklearn import linear_model
from sklearn import datasets
from sklearn.preprocessing import PolynomialFeatures
import numpy as np
import pandas as pd
import csv
import matplotlib.pyplot as plt
import pylab
import random
'''
algorithms
laplace
'''
train_data_Y = [ x**2 + random.randrange(-2,2) for x in range(-10,... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2017-07-14 06:29
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Version',... |
from turbofats.Base import Base
from turbofats import lomb
import numpy as np
class PeriodLS_v2(Base):
def __init__(self, shared_data, ofac=6.0):
super().__init__(shared_data)
self.Data = ['magnitude', 'time', 'error']
self.ofac = ofac
def fit(self, data):
magnitude = data[0]
... |
#!/usr/bin/env python
#coding:utf-8
# Author: LPP --<lpp1985@hotmail.com>
# Purpose:
# Created: 2011/4/19
import multiprocessing
from lpp import *
all_file = glob.glob( '*.corr' )
def check( e_f ):
RAW = fasta_check(open( e_f,'rU' ) )
cache_hash = {}
for t,s in RAW:
cache_hash[ t[1:-1].split( )[0] ] = ''
EN... |
__author__ = 'tamar'
class Crowdmap(object):
def __init__(self, init_list):
self.list = init_list
self.location_service = LocationService()
def get_all_posts_for(self, name):
return [post for post in self.list if post.find(name) != -1]
def is_location_for_name(self, name):
name_posts = self.get_all_posts_... |
from __future__ import absolute_import
import logging
from eth_utils import (
pad_right,
)
from evm.constants import (
BLOCK_REWARD,
NEPHEW_REWARD,
UNCLE_DEPTH_PENALTY_FACTOR,
)
from evm.exceptions import (
ValidationError,
)
from evm.logic.invalid import (
InvalidOpcode,
)
from evm.state imp... |
from keras.layers import Input, Dense
from keras.models import Model
import numpy as np
from keras.layers import LSTM, TimeDistributed, Activation
from keras.optimizers import RMSprop
from keras.preprocessing import sequence
from keras.utils import to_categorical
from keras.callbacks import Callback
from keras.callback... |
import csv
import string
from multiprocessing.pool import ThreadPool
from requests.exceptions import ConnectTimeout, ConnectionError, ProxyError
from settings import *
from utils.utils import *
class CrawlError(Exception):
...
def crawl(writer, page=1):
print(f'Starting fetch Page {page}')
callback_st... |
def matchtyper(li):
import json
import collections as cl
data = cl.OrderedDict()
data[li[0]] = li[1]
ys = cl.OrderedDict()
d = ys[li[0]] = data
return d
#もしjsonファイルに書き出す場合。↓の処理
#fw = open('test.json','w')
#json.dump(ys,fw,indent=4)
if __name__ == '__main__':
li = ["Kodai",[1... |
class Solution:
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
res, tmp = [], []
self.collector_combination(candidates, target, tmp, res)
return res
def collector_combina... |
#!/Users/hanzhang/Documents/GitHub/learning_log_django/ll_env/bin/python3
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
|
from a10sdk.common.A10BaseClass import A10BaseClass
class Partition(A10BaseClass):
"""Class Description::
Create/unload a Network partition.
Class partition supports CRUD Operations and inherits from `common/A10BaseClass`.
This class is the `"PARENT"` class for this module.`
:param partitio... |
import requests
import json
with open('token.json', 'r') as file:
data = json.load(file)
TOKEN = data[0]['token']
class Group:
def __init__(self, id):
self.id = id
def get_params(self):
return {
'group_id': self.id,
'fields': 'members_count',
'acces... |
'''
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
Find the sum of all numbers which are equal to the sum of the factorial of their digits.
Note: as 1! = 1 and 2! = 2 are not sums they are not included.
'''
from _functools import reduce
from time import time
def is_curious(num,pro_dict):
tmp=num
... |
import os
import sys
import uuid
import configuration
import json
import pandas as pd
from forecaster.forecaster_factory import ForecasterFactory
from forecaster.datamanager import DataManager
from argparse import ArgumentParser
"""
This module loads and ARIMA model and outputs a forecast.
"""
class Predict():
... |
#!/usr/bin/python
import difflib
import sys
try:
textfile1=sys.argv[1]
textfile2=sys.argv[2]
except Exception,e:
print "Error:"+str(e)
print "Usage: simple3.py filename1 filename2"
sys.exit()
def readfile(filename): #文件读取分隔函数
try:
fileHandle = open (filename, 'rb' )
text=f... |
import cv2
import matplotlib.pyplot as plt
import numpy as np
def display_img(img, cmap=None):
fig = plt.figure(figsize=(12, 6))
ax = fig.add_subplot(111)
ax.imshow(img, cmap)
# Open and display the giraffes.jpg
img = cv2.imread('../DATA/giraffes.jpg')
img_color_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB... |
# Example 1: Using negative indexing
my_list = ['a', 'b', 'c', 'd', 'e', 'f']
# print the last element
print(my_list[-1])
|
class FoxAndClassroom:
def ableTo(self, n, m):
s, i, j = set(), 0, 0
while (i, j) not in s:
s.add((i, j))
i, j = (i+1)%n, (j+1)%m
return 'Possible' if len(s) == n*m else 'Impossible'
|
import requests
import math
from pyquaternion import Quaternion as quat
url = "https://t-solvies.herokuapp.com/fetch.php"
req = requests.get(url)
tri = req.text.split("|")
'''
signx = -1
switchx = False
signy = -1
switchy = False
signz = -1
switchz = False
ax = []
ay = []
az = []
gx = []
gy = []
gz = []
for i in... |
__author__ = 'Kamil Koziara & Taiyeb Zahir'
import cProfile
import numpy
from utils import generate_pop, HexGrid, draw_hex_grid
from stops_ import Stops2
secretion = numpy.array([0, 5])
reception = numpy.array([3, 4])
receptors = numpy.array([-1,-1])
bound=numpy.array([1,1,1,1,1,1])
base1=numpy.array([0,0,1,0,0,0])... |
import serial
import sys
import time
import serial.tools.list_ports
serPort = ""
totalPorts = 0
count = 0
eggComPort = ""
eggCount = 0
eggNotFound = True
while eggNotFound:
# Find Live Ports
ports = list(serial.tools.list_ports.comports())
totalPorts = len(ports)
print "there are " + str(totalPorts)... |
import itertools
import numpy as np
import copy as cp
from collections import OrderedDict
import matplotlib.pyplot as plt
import topology
INF = 9999
NODECNT = 0
avBranch = [[0, 2], [0, 3], [1, 2], [1, 3]]
avBranch2 = [[0, 3], [0, 4], [0, 5], [1, 3], [1, 4], [1, 5], [2, 3], [2, 4], [2, 5]]
def f_undire... |
# -*- coding: utf-8 -*-
import logging
from zope.publisher.browser import BrowserView
# from operator import attrgetter
# from plone import api
logger = logging.getLogger('bebest')
class bebestPageView(BrowserView):
def __init__(self, context, request):
self.context = context
self.request = req... |
# Wykonaj funkcję dodawania obu macierzy zapisanych wcześniej do zmiennych a i b.
import zadanie_5
import zadanie_6
print(zadanie_5.a + zadanie_6.b) |
import numpy as np # numpy - manipulate the packet data returned by depthai
import cv2 # opencv - display the video stream
import depthai # access the camera and its data packets
import consts.resource_paths # load paths to depthai resources
import os
device = depthai.Device("", False)
# Create the pipeline using... |
from mpi4py import MPI
comm = MPI.COMM_WORLD
sendmsg = [comm.rank]*3
right = (comm.rank + 1) % comm.size
left = (comm.rank - 1) % comm.size
req1 = comm.isend(sendmsg, dest=right)
req2 = comm.isend(sendmsg, dest=left)
lmsg = comm.recv(source=left)
rmsg = comm.recv(source=right)
MPI.Request.waitall([req1, req2])
asse... |
import requests
import json
def connect(number, token):
s = requests.Session()
s.headers['authorization'] = 'Bearer ' + token
parameters = {'rows': '50'}
h = s.get('https://edge.qiwi.com/payment-history/v1/persons/' + number + '/payments', params=parameters)
req = json.loads(h.text)
return req... |
import time
import datetime
import ephem
import random
#GPIO.setmode(GPIO.BOARD)
#GPIO.setup(10, GPIO.OUT)
# make sure "off_minutes" has a value
off_minutes = 1
while 1:
print('in the loop')
now = datetime.datetime.now()
now_hours = time.localtime(time.time())[3]
now_minutes = time.localtime(time.time())[4]
#... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
generate_alignments.py: Code used for creating alignments for
mammalian genomes, which will be used for developing consensus
sequence score thresholds and for the Hood-Price adjudication
project.
Contains variety of util functions for:
- separating consensus sequences in... |
from tensorflow_io.bigquery import BigQueryClient
from tensorflow_io.bigquery import BigQueryReadSession
import tensorflow as tf
from tensorflow.python.framework import dtypes
from tensorflow import feature_column
import os
training_data_uri = os.environ["AIP_TRAINING_DATA_URI"]
validation_data_uri = os.environ["AIP_V... |
import os
import threading
import time
import urllib2
import socket
#####
import Helper
#####
class ForgePacket(threading.Thread):
def __init__(self, url, packetHeaders):
threading.Thread.__init__(self)
self.url = url
self.packetHeaders = packetHeaders
self.disconnectionError = False
self.exception = Fal... |
# Generated by Django 3.2.6 on 2021-08-28 17:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ecom', '0032_hijab_treasure'),
]
operations = [
migrations.AlterField(
model_name='hijab',
name='category',
... |
import functools
from tensorflow import keras
import numpy as np
IMAGE_SHAPE = (48, 48, 1)
TRAIN_SIZE = 28709
VALIDATION_SIZE = 3589
TEST_SIZE = 3589
CLASSES = 7
RANDOM_ROTATION_CONFIG = {
'rotation_range': 30, # Random rotations from -30 deg to 30 deg
'width_shift_range': 0.1,
'height_shift_range'... |
import csv
import pandas as pd
import numpy as np
import natsort
import os
import moviepy
from moviepy.editor import VideoFileClip
from skimage.measure import compare_ssim as ssim
from scipy import spatial
import subprocess
from PIL import Image
#USE this command in TERMINAL TO REMOVE .DS_Store file
'''
import glob, ... |
# -*- coding: utf-8 -*-
#################################################################################
# Author : Acespritech Solutions Pvt. Ltd. (<www.acespritech.com>)
# Copyright(c): 2012-Present Acespritech Solutions Pvt. Ltd.
# All Rights Reserved.
#
# This program is copyright property of the author menti... |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 29 10:53:05 2019
@author: Minimol
"""
#Using the keys(), values(), and items() methods, a for loop can iterate over the keys, values,
#or key-value pairs in a dictionary, respectively.
spam = {'color': 'red', 'age': 42 , 'size' : 'big' , 'efficiency' : 'high'}
print()... |
from django.contrib import admin
from .models import Post, PostCategories
from django import forms
from django.db import models
class PostAdmin(admin.ModelAdmin):
list_display = ('title', 'slug', 'status','created')
list_filter = ("status",)
search_fields = ['title', 'content']
prepopulated_fields = ... |
def pattern_search_multiple(data_series, pattern_width, threshold):
data_series_length = len(data_series)
# suppose pattern width is 4, we can't find the pattern in the data_series
# if lenght of data_series is less than 9 (due to given conditions).
if data_series_length < 2 * pattern_width + 1:
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from random import randint
from flask import url_for
from jinja2 import Markup
from wtforms.widgets import Input, HTMLString
class CaptchaWidget(object):
def __call__(self, field, **kwargs):
rand = randint(0, 0xffffffff)
html = HTM... |
from django.db import models
class MainMenu(models.Model):
name = models.CharField(max_length=50, null=True)
class Meta:
db_table='main_menus'
class ProductCategory(models.Model):
menu = models.ForeignKey('MainMenu', on_delete=models.CASCADE, null=True)
name = models.CharField(max_length=50, ... |
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and rel... |
from contactos import views
from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^$', views.index, name='index')
) |
# -*- coding: utf-8 -*-
import pytest
"""
Test paste 1 ligne : contenu + délai
Test paste 1 cellule : contenu + délai
Test affichage URL 1 ligne dans NB : récupération output ?
Test affichage URL 1 cellule dans NB : idem ?
Test get (avec une URL de test forever ?)
"""
import requests
import dpaste_magic
def test_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.