text stringlengths 8 6.05M |
|---|
"""
Author: Ben Knisley [benknisley@gmail.com]
Date: 26 March, 2021
"""
def process_message(data):
## Convert manchesterSignal into rawSignal by remove first and then every other
## As each bit is sent twice and inverted
dataSignal = data[1::2]
## Split dataSignal into list of 4 chars for each nimble
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import gzip
import datetime
import string
import json
import statistics
import sys
import getopt
import logging
# log_format ui_short '$remote_addr $remote_user $http_x_real_ip [$time_local] "$request" '
# '$status $body_bytes_sent... |
#/usr/bin/ipython
from mpi4py import MPI
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy.linalg as la
from mpl_toolkits.mplot3d import Axes3D
import GreenF
import Impurity
def line(g,x,E, theta):
M = np.array([[np.cos(theta), - np.sin(theta)],
[np.sin... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import dataclasses
import logging
import os
from dataclasses import dataclass
from typing import Any
from pants.backend.helm.dependency_inference.unitt... |
# -*- coding: utf-8 -*-
"""`anarchytools` lives on `Github`_.
.. _github: https://github.com/AnarchyTools/anarchy_sphinx
"""
from setuptools import setup
from anarchy_theme import __version__
setup(
name='anarchy_sphinx',
version=__version__,
url='https://github.com/AnarchyTools/anarchy_sphinx',
lic... |
import bpy
import math
# mesh arrays
verts = []
faces = []
edges = []
#3D supershape parameters
m = 14.23
a = -0.06
b = 2.78
n1 = 0.5
n2 = -.48
n3 = 1.5
scale = 3
Unum = 50
Vnum = 50
Uinc = math.pi / (Unum/2)
Vinc = (math.pi/2)/(Vnum/2)
#fill verts array
theta = -math.pi
for i in range (0, Unum + 1):
ph... |
import json
from dotmap import DotMap
from util import fake_value, load_catalogs
from pymongo import MongoClient
class DataFaker:
STRING = 'string'
OBJECT = 'object'
ARRAY = 'array'
def __init__(self, path_to_file, path_to_schema, path_to_catalogs):
self.path_to_file = path_to_file
se... |
x = 25
epsilon = 0.01
step = epsilon ** 2
numGuess = 0
ans = 0.0
while (abs(ans ** 2 - x)) >= epsilon and ans < x:
ans += step
numGuess += 1
print('numGuess= ' + str(numGuess))
if abs(ans ** 2 - x) >= epsilon:
print('Failed on square root of ' + str(x))
else:
print(str(ans) + ' is close to the square ro... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2018-01-30 13:10
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('progress_analyzer', '0003_exercisestatscumulative_cum_overall_workout_gpa'),
]
oper... |
import datetime
datatime.datetime.now()
datetime.datetime.utcnov()
from datetime import date
now = date.today()
now.strftime("%m-%d-%y, %d %b %Y is a %A on the %d day of %B.")
birthday = date(1964, 7, 31)
age = now - birthday
age.days
|
from evaluate import pivotal, pivotality, criticality, prob_pivotal, unpacked_pivotality
from itertools import product
from simulate import *
from draw import draw, highlight_cause_effect, draw_outcomes, show_predictions
from names import *
import numpy as np
import networkx as nx
import json
'''
open input file an... |
#!/usr/local/bin/python3
import os
def main():
from ctc_server import db
db.create_all()
if __name__ == "__main__":
main()
|
#!/usr/bin/env python3
""" A python version of Vectorize2.R, uses different ways
to run the stochastic Ricker model"""
__appname__ = 'Vectorize2.py'
__author__ = 'Hanyun Zhang (hanyun.zhang18@imperial.ac.uk)'
__version__ = '0.0.1'
# Imports
import numpy as np
# Function
def matrix(numyears, p0):
""" Create an ... |
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
# File: osc4py3/tests/udpbc.py
# <pep8 compliant>
"""This file can be used as a start point for broadcast usage.
For quick test, it doesn't use osc4py3 monitors (nonblocking options set to false),
and directly target low level communication functions.
This should be mod... |
t=int(input())
for i in range(t):
num1,num2=map(int,input().split())
num1=num1%10
lastdig=num1
if num2==0:
print("1")
continue
ld=[]
ld.append(lastdig)
lookup=[]
for i in range(10):
lookup.append(0)
lookup[lastdig]=1
while True:
lastdig=lastdig*num1
lastdig=lastdig%10
if lookup[lastdig]==1:
bre... |
from __future__ import division
from collections import defaultdict
from math import *
from random import sample
import csv
from operator import itemgetter
import matplotlib as mpl
import matplotlib.pyplot as plt
import random
class BaseAlgorithm():
#def __init__(self):
# self.update_data()
def upda... |
# -*- coding:utf8 -*-
import gspread
import httplib2
import numpy as np
from collections import defaultdict
from flask import jsonify
from . import education_bp as education
from .drive import get_file_list, get_credentials_from_file
from apiclient import discovery
from oauth2client.service_account import ServiceAcco... |
# Copyright (C) 2020 THL A29 Limited, a Tencent company.
# All rights reserved.
# Licensed under the BSD 3-Clause License (the "License"); you may
# not use this file except in compliance with the License. You may
# obtain a copy of the License at
# https://opensource.org/licenses/BSD-3-Clause
# Unless required by appl... |
import datetime
# print(dir(datetime))
# print(datetime.MINYEAR)
# print(datetime.MAXYEAR)
# print(datetime.date.today())
# print(datetime.datetime.now())
from importlib._bootstrap import ModuleSpec
from importlib._bootstrap_external import SourceFileLoader
a = datetime.datetime.now()
# print(type(a))
# print(a.now()... |
from validate_command import Validate
class CommandMode:
def __init__(self, tello):
self.tello = tello
def command_mode(self):
validate = Validate()
while True:
print('Please enter a command...')
valid = False
ext = None
command = N... |
import sys
sys.path.insert(0, "./ADNET")
from utils import convert
import numpy as np
from PIL import Image
from torch.autograd import Variable
import torch
import torch.nn as nn
from torch.nn import init
import functools
from torch.optim import lr_scheduler
class UnetBlock(nn.Module):
def __init__(self, outer_nc... |
__all__ = ["mesh", "hexmesh"]
|
# Copyright 2020 Pulser Development Team
#
# 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 i... |
import libtcodpy as libtcod
class Swatch:
colors = {
# http://paletton.com/#uid=73d0u0k5qgb2NnT41jT74c8bJ8X
'PrimaryLightest': libtcod.Color(110, 121, 119),
'PrimaryLighter': libtcod.Color(88, 100, 98),
'Primary': libtcod.Color(68, 82, 79),
'PrimaryDarker': libtcod.Color(... |
from cv2 import *
def incCount(count):
f=open('count.txt','w')
f.write(str(count))
def getCount():
try:
f=open('count.txt','r')
count=int(f.read())
return count+1
except:
f=open('count.txt','w')
f.write('1')
return 1
def imageCaputre():
cam = Video... |
from modules.machine import machine
class processing_cell:
def __init__(self, type, **kwargs):
self.type = type
self.facility = kwargs.get('facility')
if type == 'packaging':
self.num_machines = {
'boxing_machine':kwargs.get('boxing_machines'),
'... |
# 数据处理,删除某些wifi
# 删除连接数小于9并且所有链接强度小于-30的wifi
# 采用了多线程运算,提高效率
import src.utils as u
import threading
strength = 35 #强度阈值
connects = 6 #连接数阈值
def run(mall_ids,i):
print(mall_ids)
for mall_id in mall_ids:
print(mall_id,' starts')
conn = u.get_db_conn()
cur = conn.cursor()
s... |
import jwt
from app import app
def generate_token(payload):
print('generate_token')
token = jwt.encode(
payload,
app.config.get('SECRET_KEY'),
algorithm='HS256'
)
print(f'{token}')
return token |
import numpy as np
def interpolate(points):
time, values = zip(*points)
new_time = np.arange(int(time[0]), int(time[-1]) + 1)
return list(zip(new_time, np.interp(new_time, time, values)))
|
# -*- coding: utf-8 -*- #
"""*********************************************************************************************"""
# FileName [ ASR_THCHS30.py ]
# Synopsis [ automatic speech recognition on the THCHS30 dataset - tensorflow ]
# Author [ Ting-Wei Liu (Andi611) ]
# Copyright [ Copyleft(... |
'''
Created on 20. mar. 2017
@author: tsy
'''
import os
import xml.etree.ElementTree as ET
def charsToDict(filename,name):
'''filename without extension'''
cwd = os.getcwd()
os.chdir(os.path.join(os.path.dirname(__file__), 'The-9th-Age'))
tree = ET.parse(filename+'.cat')
root = tree... |
#coding:utf-8
import os, os.path
from flask import flash, url_for, redirect, render_template, abort,\
request, current_app
from flask.ext.login import login_required, current_user
from . import home
from .home_form import FileUploadForm, AboutMeForm
from ..models import User, Role, Permission, db, Article, Foll... |
"""
author songjie
"""
from app.spider.get_book_data import GetBookData
from sqlalchemy import Column, String, Integer, ForeignKey, Boolean, desc
from sqlalchemy.orm import relationship
from app.models.base import Base
class Wish(Base):
__tablename__ = 'wish'
id = Column(Integer, primary_key=True)
uid =... |
# Copyright (C) 2021 FireEye, Inc. All Rights Reserved.
import speakeasy.winenv.defs.windows.netapi32 as netapi32defs
from .. import api
class NetUtils(api.ApiHandler):
name = 'netutils'
apihook = api.ApiHandler.apihook
impdata = api.ApiHandler.impdata
def __init__(self, emu):
super(NetUt... |
import tweepy
import praw
from flask import Flask, request, redirect
from flask import render_template
from flask_pymongo import PyMongo
import apikeys
app = Flask(__name__)
#Connect to Mongodb using connection string
app.config['MONGO_DBNAME'] = 'dbname'
app.config['MONGO_URI'] = "mongodb+srv://username:password@... |
REDIS_KEY = 'visited_links'
|
# -*- python -*-
from flask import Flask, render_template, redirect, request, session
import random
from datetime import datetime
app = Flask( __name__ )
app.secret_key = "NinjaGoldSecretKey"
@app.route( "/" )
def index():
if "your_gold" not in session:
session["your_gold"] = 0
session["activity... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
# from __future__ import annotations
from textwrap import dedent
from typing import Any, Mapping
import pytest
from pants.backend.docker.target_types import DockerImageSourceField, Dock... |
# Generated by Django 2.1.7 on 2019-02-20 07:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0002_auto_20190219_1320'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='company',
... |
#!/usr/bin/env python
"""
title: Export Downloader -python
description: Downloads exort data from Bazaarvoice export APIs in bulk
"""
import argparse
import os
import time
import hmac
import hashlib
import requests
import json
# Create hmac signature
def createSignature(passkey, secretKey, timestamp, path):
# If '... |
# Fibonacci series: 斐波纳契数列
# 两个元素的总和确定了下一个数
#斐波纳契数列
a, b = 0, 1
while b < 10:
print(b)
a, b = b, a+b
print("*****************")
a, b = 0, 1
while b < 10:
print(b, end=',')
a, b = b, a+b |
# Write a Python program to print each character of a string on single line.
my_string = input("Type a string: ")
for c in my_string:
print(c, end =" ")
|
from PIL import Image
import pytesseract
import cv2
import os
import numpy as np
import sys
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
import webbrowser
from googleapiclient.discovery import build
from slackclient import SlackClient
#google keys
google_api_key = os.... |
# -*-coding:Utf-8 -*
import re
chaine = ""
exp = r"^0[0-9]([ .-]?[0-9]{2}){4}$"
while re.search(exp, chaine) is None:
raw_input("Numero") |
from abc import ABC, abstractmethod
from typing import List, Tuple
import torch
from torch import nn
from torch.distributions import MultivariateNormal, Normal
from torchdiffeq import odeint
class MLP(nn.Module):
def __init__(self, dim_in: int, hidden_sizes: List[int], dim_out: int, activation: str, last_activat... |
#!/usr/bin/env python3
from sys import argv
"""
Version 2: faster than version 1 (it now uses a list to
store all palindromes and count occurrences).
Finds palindromes greater than X characters.
It also prints:
- the size of the longest palindrome
- the size of the shortest palindrome
PEP... |
# Generated by Django 2.2.4 on 2019-08-06 02:21
from django.db import migrations, models
import django.db.models.deletion
import taggit.managers
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Post',
... |
import sys
try:
import psycopg2
HAS_PSYCOPG2 = True
except ImportError:
psycopg2 = None
HAS_PSYCOPG2 = False
if sys.version < '3':
text_type = unicode
binary_type = str
string_types = basestring
else:
text_type = str
binary_type = bytes
string_types = str
|
# Loading the libraries we need
import numpy as np
import cv2
import time
#Creating a VideoCapture object to read video from the primary camera
cap=cv2.VideoCapture(0)
#Creating a VideoWriterObject to save the output video
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('wizard_smaran.avi' ... |
from default_roi_input import DefaultROIInputPopup
from own_roi_input import OwnROIInputPopup
from fs_roi_input import FSROIInputPopup |
"""
# 基于数组实现训练队列
"""
import os
import logging
from itertools import chain
logger = logging.getLogger(__name__)
class CircularQueueByArray(object):
"""基于数组实现循环队列"""
def __init__(self, capacity=5):
self._items = []
self._capacity = capacity + 1 # 预留一个空位留给尾部指针指向
self._head = 0
s... |
from django.shortcuts import render, render_to_response, RequestContext
from django.core.urlresolvers import reverse
import forms
from django.http import HttpResponseRedirect, HttpResponse
# Create your views here.
from django.views.generic import ListView, CreateView, UpdateView, DeleteView
from django.contrib import... |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 4 08:24:09 2019
@author: Reuben
A module of handy utility functions used elsewhere within resultbox.
"""
import numpy as np
from scipy.interpolate import interp1d
def listify(obj):
"""Put an object into a list if it isn't already a list"""
if not isinstance(... |
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from dataclasses import dataclass
from pants.backend.python.goals import lockfile
from pants.backend.python.lint.bandit.skip_field import SkipBanditFie... |
from operator import add as addition_calc
|
# Copyright 2021 DAI Foundation
#
# 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,... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
class Lunch(object):
def __init__(self):
self.cuntomer = Customer()
self.employee = Employee()
def order(self, foodName):
self.cuntomer.placeOrder(foodName, self.employee)
def result(self):
self.cuntomer.printFood()
class Cus... |
# -*- coding: utf-8 -*-
"""
@author: Kamila Kitowska, Katarzyna Pękala
"""
#%%
my_path = ""
#%%
#libraries
import os
os.chdir(my_path)
import importlib
import datetime
import numpy as np
import scenarios as scn
import matplotlib.pyplot as plt
from textwrap import wrap
#importlib.reload(scn)
#sim... |
# Chris Pool
# S2816539
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import Pipeline
from sklearn import svm
from sklearn.metrics import classification_report, confusion_matrix
import sys
from nltk.stem.porter import Por... |
import matplotlib.pyplot as plt
import numpy as np
import scipy.interpolate as sc_ip
# constants
offset = [70]
n_x = 100
n_y = 100
xnew = np.linspace(0, 150, n_x)
# layer_1
x_1_t = np.array([0, 8.1, 14.6, 20, 30, 40.9, 51.1, 60, 66.1, 73.3, 79.5, 86.4, 92.5, 100.9, 107.4, 114.3, 123.1, 130, 135.7, 140.2, 145.5, 150... |
import sqlite3
def createTable():#function to create a new database
connection = sqlite3.connect("login.db")
connection.execute("CREATE TABLE USERS(USERNAME TEXT NOT NULL, PASSWORD TEXT)")
connection.commit()
connection.close()
def friendsList(username):#function to create a friends list for every uni... |
from rest_framework import serializers
from . import models
class UserSerializer(serializers.ModelSerializer):
id = serializers.IntegerField(read_only=True)
name = serializers.CharField(max_length=15, default="DefaultUserName")
status = serializers.IntegerField(default=0)
class Meta:
fields = ... |
import os
import sys
path='/var/www/aceweb'
if path not in sys.path:
sys.path.append(path)
os.environ['DJANGO_SETTINGS_MODULE'] = 'ace_webserver.settings'
activate_this =path+'/env/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))
#import django.core.handlers.wsgi
#application = django.c... |
###########################
# project_euler number 1
# by 김승현
###########################
#1000보다 작은 자연수 중에서 3 또는 5의 배수를 모두 더하면?
total = 0
for i in range(1, 1000):
if i % 3 == 0 or i % 5 == 0:
total = total + i
print(total) |
"""Identify words by a number of criteria. Colour them accordingly for plotting."""
import xmlWordOperators as xmlWO
class xmlLineOperator(object):
def __init__(self, index, line, page_data, search_key_data, continuation):
self.page = page_data.page
self.index = index
self.line = line[0]... |
"""This defines the available applications."""
from django.apps import AppConfig
class ShepherdConfig(AppConfig):
name = 'ghostwriter.shepherd'
def ready(self):
try:
import ghostwriter.shepherd.signals # noqa F401
except ImportError:
pass |
"""Code to fetch the repository and commits"""
import requests
import json
def get_repository_details(user_name):
"""Fetched the repository"""
result = []
user_url = 'https://api.github.com/users/{0}/repos'.format(user_name)
result.append('User: {0}'.format(user_name))
tr... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv('Mall_Customers.csv')
X = dataset.iloc[:,[3,4]].values
'''
import scipy.cluster.hierarchy as sch
dendrogram = sch.dendrogram(sch.linkage(X,method = 'ward'))
plt.title('Dendrogram')
plt.show()
'''
GreaterClusters = 5
from sk... |
from django.db import models
from django.db.models import Q
from django.contrib.auth.models import User
from django.utils import timezone
from profanity.validators import validate_is_profane
from django.shortcuts import redirect, reverse
# Create your models here.
class JobManager(models.Manager):
def search(sel... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# File Name : 'dump_patches.py'
# Author : Steve NGUYEN
# Contact : steve.nguyen.000@gmail.com
# Created : DDDD
# Revised :
# Version :
# Target MCU :
#
# This code is distributed under the GNU Public License
# which can be found at http://www.gnu.org/licenses... |
__author__ = 'sjaku'
import os
import urllib |
from __future__ import print_function
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
def add_layer(inputs, in_size, out_size, activation_function=None):
# outputs = 1
# return outputs\
Weights = tf.Variable(tf.random_normal([in_size,out_size]))
biases = tf.Variable(tf.zeros... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 18 16:13:02 2020
@author: shaun
"""
import numpy as np
import matplotlib.pyplot as plt
from integration import *
N=1000
#creates function x
def function(x):
y=np.e**(-(x**2))
return y
#calculates the integral using n bins and simpsons rule
def f(x):
global N
... |
#! /usr/bin/env python3.3
####################################### Plot 1
from decimal import *
import matplotlib.pyplot as plt
import numpy as np
import os
from pylab import *
from matplotlib.font_manager import FontProperties
fontP = FontProperties()
fontP.set_size('small')
if not os.path.exists('../plots'):
os.ma... |
from django.contrib.auth.models import User
from django.db import models
class PlayerStat(models.Model):
user = models.OneToOneField(User, related_name="stats", on_delete=models.CASCADE)
points = models.IntegerField(default=0)
|
from functools import reduce
def ff_add(*a):
"""
>>> hex(ff_add(0x57,0x83))
'0xd4'
"""
return reduce(lambda x, y: x^y, a, 0)
def xtime(a):
"""
>>> hex(xtime(0x57))
'0xae'
>>> hex(xtime(0xae))
'0x47'
>>> hex(xtime(0x47))
'0x8e'
>>> hex(xtime(0x8e))
'0x7'
"""
... |
# This file is a "Hello, world!" in Python language for wandbox-vscode.
print("Hello, world!")
# Python language references:
# https://www.python.org
|
def solution(A, count=0):
A.sort()
if len(set(A)) != 1:
if A[-1] - 2 >= A[0]:
A[-1] -= 1
A[0] += 1
count += 1
return solution(A, count)
else:
A[0] += 1
count += 1
return solution(A, count)
else:
retur... |
import psycopg2
DB_NAME = "news"
connection = psycopg2.connect(database="news", user="postgres", password="password", host="localhost")
cursor = connection.cursor()
cursor.execute(
"select articles.title, count(*) as views "
"from articles inner join log on log.path "
"like concat('%', articles.slug, '%')... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from datetime import date
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('query', '0009_auto_20150730_1646'),
]
operations = [
migrations.AlterField(
model_name... |
""" Serializer"""
from rest_framework import serializers
from scrapingApp.models import Parliament1
class ParliamentSerializer(serializers.ModelSerializer):
""" table columns """
class Meta:
""" table columns """
model = Parliament1
fields = [
"id",
"date_born... |
t = int(input())
ans = []
for _ in range(t):
a = int(input())
setA = set(list(map(int,input().split())))
b = int(input())
setB = set(list(map(int,input().split())))
ans.append(setA.issubset(setB))
for i in range(t):
print(ans[i]) |
#!/usr/bin/env python3
import os, fnmatch
import math
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import pandas as pd
from ImageMetrics import getNCC, getSSIM
def indexOfMedian(aColumn):
return df[aColumn][df[aColumn] == df[aColumn].median()].index.tolist();
# Get all the... |
import sys
import os
f = open("C:/Users/user/Documents/python/ant_re/import.txt","r")
sys.stdin = f
# -*- coding: utf-8 -*-
# 入力
N = int(input())
S = list(map(int,input().split()))
T = list(map(int,input().split()))
# 仕事をソートするためのpairの配列
itv = [[0,0] for _ in range(N)]
# pairは辞書順で比較される
# 終了時間の早い順にしたい... |
from rest_framework import serializers
from .models import Category, Case, CasePicture
from ..common.serializers import ArticleSerializer
from ..utils import build_absolute_uri
class CasePictureSerializer(serializers.ModelSerializer):
id = serializers.CharField(source='uuid')
image_url = serializers.Serialize... |
import ucam_webauth
import ucam_webauth.rsa
import ucam_webauth.flask_glue
from werkzeug.middleware.proxy_fix import ProxyFix
import os
class WLSRequest(ucam_webauth.Request):
def __str__(self):
query_string = ucam_webauth.Request.__str__(self)
return "https://auth.srcf.net/wls/authenticate?" + qu... |
salarioPorHora = float(input("Quanto você ganha por hora?"))
horasTrabalhadas = int(input("Quantas horas você trabalhou no mês?"))
salarioBruto = salarioPorHora * horasTrabalhadas
descontoImposto = salarioBruto * 0.11
descontoINSS = salarioBruto * 0.08
descontoSindicato = salarioBruto * 0.05
salarioLiquido = sa... |
#!/usr/bin/env python
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
#
# # Authors informations
#
# @author: HUC Stéphane
# @email: <devs@stephane-huc.net>
# @url: http://stephane-huc.net
#
# @license : BSD "Simplified" 2 clauses
#
''' Manage notifications systems '''
#import dbus
import ... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
class Flatten(nn.Module):
def forward(self, x):
N, C, H, W = x.size()
return x.view(N, -1)
class SimpleSliceNet(nn.Module):
def __init__(self):
super(SimpleSliceNet, self).__init__()
... |
#!/usr/bin/env python
from flask import Flask, Response, request
import requests
EVENTS_URI = 'https://www.carnegielibrary.org/events/'
app = Flask(__name__)
@app.route("/events", methods=['GET'])
def events():
params = {
'ical': '1',
}
for k, v in request.args.items():
params['tribe_' +... |
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import *
engine = create_engine("sqlite:///shoeland.db")
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
# session.query(Owner).delete()
# session.query(Category).delete()
# ... |
import os
import sys
import json
import re
import _pickle as pickle
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import TruncatedSVD
from nltk.corpus import stopwords
from nltk import word_tokenize
from nltk.stem import PorterStemmer
from nltk.stem import SnowballStemmer
from m... |
import cx_Oracle # 오라클 DB를 쉽게 활용 가능하게 해주는 driver
connection = cx_Oracle.connect(user="SCOTT", password="TIGER", dsn="xe")
print('1---',connection)
print("Database version:", connection.version) # Database version: 11.2.0.2.0
cur = connection.cursor()
print('2---',cur)
# for row in cur.execute("""select * from dept"""... |
# -*- coding: utf-8 -*-
import csv
with open('pm2.5Taiwan.csv',encoding="utf-8") as input_csv \
,open('cleaned_pm2.5.csv','w', encoding="utf-8") as output_csv:
reader = csv.reader(input_csv) # 讀取 CSV
writer = csv.writer(output_csv) # 寫入 CSV
next(reader)
# 第一行
writer.writerow(['日期','測站','AMB_TEMP', 'CO', 'NO',... |
"""
Django views for the CardControl application. Since our application has a
frontend of static content built in Angular, we do not have any significant
views here. Note that there are some views in the backend for infrastrucuture
related tasks.
"""
from django.conf.urls import url
from . import views
urlpatterns = ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#------------------------------------------------------------------------------
__author__ = 'James T. Dietrich'
__contact__ = 'james.dietrich@uni.edu'
__copyright__ = '(c) James Dietrich 2019'
__license__ = 'MIT'
__date__ = '26 JUNE 2019'
__version__ = '4.0'
__status__ = "... |
import os
import sys
binstart=float(sys.argv[1])
binend=float(sys.argv[2])
numbins = int(sys.argv[3])
width=(binend-binstart)/numbins
for a in range(0,numbins):
edge=binstart+width*a
print edge,", ",
|
from django import template
from django.template.defaulttags import register
register = template.Library()
@register.filter
def index(indexable,i):
return indexable[i] |
from spack import *
from glob import glob
from string import Template
import re
import os
import fnmatch
import sys
import shutil
class Cmssw(Package):
"""CMSSW built with Cmakefile generated by scram2cmake"""
homepage = "http://cms-sw.github.io"
url = "http://cmsrep.cern.ch/cmssw/repos/cms/SOURCES/slc_a... |
import numpy as np
class Plate:
def __init__(self, p1, p2, p3, p4) -> None:
self.p1 = np.array(p1)
self.p2 = np.array(p2)
self.p3 = np.array(p3)
self.p4 = np.array(p4)
@property
def d12(self):
return self.p2 - self.p1
@property
def l12(self):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.