text stringlengths 38 1.54M |
|---|
#!/usr/bin/env python
"""
Copyright (c) 2012, 2013, 2014 Centarra Networks, Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice, this permission notice and all necessary source code
to recompile the softwa... |
from django.db import models
from .organization import Organization
class TaskList(models.Model):
title = models.CharField(max_length=100)
datetime = models.DateTimeField(auto_now_add=True, null=True)
organization = models.ForeignKey(Organization, on_delete=models.PROTECT)
class Meta:
orderin... |
import unittest
from main import scale
class TestSum(unittest.TestCase):
a = "abcd\nefgh\nijkl\nmnop"
r = "aabbccdd\naabbccdd\naabbccdd\neeffgghh\neeffgghh\neeffgghh\niijjkkll\niijjkkll\niijjkkll\nmmnnoopp\nmmnnoopp\nmmnnoopp"
def test(self):
self.assertEqual(scale(self.a, 2, 3), self.r)
... |
from math import *
from collections import *
from heapq import *
class Solution:
def minCost(self, maxTime: int, edges, passingFees) -> int:
# fee, vertex, time
q = [(passingFees[0], 0, 0)]
n = len(passingFees)
times = [inf] * n
adj_lst = defaultdict(list)
for (s, e,... |
# Copyright 2017 The Forseti Security 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 required by ap... |
import numpy as np
from sklearn import linear_model
from sklearn import preprocessing
from sklearn import metrics,neighbors
import matplotlib.pyplot as plt
from sklearn.cross_validation import train_test_split,cross_val_score
Observations = np.genfromtxt("./Observations.csv",dtype = float,defaultfmt = "%.3e",delimiter... |
from flask import Flask, jsonify
import requests
from flask_cors import CORS
from os import link
import os
from bs4 import BeautifulSoup
import re
import json
import yfinance as yf
from pymongo import MongoClient
# mongo DB
client = MongoClient(os.environ.get('MONGO_DB', 'localhost'), 27017)
db = client.news
posts = d... |
print ("11")
print ("10")
print ("9")
print ("8")
print ("7")
print ("6")
print ("5")
print ("4")
print ("3")
print ("2")
print ("1") |
import socket
import os
import shutil
import logging
import json
import hashlib
import binascii
from threading import Thread
"""
pwd - print working directory name
ls - shows inner of working dir
cat <filename> - shows inner of file
mkdir <dir name> - make dir
remdir <dir name> - delete dir with evrthng ... |
from django.db import models
from django.contrib.auth.models import User, UserManager
#class User(models.Model):
# username=models.CharField(max_lenght=30)
# password=models.CharField(max_lenght=70)
# Email=models.models.EmailField(max_length=254)
class UserprofileInfo(models.Model):
user = models.One... |
import tkinter
top = tkinter.Tk()
hello = tkinter.Label(top, text='Hello World!')
hello.pack()
quit_tk = tkinter.Button(top, text='QUIT', command=top.quit, bg='red', fg='white')
quit_tk.pack(fill=tkinter.X, expand=1)
tkinter.mainloop()
|
# importamos lo necesario para el formato de la entrada
import datetime
import os
import sys
import re
import time
import numpy as np
try:
import imdb
except ImportError:
imdb = None
from tabulate import tabulate
from pprintpp import pprint
# blank node
# a ConjunctiveGraph is an aggregation of all the named ... |
from Lib.common.ConfigLoader import ConfigLoader
from Lib.common.DriverData import DriverData
from Lib.common.Log import Log
from Lib.temasekproperties.HomePage import HomePage
from Lib.temasekproperties.Listings import Listings
from Lib.temasekproperties.LogIn import LogIn
from Lib.temasekproperties.Resources import R... |
import math
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.utils.model_zoo as model_zoo
import pdb
__all__ = ['C3D', 'c3d_v1']
class C3D(nn.Module):
def __init__(self,
sample_size,
sample_duration,
num_classes=400):
super(... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
import numpy as np
import scipy as sp
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import seaborn as sns
from multiprocessing import Pool
y = np.array([4, 3, 4, 5, 5, 2, 3, 1, 4, 0, 1, 5, 5, 6, 5, 4, 4, 5, 3, 4])
N_comb_y = sp.misc.c... |
import datetime
from django.db import models
class IssueManager(models.Manager):
"""An Issue manager to define custom calculation methods for object
istances
"""
def get_solved_issue_durations(self):
"""A manager method that returns time durations for all solved issues
"""
dur... |
# encoding: UTF-8
"""
展示如何执行策略回测。
"""
from __future__ import division
from vnpy.trader.app.ctaStrategy.ctaBacktesting import BacktestingEngine
from vnpy.trader.app.ctaStrategy.ctaBase import *
if __name__ == '__main__':
from strategyBollBand import BollBandsStrategy
# 创建回测引擎
engine = BacktestingEngine... |
#!/usr/bin/env python
# -*-coding:utf-8-*-
import pygame
from pygame.locals import *
import copy
import pgwidth
import pgrect
import pgrect_window
import time
class rect:
def __init__ (self,root,rt,ima_lo) :
""
s... |
import json
import os
import falcon
class StudentReportJSON:
def __init__(self):
self._json_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '../..', 'media',
'student_report.json')
def on_get(self, req, resp):
with open(self._json_path... |
import torch
import torch.nn as nn
import physics_aware_training.digital_twin_utils
class SplitInputParameterNet(nn.Module):
def __init__(self,
input_dim,
nparams,
output_dim,
parameterNunits = [100,100,100],
internalNunits =... |
import FWCore.ParameterSet.Config as cms
process = cms.Process("Test")
process.source = cms.Source("EmptySource")
process.options.numberOfStreams = 2
process.a = cms.EDProducer("edmtest::one::WatchLumiBlocksProducer", transitions = cms.int32(0))
process.p = cms.Path(process.a)
|
from os import listdir
from os.path import isfile, join, abspath
image_path = abspath('./images')
onlyfiles = [f for f in listdir(image_path) if isfile(join(image_path, f))]
readme = '''# awesome-video-chat-backgrounds
Just in case you're at home on a video call and you haven't had time to tidy up your REAL backgrou... |
from enum import Enum
class Sensortype(Enum):
Door = 0
Infrared = 1
Water = 2
Smoke = 3
Temperature = 4
class Recordtype(Enum):
Door = 0
Infrared = 1
Water = 2
Smoke = 3
Temperature = 4
class Onoff():
On = 1
Off = 0
class Status():
Success = 0
Fail = 1 |
from flask import Flask, render_template, request, redirect, session, flash
import re
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
app = Flask(__name__)
app.secret_key = '&@DHDJ^^(%^(^^^G@#$@#!@EDQADSG'
@app.route('/')
def index():
return render_template("index.html")
# check all in... |
"""
伙伴模块
"""
# -*- encoding=utf8 -*-
__author__ = "Lee.li"
from airtest.core.api import *
from multi_processframe.ProjectTools import common, common, common
def monster(start, devices):
"""
伙伴测试脚本
:param devices:
:return:
"""
poco = common.deviceconnect(devices)
check_menu("SysDMonster", po... |
"""
# -*- coding: utf-8 -*-
# 写代码是热爱,写到世界充满爱!
# @Author:AI悦创 @DateTime :2019/10/1 13:13 @Function :数据库连接 Development_tool :PyCharm
# code is far away from bugs with the god animal protecting
I love animals. They taste delicious.
┏┓ ┏┓
┏┛┻━━━┛┻┓
┃ ☃ ┃
... |
from lxml import html
import requests
domain = 'https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/speechcon-reference'
page = requests.get(domain)
tree = html.fromstring(page.content)
responce = tree.xpath('//audio/@title')
print(responce)
|
from django.conf.urls import url
from .views import (
SubjectListAPIView,
SubjectCreateAPIView,
SubjectDetailAPIView
)
urlpatterns = [
url(r'^$', SubjectListAPIView.as_view(), name='list'),
url(r'^create/$', SubjectCreateAPIView.as_view(), name='create'),
url(r'^(?P<id>\d+)/$', SubjectDetailAP... |
# -*- coding: utf-8 -*-
# @File : get_info_jd.py
# @Author: KingJX
# @Date : 2019/1/19
""""""
import requests
import json
from lxml import etree
def get_url_page(url):
"""
获取页面信息
:param url: 传入页面地址
:return:
"""
headers = {
"User-Agent": "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT ... |
# Copyright 2019 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
1391. Check if There is a Valid Path in a Grid
Given a m x n grid. Each cell of the grid represents a street. The street of grid[i][j] can be:
1 which means a street connecting the left cell and the right cell.
2 which means a street connecting the upper cell and the lower cell.
3 which means a street connecting the l... |
from alpaca_trade_api.rest import REST,TimeFrame
import pandas as pd
class Mercado:
def __init__(self, agent_hodings: dict, agent_cash: dict, api_key: str, secret_key: str, live: bool) -> None:
"""
A class used to represent an Animal
...
Attributes
----------
api... |
from TinhToan import giaTriTheoKhuc
from MayInNhanh import *
# Tính thử về lợi nhuận
daySoLuong = [1,50,100,150,200]
dayLoiNhuan = [50,60,70,80,90]
#print(giaTriTheoKhuc(daySoLuong, dayLoiNhuan, 52))
#1). Dữ liệu cơ bản 01 hớ số lượng bắt đầu 1
daySoLuongCB01 = [1,50,100,150,200,250,300,350,400,450,500,550,600,650,70... |
from django.contrib import admin
from django.utils.safestring import mark_safe
from Profile.models import PostWall, Reviews, LikePost
from mptt.admin import MPTTModelAdmin
@admin.register(PostWall)
class PostWallAdmin(admin.ModelAdmin):
list_display = ('id', 'des', 'user', 'get_image')
def get_image(self, obj... |
import FWCore.ParameterSet.Config as cms
# define all the changes for unganging ME1a
def unganged_me1a(process):
### CSC geometry customization:
#from Configuration.StandardSequences.GeometryDB_cff import *
if not process.es_producers_().has_key('idealForDigiCSCGeometry'):
process.load('Geome... |
#!/usr/bin/python
import os
import sys
import glob
map = {
'Professional': 'STND',
'People': 'PEPL',
'Planner': 'PLNR',
}
for name in ['STND', 'PEPL', 'PLNR']:
deb = glob.glob('/home/tualatrix/Sources/pagico/%s/*.deb' % name)[0]
new_deb = deb.replace('karmic1', name)
os.system('mv %s %s' % (... |
import datetime
create_time=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(create_time)
print(type(create_time))
data={}
print(data["img"]) |
import csv
def inputParse(file):
f = open(file)
reader = csv.reader(f)
headers = reader.next()
summary = {}
pat_index = headers.index('DESYNPUF_ID')
claim_index = headers.index('CLM_PMT_AMT')
diag1_index = headers.index('ICD9_DGNS_CD_1')
diag2_index = headers.index('ICD9_DGNS_CD_2')
diag3_index = header... |
# Generated by Django 2.2.5 on 2019-09-14 22:41
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('mesfactory', '0001_initial'),
]
operations = [
migrations.AlterModelTable(
name='factory',
table='factory',
),
... |
import sys
import numpy as np
import random
import matplotlib.pyplot as plt
## change Path ##
sys.path.append("/home/elkin/university/gradSchool/Fall2020/CS472/CS472")
from tools import arff, splitData, generatePerceptronData, graph_tools,list2csv
import itertools
import mlp
from sklearn.neural_network import MLPClassi... |
#!/usr/bin/env python3
import argparse, logging, paramiko, socket, sys, os
class InvalidUsername(Exception):
pass
# malicious function to malform packet
def add_boolean(*args, **kwargs):
pass
# function that'll be overwritten to malform the packet
old_service_accept = paramiko.auth_handler.AuthHandler._client_ha... |
import copy
from collections.abc import Iterable
import numpy as np
__all__ = ["load", "TimeSeries", "DEFAULT_MAX_TIME", "DEFAULT_ERROR_VALUE"]
DEFAULT_MAX_TIME = 1.0
DEFAULT_ERROR_VALUE = 1e-4
def _ndim(x):
"""Return number of dimensions for a (possibly ragged) array."""
n = 0
while isinstance(x, Ite... |
# -*- coding: utf-8 -*-
"""ResNet model.
Related papers:
https://arxiv.org/pdf/1603.05027v2.pdf
https://arxiv.org/pdf/1512.03385v1.pdf
https://arxiv.org/pdf/1605.07146v1.pdf
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.training i... |
"""
Utils for the approaches
"""
import math
from typing import Union, Optional, Tuple, List, Dict
# We executed the code on strong CPU clusters without an GPU (ssh compute). Because of this extraordinary
# executing environment, we introduce this flag. To reproduce the results in the paper, enable this flag.
execute_... |
#!/usr/bin/env python
import datetime
import os
from datetime import timedelta
from stock import stockImport
sk = stockImport()
#start_date = datetime.date(2016, 12, 20)
#today = datetime.date(2016, 12, 30)
#start_date = datetime.date(2009, 9, 25)
#start_date = datetime.date(2004, 2, 11)
stocks = []
scan_date = date... |
lista = list()
for c in range(1, 6):
lista.append(int(input('Digite Um Numero: ')))
print(f'\nO Menor valor Foi {min(lista)} Na {lista.index(min(lista)) + 1}ª Posição')
print(f'O Maior valor Foi {max(lista)} Na {lista.index(max(lista)) + 1}ª Posição')
|
FORM_NUM = 7
# DATA FORM
DF_SCALAR = 0
DF_VECTOR = 1
DF_PAIR = 2
DF_MATRIX = 3
DF_SET = 4
DF_DICTIONARY = 5
DF_TABLE = 6
DF_CHART = 7
TYPE_NUM = 27
# DATA TYPE
DT_VOID = 0
DT_BOOL = 1
DT_BYTE = 2
DT_SHORT = 3
DT_INT = 4
DT_LONG = 5
DT_DATE = 6
DT_MONTH = 7
DT_TIME = 8
DT_MINUTE = 9
DT_SECOND = 10
DT_DATETIME = 11
DT_... |
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
import scrapy
class OfferItem(scrapy.Item):
technologies = scrapy.Field()
city = scrapy.Field()
salary = scrapy.Field()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Audio sinusoidal waves generator.
---------------------------------
Can be used to generate waves of the particular frequency,
or sum of all frequencies for frequency response measurements.
"""
import argparse
import numpy
import sounddevice
SAMPLING =... |
import pyopenjtalk
from ttslearn.tacotron.frontend.openjtalk import pp_symbols
def test_pp_symbols_kurihara():
# 参考文献に載っている例
# Ref: Prosodic Features Control by Symbols as Input of Sequence-to-Sequence
# Acoustic Modeling for Neural TTS
for text, expected in [
# NOTE: 参考文献では、「お伝えします」が一つのアクセント句... |
# USAGE
import keras
from keras.models import load_model
from keras.models import Model
from keras.layers import Dense
from keras.utils.vis_utils import plot_model
from keras.utils.generic_utils import CustomObjectScope
from keras.callbacks import ModelCheckpoint, EarlyStopping
from keras.preprocessing.image import Ima... |
import jinja2
import os
import string
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir))
class PlayerFormInput:
keys = list(string.ascii_uppercase) + list(string.digits) + ['LEFT', 'RIGHT', 'UP', 'DOWN']
colors = [... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.MaterialCreateInfo import MaterialCreateInfo
class AntMerchantExpandFrontcategorySecurityCreateModel(object):
def __init__(self):
self._description = None
sel... |
#!/usr/bin/env python
'''
unit tests for split_fasta.py
'''
from SmileTrain.test import fake_fh
import unittest
from SmileTrain import split_fasta
class TestSplitFastaEntries(unittest.TestCase):
def setUp(self):
self.fh = fake_fh(">foo\nAAA\n>bar\nCCC\n>baz\nTTT\n>poo\nGGG\n")
def test_correct(s... |
import psycopg2
def database_creator():
try:
conn = psycopg2.connect(database="raidforum",user="saugat1",password="saugat123",host = "127.0.0.1",port = "5432")
cur = conn.cursor()
print(cur)
table_schema1 = '''CREATE TABLE IF NOT EXISTS posts(
post_id INT GENERATED ALW... |
"""
For loops are called count controlled iteration
Unlike while loops that are controlled by a condition
for loops run a certain number of times and then stop.
The i variable after the key word for is the loop variable
Each time the loop executes the loop variable is incremented
The value of the loop variable starts a... |
import requests
headers = {"User-Agent":"hui bo tou zi fen xi/2.5.5 (iPhone; iOS 14.4; Scale/2.00)",
"Cookie":"safedog-flow-item=B51B3C6B0CC13D2D20E9766C4E571EB8",
"Accept-Language":"zh-Hans-CN;q=1, en-CN;q=0.9, zh-Hant-CN;q=0.8, el-CN;q=0.7",
"Content-Length":"52", "Accept-Encoding":"... |
from django.contrib import admin
from .models import *
@admin.register(AdditionalInfo)
class AdditionalInfoAdmin(admin.ModelAdmin):
search_fields = ['name']
list_display = ('canonical', 'candidate', 'name', 'title',)
@admin.register(Candidate)
class CandidateAdmin(admin.ModelAdmin):
search_fields = ['cand... |
class ClickHouse:
@staticmethod
def read_settings_async():
from envparse import env
env.read_envfile()
config = dict()
config["url"] = env("CH_URL")
config["user"] = env("CH_USER")
config["password"] = env("CH_PASS")
return config
@staticmethod
... |
'''
At CodeSignal the users can get to the top of the leaderboard by earning XP (experience points) in different modes. The leaderboard is sorted by players XP in descending order, and in case of a tie - by their ids in ascending order.
Your task is to implement an algorithm that will return the state of the weekly le... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import os
import sys
import abc
import time
import struct
import serial
import threading
import collections as col
from types import SimpleNamespace
from datetime import datetime
from threading import Thread, Event
if sys.version_info.major == 2:
import subprocess32 ... |
from pprint import pprint
from bs4 import BeautifulSoup
import requests
import json
from Task4 import *
top_movies = scrape_top_list()
def get_movie_list_details(movie_list):
listOfUrl=[]
scrapMoviesList10=[]
i=0
while i<len(movie_list):
listOfUrl.append(movie_list[i]['url'])
scrap_data=s... |
"""
VERSION
- Python 3
FUNCTION
- Write image urls to files
"""
import os
import pandas as pd
import requests
import multiprocessing
from optparse import OptionParser
import pickle as pkl
op = OptionParser()
op.add_option('--clss', action='store', type=str,
help='The image class (e.g., vietnam war).')... |
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def widthOfBinaryTree(root):
queue = [(root, 0, 0)]
cur_depth = left = ans = 0
for node, depth, pos in queue:
if node:
queue.append((node.left, depth+1, pos*2))
... |
import copy
import numpy as np
np.random.seed(1)
def sigmoid(x):
output = 1/(1 + np.exp(-x))
return output
def sigmoid_derivative(x):
derivative = x*(1-x)
return derivative
#dataset generation
int2binary = {}
binary_dim = 8
largest_number = pow(2,binary_dim)
binary = np.unpackbits(np.array([range(largest_nu... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os.path
import glob
import numpy as np
from scipy.special import erfinv
from sklearn.decomposition import PCA
from matplotlib import pyplot as plt
from matplotlib.patches import Ellipse
from collections import OrderedDict
input_file, title, scale_of_the_scales = ('... |
import pandas as pd
from sqlalchemy import create_engine
MYSQL_USER = os.environ["MYSQL_USER"]
MYSQL_PASSWORD = os.environ["MYSQL_PASSWORD"]
MYSQL_HOST = os.environ["MYSQL_HOST"]
MYSQL_DATABASE = os.environ["MYSQL_DATABASE"]
mysql_engine = create_engine(f'mysql+pymysql://{MYSQL_USER}:{MYSQL_PASSWORD}@{MYSQL_HOST}/{MY... |
# 2014.10.18 14:41:34 Central European Daylight Time
#Embedded file name: scripts/client/gui/Scaleform/daapi/view/lobby/profile/ProfileAchievementSection.py
from gui.shared import g_itemsCache
from gui.Scaleform.daapi.view.lobby.profile.ProfileSection import ProfileSection
from gui.Scaleform.daapi.view.meta.Profile... |
from selenium.webdriver.remote.webdriver import WebDriver
from homework_zfh.test_frame.handle_black import handle_black
class BasePage:
def __init__(self, driver: WebDriver = None):
self.driver = driver
@handle_black
def find(self, locator):
return self.driver.find_element(*locator)
... |
#####################################################################################################################################################################
#
# Grzegorz M Koczyk (2007-)
#
# Decomposition of protein structures into loops
#
######################################################################... |
#John F. Lake, Jr.
#This is the handler for /movies/, /movies/{movieID}, /reset/, and /reset/{movieID}
import cherrypy
from _movie_database import _movie_database
import json
class Movies(object):
@cherrypy.tools.json_in()
#Load in all of the data.
def __init__(self,DB):
self.API_KEY = 'AAAAAAAB'
self.myD... |
'''
Write a pseudo-code to move from the start (S) to the end (E) in the maze.
Note: You can drag and drop the pseudo-code magnets to the pseudo-code box and create the appropriate pseudo-code.
'''
while(start!=end) do
if(Is_Next_Block_Bomp) then
move Down
move Dowm
else
move Right
end-if
end-while
|
import random
from cimensa.models import Words
class Homegame:
def __init__(self):
self.page_title = 'Games'
words = Words.objects.raw("SELECT id, word, part_of_speech, definition FROM cimensa_words ORDER BY RAND() LIMIT 6")
rnd = random.random()
self.correct = 1+int(6 * rnd)
... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='aug_c'),
] |
import json
from django import forms
from django.apps import apps
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http.response import HttpResponse, HttpResponseBadRequest
from django.shortcuts import render, get_object_or_404
from django.core.urlresolvers import reverse
from django.views import ... |
"""
LED
Author: Robert Ross
Outputs data to the led on the indicated pin
"""
import RPi.GPIO as GPIO
class LED:
"""
Handles the control of an LED
"""
def __init__(self, dataPin=4):
"""
Create the object to talk to the LED
Keyword arguments:
dataPin - the pin that... |
import itertools
INDEX = 1000000
permutation_list = list(itertools.permutations(range(10)))
permutation_list.sort()
output = list(permutation_list[INDEX - 1])
output = map(str, output)
print ''.join(output)
|
# -*- coding: utf-8 -*-
"""A daily rotating file."""
from threading import Lock
from time import localtime
from time import mktime
from time import strftime
from time import time
class RotatorInfo:
"""information about a rotating file."""
def __init__(self, base, format='.%y%m%d'):
self._base = base... |
# Generated by Django 2.0 on 2021-05-11 09:13
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('barter', '0004_auto_202104... |
from django.contrib import admin
from .models import Product, userProducts, UserProfile
# creating a list for the admin page view
@admin.register(UserProfile)
class UserProfile(admin.ModelAdmin):
list_display = ("user", "first_name", 'last_name', 'phone_number')
@admin.register(Product)
class ProductAdmin(admin.M... |
"""12. Using Ternary operator or COnditional operator: Identify minimum of three numbers """
a = 10
b = 20
c = 3
print(a if (a < b and a < c) else (b if (b < a and b < c)else c))
|
from django.shortcuts import render
# Create your views here.
def demo_home(request):
# if request.user.is_authenticated():
return render(request, "demo_home.html", {})
# else:
#return render(request, "registration/login.html", {})
def demo_sales(request):
# if request.user.is_authenticated():
... |
import numpy as np
import os
from utils.utils import from_csv_with_filenames
from utils.constants import Constants
#import matplotlib.pyplot as plt
from collections import OrderedDict
CSV_PATH = os.path.join(
Constants.DATA_FOLDER,
'10classes',
'audio_data.csv'
)
def ge... |
import traceback
from .video_input import WebcamVideoStream
from .image_processing_utils import *
from . import *
close_flag = False
def on_close(event):
global close_flag
close_flag = True
color_names = {0:"white", 1:"red", 2:"blue", 3:"orange", 4:"green", 5:"yellow", -2: "gray", -1:"purple?"}
def face_equ... |
"""
Dictionary
* Translator playground
📚 Resources:
https://www.youtube.com/watch?v=rfscVS0vtbw&t=1s&ab_channel=freeCodeCamp.org
"""
vowel = ['a', 'e', 'i', 'o', 'u']
# Translate function: If letter is a vowel, we transform it to g
def translate(phrase):
translation = ''
for letter in phrase:
if let... |
import sys
from PyQt5.uic import loadUi
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QDialog, QApplication, QWidget
from PyQt5.QtGui import QPixmap
from qt_material import apply_stylesheet # pip install qt-material
class WelcomeScreen(QDialog):
def __init__(self):
super(WelcomeScreen, self)._... |
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from scrapy.loader import ItemLoader
from scraper.items import MatchItem as Match
import json
class FutureSpider(CrawlSpider):
name = 'future'
start_urls = [
'http://www.d... |
a = int(input())
b = int(input())
indeks = a
while indeks <= b:
if indeks%2 == 0:
print(indeks)
indeks += 1
for a in range(b):
if a%2 == 0:
print(a) |
"""
#十進制轉換
(若為 C 語言,請使用一個 loop 和 function call)
給予一個十進位整數,請撰寫一程式可以將此十進位整數轉換為指定的進制的整數。
輸入說明:
輸入分為兩部份,包括指定的進制數
(2 ~ 16)
與十進位整數(0 ~ 1000000000)
輸出說明:
經轉換後的新進位制的整數( y )
不合法的輸入則輸出E
input:
16 1234
output:
4D2
----------------------
Input:
8 56456456
Output:
327272410
-----------------------
Input:
11 ... |
import couchdb
import urllib2
import json
dbName = 'tweets3'
ServerUrl = "http://127.0.0.1:5984/"
designName = 'suburbs'
server = couchdb.Server(ServerUrl)
db = server[dbName]
test_view = """function (doc) {
emit(doc.suburb, 1);
}"""
design = {'views': {"sub_lst": {'map': test_view, 'reduce': '_count'}}, 'languag... |
import base64
# base64编码原理:https://blog.csdn.net/zhubaoJay/article/details/72957135
'''
print(base64.b64encode(b'binary\x00string'))
print(base64.b64decode(b'YmluYXJ5AHN0cmluZw=='))
print(base64.b64encode(b'i\xb7\x1d\xfb\xef\xff'))
print(base64.urlsafe_b64encode(b'i\xb7\x1d\xfb\xef\xff'))
# 标准base64编码后可能出现+和/,在URL中不能直接... |
from functools import reduce
def knot_hash_round(lst, lengths, pos, skip):
for l in lengths:
rev = list(reversed([lst[(pos + i) % len(lst)] for i in range(l)]))
for i in range(l):
lst[(pos + i) % len(lst)] = rev[i]
pos += (l + skip) % len(lst)
skip += 1
return pos, s... |
#!/usr/bin/env python3
if __name__ == "__main__":
while True:
i = int(input())
if i == -1:
break
d = 0
tot = 0
for ii in range(i):
s, t = list(map(int, input().split()))
t = t-d
d+=t
tot += t * s
print("... |
"""
Solution for 340. Longest Substring with At Most K Distinct Characters
https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/
"""
from collections import defaultdict
from collections import OrderedDict
class Solution:
"""
Runtime: 72 ms, faster than 86.01% of Python3 online submiss... |
from typing import Optional, Union
__all__ = ["MissingSerializerError", "IncompleteOrCorruptedStreamError"]
class MissingSerializerError(Exception):
"""
Raised when trying to serialize a value whose type is not registered
with a serializer.
"""
class IncompleteOrCorruptedStreamError(Exception):
... |
import numpy as np
import pandas as pd
#creating a series from list
mylist=['m','h','n']
print(pd.Series(data=mylist))
print('\n')
#changing or assigning labels
labels =['bad', 'good', 'unknown']
print(pd.Series(data=mylist,index=labels))
print('\n')
#creating a series from np array
array=np.array([2... |
def m_func(n_1, n_2, n_3):
m_list = [n_1, n_2, n_3]
try:
m_list.remove(min(m_list))
return sum(m_list)
except TypeError:
return 'Error'
print(m_func(n_1=15, n_2=5, n_3=10))
|
n = int(input())
t = list(map(int, input().split()))
m = int(input())
P, X = [], []
for i in range(m):
p, x = map(int, input().split())
P.append(p)
X.append(x)
s = 0
dic = {}
for i in range(n):
s += t[i]
dic[i] = t[i]
for i in range(m):
k = dic[P[i]-1]
print(s-k+X[i])
|
#
# SPDX-License-Identifier: Apache-2.0
#
# Copyright 2020 Andrey Pleshakov
#
# 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... |
def maxReach(arr):
maxReachPos = 0
for i, num in enumerate(arr):
if maxReachPos < i:
return False
maxReachPos = max(maxReachPos, num+i)
if maxReachPos >= len(arr):
return True
return False
arr = [1, 0, 8, 8, 4, 2, 0, 0, 2, 1, 0]
res = maxReach(arr)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.