text stringlengths 8 6.05M |
|---|
#!/usr/bin/env python
import liboscimp_fpga
import sys
liboscimp_fpga.fir_send_conf(sys.argv[1], sys.argv[2], 25)
|
import sys
import shelve
import pickle
import os
import math
from utils import helper, textprocessing
from collections import Counter
# Load data from files
db_file = os.path.join(os.getcwd(), 'db', 'index.db')
urls_file = os.path.join(os.getcwd(), 'db', 'urls.db')
lengths_file = os.path.join(os.getcwd(), 'db', 'leng... |
#!/usr/bin/python
import re, os
def getpwd(X):
s = "%s: (.*)" % X
p = re.compile(s)
authinfo = os.popen("gpg -q --batch -d ~/.pwd/emails.gpg").read()
return p.search(authinfo).group(1) |
from .database import *
def createDb():
"""Metodo de cracion de la base de datos"""
db.drop_all()
db.create_all()
def initDb():
"""Metodo de inicializacion de uestra base de datos"""
createDb()
admin = User(
name="faby",
lastname="star",
username="faby",
email="... |
import logging
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from djangosaml2.backends import Saml2Backend
from djangosaml2.signals import pre_user_save
try:
from django.contrib.auth.models import SiteProfileNotAvailable
except ImportError:
class SiteProfileNotAvailab... |
import hashlib
print(hashlib.sha512(raw_input()).hexdigest()) |
# -*- encoding: utf-8 -*-
from openerp.osv import fields, orm, osv
import openerp.addons.decimal_precision as dp
class account_invoice_line(osv.osv):
_inherit = "account.invoice.line"
def _amount_line(self, cr, uid, ids, prop, unknow_none, unknow_dict):
res = {}
tax_obj = self.pool.get('a... |
from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from .models import *
# Create your tests here.
class UserTests(APITestCase):
def test_create_user(self):
"""
Ensure we can create a new user object.
... |
print([5, 6])
|
#!/usr/bin/env python3
import boto3, json
from time import sleep
def create_athena_DB(database, regionName, DBbucket):
#Athena database and table definition
create_database = "CREATE DATABASE IF NOT EXISTS %s;" % (database)
client = boto3.client('athena', region_name = regionName)
config = {'Outpu... |
from keras.models import load_model
from helpers import resize_to_fit
from imutils import paths
import numpy as np
import imutils
import cv2
import pickle
import os
LETTER_MODEL_FILENAME = "captcha_model.hdf5"
LETTER_MODEL_LABELS_FILENAME = "model_labels.dat"
LENGHT_MODEL_FILENAME = "captcha_model_len.hdf5"
LENGHT_MO... |
# def array_length(arr):
# return len(test)
# def insert_number(arr, index, number):
# arr.insert(index, number)
# return arr
def insertShiftArray(arr, num):
array_length = len(arr)
if array_length % 2:
middle_array = round(array_length // 2) + 1
else:
middle_array = array_length // 2
arr.in... |
from cookiecutter.main import cookiecutter as bake
from cutout.constants import STENCIL_PATH_PREFIX
class TestBuild:
def test_build__with_defaults(self, tmp_path):
bake("examples", output_dir=tmp_path, no_input=True)
build_path = tmp_path / "cut-out-test"
assert build_path.exists()
... |
import matplotlib.pyplot as plt
import numpy as np
IB=np.arange(0.001,40,0.005)
IBAR=[0.001,0.002,0.003,0.004,0.005,0.006,0.008,0.009,0.01,0.02,0.03,0.04,0.05,0.08,1,1.1,1.5,1.8,2,3,4,5,6,7,8,9,10,11,13,15,18,20,22,24,26,28,30,32,34,35,40]
curvature=[0.0,0.005,0.01,0.015,0.02,0.025,0.03,0.035,0.04,0.045,0.05,0.055,0.06... |
#!/usr/local/bin/python3
# Change the above shebang to your python3 binary path
import os, sys, subprocess
import getpass, hashlib, binascii
import atexit
import argparse
# Check for Python3
if sys.version_info[0] < 3:
print("ShellLocker requires Python 3 or higher.")
exit()
# Silence Python internal error... |
import aiohttp
import asyncio
from base import base as base
import time
import utils.make_exercise as make_exercise
import re
# 获取测试用户token,供并发测试使用
def get_users_token():
with open('../data/users.txt', 'r') as fp:
user_names = eval(fp.read())
print(user_names)
tokens = []
for user_name in ... |
f = open("extract.txt","r")
lines = f.read().split("<div class=\"icon\" id=\"")
f.close()
ids = [i.split("\">")[0].strip() for i in lines][1:]
idsstr = '\n'.join(ids)
print idsstr
# #id1:hover,#id2:hover
hoverlist = ["#"+id+":hover" for id in ids]
hover = ', '.join(hoverlist)
print hover
# #id{
# background: url('../i... |
"""Run parallel shallow water domain.
run using command like:
mpirun -np m python run_parallel_sw_merimbula.py
where m is the number of processors to be used.
Will produce sww files with names domain_Pn_m.sww where m is number of processors and
n in [0, m-1] refers to specific processor that owne... |
class Test:
def __init__(self):
self.__color = 'red'
@property
def color(self):
return self.__color
@color.setter
def color(self, clr):
self.__color = clr
if __name__ == '__main__':
t = Test()
print(t.color)
t.color = 'blue'
print(t.color)
|
#PSU ARL 5 Capstone
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import sklearn
from sklearn import linear_model
from sklearn import metrics
from sklearn.model_selection import train_test_split
from sklearn.ensemble import AdaBoostClassifier, GradientBoostingClassifi... |
def aumentar(n, aum):
return n + aum
def diminuir(n, dim):
return n - dim
def dobro(n):
return n * 2
def metade(n):
return n / 2
def moeda(n):
print(f'R${n}')
|
# -*- coding:utf-8 -*-
"""
@file: feature_process.py
@time: 2019/06/05
"""
import pandas as pd
import numpy as np
from sklearn.feature_extraction import FeatureHasher
from sklearn.preprocessing import LabelBinarizer
from scipy.sparse import hstack
META_INFO = pd.DataFrame([{"col": "id", "unique_count": 40428967},... |
import xml.dom.minidom
import re
from zipfile import ZipFile
import os
class ParserKM():
""" Класс который пердоставляет методы для получения
имён и координат из файлов kmz и kml """
def __init__(self,p):
filename, file_extension = os.path.splitext(p)
if file_extension==".kmz":
... |
from math import ceil
ADJ = None
GROUPID = None
GROUPS = None
VISITED = None
HEIGHT = None
OPT_TREE_HEIGHTS = None
def flood(u, gid):
GROUPS[gid] = [u]
queue = [u]
qi = 0
VISITED[u] = True
GROUPID[u] = gid
while qi < len(queue):
u = queue[qi]
for v in ADJ[u]:
if n... |
import yaml
from src import helpers,descriptors,svm,evaluate
from sklearn.externals import joblib
from ast import literal_eval
import numpy as np
# svm test data path to get the matrices like accuracy,recall and precision
svm_test_path='C:/Users/gvadakku/Desktop/final_software_cnn_play/images/svm_data/svm_evaluate/'
... |
from db_models.models.exercise import Exercise
from db_models.models.profile import Profile
from django.db import models
class PersonalRecord(models.Model):
profile = models.ForeignKey(
Profile,
on_delete=models.CASCADE,
db_index=True,
)
exercise = models.ForeignKey(
Exer... |
from selenium import webdriver
import math
def calc(x):
return str(math.log(abs(12*math.sin(int(x)))))
browser = webdriver.Chrome()
link = "https://suninjuly.github.io/execute_script.html"
browser.get(link)
x = browser.find_element_by_id("input_value").text
answer = calc(x)
browser.execute_script("window.scrollBy(... |
import sys,getopt,ConfigParser,os
import json
import subprocess
import math
ROOT_DIR = '/data/vision/billf/object-properties/sound/sound/'
class Obj:
ROOT = ROOT_DIR
def __init__(self,objId=0,matId=0):
self.objId = objId
self.matId = matId
self.Load()
def ReadMaterial(self,matId):
... |
#Import dependencies
import numpy as np
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
import datetime as dt
##############################################################################... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# classify_captures.py
#
# Copyright 2018 Andres Aguilar <andresyoshimar@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundati... |
def main(config):
from SDML import Solver
solver = Solver(config)
cudnn.benchmark = True
return solver.train()
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--compute_all', type=bool, default=False)
parser.add_argument('--mode', type... |
from django.db import models
from django.db.models.signals import pre_save, post_save
from django.utils.text import slugify
from django.conf import settings
from django.urls import reverse
def get_unique_slug(model_instance, slugable_field_name, slug_field_name):
"""
Takes a model instance, sluggable field nam... |
from django.urls import path, include
urlpatterns = [
path('api/tasks/', include('todo.urls')),
]
|
import onegov.core
import onegov.org
from tests.shared import utils
def test_view_permissions():
utils.assert_explicit_permissions(onegov.org, onegov.org.OrgApp)
def test_notfound(client):
notfound_page = client.get('/foobar', expect_errors=True)
assert "Seite nicht gefunden" in notfound_page
assert... |
SUBSCRIPT = str.maketrans("0123456789", "₀₁₂₃₄₅₆₇₈₉")
class SymbolParser:
@staticmethod
def subscript(string):
return string.translate(SUBSCRIPT)
|
#import sys
#input = sys.stdin.readline
def main():
N = 50
A = [["x"]*N for _ in range(N)]
cnt = 0
for i in range(1, N+1):
print(i, bin(i)[2:], end = " | ")
for j in range(i,N+1):
if j%i == i^j:
print(bin(j)[2:], end = " ")
cnt += 1
... |
import numpy as np
from scipy.stats import multivariate_normal
from matplotlib import pyplot as plt, lines as mlines, patches as mpatch
# Given in the problem
prior = [0.15, 0.35, 0.5]
mu = [np.array([-1, 0]), np.array([1, 0]), np.array([0, 1])]
sigma = [np.array([[1, -.4], [-.4, .5]]), np.array([[.5, 0], [0, .2]]), ... |
# 312. Burst Balloons
'''
Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by array nums. You are asked to burst all the balloons. If the you burst balloon i you will get nums[left] * nums[i] * nums[right] coins. Here left and right are adjacent indices of i. After the b... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
import os, sys, re
# from fabric.api import *
# from fabric.contrib.console import confirm
from fabric2 import Connection
# .dotenv
# from os.path import join, dirname
# from dotenv import load_dotenv
# load environm... |
#ecoding = utf-8
__author__ = 'bohan'
# 函数修饰符的使用
|
from django.db import models
from tweets.models import Tweet
from users.models import UserAccount
# Create your models here.
class Comment(models.Model):
user_id = models.ForeignKey(UserAccount, on_delete=models.CASCADE, related_name='user_comments')
tweet_id = models.ForeignKey(Tweet, on_delete=models.CASCADE... |
from oscpy.client import OSCClient
address = "127.0.0.1"
port = 8000
osc = OSCClient(address, port)
for i in range(10):
osc.send_message(b'/send_i', [i])
|
import httplib2
from datetime import datetime
import simplejson
import time
URL = 'http://localhost:7777/api/newuser'
role = "driver"
uname = "hitesh"
fullname = "hitesh katre"
mob_num = "8085461683"
email_id = "hkkatre@gmail.com"
v_id = "jhgfdshddsd"
token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjp7IjIiOnRydWV... |
sum_of_sqares = sum(map(lambda x: x ** 2,list(range(1,101))))
sum_squared = sum(list(range(1,101))) ** 2
print sum_squared - sum_of_sqares
|
from application import Application
import pyglet
pyglet.resource.path = ['resources', 'resources/images/', 'resources/levels']
pyglet.resource.reindex()
application = Application()
|
list1 = [1,2,3]
try:
print(list1.index(5))
except:
print("ERROR")
|
import abc
class Embedding(abc.ABC):
"""Embedding interface."""
def embedding(self, inputs, length, params=None):
"""Do embedding.
Args:
inputs: A tensor, input sequence, shape is [B, T]
length: A tensor, input's length, shape is [B]
params: A python dict,... |
from selenium import webdriver
from time import sleep
driver = webdriver.Firefox()
driver.get("https://videojs.com/")
video = driver.find_element_by_xpath("//*[@id='preview-player_html5_api']")
sleep(5)
url = driver.execute_script("return arguments[0].currentSrc;",video)
print(url)
print("start")
driver.execute_scr... |
#Receba o número de voltas, a extensão do circuito (em metros) e o tempo de
#duração (minutos). Calcule e mostre a velocidade média em km/h.
vt=int(input('digite o numero de voltas: '))
ext=int(input('digite a extensão do percurso(metros): '))
tempo=int(input('digite o tempo de duração(min): '))
print(f'a velocidade ... |
from src.set_encoders import ContextFreeEncoder
import torch
import torch.nn.functional as F
import torch.nn as nn
from torch.autograd import Variable
import numpy as np
class Simple2DConvNet(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(3, 10, kernel_size=5)
se... |
class Stack():
def __init__(self, stackSize):
self._top = -1
self._stackSize = stackSize
self._stackArray = [None] * stackSize
def getStackSize(self):
return (self._stackSize)
def setStackSize(self, stackSize):
self._stackSize = stackSize
def isEmpt... |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Topic(models.Model):
top_name = models.CharField(max_length=264, unique=True)
def __str__(self):
return self.top_name
class Webpage(models.Model):
topic = models.ForeignKey(Topic,on_delete=m... |
#!/usr/bin/env python
"""
wmcore-sensord
daemon for WMComponent, Service, Resource and Disk.
"""
import time
import os
import sys
import getopt
import subprocess
import string
import copy
import time
import smtplib
import signal
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from e... |
import sys
sys.stdin = open('input.txt', 'rt')
n,m = map(int, input().split())
cnt = [0]*(n+m+3 )
max = -2147000000
for i in range(1,n+1):
for j in range(1,m+1):
cnt[i+j] +=1
for i in range(n+m+1):
if cnt[i] > max:
max=cnt[i]
for i in range(n+m+1):
if cnt[i] == max:
print(i, end =... |
from django.shortcuts import render
from .models import *
from django.contrib.auth.models import User
from rest_framework import viewsets,permissions
from order.serializers import *
from rest_framework.views import APIView
from rest_framework.response import Response
from django.core.mail import send_mail
from ... |
import numpy as np
np.set_printoptions(precision=3, suppress=True)
np.core.arrayprint._line_width = 10
import os
from itertools import product
import glob
from adult import preprocess_adult_data, get_metrics
from train_clp_adult import get_consistency, predict_from_checkpoint
from warnings import simplefilter
simplefil... |
from .piece import Piece
from game_rules import can_move
import os
class Bishop(Piece):
def __init__(self, color, name):
self.sprite_dir = color + "Bishop.png"
self.name = name
super(Bishop,self).__init__(color,name)
def get_possible_moves(self, coord, matrix):
list_aux =... |
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# 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 o... |
import time
from NID import NID
# The output (path taken from the UI): (1)Two csv files ,(2) Heat-Map for pairwise interactions, (3)Log file
# 1st csv file for pairwise interaction
# 2nd csv file for higher order interaction
# every line contains interaction and strength
'''input params, init... |
#!/usr/bin/env python
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# -------------------------... |
#! usr/bin/python3
from treenode import TreeNode
def maxDepth(root: TreeNode) -> int:
if not root:
return 0
if not root.left and not root.right:
return 1
else:
return max(maxDepth(root.left), maxDepth(root.right)) + 1
t = TreeNode(1)
t.right = TreeNode(2)
print(max... |
# quick sort
def quickSort(arr, start, end):
if start >= end: # if len(data) == 1 or start and end are crossed
return
pivot = start # pivot = first element in data set
i = start + 1 # find i bigger than pivot from start to right
j = end # find j smaller than pivot from end to left
wh... |
# 92. Backpack
'''
Given n items with size Ai, an integer m denotes the size of a backpack. How full you can fill this backpack?
'''
Basic idea: DP
T[size][j] is max cap backpack can fill with size and items 0...j
T[size][j] = T(size, j-1) if A[i] > size
max(T(size-A[i], i-1)+A[i], T(size, i-1))
Solution... |
from datetime import date
from decimal import Decimal
from onegov.core.utils import Bunch
from onegov.swissvotes.collections import SwissVoteCollection
from onegov.swissvotes.external_resources import MfgPosters
from onegov.swissvotes.external_resources import SaPosters
from onegov.swissvotes.external_resources.posters... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# time: 2020-8-9 23:11:00
# version: 1.0
# __author__: zhilong
import pymysql
def init():
conn = pymysql.connect(host='localhost', user='root', password='rootpwd', charset='utf8mb4', db='spider')
cursor = conn.cursor()
sql = '''
create table wangyi(id int ... |
import pytest
import boto3
from moto import mock_s3
import requests_mock
import os
os.environ['ATTACHMENT_BUCKET'] = 'attachments'
os.environ['BPM_CSRF_URL'] = 'https://localhost/bpm/dev/csrf'
os.environ['BPM_EMAIL_URL'] = 'https://localhost/bpm/dev/launch'
os.environ['BPM_PW'] = 'blah'
os.environ['BPM_USER'] = 'blah'
... |
## List Mutation ##
def map(fn, lst):
"""Maps fn onto lst using mutation.
>>> original_list = [5, -1, 2, 0]
>>> map(lambda x: x * x, original_list)
>>> original_list
[25, 1, 4, 0]
"""
for item in range(len(lst)):
lst[item] = fn(lst[item]) #need to say that its
# lst[:] = [fn(it... |
import os
def main():
os.chdir(os.path.dirname(os.path.abspath(__file__)))
inp = open("day23_input.txt").read().splitlines()
print(solve(inp))
class Duet:
def __init__(self, instructions):
self.instructions = instructions
self.cursor = 0
self.registers = {i: 0 for i in ['a'... |
import config
from bs4 import BeautifulSoup as bs
import os
def createTests():
for c in config.containers :
os.makedirs(config.testsDir + '/' + c + '/src', exist_ok=True)
for file in os.scandir(config.pagesDir + '/' + c + '/functions/' ):
with open(file, "r") as f :
c... |
n = 1001
a = 1
sq_list = [1]
for i in range(1,1+(n-1)/2):
for j in range(4):
a += 2*i
sq_list.append(a)
a = sq_list[-1]
print sum(sq_list)
|
import glob2
from datetime import datetime
szorsz = ["file1.txt", "file2.txt", "file3.txt"]
#fajlnev = str(date(now)) + ".txt"
fajlnev = "etwas.txt"
def writer(fajlok, fajlpath):
with open(fajlpath, "a") as myfile:
for s in fajlok:
readf = open(s)
content = readf.read()
... |
import sys
sys.stdin=open("input.txt", "r")
'''
# 사용해야 하는 알고리즘 = bfs (최단 거리)
: 어느 지점에서 목표 지점으로 가는 최단 거리는 bfs로 구한다.
# 문제 풀이 아이디어
: 현재 위치에서 bfs를 한다.
: 단, bfs를 하기 전에 불이 번진 것을 먼저 표시한다.
: 출구가 몇개인지 어디 있는지 알 수 없으므로
: x 혹은 y 좌표가 가장자리에 위치하면 탈출한 것으로 간주한다.
# 중간 개선 사항
1. 시간초과 : fire를 원래 이중 반복문으로 체크하... |
# Copyright 2017 Covata Limited or its affiliates
#
# 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 applica... |
import time
from actors import Actor, Core, TAG_USER_CLASSIFER
from actors import concurentmethod, WorkAssignerActor
from twitter import Api, Status
class UserClassifierActor(Actor):
def __init__(self, core: Core):
super().__init__(core)
self.tags = [TAG_USER_CLASSIFER]
@concurentmethod
... |
"""empty message
Revision ID: bcce035c4d07
Revises: f1fabccfa03d
Create Date: 2018-03-10 12:18:08.413852
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'bcce035c4d07'
down_revision = 'f1fabccfa03d'
branch_labels = None
depends_on = None
def upgrade():
# ... |
"""
Scraper for allrecipes.com. Collectis all recipe links from website.
Author: Ankur Duggal & John Li
"""
from .scraper_base import ScraperBase
from selectolax.parser import HTMLParser
import json
import requests
import string
import re
class AllRecipes(ScraperBase):
""" Class for scraping recipe links from ... |
from django.db import models
from datetime import datetime
from django.utils.timezone import now
from django.contrib.sitemaps import ping_google
class Category(models.Model):
category = models.CharField(max_length=20)
category_en = models.CharField(max_length=20)
category_image = models.CharField(max_leng... |
N, A, B = map( int, input().split())
hmax = 0
H = [ int( input()) for _ in range(N)]
hmax = max(H)
L = 0
R = hmax//B + 1
add = A-B
#以下よりも早い
while R-L != 1:#L != R:
now = (L+R)//2
need = 0
for i in range(N):
r = H[i] - now*B
if r > 0:
need += (r-1)//add+1
if need <= now:##うまくい... |
import unittest
class Solution:
def get_int(self, s):
i = 0
ans = 0
while i < len(s) and s[i] in "0123456789":
ans = 10 * ans + int(s[i])
i += 1
return ans
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
... |
import bson
import datetime
import json
import os
import uuid
import fs.errors
import fs.path
from .web import base
from .web.errors import FileFormException
from . import config
from . import files
from . import placer as pl
from . import util
from .dao import hierarchy
Strategy = util.Enum('Strategy', {
'targe... |
import sys
from rosalind_utility import parse_fasta
def semiglobal_alignment(str1, str2):
str1 = "-" + str1
str2 = "-" + str2
score_mat = [[0 for j in range(len(str2))] for i in range(len(str1))]
backtrack_mat = [[None for j in range(len(str2))] for i in range(len(str1))]
for i in range(1, len(s... |
import random as r, csv
issuers =('Adventure Lending','ABC Lending','Global Lending')
property_types=('Multi-family','Single-family','Retail','Office')
age_ranges = ('20-25','26-30','30-40','40-50','50-60')
currency = 'USD'
asset_type = "Mortgage Token"
with open('mortgage_data.csv', mode='w+') as mortgage_data:
... |
"""A number-guessing game."""
# Put your code here
#let's make a random number selection
import random
randomizer = random.randrange(1, 100)
#print(randomizer)
#let's greet the player
name = input('Hello, what is your name? ')
print(name + ", I'm thinking of a number between 1 and 100. \n Try to guess my number.")
... |
from functools import cached_property
from onegov.core.elements import Confirm
from onegov.core.elements import Intercooler
from onegov.core.elements import Link
from onegov.wtfs import _
from onegov.wtfs.layouts.default import DefaultLayout
from onegov.wtfs.security import AddModel
from onegov.wtfs.security import Add... |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Neighborhood(models.Model):
name = models.CharField(max_length=50)
location = models.ForeignKey('Location', on_delete=models.CASCADE, null=True)
admin = models.ForeignKey(User, on_delete=models.CASCAD... |
from orun.db import models
from orun.utils.translation import gettext_lazy as _
class ActivityType(models.Model):
name = models.CharField(_('Name'), null=False, translate=True)
summary = models.CharField(_('Summary'), translate=True)
sequence = models.IntegerField(_('Sequence'), default=10)
active = m... |
import unittest
import mimec
from email.message import Message
from email.parser import FeedParser
def mail(data):
parser = FeedParser()
parser.feed(data)
return parser.close()
def envelope(message):
return {
'from': str(message.get_all('From')),
'to': str(message.get_all('To')),
... |
# Generated by Django 2.0 on 2019-11-06 07:49
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('chats', '0003_auto_20191030_1613'),
]
operations = [
migrations.AlterModelOptions(
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# this script serves to use the k-means
# to cluster articles within a category
#
# @author Yuan JIN
# @contact chengdujin@gmail.com
# @since 2012.03.15
# @latest 2012.03.21
#
import redis
REDIS_SERVER = 'localhost'
r = redis.StrictRedis(REDIS_SERVER)
# reload the script ... |
# coding: utf-8
# Game board. It needs a height and a width in order
# to be instantiated
class board(object):
BLACK = 1
WHITE = 0
NOTDONE = -1
def __init__(self, height, width, firstPlayer):
"""
Constructs a board, right now maxDepth is statically assigned
"""
# Set ... |
# -*- coding: utf-8 -*-
"""
Este script utiliza funciones, importadas de boltzmann_codes.py, que calculan cantidades
cosmologicas (matter power spectrum, angular power spectrum, angular diameter distance,
hubble parameter, growth rate) para parametros cosmologicos a eleccion, utilizando ya sea
CAMB o CLASS
"""
from ... |
# # project euler problems
#
# # project euler problem 1 (multiples of 3 and 5)
#
# multiples = 0
# for x in range(3, 1000):
# if (x % 3) == 0 or (x % 5) == 0:
# multiples = multiples + x
#
# print(multiples)
#
# # project euler problem 2 (even fibonacci numbers)
#
# sum = 0
# a = 1
# b = 1
# for x in range... |
import unittest
from dictpath import dictpath
class TestDictPath(unittest.TestCase):
def test_explore(self):
d = { 'level1a': 'string'}
self.assertEqual(dictpath(d).explore(), { 'level1a': 'str' })
d = { 'level1a': 'string',
'level1b': 1,
'level1c': [1 ,2 ,3],... |
from django.contrib.auth.models import User, Group
from django.core.management.base import BaseCommand
from materialcleaner.settings import ACCESS_POLICIES
class Command(BaseCommand):
help = 'Step 5 @ fill-in new DB. Assign users to user-groups to define her/his permissions acc. ACCESS_POLICIES'
def ha... |
#!/usr/bin/python
import json, operator
from datetime import datetime, timedelta
from sqlalchemy import create_engine, or_, and_
from sqlalchemy.orm import sessionmaker
# http://docs.sqlalchemy.org/en/latest/faq/performance.html
import cProfile
from io import StringIO
import pstats
import contextlib
import logging
@... |
def get_raw_path(cropped_path):
tmp_out_path = cropped_path.split('/')
orig_img_name = tmp_out_path[len(tmp_out_path)-1].split('_')[0]
raw_out_target = tmp_out_path[0] + '/' + tmp_out_path[1] + '/' + tmp_out_path[2] + '/' + tmp_out_path[3] + '/' + tmp_out_path[4] + '/' + orig_img_name
return raw_out_ta... |
import urllib.request, urllib.parse, urllib.error
import http.cookiejar
LOGIN_URL = 'http://acm.hit.edu.cn/hoj/system/login'
values = {'user': '******', 'password': '******'} # , 'submit' : 'Login'
postdata = urllib.parse.urlencode(values).encode()
user_agent = r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 ... |
import itertools
import math
import numpy as np
import pickle
import torch
from torch.utils.data import Dataset
from torch.utils.data.sampler import Sampler
class Seq2SeqDataset(Dataset):
def __init__(self, src_file, tgt_file, src_dict, tgt_dict):
self.src_dict, self.src_dict = src_dict, tgt_dict
... |
'''
Created on Dec 20, 2016
@author: bogdan
'''
from repo.repository import *
class FileDriverRepository(DriverRepository):
def __init__(self,file="/home/bogdan/Documents/test2/src/drivers.in"):
super().__init__()
self.__file=file
self.__loadData()
def __loadData(self):
... |
from onegov.core.orm import Base
from onegov.core.orm.abstract import associated
from onegov.core.orm.mixins import ContentMixin
from onegov.core.orm.types import UUID, UTCDateTime
from onegov.file import File
from onegov.org.models import AccessExtension
from sedate import to_timezone
from sqlalchemy import (
Bool... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.