text
stringlengths
8
6.05M
import os import cv2 from trvo_utils import toInt_array from trvo_utils.annotation import PascalVocXmlParser, voc_to_yolo import xml.etree.ElementTree as ET from xml.etree.ElementTree import ElementTree from trvo_utils.imutils import imgByBox, IMAGES_EXTENSIONS from trvo_utils.path_utils import list_files from dat...
# 새 파일 안에서 이전에 만든 모듈 불러오기 import mod2 result = mod2.sum(3,4) print('mod2.sum(3, 4) = {}'.format(result))
from collections import defaultdict from morepath import redirect from onegov.ballot import Election from onegov.core.security import Public from onegov.core.utils import normalize_for_url from onegov.election_day import ElectionDayApp from onegov.election_day.layouts import ElectionLayout from onegov.election_day.util...
from django.shortcuts import render # Create your views here. from .models import User def index(request): return render(request, 'index.html') def users(request): user_list = User.objects.order_by('name') user_dict = {'users': user_list} return render(request, 'user.html', context=user_dict)
from lstm_end_to_end.model.AU_rcnn.utils.resize_bbox import resize_bbox from lstm_end_to_end.model.AU_rcnn.utils.random_flip import random_flip from lstm_end_to_end.model.AU_rcnn.utils.flip_bbox import flip_bbox
word = "hello there!" for i in word: print(i) guess="" for i in range(0, len(word)): guess+="_" print(guess)
class Animals: def __init__(self): return def eat(self): print('eat') def talk(self): print('talk') class Cat(Animals): def talk(self): print('Meows') def move(self): print('Jump') class Dog(Animals): def talk(self)...
import time import torch from torch import nn from models.transformer import SimpleTransformer class PrikolNet(nn.Module): def __init__(self, backbone, pool_shape, embd_dim, n_head, attn_pdrop, resid_pdrop, embd_pdrop, n_layer, out_dim, **kwargs): super(PrikolNet, self).__init__() ...
#!user/bin/env import rospy from geometry_msgs.msg import Twist from nav_msgs.msg import Odometry import math import tf print("------------------------------------") print("ROLL PITCH YAW CONVERSION") x=math.radians(30) y=math.radians(42) z=math.radians(38) print("ROLL= {0}, PITCH= {1}, YAW= {2}".format(math.degrees...
""" The objectmodel.py module defines base classes Object, Folder, File, and Converter, which are used to manage projects (hyerarchical set of folders and files) in the ide. """ import re # regular expression operations from application.lib.com_classes import Subject class Object(object, Subject): """ A ne...
import matplotlib.pyplot as plt import numpy as np AP = [0.88,0.83,0.74,0.7,0.67,0.66,0.57,0.56,0.5,0.39] OVERLAP = [0.02, 0.04, 0.06, 0.08, 0.10, 0.12, 0.14, 0.16, 0.18,0.20] plt.plot(OVERLAP, AP,'r', label='r=2, vocab = 1M') AP = [0.86,0.89,0.89, 0.89, 0.87, 0.85,0.83,0.78,0.75] OVERLAP = [0.04, 0.06, 0.08, 0.10, ...
#! /anaconda3/bin/python # # Interface for the assignement DATABASE_NAME = 'dds_assignment' # TODO: Change these as per your code RATINGS_TABLE = 'ratings' RANGE_TABLE_PREFIX = 'rangeratingspart' RROBIN_TABLE_PREFIX = 'roundrobinratingspart' RATING_COLNAME = 'rating' import psycopg2 import os import io def getOpen...
def menu(): print('Main Menu:') print(' 1. Cost of Gas') print(' 2. Used Value') print(' 3. Stopping Distance') print (' 4. Quit') print() print() r=2 while r>1: user=int(input('Choose a function from the list:\n')) if (user == 1) or (user==2) or (user==3) or (user==...
# Generated by Django 2.2.4 on 2020-09-21 08:42 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0004_auto_20200921_0802'), ] operations = [ migrations.RemoveField( model_name='payment', name='payment_status', ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('user', '__first__'), ] operations = [ migrations.CreateModel( name='Answer', fields=[ ...
from pathlib import Path def get_dict(file, player, round): with open(file) as f: player_data = {} for line in f: line = line.strip().replace(' ', '-').split("-") line[-1] = int(line[-1]) line[-2] = int(line[-2]) player_data[line[0]+line[1]] = [line[2...
"""Contains database models for the application. Example Usage:: Initialize the database based on the current models. $ export FLASK_APP=run.py $ export FLASK_APP_ENV=Dev $ flask db init $ flask db migrate $ flask db upgrade Upgrade the database based on model changes. $ export FLAS...
import sys from PyQt5.QtWidgets import (QApplication, QWidget, QLabel, QLineEdit, QHBoxLayout, QVBoxLayout, QPushButton) import backend as back class MyLabel(QLabel): rut = 0 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.boton = QPushB...
# #-*- coding:utf-8 -*- # # @author : MaLei # # @datetime : 2020/4/21 7:22 下午 # # @file : file_workflow.py # # @software : PyCharm # # from SpiffWorkflow.specs import WorkflowSpec,ExclusiveChoice,Simple,Cancel # from SpiffWorkflow.serializer.json import JSONSerializer # from SpiffWorkflow.operators import Equal,Attrib ...
from heroes import SuperHeroes hero_one = SuperHeroes("iron man") print(hero_one.convert_superhero_name()) hero_object2 = SuperHeroes("ant man") print(hero_object2.convert_superhero_name())
"""Module to build the Manage Servers Window.""" import tkinter as tk def build_frames(dialbox): """Adds the Frames to the gui.""" #Window Frame dialbox.manage_frame = tk.Frame(dialbox.master_frame) dialbox.manage_frame.grid(row=0, column=0) #SERVER LIST FRAME dialbox.server_list_frame = tk.Fr...
def convertToOrdinal(number=None): """This takes in a number, and converts it to an ordinal. Example, 1 gets converted to 1st, 2 gets convered to 2nd""" """This takes modulo of the number by 10 to get the last digit. It also takes modulo of 100 to get the last two digits. It then analyzes that information to co...
import database as db if __name__ == "__main__": db.list_all_users()
print(2 < 3) print(type(True)) print() print(2 == 2) print() print('2!=3', 2 != 3) print() print(bool(0))
import time import random from multiprocessing import Process, Queue from calibration import calibration def generator(queue: Queue, channels_count: int): while True: time.sleep(0.1) ch = random.randint(1, channels_count) value = random.randint(1345, 2432) queue.put((ch, value)) ...
idade = int(input("Digite sua idade para varificarmos sua categoria: ")) if idade >= 5 and idade <= 7: print("infantil A") elif idade >= 8 and idade <= 10: print("infantil B") elif idade >= 11 and idade <= 13: print("juvenil A") elif idade >= 14 and idade <= 17: print("juvenil B") elif idade >= 18: print("Adult...
from ham_distance import hamdistance def normalize(s, length): #length is key length in question and data is the whole string in ascii norm_dist = 0 for i in range (len(s)-(2*length)+1): norm_dist += hamdistance(s[i:i+length], s[i+length:i+2*length]) norm_dist = (1.0*norm_dist)/((len(s)-(2*length)+1)*length) ret...
from flask_cors import CORS from flask_script import Manager from clover import app CORS(app, supports_credentials=True) manager = Manager(app) if __name__ == '__main__': manager.run()
""" You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Ex...
from configs.utils import str2bool def add_params(parser): # -------------------------------------------------- Data -------------------------------------------------- parser.add_argument( "--dim_covariates", type=int, default=20, help="Dimensions of covariates" ) parser.add_argument( ...
from tensorflow.contrib import layers def conv_model(X, Y_): XX = tf.reshape(X, [-1, 28, 28, 1]) Y1 = layers.conv2d(XX, num_outputs=6, kernel_size=[6, 6]) Y2 = layers.conv2d(Y1, num_outputs=12, kernel_size=[5, 5], stride=2) Y3 = layers.conv2d(Y2, num_outputs=24, kernel_size=[4, 4], stride=2) Y4 = la...
import json import logging import os import pandas as pd import sys from flask import Flask from flask import render_template from flask import request from flask import redirect from flask import url_for from pandas.io.json import json_normalize from urllib.request import urlopen from db_book import * ...
#!/usr/bin/env python2 import sys import argparse import logging import traceback import payments import config def main(args, parser): loglevel = args.log try: numeric_level = getattr(logging, loglevel.upper(), None) if not isinstance(numeric_level, int): raise Val...
#!/usr/bin/env python2 # -*- coding: UTF-8 -*- n,m=map(int,raw_input().split()) e=[0]*n t=[1]*n r=[0]*n p=[int(i) for i in range(n)] def find(a): if a==p[a]: return a #新しい親になる頂点を決めて辺や頂点の数をまとめる tmp=find(p[a]) t[tmp]=t[tmp]+t[a] t[a]=0 e[tmp]=e[tmp]+e[a] e[a]=0 p[a]=tmp retu...
def get_total_bebidas(pueblos): bebidas = [0, 0, 0, 0, 0, 0, 0, 0] for drinks in pueblos: for drink in range(8): bebidas[drink] += drinks[drink] return bebidas def get_bebida_alcoholica_mas_consumida(bebidas, alcohol): tipos = [1, 2, 3, 4, 5, 6, 7, 8] assigned = list(sorted(zip(...
#!/usr/bin/env python # encoding: utf-8 """ desc: ali sms module & ali dingding module author: lu.luo date: 2017-06-07 """ import urllib2 import urllib import json import requests from settings import * class AliyunSms(object): """ params: dict or str, sms content recnum: str or list, sms receiver ...
from django.conf.urls import url, include from .views import * urlpatterns = [ url(r'show_conference$', show_conference, ), url(r'yy_conference', yy_conference), url(r'show_name', show_name), url(r'draw_forms', draw_forms), url(r'cancel_book', cancel_book), url(r'sgin_in', sgin_in), url(r'u...
# Copyright (c) 2011, Chandler Armstrong (omni dot armstrong at gmail dot com) # see LICENSE.txt for details """ line segment object """ from math import sqrt class Line(object): """line segment object""" def __init__(self, *a): """ construct a line segment object arguments must be...
from django.contrib import admin from .models import LocationModel class LocationModelAdmin(admin.ModelAdmin): list_display = ('id','name', 'key', 'created', 'modified', 'active') search_fields = ('name', 'key') readonly_fields = ('created', 'modified',) date_hierarchy = ('created') admin.site.register(LocationM...
from django.contrib import admin from .models import WikiModel, ItemModel, UserModel # Register your models here. admin.site.register(WikiModel) admin.site.register(ItemModel) admin.site.register(UserModel)
# !/usr/bin/env python3 # _*_ utf-8 _*_ # @Time : 2018/10/12/012 19:31 # @File : TCPServer.py # @Software: PyCharm # @author = zp """ 配置文件 消息长度(大端对齐)尚未实现 消息和目的用户都用json.dumps()表示 收到的消息形式 日期,收信人,消息 发送的消息形式 日期,发信人,消息$ """ MAX_USER = 20 # 最大用户数 SERVER_PORT = 8080 # 服务器端口号 M...
from flask_babel import lazy_gettext as _ from shelf import LazyConfigured from shelf import db from shelf.plugins.library import PictureModelMixin from shelf.plugins.workflow import WorkflowModelMixin, WORKFLOW_STATES from sqlalchemy_defaults import Column class Picture(LazyConfigured, PictureModelMixin): id = Co...
#!/usr/bin/env python3 import os import os.path as op import re import sys import string import json import urllib.request import argparse import requests import subprocess from yaml import safe_load from jsonschema import validate from requests.exceptions import RequestException def is_valid_file(parser, arg): if...
import numpy as np import math upVec = np.array([0,0,1]) eyeVec = np.array([0,10,10]) def normalize(v): norm=np.linalg.norm(v) if norm==0: return v return v/norm def rotate(degrees,axis): x = axis[0] y = axis[1] z = axis[2] cos_theta = math.cos(math.radians(degrees)) sin_theta = math.sin(ma...
from io import BytesIO import os from pathlib import PurePosixPath import tarfile def docker_copyto(container, srcfile, dstfile): p = PurePosixPath(dstfile) dstdir = p.parent dstname = p.name tarstream = BytesIO() tar = tarfile.open(fileobj = tarstream, mode = 'w') tar.add(srcfile, arcname = ds...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 22 23:24:17 2016 @author: mickmccart """ import os import requests import pandas as pd import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap from mpl_toolkits.axes_grid1 import make_axes_locatable import matplotlib as mpl # Set ...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- __author__ = 'zdy' __version__ = '1.0.0' __date__ = '20/11/2017' __copyright__ = "RR" __all__ = [ 'VisualMark', ] import os import sys import rospy from geometry_msgs.msg import * from rr_robot_plugin.srv import * __current_path = os.path.dirname(__file__) or '.' sys....
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from .modules import Compose, BatchNorm class MADE(nn.Module): def __init__(self, in_out_features, num_hidden=2, base_filters=32, use_companion=False): super(MADE, self).__init__() self.in_out_chs = in_out_featu...
c.IPKernelApp.extensions = ['pymor.discretizers.builtin.gui.jupyter']
#!/usr/bin/env python #encoding: utf-8 from distutils.core import setup setup( name='django-form-timeout', version='0.1', description='Simple Django forms bruteforce prevention', author='Gustaf Sjöberg', author_email='gs@distrop.com', packages=['form_timeout'], )
""" Tests the initialization methods """ import pytest import sonar.database as Database from sonar.exceptions import ReturnValue class TestVivado: """ Group the Vivado initializations """ @pytest.fixture(autouse=True) def setup(self, test_dir, call_sonar): """ Add shared object...
from datetime import timedelta from django.shortcuts import render, redirect from django.utils.datetime_safe import date from customer.models import Customer, Discount from order.models import Order, OrderHistory def order_basket(request): customer = Customer.objects.filter(owner=request.user).first() try: ...
import django django.get_version()
import argparse import os.path import linecache parser = argparse.ArgumentParser(description= 'embed fasta sequences' + '\n' 'Usage:' + '\t' + 'iTerm2gff.py <options> -i -o') #required files: parser.add_argument('-iterm', dest='iTermOutput', help='output file from iTerm-PseKNC', requ...
import pyodbc import pandas cnx = pyodbc.connect( 'Driver=IBM i Access ODBC Driver; ' 'System=p1214-pvm1.cecc.ihost.com; ' 'UserID=user1214; ' 'Password=z8ks0%uB-87o0Nk;' ) SCHEMA="example_s" sql = "Select * from {}.tmp".format(SCHEMA) data = pandas.read_sql(sql, cnx) print(data...
# -*- coding: utf-8 -*- from django.contrib.auth.models import User import requests def base_response(success=False, message='Data empty'): return {'success': success, 'message': message} def obtain_token(username, password): if not username or not password: return None try: post_data = {'username': usernam...
## ## Labels ## Numeric: rate_spread import pandas as pd from sklearn import preprocessing import matplotlib.pyplot as plt import seaborn as sns import scipy.stats as ss import numpy as np import numpy.random as nr import math ## Import data hmda_train=pd.read_csv('hmda_train.csv') print('Load hmda_train.csv') cat_c...
from game_engine.deck import Deck # Should generate 52 cards def test_cards_total(): deck = Deck() assert len(deck._cards) == 52 # All cards should be unique def test_all_cards_unique(): seen = set() uniq = [] deck = Deck() for card in deck._cards: if card.__str__() not in seen: ...
import turtle t = turtle.Turtle() def triangle(len): for i in range(3): t.forward(len) t.left(120) def rectangle(width, height): for i in range(2): t.forward(width) t.right(90) t.forward(height) t.right(90) def lg_cake(): for i in range(3): rectangle(30,310) t.forward(30) def s...
import os class Config(object): db_path = 'localhost:27017' db_name = 'ronfe' local_path = os.path.dirname(os.path.realpath(__file__)) local_path = local_path.split("/") local_path = local_path[:-1] local_path = "/".join(local_path) gamers = [ { "name": "苏嘉锐", ...
from django.db import models import string import random def random_generator(size=6, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for x in range(size)) class Bitly(models.Model): website=models.CharField(max_length=200) keys=models.CharField(max_length=10, unique=True...
import cv2 import time def main(): #capture cam 1 cam = cv2.VideoCapture(0) cam.set(3,1280) cam.set(4,720) time.sleep(5) _,frame = cam.read() img = cv2.flip(frame,0) cv2.imwrite("calib_images/frame_10.jpg", img) cam.release() if __name__=='__main__': main()
#!/usr/bin/env python3 #import numpy as np # Number of decks n = 1 deck = [4*n]*9 deck.append(16*n) # Dealer hits soft 17 hit_soft_17 = False # Double after split double_after_split = True # Resplit aces resplit_aces = False class memoize: def __init__(self, func): self.func = func self.know...
# This is an awful program. I will not accept homicide over it, though. Thank You. # _ _ # | | | | # | |__| | __ _ _ __ __ _ _ __ ___ __ _ _ __ # | __ |/ _` | '_ \ / _` | '_ ` _ \ / _` | '_ \ # | | | | (_| | | | | (_| | | | | | | (_| | | | | # |_| |_|\__,_|_| |_|\__, |_| |_| |_|\__,_|_| |_| # ...
import calc import pytest def test_add(): assert calc.add(2,2) == 4 def test_subtract(): assert calc.subtract(2,2) == 0 def test_multiply(): assert calc.multiply(2,2) == 4 def test_divide(): assert calc.divide(2,2) == 1 def test_fail(): assert calc.divide(2,0) == 0
# import rospy import argparse import json from scipy import misc from keras.optimizers import SGD from keras.models import model_from_json, load_model import utils import numpy as np # import thread import tensorflow as tf # from geometry_msgs.msg import Twist import time # from premodel import ChauffeurModel from ker...
import requests import json import urllib.parse from bs4 import BeautifulSoup import threading #from threading import Thread, Condition, Lock import time def get_n_save(song): #request = 'https://api.vk.com/method/audio.search?q=' + song + '&auto_complete=1&lyrics=0&performer_only=0&sort=2&count=1&version=5.53' ...
#-*-coding: utf-8 -*-# f = open("./sample.txt","r") lines=f.readlines() total = 0 #score = lines.split() #students=len(score) for line in lines : score = int(line) total += score average = total/len(lines) f=open("./result.txt","w") f.write(str(average)) f.close() print(lines)
import cv2 import numpy as np # read as <class 'numpy.ndarray'> img = cv2.imread("H:/Github/OpenCv/Research/images/red1.jpg") img1 = cv2.imread("H:/Github/OpenCv/Research/images/blue1.jpg") # # dst = α ⋅ img1 + β ⋅ img2 + γ img = cv2.addWeighted(img,0.5,img1,0.3,1) cv2.imshow("Covert",img ) cv2.waitKey(0) cv2.destr...
import sys from PyQt5 import QtWidgets from PyQt5.QtCore import Qt from data_source import DataSource from main_window import MainWindow from play_list import PlayList from play_list_scanner import PlayListScanner from player import Player def main(): """Entry point for our simple vlc player """ app = Q...
# -*- coding:ascii -*- from mako import runtime, filters, cache UNDEFINED = runtime.UNDEFINED STOP_RENDERING = runtime.STOP_RENDERING __M_dict_builtin = dict __M_locals_builtin = locals _magic_number = 10 _modified_time = 1455050976.637967 _enable_loop = True _template_filename = '/Users/benmackley/Projects/history/bas...
import lxml.etree as ET if __name__ == '__main__': tree = ET.parse('xml/cityindex.xml') tree.write('xml/cityindex.new.xml') tree.write('xml/cityindex.newc14n.xml', method='c14n')
import sys class DirectionHelper(object): NORTH = 0 EAST = 1 SOUTH = 2 WEST = 3 DIRECTIONS = ['North', 'East', 'South', 'West'] def __init__(self): self.dir = self.NORTH def right(self): self.dir = (self.dir + 1) % 4 return self.dir def left(self): se...
from invoke import task @task def compile(ctx): commands = [ 'python setup.py build_ext --inplace', 'mkdir -p build', 'cd build', 'cmake ..', 'make', 'make install' ] ctx.run(' && '.join(commands)) @task def cdt(ctx, build_type='Debug', target='../lid_drive...
import warnings from pathlib import Path import json import numpy as np import vcd.core as core import vcd.types as types import time # TODO: get actions and objects per frame # TODO: funtion to get frame intervals per action or object presence #TODO: delete unecessary code # dict for changes in structures # data ...
# TAREA 5 # Autor: Julio M.Lerma # # 1.Elaborar un programa en Python que encueste a 10 personas y las clasifique seg�n el deporte que practica. # La lista de deportes v�lidos son: Ajedrez, Atletismo, Baloncesto, F�tbol, Karate, Nataci�n, Volleyball, # Flag y Ping Pong. Puede darse el caso que no le guste ninguno de...
from __future__ import division from kd_helpers import * import numpy as np import sys, glob id_name_map = { "Airplane":"02691156", "Bag":"02773838", "Cap":"02954340", "Car":"02958343", "Chair":"03001627", "Earphone":"03261776", "Guitar":"03467517", "Knife":"03624134", "Lamp":"03636649", "Laptop":"03642806...
from .base import Response class Domains(Response): def getList(self, **kwargs): """ Command: `namecheap.domains.getList` [Online documentation]( https://www.namecheap.com/support/api/methods/domains/get-list.aspx ) """ return self._request( ...
r""" =============================================================================== Submodule -- miscillaneous =============================================================================== Models for applying basic phase properties """ import scipy as _sp def constant(phase, value, **kwargs): r""" Assign...
import sys input = sys.stdin.readline def bfs(n, m): queue = [] queue.append([n, m]) while queue: a = queue.pop(0) x = a[0] y = a[1] for dx, dy in (1,0), (-1,0),(0,1),(0,-1): if 0 <= x+dx < N and 0 <= y+dy < M and matrix[x+dx][y+dy] ==1: queue.ap...
import csv import pandas as pd df = pd.read_csv("warranty_status.csv") g = df.groupby('dental_outlet') print(g) print(g.get_group('LIVERPOOL DENTAL CARE')) h = g.get_group('LIVERPOOL DENTAL CARE') print(h.count()) start_count = h.count().warranty_start total_count = h.count().dental_outlet non_count = total_count - st...
import csv from parser import result from time import time with open(f'./jobs{time()}.csv', 'w') as file: fieldnames = ['id', 'title', 'salary', 'description'] csv_writer = csv.DictWriter(file, fieldnames=fieldnames) csv_writer.writeheader() for item in result: salary = ''.join(''.join(item['...
M = 1_000_000 INP = "496138527" L = [int(i) for i in INP] + list(range(10, M + 1)) CUPS = dict() for i, _ in enumerate(L[:-1]): CUPS[_] = L[i + 1] CUPS[M] = L[0] CUR = L[0] def move(): global CUPS, CUR picked = [CUPS[CUR], CUPS[CUPS[CUR]], CUPS[CUPS[CUPS[CUR]]]] DES = CUR - 1 if CUR > 1 else M w...
from django.shortcuts import render, redirect from login_app.models import User from django.contrib import messages import bcrypt from datetime import datetime def index(request): return render(request, "index.html") def success(request): if "user_id" not in request.session: return redirect("/") ...
from . import views from django.urls import path urlpatterns = [ path('', views.all_threads, name='forum'), path('<slug:slug>/', views.thread_detail, name='thread_detail'), path('add', views.add_thread, name='add_thread'), path('edit/<slug:slug>/', views.edit_thread, name='edit_thread'), path('del...
import time from os.path import exists import numpy import torch from tifffile import imread, imwrite from ssi.ssi_deconv import SSIDeconvolution from ssi.models.unet import UNet from ssi.utils.io.datasets import add_microscope_blur_2d, add_poisson_gaussian_noise def demo(image): image = image[0:512] _, psf...
from discord.ext import commands bot = None def is_owner_check(ctx): bot = ctx.bot return str(ctx.message.author.id) in ctx.bot.config.get('OWNERS') def is_owner_or_gmod(ctx): bot = ctx.bot return (str(ctx.message.author.id) in ctx.bot.config.get('OWNERS')) or (str(ctx.message.author.id) in bot.c...
#!/usr/bin/python import matplotlib.pyplot as plt import json import subprocess import datetime import numpy as np blue = [136./255., 186./255., 235./255.] orange = [253./255., 174./255., 97./255.] red = [140./255., 20./255., 32./255.] green = [171./255., 221./255., 164./255.] def main(): date = '14May' db...
# from hm.utils.utils import disp import numpy as np from .base_model import mob_model class gravity(mob_model): ''' The gravity human mobility model ''' def __init__(self, pop, alpha, beta, gamma, **kwargs): super().__init__(pop) kwargs.setdefault('exp', False) self.alpha = alpha # population i exponent ...
from django.shortcuts import render from django.http import HttpResponse # Create your views here. """ Where we handle request logic for our web application. What needs to happen or what data needs to be present at the press of a button """ def frontPageView(request): return HttpResponse('What is going on folks....
#!/usr/bin/env python # -*- coding:utf-8 -*- import torch import torch.nn as nn import numpy as np import time from trainer import trainer, Divide, TrainValidTest from model import STDGN_woa import measure import utils from torch.utils.data import TensorDataset, Dataset, DataLoader from torch.autograd import Variable ...
from typing import Callable from chex import Array
import scrapy import time from scrapy.loader import ItemLoader from optimiced.items import Article from datetime import datetime import re class OptiSpider(scrapy.Spider): name = 'opti_en' allowed_domains = ['optimiced.com'] start_urls = ['http://optimiced.com/en'] def parse(self, response): ...
import hashlib import os from appJar import gui import assistant.setup, assistant.assistant # import assistant.setup as setup def hash_password(password): password = hashlib.md5(password.encode()) return password def main(): def press(name): if name == "Cancel": start.stop() e...
#!/usr/bin/python import os import requests import sys from subprocess import call from __future__ import print_function ### Modify the below parameters ### # You may need to modify feed configuration in create_feed() if you don't use localhost interpreter = "python2.7" # Python interpreter to run YCSB load_name ...
# Two lists of numbers are given, which can contain # up to 100,000 numbers each. Calculate how many numbers # are contained simultaneously in both the first list and the second. a = list(map(int, input().split())) b = list(map(int, input().split())) print(len(set(a) & set(b)))
from timeit import default_timer as timer import json class Settings(object): """ Shared settings for all hardcoded values (easier for migrations of code and such...) """ def __init__(self, args=None): self.server_model_paths_start = "/media/vitek/SCAN/LONDON_external_data/ProcessedMusicData/...
from django.apps import AppConfig class HsmConfig(AppConfig): name = 'hsm'
import torch import numpy as np import visdom import pickle from tqdm import tqdm from PIL import Image def calc_hamming_dist(B1, B2): q = B2.shape[1] if len(B1.shape) < 2: B1 = B1.unsqueeze(0) distH = 0.5 * (q - B1.mm(B2.t())) return distH def calc_map_k(qB, rB, query_label, retrieval_label...
#!/usr/bin/python ''' Day 3 - Morning (pt. 1) A new system policy has been put in place that requires all accounts to use a passphrase instead of simply a password. A passphrase consists of a series of words (lowercase letters) separated by spaces. To ensure security, a valid passphrase must contain no duplicate w...