text stringlengths 8 6.05M |
|---|
__author__='RodrigoMachado'
__license__ = "MIT"
__version__ = "1.0.1"
__status__ = "Production"
__copyright__ = "Copyright 2019"
__maintainer__ = "RodrigoMachado9"
__email__ = "rodrigo.machado3.14@hotmail.com"
__credits__ = ["Python is life", "Live the opensource world"]
from sql_alchemy import banco
from sqlalchemy i... |
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
cursor = self
string = ''
while cursor != None:
string += '{}, '.format(cursor.val)
cursor = cursor.next
return '[' + string + ']'
def list_to... |
mat = open('problem81.txt','r')
raw_path = mat.read().split('\n')
path = []
for y in raw_path:
path.append(y.split(','))
for y in range(0,len(path)):
for x in range(0,len(path[0])):
path[y][x] = int(path[y][x])
mat.close()
## Gets the matrix into a readable form of integers
## First value represents ve... |
#!/usr/bin/env python3
import sys
def even(integers):
for i in integers:
if i % 2 == 0:
yield i
def main(lines):
for i in even(map(int, lines)):
try:
print(i)
except BrokenPipeError:
break
if __name__ == '__main__':
main(sys.stdin)
|
X = int(input("Digite o valor de X: "))
Y = int(input("Digite o valor de Y: "))
F = 2*X + 2*(Y**2)
print(F) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This is an example on homography estimation using OpenCV
Created on Tue Sep 12 21:01:53 2017
@author: gholguin
"""
# Imports
import cv2
import numpy as np
# Variable global que se pueda compartir con el callback
puntos_click = list()
# -----------------------------... |
#!/usr/bin/env python3
import numpy as np
from keras import Input, Model, Sequential
from keras.layers import BatchNormalization, Conv2DTranspose, LeakyReLU, Conv2D, Activation, Flatten, Dense, Reshape, \
Lambda
from keras import backend as K
def create_models():
n_channels = 3 + 1
image_shape = (64, 64... |
# coding: utf-8
import xadmin
from .models import UserComments, UserMessage, UserLearn
class UserCommentsAdmin(object):
list_display = ['user', 'comment_id', 'comment_type', 'comments', 'add_time']
class UserMessageAdmin(object):
list_display = ["email", "message", "has_read", "add_time"]
search_field... |
#!/usr/bin/env python
from __future__ import print_function, unicode_literals
# ConnectHandler
from netmiko import Netmiko
from getpass import getpass
net_conn = Netmiko(host="cisco1.twb-tech.com", username='pyclass', password=getpass(), device_type='cisco_ios')
print(net_conn.find_prompt())
|
# feature selection
logreg = LogisticRegression()
rfe = RFE(logreg, n_features_to_select=15)
rfe = rfe.fit(X_sm, Y_sm)
print(rfe.support_)
print(rfe.ranking_)
# building
logit_model=sm.Logit(Y_sm,X_selected)
result=logit_model.fit()
print(result.summary2())
logreg = LogisticRegression()
logreg.fit(X_train, y_train)... |
import datetime
import re
class Field:
name: str = None
def __init__(self, fixed_length=None, validators=None, trim=None):
self.fixed_length = fixed_length
if self.fixed_length and trim is None:
self.trim = True
else:
self.trim = trim
def __set_name__(self... |
from time import sleep
import numpy as np
import random
import copy
import os
def formatmap(num):
global x, y
x = [3, 3, 3, 3, 3, 3, 3, 3, 3, 3]
y = [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
map1[num][y[num]][x[num]] = 2
for i in range(10):
if i % 2 == 0:
for j in range(7):
... |
cache = []
MAXLEN = 0
def checkUni():
pass
def bfs(n):
global MAXLEN
if n == MAXLEN - 1: # 종료조건 - 마지막 index에 도달
return 0
s = 0
for i in range(n+1, MAXLEN):
s += bfs(i)
return s
def solution(relation):
global MAXLEN
MAXLEN = len(relation[0])
answer = 0
return an... |
#!/usr/bin/env python
"""
_Test_
Component that can parse a cvs log
and generate a file for generating test that map
to developers responsible for the test.
"""
from __future__ import print_function
import os
import unittest
import WMCore.WMInit
try:
from commands import getstatusoutput
except ImportError:
... |
# %%
# This script will recompute epochs and restore them in memory dir (see deploy.py).
# It uses multiprocessing to operate, and it requires a long time to complete.
# You can run the script as following.
# python recompute_epochs.py >> running.log
# %%
import multiprocessing
from tools.data_manager import DataMana... |
n=int(input())
a=int()
a==2
while a<=n:
if n%a==0:
print('No')
else:
a+=1
if a==n:
print('YES') |
# drop_char.py
#
# a function that uses a List Comprehension to take a string and
#returns a list of all lower case strings you can obtain by removing
# a single character.
# Usage:
# % python drop_char.py
#
# Himanshu Mohan, Nov 11, 2019
from typing import List
def drop_char(word: str) -> List[str]:
"Ret... |
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view
from packages.models import PackageSettings
from packages.serializers import PackageSettingsSerializer
@api_view(["get", "put", "delete"])
def PackageSettingsView(request):
def save_or_... |
#!/usr/bin/env python
from setuptools import Command, find_packages, setup
version = '0.8.10'
class PyTest(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import sys, subprocess
try:
from py import test as pytest
exce... |
import numpy as np
from ..psychopy.psychopy_line import psychopy_line
from .zollner_parameters import _zollner_parameters
def _zollner_psychopy(window, parameters=None, **kwargs):
# Create white canvas and get drawing context
if parameters is None:
parameters = _zollner_parameters(**kwargs)
# L... |
# @Title: 同构字符串 (Isomorphic Strings)
# @Author: 2464512446@qq.com
# @Date: 2020-12-28 16:12:46
# @Runtime: 48 ms
# @Memory: 17.1 MB
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
d1,d2 = defaultdict(list), defaultdict(list)
for index,i in enumerate(s):
d1[i].append(ind... |
import uuid
from http import HTTPStatus
from flask_restful import Resource, reqparse, fields, marshal
from flask_jwt_extended import (
create_access_token,
create_refresh_token,
jwt_required,
jwt_refresh_token_required,
get_jwt_identity,
get_raw_jwt
)
from flask import current_app, request, make_response,... |
if __name__ == "__main__":
T = 0
while True:
T += 1
s = input()
if s == "END":
break
sections = s.split("*")
if s[0] == "*":
sections = sections[1:]
if s[-1] == "*":
sections = sections[:-1]
if sections:
t... |
"""
Make a plot of the UVIS cosmic ray rate as a function of spacecraft
suborbital position. Shows that there is an enhancement in the CR
rate at longitudes near the magnetic poles, not just in the SAA.
"""
import numpy as np
from astropy.coordinates import Angle
import ephem
def archived_tle():
"""
Return a... |
from abc import abstractmethod
from Domain.FacesCollection import FacesCollection
class FaceHeuristic:
def __init__(self, type: str):
self.type = type
@abstractmethod
def filterFaces(self, faceCollection: FacesCollection) -> FacesCollection:
pass
class NonHeuristic(FaceHeuristic):
d... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import copy
TYPE_A = 1
TYPE_B = 2
def entropy(prob):
p = prob*(1-2e-10) + 1e-10
return -torch.dot(p, torch.log(p))
class DcpConfig():
def __init__(self, n_param=1, split_type=TYPE_A, reuse_gate=None):
self.n_par... |
from abc import ABCMeta, abstractmethod, abstractproperty
__all__ = ['literalvalidator', 'complexvalidator']
class MODE(object):
"""Validation modes
NONE: always true
SIMPLE: mimeType check
STRICT: can be opened using standard library (e.g. GDAL)
VERYSTRICT: Schema passes
"""
NONE = 0
... |
import scrapy
import time
from os import walk
import json
import datetime
class PropertySpider(scrapy.Spider):
name = "property"
def start_requests(self):
urls = []
for url in urls:
time.sleep(1.5)
yield scrapy.Request(url=url, callback=self.parse_property)
d... |
from decocare import lib
from decocare import commands
import logging
import time
log = logging.getLogger( ).getChild(__name__)
"""
0x8d == 141 == ReadPumpModel
0000000: 0000 0028 5101 3636 3534 3535 0000 0000 ...(Q.665455....
0000010: 0000 0000 0000 1221 0500 0000 0000 0000 .......!........
0000020: 0700 0000 30a... |
#coding:utf-8
from service.service import Service
from dao.database import Database
from repository.task import TaskRepository
from repository.project import ProjectRepository
class TopDisplayService(Service):
def __init__(self):
pass
def execute(self):
db = Database()
task_repo = Task... |
from google.appengine.ext import db
from ragendja.auth.google_models import User as BaseUser
class User(BaseUser):
"""Represents a user in the system"""
pickled_tokens = db.BlobProperty()
class Document(db.Model):
"""Represents a Document in the system"""
user = db.ReferenceProperty(User,required=... |
import discord
from .utils import checks
from discord.ext import commands
from cogs.utils.dataIO import dataIO
import os
from datetime import datetime as dt
import random
import asyncio
class ChannelDraw:
"""Draws a random message from a set"""
__author__ = "mikeshardmind"
__version__ = "2.2a"
def _... |
#!/usr/bin/env python
"""
_GetCompletedFilesByRun_
Oracle implementation of Subscription.GetCompletedFilesByRun
"""
from WMCore.WMBS.MySQL.Subscriptions.GetCompletedFilesByRun import \
GetCompletedFilesByRun as GetCompletedFilesByRunMySQL
class GetCompletedFilesByRun(GetCompletedFilesByRunMySQL):
pass
|
#!/usr/bin/env python3
# Names: Sophia Trump, Eunsoo Jang, Maria Vivanco, Emily Lobel
# File: makeCleanDictionary.py
# Description: Takes 3 dictionary files and cleans them, saving the mega combined cleaned dictionary
# into a file called "cleanedDictionary.txt".
# Run in the cmd with python3 makeCleanDictionary.py <... |
# General Imports
from django.core.mail import send_mail
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
import secrets as python_secrets
import json
# Model Imports
from apps.Espn import models as espn_models
def creat... |
from django.db import models
from swgraph.models import DateTimeModel
from people.models import People
class Transport(DateTimeModel):
name = models.CharField(max_length=40)
model = models.CharField(max_length=40)
manufacturer = models.CharField(max_length=80)
cost_in_credits = models.CharField(max_le... |
from django.shortcuts import render
from django.views.generic import ListView
from app.models import News
import logging
logger = logging.getLogger(__name__)
# Create your views here.
class NewsList(ListView):
model = News
def get_queryset(self):
logger.debug(f"Request to NewsList from user: {self.re... |
from tkinter import *
import base64
# Initialize window
root = Tk()
root.geometry("590x540")
root.title("Encode & Decode Messages")
root.config(bg="light blue")
# Label
Label(root, text="Encode & Decode Messages", font="aerial 25 italic", bg="light blue").pack()
# Define variables
Text = StringVar()
private_key = St... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
sys.path.append("../..")
import json
import logging
from flask import Flask, request
from keras_bert_ner.utils.predict import build_trained_model, get_model_inputs
class A... |
import os
import io
import time
import subprocess
import sys
from threading import Thread
import datetime
import tarfile
import ctypes
import shutil
import webbrowser
from enum import Enum
from system_hotkey import SystemHotkey
import yaml
import win32api
import win32gui
import win32process
import win32con
import keyb... |
def longest_palindromic_substring(s):
if s == '':
return 0
# Use list for inner function visit. Python2 does not support nonlocal.
max_start = [0]
max_length = [1]
def trace(l, r, initial_length):
length = initial_length
while l >= 0 and r < ... |
# ----------------Break------------------------
print("Example of break:\n")
for letter in 'Python':
if letter == 'h':
break
print('Current Letter :\t', letter)
var = 10
while var > 0:
var = var - 1
if var == 5:
break
print('Current variable value :\t', var)
# ---------------Contin... |
from django.shortcuts import render,get_object_or_404,render_to_response
from blog.models import Blog,Post,Tag, DocumentForm, Document
from django.contrib.auth import authenticate, login,logout
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.models import User
import re,copy
from dja... |
#!/opt/conda/bin/python
import pandas
from keras.layers import concatenate, Dropout
import numpy
from math import sqrt
from keras.callbacks import EarlyStopping
import statsmodels.api as sm
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler, LabelEncoder
import keras
from keras import layers... |
import json
import os
import praw
import pdb
import re
import copy
from functools import wraps
def set_default(obj):
if isinstance(obj, set):
return list(obj)
raise TypeError
def options_sub(options, keys):
return dict((k, options[k]) for k in keys)
class Reddit(object):
# Config/Options st... |
from django.urls import path
from . import views
urlpatterns = [
path('signup/', views.sign_up, name='signup'),
path('profile/<str:username>/', views.profile, name='profile'),
path('profile/update/<int:pk>/', views.update_profile, name='update_profile'),
path('profile/picture/<int:pk>/', views.update_... |
import pandas as pd
import time
def get_event_sv():
# Ask the user what game they want to select, then ask which event of that list
# Need to add checks of when there is no event in game or when user does not select valid event !!!
game_map = pd.read_csv('../data/game_map.csv') # Obtain the map between g... |
#coding:utf-8
import os
import sys;
# reload(sys);
# sys.setdefaultencoding("utf8")
# import sys
# sys.setdefaultencoding('utf-8')
path = '/Users/zy/Downloads/pdf/'
generatorWalk= os.walk(path)
fileLists = []
for root, dirs, files in os.walk(path):
# files 是一个内存地址 直接输入不会受到任何转码指令的影响
print("Root=",root, "di... |
if __name__ == "__main__":
n = int(input())
CURRENT = 0
MIN = 0
for _ in range(n):
CURRENT += int(input())
MIN = min(MIN, CURRENT)
print(abs(MIN))
|
# ==================================================================================================
# Copyright 2012 Twitter, Inc.
# --------------------------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi... |
from utility import Global
class Data:
def __init__(self, t=0, ns=500, r=1, k=1, nw=1, prefix=None, f_TYPE_TEST=None, f_nwlen=None, f_mds=None, relativePath=None, fp=None):
if fp==None:
self.prefix = prefix
self.t = t
self.ns = ns
self.r = r
self.... |
import os
import math
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
from sklearn.model_selection import train_test_split, StratifiedKFold
from tensorflow.keras.models import Model, load_model
from tensorflow.keras.layers import Input, Dense, C... |
import numpy as np
from numpy import pi
from numpy import cos
from numpy import sin
from numpy import exp
from numpy import sqrt
def cross_in_tray_function(params):
f = -0.0001 * (abs(sin(params[0]) * sin(params[1]) * exp(abs(100 - sqrt(params[0]**2 + params[1]**2)/pi))) + 1)**0.1
return f
def himmelblau_func... |
import argparse
import logging
import os
import sys
import systemstat
class SystemStatTool(systemstat.SystemStat):
def __init__(self,logfile='systemstat.log', **kwargs):
self.options = None
self.logger = logging.getLogger(__name__)
self.command_parser = argparse.ArgumentParser()
... |
from flask import Flask,jsonify,request
from flask_pymongo import PyMongo
from bson.json_util import dumps
from flask_cors import CORS
from numpy.core.numeric import NaN
from model.plagiarism import cosine_distance_countvectorizer_method
import json
app =Flask(__name__)
CORS(app)
cors = CORS(app,resources = {
r"/*... |
import logging
# Network communication default port
DEFAULT_PORT = 7777
# Current logging level
LOGGING_LEVEL = logging.DEBUG
# Max connections queue
MAX_CONNECTIONS = 5
# Max message length (in bytes)
MAX_PACKAGE_LENGTH = 1024
# Project encoding
ENCODING = 'utf-8'
# Protocol keys
ACTION = 'action'
TIME = 'time'
... |
from py2neo import Graph, Node, Relationship
from bs4 import BeautifulSoup
import requests, json, sys
graph = Graph(password="fhdiGEN82&sk@PLD")
trans = graph.begin()
# For each movie, get the image src property
for node in graph.nodes.match("Person"):
if node['image'] == '' : continue
elif node['image'] is n... |
from django.test import TestCase, Client
from django.urls import reverse
from django.contrib.auth import get_user_model
from .models import Profile
class ProfileModelTest(TestCase):
# Test the height stringification on a normal case
def test_height_normal(self):
prof = create_user().profile
pr... |
#!/usr/bin/python
# coding: utf-8
# Screensaver for imagizer
from __future__ import division, print_function, with_statement
__author__ = "Jérôme Kieffer"
__date__ = "06/01/2016"
__copyright__ = "Jerome Kieffer"
__license__ = "GPLv3+"
__contact__ = "Jerome.Kieffer@terre-adelie.org"
import sys
import os
import gc
imp... |
import psycopg2
import pandas as pd
import numpy as np
import datetime
from sklearn.metrics.pairwise import cosine_similarity
connection = psycopg2.connect("host='localhost' dbname='movies_db_demo' user='postgres' password='tiendat148'")
mycursor = connection.cursor()
class User_User_CF(object):
def __init__(self... |
import csv
output = set()
with open("/home/basar/Downloads/icd10cm_codes_2020.txt") as f:
for line in f :
line = line.split(None, 1)
if line[0].startswith('S') :
line[0] = line[0][:3]
output.add(line[0])
print(list(output))
print(len(output))
|
from bibliopixel.animation import BaseStripAnim
import bibliopixel.colors as colors
import time
class RGBClock(BaseStripAnim):
"""RGB Clock done with RGB LED strip(s)"""
def __init__(self, led, hStart, hEnd, mStart, mEnd, sStart, sEnd):
super(RGBClock, self).__init__(led, 0, -1)
if hEnd < hSta... |
def insertion_sort(arr):
index_length = range(1, len(arr))
for i in index_length:
right = arr[i]
while arr[i-1] > right and i>0:
arr[i], arr[i-1] = arr[i-1], arr[i]
i -= 1
return arr
|
import collections
from django.core.management.base import BaseCommand
from pizzeria.order import models
def add_sizes():
for label, inches, base_cost, topping_cost in (
('Extra Large', 16, 13.95, 2.25),
('Large', 14, 11.95, 1.85),
('Medium', 12, 9.95, 1.50),
('Sma... |
class SlidingWindow:
def minSubArrayLen(self, s, nums):
# corner case
if not nums or len(nums) == 0:
return 0
# two pointers sliding window
left_idx = right_idx = 0
cur_sum = nums[0]
valid_flag = False
min_size = len(nums)
while ri... |
import re
class Solution:
def addBinary(self, a: str, b: str) -> str:
maxLength = max(len(a),len(b))
minLength = min(len(a),len(b))
resZero = ""
for i in range(maxLength-minLength):
resZero+="0"
if len(a)==minLength:
a = resZero+a
else:
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
from PIL import Image
import numpy
frame = 10
def get_image(video_path, image_path):
try:
os.system('ffmpeg -i {0} -r {1} -f image2 {2}\%05d.png'.format(video_path, frame, image_path))
except:
print('ERROR !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!') |
# %%
import os
import sys
import pickle
import multiprocessing
import mne
from mne.decoding import Vectorizer
from sklearn import svm
from sklearn import metrics
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')... |
import fitsio
import numpy as np
import numpy.random as npr
from scipy.optimize import minimize
from scipy import interpolate
from funkyyak import grad, numpy_wrapper as np
from redshift_utils import load_data_clean_split, project_to_bands, fit_weights_given_basis
from slicesample import slicesample
import matplotlib.p... |
s: str
n: int = 10
s = 'a'
def is_equal(n1: int, n2: int) -> bool:
return n1 == n2
print(is_equal(3, 3))
|
from datetime import timedelta
from sedate import utcnow
from uuid import uuid4
from pytest import mark
@mark.flaky(reruns=3)
def test_audit_for_course(client, scenario):
"""
Story:
For a course with refresh interval,
an admin checks the list of attendees.
This list contains when the attendee last... |
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session
# SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db"
SQLALCHEMY_DATABASE_URL = "postgresql://api:secret@localhost/fastapidb"
engine = create_engine(SQLALCHEMY_DATABASE_URL)
Ses... |
a=[1,4,9,16,25,36,49.64,81,100]
b=[]
for i in range(0,len(a)):
if (int(a[i])%2==0):
b.append(a[i])
print(b)
|
from Loan import Loan
def main():
annualInterestRate = eval(input ("Enter yearly interest rate, for example, 7.25: "))
numberOfYears = eval(input("Enter number of years as an integer: "))
loanAmount = eval(input("Enter loan amount, for example, 120000.95: "))
borrower = input("Enter a borrower's name: ... |
#!/usr/bin/python
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import sys
import re
from collections import namedtuple
import parse_gc_graph
import argparse
# get... |
import urllib
from bs4 import BeautifulSoup
from xlwt import *
import random
book_name=""
book_num=""
book_name = input("请输入书名:")
book_name1 = urllib.parse.quote(book_name.encode('gb2312'))
url = "http://www.biquyun.com/modules/article/soshu.php?searchkey="+book_name1
fileHandle = open ( book_name+'.txt', 'a',enco... |
"""
Owner: Noctsol
Contributors: N/A
Date Created: 2021-10-24
Summary:
Holds all the custom Exceptions for this project
"""
############################ EXCEPTIONS ############################
class EnvVarNotSet(Exception):
'''Exception for when we didn't load'''
def __init__(self):
self.messag... |
__author__ = 'Stuart'
from flask import jsonify
from app.exceptions import ValidationError
from . import api
def bad_request(message):
response = jsonify({'error':'bad request', 'message':message})
response.status_code = 400
return response
def unauthorized(message):
"""
When login credentials i... |
from __future__ import print_function
from rosetta import *
# from random import randint, random
# import sys
# import time
import lasagne
import numpy as np
import theano
import theano.tensor as ten
# import prep_v031 as prep
from predict_type2p import build_network
from toolbox import get_secstruct
from toolbox i... |
from asyncio import coroutine
from tornado import gen
from tornado.ioloop import IOLoop
from tornado.web import asynchronous
import tornado.websocket
import json
from core.player import Player
from core.server import Server
import time
from multiprocessing.managers import BaseManager
class ListManager(BaseManager): pas... |
poem = '''There was a young lady named Bright,
Whose speed was far faster than light;
She started one day
In a relative way,
And returned on the previous night.'''
lines1 = ["One", "Two", "Three", "Four", "Five"]
lines2 = ["One\n", "Two\n", "Three\n", "Four\n", "Five\n"]
fout = open('./ch08/relativity1.txt', 'wt')
fo... |
# import pygame
from network import Network
import msvcrt as m
run = True
n = Network()
# startPos = read_pos(n.getPos())
# p = Player(startPos[0],startPos[1],100,100,(0,255,0))
# p2 = Player(0,0,100,100,(255,0,0))
while run:
message=""
if m.getch():
message=str(input("Type your messa... |
from flask import Flask, request, redirect, render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://build-a-blog:helloworld@localhost:8889/build-a-blog'
app.config['SQLALCHEMY_ECHO'] = True
db = SQLAlchemy(app)
d... |
import math
import time
import logging
import itertools
import paramiko
def download_file_from_pepper(config, remote_path, local_path):
"""Download a file via SFTP from the pepper to a local file system."""
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.conne... |
"""
Configuration for docs
"""
# source_link = "https://github.com/[org_name]/oj_custom"
# docs_base_url = "https://[org_name].github.io/oj_custom"
# headline = "App that does everything"
# sub_heading = "Yes, you got that right the first time, everything"
def get_context(context):
context.brand_html = "OJ Custom"
|
import array as arr
a = arr.array ('i',[2,5,8,4,5,1,2])
print(a)
#import array as arr
#to declare array use arrayname = arr.array
#array length
print(len(a))
#add elements in array
a.append(7)
print(a)
#extend elements in array
a.extend([4,5])
print(a)
#insert value in array
a.insert(3,5)
print(a)
#remove elem... |
# coding:utf-8
import json
from django.shortcuts import render, reverse
from django.http import HttpResponseRedirect, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import authenticate, login, logout
def LoginCheck(request):
user = request.user
if user.is_active:
... |
hex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
bin = ['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111']
s = input()
result = ''
negativeFlag = False
if s >= '7f':
print("that's not my work :)")
... |
# Generated by Django 2.0.7 on 2018-07-06 23:07
from os.path import abspath, dirname, join
from django.db import migrations
BASE = join(abspath(dirname(__file__)), '..', 'sql')
with open(join(BASE, 'audit_0002.sql'), 'r') as f:
sql = f.read()
def update_triggers(apps, schema_editor):
for Model in apps.get_m... |
names=["laoliu",100,3.14,"laowang"]#描述大量相同型建议使用列表
#增
names.append("老杨")#增加一个元素
names.insert(0,"八戒")
names2=["葫芦娃","猴子"]
print(names+names2)#合并进去但不改变names
print(names.extend(names2))#合并列表,追加到后面且改变names值
#删
names.pop()#删除最后一个(栈:先进后出,后进先出的特点)
names.remove("老杨")#从左删一个
del names[1]#删除第二个元素
# del names[2:5] #删第三个到底六个
# del... |
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
value = 1
while (value*value <= x):
value += 1
return int(value-1) |
import cv2
from darkflow.net.build import TFNet
import matplotlib.pyplot as plt
options = {
'model': 'cfg/yolo.cfg',
'load': 'bin/yolov2.weights',
'threshold': 0.3,
'gpu': 1.0
}
tfnet = TFNet(options)
vidcap = cv2.VideoCapture(0)
def getFrame(sec):
vidcap.set(cv2.CAP_PROP_POS_MSEC,... |
import sys, os, importlib, json, multiprocessing, time
import rasterio, pycountry
import reverse_geocode
import geopandas as gpd
import pandas as pd
from urllib.request import urlopen
from shapely.geometry import Point
from shapely.ops import nearest_points
from shapely import wkt
# Import GOST libraries... |
import numpy as np
import matplotlib.pyplot as plt
from error_functions import mean_square_error
from math import log
def closed_form_lin_reg(X, y, query, ridge_regression=False, lambda_reg=2):
X_t = np.transpose(X)
inv_body = np.dot(X_t, X)
if ridge_regression:
inv_body += lambda_reg * np.identit... |
#!/usr/bin/env python
import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import pandas_datareader.data as web
pd.set_option('display.expand_frame_repr', False)
style.use('ggplot')
start = dt.datetime(2017, 1, 1)
end = dt.datetime.now()
df = web.DataReader('TSLA'... |
a = input()
x = (len(a)+1)//2
b = (a[x:len(a)])
c = (a[0:x])
print(b, end='')
print(c) |
def make_sandwich(bread_name, *toppings):
print("Making a " + bread_name + " with: ")
for topping in toppings:
print("- " + topping)
make_sandwich("Italian herb and cheeses", "Tomato", "Lettuce", "Chicken")
make_sandwich("Brown bread", "Meatball", "Paprika")
make_sandwich("Tosti bread", "Cheese", "Ham... |
def bin_to_int(binary):
"""
Convert a binary to an integer.
Runs O(log n).
"""
x = str(binary)
power = 0
sum = 0
for i in range(1, len(str(binary))+1):
if x[-i] == str(1):
sum += 2**power
power += 1
return int(sum)
def test_cases():
assert bin_to_int(1001) =... |
#Write a function called count_capital_consonants. This
#function should take as input a string, and return as output
#a single integer. The number the function returns should be
#the count of characters from the string that were capital
#consonants. For this problem, consider Y a consonant.
#
#For example:
#
# count_c... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Jeffrey.Sun
import numpy as np
import tensorflow as tf
PAD_ID = 0
def variable_scope(name):
def decorator(func):
def wrapper(*args, **kwargs):
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
return func(*args, **kwa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.