text stringlengths 8 6.05M |
|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/6/10 下午3:06
# @Author : Lucas Ma
# @File : getObjInfo
# 获取对象信息
import types
def fn():
pass
print(type(fn)) |
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
"""
Created on 2020/06/30
author: relu
"""
import os
import cv2
import time
import numpy as np
import albumentations as alt
from albumentations.pytorch import ToTensorV2 as ToTensor
# from matplotlib import pyplot as plt
from IPython import embed
def augment_and_show(aug, ... |
import hashlib
from django.template import TemplateDoesNotExist
from django.template.loaders.cached import Loader as DjangoCachedLoader
from django.utils.encoding import force_bytes
from amp_tools import get_amp_detect
from amp_tools.settings import settings
from amp_tools.compat import BaseLoader, template_loader, t... |
pov = dict(nombre="kevin",edad=17,sexo="masculino",intereses="videojuegos")
pov.reaplace[nombre],"JOSUE"
print(pov)
|
#--------------------------------------------------------
#
#trajvars.py
#--------------------------------------------------------
# input classes
class trajectory():
def __init__(self):
self.name=''
self.ID=0
self.numpoints=0
self.numtraj=0
self.grid=[... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2018-10-16 22:57
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('dashboard_app', '0003_auto_20181016_2230'),
]
operat... |
import unicodedata
from datetime import datetime
from django import forms
from django.contrib.auth import (
authenticate, get_user_model, password_validation,
)
from django.contrib.auth.hashers import (
UNUSABLE_PASSWORD_PREFIX, identify_hasher,
)
from django.contrib.auth.models import User
from django.contrib.... |
import random
import requests
import sys
def password():
# Remote accessing a txtfile with list of words using requests library
dictionary = "https://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
response = requests.get(dictionary)
Words = response.content.splitlines()
n... |
# TianTcl - Whisper game - generator
import random
_subject = ["กัปตัน","เทพค้อน","ยักษ์เขียว","เกราะเหล็ก","แมงมุม","มนุษย์มด","ตาเหยี่ยว","เสือดำ"]
ext_sub = ["ตัวจิ๋ว","นักกล้าม","คนเหล็ก","หล่อเหลา","ผู้หิวโหย"]
_verb = ["กำลังบิน","กลิ้ง","คลาน","นอน","เต้น"]
ext_verb = [None,"อย่างรวดเร็ว... |
import PyCapture2
import logging
import numpy as np
def setup_camera():
bus = PyCapture2.BusManager()
num_cams = bus.getNumOfCameras()
logging.info('Number of cameras detected: %d' % num_cams)
if not num_cams:
logging.error('Insufficient number of cameras. Exiting...')
raise ValueError(... |
def check_vowel(string, position):
if position < 0: return False
try:
return string[position].lower() in 'aeiou'
except IndexError:
return False
'''
Check if it is a vowel(a, e, i, o, u,) on the n position in a string
(the first argument). Don't forget about uppercase.
A few cases:
{
ch... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.http.response import HttpResponseRedirect, HttpResponse
from django.urls.base import reverse
from django.utils import timezone
from dj... |
import unittest
from katas.kyu_7.thinking_and_testing_true_or_false import testit as solution
class ThinkingAndTestingTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(solution(0), 0)
def test_equals_2(self):
self.assertEqual(solution(2), 1)
def test_equals_3(self):
... |
import numpy as np
from sklearn import metrics
import argparse
import matplotlib.pyplot as plt
from os import path, makedirs
def compute_accuracies(ranks_file, total_ranks):
rank = np.loadtxt(ranks_file, dtype=np.float)
if np.ndim(rank) == 1:
rank_scores = rank.astype(float)
else:
rank_sc... |
# Generated by Django 3.1.3 on 2021-01-04 14:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0010_auto_20210104_1508'),
]
operations = [
migrations.AddField(
model_name='booking',
name='service',
... |
#Extend#############################################################
def pip(command,value):
try:
import subprocess
subprocess.run('pip %s %s'%(command,value))
except:
raise RuntimeError ("Failed To Load subprocess library")
#Converted####################################################... |
#!/usr/bin/env python
# Copyright (C) 2012 Google 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:
#
# * Redistributions of source code must retain the above copyright
# notice, this list ... |
"""Core views."""
from .admin import (
check_top_notifications, information, logs, logs_page, parameters,
viewsettings
)
from .auth import (
PasswordResetView, dologin, dologout, VerifySMSCodeView,
ResendSMSCodeView, TwoFactorCodeVerifyView
)
from .base import RootDispatchView
from .dashboard import Da... |
# /usr/bin/python3
import argparse
import sys
# from cortx.utils.conf_store import Conf
# from cortx.utils.process import SimpleProcess
# NOTE: used pyyaml and subprocess since cortx-utils is
# not installed on the container.
import yaml
import subprocess
import os
def get_local(config_url):
# Conf.load('C... |
#!/usr/bin/python
# Orthanc - A Lightweight, RESTful DICOM Store
# Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics
# Department, University Hospital of Liege, Belgium
# Copyright (C) 2017-2020 Osimis S.A., Belgium
#
# This program is free software: you can redistribute it and/or
# modify it under the terms ... |
# back tracking problem |
# -*- coding: utf-8 -*-
'''
Tools for loading data from mne's fiff files.
.. autosummary::
:toctree: generated
events
add_epochs
add_mne_epochs
epochs
mne_epochs
Converting mne objects to :class:`NDVar`:
.. autosummary::
:toctree: generated
epochs_ndvar
evoked_ndvar
stc_ndvar
.. cur... |
# coding: utf-8
# Standard Python libraries
from io import IOBase
from pathlib import Path
from typing import Optional, Union
import numpy as np
# https://github.com/usnistgov/atomman
import atomman as am
import atomman.unitconvert as uc
# https://github.com/usnistgov/DataModelDict
from DataModelDict import DataMod... |
import pandas as pd
from sklearn import preprocessing
from preprocessing import read, split, non_numerical_features, one_hot_encoding
from preprocessing import drop_features, deal_with_23 , deal_with_58
from postprocessing import writeoutput
from csv import DictReader, DictWriter
from sklearn.feature_selection import ... |
# 03. pyqt_paint_event.py
# PyQt Paint Event
import sys
from PyQt5.QtGui import QPainter, QPen, QBrush, QColor
from PyQt5.QtCore import QDate, Qt
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
class MyApp(QWidget):
def __init__(self):
super().__init__()
self.setFixedSize(200, 300)
... |
# Flip Flopper
'''
Flip = input("Input Something To Be Flipped: ")
Flip2 = Flip
print(Flip2)
'''
flip = input("Input Something To Be Flipped: ")
def change(input_str):
return input_str[-1] + input_str[1:-1] + input_str[0]
print()
|
import os
import PyPDF2
## create path, reader, and writer objects
path = "sample.pdf"
pdf = PyPDF2.PdfFileReader(path, 'rb')
writer = PyPDF2.PdfFileWriter()
## loop to add all pages in PDF to writer object
for x in range(pdf.numPages):
page = pdf.getPage(x)
writer.addPage(page)
## encrypt method, set user p... |
#!/usr/bin/env python3
# pylint: disable=maybe-no-member
#
# This file is part of LUNA.
#
# Copyright (c) 2020 Great Scott Gadgets <info@greatscottgadgets.com>
# SPDX-License-Identifier: BSD-3-Clause
import sys
import time
from prompt_toolkit import HTML
from prompt_toolkit import print_formatted_text as pprint
from... |
import pytest
@pytest.fixture
def testdir(request):
testdir = request.getfuncargvalue('testdir')
testdir.makeini('[pytest]\ncodechecks = pyflakes')
return testdir
def test_pyflakes_finds_name_error(testdir):
testdir.makepyfile('''
def tesdt_a():
pass
def b():
... |
#!/usr/bin/env python
# encoding: utf-8
from bs4 import BeautifulSoup, Comment
import urllib
import re
# html 标签白名单
VALID_TAGS = {
'strong': [],
'em': [],
'span': {'style', },
'p': [],
'h1': [],
'pre': [],
'h2': [],
'h3': [],
'br': [],
'a': {'href', 'title'},
'img': {'src'... |
#!/usr/bin/python2.7
#-*- coding: utf-8 -*-
import numpy as np
def kalman_filter(data,Q,R,x0,P0):
N = len(data)
K = np.zeros(N)
X = np.zeros(N)
P = np.zeros(N)
X[0] = x0
P[0] = P0
K_i = 0
P_i_1 = P0
X_i_1 = x0
for i in range(1,N):
#rang(1,N) do not contain N
K_i ... |
from Dictionaries import supported_commands, materials_dict, directions_dict
from word2number import w2n
class GameCommand:
def __init__(self):
self.is_valid = False
self.command = None
self.command_token = None
self.command_text = ''
self.args = {}
self.arg_methods = {
'build': self.get_build_args, ... |
import netCDF4 as cdf
import numpy as np
import os
import re
"""
folder paths should end with a forward slash
src: root path of product
dst: destination of product
bounds: bounds of the subset given as [latmin, latmax, longmin, longmax]
"""
def subSetFolder(src, dst, bounds):
FILE_COORDS = "geo_coordin... |
import wx
import re
import os
import collections
import prefs
class World(dict):
_defaults = {
'port' : '7777',
'auto_login' : False,
'login_script' : 'connect %u %p',
}
def __init__(self, data):
data = data or World._defaults
for f in data:
i... |
#!/usr/local/bin/python
from matplotlib import pyplot as plt
from matplotlib.colors import LogNorm
from matplotlib import cm
import seaborn as sns
import numpy as np
import pandas as pd
sp = "100"
lp = "100"
fname = "soft_pf0.2_sp" + sp + "_lp" + lp + "_condensed.density"
df = pd.read_csv(fname, delim_whitespace=True,... |
from datetime import datetime as dt
import re
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
# Class needed for the pipeline to work
class ColumnSelector(BaseEstimator, TransformerMixin):
def __init__(self, columns):
self.columns = columns
def fit(sel... |
from functions import box_volume, ball_volume, pipe_volume
try:
running = True
while running:
shape = int(input("Annan kappaleen muoto:\n"
"(1 = laatikko, 2 = pallo, 3 = putki."
" 0 = lopetetaan ohjelman käyttäminen)\n"))
if shape == 0:
... |
# coding=utf-8
# 批量修改图片尺寸
# imageResize(r"D:\tmp", r"D:\tmp\3", 0.7)
from PIL import Image
import os
def imageResize(input_path, output_path, scale):
# 获取输入文件夹中的所有文件/夹,并改变工作空间
files = os.listdir(input_path)
os.chdir(input_path) #更改为当前路径Input_path
# 判断输出文件夹是否存在,不存在则创建
if (not os.pa... |
#方法一 直接调用
import time
import random
from multiprocessing import Process
def run(name):
print('%s runing' %name)
time.sleep(random.randrange(1,50))
print('%s running end' %name)
p1=Process(target=run,args=('anne',)) #必须加,号
p2=Process(target=run,args=('alice',))
p3=Process(target=run,args=('biantai',))
p4... |
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
nums[:] = [n for n in nums if n != 0] + [0] * nums.count(0)
|
def encode(plain_text):
encoded = ''
chuncksize = 5
for char in plain_text.lower():
encoded += flip(char)
chuncked = ''
counter = chuncksize
for char in encoded:
chuncked += char
counter -= 1
if counter == 0:
chuncked += ' '
... |
import pygame
import math
from pygame.sprite import Sprite
from bullet_ship import Bullet
# There's a bug in invincibilty frame...
class Ship(Sprite):
def __init__(self, main_game_class):
"""Initialize the ship and its starting positions"""
super().__init__()
# Load parent's class necessar... |
from flask_wtf import FlaskForm as Form
from wtforms import PasswordField, StringField, SubmitField, BooleanField, SelectField, IntegerField, FileField, DateTimeField, HiddenField, FloatField
from wtforms.validators import DataRequired, Length, EqualTo, ValidationError, NumberRange, InputRequired
from flask_wtf.file i... |
from redis import StrictRedis
import json
from src import env
CACHED_CARDS = 'cards'
class Redis:
def __init__(self):
self.redis = StrictRedis(
host=env.get_redis_host(),
port=env.get_redis_port(),
password=env.get_redis_password()
)
def get_cached_data(se... |
import module
from pydub.playback import play
from pydub import AudioSegment
import threading
import time
class Pad:
"""
Pad class for playing and modifying sounds
"""
def __init__(self):
"""
Currently empty, can be useful in the future
"""
pass
def play_sound(sel... |
num1 =int(input("첫 번째 수 : "))
num2 =int(input("두 번째 수 : "))
print("%d ** %d = %d"%(num1,num2,num1**num2))
print("%d // %d = %d"%(num1,num2,num1//num2)) #몫
print("%d / %d = %.2f"%(num1,num2,num1/num2)) #나누기
print("%d %% %d = %d"%(num1,num2,num1%num2)) #나머지
#%를 출력할때 %%두번 적어줍니다.
#%가 포맷코드의 시작 글자 => %%적어줘야지 이거 포맷코드가 ... |
import argparse
import sys
def get_args_from_settings(ssettings):
sys.argv=[' '] + ssettings.split()
parser = argparse.ArgumentParser(description='pythia8 fastjet on the fly')
pyconf.add_standard_pythia_args(parser)
parser.add_argument('--output', default="test_ang_ue.root", type=str)
parser.add_ar... |
import pandas as pd
import numpy as np
from pandas import DataFrame
from sklearn import linear_model
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.decomposition import PCA, TruncatedSVD
from sklearn.datasets import load_boston
boston= lo... |
import configparser
from datetime import datetime
import os
from pyspark.sql import SparkSession
from pyspark.sql.functions import *
from pyspark.sql.types import TimestampType
config = configparser.ConfigParser()
config.read('dl.cfg')
os.environ['AWS_ACCESS_KEY_ID']=config['AWS']['AWS_ACCESS_KEY_ID']
os.environ['AWS... |
"""Core authentication views."""
import logging
import oath
from django.conf import settings
from django.http import (
HttpResponse, HttpResponseRedirect, Http404, JsonResponse)
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils import translation
from django.ut... |
# Facebook Msg
verify_token = 'YOUR_VERIFY_TOKEN'
token = "YOUR_TOKEN"
# Database
DATABASE_NAME = 'yumngein'
DATABASE_USER = 'yumngeinadmin'
DATABASE_HOST = 'localhost'
DATABASE_PASSWORD = 'myBestPassword'
DATABASE_STRING_FORM = "postgresql://{}:{}@{}:5432/{}"
DATABASE_STRING = DATABASE_STRING_FORM.format(DATABASE_U... |
def hor_mirror(s):
return '\n'.join(reversed(s.split('\n')))
def vert_mirror(s):
return '\n'.join(a[::-1] for a in s.split('\n'))
def oper(fct, s):
return fct(s)
|
# coding: utf-8
# In[1]:
import numpy as np
import matplotlib.pyplot as plt
# In[2]:
class Neuron(object):
def __init__(self, w_num):
self.input = []
self.output = 0
self.weights = []
self.bias = 0
self.delta = 0
self.bias = np.random.randn()
for i in range(w_num):
self.weights.append(np.rando... |
from django.apps import AppConfig
class TraintestConfig(AppConfig):
name = 'traintest'
|
'''
字符串的切片,str[::-1],实现字符串的反转。
其他的List 等也可以这样实现反转
注意 python3 中的数字已经没有的范围限制,但是要人为的处理 int的范围 -2^31 ~ 2^31 - 1
'''
class Solution:
def reverse(self, x: int) -> int:
if x == 0:
return 0
str_x = str(x)
result = ''
if str_x[0] == '-':
result = result + '-'
... |
###MODULES###
import numpy as np
import pandas as pd
import os, sys
import time as t
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib.ticker import MaxNLocator
import pathlib
from matplotlib.colors import Normalize
from scipy import interpola... |
def is_even(number):
if number % 2 == 0 and number > 0:
return 1
else:
return 0
def print_even_numbers(n):
counter = 0
iteration = 0
while True:
if counter < n:
if is_even(iteration):
print(iteration, end='')
counter... |
# Exercício 9.5 - Livro
with open('txt/pares.txt', 'r') as pares:
valores_pares = pares.readlines()
ultimo = len(valores_pares) - 1
primeiro = -1
for pos in range(ultimo, primeiro, -1):
print(f'{valores_pares[pos]}', end='')
|
# -*- encoding:utf-8 -*-
# __author__=='Gan'
# Write a program to find the nth super ugly number.
# Super ugly numbers are positive numbers whose all prime factors are in the given prime list primes of size k.
# For example, [1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32] is the sequence of the first 12 super ugly
# numb... |
import tkinter
import time
import threading
import math
import sys
class Vertex:
def __init__(self, name, x, y):
self.name = name
self.x = x
self.y = y
self.edges = {}
self.visited = False
self.dist = sys.maxsize
self.parent = None
self.dist_text = N... |
#!/usr/bin/env python
import Keylogger
print("Please enter your gmail's credentials here so that log email can be sent.")
print("")
email = input("Email Address : ")
password = input("Email's password : ")
print("Enter the number of seconds in which you want the email to be sent-")
seconds = input("seconds : ")
# time... |
"""Get EXIF data from a directory of photos"""
from pyexiv2 import Image # type: ignore
import pyexiv2
import os
import re
pyexiv2.set_log_level(4)
def scan_tree(directory: str):
"""Recursively yield DirEntry objects for given directory.
:param directory: A string with the directory to scan for photos.
... |
from tkinter import *
root = Tk()
display = Entry(root)
display.grid(sticky=N,columnspan=50)
def getvarriables(number):
current = display.get()
display.delete(0, END)
display.insert(0, (current) + (number))
def cleardata():
display.delete(0, END)
def add():
first_num = display.get()
global f_num
global math
... |
import boto3
from pprint import pprint
BUCKET = "mygirlfriend"
KEY_SOURCE = "1.jpg"
KEY_TARGET = "2.jpg"
def compare_faces(bucket, key, bucket_target, key_target, threshold=80, region="ap-southeast-2"):
rekognition = boto3.client("rekognition", region)
response = rekognition.compare_faces(
SourceImag... |
import multiprocessing as mp
import queue
import numpy as np
import time
import random
def main():
trainbatch_q = mp.Queue(10)
batchperq = 50
event = mp.Event()
tl1 = mp.Process(target=proc, args=( trainbatch_q, 20, batchperq, event))
print("Got here")
tl1.start()
time.sleep(3)
even... |
"""
An image classifier using a tf.keras.Sequential model and load data using tf.keras.preprocessing.image.ImageDataGenerator
"""
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, Flatten, Dropout, MaxPooling2D
from tensorflow.keras.preprocess... |
class Menu:
def __init__(self, title="Menu", options=["Option 1", "Option 2"]):
self.options = options
self.result = -1
self.title = title
def __str__(self):
result = ""
self.options.append(self.title)
maxLength = int(len(max(self.options, key=len)) + len(str(len(self.options))))
dashes = int((maxLength... |
from dynaconf import Dynaconf
settings = Dynaconf(
load_dotenv=True,
environments=True,
settings_files=['settings.toml'],
{%- if cookiecutter.enable_vault_loader == 'y' %}
loaders=['dynaconf.loaders.vault_loader'],
{%- endif %}
)
|
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 25 19:36:36 2017
@author: anders & torgeir
"""
'''
620031587
Net-Centric Computing Assignment
Part A - RSA Encryption
'''
import random
from datetime import datetime
'''
Euclid's algorithm for determining the greatest common divisor
Use iteration to make it faster for l... |
default_app_config = 'eshop_products_category.apps.EshopProductsCategoryConfig'
|
from __future__ import print_function
import base64
import binascii
import json
import flask
import six
from six.moves import cPickle as pickle
from six.moves import urllib, zip
from smqtk.algorithms import (
get_classifier_impls,
get_descriptor_generator_impls,
SupervisedClassifier
)
from smqtk.algorith... |
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
return 0 if not root else max(self.maxDepth(root.left) + 1, self.maxDepth(root.right)+1) |
#!/usr/bin/python3.4
import os
import sys
import traceback
def pyvercheck():
if sys.version_info < (3, 0):
print("Requires python 3.x, exiting.")
sys.exit(1)
def run():
pyvercheck()
print("Child PID: "+str(os.getpid()))
try:
import ircbot
except ImportError:
print(traceback.format_exc())
print("Canno... |
def subset_select(data):
set_size = {1: [data[:, :1], data[:, 1:2], data[:, 2:3], data[:, 3:4], data[:, 4:5], data[:, 5:6], data[:, 6:]]}
temp_list = []
for i in range(7):
for j in range(7):
if i < j:
temp_list.append(data[:, [i, j]])
set_size[2] = temp_list
... |
#This module contains to infrastructure for handling communication with the VERITAS database
import pymysql
import datetime
class DBConnection:
def __init__(self, *args, **kwargs):
#Extract the database information from the configuration dictionary
configdict=kwargs.get('configdict')
self.host=configdict.get('... |
# Copyright 2019 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import os
import subprocess
from io import BytesIO
from textwrap import dedent
from zipfile import ZipFile
import pytest
from pants.backend.google_clo... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
class data():
'''
class used to generate cleaned data
'''
def __init__(self, initial_data):
self.initial_data = initial_data
# function used to clean data
def clean_data(self):
df = self.initial_data[['CAMIS', 'BORO', 'GRADE', 'GR... |
import copy
from board import Board
from dice import Dice
class Game:
colors = ['blue', 'red', 'green', 'yellow']
max_players = 4
max_rounds = 15
def __init__(self):
self.players = []
self.board = Board()
def add_player(self, player):
if len(self.players) < self.max_play... |
def kruskal(G):
E = [(G[u][v], u, v) for u in G for v in G[u]]
T = set()
vertex = set()
E = sorted(E)
for _, u, v in E:
if len(T) == len(G) - 1:
return T
else:
if u and v in vertex:
continue
else:
T.add((u, v))
... |
print("my first pgm") |
from django.db import models
def format_filename(format_string):
"""
Takes a Django format string like
"/a/path/{instance.lol}/"
and returns a function for the FileField
"""
def upload_to(instance, filename):
return format_string.format(obj=instance, filename=filename)
return... |
'''
Created on Apr 21, 2017
@author: andrewbloomberg
'''
from bs4 import BeautifulSoup
import urllib2
import re
from urllib2 import URLError
import json
if __name__ == '__main__':
file = open('buildings_and_addresses.txt', 'r')
lines = file.readlines()
buildings = []
for line in lines:
split =... |
#!/usr/bin/python
import os
import sys
import StringIO
import unittest
from mic import msger
def suite():
return unittest.makeSuite(MsgerTest)
class MsgerTest(unittest.TestCase):
def setUp(self):
self.stdout = sys.stdout
self.stderr = sys.stderr
sys.stdout = StringIO.StringIO()
... |
import argparse
import configparser
DEFAULT_CONFIG = 'config.ini'
import datetime
from pandas_datareader import get_data_tiingo
import pickle
def settings(args):
# Settings configuration, defaults can be changed in the config file
config = configparser.ConfigParser()
if args.config_file is None:
... |
""" Extract multiple 2D surfaces from a cube by controllably removing non-crucial amplitude information. """
#pylint: disable=import-error, no-name-in-module, wrong-import-position
from copy import copy
import numpy as np
from scipy.ndimage import sobel
from .base import BaseController
from ..labels import Horizon
f... |
"""
Definition of views.
"""
from datetime import datetime
from django.shortcuts import render
from django.http import HttpRequest,JsonResponse, HttpResponse
import requests
from . models import Place
def search_view(request):
# response = requests.get('https://places.ls.hereapi.com/places/v1/autosuggest?at=40... |
from django.shortcuts import render
from django.views.generic import ListView
from .models import Event
class MainPage(ListView):
model = Event
template_name = 'mainapp/index.html'
context_object_name = 'events'
|
#!/usr/bin/env python
# coding=utf-8
from torch.utils.data import Dataset
from torchvision import transforms
import skimage.io as io
import torch
import matplotlib.pyplot as plt
class PETADataset(Dataset):
def __init__(self,img_list_path,transform=None):
self.img_list_path = img_list_path
self.tra... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Artist',
fields=[
('id', models.AutoField(verbo... |
def crawler(nombreFichero):
print("El fichero ha sido introducido correctamente")
|
from functools import reduce
from collections import Counter
import itertools
puzzle = [int(line.rstrip('\n').split) for line in open('input.txt')]
# with open('input.txt', 'r') as myfile:
# puzzle = myfile.readlines()
# total = 0
# print(reduce(lambda sum, x: sum + x[0] if else sum, puzzle, 0))
# for line... |
from .print import print
def render(t, padding=''):
"""Render an ASCII table"""
# Convert all to strings
t = [[str(cell) for cell in row] for row in t]
# Ensure table has same dimensions
for row in t:
assert len(row) == len(t[0])
# Get column widths
widths = [0 for _ in t[0]]
... |
import random
import time
import os
import sys
from Quartz.CoreGraphics import CGEventCreateMouseEvent
from Quartz.CoreGraphics import CGEventPost
from Quartz.CoreGraphics import kCGEventMouseMoved
from Quartz.CoreGraphics import kCGEventLeftMouseDown
from Quartz.CoreGraphics import kCGEventLeftMouseDown
from Quartz.Co... |
# Copyright (c) 2021 Mahdi Biparva, mahdi.biparva@gmail.com
# miTorch: Medical Imaging with PyTorch
# Deep Learning Package for 3D medical imaging in PyTorch
# Implemented by Mahdi Biparva, April 2021
# Brain Imaging Lab, Sunnybrook Research Institute (SRI)
import torch
import torch.nn as nn
import torch.nn.funct... |
#Funcoes e variaveis
#1 - Lista de compras
carrinho = []
#2 - Criar funcao para adicionar itens
def adiciona_item(valor):
carrinho.append(valor)
#2 - funcao total carrinho
def total_carrinho(lista_compras):
for intem in lista_compras:
soma += soma
retorn soma
|
import sys, logging
import subprocess
import json
import binascii
import numpy as np
from bitcoin import SelectParams
from bitcoin.core import b2x
from bitcoin.core.script import *
from bitcoin.wallet import *
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(levelname)-2s %(name)-2s %(module)s@%(lineno)... |
from __future__ import division, print_function
import abc
import logging
import json
import math
import mimetypes
import multiprocessing
import multiprocessing.pool
import os
import os.path as osp
import subprocess
import sys
import tempfile
import six
import numpy
import six
import sklearn.cluster
from smqtk.algori... |
from django.core.exceptions import ValidationError
from django.shortcuts import render, redirect
from django.http import HttpResponse
# from django.shortcuts
from lists.forms import ItemForm
from lists.models import Item, List
# Create your views here.
def home_page( request ):
return render(
request,
'home.... |
from itertools import groupby
def double_check(s):
return any(sum(1 for _ in g) == 2 for _, g in groupby(s.lower()))
# from re import compile, search
#
# REGEX = compile(r'(.)\1')
#
#
# def double_check(s):
# return bool(search(REGEX, s.lower()))
|
# 用户
from Gamer.models import User
import json as simplejson
from django.views.generic import View
from django.http import JsonResponse
class Username(View):
# username
def post(self,request,*args,**kwargs):
# username = request.POST.get('username')
req = simplejson.loads(request.body.decode('u... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.