text stringlengths 38 1.54M |
|---|
import math
from math import pi
from flask import jsonify, request, render_template,flash,redirect,session,url_for
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager,UserMixin,login_user,logout_user,current_user
from forms import RegistrationForm,LoginForm
from oauth im... |
# vim: ai ts=4 sts=4 et sw=4
import logging
from mwana import const
from mwana.apps.labresults.util import is_eligible_for_results
from mwana.apps.stringcleaning.inputcleaner import InputCleaner
from rapidsms.contrib.handlers.handlers.keyword import KeywordHandler
from rapidsms.messages import OutgoingMessage
from rap... |
from django.db import models
class BudgetItem(models.Model):
name = models.CharField(max_length=100)
description = models.CharField(max_length=500)
amount = models.DecimalField(max_digits=7, decimal_places=2)
when = models.DateTimeField()
def to_dict(self):
return {
"name": sel... |
class Solution:
def intToRoman(self, num: int) -> str:
values = [1000,900,500,400,100,90,50,40,10,9,5,4,1]
reps = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]
res = ""
for i in range(13):
while num >= values[i]:
res += reps[i]
... |
import scrapy
import date
from models import RentalProperty
class CraigslistURLScraper(scrapy.Spider):
name = 'Cragislist URL Scraper'
allowed_domains = ['craigslist.org']
# Currently on east SD RentalProperties
start_urls = [
'https://sandiego.craigslist.org/search/esd/apa'
]
def _... |
# -*- coding: utf-8 -*-
from gensim.models import word2vec
import logging
import sys
import codecs
import numpy as np
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
model = word2vec.Word2Vec.load("jawiki_wakati.model")
argvs = sys.argv
results = model.most_similar(positive... |
'''
Created on Mar 26, 2014
@package: dtm
@author: scorp
@link: http://hierarchical-cluster-engine.com/
@copyright: Copyright © 2013-2014 IOIX Ukraine
@license: http://hierarchical-cluster-engine.com/license/
@since: 0.1
'''
##DTMAExceptions module keepts DTMA module native exceptions
class DTMAEmptyClasses(Exce... |
# -*- coding: utf-8 -*-
"""
Author:Yuetianzhuang
注册供应商
"""
import unittest
from time import sleep
from appium import webdriver
from UIAutomation.Page.Mobile.RegisteredSuppliers import RegisterSuppliersPage
from UIAutomation.Page.Mobile.iOS.CardListPage import CardPage
from UIAutomation.Page.Mobile.iOS.LoginPage impo... |
"""
Instructions to candidate.
1) Run this code in the REPL to observe its behaviour. The execution entry point is main().
2) Consider adding some additional tests in doTestsPass().
3) Implement findFirst(str) correctly.
4) If time permits, some possible follow-ups.
"""
"""
Finds the first c... |
import sys
import os
import numpy as np
import scipy.signal as sig
import matplotlib.pyplot as plt
SHORT_SIZE = 2
INPUT_RANGE = 2014.3445
def mvToADCCode(value):
return round ( value / ( INPUT_RANGE / 2 ) * (2**15) )
def adcCodeToMv(value):
return value * ( INPUT_RANGE / 2 ) / (2**15)
if __name__ == "__main_... |
from imageio import imwrite
import os
from pathlib import Path
def image(image):
path_store_dir = Path(os.path.abspath(__file__))/'..'
path_out = path_store_dir/'out.png'
imwrite(str(path_out), image) |
# -*- coding: utf-8 -*-
'''
@Author: Wengang.Zheng
@Email: zwg0606@gmail.com
@Filename: 编辑距离.py
@Time: 2021-01-10-15:46:23
@Des:
最小编辑距离:通常思路为采用两个指针i,j分别指向两个字符串的最后,然后一步步往前走,缩小问题的规模
'''
def minDistance(s1, s2):
"""
@brief 得到两个字符串的最小编辑距离,可用的编辑操作:
+ 插入一个字符
+ 删除一个字符
... |
import freezegun
import pytest
from CommonServerPython import * # noqa: F401
from QualysEventCollector import get_activity_logs_events_command, get_host_list_detections_events_command, \
Client, fetch_events, get_host_list_detections_events, get_activity_logs_events, should_run_host_detections_fetch
ACTIVITY_LOG... |
# Copyright 2015 Hewlett-Packard Development Company, L.P.
# 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... |
# Generated by Django 3.0 on 2020-05-14 14:32
from django.db import migrations
def create_through_relations(apps, schema_editor):
Tag = apps.get_model("grades", "Tag")
CourseTag = apps.get_model("grades", "CourseTag")
for tag in Tag.objects.all():
for course in tag.courses.all():
Cour... |
import unittest
#--- RECURSIVE SOLUTION (No memoization)
def staircaseTraversal(height, maxSteps):
return staircaseCounter(height, maxSteps)
def staircaseCounter(height, maxSteps):
if height <=1:
return 1
count = 0
for step in range(1,min(maxSteps, height)+1):
count += staircaseCounter(height - step, m... |
import uvicore
import sqlalchemy as sa
from uvicore.database import Table
from uvicore.support.dumper import dump
@uvicore.table()
class Images(Table):
# Actual database table name
# Plural table names and singluar model names are encouraged
# Do not add a package prefix, leave that to the connection con... |
# -*- coding:utf-8 -*-
'''
generate MF features from the meta-structure similarity
'''
from __future__ import print_function
from mf import MF_BGD as MF
from utils import reverse_map
from logging_util import init_logger
import sys
import time
import logging
import numpy as np
import os
topK = 500
data_dir = "data... |
import os
import sqlite3
DB_FILEPATH = os.path.join(os.path.dirname(__file__), ".", "buddymove_holidayiq.sqlite3")
connection = sqlite3.connect(DB_FILEPATH)
c = connection.cursor()
c.execute('CREATE TABLE Review (User Id, Sports, Religious, Nature, Theatre, Shopping, Picnic)')
connection.commit()
import pandas as pd... |
# Copyright 2017 Google Inc. 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 applicable law or a... |
def exotic_sorter(lst):
mix_lst = list(map(list, zip(*lst)))
for i in range(len(lst)):
for j in range(len(lst[i])):
if i % 2 == 0:
mix_lst[i].sort(reverse=True)
else:
mix_lst[i].sort()
result = list(map(list, zip(*mix_lst)))
return result
... |
#Huffman Coding
#Padraig Mitchell
#Takes in a alphabet and each elements probability & max number for encoding
#Uses the max number of encoding to create huffman tree of the same number of childern
#returns a dict of each alphabet element and its code & the average length of the codes
import node
import levels
import... |
# -*- coding: utf-8 -*-
"""A least-squares estimator for count-min sketches, as introduced by Lee, Lui,
Yoon, & Zhang:
https://www.usenix.org/legacy/event/imc05/tech/full_papers/lee/lee.pdf
"""
from itertools import izip
import numpy
import count_min_sketch
class LeastSquaresTopNSketch(count_min_sketch.TopNCountMin... |
#!/usr/bin/env python3
#
#
# refactor.py
#
# Lesson 15: Building and
# Debugging Whole Programs
#
# by David S. Jackson
# 12/24/2014
#
# OST Python1: Beginning Python
# for Pat Barton, Instructor
#
"""
Project:
Objective:
This project tests your ability to analyze the structure of cod... |
import os
import matplotlib.pyplot as plt
import sis_utils
import ersa_utils
img_dir, task_dir = sis_utils.get_task_img_folder()
# plot train all curves
data_type = ['Orig', 'Hist']
lrs = [0.001, 0.0001]
run_ids = range(4)
marker_style = ['o', 'd']
line_style = ['-', '--']
colors = ersa_utils.get_default_colors()
pl... |
# -*- coding: utf-8 -*-
# :Project: python-rapidjson -- Basic tests
# :Author: John Anderson <sontek@gmail.com>
# :License: MIT License
# :Copyright: © 2015 John Anderson
# :Copyright: © 2016, 2017, 2018, 2019, 2020, 2021 Lele Gaifax
#
import random
import sys
import pytest
import rapidjson as rj
@pytest.ma... |
names = {'liuqian','du','li','huo'}
def show_magicians():
for mag_names in names:
print(mag_names)
show_magicians()
print("---------------------------------------")
names = {'liuqian','du','li','huo'}
mag_names = []
def make_great(names,mag_names):
while names:
mag = names.pop()
mag = 'the great ' + mag
m... |
#!/usr/bin/env python
# coding: utf-8
from __future__ import (absolute_import, division,
print_function, unicode_literals)
try:
# noinspection PyUnresolvedReferences, PyCompatibility
from builtins import * # noqa
except ImportError:
pass
import numpy as np
import os
from scipy imp... |
#!/usr/bin/python
import os
import threading
import time
TOTALDATASIZE = 10 # in Mb
BUFFSIZEB = 5000 # in b
BUFFSIZEBYTE = BUFFSIZEB/8
LOSDUPRATES = [(0.05,0.05),(0.15,0.15),(0.30,0.30),(0.50,0.50),(0.80,0.80),]
#LOSDUPRATES = [(0.80,0.80),]
def compile(sources,executable,libs):
result = "gcc -w -std=c99"
for so... |
from pymodm import MongoModel, fields
class Instagrams(MongoModel):
username = fields.CharField(required=True)
user = fields.CharField(required=True)
package = fields.CharField(required=True)
status = fields.CharField(required=True, default='Live')
followers = fields.IntegerField(required=True)
... |
def partition(arr, low, high):
pivotpt = arr[high]
idx = low - 1
for i in range(low,high):
if arr[i] <= pivotpt:
idx += 1
arr[i], arr[idx] = arr[idx], arr[i]
idx += 1
arr[idx], arr[high] = arr[high], arr[idx]
return idx
def qsort(arr,low,high):
if low < high:
pivot = partition(arr, low, high)
qsor... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def extended_euclidean_algorithm(a, b):
"""
Calculates gcd(a,b) and a linear combination such that
gcd(a,b) = a*x + b*y
As a side effect:
If gcd(a,b) = 1 = a*x + b*y
Then x is multiplicative inverse of a modulo b.
"""
aO, bO = a, b
x ... |
class Config:
""" Exec parameters """
## Dataset dirs
training_dir = "data/openlogo/test_split/train/"
testing_dir = "data/openlogo/test_split/test/"
# Alexnet 224,224 following pytorch doc
im_w = 224
im_h = 224
## Model params
model = "alexnet"
#model = "resnet"
#model = ... |
from larcc import *
### larFunctions ###
def translatePoints (points, tvect):
return [VECTSUM([p,tvect]) for p in points]
def rotatePoints (points, angle):
a = angle
return [[x*COS(a)-y*SIN(a), x*SIN(a)+y*COS(a)] for x,y in points]
def scalePoints (points, svect):
return [AA(PROD)(TRANS([p,svect])) for p in poi... |
# -*- coding: utf-8 -*
'''
Created on 2012-11-9
@author: vincent
'''
import os
import aopMiscUtils
class SvnLook:
def __init__(self, basePath = "/usr/bin"):
self.lookCmd = os.path.join(basePath, "svnlook")
self.repository = ""
self.target = ""
self.targetType = "r"
def... |
'''
wd ca 170MB/subj
'''
import os
from metrics.calc_metrics import calc_local_metrics
from variables import template_dir, in_data_root_path, subjects_list, \
metrics_root_path, wd_root_path, selectfiles_templates
working_dir_base = os.path.join(wd_root_path, 'wd_metrics')
ds_dir_base = os.path.join(metrics_root_p... |
__author__ = 'chira'
'''
def <function name>(keyword_1 = default_val1, keyword_2 = default_val2...):
....
....
during function call you can specify SOME or ALL arguments
function name(keyword_i = value_i, keyword_j = value_j...)'''
# parameter passing flexibilities
def dumb_sentence(name = 'Chirag... |
#!/usr/bin/python
import wx
import Scanner
import pickle
import json
class MyFrame(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size = (1598, 723))
# TODO: Define 1598 x 723 2D matrix for each WAP on each nework
self.listOfWAPS = list()
... |
# Generated by Django 3.0.5 on 2020-04-14 13:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [('applications', '0021_applicationinstance_commit_id')]
operations = [
migrations.RemoveIndex(
model_name='applicationtemplate', name='app_appl... |
##################################
# Sesli Harf Bulma Projesi #
# Yazar: Babat #
##################################
print(
"##################################\n" + "# Sesli Harf Bulma Projesi #\n" + "# Yazar: Babat #\n" + "##################################",
... |
import matplotlib.pyplot as plt
import ruptures as rpt
import argparse
import numpy as np
import pandas as pd
import sys
import os
parser = argparse.ArgumentParser(description='RupturesApp')
parser.add_argument('--src', required=True, help='Path for source dataset')
# parser.add_argument('--out', required=True, help='... |
# A-Z 65 - 90
#a-z 97 - 122
orig_message = input("Enter the Message: ")
shift = int(input("Enter the shift number : "))
secret= ""
decrypt= ""
for chars in orig_message:
if chars.isalpha():
char_code = ord(chars)+shift
if chars.isupper():
if char_code > ord('Z'):
... |
#!/usr/bin/python
import sys
def get_timestamp(dateStr):
from dateutil import parser
from dateutil.tz import tzutc
from calendar import timegm
dt = parser.parse(dateStr, tzinfos=tzutc)
return 1000*timegm(dt.utctimetuple())
if len(sys.argv) < 2:
print('SYNTAX: %s date_string (format of your ch... |
import random
bike1={"Model name":"Bandit","Weight":4,"Cost to produce":200}
bike2={"Model name":"Rocker","Weight":3,"Cost to produce":300}
bike3={"Model name":"Dirt Rider","Weight":2,"Cost to produce":800}
bike4={"Model name":"Fusion","Weight":1.5,"Cost to produce":1000}
bike5={"Model name":"Adder","Weight":2.5,"Cos... |
""" Some convenience functions for translating between various representations
of a robot pose. """
import rospy
from std_msgs.msg import Header
from geometry_msgs.msg import PoseStamped, Pose, Point, Quaternion
import tf.transformations as t
from tf import TransformListener
from tf import TransformBroadcaster
... |
#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
PACKAGE = "sonar_oculus"
import math
from dynamic_reconfigure.parameter_generator_catkin import *
gen = ParameterGenerator()
# Name Type Level Description Default Min Max
gen.add("Mode", int_t, 0, "Mode: 1)750kHz 2)1.2MHz", 1, 1, 2)
gen.add("Gai... |
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import *
import win32gui
import sys
hwnd = 658262
app = QApplication(sys.argv)
screen = QApplication.primaryScreen()
img = screen.grabWindow(hwnd).toImage()
img.save("screenshot.jpg") |
from util import divisors
limit = 28124
abundant = lambda n: sum(divisors(n)) > n
non_abundant_sums = set(range(1, limit))
abundants = set()
for n in range(1, limit):
if abundant(n):
abundants.add(n)
for a in abundants:
non_abundant_sums.discard(n+a)
print(sum(non_abundant_sums))
|
from time import process_time
from table import StoredList
from random import shuffle, randint
def test_basic_stored_list():
A = list(range(100))
B = StoredList()
B.extend(A)
assert len(B) == len(A)
# assert len(B) == len(A)
assert B.index(0) == A.index(0)
assert B.index(99) == A.index(99)... |
# Enqueue failed entries (i.e. entries missing the calculation results) for repeated processing.
# Scan all CDS entries from a given taxid; Find entries missing a computation result; Re-insert them into the queue for repeated processing
# Input - taxid1,taxid2,taxid3
# - computationTag
# - randomFraction
# ... |
from tkinter import *
root = Tk( )
#this is used to fix the size of gui
lb = Label(root,text='hello ! world')
lb.pack()
#root is a GUI variable, you can use anything instead of that
root.title("A simple application")
root.minsize(300,300)
root.resizable(0,0)
root.mainloop( )
|
from django.contrib import admin
from ..models.place import Place
@admin.register(Place)
class PlaceAdmin(admin.ModelAdmin):
list_display = ("name", "place")
|
from dosql import *
import cgi
try:
import json
except ImportError:
import simplejson as json
def index(req, stud_id, course_fk, college_fk, organization_name, position, academic_year,
aa_ca, scholar_grant, dissertation, special_project, thesis_title):
stud_id = cgi.escape(stud_id)
course_fk = cgi.... |
import kivy
kivy.require('1.10.1')
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.properties import ObjectProperty
from kivy.uix.label import Label
from kivy.uix.popup import Popup
from kivy.uix.filechooser import Fi... |
# -*- coding: utf-8 -*
from sys import argv
from os.path import exists
import os
import sys
script, RLS_dxj_lyt = argv
#################################################################################################
infilename = "../"+RLS_dxj_lyt+"_top_org.v"
outfilename = RLS_dxj_lyt+"_top_rmbuf.v"
print infilename... |
class LogData(object):
def __init__(self, start_time = 0, stop_time = 0, ip = 0):
self.start_time = start_time
self.stop_time = stop_time
self.ip = ip
def get_start_time(self):
return self.start_time
def get_stop_time(self):
return self.stop_time
def get_ip(se... |
#!/usr/bin/python3
"""This is the place class"""
import sqlalchemy
import os
import models
from models.base_model import BaseModel, Base
from models.amenity import Amenity
from models.review import Review
from models.state import State
from models.city import City
from sqlalchemy import Table, Column, Integer, String, ... |
# -*- coding:utf-8 -*-
import tensorflux.graph as tfg
import math
import numpy as np
import tensorflux.functions as tff
import random
class Affine(tfg.Operation):
"""Returns w * x + b.
"""
def __init__(self, w, x, b, name=None, graph=None):
"""Construct Affine
Args:
x: Weight no... |
import numpy as np
import random
import torch
import dgl
import sys
import os
from torch import nn
import torch.nn.functional as F
import dgl.nn as dglnn
import dgl.function as fn
"""
class MLPPredictor(nn.Module):
def __init__(self, in_features, out_classes):
super().__init__()
self.W = nn.Linear(i... |
#!/usr/bin/env python3
import requests
headers = {
"User-Agent": "Requests over Tor"
}
proxies = {
"http": "http://127.0.0.1:8118",
"https": "https://127.0.0.1:8118",
}
url = "https://check.torproject.org/"
good = "Congratulations. This browser is configured to use Tor."
r = requests.get(url, h... |
import unittest
from unittest import skip
from asgard.models.account import AccountDB as Account
from hollowman.filters.autodisablehttp import AutoDisableHTTPFilter
from hollowman.marathonapp import AsgardApp
from hollowman.models import User
from tests.utils import with_json_fixture
APP_WITH_HTTP_LABELS = "single_fu... |
'''
Script used to perform analysis over csv file used
to store raw bank information
Author: Juan Pablo Castellanos Flores
'''
#General imports
import os
import csv
import collections
def log(msg,file_hdlr):
'''
Function used to print the value to std out
and a file manages by the file handlers passed
... |
import json
from err import *
#This class represents a datatable of a function it includes methods to create new variables,to get their value, address, type.
#This class also include a print method to print all of its content as if it was a json.
#This function is used by the parser to create new tables for all of t... |
# Author:houyafan
import os, sys, json
from core.data.CONST import BASE_PATH, DATA_PATH
from core.tools.check import *
from core.tools.public_file import *
from core.modifyDeposit.modifyDeposit import *
# 查询方法
@public
def select():
username = get_username()
menu_list = ['查询总信用额度', '查询消费账单', '查询剩余额度', '退出']
... |
"""
All necessary data models are here
"""
class Product():
"""
iHerb product
"""
def __init__(self):
self.name = ''
self.t_img = ''
self.s_img = ''
self.l_img = ''
|
#!/usr/bin/env ptyhon3
# -*- coding: utf-8 -*-
""" 命令行火车票查看器
Usage:
tickets [-gdtkz] <from> <to> <date>
Options:
-h, --help 显示帮助菜单
-g 高铁
-d 动车
-t 特快
-k 快速
-z 直达
Example:
tickets 北京 上海 2017-07-01
tickets -dg 深圳北 广州南 2017-07-01
"""
fro... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from .models import Sponsor
from news.models import Item
from .forms import MessageForm
from django.template.context_processors import csrf
from django.contrib import messages
from django.core.urlresolvers import revers... |
#! /usr/bin/env python
# This codes is to diagnose the red mapper for stripe 82
import numpy as np
import pyfits as pf
import pylab as pl
import richCoaddIter as rhcoadd
import richDr7Iter as rhdr7
import healpy as hp
bg = pf.getdata('/home/jghao/research/data/sogras/sogras_ra_dec.fits')
N = len(bg)
clusterid = np.ara... |
import numpy as np
import datetime as dt
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask import Flask, jsonify
# Database Setup
engine = create_engine("sqlite:///Resources/hawaii.sqlite")
# reflect an existing... |
# -*- coding: utf-8 -*-
# Copyright (C) 2016-TODAY touch:n:track <https://tnt.pythonanywhere.com>
# Part of tnt: Flespi Receiver addon for Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
from datetime import datetime
class TntFlespiDevice(models.Model):
_nam... |
import os
from todolism.settings import config
from todolism.extensions import db
from todolism.blueprints.home import home_bp
from todolism.blueprints.todo import todo_bp
from todolism.commands import register_commands
from flask import Flask
def create_app(config_name=None):
if config_name==None:
config... |
# encoding=utf-8
from pprint import pprint
from kyototycoon import KyotoTycoon
# connect
db = KyotoTycoon()
db.open(host='127.0.0.1', port=1978, timeout=5)
# set
db.set('name', 'alen') # no expire
db.set('vip', 1, 31 * 24 * 60 * 60) # a month expire
# get
print('get from db')
keys = ['name', '... |
from script import send, send1, send2, send3
import schedule
import time
#TAFL
schedule.every().monday.at("03:40").do(send)
schedule.every().tuesday.at("08:30").do(send)
schedule.every().wednesday.at("04:40").do(send)
#Maths
schedule.every().monday.at("04:40").do(send1)
schedule.every().tuesday.at("05:45")... |
from collections import defaultdict
from dotted.utils import dot_json
with open('hero_defines.json') as f:
heros = dot_json(f.read())
tag_list = defaultdict(list)
for h in heros:
print(f'{h.id:>3}:{h.seat_id:<3} {h.name:<35}{h.properties.type:^8}{",".join(h.properties.tags)}')
for t in h.properties.tags... |
import requests
import pprint
import json
import os
url = 'https://login.salesforce.com/services/oauth2/token'
d = {
'client_id': '3MVG91ftikjGaMd9IQ9dEbGephypa2HaVfYpdeXiGBSuXeEmhDH4QWvFhR.aDj0.q1ZPPLxzTzWNfbCmS8fso',
'client_secret': '6723928713317818058',
'grant_type': 'password',
'password': os.environ['SFD... |
from flask import Flask, request, redirect, url_for, render_template, flash, jsonify
from helpers import header_active
import random
import datetime
app = Flask(__name__)
restaurants = open("restaurants", "r")
arr = restaurants.readlines()
@app.route("/")
@app.route("/index")
def index():
return render_template(... |
import json
import traceback
from flask import Response as FlaskResponse
class ValidationError(Exception):
pass
class HttpErrorBase(Exception):
status_code = None
default_message = None
def __init__(self, message=None, headers=None, code=None):
self.headers = headers if headers else {}
... |
import webbrowser, urllib2
webbrowser.open('http://localhost:5000/?q=' + urllib2.quote(raw_input()))
|
# coding=utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
from contextlib import contextmanager
from flask_sqlalchemy import SQLAlchemy
from scout_apm.flask.sqlalchemy import instrument_sqlalchemy
from tests.integration.test_flask import app_with_scout
@contextmanager
def co... |
import math
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from .HiddenLayer import HiddenLayer
class OutputLayer(HiddenLayer):
'''
Output of an Artificial Neural Network
delta is calculated differently
'''
def __init__(self, number_of_neurons=2):
super().__init__... |
lines = [int(line) for line in open('A-large.in')]
for i in range(lines[0]):
val = lines[i+1]
if val == 0:
print 'Case #%d: INSOMNIA' % (i+1)
continue;
j = 1
s = set()
while True:
s.update(set(str(val*j)))
if len(s) == 10:
break;
j = j+1
pr... |
import os;2
print('hello')
one='spam eggs '
#printing a word which has '
two="doesn't"
print(one+two)
#concatenate
print('Isn\'t?, they said.')
#nextone lol. Strings can be concatenated (glued together) with the + operator, and repeated with *:
print (3 * 'un' + 'ium')
concat= (3 * 'un' + 'ium');
#pritn the ... |
import csv,os
path = r"C:\Users\a7825\Desktop\工作空间\语音数据\UUDB\var_out\C064\keka"
for name in os.listdir(path):
csv_path = os.path.join(path,name)
a = csv.reader(open(csv_path, 'r', encoding='utf-8'))
b = [i for i in a]
if len(b)==1:
print(name)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# $Id$
# Simple example showing how to display the glosses track of a signstream database
from __future__ import absolute_import
import sys
import analysis.signstream as ss
if len(sys.argv) != 2:
sys.stderr.write("Usage: showglosses.py <XML file>\n")
sys.exit(1)
db = ... |
'''game = [[0,0,0],[0,0,0],[0,0,0]]
def game_board(player=0,row=0 ,column=0, just_display=False):
if not just_display:
game[row][column]= player
print(" 0 1 2")
for count, cell in enumerate(game):
print(count, cell)
game_board(player=3,row=0,column=0)
game_board(just_display... |
#!/usr/bin/python
# Programmer : Liguo Zhang
# Date:
# Last-modified: 01 Mar 2019
import os,sys,argparse
import numpy as np
import tempfile
from TSA_utility import *
import matplotlib
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde
def ParseArg():
''' This Function Parse the Argument '''
... |
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if len(s) == 0:
return 0
if len(s) == 1:
return 1
res = 0
i = 0
j = 1
while j < len(s):
word = s[i:j]
if s[j] in word:
res = max(res, j -... |
#Ejemplo manejo del try-except, ejercicio de raiz cuadrada de un numero decimal.
import math
y = True
while y == True:
try:
x = float(input("Ingresa un numero: "))
assert x >= 0.0 and x < 100000
x = math.sqrt(x)
print(x)
y = False
except ValueError:
print("Por fa... |
"""
Test the handling of analysis units in the properties DSL.
"""
from langkit.diagnostics import DiagnosticError
from langkit.dsl import Bool, Struct, UserField
try:
class MyStruct(Struct):
A = UserField(type=Bool)
except DiagnosticError:
pass # If we get here, a diagnostic should be emitted on st... |
import tweepy
import requests
import json
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
from logging.handlers import RotatingFileHandler
# creation de l_objet logger qui va nous servir a ecrire dans les logs
logger = logging.getLogger()
# on met le niveau du logger a DEBUG, comme ca il... |
from distutils.core import setup
import py2exe
import labels
from reportlab.graphics import shapes
setup(windows=['PATLabels.pyw'])
|
# input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
import sys
sys.stdin = open("InputDuyetTheoChieuRongBST.txt","r")
sys.stdout = open("OutpuDuyetTheoChieuRongBST.txt","w")
class BST:
def __init__(self,x):
self.left = None
self.right = None
self.val = x
def insert(root, k... |
'''
Wrapper for running pretrained ELMo on preprocessed sentences.
'''
import codecs
import numpy as np
import tensorflow as tf
from bilm import Batcher, BidirectionalLanguageModel, weight_layers
class ELMoParams:
def __init__(self,
options_file=None,
weights_file=None,
vo... |
from .layers import Linear, Dropout
from .activations import ReLU, Tanh
from .losses import LossMSE, LossCrossEntropy
from .sequential import Sequential
# All possible child classes of Module class
__all__ = ['Linear',
'ReLU', 'Tanh',
'LossMSE', 'LossCrossEntropy',
'Sequential',
... |
from django.conf.urls import url
from .views import GalleryListView, ImageDetailView
urlpatterns = [
url(r'^$', GalleryListView.as_view(), name='gallery-list'),
url(r'^(?P<galleryslug>[\-\d\w]+)/(?P<slug>[\-\d\w]+)/$', \
ImageDetailView.as_view(), name='image'),
]
|
#!/usr/bin/python
import re
url = "https://www.facebook.com/norkamusica/?fref=ts"
url2 = "https://www.facebook.com/kalethoficial/"
url3 = "https://www.facebook.com/kalethoficial"
exRegFacebook = r'https://www.facebook.com/(.*)/.*|https://www.facebook.com/(.*)'
match = re.match( exRegFacebook, url, re.M|re.I)
if... |
from cemubot import Cemubot
from cogs import config
from discord import app_commands
from discord.ext import commands
import discord
class Rules(commands.Cog):
bot: Cemubot
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
self.bot.rules_ready... |
# Given an array of strings, return another array containing all of its longest strings.
# Example
# For inputArray = ["aba", "aa", "ad", "vcd", "aba"], the output should be
# allLongestStrings(inputArray) = ["aba", "vcd", "aba"].
def allLongestStrings(inputArray):
result = []
maxlength = len(max(... |
import json
with open('config.json') as file_handler:
data = json.loads(file_handler.read())
for key, value in data.items():
print(f'key: {key}, value: {value}')
with open('tekst.txt', 'w') as file_handler:
for key, value in data.items():
file_handler.write(f'{key} = {value}\n') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.