text stringlengths 8 6.05M |
|---|
from urllib.request import Request, urlopen
from urllib.error import HTTPError, URLError
from typing import Optional, List, Tuple
import gzip
import zlib
def decompress_gzip(content: bytes) -> bytes:
"""
Decompress content compressed with gzip.
:param content: content to decompress
:return:
"""
... |
import pandas as pd
def scale_profile(profile, weight):
"""Scale hourly profile using a list of monthly weights.
:param pandas.DataFrame profile: hourly profile.
:param list weight: list of monthly weights.
:return: (*pandas.DataFrame*) -- scaled hourly profile.
:raises TypeError: if profile is n... |
# Copyright (c) 2021 kamyu. All rights reserved.
#
# Google Code Jam 2021 Round 3 - Problem A. Build-A-Pair
# https://codingcompetitions.withgoogle.com/codejam/round/0000000000436142/0000000000813aa8
#
# Time: O((N/(2b) + 1)^b * b^2 * N), b = 10, pass in PyPy2 but Python2
# Space: O(b)
#
from operator import mul
def... |
# coding=utf-8
'''
“闹铃”播放器。可多次调用,前后值相同不会产生影响。
唯一接口:
play(wav_filename)循环播放wav音频(不可为'default')
play('default')播放windows beep声,可以在配置文件beep.conf设置样式(出现win7没有声音的问题,但在播放音乐时有声音,也可能是声卡问题)
play('')不作变化
play(None)停止
此外还可以用win32自带系统声音:
'SystemAsterisk' Asterisk
'SystemExclamation' Exclamation
'SystemExit' Exit Windows
'SystemHan... |
# create deterministic fixed keys according to the specified parameter sizes
raise NotImplementedError("module not complete")
from hashlib import sha512
from epqcrypto.utilities import deterministic_random, bytes_to_integer, modular_inverse
from epqcrypto.asymmetric.trapdoor import Q, INVERSE_SIZE, SHIFT, K_SIZE, A_S... |
import tensorflow as tf
import numpy as np
phi_up = np.load('./Data/Channel/Phase_uplink_init.npy')
diag_Phi_up = tf.linalg.diag(phi_up)
print(diag_Phi_up.shape)
a= np.array([[1,2,3],[1,2,3]])
b= np.array([[1,2],[1,1],[1,0]])
c =a*b
print(c) |
from django.db import models
# Create your models here.
from django.utils import timezone
#Definición del modelo
class Post(models.Model): # Define el objeto para el modelo, proveniente de model q es de Django
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = ... |
from models import db, Post, User, Tag, PostTag
from app import app
from random import randint
db.drop_all()
db.create_all()
users = [
User(first_name='Sara', last_name='Sanders'),
User(first_name='John', last_name='Doe'),
User(first_name='Diane', last_name='Diedrich'),
User(first_name='Robert', last_... |
def palindrome(original):
reverse = original[::-1]
if original == "":
return False
elif original == reverse:
return True
else:
return False |
def quicksort(list):
if len(list) > 1:
l, e, g = partition(list)
return quicksort(l) + e + quicksort(g)
else:
return list
def partition(list):
pivot = list[len(list) - 1]
l = []
e = []
g = []
for i in range(len(list)):
if list[i] > pivot:
g.append(list[i])
elif list[i] < pivot:
l.a... |
import sys,os
sys.path.append(os.getcwd())
from appium import webdriver
import pytest
from Page_Object_Pro.Page.sms import Send_Sms
from Page_Object_Pro.Base.base import Base
class Test_Search:
def setup_class(self):
desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps[... |
haystack = raw_input()
needle = raw_input().strip(" ")
if (len(haystack) == 0 and len(needle)==0) or len(needle)==0:
return 0
h = list(map(str, haystack.split(" ")))
if needle not in h:
return -1
p = 0
for i in range(len(h)):
if h[i] == needle:
p = i
return p
break
if p != 0:
r... |
#!/bin/env python
# encoding:utf-8
'''
#=============================================================================
# FileName: exception.py
# Desc:
# Author: Crow
# Email: lrt_no1@163.com
# HomePage: @_@"
# Version: 0.0.1
# LastChange: 2016-05-24 10:03:32
# History:
#========... |
#! /usr/bin/env python3
#03_schaltjahre.py
jahr = int(input("Geben Sie ein Jahr ein: "))
if (jahr%400 == 0) or (jahr%4 == 0) and not (jahr%100 == 0):
print("Es ist ein Schaltjahr!")
else:
print("Es ist KEIN Schaltjahr!!!")
input("Eingabe mit ENTER beenden.") |
import os
from keras.models import Model, Sequential
from keras.layers import Input, Activation, Flatten, Conv2D, Dense, MaxPooling2D, UpSampling2D, Concatenate, Dropout, AlphaDropout
from keras.layers.normalization import BatchNormalization
from keras.layers.advanced_activations import LeakyReLU
from keras.regularize... |
from sys import argv,exit
import os.path
print("argvLen:", len(argv))
# print(argv[0])
def count(file_path):
"""count the line, word, and char of a given file"""
line_count = word_count = char_count = 0
with open(file_path, mode="r", encoding="utf8") as file:
# file= open(file_path,'r')
print... |
import csv, os
# inport informations about relations between recoders and indices
def get_fdr_indices(recoders):
mydir = '..'+os.sep+'recoder_index'+os.sep
files = os.listdir(mydir)
for filename in files:
reader = csv.reader(file(mydir+filename, 'rb'), delimiter='\t')
recoderType = filename.split('.')[0]
reco... |
from dataclasses import *
@dataclass
class Result:
name: str
math: int
science: int
english: int
def score():
results = [
Result("Alice", 100, 65, 57),
Result("Bob", 45, 98, 100),
Result("Charley", 50, 50, 50)]
return results
def max_point(student):
m_score = 0
... |
import math
import os
import random
import re
import sys
class SinglyLinkedListNode:
def __init__(self, node_data):
self.data = node_data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def insert_node(self, node_data):
... |
"""
CSSE1001 Assignment 3
Semester 1, 2017
"""
import tkinter as tk
from tkinter import messagebox
import random
import winsound
import json
import model
import view
import highscores
from game_regular import RegularGame
# # For alternative game modes
from game_make13 import Make13Game
from game_lucky7 import Lucky7G... |
from django.db import models
# Create your models here.
from healthapp.utils.models import BaseModel
|
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import logging
impor... |
"""
Definition of urls for DjangoWebProject.
"""
from datetime import datetime
from django.conf.urls import patterns, url, include
# Uncomment the next lines to enable the admin:
# from django.conf.urls import include
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
url('', in... |
import sqlite3
import csv
import pandas as pd
####Code to query the local table####
con = sqlite3.connect('MY_SAMPLE_SQLITE.db')
db_df = pd.read_sql_query('SELECT distinct M.MEMBER_ID, \
C.PaidAmt, C.billedamt, C.AllowedAmt, C.PcpProvNbr, C.VendorNumber, \
P.ProviderName, \
V.VendorNum... |
from embedly import Embedly
from api_keys import embedly_key
from classes import Link
from google.appengine.ext import db
import datetime
import re
import feedparser
from bs4 import BeautifulSoup
import uuid
from classes import Email
configuration = {"vote_deflator":2}
def embedly_link(URL):
#Takes a URL, returns ... |
""" Fault class and processing methods. """
import os
import glob
import warnings
import numpy as np
import pandas as pd
from numba import prange, njit
from sklearn.decomposition import PCA
from sklearn.neighbors import NearestNeighbors
from skimage.morphology import skeletonize
from scipy.ndimage import measuremen... |
import time
def time_cost(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print('function {} cost: {}'.format(func.__name__, round(end - start, 2)))
return result
return wrapper
@time_cost
def foo():
time.s... |
from tensorflow.keras.models import Model, load_model, save_model
import tensorflow.compat.v1.keras.backend as K
from tensorflow.keras.layers import Dense, Activation, Input, LeakyReLU, Dropout, GaussianNoise, concatenate
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.regularizers import l2
import n... |
vowels = ('h', 'i', 'i')
print(vowels)
# vowels[3] = 'g'
# print(vowels)
word = ('word')
realWord = ('word',)
realWordTuple = tuple('word')
# print(type(vowels))
print(type(word))
print(type(realWord))
print(type(realWordTuple))
|
# -*- coding: utf-8 -*-
import argparse
import base64
import errno
import logging
import os
import shlex
import socket
from collections import OrderedDict
from contextlib import contextmanager
from gettext import gettext
from streamlink import plugins, Streamlink
from streamlink.compat import (
is_py2,
parse_... |
# Smearing schemes for delta function
# Intended for use with fc_direct.py for calculation of
# free-carrier direct absorption transitions
#
# Methods:
# w0gauss : standard Gaussian smearing
# w1gauss : FD smearing
# sig_nk# : variable smearing for Dirac-delta involvinv e_{nk} - e_{m,k+q}
# TODO: implement band ve... |
# Generated by Django 2.2 on 2019-04-24 22:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('user', '0003_auto_20190424_2246'),
]
operations = [
migrations.RemoveField(
model_name='user',
name='user_name',
... |
#!/usr/bin/env python
# WS server that sends messages at random intervals
import asyncio
import datetime
import random
import websockets
import redis
from dotenv import dotenv_values
config = dotenv_values("../.env")
WEBSOCKET_HOST = config["WEBSOCKET_HOST"]
WEBSOCKET_PORT = config["WEBSOCKET_PORT"]
HOST_REDIS = co... |
import torch
import copy
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import networkFiles as NF
import numpy as np
import logging
# Module ToDo List
# Do we want to add weight decay as a hyperparameter?
# What is a sensible value for the weight_decay
# Add function to generate diff... |
# Copied from OpenAI baselines
# Modified by Kenneth Marino
from abc import ABC, abstractmethod
from baselines import logger
import numpy as np
from gym import spaces
from collections import OrderedDict
from multiprocessing import Process, Pipe
from baselines.common.tile_images import tile_images
import pdb
class Alre... |
# Copyright 2017 The Forseti Security Authors. All rights reserved.
#
# 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 ap... |
from rest_framework import generics
from .models import Author, Book
from .serializers import AuthorSerializer, BookSerializer
class AuthorListAPIView(generics.ListCreateAPIView):
queryset = Author.objects.all()
serializer_class = AuthorSerializer
class AuthorDetailAPIView(generics.RetrieveUpdateDestroyAPI... |
# Generated by Django 2.2.6 on 2019-11-30 10:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('work', '0047_auto_20191130_1013'),
]
operations = [
migrations.AlterField(
model_name='progressqty',
name='status',
... |
from django.conf.urls import url
from .views import CafeCoordinates
from .views import ItemDetail
from .views import CafeName
from .views import CafeList
from .views import CafeDetail
from .views import OrderCreation
from .views import OrdersList
from .views import ChangingOrderStatus
urlpatterns = [
url(r'^cafes/... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class ScraperAuchanItem(scrapy.Item):
id = scrapy.Field()
name = scrapy.Field()
desc = scrapy.Field()
price = scrapy.Field()
pricePer... |
import webapp2
from views.ViewHandler import ViewHandler
from models.AppUserModel import *
import urlparse
import json
"""
Base class for webapp2
Base logged in authentication and common variables created here
"""
class BaseHandler(webapp2.RequestHandler):
def __init__(self, request, response):
# calling... |
#!/usr/bin/env python3
from ev3dev2.motor import MoveSteering, MoveTank, MediumMotor, LargeMotor, OUTPUT_A, OUTPUT_B, OUTPUT_C, OUTPUT_D
from ev3dev2.sensor.lego import TouchSensor, ColorSensor, GyroSensor
from ev3dev2.sensor import INPUT_1, INPUT_2, INPUT_3, INPUT_4
import xml.etree.ElementTree as ET
import threading... |
from rest_framework import viewsets
from .serializers import CoffeeShopSerializer, NewsletterSerializer, BookSerializer
from ..models import CoffeeShop, Newsletter,Book
from rest_framework.response import Response
class CoffeeShopViewSet(viewsets.ModelViewSet):
queryset = CoffeeShop.objects.all()
serializer_cla... |
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gio
from gi.repository.GdkPixbuf import Pixbuf
class tagOverlay(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Tag Overlay")
self.set_border_width(10)
hb = Gtk.HeaderBar(title="Tag Overlay")
... |
import numpy as np
import pytest
from sklearn.base import clone
from sklearn.linear_model import Lasso
from sklearn.ensemble import RandomForestRegressor
import doubleml as dml
from ._utils import draw_smpls
from ._utils_plr_manual import fit_plr_multitreat, boot_plr_multitreat
@pytest.fixture(scope='module',
... |
import requests
import pandas as pd
import environ
env = environ.Env()
environ.Env.read_env() # reading .env file
cert_cert = env('CERT')
cert_key = env('KEY')
online_edu_link = 'https://online.edu.ru/api/'
def get_data():
"""
Collecting platforms to DataFrame
"""
cert_cert = env('CERT')
cert_k... |
def checker(datelist):
longmonths = [1, 3 , 5, 7 , 8 , 10 , 12]
date = True
if len(datelist) != 3:
date = False
else:
month , day , year = datelist
month = int(month)
day = int(day)
year = int(year)
if month > 12 or month < 1 or day < 1 or day > 31 or year... |
def solution(arrangement):
laser = arrangement.replace("()","r");
cutting = []
count = 0
for i in laser:
if i == "r":
count+=len(cutting)
elif i == "(":
cutting.append("(")
elif i == ")":
cutting.pop(... |
import json
import unittest
import responses
import pyyoutube
class ApiCaptionsTest(unittest.TestCase):
BASE_PATH = "testdata/apidata/captions/"
BASE_URL = "https://www.googleapis.com/youtube/v3/captions"
with open(BASE_PATH + "captions_by_video.json", "rb") as f:
CAPTIONS_BY_VIDEO = json.loads... |
#test clear_tokens.py
from dotenv import load_dotenv, find_dotenv
from pathlib import Path
import json
import os
import pymysql
import traceback
import time
import sys
import re
import subprocess
path = os.path.dirname(os.path.abspath(__file__))
sys.path.append(path + "/../../cron")
sys.path.append(path + "/../../")
... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
class ListInstance(object):
"""
使用 __dict__ 列出实例属性
"""
def __str__(self):
return '<Instance of %s, address %s:\n%s>' % (
self.__class__.__name__, id(self), self.__attrnames())
def __attrnames(self):
# result = ''
fo... |
import turtle as t
t.setup(600,600,300,200)
#绘图框的宽、高,绘图框距屏幕左上角的左右、上下间距
t.width(2)
t.color('black')
t.left(45)
for i in range(2):
t.fd(150)
t.left(90)
#圆弧与当前朝向相切
t.circle(150,360/8)
t.left(90)
t.fd(150)
t.right(45)
t.seth(135)
for j in range(2):
t.fd(150)
t.left(90)
t.circle(150,3... |
#!/usr/bin/env python
import argparse
import requests
import sys
twitter_url = 'http://search.twitter.com/search.json?q=from:{username}'
parser = argparse.ArgumentParser(description='Fetch some tweets.')
parser.add_argument('--username', '-u', dest='username',
help='Twitter username to fetch', required=False)
d... |
from django.core.management.base import BaseCommand
from review.models import Comment, Review
from titles.models import Category, Genre, Title
from users.models import CustomUser
from utils.csv_to_db import fill_db
class Command(BaseCommand):
help = 'Fill db'
def handle(self, *args, **options):
mode... |
# Generated by Django 3.0.6 on 2020-05-22 13:51
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Find',
fields=[
('id', models.AutoField(aut... |
from django.urls import reverse_lazy
from django.views.generic import FormView
from django.contrib.auth import login as auth_login
from member.forms import SignupModelForm
__all__ = [
'SignupView',
]
class SignupView(FormView):
template_name = 'member/signup.html'
form_class = SignupModelForm
success... |
#!/usr/bin/python
#Prepocess labels, non-text and text features
import FeatureActualExtraction
import constants
from PreprocessingFunctions import label_transform, label_inv_transform, nonTextFeature_transform, nonTextFeature_nvalues, checkLabelsNFeatures
from sklearn.preprocessing import OneHotEncoder
#Features (n... |
#Create a form using input and raw_input
#name
#last name
#year of birth
#Favorite singer band
#favorite movie
#best fiend
#calculate current age
#print everything in a string concatenating variables
#print the name 10 times
name = raw_input('What is your name?')
lastname = raw_input('What is last your name?')
yearofb... |
# -*- coding: utf-8 -*-
import os
import time
import socket
import subprocess
from wifi import Cell
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from django.conf import settings
from .models import Info, Robot
from .robot_server import Server, find_local_ip, check_url,... |
import json
from pprint import pprint
from django.db.models.aggregates import Count
from django.shortcuts import get_object_or_404
from rest_framework import generics
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny, IsAdminUser, IsAuthenticated
from re... |
import nltk
from nltk.tokenize import word_tokenize
from nltk.tokenize import sent_tokenize
import spacy
import json
import os
import spacy
import json
import numpy as np
from functools import reduce
from sklearn import decomposition
from sklearn.decomposition import PCA
import pandas as pd
import matplotlib.pyplot as... |
from abc import ABC, abstractmethod
class AbstractFactory(metaclass=ABC):
@abstractmethod
def create_product_a(self): pass
@abstractmethod
def create_product_b(self): pass
class ConcreteFactoryOne(AbstractFactory):
def create_product_a(self):
return ConcreteProductA()
def create_... |
#!/usr/bin/env python
# encoding: utf-8
"""
Created by 'bens3' on 2013-06-21.
Copyright (c) 2013 'bens3'. All rights reserved.
python test_csv.py MongoTestTask --local-scheduler
"""
import sys
import os
import luigi
from ke2mongo.tasks.csv import CSVTask
from ke2mongo.tests.tasks.mongo_test import MongoTestTask
cl... |
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from tkinter import messagebox
import pandas as pd # Para la manipulación de datos y análisis
import numpy as np # Para crear vectores de datos, matrices de n dimensiones
import matplotlib.pyplot as plt # Para ge... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the jumpingOnClouds function below.
def jumpingOnClouds(c):
#we have the first and last element are always 0
#last three elements possibilities: (110 can't be), 010, 000, 100
#once, we reach third to last, we need one count... |
"""
COG INVASION ONLINE
Copyright (c) CIO Team. All rights reserved.
@file ScreenshotHandler.py
@author Maverick Liberty
@date April 19, 2016
@desc System used to combat problems that occur when taking
screenshots in the same thread as everything else is running in.
"""
from datetime import datetime
from pand... |
#!/usr/bin/env python
"""
decrypts stored passwords used by Psi messenger
(psi-im.org)
the idea is from
https://www.georglutz.de/blog/2005/07/01/recover-lost-jabber-passwords-in-psis-config-files/
Copyright © 2019 Jose Riha <jose1711 gmail com>
This work is free. You can redistribute it and/or modify it under the
ter... |
ck = ""
cs = ""
ak = ""
ast = ""
recent_id = 0
recent_date = ""
recent_date1 = "" |
class Event:
def __init__(self, time, delay, name):
self.time = time
self.when = time + delay
self.delay = delay
self.name = name
|
from email.mime.text import MIMEText
class Mail():
def __init__(self, to, fromAddr, subject, message, cc=None, bcc=None):
self.to = to
self.fromAddr = fromAddr
self.message = message
self.subject = subject
self.cc = cc
self.bcc = bcc
@property
def email(sel... |
class Solution:
def dfs(self, curr, M, mark):
if mark[curr]==True:
return
mark[curr] = True
#find all friends
for i in range(len(M)):
if M[curr][i]==1 and mark[i]==False:
self.dfs(i, M, mark)
def findCircleNum(self, M:... |
#using SBS(Summation-Based Selection)
from representative_score import rep_score_sentence
import config
import os
import nltk.data
import time
from decimal import Decimal
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
'-f',
'--factor',
default = 1,
help = 'factor of threshold for summary'... |
from torch_lib.Dataset import *
from torch_lib.Model import Model, OrientationLoss
import torch
import torch.nn as nn
from torch.autograd import Variable
from torchvision.models import vgg
from torch.utils import data
import os
# 训练的时候,不需要相机校正参数,但是DetectedObject类在测试集上也用到了
# 而测试集中需要用要相机参数,所以为了代码的兼容性,所以,训练集会加载
# 一个glo... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import os.path
import subprocess
from textwrap import dedent
import pytest
from pants.backend.go import target_type_rules
from pants.backend.go.goals ... |
import tkinter as tk
import data
data.saveFilesToList()
# creating the root or 'master/parent' window
root = tk.Tk()
app_name = root.title("TakeNote")
# width
window_width = 600
# height
window_height = 400
# windows x position
window_x_pos = int((root.winfo_screenwidth() / 2) - (window_width / 2))
# windows y po... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 25 00:16:07 2020
@author: shaun
"""
import numpy as np
from gaussxw import gaussxw
import matplotlib.pyplot as plt
import plotly.express as px
import plotly.graph_objects as go
#grab key points and weights from legendre polymials
N=10
x,w=gaussxw(N)
#define the integra... |
#!/usr/bin/env python
"""
Proxy class for XML-PRC
"""
__author__ = "Mezhenin Artoym <mezhenin@cs.karelia.ru>"
__version__ = "$Revision: 0.1 $"
__date__ = "$Date: 2010/01/10 $"
__copyright__ = ""
__license__ = "GPLv2"
import xmlrpclib
import httplib
class ProxyedTransp (xmlrpclib.Transport):
"""
To access an... |
from django.conf.urls import url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('autores/', views.AutorSearchFormListView.as_view(), name = 'autor-list'),
path('a... |
# from tensorflow.examples.tutorials.mnist import input_data
from data_helper import load_data
import numpy as np
def load():
mnist = input_data.read_data_sets('data/', one_hot=False)
return mnist.train.images, mnist.train.labels
# return np.ones([55000, 784]), np.ones([55000, ])
def EM(imgs, tags):
"... |
#!/usr/local/bin/python3.8
print ('pass condition')
# PASS keyword is a non-operational statement. It doesn't do anything but it allows us to define the else statement without writing anything
name = input('Enter your name: ')
if name == 'bill':
print ('Hello bill')
else:
pass ... |
# coding: utf-8
"""Parser for KumaScript used in compatibility data.
KumaScript is a macro system used on MDN:
https://github.com/mozilla/kumascript
KumaScript uses a JS-like syntax. The source is stored as pages on MDN:
https://developer.mozilla.org/en-US/docs/Template:SpecName
KumaScript can query the database,... |
def distance_hamming(mot1,mot2):
distance = 0
L=len(mot1)
L2=len(mot2)
if L == L2:
for i in range(L):
if mot1[i] != mot2[i]:
distance += 1
return distance
else:
print('Attention : Les 2 mots doivent êtres de la même longueur !!')
A = input('Entrez... |
__author__ = 'bartek'
import ios
import myIos
import matplotlib.pyplot as plt
data = []
xpoints = []
ypoints = []
def save(Filename = 'out.csv' ):
global data
myIos.write_data(data, Filename)
return True
def plotData(data):
for value in data:
xpoints.append(value[0])
ypoints.append(v... |
"""
WEB FRAME 配置文件
"""
# frame ip ='0.0.0.0'
frame_ip = '0.0.0.0'
frame_port = 8080
DEBUG = True
|
import soundLayer
soundLayer= soundLayer.SoundLayer()
globalStream=None
def loop():
while soundLayer.should_play():
pass
#This function schedules a sound.
#@path The path to the sound file to play
#@startOffset Time to wait before playing the sound
#@tag A textual tag to attach to the sound
def scheduleSound(path... |
from math import floor
from copy import copy
def max_heapify(nlist, index):
# LEFT = parent * 2 + 1
# RIGHT = parent * 2
# BUT we are using zero index
left = (index+1) * 2 - 1
right = (index+1) * 2
largest = index
if left < len(nlist) and nlist[left] > nlist[largest]:
largest = l... |
# -*- coding:utf-8 -*-
# Author: Jorden Hai
class School(object):
def __init__(self,name,addr):
self.name = name
self.addr = addr
self.students = []
self.grades = []
self.staffs = []
self.courses = []
def create_course(course_kind):
self.courses.append(... |
"""Setup script."""
import re
from os import path
from io import open
from setuptools import setup, find_packages
__encode__ = 'utf8'
DISTNAME = 'pyss3'
DESCRIPTION = ("Python package that implements the SS3 text classifier (with "
"visualizations tools for XAI)")
AUTHOR = 'Sergio Burdisso'
AUTHOR_EMAI... |
#Creating Training Sample
f = open('ts.txt', 'w')
for i in range(1,1001):
s = './datasetnb/drone (' + str(i) + ').jpg-drone' + '\n'
f.write(s)
for i in range(1,1001):
s = './datasetnb/fighterjet (' + str(i) + ').jpg-fighterjet' + '\n'
f.write(s)
for i in range(1,1001):
s = './data... |
from abc import ABC
from colorama import Fore, Style
class AbstractConsole(ABC):
@staticmethod
def color(color: str, text: str) -> str:
return color + text + Style.RESET_ALL
@staticmethod
def alert(text: str) -> str:
return AbstractConsole.color(Fore.RED, text)
@staticmethod
... |
from deck import Deck
from players.human_cli_player import Player
from functools import reduce
import random
from pprint import pprint
from copy import deepcopy
import colorama
from colorama import Fore, Back, Style
class Log:
def __init__(self):
self.__states = []
def log_state(self, state):
... |
import computerapp.views as computerapp
from django.urls import path
app_name = 'computerapp'
urlpatterns = [
path('computer/', computerapp.computer, name='computer'),
]
|
# -*- python -*-
# Assignment: Compare Arrays
# Write a program that compares two lists and prints a message depending on if the inputs are identical or not.
# Your program should be able to accept and compare two lists: list_one and list_two.
# - If both lists are identical print "The lists are the same".
# - If the... |
from datetime import datetime
from decimal import Decimal, ROUND_HALF_DOWN
from functools import reduce
from flask import Blueprint, request
from marshmallow import fields, validate
from sqlalchemy import func, text
import grant.utils.admin as admin
import grant.utils.auth as auth
from grant.ccr.models import CCR, cc... |
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic
from django.utils import timezone
from .models import News, Category
class BlogIndexView(generic.ListView):
model = News
#paginate_... |
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 26 19:24:02 2020
@author: shaun
"""
import numpy as np
def eulerstep(yn,tn,f,h):
yn1=yn+h*f(yn,tn)
return yn1
def nonlinE(yn,tn1,h):
#solve the differential equation you have for
# the equation that satisfies yn+1 equaling some function of x and t
top=yn+h*2.0*... |
import json
intentionFile = 'Intentions_fr.json'
# importation du fichier d'intention Json
def load_intent(rep = ""):
with open(rep + intentionFile) as json_data:
intents = json.load(json_data)
return intents
def intents_list():
intents_list = ""
intents = load_intent()
for i in range(len... |
#Leo Li
#09/27/18
#Description: task for this program is Take two values, base and exponent, from the user. Then create a list that displays the exponents of that base from the 0 power (1) to the [entered exponent] power in ascending order. For example, if the base was 2 and the exponent was 5, the list should show [1,... |
from openerp.osv import fields, osv
import logging
from logging import getLogger
_logger = getLogger(__name__)
class syncjob_chargetype_category_mapping(osv.osv):
_name = 'syncjob.chargetype.category.mapping'
_description = "Chargetype"
_columns = {
'chargetype_name': fields.char('Chargetype Na... |
"""empty message
Revision ID: 91b16dc2fd74
Revises: d03c91f3038d
Create Date: 2021-02-01 17:00:23.721765
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '91b16dc2fd74'
down_revision = 'd03c91f3038d'
branch_labels = None
depends_on = None
def upgrade():
# ### ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.