text stringlengths 8 6.05M |
|---|
from suds.client import Client
from suds import WebFault
from model.project import Project
from test_adds import adjustement
class SoapHelper:
def __init__(self, app):
self.app = app
def can_login(self, username, password):
client = Client('http://localhost/mantisbt-1.2.19/api/soap/mantisco... |
from collections import OrderedDict
from typing import Callable, Dict, List, Optional, Tuple
import torch.nn.functional as F
from torch import nn, Tensor
from ..ops.misc import Conv2dNormActivation
from ..utils import _log_api_usage_once
class ExtraFPNBlock(nn.Module):
"""
Base class for the extra block in ... |
#!/usr/bin/env python3
#############################################################################
#
# ja3 window analytic: Looks for unrecognised_stream events, and if there is a
# hello handshake in the payload then try to extract ja3 signature
#
# Summary information includes: src, dest, device and ja3 md5 dige... |
# -*- coding: utf-8 -*-
"""Stub to allow old tools to work."""
from setuptools import setup
setup()
|
import os
import csv
import subprocess
USERNAME = os.environ['USERNAME']
PASSWORD = os.environ['PASSWORD']
WORKDIR = os.getcwd()
repo_info_csv = 'repo_info.csv'
def read_csv(repo_info_csv):
repo_info_list = list()
with open(repo_info_csv) as fh:
rd = csv.DictReader(fh, delimiter=',')
for row ... |
import numpy as np
from numpy.linalg import inv
import quaternion
import math
from data.sample import Sample
def truncation_normalization_transform(s: Sample) -> Sample:
truncation = 3 * s.size # 3
s.tdf = np.abs(s.tdf) # Omit sign
s.tdf = np.clip(s.tdf, 0, truncation) # Truncate
s.tdf = s.tdf / tru... |
def ReduceFraction(num, denom):
from fractions import gcd
divisor = gcd (num, denom)
num = num / divisor
denom = denom / divisor
print ( str(num) + "/" + str (denom) )
|
"""
Created by Alex Wang on 2018-01-09
"""
import numpy as np
from sklearn import metrics
def cal_precision_recall(predict, tags):
"""
计算roc
:param predict: (batch_size, 2)
:param tags:(batch_size, 1) 0/1
:return:
print('roc thresholds:{}'.format(','.join(['{:.4f}'.format(item) for item in roc_... |
import logging
# log=logging.getLogger('名字') # 跟配置文件中loggers日志对象下的名字对应
log=logging.getLogger('django')
|
def myfunction(old):
if old > 18:
result: str = "Maior de idade"
elif old == 18:
result: str = "completou 18 anos"
else:
result: str = "Menor de idade"
return result
pass
nome = input("What's your name?")
print(nome)
text = 2 + 2
print(text)
age = int(input("Idade"))
res... |
from collective.websemantic.base import WebsemanticBaseMessageFactory as _
from collective.websemantic.base.interfaces import IWebSemanticPlugin
from zope.component import getGlobalSiteManager
from zope.schema.interfaces import IVocabularyFactory
from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm
class P... |
import numpy as np
import cv2
#이미지 비트 연산은 이미지에서 특정 영역을 추출하거나 직사각형 모양이 아닌 ROI를 정의하거나 할 때 매우 유용하다
def bitOperation(hpos, vpos):#인자로 로고가 있을 좌표를 받는다.
img1 = cv2.imread('images/sana.jpg')
img2 = cv2.imread('images/logo.jpg')
#로고를 사나 사진 왼쪽 윗부분에 두기 위해 해당 영역 지정
rows, cols, channels = img2.shape#로고 이미지의 크기를 구한... |
import math
from mininet.log import info
def getDistance(h1, h2):
distance = math.sqrt((int(h1.params['position'][0]) - int(h2.params['position'][0])) ** 2 + (int(h1.params['position'][1]) - int(h2.params['position'][1])) ** 2)
return distance |
from django.apps import AppConfig
class ProgressBarConfig(AppConfig):
name = 'django_celery_progressbar'
|
import numpy as np
from idlpy import interpolate
class InterpLonLat():
def __init__(self, origLon, origLat):
self.newLon = None
self.newLat = None
self.dLon = None
self.dLat = None
self._xint = None
self._yint = None
self.origLon = origLon
self.origLat = origLat
@pro... |
# Generated by Django 3.1 on 2020-08-28 17:30
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('manager', '0002_auto_20200828_1549'),
]
operations = [
migrations.AddField(
model_name='order_detail',
name='start_tim... |
import numpy as np
import scipy.interpolate as spi
import pandas as pd
import matplotlib.pyplot as plt
import math
#Reto 2 Analisis Numerico
#Santiago Fernandez - Mariana Galavis - German Velasco
#Principales referencias durante el desarrollo del codigo:
#https://numpy.org/
#https://docs.scipy.org/doc/scipy/reference/... |
import json
from redis import StrictRedis
db = StrictRedis(host='localhost', port=6379)
jokes = [dict(json.loads(db.get(k))['log_data'].items() + [('jokeId', k)]) for k in db.keys('jokes:*')]
with open('_static/jokedata.json', 'w') as f:
json.dump(jokes, f, indent=2)
|
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
# 自定义动画
# 定义画布,默认值,这个fig需要,虽然默认大小设置,fig需要挂在动画上
fig = plt.figure()
# 坐标轴刻度
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
# color='blue'=蓝色,否则默认为清淡蓝色
line, = ax.plot([], [], lw=2, color='blue')
# 因为动画,所以初始化列表线条
def init():
line.... |
from ApplicationManager import ApplicationManager
from PyQt5 import QtWidgets
import LoggersConfig
from LoggersConfig import loggers
if __name__ == "__main__":
import sys
try:
app = QtWidgets.QApplication(sys.argv)
LoggersConfig.init_loggers()
AppManager = ApplicationManager()
... |
from __future__ import print_function, division
import os
from isochrones.starfit import starfit
from .data import dirname, STARMODELDIR
from .models import GaiaDR1_StarModel
from .write import write_ini
def tgas_starfit(i, write_ini_file=True, ini_kwargs=None, rootdir=STARMODELDIR,
**kwargs):
... |
import torch as tc
x=tc.ones(2,2,requires_grad=True)
print(x)
y=x+2;print(y)
print(y.grad_fn)
z=y*y*3;print(z)
out=z.mean();print(z,out)
a=tc.randn(2,2);a=((a*3)/(a-1))
print(a.requires_grad)
a.requires_grad_(True)
print(a.requires_grad)
b=(a*a).sum()
print(b.grad_fn)
out.backward()
print(x.grad)
x=tc.randn(3,requires_... |
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import selenium.webdriver.support.expected_conditions as EC
import selenium.webdriver.support.ui as ui
from selenium.common.ex... |
import time
from datetime import date
def test():
assert calc_working_day(3, 2016, 9, 1) == 5
assert calc_working_day(11, 2016, 9, 2) == 17
def what_week_day(year, month, day):
return date(year, month, day).weekday()
def calc_working_day(x, year, month, day):
day = 5 - what_week_day(... |
# user 별로 model 생성
import tensorflow as tf
import pandas as pd
from keras.layers import Input, Dense, Dropout
from keras.models import Model
from keras.metrics import Precision, Recall
from keras.optimizers import Adam
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
i... |
# -*- coding: utf-8 -*-
__author__ = 'Tom Raz'
__email__ = 'tom@zeitgold.com'
__version__ = '0.1.0'
|
# people = [
# ["Chad", "Reynolds", 35],
# ["Taylor", "Reynolds", 29]
# ]
# coords = [
# [10,10],
# [20,10],
# [10,20]
# ]
# print(people[0])
# print(people[0][2]) # 0 points to the first list and the 2 points to the item in the first list at index 2
# me = people[0]
# print(me[2]) #will print ... |
import sys
import re
data = sys.stdin.readlines()
# wordsInTheText = data[0].split(' ')
wordsInTheText = re.findall(r"[\w']+", data[0])
lengthOfData = len(wordsInTheText)
# commonly occuring words in Wikipedia articles
placeMetadata = ['at','from','where','here','place','near','to','North','Northern','South',
'Sou... |
a1=(input("Enter alphabet: "))
if(a1=='a' or a1=='A' or a1=='e' or a1=='E' or a1=='i' or a1=='I' or a1=='o' or a1=='O' or a1=='u' or a1=='U'):
print("It is Vowel.")
else:
print("It is Consonant.") |
class Secrets:
'''
Secrets here because I am bad at secret management.
'''
netbox_url = ''
netbox_username = ''
netbox_token = ''
napalm_username = ''
napalm_password = '' |
import qgis.core
#get Rasterr layer
#now it i not the best way to do
rlayer = qgis.utils.iface.activeLayer()
#getting sample from raster
#identity() object
ident = rlayer.dataProvider().identify(QgsPoint(100,-100),QgsRaster.IdentifyFormatValue)
sampleValue = ident.results()
#gdal import
gtif=gdal.Open("/home/user/th... |
import argparse, glob, sys, json, ast, copy
from random import shuffle
def txt_to_np_arr(phrase, chat_dict):
word_arr = phrase.split()
normalized_arr = []
for word in word_arr:
normalized_arr.append(chat_dict[word])
return normalized_arr
def txt_to_dict(phrase):
chat_dict = {}
#split ... |
# Generated by Django 2.2.4 on 2019-10-06 08:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('security_guards', '0002_security_identity_no'),
]
operations = [
migrations.AlterModelOptions(
name='devicenumber',
... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
import raft.protos.raft_pb2 as raft__pb2
class NodeStub(object):
"""The generic server node definition.
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.AppendEntrie... |
import numpy as np
from shapely.geometry import Polygon, MultiPolygon, LineString, MultiLineString, Point, LinearRing
from shapely.ops import polygonize, cascaded_union
from scipy.spatial.qhull import Delaunay
from crowddynamics.core.distance import distance_circle_line
from crowddynamics.core.sampling import triangle... |
from helpers import *
def main():
tests_specs = [
("Merge sort", 'merge_sort', [10000000, 100]),
("Insertion sort", 'insertion_sort', [100000, 100]),
("Prime sum", 'prime_sum', [20000]),
("Tag", 'tag', [300]),
("String perm", 'perm', ["ABCDEFGHIJ"]),
("Prime coun... |
def last(s):
return sorted(s.split(),key=lambda x: x[-1])
'''
Given a string of words (x), you need to return an array of the words,
sorted alphabetically by the final character in each.
If two words have the same last letter, they returned array should show them
in the order they appeared in the given string.
... |
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_excel("../data/data.xlsx", sheetname="fiscal",
index_col=0, dec=',', skiprows=[0, 1])
df = df*(-1)/1000
df["target"] = -139
df['12 months rolling'] = df.iloc[:, [0]].rolling(window=12).sum()
df.dropna(inplace=True)
# charts
def gen_ch... |
from Tree import Tree
from Node import Node
import re
class TreeBuilder:
def __init__(self, data):
self.data = data
self.tree = None
def computeLevel(self, rawNode):
level = 1
for c in rawNode:
if(c == '|'):
level = level + 1
elif(c == '+' or c == '\\'):
break
# fix some special issue
spa... |
# Author: Giuseppe Di Giacomo s263765
# Academic year: 2018/19
from lib.timeControl import TimeControl
from lib.peopleControl import PeopleControl
from lib.roomControl import RoomControl
import time
import requests
import json
# IP of room catalog
catalog_IP = '172.20.10.11'
# port of room catalog
catalo... |
import sqlite3 as lite
import sys
import os
import csv
import urllib
import datetime
f = open('D:/Users/zjy/documents/bikeshare/2015_Q3.csv')
csv_f = csv.reader(f)
next(csv_f,None) #skip the headers
#dic for start_time and from_station_id, key is trip_id
start_day = dict()
start_hour = dict()
from_station_id = dict(... |
import folium
import geoip2.database
from geopy.geocoders import Nominatim
from geopy.distance import geodesic
from django.shortcuts import render, get_object_or_404
from django.views.generic import TemplateView
from .models import Visitor, Measurement
from .forms import MeasurementModelForm
from .utils import get_geo,... |
from abc import ABC, abstractmethod
# Абстрактный класс для дополнения данных
class Autocompleter(ABC):
def __init__(self):
super().__init__()
# Получение автодополнений, где
# con - соединение
# tokens (list) - список лексем
# content (str) - содержимое файла
# line (int) - строка
... |
fahrenheit=float(input("Enter the temperature in fahrenheit"))
celsius = (fahrenheit - 32) / 1.8
print("Temperature in celcius is",celsius)
|
import os
import csv
csvpath = os.path.join('Resources', 'budget_data.csv')
#establish lists
months = []
profit_losses = []
profit_loss_differential = []
print (csvpath)
# Open and Read the CSV file
with open(csvpath, 'r') as csvfile:
# split the data on commas
csvreader = csv.reader(csvfile,... |
# 取一个list或tuple部分元素
L=['pengrong','super','bilaisheng','chenzhongyi','changjie','lily']
# 笨方法
[L[0],L[1]]
# 切片
L[0:2]
|
# coding=utf-8
from __future__ import unicode_literals
from django.db import models
from django.contrib.gis.db import models
from django.utils.translation import ugettext as _
from userprofiles.models import User
class CustomPhoneNumber(models.Model):
choices_phone_type = (
('M', _('Móvil')),
('... |
import os
import numpy as np
import autodisc as ad
from autodisc.representations.static.pytorchnnrepresentation.helper import DatasetHDF5
import torch
from torch.utils.data import DataLoader
from torch.autograd import Variable
from autodisc.gui.jupyter.misc import create_colormap, transform_image_from_colormap
from PIL... |
num=int(input("enter the number"))
val= num//10
print (val)
|
from os import makedirs
from os.path import join, exists, dirname
import sys
import datetime
import shutil
import csv
def setup_logfile(log_file_dir):
if not exists(log_file_dir):
makedirs(log_file_dir)
log_file_path = join(log_file_dir, datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + "_Logfi... |
from django.conf.urls import patterns, url
from competition import views
urlpatterns = patterns('',
url(r'^category/$', views.category, name="category"),
url(r'^$', views.competition_home, name="competition_home"),
url(r'^info/$', views.competition_info, name="competition_info"),
url(r'^sponsors/$', views.comp... |
#challenge number 2: Even Fibonnachi Numbers
Total = 0
varOld = 1
varNew = 2
buffer = 0
def checkEven(Total, arg1):
number = arg1 % 2
if number == 0:
return arg1
else:
return 0
while varNew < 4000000:
Total += checkEven(Total, varNew)
buffer = varNew + varOld
varOld = varNew... |
#!/usr/bin/env python3
from random import shuffle as y
from random import randint as r
from time import sleep as o
from base64 import b64decode as u
t = print
g = range
n = input
l = len
f = "WVRKMGVtVXpVbTloV0UxNFl6STFkbVJIV25OWlYyUm1XVmRLYWxwSFZtMU5SRVY1VFhwUk1VNXFZelJQV0RBOQ=="
m = [x for x in g(l(f))]
def a(d, e... |
# -*- coding: utf-8 -*-
from typing import List
class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
index = {}
for i, num in enumerate(sorted(nums)):
if num not in index:
index[num] = i
return [index[num] for num in nums]
if __... |
import numpy as np
import sys
import time
from multiprocessing import Process, Queue
from . import plotter_base
from plotter.utils.helper import overrides
import importlib
try:
motorlib_loader = importlib.util.find_spec('RPi.GPIO')
except:
motorlib_loader = None
if motorlib_loader is None:
print("RPi.GP... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2020 the HERA Project
# Licensed under the MIT License
"""Command-line drive script for hera_cal.xtalk_filter with baseline parallelization. Only performs DAYENU Filtering"""
from hera_cal import xtalk_filter
import sys
import hera_cal.io as io
parser = xtalk... |
"""
threading.local #可以保存全局变量,但是只针对当前线程
"""
import threading,time
a = threading.local()
def working():
a.x = 0
for x in range(20):
time.sleep(0.01)
a.x += 1
print(threading.current_thread(),a.x)
for i in range(10):
threading.Thread(target = working).start() |
import os, platform
from PyQt5 import QtWidgets, uic, QtCore, QtGui, Qt
from functools import partial
import GlobalSettings
import gzip
import traceback
import math
#global logger
logger = GlobalSettings.logger
class OffTarget(QtWidgets.QMainWindow):
def __init__(self):
try:
super(OffTarget, ... |
import tornado
from tornado.options import define, options
import json
import logging
import urllib
import urllib2
#import settings
class Pay( object ):
def __init__( self, amount, sender, receiver, return_url, cancel_url, remote_address, secondary_receiver=None, ipn_url=None, shipping=False ):
self.headers = {... |
# author: Yixuan Duan
import pandas as pd
class DataManager:
def __init__(self, file_path):
self._data = pd.read_csv(file_path)
self._back_up = self._data.copy()
def load_dataframe(self, df):
self._data = df
def group_sales_by(self, column_name):
try:
se... |
import datetime
import re
from transliterate import translit
from django.db import models
from django.utils import timezone
from authentication.models import CustomUser
class BaseModel(models.Model):
objects = models.Manager()
class Meta:
abstract = True
class Genre(BaseModel):
name = models.... |
from .logic import get_timed_loop_from_config, get_exchange_data, currencies_list_from_config, convert_dic_to_list, \
create_mongo_dic, get_mongo_url
|
from setuptools import setup, find_packages
with open('README.md') as f:
read_me = f.read()
with open('requirements.txt') as rf:
requirements = rf.read()
setup(
name='PyReQTL',
version='0.4.0',
description='A python library equivalent to R ReQTL Toolkit.',
long_description=read_me,
long_d... |
import base64
import http.client
import json
from random import SystemRandom
from django.conf import settings
__all__ = (
'Routee',
'random_with_n_digits',
)
def random_with_n_digits(n):
return "".join(SystemRandom().choice('123456789') for _ in range(n))
class Routee(object):
def __init__(self):... |
# Generated by Django 2.2.6 on 2020-03-04 05:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('work', '0092_auto_20200303_1124'),
]
operations = [
migrations.AddField(
model_name='historicalsiteextra',
name='is_... |
from django.conf import settings
from django.conf.urls.defaults import *
urlpatterns = patterns('',
url(r'^$', 'profile.views.view', name='profile_view'),
url(r'^update/$', 'profile.views.update', name='profile_update'),
url(r'^delete/$', 'profile.views.delete', name='profile_delete'),
#@todo: bad-regexp ne... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import time, ConfigParser, urllib2
sys.path.append('/usr/lib64/mpd_validator_automation')
sys.path.append('/usr/lib64/mpd_validator_automation/selenium')
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys im... |
from scapy.all import *
# packet callback
def packet_callback(packet):
print(packet.show())
# run the sniffer
sniff(prn=packet_callback,count=1)
|
import unittest
from katas.beta.how_much_coffee_do_you_need import how_much_coffee
class HowMuchCoffeeTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(how_much_coffee([]), 0)
def test_equal_2(self):
self.assertEqual(how_much_coffee(['cw']), 1)
def test_equal_3(self)... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Merge all subcrawlers into one stream.
For the ground-truth stream, the lower bound is the merged tweets (as they are what we observed/what happened).
The upper bound is the number of merged tweets plus the sum of all rate limit messages,
assuming all missing tweets in... |
import PySimpleGUIWeb as sg
layout=[[sg.Text("name:")], [sg.Input(key="-INPUT-")], [sg.Text(size=(40,1,), key="-OUTPUT-")], [sg.Button("Ok"), sg.Button("Quit")]]
window=sg.Window("Window Title", layout)
while (True):
event, values=window.read()
if ( (event in (sg.WIN_CLOSED,"Quit",)) ):
break
window... |
#-*- encoding:utf-8 -*-
from hello import Collage,db
f= open('collage.txt','rt',encoding="utf-8")
for x in f:
db.session.add(Collage(cname=x[:-1]))
db.session.commit()
f.close() |
import random
import datetime
from collections import Counter
__author__ = "William Hardy Gest"
__version__ = "1.0"
try:
import yagmail
except ModuleNotFoundError as e:
print("External library 'yagmail' required to send emails. Try 'pip install -r requirements.txt'")
exit()
try:
from participants imp... |
#To find the last term of an arithmetic progression
import math
a=input("Enter the starting term of AP 'a':")
n=input("Enter the number of terms of AP 'n':")
d=input("Enter the common difference of AP 'd':")
if n>=1:
an=a+(n-1)*(d)
print "The last term of the AP is",an
else:
print "The inform... |
class MyStack:
def __init__(self):
self.arr=[]
#Function to push an integer into the stack.
def push(self,data):
self.data=data
self.arr.append(self.data)
#Function to remove an item from top of the stack.
def pop(self):
if len(self.arr):
re... |
try:
import numpy as np
from pm4py.objects.log import log as event_log
from pm4py.objects.log.exporter.xes import factory as xes_exporter
from pm4py.objects.log.importer.xes import factory as xes_import_factory
import datetime
from dateutil.tz import tzutc
import sys
import sql... |
from keras.callbacks import LambdaCallback
from keras import backend as K
import matplotlib.pyplot as plt
import numpy as np
import tempfile
class LearningRateFinder:
def __init__(self, model, stop_factor=4, beta=0.98):
# store the model, stop factor, and beta value (for computing a smoothed, avera... |
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect, get_object_or_404
from django.contrib.auth import authenticate, login, logout
from django.template import loader
from django.template.context import RequestContext
from django.core.context_processors import csrf
import ... |
import hidden_markov
import numpy as np
import pandas as p
#Class to launch and use the hidden_markov library with our data
#It's a wrapper of the library
class HMM():
#Class constructor
def __init__(self,states,evidence,probability,transition,emission):
#Hidden states of the net
self.sta... |
# coding=utf-8
import cv2
#opencv的库
import os, shutil
import tensorflow as tf
from tensorflow.python.keras.applications.resnet50 import ResNet50
from tensorflow.python.keras.applications.vgg19 import VGG19
from tensorflow.python.keras.models import load_model
import numpy as np
import sys
font = cv2.FONT_HERSHEY_SIMPL... |
#!/usr/bin/python
import sys, getopt,bsdiff4
def main(argv):
patchFilePath = ''
originFilePath = ''
try:
opts, args = getopt.getopt(argv, "hp:o:", ["patchFilePath =", "originFilePath ="])
except getopt.GetoptError:
print 'bspatch -o <originFilePath> -p <patchFilePath>'
for opt, arg... |
print('Gerador de PA')
print('-=' *10)
primeiro = int(input('Digite o 1º termo: '))
razao = int(input('Digite a razão: '))
termo = primeiro
print('A PA de {} com razão {} :'.format(primeiro, razao))
c=1
maistermos = 10
total = 0
while maistermos!= 0:
total = total+maistermos
while c <= total:
termo = ... |
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
from datetime import datetime
import random
"""-----------------------------------------------------------------
postQuestion - User will post a question
Purpose: Ask user for a question and insert to db
Params: posts, tags (collections)
--... |
import sys; sys.path.insert(0, "/home/adriano/goamazondownloader")
import os
from goamazondownloader import (requests as req, tqdm)
from xml.etree import ElementTree as ET
from goamazondownloader.constants import *
from goamazondownloader._exceptions import *
from goamazondownloader._exceptions import *
class Downloa... |
#!/usr/bin/env python3
"""
Setup and install TSurvey
"""
from setuptools import setup
setup(
name="tsurvey",
version="0.1.0",
description="Anonymous Token-Based Surveys",
long_description="A Complete WSGI solution for creating Anonymous Token-Based Surveys using Flask and Peewee.",
url="https://... |
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
# File: osc4py3/oscnettools.py
# <pep8 compliant>
"""Utility functions for network or serial line communications.
Two functions, :func:`packet2slip` and :func:`slip2packet` allow to
encode and decode SLIP packets to deal with stream based communications
using this proto... |
from PACK import *
class BaseNet(nn.Module):
def __init__(self):
super(BaseNet, self).__init__()
def forward_feature(self, *x):
x0 = x[0]
x0 = self.feature(x0)
x0 = x0.view(x0.size(0), -1)
return x0
def forward_train(self, *x):
x0 = x[0]
x1 = x[1]
... |
import scrapy
from datetime import datetime
from scrapy.http import Request, FormRequest
from scrapy.utils.response import open_in_browser
from json import load, dump
class BookSpider(scrapy.Spider):
name = 'book_of_modules'
start_urls = ['https://bookofmodules.ul.ie/']
dsk_query = '' # bulk... |
# KVM-based Discoverable Cloudlet (KD-Cloudlet)
# Copyright (c) 2015 Carnegie Mellon University.
# All Rights Reserved.
#
# THIS SOFTWARE IS PROVIDED "AS IS," WITH NO WARRANTIES WHATSOEVER. CARNEGIE MELLON UNIVERSITY EXPRESSLY DISCLAIMS TO THE FULLEST EXTENT PERMITTEDBY LAW ALL EXPRESS, IMPLIED, AND STATUTORY WARRANTIE... |
#!/usr/bin/env python
# Level Script
# Use scene.when to schedule events.
# Yield when you want to wait until the next event.
# This is a generator. Using a busy loop will halt the game.
from math import pi
from random import uniform
from game.entities.ai import AvoidAi
from game.scripts.level import Level
class ... |
#! Homework lesson 1 part 1
words = ["разработка", "сокет", "декоратор"]
unicode_words = ["\u0440\u0430\u0437\u0440\u0430\u0431\u043e\u0442\u043a\u0430",
"\u0441\u043e\u043a\u0435\u0442",
"\u0434\u0435\u043a\u043e\u0440\u0430\u0442\u043e\u0440"]
print("Слова в строковом формате")
fo... |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 3 10:11:29 2013
@author: bejar
"""
import numpy as np
import scipy.io
import matplotlib
matplotlib.use('SVG')
from pylab import *
from numpy.fft import rfft, irfft
import pywt
def plotSignalValues(signal1,name):
fig = plt.figure()
minaxis=min(signal1)
maxax... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import itertools
import re
from collections import defaultdict
from typing import Iterable, Iterator, Sequence, Tuple, TypeVar
from pkg_resources impor... |
"""
TP1 : Arbres Génériques
"""
#==============================================================================
#==============================================================================
# Classe 'Node'
#==============================================================================
#===... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'launcher.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from .pyqt_utils import *
cla... |
import os
## Price
# The minimum rent you want to pay per month.
MIN_PRICE = 1500
# The maximum rent you want to pay per month.
MAX_PRICE = 2000
## Location preferences
# The Craigslist site you want to search on.
# For instance, https://sfbay.craigslist.org is SF and the Bay Area.
# You only need the beginning of... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
################################################################################
## raw_socket_sniff_example.py Software Developer SACKUFPI ##
## ... |
from selenium import webdriver
from time import sleep
driver = webdriver.Ie()
driver.get("https://172.18.5.111:8888")
def login_adm():
driver.find_element_by_css_selector("a#overridelink").click()
driver.find_element_by_xpath("//*/input[@id='user']").send_keys('adm')
driver.find_element_by_xpath("//*/inpu... |
from migen import *
from shift_out import *
from spi_receiver import *
class PWM_stripper(Module):
def __init__(self, data):
# FSM to run through the data for each panel and generate a PWM mask
# There will be an instance of this for each panel.
self.submodules.PMW_fsm = FSM(reset_state='... |
departure=input("Departure province:\n").upper()
arrival=input("Arrival province:\n").upper()
travel_type=input("Enter travel type:\n").capitalize()
#print("I am calculating the distance between "+departure+" and "+arrival)
file=open("provinces.txt","r")
provList=[]
name_of_city=[]
loc1=[]
loc2=[]
vehicle=["Car","Mot... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.