text stringlengths 38 1.54M |
|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module that provides functions used in
the context to pre-process input
"""
import argparse
import numpy as np
import scipy as sp
def parse_args_for_image_input():
"""Parses the arguments for test ui's that accept images as input"""
parser = argparse.Argum... |
#https://scipy-lectures.org/packages/scikit-learn/auto_examples/plot_tsne.html
import os
import numpy as np
import argparse
import math
import random
import pandas as pd
import csv
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
#matplotlib.use("Agg")
import torch
import torch.nn as nn... |
#!/usr/bin/env python
import collectd
import collections
import json
import urllib2
CONFIGS = []
CONFIG_DEFAULT = [{
"host": "localhost",
"port": "9700",
"node": "filebeat",
"url": "http://localhost:9700/debug/vars"
}]
stat = collections.namedtuple("Stat", ("type", "path"))
# Metrics dictionary
STATS = {
... |
#!c:\users\samb5\documents\visual studio 2015\Projects\django_azure\django_azure\venv\Scripts\python.exe
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
|
from .api import Legalizer
from .base import LegalizerBase
@Legalizer.register
class GraphDefLegalizer(LegalizerBase):
TARGET = 'tensorflow'
class _OpTypeRenamePostProcessing(object):
_RENAME_MAP = {
'BatchMatMulV2': 'MatMul',
# FIXME: need to update matcher before adding this line
# 'Add':... |
import sample_oauth1_code
get_tokens(request_token_url='https://www.tumblr.com/docs/en/api/v2', client_key='', client_secret='') |
import base64
import boto3
import json
import os
ddb_client = boto3.client('dynamodb')
lambda_client = boto3.client('lambda')
table_name = os.environ['STM_TABLE_NAME']
def process_standard_record(parsed, decoded):
txn_id = parsed['txnId']
model_id = parsed['modelId']
print 'processing status ... |
for i in range(1,3):
print(i)
if i==2:
print("2 found")
print("1 and 2 are going to print")
print(" new line")
break
|
import matplotlib.pyplot as plt
#matplotlib.org basically matlab graphs in python
import data as d
purchases = d.selectAllPurchases() #return list of dictionary
costs = list(map(lambda m: float(m.get('Cost')), purchases))
category = list(map(lambda m: m.get('CategoryName')[0:10], purchases))
print(costs[0])
plt.figu... |
import os
class Config(object):
APP_NAME = os.getenv("APP_NAME", "Commentaria")
SECRET_KEY = os.getenv("SECRET_KEY")
DATABASE_URL = os.getenv("DATABASE_URL")
SQLALCHEMY_DATABASE_URI = os.getenv("SQLALCHEMY_DATABASE_URI", DATABASE_URL)
MAIL_SERVER = os.getenv("MAIL_SERVER")
MAIL_PORT = os.geten... |
seconds = int(input("Введите целое число - "))
second = seconds % 60
minutes = seconds % 3600 // 60
hours = seconds // 3660
print('%d:%d:%d' % (hours, minutes, second))
|
weight = int(input('Enter the weight: ' ))
unit = input('(l )bs or (k)g : ')
if unit.lower() == 'l':
converted = weight * 0.45
print(f'You are {converted} kilos')
else:
converted =weight /0.45
print(f"you are {converted} lbs")
|
class Node(object):
"""
Class to represent a node in the circuit. A node is simply a location
where multiple components connect.
"""
def __init__(self, node_id):
"""
Constructs a node, assigning it a unique identifier.
"""
self.node_id = node_id
self.components = []
def __hash__(self):
"""
Hash a... |
#!/usr/bin/env python3
class StringOperations:
def isPalindrome(string):
return string == string[::-1]
def isPalindromeBrute(string):
strlen = len(string)
if strlen % 2 != 0:
strFirstHalf = string[0:int(strlen/2)]
strSecondHalf = string[int(strlen/2+1):]
... |
import pygame
from settings import Settings
import game_functions as gf
from boy import Boy
from ball import Ball
from pygame.sprite import Group
def run_game():
"""运行游戏"""
#初始化
pygame.init()
#导入设置
my_settings = Settings()
#创建屏幕实例
screen = pygame.display.set_mode(
(my_settings.screen_width, my_settings.screen... |
import glob
import rpm
import unittest
M = None
ErlDrvDep = ""
ErlNifDep = ""
class TestAllMethods(unittest.TestCase):
def test_sort_and_uniq(self):
self.assertEqual(M.sort_and_uniq([1,2,2,2,2,4,3,2,1]), [1,2,3,4])
def test_check_for_mfa(self):
# This test requires erlang-erts RPM package ins... |
# Copyright (c) 2018 Uber Technologies, Inc.
#
# 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, pub... |
import dash_html_components as html
import db_interface
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
import plotly.plotly as py
from plotly import graph_objs as go
import db_interface
import dash
from app import app, indicator, indicator_with... |
import unittest
from function.function_01 import *
class loginTest(unittest.TestCase):
def setUp(self):
pass
def test_login(self):
print("执行用例:登录")
login("1451953028@qq.com","zdd123456")
def tearDown(self):
pass
# if __name__ == "__main__":
# unittest.main() |
"""
提供GUI界面
"""
import tkinter as tk
from enum import Enum, unique
import PySimpleGUI as sg
import matplotlib.backends.tkagg as tkagg
from PIL import Image, ImageTk
from matplotlib.backends.backend_tkagg import FigureCanvasAgg
from sensor.algorithm import AlgorithmManager
from sensor.algorithm import Cycl... |
# -*- coding:utf-8 -*-
class Cat:
def say(self):
print('I am a cat.')
class Dog:
def say(self):
print('I am a dog.')
class Duck:
def say(self):
print('I am a duck.')
# Python中较灵活,只要实现say方法就行,实现了多态
animal = Cat
animal().say()
# 实现多态只要定义了相同方法即可
animal_list = [Cat, Dog, Duck]
f... |
宝石与石头
class Solution:
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
sum =0
for i in J:
for a in S:
if i==a:
sum = sum +1
print(sum)
return sum
|
##############################################################################
#
# regress_public.gypi
# Copyright (c) 2014 Raphael DINGE
#
#Tab=3########################################################################
{
'targets': [
{
'target_name': 'regress',
'type': 'executable... |
from afthermal.text import Text, ByteStringVisitor, Bold, Node
import pytest
@pytest.fixture
def encoding():
return 'ascii'
@pytest.fixture
def bsv(encoding):
return ByteStringVisitor(encoding)
def test_simple_text(bsv, encoding):
tx = Text(u'hello, world')
assert bsv.visit(tx) == u'hello, world'... |
from enum import Enum
from typing import Tuple
class Region(Enum):
EUR, USA, JPN, KOR = range(4)
ALL = 255
@property
def country_code(self) -> str:
try:
return {
Region.EUR: 'GB',
Region.USA: 'US',
Region.JPN: 'JP',
R... |
from app import db
contributions = db.Table('contributors',
db.Column('project_id', db.Integer, db.ForeignKey('projects.id'), primary_key=True),
db.Column('contributor_id', db.Integer, db.ForeignKey('users.id'), primary_key=True)
)
user_skills = db.Table('user_skills',
db.Column('user_id', db.Integer, db.F... |
class Sort:
def __init__(self):
pass
def search_(j, x, search):
return x[j] == search
def sort_start(search, x):
leng = len(x)
center_index = (leng - 1) / 2
if x[center_index] > search:
return method_name(0, center_index, search, x)
return method_name(center_index, leng, sea... |
#%%
from aiogram.dispatcher.filters.state import State, StatesGroup
class InterviewStates(StatesGroup):
question_number = State()
results = State()
if __name__ == '__main__':
print(InterviewStates) |
import urllib.request
from bs4 import BeautifulSoup
class Scraper:
def __init__(self, site):
self.site = site
def scrape(self):
r = urllib.request.urlopen(self.site)
html = r.read()
sp = BeautifulSoup(html, 'html.parser')
for tag in sp.find_all("div"):
url... |
import time
import traceback
from threading import Lock, currentThread, Thread
import logging
logger = logging.getLogger(__name__)
MAX_THREADS = 200
def async_get_data(func, data, mapping=False):
"""
This is used to asynchronously get records.
:param func: The function that receives a single element o... |
import os
import cv2
from PIL import Image
import torchvision.transforms as transforms
from scipy import ndimage
def is_image_file(filename):
IMG_EXTENSIONS = [
'.jpg', '.JPG', '.jpeg', '.JPEG',
'.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP',
]
return any(filename.endswith(extension) for ... |
"""
Crie um programa que leia duas notas de um aluno e calcule sua media, mostrando uma mensagem no final, de acordo com
a media atingida:
-media abaixo de 5.0: REPROVADO
-media entre 5.0 e 6.9: RECUPERAÇÃO
-media 7.0 ou superior: APROVADO
"""
n1 = float(input('Primeira nota: '))
n2 = float(input('Segunda nota: '))
med... |
from django.db import models
# Create your models here.
class CartModel(models.Model):
pro_id = models.IntegerField()
pro_name = models.CharField(max_length=100)
pro_brand = models.CharField(max_length=100)
pro_quantity = models.CharField(max_length=100)
pro_price = models.IntegerField()
pro_size = models.Int... |
import optparse
import sys
import os
from twisted.internet import defer, reactor
from twisted.python import log
sys.path.append(os.getcwd())
from social import people, utils, db
@defer.inlineCallbacks
def sendInvitations(sender):
cols = yield db.get_slice(sender, "userAuth")
senderInfo = utils.columnsToDict(c... |
# psql: \conninfo
# You are connected to database "cicero" as user "cicero" via socket in "/tmp" at port "5432".
import psycopg2
conn = psycopg2.connect(
database="eventsdb",
user="cicero",
host="/tmp",
password="123"
) |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 26 07:42:25 2019
@author: USRBET
"""
import numpy as np
import pandas as pd
arr_pand = np.random.randint(0,10,6).reshape(2,3)
df1 = pd.DataFrame(arr_pand)
s1 = df1[0]
s2 = df1[1]
s3 = df1[2]
s1[0]
df1[3] = s1
#au = df1.add(serie_a)
df1[4] = s1 * s2
datos_fisicos_uno =... |
import os
ROOT_DIR= os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + "/"
CONFIG_DIR= ROOT_DIR + "config/"
DATA_DIR= ROOT_DIR + "data/"
CACHE_DIR= ROOT_DIR + "cache/"
STRING_DIR= CONFIG_DIR + "strings/"
PERMS_DIR= CONFIG_DIR + "perms/"
COG_CONFIG_DIR= CONFIG_DIR + "cog_configs/"
BOT_CONFIG_FILE= CONFIG_D... |
import numpy as np
import sys
import copy
import pandas as pd
def assignmentToDf(assignment, real_dist_dict):
hist = [] # contiene le distanze derivanti dal nostro algoritmo
histn = [] # contiene i nomi degli aminoacidi
histi = [] # contiene l'indice degli aminoacidi
real_dist = [] # contiene le d... |
rent = 12000
gas = 800
groceries = 300
total = rent + gas + groceries
print(total)
rent = 15000
item1 = "gas"
item2 = "groceries"
item3 = "rent"
print("Expense List: ", item3, item1, item2)
|
import requests
import time
import json
vis_url = 'http://0.0.0.0:5000/events'
vis_data = "../data/StreamingNWChem/"
res = requests.post(vis_url, json={'type':'reset'})
print(res.json())
#----set function dictionary----
fun_names = []
with open(vis_data+"function.json", 'r') as f:
fun_names = json.load(f)
requests.... |
from functools import reduce
import time
##li = [1,2,3,4,5,6,7,8,9,10]
##sum = reduce(lambda n,m:n+m,li)
##print(sum)
##
##li2 = [1,2,3,4,5,6,7,8,9,10]
##mul = reduce(lambda n,m:n*m,li2)
##print(mul)
##add = reduce(lambda n,m:n+m,range(1,100))
##print(add)
t1 = time.time()
print(t1)
mul = reduce(lambda n,m:n+m,range... |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 10 16:01:37 2020
@author: Felix
"""
"""
IMPORTACION DE LIBRERIAS
"""
from bokeh.layouts import layout
from bokeh.models import CategoricalColorMapper, ColumnDataSource, NumeralTickFormatter
from bokeh.plotting import figure
from source.common.Funciones_Generales imp... |
# -*- coding: utf-8 -*-
"""
Модуль *event* позволяет обрабатывать события, происходящие в приложении.
event.py::
def before_event(error, event):
...
def after_event(event):
...
def error_event(event):
...
События происходят при изменении данных в приложении пользователем
и программный интерфейс позво... |
"""
Classes from the 'FeatureFlagsSupport' framework.
"""
try:
from rubicon.objc import ObjCClass
except ValueError:
def ObjCClass(name):
return None
def _Class(name):
try:
return ObjCClass(name)
except NameError:
return None
FFConfiguration = _Class("FFConfiguration")
FFFe... |
# -*- coding: utf-8 -*-
from . import get_user_model
class SuBackend(object):
supports_inactive_user = False
def authenticate(self, su=False, user_id=None, **kwargs):
if not su:
return None
try:
user = get_user_model()._default_manager.get(
pk=user_id... |
import sys
from collections import deque
input = sys.stdin.readline
for testcase in range(int(input())) :
q = []
n = int(input())
for pyun in range(n+2) :
px, py = map(int,input().split())
q.append((px,py))
v = [[10e7 for i in range(n+2)] for _ in range(n+2)]
fo... |
""" This is a solution to an exercise from
Think Python, 2nd Edition
by Allen Downey
http://thinkpython2.com
Copyright 2015 Allen Downey
License: http://creativecommons.org/licenses/by/4.0/
Exercise 10-2:
Write a function called cumsum that takes a list of numbers and returns the cumulative
sum; that is, a new list... |
from data_analysis_base import AnalysisBaseClass
def get_ids(fname):
with open(fname, 'r') as f:
return [int(img_id.split()[0]) for img_id in f.readlines()]
# Crete analysis tools
# Get caption results
caption_paths = []
base_dir = '../final_captions_eccv2018/'
baseline_ft = ('Baseline-FT', base_dir + 'ba... |
import time
import random
#Updated 8/24
print('Please refer to README.md before playing.\n')
time.sleep(1)
print('There is darkness, all around you. You have no idea where you are.')
print('A voice calls out to you.\n')
time.sleep(1)
#Character Maker
charComplete = ('no')
while charComplete in ['n', 'NO','no','N','... |
# loader_Observer.py 4-Apr
print("loader_Observer.py..")
import matplotlib.pyplot as plt
import numpy as np
import ipywidgets as widgets
print("done.")
#end of module |
# Generated by Django 3.0.5 on 2020-06-07 02:30
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main_app', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='details',
name='city',
f... |
import numpy as np
def partition(a, left, right):
pivot = right
right -= 1
while left < right:
while left <= right and a[left] <= a[pivot]:
left += 1
while left <= right and a[right] >= a[pivot]:
right -= 1
if left < right:
a[left], a[right] = a[r... |
import requests
def getHTMLText(url):
try:
r = requests.get(url,timeout=30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return "出现异常: "+r.status_code
if __name__ == "__main__":
url = "https://item.jd.com/2967929.html"
print(getHTM... |
from ll import *
test_list = cons("a", cons("b", nil))
def test_basic():
assert head(test_list) == "a"
assert head(tail(test_list)) == "b"
def test_length():
assert len(nil) == 0
assert len(test_list) == 2
def test_iter():
assert list(test_list) == ["a", "b"]
assert "b" in test_list
def tes... |
import sqlite3
import json
#Connect to database
conn=sqlite3.connect('csc455.db')
#Request a cursor from the database
c=conn.cursor()
#Create the table
TwitterTable= '''CREATE TABLE Twitter
(
created_at VARCHAR(50),
id_str NUMBER(50),
text VARCHAR(160),
source VARCHAR(100),
in_reply_to_user_id VARCHAR(25), ... |
# Solution of;
# Project Euler Problem 302: Strong Achilles Numbers
# https://projecteuler.net/problem=302
#
# A positive integer n is powerful if p2 is a divisor of n for every prime
# factor p in n. A positive integer n is a perfect power if n can be expressed
# as a power of another positive integer. A positive i... |
# -*- coding: utf-8 -*-
from anima.dcc import empty_reference_resolution
from anima.dcc.base import DCCBase
from anima.testing import count_calls
class TestEnvironment(DCCBase):
"""A test DCC which just raises errors to check if the correct
method has been called
"""
name = "TestEnv"
representat... |
class Scene:
def __init__(self, camera, shapes, bsdfs, mediums, phases, area_lights):
self.camera = camera
self.shapes = shapes
self.bsdfs = bsdfs
self.area_lights = area_lights
self.mediums = mediums
self.phases = phases
|
from math import *
from numpy import *
from scipy import *
import cosmolopy.constants as cc
import cosmolopy.distance as cd
import cosmolopy.perturbation as cp
import matplotlib.pyplot as plt
from scipy.integrate import quad
from scipy import special
#******************************************************
#FUNCTIONS
#... |
"""empty message
Revision ID: 47b837ea14fa
Revises: 523f8db3a8ac
Create Date: 2017-06-18 08:51:36.170425
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '47b837ea14fa'
down_revision = '523f8db3a8ac'
branch_labels = None
depends_on = None
def upgrade():
# ... |
from src_describe.standard_deviation import standard_deviation
from src_describe.sum_values import sum_values
from src_describe.count_values import count_values
from src_histogram.get_num_headers import get_num_headers
from src_scatter_plot.calc_cov import calc_cov
"""
GOAL: return a table of all Pearson correlatio... |
'''
Django app for shared code and functionality used
across other applications within the project. Currently includes
abstract database models with common functionality or fields that are
used by models in multiple apps within the project.
'''
import rdflib
default_app_config = 'mep.common.apps.CommonConfig'
SCHEMA... |
#! /usr/bin/python3
import zmq
import os
import sys
class SignalingClientHelper():
def Connect(self, ):
context = zmq.Context()
ws_top = os.path.dirname(sys.argv[0]) + '/../'
ws_top = os.path.abspath(ws_top)
#os.environ['WS_TOP'] = ws_top
print( "Connecting to signaling serv... |
import pytest
from parseval.parser import FloatParser
from parseval.exceptions import (
UnexpectedParsingException,
NullValueInNotNullFieldException,
UnsupportedDatatypeException,
ValidValueCheckException,
MaximumValueConstraintException,
MinimumValueConstraintException
)
# Valid value tests
d... |
class Solution(object):
def addStrings(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
if not num1:
return num2
if not num2:
return num1
carry = 0
res = []
m, n = len(num1), le... |
import numpy as np
import nltk
import pickle
# nltk.download()
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
from nltk.stem import WordNetLemmatizer
wordLeammer=WordNetLemmatizer()
porterStemmer=PorterStemmer()
stopDict=set(stopwords.words('english'))
target=open('/kaggle/input/science... |
from typing import Optional
from context import ExecutionContext
from fastapi import FastAPI, Request
from time import sleep
from database import Database
import logging
logging.config.fileConfig('logging.conf', disable_existing_loggers=False)
app = FastAPI()
database_instance = Database()
@app.middleware("http")... |
# Generated by Django 3.0.8 on 2020-07-25 03:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('curricula', '0007_delete_alumno'),
]
operations = [
migrations.AlterField(
model_name='aniolectivo',
name='nombre',
... |
import shutil
from unittest import TestCase
from FileHandling import *
class TestFileHandling(TestCase):
def test_CreateFileIfNotExist(self):
os.mkdir("tempPath")
self.addCleanup(lambda: shutil.rmtree("tempPath"))
fileName = "tempPath/a/b/c/d/e/file"
createFilesIfNotExist(fileName... |
#js DOM can access any elements on web page just like how selenium does
#selenium hav ea method to execute javascript code in it
from selenium import webdriver
driver=webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.get("https://rahulshettyacademy.com/angularpractice/")
driver.find_element_by_name("nam... |
#to find the highest value of palindrome
'''max1=0
for i in range(100,1000):
for j in range(100,1000):
x=i*j
y=str(x)
if y==y[::-1]:
if x>max1:
max1=x
a,b=i,j
print(max1,a,b)'''
#to find the factorial
'''count=1
n=5
f... |
import cv2
import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision
import torchvision.datasets as datasets
from torch.autograd import Variable
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
import CNN
# transformation for image
transform_ori = transf... |
from catan.board import *
from catan.utils import *
from catan.player import *
from catan.board import *
import pygame
def main():
screen = pygame.display.set_mode(1024, 768)
board = Board()
resource_cards = ResourceCardDeck()
dev_cards = DevelopmentCardDeck()
if __name__ == "__main__":
main() |
"""后台添加的自定义方法,公用部分"""
from django.contrib import messages
def set_invalid(modeladmin, request, queryset):
# 批量禁用
queryset.update(is_valid=False)
messages.success(request, '操作成功')
set_invalid.short_description = '批量禁用所选对象'
def set_valid(modeladmin, request, queryset):
# 批量启用
queryset.update(is_... |
#-*-coding:utf-8-*-
from __future__ import division
if __name__=="__main__":
data = "Netflix"
k = 50
innerProduct = {}
for i in xrange(1, k+1):
innerProduct[i] = 0
count = 0
with open(data + "-50.txt") as input:
currentUserID = None
currentUserResult = []
for ... |
#import library
import cv2
import os
from skimage import exposure
from skimage.exposure import match_histograms
from matplotlib import pyplot as plt
#import images
ref = os.path.basename('reference.jpg')
sour = os.path.basename('source.jpg')
#opencv read images with gray scale
ref_img = cv2.imread(ref,0)
sour_img = ... |
#p70
# (1) 문자열 열거형객체 이용
string="홍길동"
print(len(string))
for s in string:
print(s)
# (2) list 열거형객체 이용
lstset = [1,2,3,4,5]
for e in lstset:
print('원소:',e)
#p72
# (1) range 객체 형성
num1=range(10)
print('num1:',num1)
num2=range(1,10)
print('num2:',num2)
num3=range(1,10,2)
print('num3=',num3)
# (2) range 객체 활용
f... |
def printbaar_rek(rek):
rij_1 = rek[0][0] + rek[0][1] + rek[0][2] + rek[0][3] + rek[0][4]
rij_2 = rek[1][0] + rek[1][1] + rek[1][2] + rek[1][3] + rek[1][4]
rij_3 = rek[2][0] + rek[2][1] + rek[2][2] + rek[2][3] + rek[2][4]
rij_4 = rek[3][0] + rek[3][1] + rek[3][2] + rek[3][3] + rek[3][4]
oplossing = ... |
def drawDiamond():
for i in range(2):
toytle.right(30)
toytle.forward(100)
toytle.left(60)
toytle.forward(100)
if i >0:
break
else:
toytle.left(150)
import turtle
toytle = turtle.Turtle()
toytle.hideturtle()
toytle.color("black")
toytle.speed(10)
for i in range(9):
drawDiamon... |
# -*- coding:utf-8 -*-
'''
1.6 字典中的键映射多个值
怎样实现一个键对应多个值的字典(也叫 multidict)?
一个字典就是一个键对应一个单值的映射。如果你想要一个键映射多个值,
那么你就需要将这多个值放到另外的容器中, 比如列表或者集合里面。比如,
你可以像下面这样构造这样的字典:
'''
d = {
'a':[1,2,3],
'b':[4,5]
}
e = {
'a':{1,2,3},
'b':{4,5}
}
'''
选择使用列表还是集合取决于你的实际需求。如果你想保持元素的插入顺序就应该使用列表,
如果想去掉重复元素就使用集合(并且不关心元素的顺序问题)
你... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
from ..base import LowResEmbedder, AttentionBox, CoreAndProposalLayer
class TripleMNISTLowResEmbedder(LowResEmbedder):
def __init__(self):
super(TripleMNIS... |
#!/usr/bin/python
###################
###Documentation###
###################
"""
gluIdaifFour.py: Calculates cmrGlu using a FDG water scan and an image-derived input function
Uses basic four parameter kinetic model
See Phelps et al, Annals of Neurology 1979
Can perform an optional CBV correction using method use... |
import csv
import sys
if len(sys.argv) != 3:
print("Usage: python dna.py csv_file txt_file.", file=sys.stderr)
sys.exit(1)
csv_file_name = sys.argv[1]
txt_file_name = sys.argv[2]
# Load a csv file
try:
with open(csv_file_name, "r") as csv_file:
csv_reader = csv.reader(csv_file)
ref = [row... |
import glob
import os
import pickle as pkl
import numpy as np
from PIL import Image, ImageChops
from nltk.tokenize import RegexpTokenizer
image_size = 64
# Maximum number of captions to use
SEQ_LENGTH = 40
def get_dict_correspondance(worddict="/home/davidkanaa/Documents/UdeM/ift6266_h17_deep-learning/data/inpaintin... |
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from bs4 import BeautifulSoup
import requests
class GetStats(APIView):
def get(self, request):
countries = self.request.query_params.get('countries', '')
if not countries:
... |
# AWS specific configuration
# ** IMPORTANT NOTE: Please do not check in this file. This is machine specific
# config **
# the region which we are going to use
region = "us-east-1"
# describe credentials
credentials = {
"aws_access_key_id": "your-access-key",
"aws_secret_access_key": "your-access-secret"
}
# g... |
import requests
import json
import configs.config as config
class News_api:
def __init__(self):
# api.openweathermap.org/data/2.5/forecast?id=
self.category_i = 0
self.api_url_website = "https://newsapi.org/v2/top-headlines?"
self.api_key = config.news_api['key']
self.country = config.news_api['country']
... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 15 10:50:13 2018
@author: Administrator
"""
import tensorflow as tf
#from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.python.ops.rnn_cell_impl import DropoutWrapper
import scipy.io as sio
import numpy as np
import random as rd
impo... |
"""
Copyright 2021 Mohamed Khalil
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
dis... |
#################################################################################
# WaterTAP Copyright (c) 2020-2023, The Regents of the University of California,
# through Lawrence Berkeley National Laboratory, Oak Ridge National Laboratory,
# National Renewable Energy Laboratory, and National Energy Technology
# Labo... |
from tqdm import tqdm
import torch
import config
def train(model, dataloader, optimizer):
model.train()
fn_loss = 0
tk = tqdm(dataloader, total=len(dataloader))
for data in tk:
for k, v in data.items():
data[k] = v.to(config.DEVICE)
optimizer.zero_grad()
_, loss = m... |
# Generated by Django 2.2.1 on 2019-05-13 18:22
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('api', '0003_auto_2019050... |
LIST_CMD = "/System/Library/PrivateFrameworks/Apple80211.framework/Versions/A/Resources/airport scan"
IS_WIFI_OFF = "/System/Library/PrivateFrameworks/Apple80211.framework/Versions/A/Resources/airport -I"
TURN_WIFI_ON = "networksetup -setairportpower {port} on"
TURN_WIFI_OFF = "networksetup -setairportpower {port} off... |
from typing import Tuple, List
def validate_multiple_inputs(input: List[str]) -> Tuple[List[str], str]:
errors = None
try:
# check if JSON contains the key "input_texts"
input = input.get("input_data", None)
if input is None:
raise KeyError("The key 'input_data' wa... |
#This code tracks Twitter's South America's trending topics. Countries not listed are not on Twitter's API
ARGENTINA_WOE_ID = 23424747
argentina_trends = twitter_api.trends.place(_id=ARGENTINA_WOE_ID)
print(json.dumps(argentina_trends, indent=1)
argentina_set = set([trend['name']
... |
from numpy import sum, power, ones, mean, sqrt
from scipy import stats
from .linalg import as_array
def RSS(x, y, idx=0):
return ((as_array(x)[idx:] - as_array(y)[idx:]) ** 2).sum()
def RWSE(x, y, idx=0):
x, y = as_array(x), as_array(y)
w = sum(x[idx:])
return (((x[idx:] - y[idx:]) * x[idx:]/w) ** 2).... |
# -*- coding: utf-8 -*-
import sqlite3
class DatabaseHelper():
# This class is a singleton instance
__instance = None
@staticmethod
def getInstance():
if DatabaseHelper.__instance == None:
DatabaseHelper()
return DatabaseHelper.__instance
'''Constructor'''
def _... |
def quickSort(alist,left,right):
middle=0
pivot=alist[left]
l=left
r=right
while 1:
while alist[l]<=pivot:
if l==r:
break
l=l+1
while alist[r]>pivot:
r=r-1
if l<r:
alist[l],alist[r]=alist[r],alist[l]
else... |
# Copyright 2020 Xilinx Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
#!/usr/bin/env python3
# Match with fasta input file
__appname__ = 'align_seq_fasta.py'
__author__ = 'Olivia Haas o.haas@imperial.ac.uk'
#Import sys
import sys
#seq2 = "ATCGCCGGATTACGGG"
#seq1 = "CAATTCGGAT"
# Assign the longer sequence s1, and the shorter to s2
# l1 is length of the longest, l2 that of the short... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.