text stringlengths 38 1.54M |
|---|
import os
import sys
import kaa
import kaa.webmetadata.tvdb
@kaa.coroutine()
def main():
tvdb = kaa.webmetadata.tvdb.TVDB(os.path.expanduser("~/.beacon/tvdb"))
f = tvdb.from_filename(sys.argv[1])
print 'Series Information'
for key, value in f.series.items():
print ' %s: %s' % (key, value)
... |
# -*- coding: utf-8 -*-
from collections import namedtuple
import csv
from datapro.framework.model.common import Date
from datapro.framework.db import OrmConnection
from datapro.framework.job import EtlJob
from datapro.framework.validation import Validator
from mlb import BATTED_BALL_ANGLES, BATTED_BALL_DISTANCES, B... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import rospy
from geometry_msgs.msg import Twist
from std_msgs.msg import Bool
from grasp import Arm
from config import Config
from perception import Eye
from walk import Leg
from follower import ObjTracker
NODE_NAME = "test_capture_node"
def close_obj_via_follow(obj):
... |
import grpc
import random
import customer_pb2
import customer_pb2_grpc
def create_customer(stub):
print ("-----------Creating Customer-----------")
try:
customer = customer_pb2.CustomerRequest()
addresses = customer.addresses.add()
# Asserting that the length of address would be 1
#assert len(addresses) =... |
'''
This sub-package provides the objects that encapsulate the information that represents the model of
a delivery of titles for a number of rounds and is meant to provide it in a netural manner.
'''
from .parseround import *
|
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 03 13:36:07 2016
@author: Bert Coerver, b.coerver@unesco-ihe.org
"""
from builtins import zip
def get_sheet7_classes():
live_feed = {'Pasture':.5,
'Crop':.25}
# LULC class to Pasture or Crop
feed_dict = {'Pasture':[2,3,12,13,14,15,16,17,20,29,... |
from .sub.subserializers.course import *
from .sub.subserializers.room import *
from .sub.subserializers.subject import *
|
""" Record audio from the microphone and encode as x-speex-with-header-byte to pass to Google
for speech recognition.
Aaron J. Miller, 2012. No copyright held. Use freely for your purposes.
I provide this code for informational purposes only.
"""
import sys
import pyaudio, speex
import numpy as np # just... |
"""
module to test telemetry main class for pipeline telemetry module
"""
from datetime import datetime
import pytest
from telemetry.main import Telemetry, FAIL_COUNT
from telemetry.storage import \
TelemetryInMemoryStorage, AbstractTelemetryStorage
from telemetry.settings import exceptions, settings
from tests.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
class Solution:
# @return a string
def convert(self, s, nRows):
glen = nRows * 2 - 2
if glen < 2:
return s
slen = len(s)
gnum = (slen-1) / glen + 1
rst = [''] * slen
piv = 0
# low
... |
import scrapy
import re
from datetime import datetime
from dateutil.relativedelta import relativedelta
import dateparser
from tpdb.BasePerformerScraper import BasePerformerScraper
class SpankmonsterPerformerSpider(BasePerformerScraper):
selector_map = {
'name': '//div[@id="performer"]/h1/text()|//h1[@clas... |
################## METADATA ##################
# NAME: Etkin Pinar
# USERNAME: a18etkpi
# COURSE: Scriptprogramming IT384G - Spring 2019
# ASSIGNMENT: Assignment 1 - Python
# DATE OF LAST CHANGE: 2019-06-04
##############################################
import apachelog
#finds and prints the most popular value for th... |
import flask
from flask import Flask, request, render_template
from sklearn.externals import joblib
import numpy as np
from scipy import misc
# Flask
# Jinja2
# numpy
# scikit-learn
# scipy
# virtualenv
# pillow
app = Flask(__name__)
# 메인 페이지 라우팅
@app.route("/")
@app.route("/index")
def index():
return flask.re... |
from django.contrib import admin
from scrape_app.models import WebPage, Tag
# Register your models here.
admin.site.register(WebPage)
admin.site.register(Tag)
|
import numpy as np
import signal
import sys
import tensorflow as tf
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.model_selection import StratifiedKFold
from imblearn.over_sampling import SMOTE
from confusion import evaluate
def... |
#!/usr/bin/env python
###
# Copyright (c) 2002-2007 Systems in Motion
#
# Permission to use, copy, modify, and 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 I... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class IsvMerchantSalesDetailRequest(object):
def __init__(self):
self._coupons_quantity = None
self._device_detail = None
self._merchant_pid = None
self._mini_appid = No... |
#!/bin/usr/env python3
## Desc: A script containing different functions profiled from`profileme.py`
"""
A script containing different functions optimised from `profileme.py`
"""
__appname__ = 'profileme2.py'
__author__ = 'Donal Burns (db319@ic.ac.uk)'
__version__ = '0.0.1'
__liscense__ = "Apache 2"
#################... |
import hydra
from hydra.core.config_store import ConfigStore
from deepspeech_pytorch.configs.lightning_config import ModelCheckpointConf
from deepspeech_pytorch.configs.train_config import DeepSpeechConfig, AdamConfig, SGDConfig, BiDirectionalConfig, \
UniDirectionalConfig
from deepspeech_pytorch.training import t... |
"""
Creating New Iteration Patterns with Generators
-----------------------------------------------
Problem:
--------
You want to implement a custom iteration pattern that's different than
usual built-in functions (e.g., range(), reverse(), etc).
Solution:
---------
If you want to implem... |
#!/usr/bin/env python
"""Create a Python script that has three variables: ip_addr1, ip_addr2, ip_addr3 (representing
three corresponding IP addresses). Print these three variables to standard output using a single
print statement.
Make your print statement compatible with both Python2 and Python3.
If you are using... |
import hashlib
import os
import pickle
no_itr = 100000
key_file = 'kk.bin'
info_file = 'info.bin'
message = '''
1.Add more passwords
2.Access passwords
3.Exit
'''
def write(name, lis, mode="w"):
if mode == "a":
with open(name, "ab") as f:
pickle.dump(lis, f)
elif mode ==... |
import tensorflow as tf
import sign_detect.yolo.config as cfg
from PIL import Image
import cv2
import numpy as np
from tensorflow.compat.v1 import ConfigProto
from tensorflow.compat.v1 import InteractiveSession
import threading
import timeit
framework = 'tflite'
iou_threshole = 0.1
CLASS = ['SLOWDOWN','SPEED UP','STOP... |
def VowelCounter(str):
numVowels = 0
for char in str:
if char == 'a' or char == 'e' or char == 'i' \
or char == 'o' or char == 'u':
numVowels += 1
print('# of Vowels: ', end='')
print(numVowels)
|
import time
import numpy as np
# vectorized dot product between two vectors
x, y = np.random.random(100000), np.random.random(100000)
def unvectorized_dot():
prod = 0
arr_len = x.shape[0]
for i in range(arr_len):
prod += x[i] * y[i]
return prod
def vectorized_dot():
return x.dot(y)
def unv... |
distances = {}
print('startplaceref,endplaceref,distance,operatorref,fareref')
with open('kilonetnew.dat', 'r') as f:
lines = f.readlines()
for l in lines:
fr,to,first,second,code = l.split(',')
distances[fr + ':' + to] = int(second)
def expand(lijn, operator, fareref):
for i in range(0, len(lijn)):
... |
# Nick Weiner 2017
# pcfg.py
# Get probabilisitic context free grammar from intron files made by intronitator
import re
from Bio import SeqIO
from Bio.Seq import Seq
from Bio import motifs
def recurse1(seq, parts):
data_set = []
for i in range(1, len(seq)):
addition = [seq[:i]]
for j in range(1... |
# coding: utf-8
# In[2]:
import sys
import numpy
import pandas
import matplotlib
import seaborn
import scipy
import sklearn
print('Python:{}'.format(sys.version))
print('Numpy:{}'.format(numpy.__version__))
print('Pandas:{}'.format(pandas.__version__))
print('Matplotlib:{}'.format(numpy.__version__))
print('Seabor... |
#!/usr/bin/env python26
# encoding: utf-8
import sys
import getopt
import re
from send_alert import Client
kid = "2012090416"
passwd = "VrcUe70eTvnGIm3wd4g6cLtMlvg7s7"
url_path = '/v1/alert/send'
def usage(return_code=2):
help = """
Usage %s --service "service" --object "object" --subject "subject... |
'''
### BEGIN NODE INFO
[info]
name = Bare Bones E3663A
version = 1.0
description =
instancename = Bare Bones E3663A
[startup]
cmdline = %PYTHON% %FILE%
timeout = 20
[shutdown]
message = 9083477
timeout = 20
### END NODE INFO
'''
import visa
from labrad.server import LabradServer, setting
SERVERNAME = "Bare Bones E36... |
# Generated by Django 2.0.5 on 2018-05-12 23:52
from django.conf import settings
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('library', '0001_initial'),
]
operations = [
migr... |
import mxnet as mx
import numpy as np
from gluonts.dataset.repository.datasets import get_dataset
from gluonts.dataset.loader import TrainDataLoader
def data_loader(estimator, dataset, batch):
dataset = get_dataset(dataset)
data = dataset.train
epochs = 5
batch_size = batch
num_batches_per_epoch =... |
# -*- encoding: utf-8 -*-
# pylint: disable=E0203,E1101,C0111
"""
@file
@brief Runtime operator.
"""
import numpy
from ._op import OpRun
from ..shape_object import ShapeObjectFct
from .op_conv_ import ConvFloat, ConvDouble # pylint: disable=E0611
class Conv(OpRun):
atts = {'auto_pad': 'NOTSET', 'group': 1,
... |
#
# https://learn.adafruit.com/make-it-shake-rattle-and-roll/use-in-circuitpython
import time
import math
from adafruit_circuitplayground.express import cpx
from adafruit_circuitplayground import cp
cp.pixels.brightness = 0.05
while True:
# measure accel "num" times and compute an average
sum_angle=0.0... |
from django.test import TestCase
from . models import UserModel
class UserTests(TestCase):
def test_for_user_creation(self):
user_model = UserModel.objects.create(
username='Tailor',
password='somepass',
email='Kaitin@gmail.com'
)
self.assertEquals(user_model.... |
#!/usr/bin/python3
import os
import logging as log
import datetime
import glob
from configparser import ConfigParser
VERSION = 'DirectoryCleanup\nVersion: 1.0.0'
#############################################
# 3 files are required to operate:
#
# 1. DirectoryCleanup.py -> This application
# 2. DirectoryC... |
from fastapi import FastAPI, Body, HTTPException, APIRouter
from fastapi_sqlalchemy import db
from models import Song, Podcast, Audiobook
import schemas
from typing import List, Dict, Optional
router = APIRouter()
@router.get("/audio/{audiofile_type}")
async def read_audiofiles(
audiofile_type: schemas.AudioFil... |
from rest_framework.test import APIClient
from django.test import TestCase
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from django.urls import reverse
class test_LoginView(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(username="abc", pas... |
from gesture import Gesture
class Player:
def __init__(self, name):
self.availableGestures = [Gesture("rock"), Gesture("paper"), Gesture("scissors"), Gesture("lizard"), Gesture("spock")]
self.chosenGesture = Gesture("NULL")
self.name = name
self.score = 0
#ChooseGesture should... |
def patterstar(no):
for i in range(0,no):
for j in range(no, i, -1):
print("*",end="");
print();
patterstar(5); |
#!/usr/bin/env python
# coding: utf-8
# # s{t} = [X{t}, Y{t}, X{t−1}, Y{t−1},..., X{t−7}, Y{t−7}, C].
# The input features s{t} are processed by a residual tower that consists of a single convolutional block
# followed by either 19 or 39 residual blocks.
#
# The convolutional block applies the following modules:
# (1)... |
def partiton(l):
for i in l:
if i.upper()>='A' and i.upper()<='M':
print(i)
print('Enter the first names of soccer players: ',end='')
l=[x for x in input().split()]
partiton(l)
|
#!/usr/bin/env python
# script to generate an /etc/hosts file with ip addrs
# and role-based hostnames for linodes
#
# sys.argv[1] - ansible inventory file generated by linode-launch.py
import sys
with open(sys.argv[1], 'r') as f:
lines = [ l.strip() for l in f.readlines() ]
groups = {}
for l in lines:
i... |
# -*- encoding: utf-8 -*-
# Module iaedgeoff
from numpy import *
from ia870.iasecross import iasecross
def iaedgeoff(f, Bc=iasecross()):
from ia870.iaframe import iaframe
from ia870.iasubm import iasubm
from ia870.iainfrec import iainfrec
edge = iaframe(f)
return iasubm( f, iainfrec(edge, f, Bc))... |
list = [1,3,5,8,10,13,18,36,78,]
n = len(list)
print(n)
a = []
for i in range(2,n,2):
if list[i] % 2 == 0:
a.append(list[i])
print(a)
|
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import pandas as pd
import datetime as dt
import matplotlib.pyplot as plt
import numpy as np
key = pd.read_csv('key1_plot.csv')
key['x'] = key['x'].map(lambda x: dt.datetime.strptime(x,'%Y-%m-%d %H:%M:%S'))
x,y = key.x,key.scores
plt.plot(x,y,label='Example')
plt.legend(l... |
from helmnet import IterativeSolver
from helmnet.support_functions import fig_generic
import numpy as np
import torch
solver = IterativeSolver.load_from_checkpoint(
"checkpoints/trained_weights.ckpt", strict=False
)
solver.freeze() # To evaluate the model without changing it
solver.to("cuda:0")
# Setup problem
s... |
from bokeh.plotting import figure
from bokeh.io import export_png
import numpy as np
from scipy.stats import norm
x=np.linspace(-40,100,100)
y=norm(30,15).pdf(x)
f=figure(title='Prior distribution on temperature',toolbar_location=None)
f.line(x,y,line_width=3)
export_png(f,filename='../img/prior.png')
|
import itertools
import random
from game import compare_guess, n_pins
class Player:
def __init__(self):
pass
def guess(self):
pass
def update_possible(self, guess, outcome):
pass
class BruteForcePlayer:
def __init__(self):
self.possible_guess = list(itertools.produ... |
from django.shortcuts import render
from django.views.generic import ListView, DetailView, TemplateView
from django.views.generic.dates import ArchiveIndexView, YearArchiveView, MonthArchiveView
from django.views.generic.dates import DayArchiveView, TodayArchiveView
from blog.models import Post
from tagging.models imp... |
import pickle
def dothis(message):
"""
Function to translate text
:param message:
:return: translated text
"""
def replace(lst1, lst2, text, a=True):
"""
function to replace symbols
:param lst1: keys
:param lst2: values
:param text: sentence
:pa... |
import numpy as np
import pdb
import torch
import torch.utils.data
import os
import glob
import scipy.io
from PIL import Image
from urllib.request import urlretrieve
np.random.seed(3435)
class Omniglot(torch.utils.data.Dataset):
"""
Omniglot dataset. Code and data from IWAE
https://github.com/yburda/iwae.... |
import random
N = random.randint(2,100)
print N
a_list = [random.randint(0,pow(2,31)-1) for i in range(N)]
a_list = sorted(a_list)
print a_list |
from random import randint, choice
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.views import login
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.views import View
from twisted.python import failure... |
# -*- coding: utf-8 -*-
#__author__ = Garfield
# Form implementation generated from reading ui file 'mainwindow.ui'
#
# Created: Wed Jun 10 18:01:20 2015
# by: pyside-uic 0.2.15 running on PySide 1.2.2
#
# WARNING! All changes made in this file will be lost!
import sys
import threading
import time
from database ... |
from rest_framework.pagination import PageNumberPagination
class MyPageNumberPagination(PageNumberPagination):
page_size = 10
page_query_param = 'page'
page_size_query_param = 'page_size'
max_page_size = 20
class MenuPagination(PageNumberPagination):
page_size = 100
page_query_param = 'page'... |
from django import forms
from django_ace import AceWidget
class AdminHelpAdminForm(forms.ModelForm):
help = forms.CharField(widget=AceWidget(mode='markdown', width='80%', height='500px;', showprintmargin=False), required=False) |
from django.conf import settings
from django.db import models
from django.utils import timezone
class Quote(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, db_index=True)
quote = models.TextField('quote')
date_added = models.DateTimeField('date_added', default=timezone.now)
class Me... |
import subprocess
import os
import math
def test_d54():
ls_command = 'ls -p /demo-tests/d54'
test_command = 'cd /demo-tests/d54 && bash import-dataset.sh ${PWD}/dataset ${PWD}/worker ${PWD}/invmat.yml'
output_path = '/demo-tests/d54/{}commfile1.txt/OUTPUTS/output.out'
folders_before = subprocess.check_... |
import boto3
import pprint
s3 = boto3.client("s3")
# creates 3 bucket with default set up
response = s3.create_bucket(Bucket="binary-guy-frompython-1")
print(pprint.pprint(response))
# following parameters can be passed while creating bucket
response = s3.create_bucket(
ACL="private",
Bucket="binary-guy-from... |
"""
An implementation of the basic model described in Chan, Nicholas Tung, and Christian Shelton.
"An electronic market-maker." (2001).
"""
import numpy as np
import pandas as pd
"""
Simulation events
"""
EVENT_PRICE_CHANGE_UP = 0
EVENT_PRICE_CHANGE_DOWN = 1
EVENT_UNINFORMED_BUY = 2
EVENT_UNINFORMED_SELL = 3
EVENT_IN... |
from django.contrib import admin
from models import Provider
class ProviderAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("name",)}
admin.site.register(Provider, ProviderAdmin)
|
#coding=utf-8
def func():
raise Exception('this is an error')
print 'go on'
try:
func()
except Exception:
print 'hello'
class MyError(Exception):
pass
#自定义异常,就可以抛出Myerror了
def fuc2():
raise MyError('error2')
fuc2() |
import re, os, sys, subprocess
from ruamel.yaml import safe_load
from buildstream.utils import url_directory_name
# functions that load buildstream files
def load_project_conf(commit):
projects = {}
for prefix in get_projects(commit):
#print(prefix)
projectconf = safe_load(get_file_contents(co... |
import unittest
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
class LogoCheck(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
def test_logo_check_img(self):
driver = self.driver
driver.get("http://localhost:8069/")
... |
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import UserProfile, Post, Comment, PostRating
# make emails unique
User._meta.get_field('email')._unique = True
# registration form
class UserRegisterForm(UserCreationForm):
em... |
__author__ = 'mwagner'
from sqlalchemy import Column, String, Float, Date, ForeignKey, Integer, Table
from sqlalchemy.orm import relationship
from geoalchemy2 import Geometry
from ClLanduseType import *
class CaUnionParcel(Base):
__tablename__ = 'ca_union_parcel'
parcel_id = Column(String, primary_key=True... |
from django.db import models
from .base import GeneralTest
class PictureDescriptionPair(models.Model):
picture = models.ImageField(upload_to='picture_description_pair')
description = models.CharField(
max_length=100, verbose_name='Image Description')
test = models.ForeignKey(
'Test2', on_d... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import re
from sklearn.preprocessing import LabelEncoder, MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
def simplify_to_first_letter(df: pd.DataFrame, featu... |
from fuzzywuzzy import fuzz,process
q1_not = "What do you do with row"
q2_not = "What do you do with row"
q1_d = "How can I be a good geologist?"
q2_d = "What should I do to be a great geologist?"
q1_list = q1_not.split()
q2_list = q2_not.split()
i = 0
len_ = min(len(q1_list),len(q2_list))
while i< len_:
if ... |
#File: Random52CardPickup.py
# If you were to randomly find a playing card on the floor every day,
# how many days would it take to find a full deck?
# Based on the reddit question here
# https://www.reddit.com/r/askscience/comments/6y93j8/if_you_were_to_randomly_find_a_playing_card_on/?utm_content=title&utm_medium=ho... |
import copy
import time
import pickle
import logging
from collections import deque
from heapq import heapify, heappush, heappop
from tqdm import tqdm
import numpy as np
import scipy.sparse as sp
from scipy.sparse import csr_matrix
from sparse_dot_mkl import dot_product_mkl
from assign import greedy_assign
from IPyt... |
# -*- coding: utf-8 -*-
import argparse
import inspect
import math
import os
from pprint import pprint
import sys
from lib.collection_utils import *
from lib.io_utils import *
from lib.math_utils import *
# input
parser = argparse.ArgumentParser()
parser.add_argument('-in', dest="INPUT_FILE", default="tmp/samples.cs... |
import multiprocessing as mp
import sys
import time
from queue import Empty
from typing import TYPE_CHECKING, Optional
from hermes.stillwater.logging import listener, logger
from hermes.stillwater.utils import ExceptionWrapper, Throttle
if TYPE_CHECKING:
from queue import Queue
from hermes.stillwater.utils i... |
import requests
from bs4 import BeautifulSoup
import codecs
import json
import prettytable
# response = requests.get(
# "https://www.cwb.gov.tw/V8/C/W/TemperatureTop/County_TMax_T.html",
# headers = {
# "Accept-Language":"zh-TW,zh;q=0.8,en-US;q=0.5,en;q=0.3",
# "Cookie":"V8_LANG=C; TS01c55bd7=0107dd... |
import RPi.GPIO as GPIO
from time import sleep
import motorcontrol as MC
import encoders as EC
from functools import partial
# setup GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM) #referring to pins by Boardcom SOC channel (i.e. not physical pin numbers)
# setup motors
mL = MC.motor(23,18,14)
mR = MC.motor(4,17,... |
from model.data_analyzer import DataAnalyzer
import math
import numpy as np
from numpy import newaxis
from utils.data_processor import DataLoader
from utils.timer import Timer
from keras.layers import Dense, Dropout, LSTM, GRU,Input
from keras.callbacks import EarlyStopping, ModelCheckpoint,TensorBoard
import keras
imp... |
# Copyright 2019 D-Wave Systems 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... |
#문제3. 다음과 같은 출력이 되도록 이중 for~in 문을 사용한 코드를 작성하세요.
for i in range(10):
print('*'*i)
|
import pexpect
import time
import argparse
import os
import pandas
import math
import constants
MBPS_MULTIPLIER = 0.000008
ZSCORE_PERCENT = 95
def get_command_line_arguments():
parser = argparse.ArgumentParser(description='Probability qos project runner')
parser.add_argument('-n', help='Number of performance... |
import os
import torch
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # sets device for model and PyTorch tensors
num_train = 120098
num_dev = 14326
num_test = 7176
vocab = 'abcdefghijklmnopqrstuvwxyz12345 '
vocab_size = len(vocab)
idx_to_char = {i: vocab[i] for i in range(0, len(vocab))}
ch... |
# This function prints some statements in O(n^3 * log(n)^2).
def complex_function(n):
# Get the range [0,n-1], [0,log(n)-1]
N = xrange(n)
log_N = xrange(log(n,2))
# This loop is O(n * log(n)), but does not represent
# the complexity of the algorithm (the loop below this
# one is O(n^3 * log(n)... |
"""
STACK
- Last In First Out (LIFO) container
- Can Push on (to the top of the stack)
- Can Pop off (from the top of the stack)
- Can Peek (view the top of the stack)
- Backend store can be a Linked List or an Array
- Can be useful for implementing an Undo function on a program/app
"""
from linked_list import Linked... |
from pathlib import Path
import numpy as np
from probeinterface import read_prb, write_prb
from spikeinterface.core import BinaryRecordingExtractor, BaseRecordingSegment, BaseSorting, BaseSortingSegment
from spikeinterface.core.core_tools import write_binary_recording, define_function_from_class
class SHYBRIDRecor... |
import os
import csv
csvpath = os.path.join("resources/" "budget_data.csv")
with open(csvpath) as csvfile:
csv_reader = csv.DictReader(csvfile, delimiter=',')
csv_header = list(csv_reader.fieldnames)
valuecol = (csv_header[1])
monthcol = (csv_header[0])
valueslist = []
monthlist =... |
class udp5632(DatagramProtocol):
def datagramReceived(self, data, (host, port)):
logprint("[HoneyPotTransport.UDP5632,%s:%s] PCANYWHERE PING" % (host, port))
reactor.listenUDP(5632, udp5632(), interface = interface)
|
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import matplotlib.dates as mdates
from sklearn.preprocessing import MinMaxScaler
from datetime import datetime, timedelta
timeframe = '60min'
scaler = MinMaxScaler()
# Load dataset
data_filename = 'data/processed/tweets_prices_'+ timeframe +'.csv'... |
from flask import Flask,render_template
app=Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/projects')
def projects():
return render_template('projects.html')
@app.route('/blog')
def blog():
return render_template('blog.html')
@app.route('/notes')
def note... |
"""
info GAN: https://arxiv.org/abs/1606.03657.
The latent variable of infoGAN is set randomly instead of the supervised way like ACGAN.
"""
import torch
import torch.nn as nn
import torch.optim as optim
from torchlib.common import FloatTensor, LongTensor, enable_cuda, map_location
from torchlib.utils.random import u... |
from flask import Flask, render_template
import queries
import common
app = Flask(__name__)
@app.route("/")
def home_page():
title = "Home page"
return render_template("front_page.html", title=title)
@app.route("/mentors")
def mentors_and_schools_page():
title = "Mentors and schools page"
query = c... |
from scrapy import cmdline
cmd_str = 'scrapy crawl csdn'
# cmd_str = 'scrapy crawl cnblog --nolog'
# cmd_str = 'scrapy crawl topblog --nolog'
# cmd_str = 'scrapy crawl blog_title --nolog'
# cmd_str = 'scrapy crawl cmsblogs --nolog'
cmdline.execute(cmd_str.split(' '))
|
import torch
import torchvision
import torchvision.transforms as transforms
import math
import time
# How many models (==slaves)
K=10
# train K models by Federated learning
# each iteration over a subset of parameters: 1) average 2) pass back average to slaves 3) SGD step
# initialize with pre-trained models (better ... |
import logging
logging.basicConfig(level=logging.DEBUG, format='%(message)s')
log = logging.getLogger()
|
__author__ = 'felix.shaw@tgac.ac.uk - 27/04/15'
from urllib.parse import parse_qs
import requests
from requests_oauthlib import OAuth1
from requests_oauthlib import OAuth1Session
def get_credentials():
client_key = 'id6JBVVeItadGDmjRUDljg'
client_secret = 'BC2tEMeCAT3veHhzfd2xIA'
resource_owner_key = 'B... |
#!/usr/bin python
# -*- coding: utf-8 -*-
#*******************************************************************************
# @Author: Anne Philipp (University of Vienna)
#
# @Date: Sun May 5 2019
#
# @License:
# (C) Copyright 2019.
# Anne Philipp
#
# This work is licensed under the Creative Commons Attribution... |
# This script was created by Mary Sheahen of Eramis Technologies on 5/16/2013
# The script is meant to run periodically and send text alerts when rimfire .22 caliber
# ammunition is in stock on Cabela's website
import urllib.request
import smtplib
# open the ammo variable file for reading a writing, this should be th... |
'''
Implements the Raposo line simplification
algorithm, in which consecutive vertices in hexagonal
grid cells are collapsed to a single
point. For details on the algorithm, see
Raposo (2013) Scale-specific automated line simplification by
vertex clustering on a hexagonal tessellation. CAGIS 40(5):427-443
N... |
# File for applying transformation to the original data
from os.path import join
from math import log
DATA_DIR = 'C:/Users/Patrick/PycharmProjects/who-is-more-influential/Data Analysis'
OUTPUT_DIR = 'C:/Users/Patrick/PycharmProjects/who-is-more-influential/Python'
in_train = open(join(DATA_DIR, 'train.csv'))
out_trai... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('brands-list/', views.list_brands, name='brands-list'),
path('products-list/', views.list_products, name='products-list'),
path('brands-list/brand-products/', views.brand_products, name='brand-p... |
def unpack_select_from_elements(**kwargs):
'''
unpack the string from select clause then return a list of columns
required paramater:
clause_string
return value:
list of columns
'''
return_list = list()
clause_string = kwargs.get('clause_string', None)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.