index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
800
026e06e777d64f8724ec5e89a7829b3a42a25d6b
from flask import Flask, request, redirect, url_for, render_template from flask_modus import Modus from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate app = Flask(__name__) app.config[ 'SQLALCHEMY_DATABASE_URI'] = "postgres://localhost/flask_one_to_many" app.config['SQLALCHEMY_TRACK_MODIFICAT...
801
848934680253ff2950db7723b1fe82b2ae799900
# -*- coding: utf-8 -*- """ Noting is perfect, errors and timeouts may happen, and when such failures happen, the consumer has to decide what to do with that. By default, the consumer would reject the envelope (RabbitMQ message) when a failure happens. However, errors and timeouts issues, unless there is a software bug...
802
892eb8d1802b01c035993232cc80c710211ab102
#processes are described by generator functions #during the lifetime of a process, the process function(generator function) #creates events and yields them #when a process yields an event, it gets suspended #Simpy resumes the process when the event is triggered #multiple processes waiting on the same event is resumed...
803
1f69cf5f6d15048e6ead37b5da836c9e2f783f74
# The actual code begins here # This file is intended to load everything downloaded from loaddata.py, preventing user getting banned from IMDB # The code is written to see what are some key words of the reviews from critics and normal viewers # And to see what are some of the differences # The second task is to asses t...
804
e31267871453d87aee409f1c751c36908f7f151a
""" Package with a facade to the several expansion strategies. """ from acres.resolution import resolver __all__ = ['resolver']
805
be58862b66708c9de8cf7642c9de52ec744b079e
# $Header: //depot/cs/s/ajax_support.wsgi#10 $ from werkzeug.wrappers import Response from p.DRequest import DRequest from db.Support import SupportSession from db.Exceptions import DbError, SupportSessionExpired import db.Db as Db import db.Support import cgi import simplejson as json def application(environ, start_...
806
328a03acab2a0550bea0795d22110a152db6c503
# %% import os print(os.getcwd()) # %% from TransformerModel.Model import Model from dataset.DatasetLoader import DatasetLoader import pytorch_lightning as pl from pytorch_lightning.callbacks import EarlyStopping import argparse from argparse import ArgumentParser, ArgumentTypeError # %% def run_training(arguments_...
807
c712875273f988a3aa6dab61f79e99a077823060
#! /usr/bin/python # # convert the swig -debug-lsymbols output text file format into # a simple list of lua module names and classes # # Dan Wilcox <danomatika@gmail.com> 2017 # import sys import re if len(sys.argv) < 2: print("USAGE: lua_syntax.py MODULENAME INFILE") exit(0) module = sys.argv[1] infile = sys...
808
3d3b9956a98f11a170d66280abe7f193cef9ccfb
#%% # -*- coding: utf-8 -*- import numpy as np import plotly from plotly.subplots import make_subplots import plotly.graph_objects as go import pandas as pd import os output_directory = r'C:/Users/jgamm/Desktop/rssi_measurement/2020-06-10/figures' antennas = ['original_whip'] folder = r'C:/Users/jgamm/Desktop/rssi_me...
809
4cb601d7fc4023e145c6d510d27507214ddbd2d3
from django.shortcuts import render, redirect from .models import * from django.contrib.auth import authenticate ,login,logout from django.contrib.auth.models import User from datetime import date # Create your views here. def home(request): if request.method=='GET': daily_users = User.objects.f...
810
0ed99037d7ff708b7931fbc3553b1aeb19a20f53
''' * @file IntQueue.py * @author (original JAVA) William Fiset, william.alexandre.fiset@gmail.com * liujingkun, liujkon@gmail.com * (conversion to Python) Armin Zare Zadeh, ali.a.zarezadeh@gmail.com * @date 23 Jun 2020 * @version 0.1 * @brief This file contains an implementation of an inte...
811
acff8618754658104ac36214901d346447a0134f
import firebase_admin from firebase_admin import credentials from firebase_admin import db import paho.mqtt.client as mqtt # Fetch the service account key JSON file contents cred = credentials.Certificate('iot_mikro.json') # Initialize the app with a service account, granting admin privileges firebase_admin.initialize...
812
077b6d3d7417bbc26e9f23af6f437ff05e3d5771
__author__ = "那位先生Beer" import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties import xlrd import numpy as np print('输入鲈鱼的先验概率例如:70,对应70%') a=input('输入鲈鱼的先验概率(鲑鱼对应的1减去剩余的):') font_set = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=15) #根据生成的数据画出图像(横坐标为长度,纵坐标为亮度) data=xlrd.open_w...
813
0ea67ac97ec8e7f287a2430c67f8f7d841d8b646
# -*- coding: utf-8 -*- # Copyright 2017 Objectif Libre # # 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 ...
814
883b4de18dddede97f850e3a184a0e1072bda99e
# #1 # def bi_search(l, r, arr, x): # # Code Here # if(l == r): # return arr[r] == x # mid = (l + r)//2 + 1 # if(arr[mid] > x): # return bi_search(l,mid-1,arr,x) # else: # return bi_search(mid,r,arr,x) # inp = input('Enter Input : ').split('/') # arr, k = list(map(int, ...
815
95b75395cafc6ba9f75ecf48157421e37ced2518
import math # type defining of the variable and playing with variables. a = 5.0 print(id(a)) a = 10 print("hello.....") print(type(a)) print(id(a)) # locating addresses... b = [5, 6, 7] print(id(b)) b.append(10) print(id(b)) # Strings... name = input("Enter Your Name:: ") # iNPUTTING AS NAME pri...
816
21bdf315c98a4cf69482cc7db41bc30d44781596
"""added personal collection Revision ID: 43eabda1d630 Revises: 9cad4dfb5125 Create Date: 2018-03-28 13:55:03.557872 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '43eabda1d630' down_revision = '9cad4dfb5125' branch_labels = None depends_on = None def upgra...
817
7503a0c8f83ff0ce370ed7bce733b09d9a2c69c4
# -*- coding: utf-8 -*- from selenium.webdriver.common.keys import Keys from titan.components import Base class Input(Base): def clear(self): element = self.driver.find_element_by_xpath(self.params['xpath']) if self.params.get('clear', None): element.clear() return True ...
818
b7738c27e11e9566d90157717633312031cdffd6
import sqlite3 class announcement: def __init__(eps_df, revenue_df): conn = sqlite3.connect("earnings.db", timeout=120) cur = conn.cursor() symbol_href = self.driver.find_element_by_class_name("lfkTWp") symbol = symbol_href.text eps_history_df = pd.read_sql( '...
819
8ccec24e1a7060269ffbb376ba0c480da9eabe0a
import tensorflow as tf import settings import numpy as np slim = tf.contrib.slim class Model: def __init__(self, training = True): self.classes = settings.classes_name self.num_classes = len(settings.classes_name) self.image_size = settings.image_size self.cell_size = setting...
820
920cd41b18f5cfb45f46c44ed707cebe682d4dd9
# Software License Agreement (BSD License) # # Copyright (c) 2009-2011, Eucalyptus Systems, Inc. # All rights reserved. # # Redistribution and use of this software in source and binary forms, with or # without modification, are permitted provided that the following conditions # are met: # # Redistributions of source ...
821
2b7d9ded82fa980eeae06beb2d84d89612d53df1
import SimpleITK as sitk import numpy as np from sklearn.ensemble import RandomForestClassifier # # Estimation function # # # --------------------------- # # Linear registration function # --------------------------- # # --- Input --- # # im_ref : The common image [numpy.ndarray] # im_mov : The group ima...
822
1406b2ab78b52823a8f455c8e2719f6bd84bd168
# -*- coding: utf-8 -*- """MicroPython rotary encoder library.""" from machine import Pin ENC_STATES = (0, -1, 1, 0, 1, 0, 0, -1, -1, 0, 0, 1, 0, 1, -1, 0) class Encoder(object): def __init__(self, pin_x='P4', pin_y='P5', pin_mode=Pin.PULL_UP, scale=1, min=0, max=100, reverse=False): s...
823
1bab6b039462bb5762aa588d5ba7c3e74362d0a7
class Solution: def minRemoveToMakeValid(self, s: str) -> str: bracketsToRemove = set() stack = [] for i, c in enumerate(s): if c not in '()': continue if c == '(': stack.append(i) elif not stack: ...
824
75ddcdd4e80b962198ff9de1d996837927c3ac1a
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, with_statement """ cosi299a- Cinderella alexluu@brandeis.edu """ def truecase_is(string): """ -> lower/title/upper/other """ if string.islower(): return 'l' if string.istitle(): return 't' if string...
825
cdcb2710291e9897b874f63840193470ed58be49
# -*- coding: utf-8 -*- import json import re import scrapy from scrapy import Request class PageInfoAjaxSpider(scrapy.Spider): name = 'page_info_ajax' allowed_domains = ['bilibili.com'] # start_urls = ['http://bilibili.com/'] headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x6...
826
f4bfef2ee78b87184cc72666fade949f8f931fc3
#### про enumerate ##s = input() ##for index, letter in enumerate(s): ## print(index,':',letter) #### то же что и ##for i in range(len(s)): ## print (i,':', s[i]) #### номер начала каждого слова ##st = input() ##for index, symbol in enumerate(st): ## if symbol == ' ' and index != len(st)-1 or index == 0 or in...
827
6d0340a08701b0c4f34e9b833bca27cf455d682d
# coding: utf-8 # # Read Bathy data from ERDDAP # In[ ]: get_ipython().system(u'conda install basemap --yes') # In[1]: import numpy as np import matplotlib.pyplot as plt import urllib import netCDF4 from mpl_toolkits.basemap import Basemap # In[2]: # Definine the domain of interest minlat = 42 maxlat = 45 min...
828
0f6737b9e9e9a13d75c20352e9ef9c1db6c0c8a3
#! /usr/bin/env python # import ros stuff import rospy from std_srvs.srv import * #to check if the service is active active_ = False def unable_service(req): """ This function contains the variable declared above that is used to enable the service. """ global active_ active_ = req.data res = SetBoolRespo...
829
0686dec7f3dc23f01ffff41f611a1bb597bb5352
from .base import Base class Files(Base): endpoint = "/files" def upload_file(self, channel_id, files): return self.client.post(self.endpoint, data={"channel_id": channel_id}, files=files) def get_file(self, file_id): return self.client.get( self.endpoint + "/" + file_id, ...
830
c3d9ad49b62c56dfbd9674cb1ac5c206e6401a27
# Copyright (c) 2017, Matt Layman import bisect import configparser import os import smartypants from werkzeug.contrib.atom import AtomFeed, FeedEntry from handroll import logger from handroll.exceptions import AbortError from handroll.extensions.base import Extension from handroll.i18n import _ class BlogPost(obj...
831
7fa7a632078ce4f0052e3cadf11d5efd47a1fad5
import bpy class TILA_Config_LogElement(bpy.types.PropertyGroup): name: bpy.props.StringProperty(default='') icon: bpy.props.StringProperty(default='BLANK1') class TILA_Config_LogList(bpy.types.UIList): bl_idname = "TILA_UL_Config_log_list" def draw_item(self, context, layout, data, item, icon, active_data, ac...
832
77e4bbe625251254cdadaeeb23dddf51e729e747
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.utils.translation import ugettext_lazy as _ from django import forms from programs.models import * from programs.forms import CustomUserCreationForm, CustomUserChangeForm import pdb class ProgramAdmin(admin.ModelAdmin): list...
833
58ca520a2f43cef26a95de446f9c7a82819b0b66
import urllib.request class GetData: key = 'fDs8VW%2BvtwQA8Q9LhBW%2BT2ETVBWWJaITjKfpzDsNJO8ugDsvdboInI16ZD295Txxtxwhc4G3PwMAvxd%2FWvz2gQ%3D%3D&pageNo=1&numOfRows=999' url = "http://apis.data.go.kr/B552657/ErmctInfoInqireService/getEgytBassInfoInqire?serviceKey=" + key def main(self): data = urllib...
834
9535973f9714926269490b8550a67c74d04d8f0a
'''Autogenerated by xml_generate script, do not edit!''' from OpenGL import platform as _p, arrays from OpenGL.constant import Constant as _C # End users want this... from OpenGL.raw.GLES2 import _errors # Code generation uses this from OpenGL.raw.GLES2 import _types as _cs _EXTENSION_NAME = 'GLES2_NV_viewport_array' ...
835
77d7fb49ed4c3e78b148cd446e9a5c6a0e6fac8b
#GUIcal.py from tkinter import * from tkinter import ttk import math GUI=Tk() GUI.title('My Cal Program') GUI.geometry('500x500') def calc(): height=v_height.get() base=v_base.get()#ดึงค่ามาจากv_base print(f'height is {height}') print(f'Basal length is {base}') length= math.isqrt((height*height)+(b...
836
63069f03d17862b8ea6aa74d0acd1370bbea0dcb
import os import xml.etree.ElementTree as Et import copy from .common import CommonRouteExchangeService class DataRoutes(CommonRouteExchangeService): """Класс для работы с данными аршрутов""" def get_route_from_file(self, path_route): """Считывание маршрута из файла :param path_route: Путь д...
837
41eef711c79fb084c9780b6d2638d863266e569d
import random responses = ['Seems so','Never','Untrue','Always no matter what','You decide your fate','Not sure','Yep','Nope','Maybe','Nein','Qui','Ask the person next to you','That question is not for me'] def answer(): question = input('Ask me anything: ') print(random.choice(responses)) answer() secondQues...
838
f4bc5663ab2b2a6dbb41a2fc3d7ca67100b455a4
# Compute grid scores using the new dataset format import matplotlib import os # allow code to work on machines without a display or in a screen session display = os.environ.get('DISPLAY') if display is None or 'localhost' in display: matplotlib.use('agg') import argparse import numpy as np import torch import to...
839
8c6f890631e9696a7907975b5d0bb71d03b380da
import cv2 import numpy as np img = cv2.imread('Scan1.jpg') img_height , img_width , dim = img.shape cv2.imshow('image1',img[0:int(img_height/2),0:int(img_width/2)]) cv2.imshow('image2',img[int(img_height/2):img_height,0:int(img_width/2)]) cv2.imshow('image3',img[0:int(img_height/2),int(img_width/2):img_wid...
840
c804391cc199a242d1b54ece8487ef74065a40ad
def max_product(n): lst, lstnums, res, num = [], [], [], 1 for i in range(0, n+1): lstnums.append(i) for j in str(i): num *= int(j) lst.append(num) num = 1 ​ maxlst = max(lst) for i in range(len(lst)): if lst[i] == maxlst: res.append(lstnu...
841
c43b899234ffff09225153dcaf097591c7176430
from django.contrib import admin # Register your models here. from .models import Participant class ParticipantAdmin(admin.ModelAdmin): fieldsets = [ ("Personal information", {'fields': ['email', 'name', 'institution', 'assistant']}), ("Asistance", {'fields': ['assistant', 'participant_hash']}), ...
842
95422348c8db9753830cc0a7c8785c05b44886b1
from datetime import datetime as dt YEAR = dt.today().year BINARY_LOCATION = {'binary_location': 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe'} CHROME_DRIVER_PATH = r'C:\Users\pavithra\Downloads\chromedriver_win32\chromedriver.exe' EXTRACTED_DIR = r'C:\Users\pavithra\Documents\fintuple-automation-proje...
843
96cb2754db2740767dfb145078ed17969e85123d
from .parapred import main main()
844
77f94ecd205ae9f240f25d959a6d5cd9cf844d86
""" The Snail v 2 "Buy the dips! ... then wait" STRATEGY 1. Selects coins that are X% (percent_below) below their X day (LIMIT) maximum 2. ** NEW ** Finds movement (MOVEMENT) range over X Days - if MOVEMENT* > TAKE_PROFIT coins pass to 3 3. Check coins are not already owned 4. Uses MACD to check if coins are current...
845
ea07cb640e76ced8be92b55ee14e1d3058e073c9
#!/usr/bin/env python # -*- coding: utf-8 -*- from .variational_legacy import *
846
351b2c2a18473e6ac541a96165c69c836ea101de
# # @lc app=leetcode.cn id=2006 lang=python3 # # [2006] 差的绝对值为 K 的数对数目 # # @lc code=start class Solution: def countKDifference(self, nums: List[int], k: int) -> int: def abs(x,y): if(x-y>=0): return x-y else: return y-x ret = 0 for i...
847
0fbf8efd39f583581c46fcd3f84c65a7787145cd
import tensorflow as tf def build_shared_network(x, add_summaries=False): conv1 = tf.layers.conv2d(x, 16, 8, 4, activation=tf.nn.relu, name="conv1") conv2 = tf.layers.conv2d(conv1, 32, 4, 2, activation=tf.nn.relu, name="conv2") fc1 = tf.layers.dense(tf.layers.flatten(conv2), 256, name="fc1") if add_s...
848
4d63a5f09164b78faa731af6dce41969edc2c4f5
import datastructure import wordUri class Question: def __init__(self, nlp, otter, nounArray, verbArray): self.nlp = nlp self.nounArray = nounArray self.verbArray = verbArray self.file = otter def findFirst(self, sentence): sentenceDoc = self.nlp(sentence) for...
849
6e01e36170f3f08f2030dbd4dd91019936fb9f5c
# Copyright (c) 2020 Open Collector, Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish...
850
87504fb88cbbf810ad8bab08bc59284d2cf37cce
class Solution(object): def findDisappearedNumbers(self, nums): """ :type nums: List[int] :rtype: List[int] """ ns = [0]*len(nums) for i in range(0, len(nums), 1): ns[nums[i]-1] = 1 ret = [] for j in range(0, len(ns), 1): ...
851
a7add26a919a41e52ae41c6b4c4079eadaa8aa1d
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-05-16 12:24 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0036_auto_20180516_1818'), ] operations = [ migrations.AddField( ...
852
a52743fc911beb7e51644073131b25c177d4ad29
import brainlit.algorithms.generate_fragments from brainlit.algorithms.generate_fragments import *
853
44a9bb4d74d2e694f252d8726647bca13baa4df5
import tornado.ioloop import tornado.web import json import utils class BaseHandler(tornado.web.RequestHandler): def set_default_headers(self): self.set_header("Access-Control-Allow-Origin", "*") self.set_header("Access-Control-Allow-Headers", "x-requested-with") class CondaHandler(BaseHandler): ...
854
ba8cb18544e4ded8b229bfb9cc4b28599119414f
"""MPI-supported kernels for computing diffusion flux in 2D.""" from sopht.numeric.eulerian_grid_ops.stencil_ops_2d import ( gen_diffusion_flux_pyst_kernel_2d, gen_set_fixed_val_pyst_kernel_2d, ) from sopht_mpi.utils.mpi_utils import check_valid_ghost_size_and_kernel_support from mpi4py import MPI def gen_dif...
855
7754974e79202b2df4ab9a7f69948483042a67cc
#! /usr/bin/env python import smtpsend S = smtpsend.Smtpsent(SUBJECT='Test') S.sendemail(''' this is a test! ''')
856
987d6c769a4f593405e889ed2b0e3f9955900406
from django.contrib import admin from django.urls import path, include from django.conf import settings from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='API') from django.contrib.auth import views as auth_views urlpatterns = [ path('django-admin/', admin.site.urls)...
857
b808daf8d1fbe3cc585db57e1049a502d3ca46f5
import pandas as pd from pandas.io.json import json_normalize import numpy as np import warnings import re warnings.filterwarnings("ignore") data_path = '/Users/trietnguyen/Documents/Thesis/Thesis-2020/References/Crawler/summaryDataJson.json' weights = ['mg', 'ml', '%'] def formatName(name): arr = re.split(' |-'...
858
a649139a600cb506056a20e00089a07ec9244394
# -*- coding: utf-8 -*- # Copyright 2015 Donne Martin. 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. A copy of # the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "lice...
859
5488b32970a0b734334835457c712768a756de7f
from datetime import datetime import requests as req import smtplib import mysql.connector #mysql constant MYSQL_HOST='den1.mysql6.gear.host' MYSQL_USER='winlabiot' MYSQL_PW='winlabiot+123' MYSQL_DB="winlabiot" Coffee_mailing_list_table='coffee_mailing_list' #keys in dict receive via socket TIME='time' AMBIENT_TEM...
860
b039ed74e62f3a74e8506d4e14a3422499046c06
""" Module for generic standard analysis plots. """ import numpy as np import matplotlib.pyplot as plt import cartopy as cart import xarray as xr import ecco_v4_py as ecco def global_and_stereo_map(lat, lon, fld, plot_type='pcolormesh', cmap='YlOrRd', ...
861
bf6d1ddf66bc0d54320c0491e344925a5f507df7
import os import sys sys.path.insert(0, "/path/to/mm-api/python") sys.path.insert(0, "/path/to/mm-api/distrib/python_osx") print(sys.path) import mmapi from mmRemote import * import mm; # assumption: we are running examples_dir = "/dir/of/models/" part_filename1 = os.path.join( examples_dir, "model1.stl" ) part_file...
862
28854823b1edc7df6cf025175811c1858efd2c42
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2016-12-19 15:25 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='OpenHu...
863
e3665141397d52877242463d548c059272d13536
#!/usr/bin/env python3 import io import json import fire from collections import OrderedDict def main(input, output): vocab = OrderedDict({'</s>': 0, '<unk>': 1}) for line in io.open(input, 'r', encoding='utf-8'): word, count = line.strip().split() vocab[word] = len(vocab) with io.open(ou...
864
25ff54a969651d365de33f2420c662518dd63738
import json import random from time import sleep url = "data/data.json" def loop(run_state): error = 1 simulations = 1 while run: error_margin = str((error/simulations) * 100) + "%" prediction = get_prediction() print("Prediction: %s" % prediction) print("Error Margin: %...
865
73d7b1895282df5b744d8c03ec7e6f8530366b76
# -*- coding: utf-8 -*- import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties from sklearn import svm data=np.loadtxt('yucedata1.txt') X=data[:,0] y=data[:,1] plt.figure(1,figsize=(8,6)) myfont = FontProperties(fname=r"c:\windo...
866
f2cdee7e5eebaeeb784cb901c3ac6301e90ac7b9
from django.shortcuts import render, get_object_or_404, redirect #from emailupdate.forms import emailupdate_form from forms import EmailForm from django.utils import timezone def index(request): if request.method == "POST": form = EmailForm(request.POST) if form.is_valid(): post = form.save(commit=False) po...
867
18dae039f6455f944cbaa97bcb9c36ed29ac9a21
incremental_factors_file = '../2019_2020_IncrementalFactorsList.csv' tax_pickle_for_apns = 'kmes_taxes.p' tax_history_pickle = '../cusd_1percent_tax_history.p' distribution_pickle_out = 'kmes_distribution.p' cabrillo_key = 50200 def read_incremental_factors(): import csv inc_file = open(incremental_factors_fil...
868
860f77b031c815df40a16669dae8d32af4afa5bf
from flask import Flask, jsonify, request, render_template from werkzeug import secure_filename import os from utils import allowed_file, convert_html_to_pdf, convert_doc_to_pdf app = Flask(__name__) @app.route('/', methods=['GET']) def index(): """ Renders Index.html """ try: return render_template...
869
f080191fec4e56adc4013da74c840817e88caf56
import os import base64 from urllib.parse import urlencode import json from flask import Blueprint, request, redirect, jsonify, make_response import requests spotify = Blueprint('spotify', __name__) # Client Keys SPOTIFY_CLIENT_ID = os.environ.get('SPOTIFY_CLIENT_ID') SPOTIFY_CLIENT_SECRET = os.environ.get('SPOTIFY...
870
d4d19411f0c48ffb99bd17e8387f1741144e43b4
from celery import shared_task import tweepy from datetime import datetime, timedelta from .models import Tweet from django.db import IntegrityError CONSUMER_KEY = 'Vp7FVQLSwESvE9oTQruw0TnhW' CONSUMER_SECRET = 'miy6EsGklNYxAaVn37vTjAVGwP0c67IOyuY71AAyL1p2Ba4VPN' ACCESS_TOKEN = '1952022900-5WAHk6l5d3GllFtqDPaucSpnraIo...
871
879482e4df9c3d7f32d9b2a883201ae043e1189f
import os import json from nltk.corpus import wordnet as wn from itertools import combinations #計算排列組合 # 需要被計算的分類 myTypes = ['animal', 'vehicle', 'food', 'fashion', 'dog', 'cat', 'car', 'motorcycle'] # 計算完網紅權重存放的位置 scorePath = "..\\data\\score" # getUsersData.py儲存網紅貼文資料的json檔案,拿來計算分數 usersDataFile = "..\\data\\us...
872
93d0d73d56b04bba505265958fccff229f5eaf49
# -*- coding: utf-8 -*- import os from flask import Flask, request,render_template,url_for from flask_uploads import UploadSet, configure_uploads, IMAGES, patch_request_class import sys sys.path.insert(1, 'script') from backend import model import io from PIL import Image import base64 import numpy as np app = Fla...
873
ce4ecff2012cfda4a458912713b0330a218fa186
from states.state import State class MoveDigState(State): #init attributes of state def __init__(self): super().__init__("MoveDig", "ScanDig") self.transitionReady = False self.digSiteDistance = 0 #implementation for each state: overridden def run(self, moveInstructions): ...
874
612535d95e655f2e2d2c58f41b2aa99afa7fbcbc
# from the top # clean up dependencies from flask import Flask app = Flask(__name__) @app.route("/") def index(): return "<h1>Congratulations, it's a web app!</h1>" if __name__ == "__main__": app.run(host="127.0.0.1", port=8080, debug=True)
875
2579b0c31c5f7cad361ed317f87cb8b0ffcb0098
''' Created on Feb 21, 2013 @author: dharadarji ''' def get_row(row_index): entry = [1] if row_index == 0: return entry tmp = [] for i in range(1, row_index + 2): tmp = entry print "i: ", i, "tmp: ", tmp entry = [] entry.append(1) ...
876
f135d52e4d5e49f96869c4209b84f30ff72f6780
import praw import pickle import copy class histogram: def __init__(self, dictionary=None): self.frequencies = {} if dictionary is not None: self.frequencies = copy.deepcopy(dictionary) def get_sum(self): the_sum = 0 for e in self.frequencies: the_sum +=...
877
1c85ccaacfb47808e9e74f2a18bfe3b309891cf4
#!/usr/bin/python import pymysql dbServerName = "127.0.0.1" dbUser = "root" dbPassword = "1448" dbName = "TestDataBase2" charSet = "utf8mb4" cusrorType = pymysql.cursors.DictCursor connectionObject = pymysql.connect(host=dbServerName, user=dbUser, password=dbPassword, ...
878
33b8baf2ca819315eaa5f16c7986390acb4d6efd
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, unicode_literals import urllib def normalize_mac_address(address): return address.lower().replace("-", ":") def urlencode(s): return urllib.quote(s.encode("utf-8"), "") def urlencode_plus(s): return urllib.quote_plus(s.encode("...
879
bf8ffe603b7c1e90deed6a69500ea5b7671e7270
# from suiron.core.SuironIO import SuironIO # import cv2 # import os # import time # import json # import numpy as np # suironio = SuironIO(serial_location='/dev/ttyUSB0', baudrate=57600, port=5050) # if __name__ == "__main__": # while True: # # suironio.record_inputs() # print('turn90') # suiro...
880
71ebc6e9218085e887eda7843b5489837ed45c97
import re class Zout: def __init__(self, aline): self.Str = aline self.Var = '' self.StN = '' self.ZN = '' self.ZName = '' self.Motion = '' self.Ztype = '' self.tozout(aline) def tozout(self, aline): """transform station sta...
881
58f7810e2731721562e3459f92684589dc66862c
a = [3, 4, 2, 3, 5, 8, 23, 32, 35, 34, 4, 6, 9] print("") print("Lesson #2") print("Program start:") for i in a: if i < 9: print(i) print("End")
882
aaa0ac5e31e2c10b5baba6077e952fff1a92ef82
# -*- coding: utf-8 -*- """ Created on Wed Aug 22 18:05:44 2018 @author: Administrator """ from sklearn.model_selection import cross_val_score, train_test_split from sklearn.datasets import load_iris from sklearn.linear_model import LogisticRegression from sklearn.model_selection import StratifiedKFold from sklearn.m...
883
ad3c5ed3d6a9aa83e69f53d3fec845e8e2b1c9c6
import pandas as pd import numpy as np import sys def avg (x): return [sum(x[i])/row for i in range(col)] def sd (x): return [np.std(x[i]) for i in range(col)] def cov (x, md_x): cov_xy=[[0 for r in range(col)] for c in range(col)] for i in range(col): for j in range (col): for k ...
884
d267c8cbe51fb1bacc9404a1385f1daa4a0db7f2
import pandas as pd import numpy as np import math from sklearn.datasets import load_digits, load_iris, load_boston, load_breast_cancer from sklearn.model_selection import train_test_split from sklearn.metrics import pairwise_distances class KMeans(): def __init__(self, k = 5, max_iters = 100, random_seed = 42):...
885
9189c1dd21b0858df3138bcf4fc7568b378e6271
import os import unittest from mock import Mock from tfsnippet.utils import * class HumanizeDurationTestCase(unittest.TestCase): cases = [ (0.0, '0 sec'), (1e-8, '1e-08 sec'), (0.1, '0.1 sec'), (1.0, '1 sec'), (1, '1 sec'), (1.1, '1.1 secs'), (59, '59 secs...
886
feed412278d9e711e49ef209ece0876c1de4a873
# -*- coding: UTF-8 -*- # File name: ukWorkingDays # Created by JKChang # 29/07/2020, 11:20 # Tag: # Description: from datetime import date,timedelta,datetime from workalendar.europe import UnitedKingdom cal = UnitedKingdom() print(cal.holidays(2020)) def workingDate(start,end): cal = UnitedKingdom() res = [...
887
662fc9d64b9046180cf70ce4b26ac2b9665dba0e
# -*- coding=UTF-8 -*- ''' Created on 20180127 @author: Harry ''' import datetime # today = datetime.date.today() # weekday = today.weekday() # # if weekday == 0: # print "周一" # else: # print "other days" nowtime=datetime.datetime.now() detaday = datetime.timedelta(days=-1) da_days= nowtime + detad...
888
ccee0e3c47fd3809e0670be24aaa6fd0a9bad3bc
# -*- coding: utf-8 -*- class Library(object): def __init__(self, backend): self._backend = backend @property def cache(self): return self._backend.cache def cache_key(self, key): return self._backend.cache_key(key) def get_url(self, track): raise NotImplemented...
889
f799fdfde537bbe8f6c49a5e1a15cf6f910a0d45
#!/usr/bin/python3 """Unittest for max_integer([..]) """ import unittest max_integer = __import__('6-max_integer').max_integer class TestMaxInteger(unittest.TestCase): """ Interactive tests """ def test_max(self): """Tests max_integer""" self.assertEqual(max_integer([1, 2, 3]), 3) self...
890
edd70f55e76418911d304d6eb41a6d2a93005a58
from api import url, key, opposite import requests import json import time import os from miner import mine from cpu import * class Player: def __init__(self): data = self._get_status() time.sleep(data['cooldown']) self.name = data['name'] self.cooldown = data['cooldown'] s...
891
e14bea6376c8649bf9c9c5759d530af773664cd4
#!/usr/bin/env python3 import pandas as pd import csv def get_apriori_input(input_file,output_file,sample_col="Sample",gene_id_col="Gene_ID"): df=pd.read_csv(input_file,sep="\t") sample_names=df[sample_col].unique() with open(output_file,"w") as out: csv_writer=csv.writer(out,delimiter="\t") ...
892
462d73195680118d19a3d4e8a855e65aaeecb3c6
import time class DISTRICT: def __init__( self, cdcode, county, district, street, city, zipcode, state, mailstreet, mailcity, mailzip, mailstate, phone, extphone, faxnumber, email, admfname, admlname, admemail, lat, long, distrownercode, doctype, statustype, lastup...
893
e884825325ceb401142cab0618d9d4e70e475cf5
#!/usr/bin/env python import sys, re window = 2 for line in sys.stdin: line = line.strip() twits = line.split() i = 0 while i <len(twits): j = 0 while j <len(twits): if i!= j: print("%s%s\t%d" % (twits[i]+' ', twits[j], 1)) j+=1 i+=1
894
9d6b5baa8462b2996e4518dd39b5bb1efde1fd9d
# -*- coding: utf-8 -*- # Enter your code here. Read input from STDIN. Print output to STDOUT n= input() vals= list(map(int,input().split())) def median(values): n=len(values) values = sorted(values) if n%2==1: return values[(n+1)//2 - 1] else: return int(sum(values[int((n/...
895
624b34d160ea6db4f5249544f1614a20f506ca9e
import PySimpleGUI as sg class TelaLisatrClientes(): def __init__(self): self.__window = None def init_components(self, lista_clientes): layout = [ [sg.Text('Dados do cliente')], [sg.Listbox(values=lista_clientes, size=(60, 10))], [sg.Submit()] ] ...
896
d9156c20e046f608563bc6779575e14cc60f4c25
from django.core.urlresolvers import reverse from keptar import settings import os, os.path import Image try: from collections import OrderedDict except ImportError: from keptar.odict import OrderedDict class AccessDenied(Exception): pass class FileNotFound(Exception): pass class NotDirectory(Excepti...
897
5193de15052f81460a23d993cfa039fa90c9de5e
""" Copyright (C) 2014, Jill Huchital """ # test comment from flask import Flask from flask import render_template from flask import jsonify from flask import request from playlists import get_all_playlists, create_playlists, get_all_categories, add_new_category, add_new_topic, get_all_topics from db import connect_...
898
acbe9a9501c6a8532249496f327c2470c1d2f8e0
import math import backtrader as bt from datetime import datetime from bots.TelegramBot import TelegramBot import logging class Volume(bt.Strategy): params = (('avg_volume_period', 10), ('ticker', 'hpg'), ('ratio', 1.25)) def __init__(self): self.mysignal = (self.data.volume / bt.ind.Average(self.data...
899
e37f4422c1063df50453f7abf72a0a9a31156d8b
from locations.storefinders.stockinstore import StockInStoreSpider class ScooterHutAUSpider(StockInStoreSpider): name = "scooter_hut_au" item_attributes = {"brand": "Scooter Hut", "brand_wikidata": "Q117747623"} api_site_id = "10112" api_widget_id = "119" api_widget_type = "product" api_origin...