text stringlengths 8 6.05M |
|---|
from flask import render_template
import re
import json
from .. import db
from ..work import views
from ..auth import logic as auth
from ..models import Work, Chapter, Tag, User, TagType, Bookmark, BookmarkLink, Message
def add_message(json):
message = Message(to_user_id = json["to_user"], from_user_id = json["from_u... |
N = int( input())
X = list( map( int, input().split()))
X.sort()
ans = 0
for i in range(N):
ans += X[i]*i - X[i]*(N-1-i)
print(ans)
|
import sys,os,cherrypy
sys.path.append("../.")
import unittest
import requestflow
class TestTracer(unittest.TestCase):
def deejay_output(self,request):
# Given a request, return the tracking-Id by tracer
tracer = requestflow.Tracer(service_name='deejay', aggregate_traces=True, enable_tracing=False, en... |
from typing import List
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
def sink(i):
while 2 * i + 1 <= k - 1:
j = 2 * i + 1
if j + 1 < k - 1 and nums[j + 1] < nums[j]:
j += 1
if nums[i] < nums[j]:
... |
import numpy as np
import matplotlib.pyplot as plt
import pandas
import statsmodels.api as sm
import scipy
# For 3d plots. This import is necessary to have 3D plotting below
from mpl_toolkits.mplot3d import Axes3D
# For statistics. Requires statsmodels 5.0 or more
from statsmodels.formula.api import ols
# Analysis of... |
from sqlalchemy import create_engine
import pymysql
import pandas as pd
pymysql.install_as_MySQLdb()
'''
Connection string is built as follows:
dialect://username:password@fullendpoint/database_name
dialect: The sql dialect that is being used.
username: The username to log into the database.
password: The... |
from django.test import TestCase
from books.models import Book
class BookTestCase(TestCase):
def setUp(self):
Book.objects.create(title="Test book", author="Test author", price=1, amount=3)
def test_book_must_have_author(self):
test_book = Book.objects.get(title="Test book")
self.asse... |
#######################################################################
## Este driver se encarga de las comunicacion ##
#######################################################################
## Importación de modulos
import json, requests, os
class CommunicationDriver:
## Constructor
def __... |
class City:
crime = 100
def __init__(self, poverty):
self.crime +=poverty
print(self.crime)
def aggresive_peace(self, police_budget):
self.crime -= police_budget/2
print(self.crime)
def gradual_peace(self,welfare_budget):
self.crime -= welfare_budget
print... |
import json
class JsonSerializer(object):
@classmethod
def SerializeObject(self, data):
if isinstance(data,dict):
s = json.dumps(data)
else:
s = json.dumps(data.__dict__)
return s
@classmethod
def DeserializeJson(self, json_string, object_to_serialize... |
class RedisMiddleware:
def __init__(self, redis):
self._redis = redis
async def process_resource(self, req, resp, resource, params):
req.context.redis = self._redis
|
from random import random
from math import ceil, floor
TRIALS = 10000
trial = 0
one_count = 0
two_count = 0
while (trial < TRIALS):
trial += 1
x = ceil(random() * 2)
if x == 1:
one_count += 1
elif x == 2:
two_count +=1
print(f"Number of 1s rolled: {one_count}\nNumber of 2s roled: {two_count}")
|
from collections import Counter
from itertools import chain, tee, izip
from codecs import open
import sys
def main(corpus, num_blockwords):
minimum_blockword_length = 3
maximum_blockword_length = 4
blocks_per_line = 4
blockwords = []
if num_blockwords > 0:
blockwords = get_blockwords(corpu... |
import numpy as np
import sys
import math
import operator
import csv
import glob,os
import xlrd
import cv2
import pandas as pd
import os
import glob
from sklearn.svm import SVC
from collections import Counter
from sklearn.metrics import confusion_matrix
import scipy.io as sio
from keras.models import Sequential, Mod... |
def repLength(n):
rems = []
extra = 0
num = 10
while num not in rems:
rems += [num]
while num < n:
num *= 10
extra += 1
num %= n
num *= 10
if not num: return 0
#print(rems, extra)
return len(rems)+extra
def indOfMax(ls):
retur... |
import maya.cmds as cmds
# ah_PromptWindows
def two_button_confirm_prompt(windowTitle, userMessage, button1, button2):
confirm = cmds.confirmDialog(title=windowTitle, message=userMessage, button=[button1, button2],
defaultButton=button1, cancelButton=button2, dismissString=button2... |
import unittest
from random import randint
def backward_merge(a, b):
"""a has enough buffer to hold b at the end so merge a and b backwards."""
i = len(b) - 1
j = len(a) - len(b) - 1
end = len(a) - 1
while i > -1:
if j > -1 and a[j] > b[i]:
a[end] = a[j]
j -= 1
... |
"""
Program creates triangle out of chaos game algorithm
Each subexercise is ordered as function for readability and part-by-part
execution
"""
import numpy as np
import math as m
import matplotlib.pyplot as plt
# A) Create three points. Chose to turn it
def subexerA():
"""Function runs solutions for exerci... |
from datetime import date
from celery.task import periodic_task
from dateutil.relativedelta import relativedelta
from django.contrib.auth.models import User
from django.utils.timezone import utc, datetime, timedelta
from .utils import *
from intent.apps.query.models import Rule, Author, Query, Document, DailyStat
fr... |
#!/usr/local/anaconda3/bin/python3
from __future__ import division
import sys
sys.path.insert(0, '/home/machen/face_expr')
from ROI_nets.extensions.speed_evaluator import SpeedEvaluator
from ROI_nets.model.vgg19 import ROI_NetsVGG19
try:
import matplotlib
matplotlib.use('agg')
except ImportError:
pass
... |
#!/usr/bin/python2
# -*- coding: utf-8 -*
#ref_to_md
from Crypto.Cipher import AES
import binascii
def crypterTexte(texte):
encodeur = AES.new("FAU8PdmPi7dxXFc9", AES.MODE_CBC, "84yD8kXUiZsyc22n")
texte += "\0" * (16 - (len(texte) % 16))
texte_code = binascii.b2a_hex(encodeur.encrypt(texte))
return te... |
import pytest
@pytest.allure.feature('Nodes')
@pytest.allure.story('Webform CT')
@pytest.mark.usefixtures('init_webform_page')
class TestWebformCT:
@pytest.allure.title('VDM-1267 Webform CT - creation')
def test_webform_ct_creating(self):
self.node.fill_webform_mandatory()
url = self.driver.c... |
__author__="Sara Farazi"
import re
import sys
import pdb
import math
import json
import time
import math
from collections import defaultdict
from cell import Point, Coordinates, Cell
from summary import Summary, Counter
from nltk.corpus import stopwords
from scipy.optimize import minimize_scalar
from geopy.distance im... |
from selenium.webdriver.common.by import By
from pages.BasePage import BasePage
class MainPage(BasePage):
URL='https://jqueryui.com/droppable/'
IFRAME = (By.CLASS_NAME, 'demo-frame')
SQUARE = (By.ID, 'draggable')
BOX = (By.ID, 'droppable')
def open_main_page(self):
super().open_url(self.U... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# _Author_: xiaofeng
# Date: 2018-04-10 12:08:06
# Last Modified by: xiaofeng
# Last Modified time: 2018-04-10 12:08:06
'''
原始仓库网络结构进行测试
'''
from PIL import Image
import tensorflow as tf
import os
import sys
import matplotlib as mpl
mpl.use('TkAgg')
from matplotlib import p... |
"""invproject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/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-ba... |
import bpy
class MoveBoneToHead(bpy.types.Operator):
"""Tooltip"""
bl_idname = "object.move_bone_to_head_operator"
bl_label = "Simple Object Operator"
def execute(self, context):
armature = context.active_object
dest_bone = context.active_bone
# find dest bone... |
# db 연동
# python + mysql 연동
# pip install pymysql
# 차후에는 sqlAlchemy 모듈을 설치하여 pymysql을 Wrapping 하여 사용
import pymysql as my
# 연결
connection = my.connect(host='localhost',
user='root',
password='0000',
db='pythondb',
... |
from .views import Filesystem, UploadFolder, DownloadFolder, FolderPicker, PartialDownload
from django.urls import path
urlpatterns = [
path('', Filesystem.as_view(), name="filesystem"),
path('upload-folder/', UploadFolder.as_view(), name="upload-folder"),
path('download/', DownloadFolder.as_view(), name=... |
if isinstance(0, int): print('some')
some = set()
other = set()
some.update(other)
pass |
"""
Author: Moustafa Alzantot (malzantot@ucla.edu)
"""
import tensorflow as tf
def reset_graph():
'''reset graph. if session is on, close it'''
sess = tf.get_default_session()
if sess:
sess.close()
tf.reset_default_graph()
def fully_connected(input_node, num_outputs, scope=None):
""" Implem... |
from scipy import special
from scipy import optimize as o
from scipy import integrate
from scipy.interpolate import interp1d
from scipy.interpolate import griddata
from matplotlib import pyplot as plt
import scipy
from socks import method
"""-----------------minimize----------------------------------"""
"""Simple conv... |
#-*- conding:utf-8 -*-
'''
Un programa que lea los datos de un usuario (nombre & la edad)
posteriormente a que los lee.
imprimira la cadena como en el siguiente ejemplo:
Hola 'Enrique' tu edad es: 22
'''
nombre = raw_input('EScribe tu nombre: ')
edad = raw_input('por favor ingresa tu edad: ')
pri... |
#!/usr/bin/python
#\file close_dialog.py
#\brief certain python script
#\author Akihiko Yamaguchi, info@akihikoy.net
#\version 0.1
#\date Apr.01, 2017
# http://stackoverflow.com/questions/14834494/pyqt-clicking-x-doesnt-trigger-closeevent
import sys
from PyQt4 import QtGui, QtCore, uic
class MainWindow(QtGu... |
import numpy as np
import cv2
import sys
# cap = cv2.VideoCapture('2017_06_23_1430_Falen_Cigaren_mod_byen.mp4')
cap = cv2.VideoCapture('2015_06_27_1630_Krydset_Motorvejsafkørsel_52.mp4') # 35 / 6 / 2
# cap = cv2.VideoCapture('KrydsetFaaborgvejSanderumvej1.mp4')
cv2.namedWindow("frame", cv2.WINDOW_NORMAL)
cv2.namedWin... |
import os
import site
import sys
import logging
import maya.cmds as cmds
logger = logging.getLogger(__file__)
from .menu import build_menu
from .assets import assets_dir, set_assets_dir
def add_vendor_to_path():
pb_tools = os.path.dirname(__file__)
vendor_path = os.path.join(pb_tools, "..", "..", "..", "ve... |
from sm import PDA ,CFG
filename = 'in.txt'
file = open(filename, 'r')
lines = file.readlines()
file.close()
pda = PDA()
cfg = CFG ()
pda.construct_pda_from_file(lines)
# part 1
filename2 = 'out.txt'
wrfile = open(filename2 ,'w+')
cfg.convert_from_pda(pda , wrfile)
# part 2
inputtext = "abba"
cfg.detect_word(inputtex... |
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
math = vtk.vtkMath()
math.RandomSeed(22)
sphere = vtk.vtkSphereSource()
sphere.SetPhiResolution(32)
sphere.SetThetaResolution(32)
extract = vtk.vtkExtractPolyDataPiece()
extract.Set... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
from lozapp.models import Categorie, Address
from userena.models import UserenaBaseProfile
from django.utils.translation import ugettext as _
class LozProfil... |
import numpy as np
from random import shuffle
def svm_loss_vectorized(W, X, y, reg):
"""
Structured SVM loss function, vectorized implementation.
Inputs:
- W: K x D array of weights
- X: D x N array of data. Data are D-dimensional columns
- y: 1-dimensional array of length N with labels 0...K-1, for K clas... |
from django.conf.urls import patterns, url
from user import views
urlpatterns = patterns(
'',
url(r'^create/$', views.create, name='create'),
# ex: /user/5/
url(r'^edit/(?P<user_id>\d+)/$', views.edit, name='edit'),
url(r'^login/$', views.login, name='login'),
url(r'^logout/$', views.logout, n... |
import json
import os
import pandas as pd
from autumn.settings import Region
base_dir = os.path.dirname(os.path.abspath(os.curdir))
HOSP_DATA_FILE = os.path.join(
base_dir, "data", "inputs", "hospitalisation_data", "european_data.csv"
)
COUNTRY_TARGETS = {
Region.BELGIUM: ["bel_hosp_adm_per_100K", "new_hosp... |
#import sys
#input = sys.stdin.readline
# def gcd(a, b):
# while b != 0:
# a, b = b, a % b
# return a
def main():
N = int(input())
A = list(map(int,input().split()))
ans = 2
gcd_deg = 0
for k in range(2,1001):
deg = 0
for a in A:
if a%k == 0:
... |
from datetime import datetime
from gevent.queue import Queue
from BusinessCentralLayer.middleware.redis_io import RedisClient
from config import *
# 工作栈
class Middleware:
# cache of redis
zeus = Queue()
# Trash
apollo = Queue()
theseus = {}
# work
poseidon = Queue()
def markup_admin_e... |
from urllib.parse import urljoin
# URLs
OKEX_BASE_URL = "https://www.okex.com/"
OKEX_SYMBOLS_URL = urljoin(OKEX_BASE_URL, "api/spot/v3/instruments/ticker")
OKEX_DEPTH_URL = urljoin(OKEX_BASE_URL, "api/spot/v3/instruments/{trading_pair}/book")
OKEX_PRICE_URL = urljoin(OKEX_BASE_URL, 'api/spot/v3/instruments/{tradin... |
# *args treats as a tuple. WE can pass as many args as we want.
def myfunc(*args):
print(args)
myfunc(40,60,30,60)
#args can be any other keyword
def myfunc(*spam):
for item in spam:
print(item)
myfunc(4,5,6,7,8)
# ** kwargs Key worded arguments
def myfunc(**kwargs):
if 'fruit' in kwargs:
print('Myfru... |
from src.animation import *
from src.object import *
from src.GameBody import *
from src.tools import *
from src.UITools import *
from src.font import *
NON_RENEWABLE = 1
RENEWABLE = 2
class mine(object):
def __init__(self, image, info, type):
object.__init__(self, image, "normal")
self.MINDIST = ... |
from rest_framework import serializers
from .models import (Customer, CustomerInfo, Order,
Pizza, PizzaDetail, PizzaOrder)
class CustomerInfoSerializer(serializers.ModelSerializer):
id = serializers.UUIDField(source='customer.id', required=False)
name = serializers.CharField(source='cust... |
print("100000")
for i in range(50000): print("2147483647")
for i in range(49900): print("-2147483647")
for i in range(100): print("-2147483646") |
import sys
import gc
import getopt
import os.path
import traceback
from threading import Thread
import PyQt4.uic as uic
# SUBJECT, OBSERVER, DISPATCHER, THREADEDDISPATCHER
from application.lib.base_classes1 import *
from application.lib.com_classes import * # SINGLETON, RELOADABLE
from application.lib.h... |
# 참고 : https://seolin.tistory.com/93
import os
import glob
from pytube import YouTube
# 유튜브 전용 인스턴스 생성
par = 'https://www.youtube.com/watch?v=TWj-8_-XnaU'
yt = YouTube(par)
print(yt.title)
# 화질 확인
for e in yt.streams.filter(file_extension='mp4').all():
print(str(e))
# 음성이 없는 영상 다운로드
# order_by('resolution').de... |
import data_filters
import webapp2
import jinja2
import os
import json
import logging
from urllib import quote, urlencode
from google.appengine.api import urlfetch
from google.appengine.api import memcache
from collections import namedtuple
jinja_environment = jinja2.Environment(
loader=jinja2.FileSystemLoader(o... |
'''
Created on Apr 10, 2016
@author: chunq
'''
import datetime
class Animal(object):
def __init__(self, name, time):
self.name = name
self.time = time
class Dog(Animal):
pass
class Cat(Animal):
pass
class AnimalShelter(object):
def __init__(self):
... |
# 114. Flatten Binary Tree to Linked List
#
# Given a binary tree, flatten it to a linked list in-place.
#
# For example, given the following tree:
#
# 1
# / \
# 2 5
# / \ \
# 3 4 6
# The flattened tree should look like:
#
# 1
# \
# 2
# \
# 3
# \
# 4
# \
# 5
# ... |
"""
Discrete Fourier Transforms - helper.py
"""
# Created by Pearu Peterson, September 2002
__all__ = ['fftshift','ifftshift','fftfreq']
from numpy.core import asarray, concatenate, arange, take, integer, empty
_integer_types = int, integer, int
def fftshift(x,axes=None):
"""
Shift the zero-fre... |
# Testing Taxonomies:
# https://wiki.python.org/main/PythonTestingTollsTaxonomy
# Python Unittesting
# https://docs.python.org/3/library/unittest.html
import unittest
from w2day001 import moo
# moo(2)
class TestMoo(unittest.TestCase):
def test0(self):
self.assertEqual(moo(0), '')
def test1(self):
self.assert... |
# coding: utf-8
import pytest
import sys
from faults import ImproperlyConfigured
from mock import patch, mock_open
from decouple import ConfigIni
# Useful for very coarse version differentiation.
PY3 = sys.version_info[0] == 3
if PY3:
from io import StringIO
else:
from StringIO import StringIO
INIFILE = ''... |
#!/usr/bin/env python
import re
import sys
import time
from collections import defaultdict
from datetime import datetime
from optparse import OptionGroup, OptionParser
from reddit import Reddit
from reddit.errors import ClientException
from reddit.objects import Comment
DAYS_IN_SECONDS = 60 * 60 * 24
MAX_BODY_SIZE = ... |
from ..base import *
from ..text import Text
from ..button import *
from ..menu import Menu
from ..dialog import *
from ..scroll import *
class BackgroundDialog(Dialog):
def __init__(self):
extra_button_data = (("Apply", "", self.__on_yes, None, 1.),)
Dialog.__init__(self, "View background", "o... |
import torch
import torch.nn.functional as F
import numpy as np
from math import pi
from .utils import HelperModule
class NoiseMode:
LINEAR = 'linear'
COSINE = 'cosine'
class Diffuser(HelperModule):
def build(self,
nb_timesteps: int = 1000,
mode: NoiseMode = NoiseMode.COSIN... |
#!/usr/bin/env python
import rospy
from std_msgs.msg import Int32
from std_msgs.msg import Int32MultiArray
from std_msgs.msg import String
import arbotix_msgs.msg
from actionlib_msgs.msg import *
import json
import random
import os
class RobotController:
# class to process robot controller
def __init__(self... |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 11 19:03:17 2016
@author: Vaibhav
"""
import pickle as pick
from sklearn.feature_extraction.text import TfidfVectorizer
word_data = pick.load(open('your_word_data.pkl','r'))
print word_data[0]
vectorizer = TfidfVectorizer(stop_words='english')
word_data_trans... |
class Solution:
def spiralOrder(self, matrix):
res = []
while len(matrix) and len(matrix[0]):
if len(matrix):
res.extend(matrix.pop(0))
if len(matrix) and len(matrix[0]):
for i in matrix:
res.append(i.pop(-1))
if... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
#Importação de bibliotecas necessárias
from pytube import YouTube
import moviepy.editor as mp
import re
import os
# In[ ]:
#Insira o link do vídeo que você quer o mp3 e o diretório que o arquivo será salvo
link = input("Digite o link do vídeo que deseja baixar: ")
... |
from Constants import BinaryOps, UnaryOps
class VMWriter:
_ops_map = {
BinaryOps.ADD: 'add',
BinaryOps.SUB: 'sub',
BinaryOps.MULT: 'call Math.multiply 2',
BinaryOps.DIV: 'call Math.divide 2',
BinaryOps.AND: 'and',
BinaryOps.OR: 'or',
BinaryOps.LT:... |
import json
import logging
import os
import sys
import tempfile
import warnings
from contextlib import contextmanager
from contextlib import suppress
import joblib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import sklearn
import tensorflow as tf
import yaml
from quest... |
from django.shortcuts import render
# Create your views here.
def pagina_inicial(request):
context = {"nome": "Camila",
"gatos": ["bilbo", "tigrinho", "felix", "zeus", "darko"]
}
return render(request, 'index.html', context)
|
import re
from os import environ, makedirs
from shutil import copy
import logging
from subprocess import run, Popen, PIPE, STDOUT
from pathlib import Path
from importlib.resources import read_text
from string import Template
from typing import Optional, Iterable, Set, List, Any, Tuple, OrderedDict as OD
from collection... |
#!/usr/bin/env python
# -*-python-*-
#
# Copyright (C) 1999-2017 The ViewCVS Group. All Rights Reserved.
#
# By using this file, you agree to the terms and conditions set forth in
# the LICENSE.html file which can be found at the top level of the ViewVC
# distribution or at http://viewvc.org/license-1.html.
#
# For mor... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
from ..core import AvaError
class DataError(AvaError):
"""
Generic error related to database operations.
"""
def __init__(self, *args, **kwargs):
super(DataError, self).__init__(*args, **kwargs)
... |
TOPICS = {'1': 'ordinary_life', '2': 'school_life',
'3': 'culture_education', '4': 'attitude_emotion',
'5': 'relationship', '6': 'tourism', '7': 'health',
'8': 'work', '9': 'politics', '10': 'finance'}
ACTS = {'1': 'inform', '2': 'question', '3': 'directive', '4': 'commissive'}
EMOS = ... |
import scrapy
import json
from thebodyshop.items import Product
import urlparse #to extract PID from fk_url
class FkProductSpider(scrapy.Spider):
name = 'bs'
allowed_domains = ['www.thebodyshop.in']
start_urls = [
'http://www.thebodyshop.in/pages/Bath--Body-Care-Products---The-Body-Shop-India/p... |
import sys
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torchdiffeq import odeint_adjoint as odeint
class LatentODE(nn.Module):
'''
Continuous ODE representation
'''
def __init__(self, input_size=1024,
hidden_size=1024,
... |
N, K = map( int, input().split())
ANS = [0]*(N+1)
for i in range(1,N+1):
if i >= K:
ANS[i] = 1
a = i
t = 0
while a < K:
a *= 2
t += 1
ANS[i] = 2**(-t)
print(sum(ANS)/N)
|
import csv
import PIL
from PIL import Image
import numpy as np
np.set_printoptions(threshold=np.inf)
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import cv2
import os
import pandas as pd
def convert_img_to_csv(dirname):
path = dirname + '/Image_ori' + '/'
with open('data/csv_convert1.csv',... |
from typing import (
List,
Tuple,
)
from decimal import Decimal
from hummingbot.strategy.market_trading_pair_tuple import MarketTradingPairTuple
from hummingbot.strategy.celo_arb.celo_arb import CeloArbStrategy
from hummingbot.strategy.celo_arb.celo_arb_config_map import celo_arb_config_map
def start(self):
... |
"""测试API"""
from typing import Any, Dict
import pytest
from flask import Flask
from flask.views import MethodView
from flask_smorest import Api, Blueprint
from flask_sqlalchemy import BaseQuery
from marshmallow import Schema
from smorest_sfs.extensions.api.decorators import paginate
from smorest_sfs.extensions.sqla i... |
from django.conf.urls import include, url, patterns
from . import views
urlpatterns = patterns ('',
) |
#!/usr/bin/python
from util import inclusion_exclusion
print inclusion_exclusion(3,5,999)
|
from data.configs.YAMLConfigLoader import YAMLConfigLoader
from framework.usecases.UseCase import UseCase
class LoadConfigurationUseCase(UseCase):
"""Use case for loading configuration."""
def __init__(self):
"""Create use case for configuration loading."""
super().__init__()
self._co... |
# /usr/bin/env python
# -*- coding:utf-8 -*-
import queue
import random
class Queue:
def __init__(self):
self.items = []
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
def is_... |
import os
os.environ["OMP_NUM_THREADS"] = "1"
os.environ["OPENBLAS_NUM_THREADS"] = "1"
os.environ["MKL_NUM_THREADS"] = "1"
os.environ["VECLIB_MAXIMUM_THREADS"] = "1"
os.environ["NUMEXPR_NUM_THREADS"] = "1"
import argparse
from pathlib import Path
from tempfile import mkstemp
import numpy as np
import torch
from scipy... |
import os
#遍历文件夹下的所有文件和文件夹
def loop_dir_files(path):
g = os.walk(path)
for path, dir_list, file_list in g:
print('path->'+path)
for dir_name in dir_list:
print('dir->'+os.path.join(path, dir_name))
for file in file_list:
print('file->'+os.path.join(path, file)... |
from onegov.user.collections.group import UserGroupCollection
from onegov.user.collections.user import MIN_PASSWORD_LENGTH
from onegov.user.collections.user import UserCollection
__all__ = [
'MIN_PASSWORD_LENGTH',
'UserCollection',
'UserGroupCollection'
]
|
with open("mojplik.txt") as plik:
#blok kodu, pamietam o zaglebieniu
print(plik.read())
print("Nie musze pamietac o zamknieciu!")
|
from datetime import datetime
import backtrader as bt
from backtrader import talib
class RsiSignalStrategy(bt.SignalStrategy):
params = dict(rsi_periods=14, rsi_upper=70, rsi_lower=30, rsi_mid=50)
def __init__(self):
rsi = bt.indicators.RSI(period=self.p.rsi_periods,
up... |
"""
Entry point for IDE users to run an application.
"""
from autumn.settings import Region, Models
from autumn.core.project import get_project, run_project_locally
region = Region.NORTHERN_TERRITORY
model = Models.SM_SIR
project = get_project(model, region)
# Run a model manually
run_project_locally(project, run_s... |
#! /usr/bin/env python
from bwi_planning import ActionExecutor
from segbot_gui.srv import QuestionDialogRequest
from map_mux.srv import *
import rospy
import time
from .atom_coffee import AtomCoffee
class ActionExecutorCoffee(ActionExecutor):
def __init__(self, dry_run=False, initial_file=None):
super(... |
from rest_framework import viewsets
from api.suids.serializers import SuidSerializer
from api.base import ShareViewSet
from share.models import SourceUniqueIdentifier
class SuidViewSet(ShareViewSet, viewsets.ReadOnlyModelViewSet):
serializer_class = SuidSerializer
ordering = ('id', )
def get_queryset(... |
from ED6ScenarioHelper import *
def main():
# 格兰赛尔
CreateScenaFile(
FileName = 'C4102 ._SN',
MapName = 'Grancel',
Location = 'C4102.x',
MapIndex = 1,
MapDefaultBGM = "ed60021",
Flags = 0,
... |
import numpy as np
import tensorflow as tf
from collections import OrderedDict, defaultdict
from bgan_util import AttributeDict
#### Bayesian DCGAN
from dcgan_ops import *
def conv_out_size_same(size, stride):
return int(math.ceil(float(size) / float(stride)))
class BGAN(object):
def __init__(self, x_d... |
import math
x,y = input().split()
print(math.ceil(int(y)/int(x)))
|
"""The application's model objects"""
import datetime
import sqlalchemy as sa
from sqlalchemy import orm
from sqlalchemy.ext.declarative import declarative_base
from networkpinger.model import meta
Session = meta.Session
def init_model(engine):
"""Call me before using any of the tables or classes in the model"""... |
from BFT.positional_embeddings.positional_embedding import BasePositionalEmbedding
from torch import nn
from BFT.utils import flatten
import torch
import math
class SinusoidalElapsedTimeEmbedding(BasePositionalEmbedding):
def __init__(self, positional_embedding_size, num_channels,
dataloader_gene... |
from onegov.form.forms.named_file import NamedFileForm
__all__ = (
'NamedFileForm',
)
|
import sensor, image, time
from pid import PID
from pyb import Servo
from pyb import UART
red_threshold = [(14,26,6,24,3,20)]
sensor.reset() # Initialize the camera sensor.
sensor.set_pixformat(sensor.RGB565) # use RGB565.
sensor.set_framesize(sensor.QQVGA) # use QQVGA for speed.
sensor.skip_frames(10) # Let new ... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 6 16:41:10 2020
@author: L0GYKAL
"""
import time
from pycoingecko import CoinGeckoAPI
from telegram.ext.commandhandler import CommandHandler
from telegram.ext.updater import Updater
from telegram.ext.dispatcher import Dispatcher
from telegram.update import U... |
# -*- coding: utf-8 -*-
from django import template
from django.utils import timezone
from django.core.urlresolvers import reverse
register = template.Library()
@register.simple_tag(takes_context=True)
def active(context, url_name, *url_params):
if url_params and reverse(url_name, args=url_params) == context['re... |
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
import time
import math
def calc(x):
return str(math.log(abs(12 * math.sin(int(x)))))
def calc_value(browser):
x... |
from rest_framework import serializers
from vocabulary.models import Vocabulary
class VocabularySerializer(serializers.Serializer):
word = serializers.CharField(max_length=100, allow_blank=False, trim_whitespace=True)
meaning = serializers.CharField(max_length=100, allow_blank=False, trim_whitespace=True)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.