text stringlengths 8 6.05M |
|---|
class KeyError(Exception):
''' This error is used to be raised on invalid Domainr API key '''
message = "In order to query against Domainr you will need to provide valid Domainr key."
def __init__(self, error_code=None, http_code=None):
Exception.__init__(self, self.message)
self.messa... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: Gusseppe Bravo <gbravor@uni.pe>
# License: BSD 3 clause
"""
En esta clase se define que problema se va a solucionar.
Sea de clasificacion, regression, clustering. Ademas se debe
dar una idea de los posibles algoritmos que pueden ser usados.
"""
from pyspark.sql imp... |
from django.contrib import admin
from packages.models import (
ItemsList,
Item,
PackageSettings,
MonthBudgetAmount,
) # , UploadKey, UploadKeyList
# Register your models here.
admin.site.register(
[
ItemsList,
Item,
PackageSettings,
MonthBudgetAmount,
# Up... |
import json
import socket
# UDP IP address and port
UDP_IP = "127.0.0.1"
UDP_PORT = 5005
class RPCClient:
def __init__(self, func):
# wrap the function
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.tempFunc = func
def __call__(self, *args, **kwargs):
# For... |
from turtle import *
window = Screen()
flecha = Turtle()
for i in range(4):
flecha.forward(100)
flecha.left(90)
|
import sublime
import posixpath
from collections import OrderedDict
import os
from abc import ABCMeta, abstractmethod
from ._compat.pathlib import Path
from ._util.glob import get_glob_matcher
from ._compat.typing import List, Optional, Tuple, Iterable, Union
__all__ = ['ResourcePath']
def _abs_parts(path: Path) ... |
from functools import partial
import itertools
import posixpath
import threading
try:
from twitter.common import log
except ImportError:
import logging as log
from twitter.common.concurrent import Future
from .group_base import (
Capture,
GroupBase,
GroupInterface,
Membership,
set_different)
... |
#socket udp client
import socket
target_ip = "127.0.0.1"
port = 12345
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.connect((target_ip,port))
while 1:
cmd = input("please input cmd")
cmd = cmd.encode(encoding="UTF-8")
s.send(cmd)
s.close()
|
"""
Arturo Alquicira
DPWP
Mad Lib
"""
"""
Global Variables
"""
name = raw_input("Your name: ")
hometown = raw_input("Your hometown: ")
noun = raw_input("Noun: ")
your_age = raw_input("Your age: ")
random_number = raw_input("Random number: ")
lucky_number = raw_input("Your lucky number: ")
"""
Float - year of birth... |
"""
File: profiler.py
Defines a class for profiling sort algorithms.
A Profiler object tracks the list, the number of comparisons
and exchanges, and the running time. The profiler can also
print a traced and can create a list of unique or duplicate
numbers.
Example use:
from profiler import Profiler
from algorithms imp... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 5 18:04:59 2021
@author: delizhu
"""
from __future__ import (absolute_import, division, print_function, unicode_literals)
#cerebro = bt.Cerebro(**kwargs)#创建Cerebro框架
#cerebro.addstrategy(MyStrategy,mypara1,mypara2)#增添交易策略
#
###增添其他元素
##.addwr... |
# coding=utf-8
import scrapy
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy_spider.items import DoubanItem
from scrapy.spiders import CrawlSpider, Rule
class DoubanSpider(CrawlSpider):
name = "douban_manhua"
allowed_domains = ['book.douban.com']
start_urls = ['https://book.do... |
class No():
def __init__(self, *args, **kwargs):
self.x = kwargs.get("x")
self.y = kwargs.get("y")
self.visitado = False
self.qtdLigacoes = 0
self.ligacoes = list()
self.nos = list()
def getPosicao(self):
return [self.x, self.y]
def isVisitado(self):... |
import numpy as np
import pandas as pd
class CrdRbd:
def __init__(self, data):
self.SST = None,
self.MSST = None,
self.SSt = None
self.MSSt = None
self.MSSE = None
self.MSSe = None
self.n = None
self.N = None
self.k = None
... |
# Generated by Django 2.1.4 on 2020-12-20 02:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('forensics', '0002_auto_20201214_2107'),
]
operations = [
migrations.CreateModel(
name='Caseraw',
fields=[
... |
from PIL import Image
from io import BytesIO
import base64
def crop_faces(img_file, faces_data):
if len(faces_data["images"]) == 0:
return {"status": "NO_FACE"}
im = Image.open(img_file)
faces = faces_data["images"][0]["faces"]
cropped_images = []
for face in faces:
face_location ... |
import socket
host = '127.0.0.1'
port = 5000
s = socket.socket()
s.bind((host, port))
s.listen(1)
c, addr = s.accept()
print("Connection From:" + str(addr))
data = c.recv(1024).decode('utf-8')
while(data != ":q"):
print(str(addr) +" says: " + data)
response = "Echo back - " + data
c.send(response.enc... |
from django.urls import path
from . import views_student
urlpatterns = [
path('', views_student.student_day_all, name='student_day_all'),
path('add/', views_student.StudentDayAdd.as_view(), name='student_day_add'),
path('change/<int:pk>/', views_student.student_day_change, name='student_day_change'),
... |
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
result = [[-1 for _ in range(len(obstacleGrid[0]))] for _ in range(len(obstacleGrid))]
for i in range(len(obstacleGrid)):
for j in ra... |
from django.http import HttpResponse
from .models import Pawn
from .models import SplendorGame
from .models import SplendorGameState
from .models import SplendorPlayerState
import decimal
def index(request):
return HttpResponse("Hello, world")
def read(request):
pawn = Pawn.objects.last()
res... |
import datetime
import math
import logging
import os
import stat
import pandas as pd
import paramiko
import sqlite3
import yaml
from itertools import chain
from multiprocessing import Process, Queue
from paramiko.client import SSHClient
from tqdm import tqdm
def list_sftp_epns(host, user, key_path, data_path):
wi... |
from pyquery import PyQuery as pq
import requests
url="http://nanabt.com/index.php?c=thread&fid=28"
req=requests.get(url)
html=req.text
doc = pq(html)
print(doc('.thread_posts_list').text()) |
# 创建空字典,常定义在循环之前
dict1 = {}
# # 创建普通字典
# stu_grade = {'stu1001': 95, 'stu1002': 80, 'stu1003': 75}
# 创建嵌套字典
stu_info = { 'stu1001': {'name': 'Jack', 'gender': 'male', 'age': 26},
'stu1002': {'name': 'Tom', 'gender': 'male', 'age': 25},
'stu1003': {'name': 'Lucy', 'gender': 'female', 'age': 25}}... |
# 조건문에서 아무 일도 하지 않게 설정하고 싶다면?
poket = ['paper', 'money', 'cellphone']
if 'money' in poket:
pass # C언어의 Continue와 같은 역할
else:
print('카드를 꺼내라') |
from app.database.cache import get_from_cache, add_to_cache
from app.database.database import execute_query
def get_funding_by_state(year):
query = get_query(year)
data = get_from_cache(query)
print("DB Query: " + query)
if data is None:
data = execute_query(query)
add_to_cache(query,... |
graph ={
'5': ['3','7'],
'3': ['2','4'],
'7': ['8'],
'2': [],
'4': ['8'],
'8': []
}
visited = []
queue =[]
def dfs(visited, graph, node):
visited.append(node)
queue.append(node)
while queue:
m = queue.pop(0)
... |
HOST = "irc.twitch.tv"
PORT = 6667
NICK = "supermegacoolbot"
PASS = "oauth:avvelogoxcp40nh58p05ku8ky3b88z"
WORDSPATH = "badwords.txt"
|
from Configurables import LoKi__Hybrid__DTFDict
from Configurables import TupleToolKinematic
from Configurables import TupleToolMCTruth
from Configurables import TupleToolDecayTreeFitter
from Configurables import LoKi__Hybrid__DictOfFunctors
from Configurables import LoKi__Hybrid__Dict2Tuple
from Configurables import C... |
"""
For CLI usage
"""
import argparse
from .Interpretor import Interpretor
DESCRIPTION = "PyCalc"
def parse_args():
"""Arguments parsing."""
parser = argparse.ArgumentParser(description=DESCRIPTION)
parser.add_argument('-c',
'--cmd',
type=str,
... |
from .domain import Domain
from .rule import Rule
__all__ = ["Rule", "Domain"]
|
import numpy as np
__author__ = 'Yuji Ikeda'
class EOS(object):
"""
p[0] = E_0
p[1] = B_0
p[2] = B'_0
p[3] = V_0
"""
@staticmethod
def ev(volume, *p):
raise NotImplementedError
@staticmethod
def pv(volume, *p):
raise NotImplementedError
@staticmethod
... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 31 16:32:44 2016
@author: nmvenuti
Modeling grid search
"""
#Import packages
import pandas as pd
import numpy as np
import glob
import os
from sklearn.preprocessing import StandardScaler
from sklearn import svm
from sklearn.ensemble import RandomForestRegressor
import ... |
from typing import List
from ndb_adapter.search_report import *
from ndb_adapter.statistics import Statistics
class SearchResult(object):
"""Base class for search result"""
def __init__(self):
"""Default constructor"""
self._count = 0
self._report = []
def get_count(self) -> int:
... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class TextLSTM(nn.Module):
def __init__(self, args):
#在子类中调用父类的初始化方法
super(TextLSTM, self).__init__()
if args.static:
self.embedding = nn.Embedding.from_pretrained(args.vectors, freeze = not args.fineT... |
from __future__ import print_function
import sys
import codecs
_stdin = codecs.getreader('sjis')(sys.stdin)
print(_stdin.read())
|
if __name__ == "__main__":
lucky_numbers = {
'Gerard': 1,
'Angelo': 9,
'Lisa': 5,
'Robert': 3,
'Kjell': 7
}
for key, value in lucky_numbers.items():
print(str(key) + " is " + str(value))
|
# -*- coding: utf-8 -*-
import scrapy
from ..items import ShortWordLink
class IndonesiaRestaurantAddressSpider(scrapy.Spider):
name = 'indonesia_restaurant_address'
allowed_domains = ['www.tripadvisor.co.id/Restaurants-g294225-Indonesia.html#LOCATION_LIST']
start_urls = [
'http://www.tripadvisor.c... |
"""This is 'our_toplogy' for this project
Three directly connected switches plus a host and three servers for each switch.
Adding the 'topos' dict with a key/value pair to generate 'our_toplogy'
enables one to pass in '--topo=our_topology' from the command line.
"""
from mininet.topo import Topo
from mininet.net im... |
import turtle as tu
tu.goto(0, 0)
for i in range(5):
tu.forward(100)
tu.left(180-36)
tu.penup()
tu.goto(0, 200)
tu.pendown()
for i in range(11):
tu.forward(100)
tu.left(180-360/22)
|
def test_sort_topics(client):
client.login_admin().follow()
page = client.get('/topics/themen')
page = page.click('Thema')
page.form['title'] = "Topic 1"
page = page.form.submit().follow()
page = client.get('/topics/themen')
page = page.click('Thema')
page.form['title'] = "Topic 2"
... |
# Jaemin Lee (aka, J911)
# 2019
import torch
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 30, kernel_size=10)
self.conv2 = nn.Conv2d(30, 100, kernel_size=10)
self.mp1 = nn.... |
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# Nombre: QLineEdit.py
# Autor: Miguel Andres Garcia Niño
# Creado: 22 de Mayo 2018
# Modificado: 22 de Mayo 2018
# Copyright: (c) 2018 by Miguel Andres Garcia Niño, 2018
# License: Apache... |
from PIL import Image
user_input = input("Which photo do you want to downsize?: ")
im = Image.open(user_input)
width, height = im.size
scaledown = 0.5
new_width = int(round(width*scaledown))
new_height = int(round(height*scaledown))
im = im.resize((new_width, new_height), Image.ANTIALIAS)
im.save(user_input[:-4]+"_hal... |
import ini_files.ini as ini
# объявление 2х функций для switch-case
class _switch(object):
value = None
def __new__(class_, value):
class_.value = value
return True
def _case(*args):
return any((arg == _switch.value for arg in args))
def choice_thing():
""" ф-я выбора значения """... |
from subprocess import PIPE, run
def getOnline(app, xen_cfg, ext=0):
command = ['sudo', '/bin/bash', app['path'] + '/bin/getServer.sh']
result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True)
server = []
cfg = ''
for line in result.stdout.splitlines():
cfg = line + '.cfg'
... |
from __future__ import division
import numpy as np
output = open("./A-large-practice.out", 'w+')
with open('A-large-practice.in') as fp:
T = int(fp.readline())
cur_rd = 1
while cur_rd <= T:
key = 'Case #'+str(int(cur_rd))+': '
cur_rd += 1
NP = fp.readline().strip('\n')
[N, P]... |
import cv2
import numpy as np
from PIL import Image
tab = np.array([[9,1,4,2,6],[7,8,9,2,7],[6,6,5,3,3],[8,1,4,7,1],[4,6,2,1,3]])
#Fonction pour afficher le code binaire pour chaque pixel en appliquant LTP
def Binary(mat):
L = []
L.append(mat[0][0])
L.append(mat[0][1])
L.append(mat[0][2])
... |
# Generated by Django 2.2 on 2020-09-10 10:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0003_auto_20200607_1428'),
]
operations = [
migrations.CreateModel(
name='Categorie',
fields=[
... |
# This console application allows you to add two numbers together
# Exceptions and try excepts add resiliency to your code
# If all inputs are correct and everything is how it is supposed to be (Happy Path Execution)
# Exceptions are for when code does not follow happy path execution
print("Awesome adding app")
in1 = i... |
#Kullanıcıdan aldığınız bir sayının mükemmel olup olmadığını bulmaya çalışın.
#Bir sayının kendi hariç bölenlerinin toplamı kendine eşitse bu sayıya "mükemmel sayı" denir.
#Örnek olarak, 6 mükemmel bir sayıdır. (1 + 2 + 3 = 6)
sayı = int(input("Bir Sayı Giriniz:"))
i=1
toplam=0
while(i<sayı):
if(sayı%i==0):
... |
from django.contrib import admin
from .models import *
from candidates.models import Candidato, Experiencia
# Register your models here.
@admin.register(Competencia)
class CompetenciaAdmin(admin.ModelAdmin):
list_display = (
'description',
'estado'
)
@admin.register(Idioma)
class IdiomaAd... |
from myhdl import *
def ram(dout, din, addr, we, clk, depth=256):
""" Ram model """
mem = [Signal(intbv(0)[8:]) for i in range(depth)]
@always(clk.posedge)
def write():
if we:
mem[addr].next = din
@always_comb
def read():
dout.next = mem[a... |
"""
Author: JiaHui (Jeffrey) Lu
Student ID: 25944800
"""
import numpy as np
def function1(x):
return np.power(x, 3) - 2 * x - 5
def function1_d(x):
return 3 * np.power(x, 2) - 2
def function2(x):
return np.exp(-x) - x
def function2_d(x):
return -np.exp(-x) - 1
def function3(x):
return x *... |
import re
string = "hello Long 86 bal .. dfsjldf ,: \n hello"
#string = re.findall(r"[\w']+", string)
string = re.sub(r"\W",'',string)
"""
The "re" module is the regular expression module. The r character signals we are not ignoring special characters.
In this line, we are substituting everything that is not a word ... |
import numpy as np
import struct
import numpy as np
import struct
c = 268435455
cs = 4294967295
print()
a = 5;
print(struct.pack('>i',a))
print(struct.pack('<i',a))
a = -5;
print(struct.pack('>i',a))
print(struct.pack('<i',a))
var = 4.33
print(struct.pack('>d',var))
print(struct.pack('<d',var))
|
import re,os
from urllib import request
from bs4 import BeautifulSoup
def open_url(url):
req = request.Request(url)
req.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36')
page = request.urlopen(req)
html = page.re... |
from datetime import datetime
from elasticsearch_dsl import DocType, Date, Nested, Boolean, \
analyzer, InnerDoc, Completion, Keyword, Text, Index, FacetedSearch, TermsFacet
from elasticsearch_dsl.query import MultiMatch, Match
from flask import current_app as app
from ..models import User
class BookmarkWorkSearch(In... |
from django.conf.urls import url
from . import views
app_name = 'games'
urlpatterns = [
# /games/
url(r'^$', views.IndexView.as_view(), name='index'),
# /games/<game_id>/
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
# /games/add/
url(r'^add/$', views.AddView.as_view... |
from django.shortcuts import render
# Create your views here.
def employee_list(request):
return
def employee_form(request):
return
def employee_delete(request):
return |
#!/bin/python3
"""
Place parentheses in a list of integers and math ops to maximize value
Ops are add, sub, mult
"""
import operator
import re
ops_table = { '+': operator.add, '-': operator.sub, '*': operator.mul }
def main():
expression = input()
data = [ int(i) for i in re.findall('\d+', expression) ]
... |
from random import randint
from django.http import JsonResponse
from django.shortcuts import render
from client.settings import SECRET_KEY, BASE_DIR
from main.models import User, Plate
def encode(password):
from hashlib import sha224
return sha224((SECRET_KEY + password).encode('utf-8')).hexdigest()
def si... |
l = [1, 2, 5, 13, 2, 27, 100, 34, 44, 6, 34];
def bsearch(item):
list.sort(l)
low = 0
high = len(l) - 1;
while (low <= high):
mid = (low + high) / 2
if (l[mid] == item):
return l[mid]
elif (l[mid] < item):
low = mid + 1
else:
high = mi... |
import pprint
import reprlib
def _format_repr_exception(exc, obj):
exc_name = type(exc).__name__
try:
exc_info = str(exc)
except Exception:
exc_info = "unknown"
return '<[{}("{}") raised in repr()] {} object at 0x{:x}>'.format(
exc_name, exc_info, obj.__class__.__name__, id(obj... |
# -*- coding: utf-8 -*-
import nysol._nysolshell_core as n_core
from nysol.mcmd.nysollib.core import NysolMOD_CORE
from nysol.mcmd.nysollib import nysolutil as nutil
class Nysol_Readcsv(NysolMOD_CORE): # i=必須にする? #err処理は?
_kwd ,_inkwd,_outkwd = n_core.getparalist("readcsv",3)
def __init__(self,*args, **kw_args) :
... |
class Solution(object):
def deleteDuplicates(self, head):
if head is None:
return
fake_head = ListNode(None)
fake_head.next = head
anchor = fake_head
while anchor.next != None:
cursor = anchor.next
cursor2 = cursor.next
while ... |
import sys
import random
def egcd(b, n):
(x0, x1, y0, y1) = (1, 0, 0, 1)
while n != 0:
(q, b, n) = (b // n, n, b % n)
(x0, x1) = (x1, x0 - q * x1)
(y0, y1) = (y1, y0 - q * y1)
return (b, x0, y0)
def getPrimes(maximum):
res = []
for i in range(3, maximum-1):
if isPrime(i):
re... |
class CustomPaginationMixin(object):
@property
def paginator(self):
"""
The paginator instance associated with the view, or `None`.
"""
if not hasattr(self, '_paginator'):
if self.pagination_class is None:
self._paginator = None
else:
... |
# encoding: utf-8
from web.ext.acl import when
from ..templates.admin.admintemplate import page as _page
from ..templates.requests import requeststemplate
@when(when.matches(True, 'session.authenticated', True))
class Logout:
__dispatch__ = 'resource'
def __init__(self, context, name, *arg, **args):
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib
import json
import os
import requests
import datetime
#import twilio.twiml
from flask import Flask
from flask import jsonify
from flask import url_for
from flask import request
from flask import make_response
from flask_ask import Ask, request, session, question, ... |
from typing import Callable
# Realize a function which takes a function as an arguments and finds a point where it takes the values zéro
# bisection(f) returns an x where f(x)=0
# the bisection takes three arguments:
# the function f (function)
# a: the start of the interval of study
# b: the end of the interval of st... |
from filters import Filter
from glob import glob
import cv2
import matplotlib.pyplot as plt
import numpy as np
from moviepy.editor import VideoFileClip
def main():
filter = Filter(model_file="model.p",scaler_file="scaler.p")
clip = VideoFileClip("project_video_short3.mp4")
cnt = 0
stop_frame_num = 113
... |
# -*- coding: utf-8 -*-
from django.db.models import Prefetch
from dicts.models import ProfessionalArea, City
from pages.models import PartnersPage
from partners import models
from snippets.views import BaseTemplateView
class PartnersView(BaseTemplateView):
"""Страница партнеров"""
template_name = 'partners/... |
from setuptools import setup
setup(name='pylobby',
version='0.1.0',
description='Distributed chat system',
long_description=open('README.rst').read(),
author='Marin Atanasov Nikolov',
author_email='dnaeon@gmail.com',
license='BSD',
url='https://github.com/dnaeon/pylobby',
... |
# Copyright 2020, 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 i... |
from django.conf import settings
from django.conf.urls import include, static, url
from django.contrib import admin
urlpatterns = [
url(r'^accounts/', include('allauth.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('workmate.urls')),
]
if settings.DEBUG:
urlpatterns += static... |
from using_decorators import show_args
@show_args
def mapRoots(start, number):
'''
Return the square root of integers between min and max
'''
print('Using Map')
roots = map(lambda x: x**0.5, range(start,number+1))
for root in roots:
print (root)
def compRoots(start, number)... |
import os
import time
import traceback
from pprint import pprint
import pandas as pd
import pandas_ta as ta
from binance.spot import Spot
from binance.websocket.spot.websocket_client import SpotWebsocketClient
from dotenv import load_dotenv
import matplotlib.pyplot as plt
TEST_NET = True
load_dotenv()
class Trading... |
import requests
from tqdm import tqdm
to_download = list()
with open("need_num_releases.txt") as input_file:
for line in input_file:
to_download.append(line.rstrip().replace("_", "/", 1))
output = open("project_to_num_releases_second_round.txt", "w+")
for i in tqdm(range(len(to_download))):
element = ... |
import logging
import string
from torch.utils.data import Dataset, DataLoader
import unicodedata
from typing import List
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
logging.basicConfig(level=logging.INFO)
PAD = 0
EOS = 1
LETTRES = string.ascii_letters + string.punctua... |
#using recursion to implement power and factorial functions
def power (num, pwr):
#breaking case
if pwr == 0:
return 1
else:
return num * power(num, pwr -1)
def factorial (num):
if num == 0:
return 1
else:
return num * factorial(num -1)
print ("{} to the power... |
from django.http import HttpResponse
from django.shortcuts import render
import mysql.connector
def homepage(request):
return render(request, 'home.html', {'key1':'value1'})
def selecting(request):
return render(request, 'selecting.html')
def count(request):
fulltext = request.GET['fulltext']
prin... |
import spacy
import textacy
nlp = spacy.load('en')
import re
import json
from pprint import pprint
def match_id_pattern(text):
pattern = 'id: GO:[0-9]*$'
m = re.search(pattern, text)
if m is not None:
return True
else:
return False
def match_def_pattern(text):
pattern = '^def:*'... |
import pygame
from Settings import maze as maze_settings
import MazeFunctions
from Color import Color
global coordinate_text_size
coordinate_text_size = 10
class Cell:
"""
:param tuple coordinate: square = (row, column), circle = (ring, element in ring), hexagon = (ring, element in ring) triangle ... |
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name="preproc_chip_like_data",
version="0.1.0",
author="Hanbin Lu",
author_email="lhb032@gmail.com",
license="LICENSE",
packages=find_packages(where="src"),
package_dir={"": "src"},
scripts=["scripts/sra_chip_to_b... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.allTodos, name='alltodos'),
path('delete_task/<int:pk>', views.deleteTodos, name='deletetodos'),
path('edit_task/<int:pk>', views.editTodos, name='edittodos'),
] |
import n2
import numpy as np
from pathlib import Path
import tqdm
class KNNClassifier(object):
def __init__(self, fingerprint_kind, dimension, verbose):
self.fingerprint_kind = fingerprint_kind
self.dimension = dimension
self.verbose=verbose
def build_ann_index(self, fingerpri... |
#!/usr/local/bin/python3
def checkout(score):
for line in open("checkouts_file", "r"):
check = line.split()
checkout = {}
checkout[int(check[0])] = check[1:]
if score in checkout.keys():
print('Get these to checkout:\t', ', '.join(checkout[score]))
def game_121(type):
... |
'''
Solution:
1. 1. Perform DP as there are repeated subproblems.
Recursive equation:
1. If string is empty => pattern depends on the truth value of 2 indices before.
2. If s[i] == p[j] or p[j] == '.' => isMatch(s, p, i-1, j-1)
3. If p[j] == '*':
if isMatch(s, p, i, j-2) == False:
if p[j-1] == '.' or ... |
from tkinter import *
from tkinter import ttk
root=Tk()
##login=PhotoImage(file='source.gif')
##resize=login.subsample(10,10)
en1=ttk.Entry(root,width=30)
en1.pack()
en2=ttk.Entry(root,width=30)
en2.pack()
def plus(x,y):
print(x+y)
en1.delete(0,END)
en2.delete(0,END)
def minus(x,y):
print(x-y)
en1.d... |
'''
Created on 19/05/2015
@author: Juandoso
'''
import pandas as pd
import os, csv
from pandas.core.frame import DataFrame
data_dir = 'F:/WestNileVirusPrediction/data/'
#Add up duplicated rows
def duplicates():
rread = csv.reader(open(os.path.join(data_dir,'train.csv'), 'rb'))
header = rread.next()
print ... |
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
plt.clf()
fig = plt.gcf()
fig.set_size_inches(10.0, 10.0)
dat1 = np.loadtxt('fort.100')
dat2 = np.loadtxt('fort.101')
dat3 = np.loadtxt('fort.102')
dat4 = np.loadtxt('fort.103')
Npts1 = dat1.shape[0]
Npts2 = dat2.shape[0]
Npts3... |
from flask import Flask, request, render_template
from math import sqrt
import pandas as pd
import numpy as np
from shutil import copyfile
app = Flask(__name__)
def spec(df,benchmark,client):
df2=df.copy()
df2=df2[df2["benchmark"] == benchmark]
df2.sort_values(by='SPEC_ratio', ascending=False, inplace=Tru... |
#!/usr/bin/python
import csv
import sys
import operator
import datetime
import re
MONTH_DICT = { '01': "Jan", '02': "Feb", '03': "Mar", '04': "Apr" , '05': "May", '06': "Jun", '07': "Jul", '08': "Aug" , '09': "Sep", '10': "Oct", '11': "Nov", '12': "Dec"}
if (len(sys.argv) < 2 or len(sys.argv) > 2):
print("Error! -... |
"""account urls."""
from django.urls import path
from django.conf.urls import url
from . import views
urlpatterns = [
path('', views.account, name='account'),
]
|
####Script to create .restart.h5 file (with one cycle)
#based on the abundance of the ABUPP###.DAT (mppnp output first cycle)
#and the header infos from the se file. Do a mass grid refinement that
#of the se grid to match the ABuPP grid
############Read restart0004910.check (from Falks RUN103 dir) file to g... |
import pickle as pk
from ToolScripts.TimeLogger import log
import os
# import scipy.sparse as sp
def loadData2(datasetStr, cv):
assert datasetStr == "Tianchi_time"
DIR = os.path.join(os.path.dirname(os.getcwd()), "dataset", datasetStr, 'implicit', "cv{0}".format(cv))
with open(DIR + '/pvTime.csv'.f... |
from django.db import models
from django.contrib.auth.models import User
class Preference(models.Model):
name = models.CharField(max_length = 50)
def __str__(self):
return self.name
class Image(models.Model):
photo = models.ImageField(null=True,blank=True,upload_to='media/')
tag = models.ForeignKey(Preferen... |
#__author: "Jing Xu"
#date: 2018/1/29
'''
Python中一切事物都是对象
obj是对象,Foo是类
Foo类也是一个对象,type的对象
声明了一个类
def func(self):
print("123")
Foo = type("Foo",(object,), {"func": function})
'''
class MyType(type):
def __init__(self, *args, **kwargs):
print("123")
def __call__(self, *args, **kwargs):
print("456")
class Fo... |
word = input()
password = ''
j=(word.replace('a','@').replace('i','!').replace('m','M').replace('B','8').replace('o','.')+'q*s')
print(j)
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui/dict.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.