text stringlengths 8 6.05M |
|---|
import json
from datetime import date, datetime
from pathlib import Path
from typing import List
import attr
import cattr
converter = cattr.Converter()
@attr.s(auto_attribs=True, frozen=True)
class Row:
date: str
areaCode: str
areaName: str
newCasesBySpecimenDateRollingRate: float
@attr.s(auto_att... |
#!/usr/bin/env python
import rospy
from left import Left
from right import Right
#from start import Start
from enum import IntEnum
from ar_track_alvar_msgs.msg import AlvarMarkers
from ar_switch import Ar_Find
import math
STATES = {-1:'MidWall',1:'LeftWall',4:'RightWall',2:"Start",3:"}
def ar_state(id):
... |
#oef6
a = int(input("Give a number: "))
b = int(input("Give another number: "))
result = (a+b)*(a+b)
print("({} + {}) ^ 2 = {}".format(a, b, result)) |
import pandas as pd
df = pd.read_csv('nyc_weather_report.csv')
print(df)
print(df['Temperature'].max()) #max in temp column
print(df['EST'][df['Events']=='Rain']) #dates on which event was rain
df.fillna(0, inplace = True)
#replaces the blank spaces with 0 or called data wrangling
print(df['WindSpeedMPH'].mean())
|
#TODO
'''
Map plot
'''
from .taylor import TaylorDiagram
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
from mpl_toolkits.basemap import Basemap
from .io import Raster
def layout(src, *arg, **kargs):
'''
Inputs:
-----------------------
:src - geoPackage.io.Raster object... |
#!/usr/bin/python
#\file follow_q_traj3.py
#\brief Following joint angle trajectory
# where target velocity is automatically decided with spline.
#\author Akihiko Yamaguchi, info@akihikoy.net
#\version 0.1
#\date Nov.22, 2017
import roslib; roslib.load_manifest('motoman_driver')
import rospy
import se... |
from picamera import PiCamera
from time import sleep
from datetime import datetime
class Cameratest:
def __init__(self):
self.camera = PiCamera()
self.resolution()
def __del__(self):
self.camera.close()
def preview(self):
self.camera.start_preview(fullscreen=False, window=... |
# Heuristic Cost Function *****************************************************
def heuFunc1(root,v,h):
if root == None:
return 0
val = 0
x = root.leaf
if x == v:
val+=((h-1))
val+=0
else:
val+=0
for i in range(len(root.children)):
val += heuFunc1(root.children[i],v,h+1)
return val
def heuFunc2(root,... |
#! /usr/bin/env python
import droneinfo.infonode
if __name__ == '__main__':
droneinfo.infonode.main() |
numbers = [2, 5, 1, 3, 8, 7, 10, 9, 4, 6]
print(numbers)
print(len(numbers))
print(numbers[1])
print(numbers.index(5))
numbers.sort()
print(numbers)
numbers.reverse()
print(numbers)
numbers.remove(5)
print(numbers)
numbers.append(5)
print(numbers)
numbers.pop()
print(numbers)
numbers.insert(1, 0)
print(numbers)
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ˅
from structural_patterns.bridge.display_impl import DisplayImpl
# ˄
class TextDisplayImpl(DisplayImpl):
# ˅
# ˄
def __init__(self, text):
# A string to display
self.__text = text
# A number of characters in bytes
self._... |
import random
#author name as key , and index as value
def read_authors_dict():
infile = open("data/authors.txt","r")
infile.readline()
authors_dict = {}
for line in infile:
fields = line.strip().split('|')
if fields[1] not in authors_dict:
authors_dict[fields[1]] = fields[0]... |
p = int(input())
for i in range(p):
a = input()
b = input()
count = 0
for i in a:
if i in b:
count+=1
print('YES' if count>0 else 'NO')
|
import urllib2
from bs4 import BeautifulSoup
CAPRI_HOME = 'http://www.ebi.ac.uk/msd-srv/capri/capri.html'
if __name__ == "__main__":
req = urllib2.Request(CAPRI_HOME)
response = urllib2.urlopen(req)
home_page = response.read()
soup = BeautifulSoup(home_page, 'html.parser')
rounds = soup.select(... |
def about(name, age, city):
return '{}, {} год(а), проживает в городе {}'.format(name,age,city)
name = input('Введите имя: ')
age = input('Введите возраст: ')
city = input('Введите город: ')
print(about(name,age,city)) |
# coding:utf-8
def bubble_sort(item):
"""冒泡排序 正向"""
for i in range(0, len(item)-1):
for j in range(i+1, len(item)):
if item[i] > item[j]:
item[i], item[j] = item[j], item[i]
return item
def bubble_sort2(item):
"""冒泡排序 倒序"""
for i in range(0, len(item)-1):
... |
from typing import Dict, List, Callable, Union, Set
from overrides import overrides
from antu.io.vocabulary import Vocabulary
from antu.io.instance import Instance
from antu.io.datasets.dataset import Dataset
from antu.io.dataset_readers.dataset_reader import DatasetReader
from antu.utils.padding_function import shadow... |
from django.urls import path
from . import views
urlpatterns = [
path('',views.page1,name="page1"),
path('page2',views.page2,name="page2"),
path('page3',views.page3,name="page3"),
path('page4',views.page4,name="page4"),
path('estanteria1',views.estanteria1,name="estanteria1"),
path('estanteria2... |
"""
import sys
n=int(input())
stack=[]
result=[]
array=[]
for i in range(n):
num=int(sys.stdin.readline())
for j in range(1,n+2):
if len(stack)==0:
stack.append(j)
result.append('+')
print (" ",j,result)
continue
if stack[-1]>num ... |
def authen(username,password):
if username=="coachcarl1000" and password=="pikachuPika":
return True
else:
return False
|
import pytube
import converter_moviepy
import os
# remove from title illegal characters found
def clean_title(title):
illegal_characters = []
illegal_characters.append('"')
illegal_characters.append('|')
for character in illegal_characters:
title = title.replace(character, "")
print("N... |
# Project Euler Problem 6
#Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
a=0
b=0
c=0
d=0
for a in range(1,101):
b += a #generate the sum
c += a*a #b is the sum of the squares
b=b*b
d=b-c #Difference between the sum of squares and square of sums... |
import cv2
import numpy as np
import time
# omni-lens with android_ros app param
Cx = 695
Cy = 350
SR = 120
LR = 230
imagelist = ['imageLists.txt', 'imageLists_step_2.txt', 'imageLists_step_5.txt', 'imageLists_step_10.txt']
# for loading raw datasets and panorama it to a general images
class MyDataloader:
def ... |
from mongo_connection import MongoConnection
#############################################
class User():
def __init__(self, username, password="", first_name="", last_name=""):
self.username = username
self.password = password
self.first_name = first_name
self.last_name = last_name
self.full_name = first_n... |
from marshmallow import (
fields,
Schema,
validate,
validates_schema,
ValidationError
)
from api.validators import email_not_existing, password_validate
class NewUserSchema(Schema):
name = fields.Str(required=True)
surname = fields.Str(required=True)
email = fields.Email(required=T... |
import maya.cmds as cmds
'''
Goes through selected items and checks if translates, rotates, and scales are
identity, changing them to identity if they are not identity and not locked.
Created by Derek Ho
'''
def CheckItem(a , b):
#if not identity, and not locked, add into a list
#check if... |
#!/usr/bin/python
#-*- coding: utf-8 -*-
"""
This script creates a file containing all paths of the dataset.
"""
import logging
logger = logging.getLogger(__name__)
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
import argparse
import utils
if __name__ == "__main__":
a... |
from django.db import models
# Create your models here.
class Product(models.Model):
name = models.CharField(max_length=30)
address = models.TextField()
price = models.IntegerField()
def __str__(self):
return self.name
class Shops(models.Model):
name = models.CharField(max_length=30)... |
"""
Models for Orders Service(adapted from Professor Rofrano's demo code)
All of the models are stored in this module
Models
------
Order - An order model used in the Online Shopping System
Attributes:
-----------
"""
import logging
import json
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
... |
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import Profile, Reservation
ROLES = (
('O', 'Owner'),
('R', 'Renter')
)
class SignUpForm(UserCreationForm):
role = forms.ChoiceField(choices=ROLES, help_text='Required. sele... |
from rv.chunks import DrawnWaveformChunk
from rv.modules import Behavior as B
from rv.modules import Module
from rv.modules.base.generator import BaseGenerator
class Generator(BaseGenerator, Module):
chnk = 1
behaviors = {B.receives_notes, B.receives_modulator, B.sends_audio}
class DrawnWaveform(DrawnW... |
#import sys
#input = sys.stdin.readline
def main():
N = int( input())
A = list( map( int, input().split()))
now = 0
ans = 0
for a in A:
if now <= a:
now = a
continue
ans += now - a
print(ans)
if __name__ == '__main__':
main()
|
import unittest
def triangle(n: int) -> list[str]:
result = []
for i in range(1, n + 1):
sum = "*" * i
result.append(sum)
return result
class Test(unittest.TestCase):
def test_input_n_equals_3(self):
self.assertEqual(triangle(3), ["*", "**", "***"])
def test_input_n_equ... |
import shutil, torch
def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):
torch.save(state, filename)
if is_best:
shutil.copyfile(filename, 'model_best.pth.tar')
save_checkpoint({
'epoch': epoch + 1,
'arch': args.arch,
'state_dict': model.state_dict(),
'best_prec1... |
#!/bin/env python
from argparse import ArgumentParser
import subprocess
def main() :
from GaudiScriptBuilder.AppConfig import DaVinciScript
argparser = ArgumentParser()
argparser.add_argument('--datafile')
argparser.add_argument('--linename')
argparser.add_argument('--version')
argparser.add_... |
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# Nombre: stackedWidget.py
# Autor: Miguel Andres Garcia Niño
# Creado: 11 de Mayo 2018
# Modificado: 11 de Mayo 2018
# Copyright: (c) 2018 by Miguel Andres Garcia Niño, 2018
# License: Ap... |
# Generated by Django 2.0.2 on 2018-02-28 06:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('articles', '0010_auto_20180228_0941'),
]
operations = [
migrations.AlterField(
model_name='article',
name='picture',... |
"""
NPDownloader.py
Created by Jonathon Scofield
Designed to download all comics from the 8-bit theater on nuklearpower.com
Possibly will expand to further download capability later
"""
import os
from bs4 import BeautifulSoup
import wget
import urllib
def oranizeFiles():
for i in range(0, 123... |
#!/bin/python3
# snakes and ladders DP solution
inin = lambda: [ map(int, input().split()) for _ in range(int(input())) ]
def shortest():
cost = [0] + [999] * 99
jumps = { s - 1: e - 1 for s, e in inin() + inin () }
i = 1
while i < 100:
p = [ cost[j] for j in range(max(0, i-6), i)
... |
class Solution:
def singleNumber(self, nums) -> int:
numsDict = {}
for i in range(len(nums)):
if numsDict.get(nums[i])==None:
numsDict[nums[i]] = 1
else:
numsDict.pop(nums[i])
return numsDict.popitem()[0]
def singleNumber2(s... |
import threading #import all librarisch
from rover_5 import Rover
from UltrasoneSensor import UltrasoneSensor
from KleurenSensor import KleurenSensor
from Camera import Camera
from servo import Arm
import time
import RPi.... |
from flask import Blueprint, request, jsonify
from marvel_inventory.helpers import token_required
from marvel_inventory.models import User, Character, character_schema, characters_schema, db
api = Blueprint('api', __name__, url_prefix='/api')
@api.route('/characters', methods = ['POST'])
@token_required
def create_ch... |
from django.db import models
from classrooms.models import ClassRoom
from workers.models import TeachingStaff
class Subject(models.Model):
name = models.CharField(max_length=20, unique=True)
description = models.TextField(max_length=250)
def __str__(self):
return self.name
class SubjectClass(mo... |
n =int(input())
now_x = 0
now_y = 0
now_t = 0
for i in range(n):
t,x,y= map(int,input().split())
x2 = x -now_x
y2 = y -now_y
t2 = t -now_t
distance = abs(x2) + abs(y2)
if( not(distance <= t2 and (distance - t2)%2 ==0)):
print("No")
exit()
now_x = x
now_y = y
now_t = ... |
from client_database_connection import mycursor
from config import node_id
import time
time.sleep(5)
def run():
while True:
time.sleep(5)
sql = "SELECT node_free FROM node_data where node_id = " + code_id
mycursor.execute(sql)
check = mycursor.fetchone()
if(check==... |
MONGODB_URL = "mongodb://localhost:27017/"
PORT = 5002
IS_DEBUG = False
REQUIREMENT_MANAGER_URL = "http://localhost:5003"
|
from fractions import Fraction
# a Vrectangle is a rectangle defined by its top, left, bottom, right coordinates as
# proportions of height & width of a parent canvas (itself a Vrectangle or None if top-level aka root canvas)
# top, left, bottom, right are handled as Fraction
class Vrectangle:
def __init__... |
from random import randint
class ss():
def __init__(self):
self.celloccupancy = [[0] * 10 for i in range(10)]
def act(self):
x = 5
y = 5
availableCells = []
if (self.celloccupancy[x - 1][y - 1] == 0):
availableCells.append([- 1, - 1])
if (self.cell... |
"""gcon URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based ... |
from pymodm import connect, MongoModel, EmbeddedMongoModel, fields
from pymodm.queryset import QuerySet
from pymodm.manager import Manager
connect('mongodb+srv://mah148:7C2BeZmfwzWmSgwW@bme547-gxtrh.mongodb.net/'
'test?retryWrites=true', 'bme547-db')
class ImageQuerySet(QuerySet):
def user(self, user_id)... |
import os
import sys
from subprocess import Popen, PIPE
from conans.util.files import decode_text
from conans.errors import ConanException
import six
class ConanRunner(object):
def __init__(self, print_commands_to_output=False, generate_run_log_file=False, log_run_to_output=True):
self._print_commands_to... |
class Runner:
def __init__(self, firstname, lastname, bib):
self.name = f"{lastname}, {firstname}"
self.bib = int(bib)
self.bibstring = bib
self.splits = {
"S1": "",
"S2": "",
"F": "",
}
self.ranks = {
"S1": "0",
... |
import pygame
from pygame.locals import *
import random
class Node:
# Function to initialize the node object
def __init__(self,isStar,data,color):
self.coord = data # Assign data(x,y coord)
self.isStar=isStar
self.color=color
self.next = None # Initialize next as null
... |
import tkinter
from buttons import Button as bt
from bridge import MouseMotionToController
from configuration import ConfigOfButton, ConfigOfCanvas
from controller.buttonController import ButtonController
from controller.canvasController import CanvasController
from controller.modeController import *
def initAllButto... |
import datetime
from typing import List
import sqlalchemy as sa
import sqlalchemy.orm as orm
from pypi_org.data.modelbase import SqlAlchemyBase
from pypi_org.data.releases import Release
class Package(SqlAlchemyBase):
__tablename__ = 'packages'
id = sa.Column(sa.String, primary_key=True)
created_date = ... |
numero = int(input("Digite um número"))
acumulador = 0
while numero != 0:
acumulador += numero
numero = int(input("Digite um número"))
print(acumulador)
|
import math
import xml.sax.handler
import xml.sax
import pprint
#cambiar por vectores
#La clase Vector realiza algunas operaciones basias que ayudan a la implementacion de
#algunas de las funciones de distancia y size del juego
class Vector:
def __init__(self,x,y):
self.x =x
self.y =y
def getU... |
# groceries.py
# csv-mgmt/read_teams.py
import operator
import pandas
import os
#csv_filepath = "products.csv"
csv_filepath = os.path.join(os.path.dirname(os.path.dirname(__file__)), "..", "groceries-exercise", "products.csv")
df = pandas.read_csv(csv_filepath)
products = df.to_dict("records")
def to_usd(my_pr... |
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth import get_user_model
from optparse import make_option
import logging
logger = logging.getLogger('django.commands')
class Command(BaseCommand):
help = "Create a super user"
option_list = BaseCommand.option_list + (
... |
/Users/matthewpeterson/anaconda3/lib/python3.7/functools.py |
def dimensoes(matriz):
if len(matriz) == 0:
print("0X0")
else:
linha = len(matriz)
coluna = len(matriz[0])
print(str(linha) + "X" + str(coluna))
|
from math import gcd
def eratosthenes(N):
from collections import deque
work = [True] * (N+1)
work[0] = False
work[1] = False
ret = []
for i in range(N+1):
if work[i]:
ret.append(i)
for j in range(2* i, N+1, i):
work[j] = False
return ret
# de... |
#!/usr/bin/python3
# -*- encoding: utf-8 -*-
'''
@File : testserver1.py
@Time : 2018/11/20 09:07:20
@Author : BaiYang
@Version : 1.0
@Contact : yang01.bai@horizon.ai
@License : (C)Copyright 2017-2018, Liugroup-NLPR-CASIA
@Desc : 测试tcp的非阻塞模式1:使用非阻塞单任务为多个客户端服务。
'''
import random,os,time,sys
impo... |
from django.contrib import admin
from shostpost_app.models import GhostPost
admin.site.register(GhostPost)
|
import codecs
import re
import itertools
#-------delete first line-------
'''
print "delete first line"
#delete first line and create new file such as new______.
with codecs.open('./resources/agency.txt', "r", "utf-8-sig") as fin:
data = fin.read().splitlines(True)
with codecs.open('./resources/agency.txt', "w",... |
'''
This is a implementation of Quantum State Tomography for Qubits,
using techniques of following papars.
'Iterative algorithm for reconstruction of entangled states(10.1103/PhysRevA.63.040303)'
'Diluted maximum-likelihood algorithm for quantum tomography(10.1103/PhysRevA.75.042108)'
'Qudit Quantum State Tomography(1... |
conf = '/home/pi/coffee/temp.conf';
killfile = '/var/www/html/killfile.tmp';
runfile = '/var/www/html/runfile.tmp';
##GPIO PINS
relais = 17;
statusLED = 27;
button = 22;
|
import requests
import json
# Importing json And requests
url = "https://api.tellonym.me/tokens/create"
# Login API URL
headers = {
"Host": "api.tellonym.me",
"Content-Type": "application/json",
"Accept": "application/json",
"Connection": "keep-alive",
"tellonym-client": "ios:2.65.0:488:14:iPhone13,3",
"User-A... |
# find all numbers disappeared in an array
# 取负数以标志元素是否只是出现了一次
def find_num(nums):
result = []
for i in nums:
if nums[abs(i)-1] > 0:
nums[abs(i)-1] = -nums[abs(i)-1]
for i in range(len(nums)):
if nums[i] > 0:
result.append(i+1)
return result
if __name__ == '__ma... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ˅
from behavioral_patterns.iterator.aggregate import Aggregate
from behavioral_patterns.iterator.book_shelf_iterator import BookShelfIterator
# ˄
class BookShelf(Aggregate):
# ˅
# ˄
def __init__(self, max_size):
self.__number_of_books = 0
... |
def readAllData(filename):
file = open(filename, 'r')
l = []
# print(file.readline())
# print()
# print(file.readlines())
file.readline()
for i in file.readlines():
# print(i.split())
# print(type(i))
# tup = tuple(i.split())
# print(tup)
l.append(tu... |
import os
input_file = input('Enter the file name: ')
input_file = os.path.abspath(input_file)
while True:
if os.path.isfile(input_file):
break
else:
print('{} is not a valid file path...'.format(input_file))
input_file = input('Enter the file name: ')
filename = os.path.splitext(inpu... |
class Solution(object):
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums[0]<=nums[len(nums)-1]:
return nums[0]
def bins(vals, start, end):
if end<start:
return
... |
from flask import Flask
from webapp.config import Config
app = Flask(__name__)
app.config.from_object(Config)
from webapp import routes
|
#!/bin/env python
import os
def distance_matrix(distance_matrix):
print "<br /><h1>DISTANCE MATRIX</h1><br />"
print "<table class='table'>"
print "<tr><th></th>"
for distance1 in distance_matrix.iterkeys():
print "<th>"+distance1.split("/")[-1]+"</th>"
print "</tr>"
for distance1 in dis... |
from keras.models import Sequential
from keras.layers.core import Flatten, Dense, Dropout
from keras.layers.convolutional import Convolution2D, MaxPooling2D, ZeroPadding2D
from keras.optimizers import SGD
import cv2, numpy as np
from keras import backend as K
import json
import time
from keras.callbacks import TensorBo... |
import unittest
from importlib import import_module
solution = import_module('main')
test_cases = [
"4Always0 5look8 4on9 7the2 4bright8 9side7 3of8 5life5",
"5Nobody5 7expects3 5the4 6Spanish4 9inquisition0",
]
test_results = [
"0Always4 8look5 9on4 2the7 8bright4 7side9 8of3 5life5",
... |
from bs4 import BeautifulSoup
import requests
r = requests.get("http://digidb.io/digimon-list/")
soup = BeautifulSoup(r.content, 'html.parser')
dataTarget = soup.find_all('tr', class_='')
# print(dataTarget)
# print(len(dataTarget))
# print(dataTarget[:4433])
# print(dataTarget[0].img... |
import argparse
import logging
import wandb
from action_recognition.utils.mq_tqdm import mp_tqdm, cmd_worker
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
parser = argparse.ArgumentParser()
parser.add_argument("--train_group", default='', type=str)
parser.add_argument("--group", ... |
import pathlib
PATH_TO_ROOT = pathlib.Path(__file__).parent.parent
PATH_TO_INPUT = PATH_TO_ROOT.joinpath('input')
PATH_TO_DOMAINS = PATH_TO_INPUT.joinpath('domains.txt')
PATH_TO_QUERIES = PATH_TO_INPUT.joinpath('queries.txt')
PATH_TO_OUTPUT = PATH_TO_ROOT.joinpath('output')
PATH_TO_REPORT = PATH_TO_OUTPUT.joinpath('... |
from __future__ import division
import logging; _L = logging.getLogger('openaddr.render')
from .compat import standard_library
from glob import glob
from argparse import ArgumentParser
from itertools import combinations
from os.path import join, dirname, basename
from urllib.parse import urljoin
import json
from .co... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-04-03 11:49
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('fees', '0006_auto_20180403_0937'),
]
operations = [
migrations.AlterUniqueTogether(
... |
# Copyright (c) 2022 Dell Inc. or its subsidiaries.
# 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 requi... |
# *********************************************************************************************
# Program to update dynamodb with latest data from mta feed. It also cleans up stale entried from db
# Usage python dynamodata.py
# *****************************************************************************************... |
"""
2015-2016 Constantine Belev const.belev@ya.ru
"""
import numpy as np
import scipy as sp
from scipy import sparse, optimize
from lowrank_matrix import ManifoldElement
from approximator_api import AbstractApproximator
from manifold_functions import TangentVector, svd_retraction
from manifold_functions import rieman... |
import datetime
import unittest
from time import sleep
from selenium import webdriver
class EnvironmentSetup(unittest.TestCase):
def setUp(self):
chrome_path = r"C:\Users\Idur\PycharmProjects\RaptAutomation\Drivers\chromedriver.exe"
#firefox_path = r"C:\Users\Idur\PycharmProjects\RaptAutomation\... |
from django.contrib import admin
from .models import *
admin.site.register(Tiers)
admin.site.register(CompteBancaire)
admin.site.register(Document)
admin.site.register(TypeDocument)
admin.site.register(ModePaiement)
admin.site.register(Paiement)
|
class Solution:
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
matrix = [[0 for _ in range(n)] for _ in range(n)]
up, left = 0, 0
right, bottom = n, n
i, j = 0, 0
count = 1
while True:
for j in ra... |
def normalizer(data, mean, std):
"""
Normalize features by standard deviation
data is a ndarray
"""
return (data - mean) / std |
"""Script para cythonize todos los .pyx"""
import sys, os, shutil, contextlib#, argparse
from Cython.Build import Cythonize, cythonize
#TO DO: incluir command line options
@contextlib.contextmanager
def redirect_sys_argv(*argv):
"""contextmanager para cambiar sys.argv al argv dado"""
original = list... |
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
import json
from flask import Flask, jsonify, request, abort, render_template, Response
import gevent
from redis import Redis
from index import JIRARedisIndex
from jira.client import JIRA
import module
app = Flask(__name__)
@mod... |
from django.test import TestCase
# Create your tests here.
from django.test import TestCase
# Create your tests here.
import uuid
import pytest
from django.contrib.auth.models import User
from django.urls import reverse
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
... |
import numpy as np
class Estimation:
def __init__(self, datax, datay, dataz):
self.x = datax
self.y = datay
self.v = dataz
def estimate(self, x, y, sigma=0.0, p=-2):
"""
Estimate point at coordinate x,y based on the input data for this
class.
"""
... |
DEBUG = True
import os
USERID = 0
# session
SECRET_KEY = os.urandom(24)
# 数据库 初始化提交
HOSTNAME = None
PORT = '3306'
DATABASE = 'alter'
USERNAME = None
PASSWORD = None
SQLALCHEMY_POOL_RECYCLE = 20
SQLALCHEMY_POOL_SIZE = 100
SQLALCHEMY_TRACK_MODIFICATIONS = True
DEBUG = True
# SQLALCHEMY_ECHO = True
DB_URI = 'mysql+p... |
from model.models import Contact
import random
import string
import os.path
import jsonpickle
import getopt
import sys
try:
opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["Number_of_contacts", "file"])
except getopt.GetoptError as err:
getopt.usage()
sys.exit(2)
n = 2
f = "data/contacts.json"
for o, ... |
from turtle import *
bgcolor("#16F4DC")
bgpic("Dratini.gif")
pencolor("#0624F8")
for number in range (4):
forward(100)
rt(90)
input()
|
from django.shortcuts import render
from django.http import HttpResponse
from .models import Job
from .models import Email
from django.db.models import Q
from django.core.paginator import Paginator
from django.shortcuts import redirect
# Create your views here.
def index(request):
job=Job.objects.all()[:10]
pa... |
from .opencv_utils import show_image_and_wait_for_key, BrightnessProcessor, draw_segments
from .segmentation_aux import contained_segments_matrix, LineFinder, guess_segments_lines
from .processor import DisplayingProcessor, create_broadcast
import numpy
def create_default_filter_stack():
stack = [LargeFilter(), S... |
import sys
import json
import time
import logging
import time
import random
from kafka import KafkaConsumer
from kafka import KafkaProducer
from kafka.errors import KafkaError
from opentracing.propagation import Format
from opentracing import child_of, follows_from
from jaeger_client import Config
from jaeg... |
"""
instabot example
Workflow:
Like last images with hashtags from file.
"""
import sys
import os
import time
import random
from tqdm import tqdm
sys.path.append(os.path.join(sys.path[0], '../'))
from instabot import Bot
if len(sys.argv) != 2:
print("USAGE: Pass a path to the file with hashtags.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.