text stringlengths 8 6.05M |
|---|
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 16 15:41:49 2018
@author: mynumber
功能:实现语音到文本,使用者说出一句话,讲说出的话识别成对应的文字
接口:speech_recognition ,百度语音识别api
实现过程:1、利用speech_recognition进行录音(可以检测录音开始和结束位置),并将录音转化为采样频率为16000,wav的格式
2、利用百度ResApi sdk 对 .wav格式的录音进行识别
接下来的工作:1、持续的输入输出
2、不将录... |
#!/usr/bin/python3
import socket
ip = socket.gethostbyname('www.arshadsiddiqui.in')
print (ip)
|
#!/usr/bin/python
import sys
import getopt
import matplotlib
import numpy as np
matplotlib.use("Agg") # Force matplotlib to not use Xwindows backend.
import matplotlib.pyplot as plt
# default parameters
kmer = 11
file_name = ""
xmax = 2000
file_type = "fasta"
bar_stat = 0
bar_Y_N = "Off"
output_dir = "./"
argv = sy... |
import math
import torch
def delphineat_gauss_activation(z):
'''Gauss activation as defined by SharpNEAT, which is also as in DelphiNEAT.'''
return 2 * math.exp(-1 * (z * 2.5)**2) - 1
def delphineat_sigmoid_activation(z):
'''Sigmoidal activation function as defined in DelphiNEAT'''
return 2.0 * (1.0 ... |
# -*- coding: utf-8 -*-
class Systems:
def listSystems(self,con):
cur = con.cursor()
cur.execute('select id,name,config from systems.systems')
ss = cur.fetchall()
systems = []
for s in ss:
systems.append(self.convertToDict(s))
return systems
def con... |
#!/usr/bin/python3
'''JSON module'''
import json
def load_from_json_file(filename):
'''function that creates an Object from a “JSON file”'''
with open(filename) as f:
data = json.load(f)
return data
|
#!/usr/bin/python3
def is_same_class(obj, a_class):
""" Function that returns True if the object \
is exactly an instance of the specified class
"""
return True if type(obj) == a_class else False
|
from tkinter import filedialog, Tk
import re
from math import log10
def translate(seq):
seqSplit = []
for i in range(int(len(seq) / 3)):
seqSplit.append(seq[3 * i:3 * i + 3])
proseq = ""
for i in seqSplit:
if codon[i] == "Stop":
break
else:
proseq += aa... |
from owlready2 import *
class Network:
""" A class which runs a depth-first-search on the ontology and creates
a graph network from the data.
Parameters
----------
ontology : OWL2 climate mind ontology file
Completes a depth-first search for the ontology and ret... |
import numpy as np
import torch
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
from scipy import signal
import gym
from gym import wrappers
import math
import scipy
import matplotlib.pyplot as plt
from matplotlib import animation
from typing import Optional
color2num = dict(
gray... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 5 10:56:12 2019
@author: Administrator
"""
import numpy as np
import rcos
from scipy import signal
import matplotlib.pyplot as plt
SPS = 32
#PN_CODE = np.array([1,1,1,1,1,0,0,1,1,0,1,0,1])#BARK CODE[1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, ... |
import requests
from urllib import request
from colorama import init,Fore
import json
import time
import os
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
#截取字符串
def GetMiddleStr(content,startStr,endStr):
startIndex = content.index(startStr)
if startIndex>=0:
... |
import json
import argparse
import collections
import datetime
import pathlib
import typing
import yaml
from . import serialize, discover, DateContext
ArtifactLocation = collections.namedtuple(
"ArtifactLocation",
[
"artifact_key",
"artifact",
"publication_key",
"publication"... |
from core.permissions import BasePеrmission
# permissions that will be used in the project |
import os
from flask import Flask, render_template, json , request
from flaskext.mysql import MySQL
from werkzeug import generate_password_hash, check_password_hash
app = Flask(__name__)
mysql =MySQL()
app.config['MYSQL_DATABASE_USER'] = 'ioanirimia'
app.config['MYSQL_DATABASE_PASSWORD'] = ''
app.config['MYSQL_DATA... |
# -*- coding: utf-8 -*-
class Solution:
def containsDuplicate(self, nums):
seen = set()
for num in nums:
if num in seen:
return True
seen.add(num)
return False
if __name__ == "__main__":
solution = Solution()
assert solution.containsDuplic... |
import requests
from proxypool.setting import TEST_URL
PROXY_POOL_URL = 'http://localhost:5555/random'
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36"}
def get_proxy():
try:
response = requests.get(PROXY_POOL_U... |
import unittest, os
import numpy as np
from molecules import Cluster, Property, Water, Rotator
from use_generator import Generator
from template import Template
FILE = os.path.join( os.path.dirname(__file__), 'tip3p44_10qm.mol' )
class WaterTest( unittest.TestCase ):
def setUp(self):
self.c = Cluster.ge... |
a = input().split()
a.sort()
m = ''
equals = False
result = ''
for i in range(len(a)):
if i == 0:
m = a[i]
elif a[i] == m:
if i != len(a) - 1:
equals = True
else:
result += a[i]
else:
if equals:
result += m + " "
m = a[i]
e... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
import numpy as np
from scipy.special import logsumexp
from optimization.loss import binary_loss_function
## Code adopted from
# https://github.com/riannevdberg/sylvester-flows/blob/master/utils/log_likelihood.py
#calculates the true marginal likelihood by IS
def calculate_likelihood(X, model, args, S=5000, MB=500)... |
#!/usr/bin/python
#contains most of the code for the graph drawing panel
#some display information (whether a vertex is selected, etc.) is contained
#in graph.py
#UI main loop and parent window are started in main.py
import sys
import wx
import math
from cascades import *
from math import sqrt
def control_point(edg... |
#!/usr/bin/env python3
"""
Random seating planner - 2020, Nien Huei Chang
dskrnd.py - main program
"""
import json
import curses
import random
DESK_POOL = 50
DATABASE_FILE_NAME = "dskrnd.json"
database = []
screen = curses.initscr()
def read_database_file():
""" Read database from local json file """
... |
import os
import sys
from django.utils.crypto import get_random_string
def get_settings_file_name():
return get_project_file_name('settings.py')
def get_project_file_name(file_name):
return os.path.join(project_name, file_name)
def generate_secret_key():
chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@... |
# -*- coding=utf-8 -*-
'''
Created on 2016年3月7日
@author: YANG
'''
import os
import xlrd
import matplotlib.pyplot as plt
"145800_ViVo_City"
if __name__=="__main__":
path = "C:\\Users\YANG\Desktop\Data" #os.path.dirname("statistic.py")
book = xlrd.open_workbook("%s\\4.xls"%path)
sheet ... |
"""
Python object notation to JSON.
"""
import json
from pathlib import Path
import click
from . import cli
def do_pyon2json(ifname, ofname, pretty=True):
"""
Convert the python object notation file to json object notation file.
"""
with open(ifname, "r") as fin:
x = fin.read()
x = ev... |
from pprint import pprint
from correios import calc_preco_prazo
response = calc_preco_prazo(
cep_origem='70002900',
cep_destino='04547000',
peso='1',
altura='20',
largura='20',
comprimento='20',
servicos=['04510', '04014'],
empresa='08082650',
senha='564321',
)
pprint(response)
|
#!/usr/bin/python
import numpy as np
import math
from roboclaw import *
speed = 16384
print "started"
while True:
print "loop begin"
SetM1Speed(128,speed)
SetM2Speed(129,speed)
SetM2Speed(128,speed)
time.sleep(1)
# print readM1instspeed(128)
# print readM2instspeed(128)
# print readM... |
#!/usr/bin/env python3
from time import sleep, time
import os
from sys import stdout
mlockall = True
if mlockall:
from ctypes import CDLL
CDLL('libc.so.6').mlockall(3)
psi_path = '/proc/pressure/memory'
psi_support = os.path.exists(psi_path)
def rline1(path):
"""read 1st line from path."""
with op... |
"""
sql_tables.py: all SQL table definitions and bootstrapping goes here
"""
import datetime
from backend_main import DB
class Sys_user_role(DB.Model):
"""
system user role database table definition
Stores roles for sys_user
1 = Order Taker
2 = Order Fulfiller
3 = Administrator
"""
... |
import os
import sys
import subprocess
import shutil
sys.path.insert(0, 'scripts')
sys.path.insert(0, os.path.join("tools", "families"))
import fam
import experiments as exp
def get_tree(ale_file):
for line in open(ale_file):
if (";" in line):
return line
return None
def export_ale_trees(input_trees_dir... |
import json
from datetime import datetime, timezone
import requests
from bson import ObjectId
from flask import render_template, flash, redirect, url_for, request, Response
from flask_login import current_user, login_user, logout_user, login_required
from werkzeug.urls import url_parse
from app import app
from app.fo... |
# -*- coding: utf-8 -*-
"""The app module, containing the app factory function."""
import logging
import traceback
import sentry_sdk
from animal_case import animalify
from flask import Flask, Response, jsonify, request, current_app, g
from flask_cors import CORS
from flask_security import SQLAlchemyUserDatastore
from ... |
import caffe
import numpy as np
import argparse, pprint
class TryLayer(caffe.Layer):
@classmethod
def parse_args(cls, argsStr):
parser = argparse.ArgumentParser(description='Try Layer')
parser.add_argument('--num_classes', default=20, type=int)
parser.add_argument('--aa', default=5, type=int)
args = parser... |
import numpy as np
import pandas as pd
from tensorflow import keras
import csv
from tensorflow.keras import layers
from matplotlib import pyplot as plt
import os
from datetime import datetime
# timestamp,Ttl Volume,Avg Volume,Ttl Through,Ttl Left Turn,Ttl Right Turn,Ttl Wrong Way,Overall Avg Speed, Zone 2, Zone 3, Zon... |
import numpy as np
from sklearn import cross_validation
from sklearn import datasets
from sklearn import svm
# load test data
iris = datasets.load_iris()
# split data in train set and test set
X_train, X_test, y_train, y_test = cross_validation.train_test_split(
iris.data, iris.target, test_size=0.4, ran... |
#!/usr/bin/env python
# coding: utf-8
import sys
import tkinter as tk
from tkinter.filedialog import askopenfilename
sys.path.append(".")
import spam
def handl_quit():
spam.quit()
fenetre.destroy()
def handl_run():
filename = askopenfilename()
spam.run(filen... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Run a test calculation on localhost.
Usage: ./example_01.py
"""
from os import path
import click
from aiida import cmdline, engine
from aiida.plugins import CalculationFactory
from aiida_spirit import helpers
from aiida_spirit.helpers import prepare_test_inputs
INPUT_D... |
'''
Created on Sep 10, 2010
@author: xnaud
'''
import threading
import logging
from model import modelDAO
from model.model import Note, Notebook, Tag
from service import apiService
from config import config
_BATCH_SIZE_=10
_logger=logging.getLogger(__name__)
# Thread status
STATUS_RUNNING=1
STATUS_IDLE=0
... |
import torch
import math
from typing import List, Tuple, Dict
def logsumexp(tensor: torch.Tensor, dim: int = -1, keepdim: bool = False) -> torch.Tensor:
"""
A numerically stable computation of logsumexp. This is mathematically equivalent to
`tensor.exp().sum(dim, keep=keepdim).log()`. This function is typi... |
# CDT8 SVL - M. Nebut - 03/2016
# programmation par contrats avec contract.py
class Compte:
"""
compte non plafonne, avec decouvert autorisable
>>> compte = Compte()
>>> compte.autoriser_decouvert(-100.0)
inv:
implies(self.decouvert_autorise,
self.montant >= self.decouvert... |
import logging
from os import chdir, getcwd, getenv
from os.path import exists as path_exists, join as path_join, basename
from os import remove
from subprocess import run as sp_run, PIPE, DEVNULL
from urllib.request import urlretrieve
from uuid import uuid4
from logging import getLogger
from tempfile import NamedTempo... |
# Title: Konica Minolta FTP Utility - Remote Command Execution
# Date : 20/09/2015
# Author: R-73eN
# Software: Konica Minolta FTP Utility v1.0
# Tested: Windows XP SP3
# Software link: http://download.konicaminolta.hk/bt/driver/mfpu/ftpu/ftpu_10.zip
# Every command is vulnerable to buffer overflow.
import socket
im... |
# 경찰청 분실물 api 활용(mysql과 연동해서 db 저장까지 함)
import urllib.request as ul
import xmltodict
import pymysql.cursors
import sys
from datetime import datetime,timedelta
date=datetime.today() - timedelta(10) #과거 날짜
date_s = str(date)
year = date_s[0:4]
month = date_s[5:7]
day = date_s[8:10]
START_YMD = year+month+day
date=datet... |
#Input
#The first line of input contains a single decimal integer P, (1≤P≤1000), which is the number of data sets that follow. Each data set should be processed identically and independently.
#Each data set consists of a single line of input.
#It contains the data set number, K,
#followed by the base, b (3≤b≤16... |
import boto.ec2
import WH
site_id=40466
if __name__ == '__main__':
wh = WH.WH()
wh.connect()
conn = boto.ec2.connect_to_region("us-west-2")
for a in conn.get_all_addresses():
print "%s" % (a.public_ip)
print wh.add_allowed_host(site_id,"http",a.public_ip).request
print wh.add... |
class StepSql:
def add(self, step):
query= "insert into tb_e2e_trace_steps \
(step_seq, trace_seq, step_title, mainclass, subclass, request_cmd, request_param, request_time) \
values (%d, %s, '%s', '%s', '%s', '%s', '%s', now())" % (step.seq, step.traceseq, ste... |
# 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... |
import cv2
import numpy as np
from matplotlib import pyplot as plt
import time
###########################
image = cv2.imread('a3.jpg',1)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (15, 15), 0)
thresh = ~(cv2.threshold(blurred, 200, 255, cv2.THRESH_BINARY)[1])
#cv2.imshow("test",th... |
"""
nodes @ utils
"""
import maya.cmds as mc
def remapNode(
ctrlAt,
targetAt,
ctrlMinMax,
targetMinMax,
addVal = False
):
remapNode = mc.createNode('remapValue', n = 're' + ctrlAt)
addNode = mc.createNode('plusMinusAverage') # to get any preexi... |
import math as _math
def ducks_in_earth(duck_volume, R_EARTH=6378e3):
"""Compute the number of ducks that fit in the earth
Args:
duck_volume (float): Volume of one rubber duck [m^3]
R_EARTH (float): Earth's equatorial radius [m] Default: 6,378,000.0
Returns:
num_ducks (int): Numbe... |
#calculator program
def add(a,b):
print(a+b)
def sub(a,b):
print(a-b)
def multi(a,b):
print(a*b)
def div(a,b):
z=int(input("to get value in float select 1 else 2"))
if(z==1):
print(a/b)
elif(z==2):
print(a//b)
else:
print("invalid")
def mod(a,b):
print(a%b)
... |
"""runner functions for entry points."""
import os
import sys
import argparse
import cmd
import getpass
import pprint
import hashlib
from twisted.internet import reactor, task
from twisted.internet.endpoints import TCP4ServerEndpoint
from twisted.internet.defer import inlineCallbacks
from twisted.python import log
fr... |
from datetime import datetime
from flight_delay_prediction.constant import CATEGORICAL_INPUTS, CONTINUOUS_INPUTS, AIRPORTS, INPUT_NAMES, TEMPERATURES, \
PRECIPITATION, VISIBILITY, WINDSPEED
from flight_delay_prediction.errors import *
from flight_delay_prediction.resources_loader import Resources
from flight_delay... |
import numpy as np
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense, Activation, Dropout, Flatten
from keras.layers.normalization import BatchNormalization
from keras.layers import Conv2D, MaxPooling2D
from keras.utils import np_utils
from keras impor... |
#!/usr/bin/python
"""Ball used in pong"""
import pygame
from event import Event
import math
import random
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BALL_BORDER = 1 # Width of the border around the ball
MAX_HORIZONTAL_VELOCITY = 6
MAX_VERTICAL_VELOCITY = 4
class Ball(pygame.sprite.DirtySprite):
"""Ball... |
# coding: utf-8
"""
Copyright 2016 SmartBear Software
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 applica... |
import pandas
def install_cost_solar(area: float) -> int:
"""
Calculates the average cost of installing solar panels over a given area
Info:
1 Panel is 17.55 square feet, 1.63 m^2
6 kW system requires 20 panels, 32.6 m^2
$2.78 per Watt
$512 per m^2
:param area: Area to ... |
import pyautogui as pag
import time
import csv
def enter_meeting():
pag.click(282, 459) # at khub
time.sleep(4)
pag.hotkey("ctrl", "e")
time.sleep(0.5)
pag.hotkey("ctrl", "d")
time.sleep(1)
pag.click(992, 427) # join at meet
time.sleep(2)
def start_record():
pag.clic... |
class Solution:
# @param X : list of integers
# @param Y : list of integers
# Points are represented by (X[i], Y[i])
# @return an integer
def coverPoints(self, X, Y):
steps = 0
row, col = X[0], Y[0]
for i in range(1, len(X)):
steps += max(abs(row - X[i]), abs(col ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# encoding=utf8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import requests
from bs4 import BeautifulSoup, SoupStrainer
import Tkinter
from lxml import html
import openpyxl
from time import sleep
def center(toplevel):
toplevel.update_idletasks()
w = toplev... |
# -*- coding: utf-8 -*-
import sys
sys.path.append(('..'))
import lib.Utils as U
import os
@U.log_flie_function()
def get_case_yaml_path():
ini = U.ConfigIni()
yaml_path = ini.get_ini('test_case','case')
return get_all_case(yaml_path,'.yaml')
def get_all_case(directory,extension_name):
file_dict = {}
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 26 11:41:17 2018
Building a chatbot with NLP
@author: CURIACOSI1
"""
import numpy as np
import tensorflow as tf
import re
import time
############## PART 1 - DATA PREPROCESSING #################
# Importing the datasets
lines = open('movie_lines.txt', enco... |
# -*- coding: utf-8 -*-
__author__ = 'Tan Chao'
'''
Test logger_manager module.
'''
from logger_manager import LoggerManager
logger = LoggerManager.get_logger('test')
logger.info('start...')
logger.debug('hello world')
logger.error('stop error')
try:
print(2/0)
except Exception, e:
logger.log_except() |
from difflib import SequenceMatcher
with open("1.txt") as f1, open("2.txt") as f2:
f1Data = f1.read()
f2Data = f2.read()
similarity = SequenceMaster(None, f1Data, f2Data).ratio()
print(similarity*100)
|
# %% imports
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
plt.ion()
import sys
import time
import pathlib
import numpy as np
import serial
import pandas as pd
from generated import *
_code_git_version="66e6811232d925e0f4a0f5c8f0da62125ed58de6"
_code_repository="https://gith... |
# Definição de uma classe para representar de forma abstrata as tarefas que precisaremos ordenar
class Tarefa:
nome = ""
inicio = 0
fim = 0 |
"""
Examen Parcial 1
Carrillo Medina Alexis Adrian (CMAA)
Nombre del programa: Parcial1.py
NOTA: La finalidad de este archivo es hacer las respectivas pruebas.
Los algoritmos se encuentran en matrices/Matriz.py
Se probo usando linux.
"""
#----- Seccion de bibliotecas
from matrices import Matriz
#-----... |
import os
here = os.path.dirname(os.path.abspath(__file__))
print(here)
filename = os.path.join(here, 'dt_policy_8.txt')
f = open(filename, "r")
s = ""
for line in f:
s+=line.strip()+"\\n"
f.close()
filename = os.path.join(here, 'dt_policy_8_string.txt')
f = open(filename, "w")
f.write(s)
f.close()
|
from alarm import alarm
from config import data
data = data.Data()
def symbol_to_string():
alarm_string = data.alarm
if '%' in alarm_string:
alarm_new = alarm_string.replace('%', ' percentage ')
else:
alarm_new = alarm_string
alarm.write_alarm(alarm_new)
|
#!/usr/bin/env python
##############################################################################
# Copyright (c) Members of the EGEE Collaboration. 2011.
# See http://www.eu-egee.org/partners/ for details on the copyright
# holders.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not u... |
import random
score = 0
arr = ["rock", "paper", "scissors"]
def gameThree():
num = 0
while num !=3:
num = num + 1
game()
def game():
comp = randomPlay()
print(comp)
x = input("rock paper scissors shoot !!!!")
if x == "rock":
if comp == x:
print("tie")
if comp == "paper":
print... |
s2=list(input("s = ").replace(",",'').replace(".",'').replace("'",'').replace('"','').split())
for i in s2:
if len(i)%2==0:
print(i) |
from tkinter import *
from PIL import ImageTk,Image
root = Tk()
root.title('images - tutorial')
# Does not work fore some unclear reason
root.iconbitmap('images/diablo.ico')
img_1 = ImageTk.PhotoImage(Image.open('images/test.png'))
img_2 = ImageTk.PhotoImage(Image.open('images/fireMario_PF.png'))
img_3 = ImageTk.Pho... |
# Generated by Django 2.2 on 2020-10-04 14:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('instagram', '0009_auto_20201004_1708'),
]
operations = [
migrations.AlterField(
model_name='socinstaproxy',
name='loca... |
'''
657. Judge Route Circle
Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place.
The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Rig... |
age = int(input('Please input your age: '))
yearBorn = 2021 - age
print(yearBorn) |
import serial
import numpy as np
import cv2
def send_commends(ser, motors, commands):
for motor in motors:
for direction_cmd in commands:
command_string = bytes(2)
command_string = bytearray(command_string)
command_string[0] = motor # 2 motor 1, 4 motor 2, 8 motor 3
... |
import math
num = int(input('Digite um número: '))
print('---------------------------------')
print('[1] Binário')
print('[2] Octal')
print('[3] Hexadecimal')
conv = int(input('Digite a base de conversão: '))
if conv == 1:
print('O número em binário é: {}'.format(bin(num)[2:]))
elif conv == 2:
print('O núme... |
#program to print the fibonaccci series
n=input('Enter no of digits :-')
first=0
second=1
print first,second,
count=3
while count<=n:
third=first+second
print third,
first=second
second=third
count=count+1
|
# Core python
import logging
import os
import pika
import uuid
import xml.etree.cElementTree as ET
import datetime
from datetime import timedelta
import ast
import json
# sci stack
import pandas as pd
import numpy as np
# Vibe
from rabbit_publisher_consumer import PublisherBot
# SBB
import itinerary
import init_dat... |
print()
print('*************************************************************************')
print(' LANGUAGE CONVERTER ')
print('*************************************************************************')
converter = {'aeo':'Hi',
'eooae': 'How are you... |
import unittest
from katas.kyu_7.russian_postal_codes import zip_validate
class ZipValidateTestCase(unittest.TestCase):
def test_true(self):
self.assertTrue(zip_validate('198328'))
def test_true_2(self):
self.assertTrue(zip_validate('310003'))
def test_true_3(self):
self.assertT... |
"""Create tables from data-objects"""
# Author: Christian Brodbeck <christianbrodbeck@nyu.edu>
from ._table import difference, frequencies, melt, melt_ndvar, stats, repmeas
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2018-01-19 01:46
from __future__ import unicode_literals
from django.db import migrations, models
import helpers.base.jsonfield
class Migration(migrations.Migration):
dependencies = [
('liantang', '0004_auto_20180118_2046'),
]
operations = ... |
from common.utils import get_nested_item
from functools import partial
from itertools import chain
import re
import unicodedata
def parse_bool(b):
return {
'true': True,
'false': False,
'1': True,
'0': False
}.get(str(b).lower(), bool(b))
def normalize(text):
normalized... |
import logging
import array
from twisted.internet import reactor
from twisted.internet.serialport import SerialPort
from twisted.internet.protocol import Protocol
def encode_bytes(a):
return ''.join('{:02x}'.format(x) for x in a)
def decode_bytes(s):
return [int(s[i:i+2], 16) for i in xrange(0,len(s),2)]
... |
# Generated by Django 3.1.7 on 2021-03-15 12:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('home', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='extendexd_user_model',
name='user_profil... |
from django.db import models
from django import forms
from south.db import db
models.Field.db_index = True
import datetime
class Aboutme(models.Model):
name = models.CharField(max_length=200)
slug = models.SlugField(unique=True)
description = models.TextField(blank=True)
image = ... |
"""Base cache support."""
import errno
import os
import pathlib
import shutil
from operator import attrgetter
from typing import NamedTuple
from snakeoil import klass
from snakeoil.cli.exceptions import UserException
from snakeoil.mappings import ImmutableDict
from snakeoil.osutils import pjoin
from . import const
... |
# Generated by Django 2.1.2 on 2018-11-07 01:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('misPerrisDJ', '0009_auto_20181106_2237'),
]
operations = [
migrations.AddField(
model_name='persona',
... |
from django.contrib import admin
from django.urls import path
from drf_yasg import openapi
from drf_yasg.views import get_schema_view
from . import views
schema_view = get_schema_view(
openapi.Info(
title="Predictor",
default_version='v1',
description="Test description",
terms_of_service="... |
import sys
sys.path.append('../../')
import unittest
from mock import IgorMock, ClientMock
from igor.core import Stream, ProcessOutput, handler_wrapper, flatten
import json
import time
import asyncio
class TestDictionaryFlatten(unittest.TestCase):
def test_flatten(self):
dictionary = {
'a': {
'b... |
"""Map file definitions for postfix."""
class RelayDomainsMap(object):
"""Map file to list all relay domains."""
filename = "sql-relaydomains.cf"
mysql = (
"SELECT name FROM admin_domain "
"WHERE name='%s' AND type='relaydomain' AND enabled=1"
)
postgres = (
"SELECT name F... |
from Question import Question
question_prompts = [
"What color are apples? \n(a) Red/Green\n(b) Purple\n(c) Orange\n(d) Yellow\n\n",
"What color are Bananas? \n(a) Yellow/Green\n(b) Violet\n(c) Black\n(d) Brown\n\n",
"What color are Strawberries? \n(a) Blue/Yellow\n(b) Magenta\n(c) Orange\n(d) Red\n\n"
... |
import os
import time
def search(d): #search function
query=input("query: ")
query = query.strip(" ").split() #get rid of the front and rear spaces, space being the delimiter
query = list(set(query))
Found_List=[]
if ("or" in query) and ("and" not in query): #"OR" search
query.remove("or... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from pants.backend.experimental.java.register import rules as java_rules
from pants.backend.openapi.codegen.java.rules import rules as java_codegen_rule... |
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, JsonResponse
from secondapp.models import Hospital
# Create your views here.
def index(request):
hospital_list = Hospital.objects.order_by('id')
print(hospital_list)
return render(
request, 'secondapp/home.... |
import psycopg2
from setup import *
from connection import Connection
from pprint import pprint
from datetime import date
from cus import respprint
class Admin(Connection):
def __init__(self, login, password):
self.login = login
self.password = password
def register_self(self, data):
... |
import unittest
import sys
import os
sys.path.append(os.path.join('..', 'Src'))
from GenderClassification import GenderClassify
class GenderClassificationTestCase(unittest.TestCase):
def testGeneralGenderAccuracy(self):
genderClassification = GenderClassify()
genderAccuracy = genderClassification.gende... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.