text stringlengths 38 1.54M |
|---|
# Flask framework for backend REST API
import os
import flask
from routes import routes
app = flask.Flask(__name__)
app.register_blueprint(routes)
app.secret_key = b'\xc4i\x92\xcc\x1a\xab\x9a#R\x94\xa6[\xce\xc0\xb0\t\x10$e\x1bi\xaf-\xae'
port = int(os.environ.get('PORT', 8080))
if __name__ == '__main__':
app.ru... |
# %load q06_bowled_players/build.py
# Default Imports
from greyatomlib.python_getting_started.q01_read_data.build import read_data
data = read_data()
# Your Solution
def bowled_out(data=data):
deliveries = data['innings'][1]['2nd innings']['deliveries']
return [delivery_data[delivery]['batsman'] for delivery_d... |
""" wbuilder """
from .wbuilder import WebBuilder
from .wbuilder import Css
from .version import version as __version__
__all__ = ["WebBuilder", "Css"] |
__author__ = 'rizkivmaster'
import unittest
import datetime
import random
from controllers import Record, recordAccessor
def randomId():
return random.randint(0,10000)
class RecordAccessorTest(unittest.TestCase):
def test_add(self):
record = Record(date=datetime.date.today(),accountingId=str(randomI... |
# ClickSmileKaleidoscope.py
# Billy Ridgeway
# Creates a kaleidoscope of smilies reflected across the x axis.
import random # Imports the random library.
import turtle # Imports turtle library.
t = turtle.Pen() # Creates a new turtle pen called t.
t.speed(0) ... |
"""
Mutate NucleotideSequence field of DBASS data to reflect alternate allele.
"""
import sys
import re
import argparse
import fileinput
def main(args):
o = open(args.output, 'w') if args.output != sys.stdout else sys.stdout
i = 1
dbass = sys.stdin if args.input == '-' else open(args.input, 'r')
for row in dbass... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import threading
class mutiThread():
def __init__(self, task_pool, threads=1):
self._task_pool = task_pool
self._threads = int(threads)
self._res = [None] * len(task_pool)
self._lock = threading.Lock()
def _handler(self):
... |
from django.contrib import admin
from .models import Blog, BlogLike
# Register your models here.
class BlogAdmin(admin.ModelAdmin):
fieldsets = [
(None, {
'fields': ["title", "content", "author",
"is_published", "is_public"]
})
]
admin.site.register(Blog, BlogAdmin)
... |
from django.urls import path
from . import views
from django.contrib.auth.views import (
login, logout, password_reset, password_reset_done, password_reset_confirm,
password_reset_complete
)
app_name = 'accounts'
urlpatterns = [
path('', views.index, name='index'),
path('login/', login, {'template_name':'acco... |
'''
RS review from desktop, corrected with () and ""
'''
print ("First line created by RS from github")
print ("Second line updated by sailu from github")
print ("Third line updte by ravi from local system")
print ("Fouth line update by ravi from local system branch Develop")
|
import math
class Environment:
def __init__(self, gravity=9.81, air_density=1.225):
self.gravity = gravity
self.air_density = air_density
def __repr__(self):
return f'<{self.__class__.__name__}: gravity={self.gravity}, air_density={self.air_density}>'
def compute_air_density(tempera... |
# -*- coding: utf-8 -*-
import pandas as pd
reviews = pd.read_csv("ign.csv")
xb=(df['score']>7)&(df['platform']=="Xbox One")
x=xb.value_counts()
print("xbox one score is >7 :",x[1])
ps=(df['platform']=="PlayStation 4")
print(ps)
p=ps.value_counts()
q=(df['platform']=="Xbox One")
q=q.value_counts()
q[1]
p[1]
xbox_one_... |
from datetime import datetime
from google.appengine.ext import db
from chzis.congregation.models import CongregationMember
class Lesson(db.Model):
number = db.IntegerProperty(required=True)
name = db.StringProperty(required=True)
reading = db.BooleanProperty()
demo = db.BooleanProperty()
discours... |
# coding=utf-8
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse
from manageset.models import UserProfile, Sets, Words, Kanji, KnownKanji, KnownWords, UserSets
from django.db.models import Count, Min, Sum, Avg
from django.contrib.auth.models import User
fr... |
from django.conf import settings
from django.db import models
from django.utils import timezone
#this line defines our model
#class is keyword and post is the name of the model
#models.Model means that post is a django model,it will be saved in database
class Post(models.Model):
#now we will define prope... |
import numpy as np
import cv2
import tensorflow as tf
data={
"labels":np.zeros((10,10)),
"images":np.zeros((10,784))
}
font = cv2.FONT_HERSHEY_SIMPLEX
for i in range(10):
img = np.zeros((400, 310), np.uint8)
cv2.putText(img, str(i), (0, 370), font, 16, (255, 255, 255), 12)
img=cv2.resize(img, (28... |
#!/usr/bin/python26
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/lib")
import unittest
from acl import ACL
from unit_class import *
import sys
import random
from config import ConfigService
#diff_path = os.path.dirname(os.path.abspath(__file__))
diff_path = os.path.dirname(os.pa... |
# Generated by Django 2.2.11 on 2020-03-19 06:34
import django.core.validators
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AU... |
import io_utils
import numpy as np
import pandas as pd
import shutil
class DataSets:
root_dir = ".."
data_sets = {
'colon': (
{
"path": "/COLON/COLON/colon.data",
},
{
"path": "/COLON/COLON/colon.labels",
"apply_transf... |
def main(msg):
print(msg)
#Added a comment for pi2
# add a comment for pi3
# a second comment for pi3
main('hello world!!!')
|
import subprocess, os, sys
print os.name
if os.name == 'nt':
print 'so windows'
if os.name == "nt":
#out = subprocess.check_output(["arp", "-a"])
#out = subprocess.check_output("dir", shell=True)
pass
print 'past here'
else:
out = subprocess.check_output(["ls", "-l"])
#print out
#These do no work as WoW64 ca... |
# Generated by Django 2.2.4 on 2020-05-07 10:35
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('user', '0014_auto_20200507_2028'),
]
operations = [
migrations.AlterField(
model_name='emailverifyrecord',
... |
"""
Имя проекта: practicum_1
Номер версии: 1.0
Имя файла: 23.py
Автор: 2020 © Ю.А. Мазкова, Челябинск
Лицензия использования: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru)
Дата создания: 10/12/2020
Дата последней модификации: 10/12/2020
Связанные файлы/пакеты: numpy, random
Описание: Решение за... |
from django import forms
from apps.constructora.models import *
import datetime
def validarFecha(date):
if date.month<=9:
fecha=str(date.year)+"-0"+str(date.month)+"-"+str(date.day)
else:
fecha=str(date.year)+"-"+str(date.month)+"-"+str(date.day)
return fecha
fecha=validarFecha(datetime.datetime.now())
class ... |
#!/usr/bin/env python3
from ldap3 import ALL, Server, Connection, MODIFY_REPLACE, NTLM, MODIFY_DELETE, SASL, KERBEROS
from binascii import unhexlify
from impacket.ldap.ldaptypes import SR_SECURITY_DESCRIPTOR
import argparse
parser = argparse.ArgumentParser(description='Set SD for controlled computer object to a target... |
import numpy as np
import matplotlib as mpl
mpl.use('TkAgg')
import matplotlib.pyplot as plt
from time import sleep
N = 50
x1 = np.random.random((N,2))
x1 = x1
c = x1[:,0]+x1[:,1]>1
x1 = np.hstack([x1,np.reshape(c,(N,1))])
type1 = np.array(list(filter(lambda x: x[2] == 0, x1)))
type2 = np.array(list(filter(lambda x: x... |
''' Imports '''
# optical model components
from .optics import std_opt_params, gen_optics, gen_optics_rev
# image translation
from .image import import_image, gen_image
from .image import gen_img_rays, gen_rev_rays, get_paths, translate_image
# batch image generation protocols
from .batch import init_optics, batch_... |
from tornado.escape import json_encode,json_decode
from tornado.gen import coroutine
from mod.base.base import BaseHandler
from mod.base.exceptions import ArgsError, PermissionDeniedError,OtherError
class GetAddressHandler(BaseHandler):
@coroutine
def post(self):
token = self.get_json_argumen... |
import names
import uuid
import numpy as np
from activity_model import ActivityModel
AMOUNT = 100
class Worker:
def __init__(self, pool, weights = None, surname = None):
self.name = names.get_first_name() + " " + surname if surname != None else names.get_full_name()
self.pool = pool
self... |
def print_n_times(num):
for i in range(num):
print(i)
def print_n_times_rec(num):
if num >= 0:
print(num)
return print_n_times_rec(num-1)
else:
return None
def print_n_times_asc_rec(num, count=0):
if num > count:
num += 1
print(count)... |
from .errors import *
class AlexaRequest:
"""Represents a request sent by Alexa
--- Attributes ---
version - str
the version of the request
session_is_new - bool
True if session was just created
session_id - str
id of the current session
app_id - str
id of the skill
attributes - dict
session attrib... |
# -*- coding: utf-8 -*-
"""
Template para tratar erros de leitura de titulos de paginas web
durante a realizacao de um web scraping
"""
# Importacao das bibliotecas
from bs4 import BeautifulSoup
from urllib.request import urlopen
from urllib.error import HTTPError, URLError
# Funcao para tratar erros de ret... |
import logging
import os
import re
import time
from threading import Event
import psutil
from common.timer import Timer
logger = logging.getLogger('log01')
class BatchCheckBase:
def __init__(self, pattern_id, urls):
self.usr_dict = {}
self.usr_list = []
self.pattern_id = pattern_id
... |
year = int(input("Input year: "))
if year > 0:
day = 365
if year % 4 == 0:
day = 366
if year % 100 ==0:
day = 365
if year % 400 ==0:
day = 366
print("Days number = ", day)
else:
print("Sorry but you input negative year")
|
class GoogleCampaignMiddleware:
"""This middleware captures the various utm* querystring pararmeters and saves them in session."""
UTM_CODES = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content']
def __init__(self, get_response):
self.get_response = get_response
def __call_... |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 10 14:41:51 2019
@author: AARADHYA JAIN
"""
dict1 = {1:[1],2:1,3:[3,4]}
new_list = list(filter(lambda x:(isinstance(x,list)), dict1.values()))
print(len(new_list)) |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import math
data=pd.read_csv('headbrain.csv')
x=data.iloc[:,2].values
y=data.iloc[:,3].values
xMean=np.mean(x)
yMean=np.mean(y)
upper=0
lower=0
for i in range(0,len(x)):
upper=upper+((x[i]-xMean)*(y[i]-yMean))
lower=lower+((x[i]-xMean)**2... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-10-30 04:44
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('patients', '0002_auto_20171029_2353'),
]
operations = [
migrations.AddField... |
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 26 17:54:31 2020
@author: Alex Lee
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp
from scipy.integrate import odeint
from scipy.signal import argrelextrema
G = 6.67430e-11
Msun = 1988500e24 #kg
mearth = 5.9721... |
"""Functions for simulating various SDL2 input events."""
import sdl2
from ctypes import byref
# Helper functions
def _mousebutton_flag(button):
buttons = {
'left': sdl2.SDL_BUTTON_LEFT,
'right': sdl2.SDL_BUTTON_RIGHT,
'middle': sdl2.SDL_BUTTON_MIDDLE
}
if not button in buttons.ke... |
#PB Reaction and purification Protocol 8/9
#last update: October 30, 2020
#Seqwell Workflow
import math
from opentrons import types
metadata = {
'protocolName': 'SeqWell - Pooled Barcoding and Purification',
'author': 'Chaz <chaz@opentrons.com>',
'source': 'Custom Protocol Request',
'apiLevel': '2.3'
... |
#Practica 2 Laboratorio de Ciberseguridad
import requests
import json
output = []
def call(url):
r = requests.get(url)
return (json.loads(r.content))
output.append(call("https://api.openweathermap.org/data/2.5/weather?q=London&units=metric&appid=4c35b48c9218dc4d08cd6eede31f455d"))
output.append(ca... |
import datetime
from flask import render_template, request
from flask_login import current_user, login_required
from sqlalchemy import func
from scrobbler import app, db
from scrobbler.models import Scrobble
from scrobbler.webui.consts import PERIODS
from scrobbler.webui.helpers import range_to_datetime
from scrobble... |
from django.apps import AppConfig
class GithubAuthConfig(AppConfig):
name = "apps.github_auth"
|
from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from django.core import serializers
from app1.models import *
import json
import datetime
from app1.comm.utils import *
def addTeachPlans(request):
try:
if(request.method=='POST'):
resdata=json.loads(request.b... |
import sys
sys.path.append('..')
import numpy as np
import os
from time import time
from collections import Counter
import random
from matplotlib import pyplot as plt
import pickle
from lib.data_utils import shuffle
def mnist():
data_dir = os.path.join(os.environ["DATADIR"], "mnist")
fd = open(os.path.join(... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 27 2020
@author: Palash Sashittal
"""
import pysam
import pandas as pd
import numpy as np
import sys
import argparse
from typing import List, Dict, Tuple, Optional
from collections import Counter
import math
import itertools
#from jumper.segment_g... |
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/name/<string:name>', methods=['GET'])
def name(name):
return render_template('name.html', name=name)
@app.route('/if/<string:name>', methods=['GET'])
def test_if(name):
return render_template('if.html', name=name)
@app.route('/st... |
r3=["A_{lm_3}^{\kk *}u_{l_3}^*(r)","B_{lm_3}^{\kk^*}\dot{u}_{l_3}^*(r)",\
"C_{lm_3}^{\kk^*}R^{lo*}_{lm_3}(r)","D_{lm_3}^{\kk^*}\dot{R}^{lo*}_{lm_3}(r)"]
r4=["A_{lm_4}^{\kkp}u_{l_4}(r)","B_{lm_4}^{\kkp}\dot{u}_{l_4}(r)",\
"C_{lm_4}^{\kkp}R^{lo}_{lm_4}(r)","D_{lm_4}^{\kkp}\dot{R}^{lo}_{lm_4}(r)"]
r5=["A_{lm_5}^{\... |
from twisted.internet import defer
from igs_tx.utils import defer_utils
from igs_tx.utils import defer_pipe
from vappio_tx.utils import queue
@defer_utils.timeIt
@defer.inlineCallbacks
def handleConfig(request):
"""
Returns the config for a single cluster in the system.
Throws an error if the cluster is... |
#! /usr/bin/env python3
# 2017.5.23.
def add_name_dict(namedict,resnumber,resname,restype): # add resname in 'residue name list'
# {resnumber : [resname,[restype1,restype2]]} i.e. {1: [ ALA,[Main,Side] ]}
namedict_key = namedict.keys()
if resnumber not in namedict_key:
namedict[resnumber] = (resname,[r... |
import argparse
import os
import gdal
from basin_data import BASINS_BOUNDARIES, BASIN_EPSG
from pdal_pipeline import PdalPipeline
LAZ_TO_DEM_OUTFILE = '{0}_masked_1m.tif'
DEM_COMPRESSED_OUTFILE = '{0}_masked_1m_c.tif'
SAVE_MESSAGE = 'Saved output to:\n {0}\n'
parser = argparse.ArgumentParser()
parser.add_argument... |
# Copyright (c) 2019 ETH Zurich, Lukas Cavigelli
import math
import itertools
import torch
import torch.nn as nn
import quantlab.indiv as indiv
class INQController(indiv.Controller):
"""Instantiate typically once per network, provide it with a list of INQ
modules to control and a INQ schedule, and insert a ... |
#!/usr/bin/env python
import unittest
from dominion import Game, Card, Piles
import dominion.Card as Card
###############################################################################
class Card_Fortuneteller(Card.Card):
def __init__(self):
Card.Card.__init__(self)
self.cardtype = [Card.CardTyp... |
import json
import plyvel
def make_db():
try:
# 存在しない場合作成,存在する場合エラー
db = plyvel.DB('./db_knock63/', create_if_missing=True, error_if_exists=True)
for line in open('artist.json', 'r'):
artist_dic = json.loads(line)
if {'name', 'tags'}.issubset(set(artist_dic.keys())... |
import unittest
from gp_framework import report as rep
class TestReportModule(unittest.TestCase):
def test_transpose_list_of_lists(self):
input_list = [['a', 'b', 'c', 'd', 'e'], ['f', 'g', 'h', 'i', 'j'], ['k', 'l', 'm', 'n', 'o']]
expected_output = [['a', 'f', 'k'], ['b', 'g', 'l'], ['c', 'h', ... |
import numpy as np
from get_mfc_data import get_mfc_data
from GaussianHMM import GaussianHMM
if __name__ == "__main__":
#datas = get_mfc_data('C:/Users/18341/Desktop/book/听觉/实验3-语音识别/语料/features/')
datas = get_mfc_data('F:/HIT/大三上/视听觉/lab3/组/gzx_sound_mfcc/')
# 每个类别创建一个hmm, 并用kmeans,viterbi初始化hmm
... |
import gym
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from collections import defaultdict
from collections import Counter
ACTION_HIT = 1
ACTION_STAND = 0
NUM_EPISODES = 500000
def main():
plt.style.use('ggplot')
env = gym.make('Blackjack-v0')
value_table =... |
#!/usr/bin/env python3
# Author: Carlijn Assen
import pickle
import sys
import numpy as np
def tfidf(w1, w2):
docs = pickle.load(open('docs.pickle', 'rb'))
all_tweets = 0
tf_idf_scores = {}
for item in docs:
all_tweets += 1
words = docs[item][2].split()
tweet_len = ... |
from collections.abc import Callable
from typing import Any
__version__: str
def dumps(__obj: Any, default: Callable[[Any], Any] | None = ..., option: int | None = ...) -> bytes: ...
def loads(__obj: bytes | str) -> Any: ...
class JSONDecodeError(ValueError): ...
class JSONEncodeError(TypeError): ...
OPT_APPEND_NEW... |
def unique_in_order(iterable):
iterable_list = list(iterable)
unique_list = []
if len(iterable_list) == 0:
return []
else:
unique_list.append(iterable_list[0])
for i in range(0, len(iterable_list)):
if i != 0 and iterable_list[i] != unique_list[-1]:
unique_list.ap... |
class User:
"""
Attribute is a variable associated with the object of class.
@attributes:
self.name
self.age
self.work
methods are functions defined in the class
Constructor is a method which is also called as initializing an object.
The way we create a constructor is us... |
balance = 4213
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
totalPaid = 0
for num in range(1, 13): # For 12 months
monthlyPayment = round((balance) * (monthlyPaymentRate),2)
newbalance = round((balance) - monthlyPayment,2)
balanceAndinterest = round(((newbalance) + ((annualInterestRate * (newbalan... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 5 10:07:32 2020
@author: dean
"""
import xarray as xr
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
ds = xr.open_dataset('ci_sim_data_m=40.nc')
#params = ds['params'].attrs
cis = ds['cis']
r2ers = cis.coords['r2er'... |
n, m = map(int,input().split())
p = []
s = []
for _ in range(m):
temp = input().split()
p.append(int(temp[0]))
s.append(temp[1])
ac = 0
# penaは配列にして各問題について数える
# acを出さなかった問題についてはペナ数をカウントしないから?
pena = [0]*n
flag = [False]*n
# 普通にこんがらがった
for pe, se in zip(p, s):
if se == "AC":
flag[pe-1] = True... |
#!/usr/bin/env python3
from Crypto.Cipher import AES
from Crypto.Cipher import DES
import hashlib
from Crypto.Cipher import ARC4
from Crypto.Cipher import Blowfish
class Aes():
def __init__(self,fil):
while(True):
self.key=input("ENTER THE KEY : ").strip()
self.file=fil
... |
import gwyutils, gwy, gc
from copy import deepcopy
from os import listdir, mkdir, getcwd
from os.path import isfile, join, isdir
import os, datetime
import re, shutil, imp
import numpy as np
if not '/home/june/.gwyddion/pygwy/custlib' in sys.path:
sys.path.append('/home/june/.gwyddion/pygwy/custlib')
import Fct_gwyfun... |
"""
元组:与列表类似,但是元组的元素不能被修改。
在多线程环境下可以规避线程安全的问题。元组在创建时间和空间占用都优于列表。
"""
def main():
# 定义元组
yz = ('wangfeng', 22, '162cm', '四川省南部县')
print(yz)
# 获取元组中的元素
print(yz[0])
print(yz[1])
# 遍历
for x in yz:
print(x)
# 尝试修改元组的元素
# yz[0] = 'bool' TypeError
# 对引用yz重新赋值后原来的... |
# -*- coding: utf-8 -*-
"""
Faça um Programa que peça a temperatura em graus Celsius,
transforme e mostre em graus Farenheit.
"""
celsius = float(input("Informe a temperatura em Celsius: "))
print(f"{celsius}ºC equivalem a {(celsius * 9/5) + 32}ºF")
|
import re
import sys
from flask import Flask, make_response
app = Flask(__name__)
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True
# the default page that is displayed
# when url is not provided
@app.route('/')
def default():
try:
# opens the index.html file in the current directory
with open('index.htm... |
# -*- coding: utf-8 -*-
# Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
#
# 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
#
# U... |
# -*- coding: utf-8 -*-
"""
"""
import datetime as dt
import time
from pyras.controllers import RAS500, RAS41, kill_ras
from pyras.controllers.hecras import ras_constants as RC
#project = r'temp_examples\Steady Examples\BEAVCREK.prj'
#project = r'temp_examples\Unsteady Examples\NavigationDam\ROCK_TEST.prj'
#projec... |
import itertools
import string
import enchant
import sys
if len(sys.argv) >= 2:
alphabets = list(string.uppercase for i in range(6))
d = enchant.Dict("en_US")
file1 = open(sys.argv[1], 'r')
file1 = file1.read(6)
file2 = open(sys.argv[2], 'r')
file2 = file2.read(6)
for a in itertools.produ... |
from django.apps import AppConfig
class ViewsetUrlRouteConfig(AppConfig):
name = 'Viewset_url_route'
|
from synthetic_galaxy import synthetic_galaxy
from error_with_jitter import error_with_jitter
from machine_error import machine_error
from binary_fraction import binary_fraction
def synthetic_fractions(num_of_galaxies, cloud, bf, m_min, mu, sigma, a, b):
"""Makes a list of detection rates from synthetic simulated... |
from image_processing import ImageProcessing
import numpy as np
import os
import utils
img_prc = ImageProcessing()
wally_testdir = './wally_raspCam'
imgs_coords = img_prc.generate_cropped_imgs(wally_testdir , 24,24,48,48)
for key in imgs_coords:
imgs , coord =imgs_coords[key]
np.save(file = os.path.join(wally_... |
def binary_search_1(alist, item):
"""二分查找,递归版本"""
n = len(alist)
if n > 0:
mid = n // 2
if alist[mid] == item:
return True
elif item < alist[mid]:
return binary_search_1(alist[:mid], item)
else:
return binary_search_1(alist[mid + 1:], item)... |
#! /usr/bin/env python
#
def simplex_grid_index_next ( m, n, g ):
#*****************************************************************************80
#
## SIMPLEX_GRID_INDEX_NEXT returns the next simplex grid index.
#
# Discussion:
#
# The vector G has dimension M+1. The first M entries may be regarded
# as grid ... |
from rest_framework import routers
from .views import CardsViewSet
router = routers.SimpleRouter()
router.register('', CardsViewSet)
urlpatterns = router.urls
|
from django.urls import path
from django.views.decorators.csrf import csrf_exempt
from django.views.generic.base import RedirectView
from . import views
app_name = 'campaign'
urlpatterns = [
path('', views.list_bookmarks, name='list_bookmarks'),
path('thing/<name>', views.detail, name='detail'),
path('se... |
from dolfin import *
import time
start = time.time()
# Optimization options for the form compiler
parameters["form_compiler"]["cpp_optimize"] = True
# parameters["form_compiler"]["representation"] = "quadrature" # change quadrature to uflacs if there's problem
# parameters["form_compiler"]["quadrature_degree"] = 2
ff... |
# %%
#import os
#os.environ['CUDA_LAUNCH_BLOCKING'] = '1'
#同期用コード
import pandas as pd
import numpy as np
from pyasn1.type.base import SimpleAsn1Type
from transformers import BertJapaneseTokenizer
import re
# %%
from IPython import get_ipython
import random
import glob
from tqdm import tqdm
import torch
from torch.u... |
"""
checking if I can import mnist
"""
import matplotlib.pyplot as plt
import numpy as np
import os
def load_mnist(data_dir):
X_train_raw = np.fromfile(os.path.join(data_dir, 'mnist-train-images.dat'), dtype=np.uint8, offset=16)
X_train = X_train_raw.reshape(-1, 28*28)
X_test_raw = np.fromfile(os.path.joi... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import io
import pandas as pd
from datetime import datetime
# In[2]:
# Upload the CSV Here
# from google.colab import files
# uploaded = files.upload()
# # Replace the filename here if you have saved the CSV as a different
# df = pd.read_csv(io.BytesIO(uploaded[
#... |
import load_data
import blocks
import features
import numpy as np
import scipy.sparse as sp
from sklearn.preprocessing import normalize
from sklearn.metrics import accuracy_score
from sklearn.cross_validation import train_test_split
from sklearn import cross_validation
import copy
from sklearn.externals.joblib import M... |
class Backtrack:
def backtrack(self, a, k, userData):
if (self.isSolution(a, k, userData)):
self.processSolution(a, k, userData)
else:
k += 1
candidates = self.constructCandidates(a, k, userData)
for candidate in candidates:
a[k] = cand... |
from django import forms
class NewUserForm(forms.Form):
name = forms.CharField(label='name', max_length=100)
email = forms.EmailField(label='email')
|
#task 1
nyaam = float (input('enter a length in cm: '))
if nyaam < 0:
print ('entry is invalid')
else:
res = nyaam / 2.54
print (res, 'inch')
#task 2
whoosh = int (input ('how many credits have you taken? '))
if whoosh > 0 and whoosh < 24:
print ('congrats, you a freshman!')
elif whoosh > 23 and wh... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class LogicalRuleItemDTO(object):
def __init__(self):
self._crowd_name = None
self._ext_crowd_key = None
self._gmt_expired_time = None
self._schedule_type = None
... |
from django.contrib import admin
from blogs.models import Blog
from blogs.models import Post
from blogs.models import Comment
from blogs.models import Subscription
admin.site.register(Blog)
admin.site.register(Post)
admin.site.register(Comment)
admin.site.register(Subscription) |
from django.db import models
from users.models import MainUser
from core.constants import TASK_STATUSES, TASK_TODO, TASK_DONE
class Project(models.Model):
"""
Project model
"""
name = models.CharField(max_length=300)
desc = models.TextField()
creator = models.ForeignKey(MainUser, on_delete=mo... |
#!/usr/bin/env python
from ROOT import *
import CMS_lumi
CMS_lumi.lumi_13TeV = "42 fb^{-1}"
#CMS_lumi.writeExtraText = 1
#CMS_lumi.writeExtraText2 = 1
CMS_lumi.extraText = "Preliminary"
import sys
import math
import array
gROOT.ProcessLine(".L ~/tdrStyle.C");
setTDRStyle()
gStyle.SetOptStat(0)
gROOT.SetBatch(True)
... |
# Inspired by https://ferdinand-muetsch.de/cartpole-with-qlearning-first-experiences-with-openai-gym.html
# & https://medium.com/@tuzzer/cart-pole-balancing-with-q-learning-b54c6068d947&
import gym
import numpy as np
import math
from collections import deque
class QLearningCartPoleSolver():
def __init__(self):
... |
from django.db import models
class Repository(models.Model):
owner = models.CharField(max_length=100)
repo = models.CharField(max_length=100)
date = models.DateTimeField(default=None)
class Meta:
unique_together = (('owner', 'repo'),)
|
from sensor_adapters import Sensor
from sensor_libs.VirtualSensor import *
class VirtualHumiditySensor(Sensor.Sensor):
@classmethod
def get_data(self):
sensor = VirtualSensor()
return sensor.read_humidity()
|
from setuptools import setup
from io import open
import tomlkit
def _get_version():
with open('pyproject.toml') as pyproject:
file_contents = pyproject.read()
return tomlkit.parse(file_contents)['project']['version']
with open('README.md', 'r', encoding='utf-8') as f:
readme = f.read()
setup(... |
#!/usr/bin/env python
import unittest
from chirp.common import timestamp
from chirp.library import constants
from chirp.library import ufid
class UFIDTest(unittest.TestCase):
def test_basic(self):
test_vol = 11
test_ts_human = "20090102-030405"
test_ts = timestamp.parse_human_readable(t... |
def coin_sort(amt:float) -> json:
# Dinominations
dinom = [1,5,10,25,50]
dinom_dict = {50:'half-dollar', 25:'quarter', 10:'dime'
, 5:'nickel', 1:'penny'}
num, rem = divmod(int(amt * 100),100)
result = {'silver-dollar': num}
while dinom:
coin = dinom.pop()
num, rem = divmod(... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 26 10:10:21 2018
@author: Administrator
"""
from datetime import datetime,timedelta,date
import holidays
import pandas as pd
import numpy as np
import json
try:
from itertools import izip as zip
except ImportError: # will be 3.x series
pass
#import date
i_holida... |
from YelpApi import business_search_results
import random
#print(business_search_results())
def just_pick():
random_pick = random.choice(business_search_results())
return random_pick
#print(random_pick) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.