text stringlengths 38 1.54M |
|---|
"""
Create on Sep 5 2019.
@author: dhan
适配大恒GigE数字相机python程序库。
"""
import os, sys
import multiprocessing
import numpy as np
import cv2
import time
import ctypes
from multiprocessing.sharedctypes import RawArray, RawValue
VER_MAJOR = 1
VER_MINOR = 0
VER_SPK = 0
"""
返回大恒相机多进程驱动库函数的版本
"""
def version():
return (VER... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import csv
import time
import datetime
import textwrap
import unicodedata
import string
ROOM_IDX_MAP = {
'Room 230': 1,
'Room 433': 2,
'Room 351a': 3,
'Room 357': 4,
'Room 452': 5,
'Room 358': 6
}
JOINT_NAMES = [... |
from flask import Flask, request, jsonify
import json
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from modified_models import User, Question, Option, Attempt
app = Flask(__name__)
Base = declarative_base()
engine = cr... |
"""SchoolDriver URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-... |
from flask import Flask, render_template
import json
app = Flask(__name__)
@app.route('/')
@app.route('/<nome>')
def main(nome="mundo"):
l = ["maca", "banana", "goiaba"]
return render_template("index.html", nome=nome, lista=l)
@app.route('/ola')
@app.route('/ola/<nome>')
def ola(nome="mundo"):
return 'ola... |
import math
infile = open('genelist.txt')
output = open('finalCUI.txt', 'w')
outtable = open('codontable.txt', 'w')
codon = ''
allgenescodons = {}
codonsingene = []
totalcodons= []
codonfreqtotal = {}
## Find all codons in all genes
for line in infile:
codonsingene = []
seq = line.split('\t')
codon = ''
if len(s... |
# coding=utf-8
"""
author: MiaZhang
Created on 2020/7/22 10:45
"""
import allure
@allure.title('测试用例集')
@allure.feature("中文录入,测试allure使用-feature")
class TestAllure:
@allure.title('这是用例名称,代替用例的函数名')
@allure.description('这是用例描述')
@allure.story("--测试stroy")
def test_01(self):
with allure.step("... |
from .bert_data import BertInfodemicDataset
from .data import InfodemicDataset
from .dataframe import load_dataframe
from .dataloader import SMARTTOKDataLoader
from .field import LabelField, Field
from .length import compute_max_len
from .load import load_data
from .nltk_tokenizer import NLTKTokenizer
from .oov import ... |
# coding: utf-8
import lxml.html
from lxml.cssselect import CSSSelector
import sys
import argparse
try:
from StringIO import StringIO
except ImportError:
# for Python 3.x
from io import StringIO
from csr.Data import DataStream
def import_pmids(source):
'''
Converts a list of pmids into a DataSt... |
from rest_framework import serializers
from .models import IdentificacionSenalModel
class IdentificacionSenalSerializer(serializers.ModelSerializer):
class Meta:
model = IdentificacionSenalModel
fields = ('cod_event', 'cod_event_in', 'volcan', 'est', 'componente', 'algo_detecion_id', 'fecha_pick',... |
import operator
name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
sends = {}
for line in handle.readlines():
if line.startswith("From "):
from1 = line.split()[1]
if from1 in sends:
sends[from1] += 1
else:
sends[from1] = ... |
import roslib; roslib.load_manifest('geometry_msgs')
from geometry_msgs.msg import *
from morse.middleware.ros import ROSPublisher
class BoatGPSROS_pose(ROSPublisher):
""" Publish the velocity of the acceleromter sensor.
No angular information, only linear ones.
"""
ros_class = PointStamped
def de... |
import cv2
from matplotlib import pyplot as plt
import numpy as np
try:
import Image
except ImportError:
from PIL import Image
from pytesseract import pytesseract
path = 'rgb_dst.png'
image_obj = cv2.imread(path)
gray = cv2.cvtColor(image_obj, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
th... |
#Code for Speedometer module
#Import warnings to ignore warnings
import warnings
#Import Adafruit_CharLCD library (Adafruit_CharLCD.py)
import Adafruit_CharLCD as LCD
#Import DistanceSensor, LED, OutputDevice from gpiozero library
from gpiozero import DistanceSensor, LED, OutputDevice
#Import time to pause or delay the... |
# import os
from collections import defaultdict, OrderedDict
from .. import config
from ..utils.io import load_or_create
class Lang(object):
def __init__(self, sents, min_freq_threshold=0, force_reload=False):
"""sents is a list of tokenized sentences"""
# token_dict = load_or_create(token_dic... |
import speech_recognition as sr
import xlsxwriter
workbook = xlsxwriter.Workbook('cardioenglish.xlsx')
sheet1 = workbook.add_worksheet()
cell_format = workbook.add_format({'align': 'center',
'valign': 'vcenter',
'border': 1})
sheet1.write('F1', ... |
from bento.core.parser.api \
import \
raw_parse, build_ast_from_raw_dict
from bento.core.pkg_objects \
import \
PathOption, FlagOption
def raw_to_options_kw(raw):
d = build_ast_from_raw_dict(raw)
kw = {}
if not "name" in d:
raise ValueError("No name field found")
kw["na... |
from flask import Blueprint
bp = Blueprint('coaches', __name__, url_prefix='/coaches')
from .import routes |
#!/usr/bin/python
# Import PySide classes
import sys
import math
import rospy
import myo_msgs.srv
import logger
import PySide.QtGui
import PySide.QtCore
class OrthosisGUI:
"""Simple GUI for Orthosis Displacement Controller
Attributes
-----------
increment : int
Increments allowed for the D... |
"""
Step 2
Read the file from disk, calculate the number of kilometers for each trip (POLYLINE), and write the results to disk.
The results set should have the POLYLINE column omitted, and a new TRIP_LENGTH column added. You may
choose any storage format for the output file(s), but it should be optimized for fast read... |
import asyncio
from urllib.parse import unquote, urlparse
from http.client import HTTPConnection
import logging
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
l = logging.getLogger('name')
def test():
l.error(Exception("wrong"))
# test()
class MyProto(asyncio.Protocol):
... |
import logging
from simutator import genome_mutator
def _parse_indels_option_string(s):
distances_and_lengths = []
for x in s.split(","):
dist, length = x.split(":")
distances_and_lengths.append({"dist": int(dist), "len": int(length)})
return distances_and_lengths
def _parse_complex_opt... |
"""
config
~~~~~~
Application configuration module.
:author: Krohx Technologies (krohxinc@gmail.com)
:copyright: (c) 2016 by Krohx Technologies
:license: see LICENSE for details.
"""
# standard library imports
import os
"""
Global variables
"""
# This will get the absolute path to the module that
# imports this con... |
"""
Author: Brian Mascitello
Date: 4/17/2016
School: Arizona State University
Websites: http://codingbat.com/prob/p192589
Info: Given an array of ints, return the sum of the first 2 elements in the array. If the array length is less
than 2, just sum up the elements that exist, returning 0 if t... |
from CreateDocument import CreateDocument
from ExecuteProgram import ExecuteProgram
from GetFiles import GetFiles
from ReadFile import ReadFile
import argparse, sys
from pyautogui import screenshot
from datetime import datetime
from time import sleep
def main():
parser = argparse.ArgumentParser()
... |
pip install web3
#猜哈哈哈
#我运气不好,1000没有出现有钱的。
```from web3 import Web3
import random
from eth_account import Account
my_provider = Web3.HTTPProvider('https://ropsten.infura.io/v3/')
w3 = Web3(my_provider)
for i in range(1000):
ran1=random.randint(130149309292767984627882592913311145693508503853405435811560606832760015... |
# -*- coding: utf-8 -*-
# Copyright (c) 2018-2020 Niko Sandschneider
"""Module containing all tests for p2p_credentials."""
import unittest.mock
from keyring.errors import PasswordDeleteError
from easyp2p.p2p_credentials import (
keyring_exists, get_credentials_from_keyring, get_credentials_from_user,
get_... |
class MIME_TYPES:
TEXT_PLAIN = 'text/plain'
APPLICATION_JSON = 'application/json'
APPLICATION_X_WWW_FORM_URLENCODED = 'application/x-www-form-urlencoded'
MULTIPART_FORM_DATA = 'multipart/form-data'
|
from django.urls import reverse
from django.utils.text import slugify
from django.db import models
def create_unique_slug(model, instance):
expected_slug = slugify(instance.title)
rivals = model.objects.filter(
slug__startswith=expected_slug
).count()
if rivals > 0:
str_length = 100 ... |
#!usr/bin/env python3
import sqlite3
import pandas as pd
def lookup_student(first_name, last_name=None):
connection = sqlite3.connect('byte_master.db', check_same_thread = False)
cursor = connection.cursor()
first_name = str(first_name.title())
try:
last_name = str(last_name.title())
... |
#import libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#get dataset
dataset = pd.read_csv('Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values
#splitting data
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = tra... |
import random
random_word = random.choice(["pokemon", "digimon", "dragonball", "dexter"])
scrambled_word = "".join(random.sample(random_word, len(random_word)))
print(scrambled_word)
count = 0
def verify_input():
global count
guess_word = input("adivinhe a palavra: ")
if guess_word != random_word and ... |
# https://sites.google.com/site/prologsite/prolog-problems/1
# 1.02 (*) Find the last but one element of a list.
def main():
mylist = ['a','b','c']
print(mylist)
# This way works
print(mylist[len(mylist) - 2 ])
# This way is a bit prettier
print(mylist[-2])
# Let's try to break the list'... |
import os
import sys
try:
os.mkdir('new1')
print('directory created')
raise RuntimeError('runtime error occured')
except FileExistsError:
print(‘Directory is already created’)
|
# bias.py
"""
Use it with internalblue
"""
#!/usr/bin/python2
from pwn import *
from internalblue.hcicore import HCICore
internalblue = HCICore()
internalblue.interface = internalblue.device_list()[0][1]
# setup sockets
if not internalblue.connect():
log.critical("No connection to target device.")
exit(-1)... |
import base64
import cv2
import zmq
import zlib
context = zmq.Context()
footage_socket = context.socket(zmq.PUB)
footage_socket.setsockopt(zmq.CONFLATE, 1)
#footage_socket.connect('tcp://192.168.1.141:5555')
footage_socket.bind('tcp://*:5555')
camera = cv2.VideoCapture(0) # init the camera
#camera.set(3, 640)
#camer... |
"""
Extract openstack database (nova, neutron,...) records based on libvirt state or ovs state,
and only parse the selected record into json format.
"""
from __future__ import print_function
import re
import sys
import datetime
#from pyspark.sql import Row
from pyspark import SparkContext, SparkConf
recordFormat = r'... |
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship
Base = declarative_base()
class Student(Base):
__tablename__ = "students"
id = Column(Integer, primary_key=True)
name = Column(Str... |
import re
import socket
import multiprocessing
#注意:使用此程序需要使用当前目录下的html目录里面的html文件
#html文件使用带有超链接的最好,最好可以有图片
def server_client(new_socket):
"""为客户端返回数据"""
#接收发送过来的数据
repuest = new_socket.recv(1024).decode("utf-8")
repuest_lines = repuest.splitlines() # 将数据转弯为列表
print("")
print(">" * ... |
#!/usr/bin/python
# -*- coding:utf-8 -*-
app = {
'settle_interval': 900, # 结算时间间隔(秒)
'cv_settle_time_unit': 3600, # 贡献值结算时间单元(秒)
'cv_per_settle_unit': 1, # 账号每使用一个结算时间单元,对应的贡献值
'login_interval': 10800, # 账号重新登陆时间间隔(秒)
'report_interval': 900, # 账号上报时间间隔(秒)
}
server ... |
import random
from sys import stdin
diametro = 7
matriz = []
road = []
num = 10
objetos = []
pressure = 5
mutation_chance = 0.05
class Objeto():
rueda = []
fitness = 0
def crear_rueda():
objeto = Objeto()
individuo = []
for i in range(diametro):
individuo.append([])
for j in range... |
#!python3.6
import os, subprocess, sys
sys.path.insert(0, 'pkgs')
os.environ["PATH"] += os.pathsep + os.path.join(os.path.dirname(sys.executable), 'Scripts')
def main():
args = sys.argv[1:]
process = subprocess.run(args)
sys.exit(process.returncode)
|
import tensorflow as tf
#sigmoid를 사용하여 진행을 합니다. => g(z) = 1 / 1 + e^-z
#여기서 H(X)의 경우 X = WX이므로, H(X) = 1 / 1 + e^-WX 입니다.
x_data = [[1, 2], [2, 3], [3, 1], [4, 3], [5, 3], [6, 2]]
y_data = [[0], [0], [0], [1], [1], [1]] #linear regression이 아니기 때문에 0과 1인 binary classification이 주어진다.
#0은 fail, 1은 pass가 될 수도있다.
X = tf.pla... |
#!/usr/bin/env mpipython.lam
"""
Usage: netmine_wrapper.py --mp=FILEPREFIX [OPTIONS]
Option:
-m ..., --run_mode=... 0(default), 1, 2
-n ..., --genenum=... number of genes, 6661(default)
-p ..., --svnum=... number of edges, 805939(default)
-l ..., --sv_length=... length of edge correlation vector, #datasets, 54(def... |
import numpy as np
import pandas as pd
from pythainlp.ulmfit import process_thai
from sklearn.feature_extraction.text import TfidfVectorizer
import joblib
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
def isAgendaPredict(df):
tfidf_fit = joblib.load('isAg... |
# Standard Python libraries
from __future__ import (absolute_import, print_function,
division, unicode_literals)
import os
# https://github.com/usnistgov/DataModelDict
from DataModelDict import DataModelDict as DM
# http://www.numpy.org/
import numpy as np
# https://github.com/usnistgov/atomm... |
#
# @lc app=leetcode id=1525 lang=python3
#
# [1525] Number of Good Ways to Split a String
#
# https://leetcode.com/problems/number-of-good-ways-to-split-a-string/description/
#
# algorithms
# Medium (69.35%)
# Likes: 199
# Dislikes: 5
# Total Accepted: 10.7K
# Total Submissions: 15.6K
# Testcase Example: '"aaca... |
import wpilib
class pivot_arm():
#None of it works
def __init__(self, robot):
self.pivot = wpilib.Victor(8)
self.pivotspeedup = .3
self.pivotspeeddown = -.3
self.pivotArm = False
def teleopPeriodic(self, robot):
if robot.gamepad.getRawButton(5):
... |
# -*- coding: utf-8 -*-
from com.tomcatwang.db.db import Database
from com.tomcatwang.dict.db_dict import test_db_dict
from com.tomcatwang.common.log import Logger
#from reflect.conf.settings import FUNC
#from reflect.conf.settings import MODE
import importlib,re
logger = Logger().logger
m = importlib.import_module(... |
# 2. 写程序用while实现打印三角形。
# 要求输入一个整数表示三角形的宽度和高度,打印出如下的三种直角三角形
# 1)
# *
# **
# ***
# ****
# 2)
# ****
# ***
# **
# *
# 3)
# ****
# ***
# **
# *
w = int(input("请输入三角形的宽度: "))
i = 1 # i代表星号的个数和行数
while i <= w:
blanks_count = w - i # 空格数=宽度-星号个数
print(' ' * b... |
import copy
import time
from dictionaries import hashtable
from testers import tester
class HashtableTester(tester.Tester):
def __init__(self, iter_amount, test_directory, result_directory, hash_func):
self.suffix = result_directory.rsplit('/',maxsplit=1)[1]
super().__init__(hashtable.HashTable, i... |
# Generated by Django 2.2.9 on 2020-03-07 23:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('challenge', '0047_rungroup'),
]
operations = [
migrations.AddField(
model_name='group',
name='name',
fie... |
from google.appengine.ext import ndb
class Example(ndb.Model):
"""Defines an example entity"""
# Meta
id = ndb.IntegerProperty()
created = ndb.DateTimeProperty(auto_now_add=True)
modified = ndb.DateTimeProperty(auto_now=True)
# Core
name = ndb.StringProperty(verbose_name='Event Name', req... |
from tkinter import*
root = Tk()
text=Text(root,width=20,height=10,wrap=WORD,padx=10,pady=10,bd=5,selectbackground="blue")
text.pack()
text.insert(INSERT,"hello world")
root.geometry("900x600+120+120")
root.mainloop()
|
# Expand games table's "id" primary key to (season, id) pair.
# The new table is games2.
import os
import os.path
OLD_DB = 'season27.db'
NEW_DB = 'main.db'
if not os.path.exists(NEW_DB):
os.rename(OLD_DB, NEW_DB)
OLD_SEASON = 24
# Import down here to pick up on the new database filename.
from tbl import conn, cu... |
"""
import turtle
x = 0
while x<300:
y = x**2/300
turtle.goto(x, y)
x = x + 100
turtle.mainloop()
"""
"""
import turtle
num_pts = 10
for i in range(num_pts):
turtle.left(360/num_pts)
turtle.forward(100)
turtle.mainloop()
"""
"""
result = []
n = 16
for count in range(1,n):
if count % 5 == 0:
... |
# import "packages" from flask
from flask import Flask, request, render_template
from image import image_data
import requests
import json
# create a Flask instance
app = Flask(__name__)
# connects default URL to render index.html
@app.route('/')
def index():
return render_template("index.html")
@app.route('/Re... |
#!/usr/bin/python
"""
Created on Thu Dec 1 15:41:13 2016
@author: pavla kratochvilova
"""
# Imports----------------------------------------------------------------------
from argparse import ArgumentParser
from time import sleep
import threading
import logging
import pika
# Custom imports ----------------------------... |
# coding=utf-8
import pickle
import backend
import os
import click
from backend.evaluation.summary import ResultsSummary
@click.group()
def cli():
pass
@cli.command("start")
@click.argument("data_dir", type=click.Path(exists=True))
def start(data_dir):
for batch in ["demo1", "demo2", "demo3", "demo4"]:
... |
class Stack:
def __init__(self, data):
self.data = data
def get_top(self):
return self.data[-1]
def pop(self):
top = self.data[-1]
del(self.data[-1])
def computeMap(self):
numMin_for_maxWin = {}
while(self.data!=[]):
top = self.get_top()
max_win_size = 0
idx = len(self.data)-1
while... |
#This program computes compound interest
#Prompt the user to input the inital investment
C = int(input('Enter the initial amount of an investment(C): '))
#Prompt the user to input the yearly rate of interest
r = float(input('Enter the yearly rate of interest(r): '))
#Prompt the user to input the number of years unti... |
# 03 Write a Python program that accepts a filename from the user and prints the filename’s extension.
# Sample filename : abc.java
# Output : java
text_input = ''
while text_input != '0':
print('Write a file name: ')
text_input = input('> ')
extension = text_input.split(sep='.')
print(extension[le... |
'''
Created on 18-Jan-2018
@author: senthilkumar
'''
from pprint import pprint as pp
if __name__ == '__main__':
pass
country_to_capital = {'United Kingdom' : 'London',
'Brazil':'Brazilia',
'Morocco':'Rabat',
'Sweden':'Stockholm'}
print({capital :... |
from django.conf import settings as django_settings
def settings(request):
return dict( # wrapped oddly to stay narrow
(k, getattr(django_settings, k))
for k in django_settings.SETTINGS_IN_CONTEXT
)
|
import chart
import math
import util
class Points:
def __init__(self, valid, points):
self.valid = valid
self.pts = points
class ZodParsBase:
"""Computes zodiacal parallels (abstract)"""
def __init__(self, obl):
self.obl = obl
def getEclPoints(self, lon, decl, onEcl):
'''Calculate... |
import cv2 as cv
import numpy as np
import scipy
from matplotlib.path import Path
from skimage import measure, morphology
from sklearn.cluster import KMeans
def get_lung_mask(img):
"""
Given a 2D axial slice from a lung CT, returns a binary mask of the lung
regions in the image
:param img: 512x512 ra... |
import numpy as np
import re
from nltk.tokenize import RegexpTokenizer
tokenizer = RegexpTokenizer(r"\w+|\$[\d\.]+|\S+\'")
file = open('T1815SDec2014AFAS0.txt', 'r', encoding="ISO-8859-1")
book = file.read()
pattern = r"|=|\+|\*|`|\'|\[|]|(|)|,|\.|:|\?|ù|%|«|»|\^|¨|/|&|@|#|§|°|\$|£|~|=|<|>|\t"
def tokenize():
... |
##########################################################################
#
# Copyright (c) 2015, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistrib... |
# author:lzt
# date: 2019/12/4 14:39
# file_name: set_test
# 创建一个集合
set1 = {1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 5}
print(set1)
# 通过类创建集合
set2 = set("12312312")
# print(set2)
# 添加数据
set2.add("12")
set2.add(12)
# set2.add([1, 2, 3])
# update可以追加可迭代的元素序列
set2.update([2, 3, 4])
print(set2)
try:
# 删除
# set2.remove("12... |
'''
Pyramid of Natural Numbers Less Than 10
Pattern:
1
2 3 4
5 6 7 8 9
'''
def pattern(number):
level = int((number/2)-2)
start=1
stop=2
for i in range(level):
for j in range(1,stop):
print(start,end='')
start+=1
print()
stop+=2
if __name__... |
import numpy as np
from Neuron import Neuron
class InputLayer:
def execute_forward_pass(self, input_vector):
return input_vector |
#!/usr/bin/python
import socket
import cv2
import numpy
#socket 수신 버퍼를 읽어서 반환하는 함수
def recvall(sock, count):
buf = b''
while count:
newbuf = sock.recv(count)
if not newbuf: return None
buf += newbuf
count -= len(newbuf)
return buf
#수신에 사용될 내 ip와 내 port번호
TCP_IP = '172.18.139... |
"""
Write all the data from a dictionary to a file.
"""
favorites = {
'food': 'pizza',
'color': 'green',
'band': 'REM'
}
f = open('favorites.txt', 'w')
for key, value in favorites.items():
f.write(f'Your favorite {key} is {value}.\n')
f.close() |
# refer : https://www.youtube.com/watch?v=10laHayu2dc
class Solution:
def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int:
d = {i: set() for i in range(n)}
currPairs = {i: None for i in range(n)}
# count = 0
for p in pairs:
n1, n2... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from s... |
__author__ = 'Oier Lopez de Lacalle'
import sys
import re
from xml.dom import minidom
import nltk
"""
A helper class that reads Senseval/Semeval format file and returns
a list the tokenized contexts of the target words, instance id,
instance label, and target-word offset. The tuple contains the
information in the f... |
#todo сделать мини игру камень ножници бумага
import random
from datetime import datetime , timedelta
import time
from func import *
from main import *
def knb(call, y):
future_in_half_hour = datetime.utcnow() + timedelta(hours=3)
local_time = future_in_half_hour.replace(microsecond=0)
x = random.randint (... |
# Copyright (c) 2014--2019 Muhammad Yousefnezhad
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, ... |
from __future__ import absolute_import
from django.core.mail.backends.smtp import EmailBackend
from django.conf import settings
from django.utils.importlib import import_module
from .models import Message
from .filter import MessageFilter
import sys
from std2.singleton import Singleton
class MessageFilters(Singlet... |
# -*- coding: utf-8 -*-
#
# Logging functions for Syncopy.
#
# Note: The logging setup is done in the top-level `__init.py__` file.
import os
import sys
import logging
import socket
import syncopy
import warnings
import datetime
import platform
loggername = "syncopy" # Since this is a library, we should not use the... |
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022)
#
# 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 appl... |
x = 50
def myfun():
#global x Now this x will be global
x=22
print(x)
def fun():
x = 7
print(x)
fun()
print(myfun())
print(x)
|
def solve(num):
recipes = [3,7]
elv1 = 0
elv2 = 1
cur_pos = 0
digits = map(int, list(str(num)))
while True:
s = recipes[elv1] + recipes[elv2]
parts = map(int, list(str(s)))
for i in range(len(parts)):
if parts[i] == digits[cur_pos]:
cur_pos +... |
import unittest
import mock
import requests
BASE_URL = "https://3ytleagu47.execute-api.us-east-1.amazonaws.com/dev"
class TestAPIRoutes(unittest.TestCase):
def test_ping(self):
req = requests.get("{url}/ping".format(url=BASE_URL))
res = req.json()
self.assertEqual(res, {"message": "PONG"... |
import csv
import time
from twarc import Twarc
import numpy as np
#https://stackoverflow.com/questions/51162636/unicodeencodeerror-ucs-2-codec-cant-encode-characters-in-position-8-8-non-b
# I adapted this
def BMP(s):
print("called \n")
return "".join((i if ord(i) < 10000 else '\ufffd' for i in s))
... |
"""
1. Remove deprecated statements about diseases that have deprecated DOID statements
2. Un-deprecate the mesh, nci and icd9 statements (I hand checked like a hundred of them and they are all ok, we'll let
the community delete the bad ones)
3. delete the items that are newly empty (no xrefs) (ended up with 135 of the... |
from flask import Flask, request, render_template, redirect, url_for
from flask import make_response, send_from_directory
from werkzeug import secure_filename
import os
from pickle import load
from re import subn
from nltk import word_tokenize
from sklearn import linear_model
from sklearn.feature_extraction.text impo... |
import tensorflow as tf
import numpy as np
from models.components import netComp as nc
class CnnNetwork():
def __init__(self, inputSize, outputSize):
self._batch_size = 25
self._learningRate = 1e-2
self._inputSize = list(inputSize)
self._outputSize = list(outputSize)
self._P... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-11-07 14:31
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('armylist', '0007_unit_model_pic'),
]
operations = [
migrations.RemoveField(
... |
import matplotlib.pyplot as plt
#basics, line graph
x = [1,2,3,4,5,6,7]
y = [1,4,9,16,9,4,1]
x2 = [1,2,3,4,5,6,7]
y2 = [1,8,27,64,27,8,1]
plt.plot(x,y, label ='square', linewidth = 5)
plt.plot(x2, y2, label ='cube')
plt.xlabel('Plot Number')
plt.ylabel('Important Var')
plt.title('Intresting Graph\nCheck i... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def szyfruj_vigenere(tekst, klucz):
szyfrogram = ''
i = 0
for l1 in tekst:
wartosc1 = ord(l1.upper()) - 64
# print wartosc1
wartosc2 = ord(klucz[i].upper()) - 64
# print wartosc2
i += 1
wartosc3 = wartosc1 + wartosc2
if wartosc3 > 26:
wartosc3 -= 26
... |
#!/home/porosya/.local/share/virtualenvs/checkio-VEsvC6M1/bin/checkio --domain=py run pawn-brotherhood
# https://py.checkio.org/mission/pawn-brotherhood/
#
# END_DESC
def safe_pawns(pawns):
CONV_TABLE = {"a": 0, "b": 1, "c": 2, "d": 3, "e": 4, "f": 5, "g": 6, "h": 7}
chess_board = [["." for x in range(8)]fo... |
"""
功能:Game2048类
作者:指尖魔法师
QQ:14555110
"""
import pygame
import random
import copy
class Game2048(object):
def __init__(self, matrix_size=(4, 4), max_score_filepath=None):
self.matrix_size = matrix_size
# 游戏最高分保存路径
self.max_score_filepath = max_score_filepath
self.initialize()
... |
# To add a new cell, type '#%%'
# To add a new markdown cell, type '#%% [markdown]'
#%%
import numpy as np
import matplotlib.pyplot as plt
import sympy as sp
import math as m
from sympy.abc import a, c, x, y, z
Docx, Docy, Docz, Dcax, Dcay, Dcaz = sp.symbols('Docx, Docy, Docz, Dcax, Dcay, Dcaz')
#%%
A = sp.Matrix([[... |
from django.contrib import admin
from .models import *
admin.site.register(Vertex_Class, admin.ModelAdmin)
admin.site.register(Preamble, admin.ModelAdmin)
admin.site.register(Discipline, admin.ModelAdmin)
admin.site.register(Section, admin.ModelAdmin)
admin.site.register(Subject, admin.ModelAdmin)
admin.site.register... |
# -*- coding: utf-8 -*-
import xbmc
import xbmcgui
import os
import shutil
import socket
# define some places
USERDATA = xbmc.translatePath('special://masterprofile')
SMASHINGFAVOURITES = os.path.join(USERDATA, "smashing", "smashingfavourites")
# path to advancedsettings options folders:
FOLDERSPATH = os.path.join(S... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
from time import time
import gl
from string import ascii_lowercase
import codecs
import re
import json
import operator
'''
usage: python trans2model.py
把标注好的文件zhidao_question.txt转变为可以用于训练的数据文件json/zhidao_question_0x.json
同时会生成关系文件zhidao_ques... |
#!/usr/bin/env python
from __future__ import print_function
import json
import requests
import re
from sys import stdout
from difflib import get_close_matches
from bs4 import BeautifulSoup
from datetime import datetime
venues = {}
venue_names = []
events = []
def lookup_venue(name):
return venues[get_close_matche... |
import logging
import os
from pathlib import Path
import uvicorn
from dotenv import load_dotenv
from starlette_prometheus import PrometheusMiddleware, metrics
from nivacloud_logging.log_utils import setup_logging
if __name__ == "__main__":
setup_logging(plaintext=True)
port = 5000
if os.environ.get("NIVA_... |
#Estrutura de Controle - if
idade = int(input('Digite a sua idade: '))#Recebe a idade
if (idade < 18): #Verifica se idade é menor que 18
print('Menor de Idade')
else: #Se não for
print('Maior de Idade')
#Teste de Notas
print('Verificação de rendimento dos alunos!\n')
print('Digite suas 3 notas:\n')
#Recebe a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.