text stringlengths 8 6.05M |
|---|
"""
Time Complexity = O(N)
Space Complexity = O(1)
"""
class Solution:
def minDistance(self, height: int, width: int, tree: List[int], squirrel: List[int], nuts: List[List[int]]) -> int:
def distance(a, b):
return abs(a[0]-b[0]) + abs(a[1]-b[1])
dst = 0
min_d = ... |
"""
Importing Hyper.ag data using Azure FunctionApp.
"""
from datetime import datetime, timedelta, timezone
import logging
import azure.functions as func
from core.ingress_hyper import import_hyper_data
from core.constants import SQL_CONNECTION_STRING, SQL_DBNAME
def hyper_import(mytimer: func.TimerRe... |
class Memory:
EMPTY = "EMPTY"
memID = []
def __init__(self,memSize):
self.memSize = memSize
for i in range(0,memSize):
self.memID.append(self.EMPTY)
def AllocateProcess(self,allocatedProcess):
allocatedProcess.allocate(self)
def ReleaseProcess(s... |
import urllib2
response = urllib2.urlopen('http://worldclockapi.com/api/json/est/now')
html = response.read()
splitData = html.split(',')
_dateTime = splitData[1]
print _dateTime
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 12 13:35:41 2019
@author: wkg
"""
from nxviz.plots import CircosPlot
import networkx as nx
import matplotlib.pyplot as plt
from random import choice
term_names = {}
uids = []
with open("data/mesh_data.tab", "r") as handle:
for line in handle:
... |
from random import randint
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from account.models import HomeworkAssignment, Class, SUBJECTS, Teacher, Student, Parent
class RegistrationForm(UserCreationForm):
first_name = forms.CharField(m... |
from blue import BLUE
import os,csv
sysNames=[
["stat","statistical"],
["generator","signal modeling"],
["tchan_scale","t-channel scale"],
["ttjets_scale","\\tt+jets scale"],
["wzjets_scale","W+jets scale"],
["mass","top quark mass"],
["wjets_shape","W+jets shape"],
["wjets_flavour_hea... |
"""
Identifier Class for ip-reverse-dns
"""
import dns
import ipaddress
import re
import sre_constants
from ...iso8601 import *
from ...psjson import *
from ...pstime import *
from ...stringmatcher import *
data_validator = {
"type": "object",
"properties": {
"match": { "$ref": "#/pScheduler/StringM... |
# coding: utf-8
# Copyright 2013 The Font Bakery Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... |
from .visualization import visualize
|
from service.courses_service import CoursesService
import unittest
from unittest.mock import MagicMock
from models.courses import Courses
from daos.courses_dao import CoursesDAO
from daos.daos_impl.courses_dao_impl import CoursesDaoImpl
from service.courses_service import CoursesService
course = Courses(1, 'Physical ... |
from web_adapter import WebAdapter
from db_adapter import DBAdapter
class TopApps(WebAdapter):
data_src = 'https://play.google.com/store/apps/collection/topselling_free'
status = 0
data = None
def harvest(self):
if not self.load_data():
print('Error loading data')
retu... |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 19 08:23:22 2019
@author: Joule
"""
import numpy as np
#import numpy as np
#from queues import Queue
#from stack import Stack
#import math
#
#a = {1:2,2:15,3:47,4:0}
#
#board = np.zeros((6,7,2),dtype=int)
#import re
#
#f = "asdasd"
#print (np.zeros((3,... |
import numpy
n, m, p = map(int, input().split())
a1 = []
a2 = []
for _ in range(n):
a1.append([int(x) for x in input().split()])
for _ in range(m):
a2.append([int(x) for x in input().split()])
array_1 = numpy.array(a1)
array_2 = numpy.array(a2)
print(numpy.concatenate((array_1, array_2)))
|
import sys
import os
from qgis import core as qgisCore
from qgis import gui as qgisGui
from PyQt5 import QtGui
from PyQt5 import QtWidgets
from qgis.PyQt.QtCore import Qt
#############################################################################
class MapViewer(QtWidgets.QMainWindow):
def __init__(self, shap... |
#!/usr/bin/env python
"""
Request input from user to acquire a website URL.
Retrieve all links from the page and check their validity.
"""
import requests
import bs4
import pyinputplus as pyip
from urllib.request import Request, urlopen
def validate_url(url):
'''
Custom function used for URL input validation... |
from rv.api import m
def test_kicker(read_write_read_synth):
mod: m.Kicker = read_write_read_synth("kicker").module
assert mod.flags == 73
assert mod.name == "kickadee"
assert mod.volume == 137
assert mod.waveform == mod.Waveform.triangle
assert mod.panning == 37
assert mod.attack == 392
... |
'''
需求:一直学生列表stu_list=['大乔','小乔','周瑜','诸葛亮','嬴政']
1、显示所有的学生
2、增加学生
3、删除学生
4、更改学生信息
5、退出程序
'''
stu_list = ['大乔','小乔','周瑜','诸葛亮','嬴政']
print('1代表显示所有的学生')
print('2代表增加学生')
print('3删除学生')
print('4更改学生信息')
print('5退出程序')
while True:
option = int(input('\t请输入你选择的操作:'))
if option == 1:
for i in stu_list:
... |
import os.path as osp
import unittest
from unittest.mock import MagicMock, patch
from mne import get_config
from moabb.datasets import utils
from moabb.utils import aliases_list, depreciated_alias, set_download_dir, setup_seed
class TestDownload(unittest.TestCase):
def test_set_download_dir(self):
origi... |
import cv2
# Video capture settings
PICAMERA = False
FRAME_WIDTH = 480
CAMERA_FPS = 30
DISPLAY = True
# Motion detection settings
BACKGROUNDSUB_FRAMES = 256
DISTANCE_TO_THRESHOLD = 16
DETECT_SHADOWS = False
# Object detection settings
COCO_LABELS_PATH = 'yolo-coco/coco.names'
YOLO_CONFIG_PATH = 'yolo-coco/yolov4/yol... |
'''
apkg
~~~~
The Agda Package Manager.
'''
|
from collections import deque
class Palindrome:
def __init__(self):
self.stack = []
self.queue = deque([])
def pushCharacter(self, c):
self.stack.append(c)
def popCharacter(self):
return self.stack.pop()
def enqueueCharacter(self, c):
self.queue.append(c)
... |
from PIL import Image, ImageFilter
from PIL.ImageFilter import SHARPEN
import tkinter.simpledialog as simpleDialog
def effect(image_data) -> Image:
img = image_data.filter(SHARPEN)
img = img.convert("RGBA")
return img |
class Solution(object):
def maximumCount(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# count forward and when - switch to +
# could also say if negative_count > len(arr)/2, return negative_count
# return max(current_index, rest_of_array)
pos... |
import cv2 as cv
import numpy as np
width = 640
height = 480
bpp = 3
img = np.zeros((height, width, bpp), np.uint8)
center = (int(width/2), int(height/2))
# case1
# 노란색 타원
# cv.ellipse(img, center, (200, 10), 0, 0, 360, (0, 255, 255), 3)
# 초록색 타원
# cv.ellipse(img, center, (10, 200), 0, 0, 360, (0, 255, 0), 3)
# 빨... |
from json import dumps
from threading import Thread
import tensorflow as tf
import numpy as np
import cv2
from influxdb_client import Point, InfluxDBClient
from influxdb_client.client.write_api import SYNCHRONOUS
import config
import logging
from flask import Flask, render_template, Response
from flask_cors import COR... |
# This script will calculate the "average read length" which can be used as an argument in the execution command with "Calculate_stats_v2.py"
# Usage:
# $ python Calculate_avReadLen.py contig-fasta-file
import sys
from Bio import SeqIO
contigs = open(sys.argv[1], 'rU')
seqlen = []
N = 0
for rec in SeqIO.parse(cont... |
from asyncio import Queue
from .Schedule import Schedule
from .Cycle import Cycle
import time
import asyncio
import threading
from project.PushAlarm import PushAlarm
|
import random
#Method to check for lose
def checkForLose(item, value, no_of_turns):
if value not in item:
no_of_turns -= 1
print "\n\t\t\t\t\t\t\t\tWrong Word"
print +no_of_turns, " more turns"
if no_of_turns == 0:
print "\t\t\t ! LOSE !"
return no_of_turns
#Method to get value
... |
# PyAgent.py
import Action
import Orientation
import numpy
import sys
class Agent:
def __init__(self):
self.__score = 0
self.__epsilon = 0.1
self.__alpha = 0.6
self.__Q = {}
self.__last_action = 0
self.__last_state = ''
def action(self, s, gold):
self... |
mylist = [1,2,3,4,5]
for key in mylist:
if key >2:
print(key)
mylist = ["Terribly Tricky"]
for word in mylist:
for letter in word[-6:]:
print(letter)
|
with open("data.txt") as f:
data = f.read()
num = 10
data = data.split('\n')
del data[-1]
print(data)
xs = data[0].split(' ')
ys = data[1].split(' ')
meanX = 0
for x in xs:
meanX += float(x)
meanX /= num
meanY = 0
for y in ys:
meanY += float(y)
meanY /= num
sumTL = 0
sumBR = 0
sumTR = 0
for index in range(n... |
#!/usr/bin/python2
import unittest
from elementary_sort import SelectionSort, InsertionSort, ShellSort
from random import sample
class SortTester(unittest.TestCase):
def checkArrayAscending(self, arr):
for pos in range(1, len(arr)):
self.assertTrue(arr[pos - 1] <= arr[pos])
class TestSelectio... |
# -*- coding: utf-8 -*-
from irc3 import testing
class TestCommands(testing.ServerTestCase):
def test_not_registered(self):
s = self.callFTU(clients=3, opers={'superman': 'passwd'})
del s.client1.data['nick']
s.client1.dispatch('OPER superman passwd')
self.assertSent(
... |
import CelestePy.celeste_sample_sources as css
import numpy as np
def test_sample_binomial():
N = 914
p = 6.29379e-16
print css.sample_binomial(N, p, np.random.RandomState(0))
|
def threshold_values(seq,threshold=1):
'''
:param seq:
:param threshold:
:return:
'''
assert isinstance(seq,list)
for i in seq:
assert isinstance(i,str)
assert isinstance(threshold, int)
assert threshold>0
from collections import Counter
import heapq... |
# coding=utf-8
import datetime
import pytils
from django.contrib.syndication.views import Feed
from digest.models import Item, Issue
class CommonFeed(Feed):
"""
Лента РСС для новостей
"""
title = u"Дайджест новостей о python"
link = "/"
description = u"""Рускоязычные анонсы свежих новостей о p... |
# -*- coding: utf-8 -*-
#
# Copyright 2015-2018 Hans Dembinski
#
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt
# or copy at http://www.boost.org/LICENSE_1_0.txt)
import sys
import os
sys.path.append(os.getcwd())
import unittest
from math import pi
from histogram ... |
# 递归求斐波那契数列的第n项
def fib(n):
if n==1:
return(1)
if n==2:
return(1)
return(fib(n-1)+fib(n-2))
def fiblist(n):
L = []
for i in range(1,n+1):
L.append(fib(i))
return(L)
|
class TUser:
def __init__(self,p_name):
self._name=p_name
self._username=""
self._password=""
self._description=""
self.__connection=False
def setConnection(self,p_connection):
self.__connection=p_connection
def getConnection(self):
return self.__connection
def getName(self):
return self._nam... |
N = 8
cnt = 0
for i in range(N):
for j in range(N):
if i+j == i^j and i+j <= 3:
print(i,j,i+j, i^j)
cnt += 1
print(cnt)
|
from abc import ABC
from torch.nn import functional as F
from brevitas.export.onnx.base import ONNXBaseManager
from ..transform import move_domain_attributes_into_domain
def _handler_wrapper(handler, cached_io):
handler = handler()
handler.prepare_from_cached_io(cached_io)
return handler
class PyXIRMa... |
import os
import sys
import numpy as np
import math
import matplotlib.pyplot as plot
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF
from scipy.stats import norm
from . import utils
class calibrate:
def __init__(self, priorPPF, sigmaY, nugget=0, lamb... |
from collections import defaultdict
import chainer
import chainer.functions as F
import chainer.links as L
import config
from time_axis_rcnn.model.time_segment_network.dilated_convolution_1d import DilatedConvolution1D
from time_axis_rcnn.model.time_segment_network.util.links.convolution_nd import ConvolutionND
class... |
def quicks(a, l, r):
global comp
#base case, if right - left indexs <= 1 then we return since size of array is <= 1
if r-l <= 1:
return a
comp = comp + r-l-1
p = partitionm(a, l, r)
quicks(a,l,p-1)
quicks(a,p,r)
return a
def partitionm(a, l, r):
mid = ((r-l)-1)/2
li = [a[l],a[l+mi... |
from pyVim import connect
from pyVmomi import vim
from pyVmomi import vmodl
import atexit
# import tools.cli as cli
import ssl
from tools import cli
from tools.connect import connect_no_ssl
def PrintVmInfo(vm):
summary = vm.summary
print("Name : ", summary.config.name)
print("Template : ", summar... |
# Generated by Django 3.2.3 on 2021-05-20 17:15
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('forum', '0002_auto_20210520_1817'),
]
operations = [
migrations.CreateMode... |
# -*- coding: utf-8 -*-
# @Author: IBNBlank
# @Date: 2018-10-30 23:37:45
# @Last Modified by: IBNBlank
# @Last Modified time: 2018-10-30 23:41:11
import tensorflow as tf
# Create a Constant op
hello = tf.constant("Hello World")
# Start tf session
sess = tf.Session()
# Run the op
print(sess.run(hello)) |
#模型构造
"""
Module类是nn模块里提供的一个模型构造类,是所有神经网络模块的基类,从而可以继承它来定义想要的模型。
用户定义的类需要重载Module类的__int__函数和forward函数,分别用于创建模型参数和定义前向计算
实例化网络后,如net=MLP()
net(X)会自动调用MLP继承自Module类的__call__函数,这个函数将自动调用MLP类定义的forward函数来完成前向计算
Module类是一个通用的部件,事实上,pytorch还实现了继承自Module的可以方便构建模型的类,如Sequential,ModuleList,ModuleDict等
Sequential类
当模型的前向计算为简单... |
n1 = int(input('Digite um numero: '))
print('''Você deseja convertar para:
1 - Binário
2 - octal
3 - hexadecimal''')
base = int(input('Digite o número correspondente a conversão: '))
if base == 1:
binario = bin(n1)[2:]
print('O numero {} em binário é {}'.format(n1, binario))
elif base == 2:
octal = oct(n... |
from django.contrib import admin
from . models import *
admin.site.register(AnswerKey)
admin.site.register(ConfigCreation)
admin.site.register(QuestionModel)
|
class Solution(object):
def numDecodings(self, s):
ways = [None] * len(s)
ways[0] = 1
for c in s:
|
import uuid
from django.contrib import messages
from django.utils.timezone import now
from ..models import Asset, Transcription, TranscriptionStatus
def anonymize_action(modeladmin, request, queryset):
count = queryset.count()
for user_account in queryset:
user_account.username = "Anonymized %s" % u... |
sinle inheritance
class car:
type="sedan"
def info(self):
print(f"This is a {self.type} car information")
class truck(car):
type ="hpm"
def gettype(self):
print(f"type of vehical {self.type}")
ecar=car()
ecar.info()
p=truck()
p.gettype()
p.info()
class doctor:
type="orthologist"... |
from fiixclient import FiixClient
import os
from dotenv import dotenv_values
config = dotenv_values(".env")
client_version = {"clientVersion": {"major": 2, "minor": 8, "patch": 1}}
fiix = FiixClient(subdomain=config['SUBDOMAIN'], api_key=config['API_KEY'],
access_key=config['ACCESS_KEY'], api_secre... |
def maiusculas(frase):
letras_maiusculas = ""
for i in range(len(frase)):
if ord(frase[i]) >= 65 and ord(frase[i]) <= 90:
letras_maiusculas += frase[i]
return letras_maiusculas
frase = "Programamos em python 2?"
frase2 = 'Programamos em Python 3.'
frase3 = 'PrOgRaMaMoS em pyt... |
class Solution:
def connect(self, root):
if root and root.left:
root.left.next = root.right
if root.next:
root.right.next = root.next.left
else:
root.right.next = None
self.connect(root.left)
self.connect(root.right)... |
#Import necessary libraries
from flask import Flask, render_template, request
import pandas as pd
import numpy as np
import tensorflow as tf
# from keras.preprocessing.image import load_img
# from keras.preprocessing.image import img_to_array
# from keras.models import load_model
import os
# Create flask instance
app ... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class OctConv(nn.Module):
def __init__(self, ch_in, ch_out, kernel_size, stride=1, alphas=(0.5, 0.5)):
super(OctConv, self).__init__()
self.alpha_in, self.alpha_out = alphas
assert 0 <= self.alpha_in <= 1... |
from ED6ScenarioHelper import *
def main():
# 威尔特桥 关所
CreateScenaFile(
FileName = 'T0500 ._SN',
MapName = 'Rolent',
Location = 'T0500.x',
MapIndex = 18,
MapDefaultBGM = "ed60016",
Flags = 0,
... |
i=input('enter name')
print i
go
to
|
#!/usr/bin/python
from setuptools import setup
setup()
|
#!/usr/bin/env python3
import logging
import json
from bs4 import BeautifulSoup
from tqdm import tqdm
# Set up logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
handler = logging.FileHandler("mesh_term_extraction.log")
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %... |
# Generated by Django 2.1.5 on 2019-02-21 22:16
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('address', '0001_initial'),
('products', '0001_initial'),
('values', '0001_initial'),
... |
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
import threading
import discord
import os
from discord.ext import commands, tasks
myurl = 'https://finance.yahoo.com/quote/DOGE-USD/'
uClient = uReq(myurl)
page_html = uClient.read()
page_soup = soup(page_html, "html.parser")
... |
# coding: utf-8
# In[ ]:
# opengrid imports
from opengrid.library import misc, houseprint, caching
from opengrid.library.analysis import DailyAgg
from opengrid import config
from opengrid.library.slack import Slack
from opengrid.library import alerts
c=config.Config()
# other imports
import pandas as pd
import json... |
#!/usr/bin/env
############################################
# exercise_3.py
# Author: Paul Yang
# Date: June, 2016
# Brief: demo
############################################
10 + 10
print("Hello World") |
from onegov.people.collections.agencies import AgencyCollection
from onegov.people.collections.memberships import AgencyMembershipCollection
from onegov.people.collections.people import PersonCollection
__all__ = (
'AgencyCollection',
'AgencyMembershipCollection',
'PersonCollection',
)
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import visualize.models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
... |
import os
import json
import pprint
from utils import escape_non_alphanumeric, escape_non_ascii
'''
{
<server_id> : [<channel_id>]
}
'''
_SERVERS_FILE = "server.json"
_LOG_DIR = "logs"
tracked_servers = {}
def track(channel):
server = channel.guild
server_id = str(server.id)
channel_id = str(channel.... |
from cudatext import *
import sys
import os
import shutil
INI = 'cuda_someformat.cfg'
MSG = '[NNN Format] '
def ini_global():
ini = os.path.join(app_path(APP_DIR_SETTINGS), INI)
ini0 = os.path.join(os.path.dirname(__file__), INI)
if not os.path.isfile(ini) and os.path.isfile(ini0):
shutil.copyfile... |
import os
###the directory in which you have your img folder with only the images you want to keep
PATH_TO_FILES = '/home/young-joo/Desktop/Cleaning_Complete/'
###the name of the bbox text file you just created using bbox_and_label.py
BBOX_FILE_OLD = 'bbox_full_body_wear.txt'
###what you want the name of the new bb... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 11 16:11:45 2021
@author: Mukul Kirti Verma
"""
class cq:
def __init__(self,capacity):
self.size=0
self.rear=-1
self.front=-1
self.capacity=capacity
self.q=[None]*capacity
def enqueue(self,data):
if (self.rear+1)%self.ca... |
import matplotlib.pyplot as plt
times = [0.02, 0.03, 0.09, 0.86, 2.8, 13.31, 28.26, 49.32]
cell_counts = [1, 10, 100, 1000, 2500, 5000, 7500, 10000]
plt.plot(cell_counts, times, '-ko')
plt.xlabel("# cells")
plt.ylabel("Simulation time (s)")
plt.title("NEURON")
plt.show()
|
# basecon.py jeremyhitt
def bincon(num,addSpace):
n = num
s = addSpace
print(n," = ",end="") #debug
d = 128
binString ="" #create a string called binString
for i in range(0,8):
q = int(n / d)
r = int(n % d)
n = r
d = int(d / 2)
binString = binString+str(q)
if(s == 1 and i == 3):
binSt... |
# coding=utf-8
from flask import Blueprint
from flask_restful import Api
from .article import ArticleListApi
from .auth import Signup, Login
bp = Blueprint('api_v1', __name__, url_prefix='/api/v1')
api = Api(bp)
# authenticated
api.add_resource(Signup, '/signup')
api.add_resource(Login, '/login')
|
def det(**data):
for i in data:
print('I am ',i,'from',data[i])
det(eish='hyderabad',sharath='mumbai',akhil='delhi') |
from app.models import db, Geneset
try:
gs = Geneset("STAT3 STAT1")
db.session.add(gs)
db.session.commit()
except Exception as e:
print ("Error inserting gs")
#Rollback if there are errors
db.session.rollback()
# Will produce an error, why?
try:
gs = Geneset("STAT1 STAT3")
db.session.ad... |
from concurrent import futures
import server_pb2
import server_pb2_grpc
import grpc
import time
import numpy as np
class ServerServicer(server_pb2_grpc.ServerServicer):
def voidFunction(self, request, context):
return server_pb2.void()
def boolFunction(self, request, context):
return server_... |
import time
class Car(object):
"""
Abstracts a car. It is meant to have all the functionalities of an actual car.
"""
def __init__(self) -> None:
self.__engine_on: bool = False
self.__speed_in_kmph: float = 0
self.max_speed_in_kmph = 0
@staticmethod
def get_type() -> ... |
# Generated by Django 3.2.7 on 2021-10-03 17:28
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('leaguestats', '0004_alter_team_number_of_players'),
]
operations = [
migrations.RemoveField(
model_name='team',
name='player... |
# Generated by Django 2.2.11 on 2020-04-08 12:35
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('home', '0002_advertisingimagemodel'),
]
operations = [
migrations.RemoveField(
model_name='advertisingimagemodel',
name='sl... |
from time import sleep, strftime
from bcc import BPF
from bcc.utils import printb
from bcc.syscall import syscall_name, syscalls
b = BPF(text = """
struct data_t {
u64 count;
u64 total_ns;
};
BPF_HASH(start, u32, u64);
BPF_HASH(data, u32, struct data_t);
TRACEPOINT_PROBE(raw_syscalls, sys_enter)
{
u32 syscall_id... |
import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
import random
from src.TSPData import TSPData
# TSP problem solver using genetic algorithms.
class GeneticAlgorithm:
# Constructs a new 'genetic algorithm' object.
# @param generations the amount of generations.
... |
from django.db import models
from rest_framework import serializers
class Vehicle(models.Model):
class Meta:
app_label = 'user'
car_type = models.CharField(max_length=255)
plate_no = models.CharField(max_length=255)
def __str__(self):
return 'car_type={},plate_no={}'.format(self.car... |
#
# File: timer.py
# Author: Isaac J. Mertzenich
# (c) 2015
# Created: April 15, 2015
#
# Description: This file contains a timer that can be started Author
#at a certain time. This is used to keep track of the game clock, so
#as to determine when the game ends. This file works as a countdown.
#
#IMPORTS
import time... |
#!/usr/bin/env python
import os
import h5py
import numpy as np
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from matplotlib import cm
import argparse
import ext.progressbar as progressbar
from ext.colors import rundark
from ext.colors import runbright
from misc import drawwidget
from misc im... |
#import sys
#input = sys.stdin.readline
from collections import Counter, defaultdict
Q = 10**9+7
def main():
N, M = map( int, input().split())
A = list( map( int, input().split()))
B = list( map( int, input().split()))
CA = Counter(A)
CB = Counter(B)
for a in A:
if CA[a] >= 2:
... |
from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static
from rest_framework.urlpatterns import format_suffix_patterns
from . import views
urlpatterns = format_suffix_patterns([
# /store/
url(r'^$', views.IndexView.as_view(), name='index'),
# auth_links... |
class Solution:
def twoSumBest(self, nums, target):
hashmap = {}
for ind, num in enumerate(nums):
hashmap[num] = ind
for i, num in enumerate(nums):
j = hashmap.get(target - num)
if j is not None and i != j:
return [i, j]
def twoSum(sel... |
import os
import pytest
@pytest.fixture(scope = 'session')
def ICDIR():
return os.environ['ICDIR']
@pytest.fixture(scope = 'session')
def ICDATADIR(ICDIR):
return os.path.join(ICDIR, "database/test_data/")
@pytest.fixture(scope = 'session')
def DETSIMDATA():
return os.path.join(os.environ['DETSIMDIR']... |
/home/miaojian/miniconda3/lib/python3.7/locale.py |
#
# Copyright 2019 Gianluca Frison, Dimitris Kouzoupis, Robin Verschueren,
# Andrea Zanelli, Niels van Duijkeren, Jonathan Frey, Tommaso Sartor,
# Branimir Novoselnik, Rien Quirynen, Rezart Qelibari, Dang Doan,
# Jonas Koenemann, Yutao Chen, Tobias Schöls, Jonas Schlagenhauf, Moritz Diehl
#
# This file is part of acado... |
import pygame, os, sys, queue, random
os.environ['SDL_AUDIODRIVER'] = 'dsp'
from pygame.locals import *
pygame.init()
WIDTH = 720
HEIGHT = 480
screen = pygame.display.set_mode((WIDTH, HEIGHT))
CLK = pygame.time.Clock()
green = (44, 219, 96)
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
gold = (255,223,0)
s... |
#!/usr/bin/env python
import sys
def get_episode_filename( this_series, this_episode ):
if this_series == 'land_girls':
return( "5378744311360060124" )
elif this_series == 'eastenders':
return( "5982565603066810026" )
elif this_series == 'luther':
return( "5898708084599343208" )
... |
Hello DevOps is promising
|
"""
Runs Autumn utilities
You can access this script from your CLI by running:
python -m autumn --help
"""
import click
from .database import db
from .secrets import secrets
from .projects import project
from .remote import remote
from .tasks import tasks
@click.group()
def cli():
"""Autumn project comman... |
# coding:utf-8
from matplotlib.pyplot import plot
from matplotlib.pyplot import show
import numpy as np
import sys
N = int(5)
weights = [0.2,0.2,0.2,0.2,0.2]
print "Weights",weights
c = np.loadtxt('data.csv',delimiter = ',',usecols = (6,),unpack = True)
sma = np.convolve(weights,c)[N-1:-N+1]
print sma
t = np.ara... |
def winter_is_coming(seasons):
counter = 0
for season in seasons:
if season == "winter":
counter = 0
else:
counter += 1
if counter >= 5:
return True
else:
return False
print(winter_is_coming(["winter", "summer", "summer", "summer", "spring", "sp... |
from django.test import TestCase
from .SyncHandler import SyncHandler
from .models import LocalVlans, RemoteVlans
class MyTest(TestCase):
def setUp(self):
l = LocalVlans(id=1, name="test1", description="dddd")
l.save()
lm = RemoteVlans(id=2, name="test5", description="dddddd")
lm... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.