text stringlengths 8 6.05M |
|---|
a = 10
a = 4
a = 80
print("a")
|
from flask import Flask, render_template, request
import xmlrpc.client
server = xmlrpc.client.ServerProxy('http://127.0.0.1:8080')
app = Flask(__name__)
@app.route('/submit', methods=['post', 'get'])
def submit():
data = {}
pesan = [1, 2, 3]
if request.method == 'POST':
data['nama'] =... |
'''
Contains the L{Parser} class for parsing a header file for
function definitions and user-defined types.
@author: Erik Schmidt
@contact: emschmitty@gmail.com
@organization: Carnegie Mellon University
@since: October 23, 2011
'''
import xml.dom.minidom as xml
import logging
import os
import dllexp
imp... |
# coding:utf-8
import threading, Queue, sys
import requests, re
class RedisUN(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self._queue = queue
def run(self):
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, l... |
import torch
import torchaudio
import torchvision
import torchtext
# import torchcsprng
print(torch.__version__)
print(torchaudio.__version__)
print(torchvision.__version__)
print(torchtext.__version__)
# print(torchcsprng.__version__)
|
import requests
import json
name = input('User name: ')
r = requests.get(f'https://api.github.com/users/{name}/repos')
r = r.json()
list_of_repo = []
for el in r:
list_of_repo.append(el['name'])
my_dict = {"user": name, "repo": list_of_repo}
json_obj = json.dumps(my_dict)
with open('data.json', 'w') as f:
... |
#!/usr/bin/python
import pprint
pp = pprint.PrettyPrinter(indent=4, width=120, depth=3)
import sys
import numpy as np
import pygame as pg
from genotype import *
from phenotype import *
from neat import *
# from numeric_3d
def in2pi(a):
""" Brings an angle in the range between -pi and +pi """
if a > np.pi:
... |
import _lib
import re
import time
def StartNodeInteractive(datadir, address, port,comment = ""):
_lib.StartTest("Start node (debug) "+comment)
res = _lib.ExecuteHangNode(['startintnode','-datadir',datadir,'-port',port,'-minter',address],datadir)
_lib.FatalAssertSubstr(res,"Process started","No process star... |
import os
directory = os.path.join('..','logswithexp')
if not os.path.exists(d):
os.makedirs(d)
for root,dirs,files in os.walk('.'):
for f in files:
log = open(f,'r')
for line in log:
if 'SystemAnalysis-Snapshot' in line:
print os.path.basename(f)
os... |
"""
Stuff
"""
import sys
import os
import fbx
from brenpy.qt.bpQtImportUtils import QtCore
from brenpy.qt.bpQtImportUtils import QtWidgets
from brenfbx.utils import bfFbxUtils
from brenpy.qt import bpQtCore
# from brenrig.sandbox import fbx_prototype_01
from brenfbx.fbxsdk.core import bfProperty
from brenpy.qt.i... |
#coding=utf-8
#2: how to get bigger version?
version1 = [1,22,2,6,3,1]
version2 = [1,22,2,4,5]
def cmp(s1,s2):
if s1 == s2:
return 0
elif s1 > s2:
return 1
elif s1 < s2:
return -1
def check_ver(v1,v2):
#The base line should be the smaller length List
for i in range(mi... |
import sys
import collections
sys.path.append('../')
from leetCodeUtil import ListNode
from leetCodeUtil import TreeNode
class Interview(object):
def normalizeString(self, s):
string = s.split()
return ' '.join(string)
def checkPairsIntervalOverlap(self, nums):
nums.sort(key=lambda ... |
from django.shortcuts import render_to_response
from chaos import settings
from core import SWARM
import datetime
import os
def render_chaos(request):
def decode_dt_param(str_dt):
date, time = str_dt.split('T')
dt = datetime.datetime.strptime(
'%s %s' %
(date, time), '%Y-%m... |
# Generated by Django 2.0.7 on 2019-01-05 18:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('basedata', '0029_auto_20190104_1627'),
]
operations = [
migrations.AlterField(
model_name='device',
name='workflow_n... |
import os
import sys
main_dir = os.path.split(os.getcwd())[0]
result_dir = main_dir + '/results'
sys.path.append(main_dir)
from data import fmri_data_cv as fmril
from data import fmri_data_cv_rh as fmrir
from data import meg_data_cv as meg
import scipy.io
main_dir = os.path.split(os.getcwd())[0]
scipy.io.savemat(ma... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def findTilt(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None:
return 0
... |
from PIL import Image
def numLivingNeighbours(board, i, j, xDim, yDim):
count = 0
if i>0:
if j > 0:
count += board[i-1][j-1]
count+=board[i-1][j]
if j<xDim-1:
count+=board[i-1][j+1]
if j>0:
count += board[i][j-1]
if j<xDim-1:
count+=board[i... |
lista1 = ["abacate", "melancia", "abacaxi"]
lista2 = [1, 2, 3, 4, 5]
lista3 = ["abacaxi", 1, 9.98, True]
# tamanho do vetor
tamanho = len(lista2)
print(tamanho, "\n")
# método append() -> adicionar itens
lista1.append("limao")
print(lista1, "\n")
#verificar se existe determinado item a lista
# uso a palavra reserva... |
from aiogram import Bot, Dispatcher
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from .configs import bot as config
from .configs import messages
from . import routes
if not config.API_TOKEN:
msg = messages.SPECIFY_TOKEN_TEMPLATE.format(
config.API_TOKEN_ENV,
)
raise RuntimeError(m... |
# Generated by Django 3.2.5 on 2021-07-12 13:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0005_post_is_featured'),
]
operations = [
migrations.AlterField(
model_name='post',
name='is_featured',
... |
# Load pretrained weights
pretrained_dict = torch.load(pretrained_path)
# Get model state dicts
model_dict = model.state_dict()
# Filter out unnecessary keys
pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}
# Overwrite entries in the existing state dict
model_dict.update(pretrained_dict) ... |
# -*- coding: utf-8 -*-
import logging
from datetime import datetime
import json
import os
import random
import numpy as np
import torch
from torch.utils.data import (DataLoader, SequentialSampler,TensorDataset)
from torch.utils.data.distributed import DistributedSampler
from tqdm import tqdm
from pyto... |
def sqroot(num):
if(type(num)==int):
print 'The square root of the number is ',num**0.5
else:
print 'Please Enter integers'
def addition(num1,num2):
if(type(num1)==int and (type(num2)==int)):
print 'The sum of the numbers is :',num1+num2
else:
print 'Please Enter integer... |
"""
Algoritmo para realizar la suma aritmetica del 1 al n
"""
"""
Aqui puedes cambiar el valor de n
"""
n = 1000000000
suma = 00
suma2 = 00
"""
Algoritmo 1. Se utiliza la formula (n * (n + 1))/2 para realizar la suma
"""
suma = (n * (n + 1)) / 2
print 'La suma es', suma
"""
Algoritmo 2. Se utiliza un ciclo for pa... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2019-11-30 06:34
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('web', '0004_remove_deploytask_deploy_servers'),
]
op... |
import os
import numpy as np
from sklearn.ensemble import BaggingClassifier
from sklearn.model_selection import GridSearchCV, StratifiedKFold, train_test_split
from sklearn.neighbors import KNeighborsClassifier
from machine_learning.aux import directories
from machine_learning.aux.persist import save_model
from machi... |
import os
from flask import render_template, url_for, flash,redirect, request
from flaskblog2 import app, db, bcrypt
from flaskblog2.forms import RegistrationForm, LoginForm,UpdateAccountForm,PostForm
from flaskblog2.models import User, Post
from flask_login import login_user, logout_user, current_user, login_required
... |
from django.shortcuts import render
from.serializers import TaskSerializers,UserSerializers
from.models import Task
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated,AllowAny
from django.contrib.auth import get_user_model
from rest_framework.generics import CreateAPIView
from re... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
w=[]
n=int(input())
for i in range(1,10):
for j in range(1,5):
w.append(str(i)*j)
for i in range(n):
s=input()
cnt=0
for k in w:
cnt+=len(k)
if s==k:
print(cnt)
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Collections',
fields=[
('id', models.AutoField(... |
#the application wrapper
# connect data grid with drawing context here...
import sys
import os
import time
import datetime
from progress.bar import Bar
from db import ConfUtil
from GraphContext import GraphCtx # plotting
from CsvContext import CsvContext #no ui mode
class Application:
"""
Bring all blocks ... |
import sys
input_file = 'Day 1\\Input.csv'
text_file = open(input_file)
lines = text_file.read().split(', ')
# lines = "R2, L3" # Answer = 5
# lines = "R2, R2, R2" # Answer = 2
# lines = "R5, L5, R5, R3" # Answer = 12
# lines = "R8, R4, R4, R8"
direction = []
blocks = []
# for line in lines.split(', '): # F... |
from .Section import *
from .ExperimentImages import *
class SectionImage(Section):
def __init__(self, api, data):
"""
Internal use only: initialize section object
"""
if (not(data==None) & (type(data) == dict) &
("sectionType" in data.keys())
):
... |
#!/usr/bin/env python
import subprocess
n = 100
count = 0
for i in range(n):
res = subprocess.check_output(["./ml_por", "a.param"])
#print(res)
if(res.find("equal", 0, len(res)) != -1):
# equals
count += 1
else:
print("Failed at iteraction no. " + str(i))
print("Worked: " + str(count) + "/" + str(n) + " (... |
from pseudoQuicksort import quicksort
FILE = "file.txt"
lst = []
with open(FILE) as file:
for line in file:
lst.append(int(line.replace('\n','')))
quicksort(lst) |
Import('env')
sources = Split("""
g4display.cc
utilities.cc
displayUI.cc
tabs/gcamera.cc
tabs/gslice.cc
""")
lib = env.Library(source = sources, target = "../lib/g4display")
|
class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
rowIndex += 1 # XXX: Quick and dirty fix.
bufs = [[1]*rowIndex, [1]*rowIndex]
current_buf_index = 0
for row_no in range(3, rowIndex + 1):
c... |
def copy(L):
l = []
for i in L:
l.append(i)
return l
def sort(N, L):
for i in range(N):
for j in range(N-i-1):
if(L[j] > L[j+1]):
L[j], L[j+1] = L[j+1], L[j]
return L
def SynchronizingTables(N, ids, salary):
N = N
copy_ids = copy(ids)
cop... |
#!/usr/bin/env python3
import os, sys
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)
import json
from scripts.logger import log
from scripts import utils
def get_alerts_endpoint(namespace: str) -> (str):
prometheus_route = utils.get_cmd_ou... |
from django.shortcuts import render
from django.views.generic import ListView, DetailView,CreateView,DeleteView,UpdateView
from .models import PnModel
from django.urls import reverse_lazy
# Create your views here.
class PnList(ListView):
template_name = 'list.html'
model = PnModel #表示したいモデルをmodels.pyから選択して、モデル... |
'''
Charlie has been given an assignment by his Professor to strip the links and the text name from the html pages.
A html link is of the form,
<a href="http://www.hackerrank.com">HackerRank</a>
Where a is the tag and href is an attribute which holds the link charlie is interested in. The text name is HackerRank.
... |
from django.db import models
from django.urls import reverse
# Create your models here.
class PageCategory(models.Model):
name = models.CharField(max_length=255, unique=True)
def __str__(self):
return self.name
class Title(models.Model):
title = models.CharField(max_length=255)
category = ... |
import smtplib
#from twilio.rest import Client
#from twython import Twython
def gmail(msg,eml,pwd,teml):
content = msg
mail = smtplib.SMTP('smtp.gmail.com',587)
mail.ehlo()
mail.starttls()
mail.login(eml,pwd)
mail.sendmail('Notification',teml,content)
mail.close();
... |
def make_tags(tag, word):
output = "<" + tag + ">" + word + "</" + tag + ">"
return output
def cigar_party(cigars, is_weekend):
if is_weekend == True:
if cigars>=40:
return True
else:
return False
else:
if cigars>=40 and cigars<= 60:
return True
else:
return False
def sum2(num... |
def f(a):
if a in range (10):
print (' '*a +'Hello World!')
f(0)
f(1)
f(2)
f(3)
f(4)
f(5)
f(6)
f(7)
f(8)
f(9)
|
import csv
import faker
import random
fake = faker.Faker()
positions = ('Developer', 'Manager', 'Admin', 'Assistant', 'Analytic')
departments = ('Develop', 'QA', 'Maintenance', 'DevOps', 'EndUser service')
class Employee:
"""Represented single Employee object"""
fio: str
Position: str
Department: str... |
import tensorflow as tf
import pandas as pd
import numpy as np
data = pd.read_csv('indices.csv', delimiter=',', header=None).to_numpy()
x_train, y_train = data[:, 0], data[:, 1]
model = tf.keras.models.load_model('model.h5')
print(model.evaluate(x_train, y_train))
|
"""scanless.exceptions"""
class ScannerNotFound(Exception):
pass
class ScannerRequestError(Exception):
pass
|
# Doubly Linked List
# Triple: [value, triple_or_none, triple_or_none]
# Raymond <--> Rachel <--> Matthew
VALUE, PREV, NEXT = 0, 1, 2
a = ['Raymond', None, None]
b = a[NEXT] = ['Rachel', a, None] # 1st make list, 2nd assign b, 3rd a[NEXT]
c = b[NEXT] = ['Matthew', b, None]
# TODO: Write a recursive algorithm that ... |
import pyowm
owm=pyowm.OWM('fa8be47e49ac1dc839e726120dda317b')
mgr=owm.weather_manager()
place=(input("Enter the city name : "))
obs=mgr.weather_at_place(place)
weather=obs.weather
temp_f=weather.temperature(unit='fahrenheit')['temp']
temp_c=weather.temperature(unit='celsius')['temp']
print(f'The Temperatur... |
from django import forms
from django.contrib.auth.models import User
from django.forms import inlineformset_factory
from .models import Post, Photo
from django.forms import formset_factory
MAX_PHOTOS = 10
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['description']
class ... |
from flask import Flask
from flask import Blueprint
from flask import request
from flask import jsonify
from flaskext.mysql import MySQL
from flask_cors import CORS, cross_origin
app= Flask(__name__)
mysql=MySQL()
app.config['MYSQL_DATABASE_USER'] ='root'
app.config['MYSQL_DATABASE_PASSWORD'] ='admi'
app.... |
import os, sys
import rasterio
import pandas as pd
import geopandas as gpd
import numpy as np
from scipy import interpolate
from rasterio import features
from rasterio.mask import mask
from rasterio.features import rasterize
from rasterio.warp import reproject, Resampling
def rasterize_od_results(inD, outFile, field... |
#!/usr/bin/python2.7
import datetime
import json
import time
import webapp2
import models
class GetLatest(webapp2.RequestHandler):
def get(self):
queries = []
for reporter in models.Reporter.all(keys_only=True):
queries.append(
models.Report.all()
.filter('reporter =', reporter)
... |
import numpy as np
try:
import numba
from spikeinterface.sortingcomponents.clustering.isocut5 import isocut5
HAVE_NUMBA = True
except ImportError:
HAVE_NUMBA = False
def test_isocut5():
print("hi", HAVE_NUMBA)
if not HAVE_NUMBA:
return
# test cases generated by calling the matla... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django import forms
from django.utils.translation import ugettext_lazy as _
from .models import Image
from .widgets import CropExample
from opps.core.widgets import OppsEditor
class ImageModelForm(forms.ModelForm):
crop_example = forms.CharField(label=_('Crop E... |
#!/usr/bin/python3
""" test state file """
from models.state import State
import unittest
from models.city import City
from models.base_model import BaseModel
from sqlalchemy.orm.collections import InstrumentedList
from datetime import datetime
import models
from models.engine.db_storage import DBStorage
from models.en... |
from os.path import join
import flowiz as fz
import glob
import matplotlib.pyplot as plt
from tqdm import tqdm
import sys
dataset='Mushroom'
datatype=['', 'orig', 'tip', 'inter', 'gdci', ]
typeindex=int(sys.argv[1]) # 把数字作为参数传进来
filepathFlo='./dataset/flo/inference/run.epoch-0-flow-field/'
filepathPng='./dataset/Vid... |
'''
要求:
输入一个字符串,按字典序打印出该字符串的所有排列。
例如输入字符串abc,则打印出由字符串a,b,c所能排列出来的所有字符串abc,acb,bac,cab和cba
分析:
求整个字符串的排列,可以看出两步:
首先求所有可能出现在第一个位置的字符,既把第一个字符和后面的所有字符交换
然后固定第一个字符,求后面所有的字符的排序,此时仍把后面的字符看成两部分,第一个字符和后面的字符
然后重复上述步骤
通过递归的方式,递归去处理确定字符值后的所有字符,递归的终止条件是需要处理的字符长度为1
'''
def permutation(data):
if len(data) <=1:
return [d... |
import logging
import requests
import base64
import time
class Server(object):
url = 'https://mlb.praetorian.com'
def __init__(self, log=None):
self.session = requests.session()
self.binary = None
self.bin_b64 = None
self.hash = None
self.wins = 0
self.targets ... |
#-*- encoding=utf8 -*-
#!/usr/bin/env python
import sys, operator, string
path_to_stop_words = '../BasicData/stop_words.txt'
path_to_text = '../BasicData/Pride_And_Prejudice.txt'
def characters(filename):
for line in open(filename):
for c in line:
yield c
def all_words(filename):
start_ch... |
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from method import *
a = np.array([[1,0,0],[0,0,1],[0,1,0]])
P1 = np.array([[1, 0, 0],\
[0,np.cos(np.pi/4),np.sin(np.pi/4)],\
[0,-np.sin(np.pi/4),np.cos(np.pi/4)]])
P2 = n... |
from PyQt5.QtWidgets import QWidget, QDialog, QInputDialog, QFileDialog
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtGui import QImage, QPalette, QBrush
from PyQt5.QtCore import QSize
import os
import shutil
import blank_displaying
SCREEN_SIZE = [700, 700]
class AddCustomLevel(QDialog, QWidget):
def __in... |
import numpy as np
import scipy as sp
import fitsio as fi
import glob
import tools.covariance as cv
import tools.n_of_z as nz
dirs={"xip":"shear_xi/", "xim":"shear_xi/"}
datavector_names={"xip":("theta","xiplus"), "xim":("theta","ximinus")}
realspace_lookup={"xip":True, "xim":True}
corr={"xip":("ee","xi+"), "xim":("ee... |
from django.db import models
from django.contrib.auth.models import BaseUserManager,AbstractBaseUser
# Create your models here.
class UserManager(BaseUserManager):
def create_user(self, email, password=None):
if not email:
raise ValueError('User must have email address')
user=self.model(... |
inp = 3017957
test = 5
print("Test: " + str(int('0b' + bin(test)[3:] + '1', 2))) # Correct!
print("Part 1: " + str(int('0b' + bin(inp)[3:] + '1', 2))) # Correct!
i = 1
while i * 3 < inp:
i *= 3
print("Part 2: " + str(inp - i)) |
## Importation des modules
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders
Fromadd = "matthieu.devalle@telecomnancy.net"
Toadd = "matthieu.devalle@telecomnancy.net" ## Spécification des destinataires
... |
#writing to files
outfile= open('write.txt','w')
outfile.write('testing write ... ')
print ("testing123")
outfile.close() |
#!/usr/bin/env python3
#
# Development Order #3:
#
# This file will determine if this tool can run a test based on a test spec.
#
# Be sure to edit line 19, inserting the names of the tests the tool
# should be compatible with.
#
# exit statuses should be different based on error
import pscheduler
json = pschedul... |
{
'name': "Database restore",
'summary': 'Backups local restore',
'description': "Restore backups from local files",
'author': "Artem Shelest",
'website': "http://www.lumirang.com",
'category': 'Administration',
'version': '13.0.1.0',
'installable': True,
'depends': ['base'],
... |
# Copyright The OpenTelemetry Authors
#
# 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 applicable law or agreed to in ... |
from autumn.settings import Region
CALIBRATION_START = 100
CALIBRATION_END = 244
# Please keep this code in place
OPTI_REGIONS = [
Region.BELGIUM,
Region.FRANCE,
Region.ITALY,
Region.SPAIN,
Region.SWEDEN,
Region.UNITED_KINGDOM,
]
OPTI_ISO3S = [
"BEL",
"GBR",
"ITA",
"SWE",
... |
import utils
initial_facts = []
queries = []
def unpack_facts_to_list(facts):
"""
:param facts: string to decompose into a list of chars
:return: list of chars
Unpacking a string into a list of chars, used for initial facts
and queries
"""
lst_facts = []
for c in fact... |
import sys,pickle
from itertools import *
aspect = sys.argv[1]
f_actual = open('../data/input/test/'+aspect,'r')
predicted_labels = pickle.load(open('../data/predicted_labels.pkl','r'))
numerator = 0
denominator_system = 0
denominator_gold = 0
for lineno,line in enumerate(f_actual):
actual_line = int(line.split('\t... |
# -*- coding: utf8 -*-
import pandas as pd
import numpy as np
symPath='./prepareTrainSets/Indication.csv'
# disPath='datasets/prepareTrainSets/diseaseMatch.csv'
disDictName = "prepareTrainSets/disease_new2.dic"
symDictName = "prepareTrainSets/symptom_new2.dic"
bodyDictName = "prepareTrainSets/body中文身体部位名称.di... |
from database import *
from datetime import *
import types
from copy import deepcopy
config = {
'user': 'root',
'password': '123456',
'host': '127.0.0.1',
'charset': 'utf8',
'db' : 'mtdb',
}
database = database.current(config)
def checkDataType(obj):
attr_s = "%s,"
attr_d = "%d,"
... |
from flask import jsonify, session, g
from functools import wraps
from datetime import datetime
from app import redisClient
def check_permission(func):
@wraps(func)
def wrapper(*args, **kwargs):
session_id = session.get('session_id')
if not session_id:
return jsonify(error=False, au... |
# Copyright 2011 OpenStack LLC.
# 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 b... |
# Copyright 2016 Jochen Kursawe. See the LICENSE file at the top-level directory
# of this distribution and at https://github.com/kursawe/MCSTracker/blob/master/LICENSE.
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import sys
from os import path
from os.path import dirname
def make_all... |
#encoding: cinje
: from .. import table_args, caption_args
: def toprequestors ctx
<div class='table-responsive'>
<table #{table_args}>
<caption #{caption_args}>Top 10 Requestors</caption>
<tr><th># Requests</th><th>Requestor</th><th>Last Request</th></tr>
: for r in ctx.queries.get_top_requestors()
<tr>
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 5 18:10:25 2019
@author: hasee
"""
import cv2 as cv
img = cv.imread("E:\py/test.jpg")
cv.namedWindow("Image")
cv.imshow("Image",img)
cv.waitKey(0)
cv.destroyAllWindows() |
#!/usr/bin/python3
class Vertex:
def __init__(self, key):
self.id = key
self.connectedTo = {}
def addNeighbour(self, nbr, weight=0):
self.connectedTo[nbr] = weight
def __str__(self):
return str(self.id) + ' connectedTo: ' + str([x.id for x in self.connectedTo])
de... |
from collections import OrderedDict
import numpy as np
# This is pasted from massivepy.postprocess
def group_bins(bindata,n0=3):
"""
Group bins into annuli. Does the obvious thing for outer annuli.
Also groups the center single-fiber bins into annuli of approximately
equal radius, based on having n0 as... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 31 14:49:00 2020
@author: Dell
"""
###############################################################################
###############################################################################
###########################################################################... |
__author__ = "TUSHIT AGARWAL"
from requests import get
import json
from openpyxl import Workbook, load_workbook
import os
from random import shuffle, choice
from time import sleep
import gzip
import shutil
import urllib
import urllib.request
def kelvin_to_Celcius(k):
return (k - 273.15)
def... |
# -*- coding: utf-8 -*-
class dict_with_default(dict):
"""Dictionary that returns a default value when key is missing
:param default: default value to return when key is missing
"""
def __init__(self, default, *args, **kwargs):
super(dict_with_default, self).__init__(*args, **kwargs)
... |
import math
from tkinter import *
window = Tk()
c = Canvas(window, width=640, height=360, bg='grey')
c.pack()
def drawPoint(x, y, color):
c.create_rectangle(x-1, y-1, x, y, outline=color)
def drawTriangle(posX, posY, posX1, posY1, posX2, posY2, colour):
c.create_polygon(posX, posY, posX1, posY1, posX2, posY2,... |
one=input('Enter weight 1:\n')
two=input('Enter weight 2:\n')
three=input('Enter weight 3:\n')
four=input('Enter weight 4:\n')
l=[]
l.append(one)
l.append(two)
l.append(three)
l.append(four)
t=[float(i) for i in l]
print('Weights:',t)
n=len(t)
max=t[1]
avg=0
for i in t:
avg+=i
avg=avg/n
print()
print('Average weigh... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^map/$', views.index, name='index'),
url(r'^form/$', views.form, name='form'),
url(r'^form/post/$', views.post, name='post'),
url(r'^about/$', views.about, name='about')
] |
#!/usr/bin/env python3
# -*-coding: utf-8-*-
# Author : Christopher Lee
# License: MIT License
# File : downloader.py
# Date : 2016-12-29 22:41
# Version: 0.0.1
# Description: description of this file.
from time import sleep
import requests
from concurrent.futures import ThreadPoolExecutor
import pika
__version_... |
from . import reddit
print "Creating new reddit instance"
red = reddit.Reddit() |
import io
import json
import os
import sys
#time_container=[0]*60*24
month_container=[0]*12*8
mk=dict()
mk['Oct']=10
mk['Jan']=1
mk['Nov']=11
mk['Dec']=12
mk['Sep']=9
mk['Aug']=8
mk['Jul']=7
mk['Jun']=6
mk['May']=5
mk['Apr']=4
mk['Mar']=3
mk['Feb']=2
with open('succ.txt','r') as f:
for line in f:
if line ==... |
#!/usr/bin/python
# Update IATA & ICAO code for planes from Wikipedia
#
# Prereqs:
# virtualenv env
# source env/bin/activate
# curl https://bootstrap.pypa.io/get-pip.py | python
# pip install mysql-connector unittest
import argparse
import codecs
import mysql.connector
import sys
import urllib2
from collections impor... |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 20 11:09:53 2021
@author: user
"""
#key 1 將中間當作大迴圈
#key 2 用相乘計算
class Solution(object):
def numTeams(self, rating):
"""
:type rating: List[int]
:rtype: int
"""
c = 0
for i, value in enumerate(rating):
AB_c = ... |
from django.shortcuts import render
from django.shortcuts import get_object_or_404, render, render_to_response
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpResponse, Http404,JsonResponse
from django.core.mail import send_mail, EmailMessage
from django.co... |
def end_list(a):
return [a[0], a[-1]]
list = [i for i in range(1, 11)]
print(end_list(list))
|
"""
문제: X보다 작은 수
정수 N개로 이루어진 수열 A와 정수 X가 주어진다.
이때, A에서 X보다 작은 수를 모두 출력하는 프로그램을 작성하시오.
입력: 첫째 줄에 N과 X가 주어진다. (1 ≤ N, X ≤ 10,000)
둘째 줄에 수열 A를 이루는 정수 N개가 주어진다.
주어지는 정수는 모두 1보다 크거나 같고, 10,000보다 작거나 같은 정수이다.
출력: X보다 작은 수를 입력받은 순서대로 공백으로 구분해 출력한다.
X보다 작은 수는 적어도 하나 존재한다.
입력 예제:
10 5
1 10 4 9 2 3 8 5 7 6
츨략 예제:
1 4 2 3
me... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='UserInfo',
fields=[
('id', models.AutoField(ver... |
from django import forms
from .models import Team
class CreateTeamForm(forms.ModelForm):
class Meta:
model = Team
fields = ['title',]
class UserSearchForm(forms.Form):
username = forms.CharField(
label='',
widget=forms.TextInput(attrs={
'type': 'text',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.