text stringlengths 8 6.05M |
|---|
from .base_query_based_model import QueryBasedSummModel
from summertime.model.base_model import SummModel
from summertime.model.single_doc import TextRankModel
from typing import List
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
class TFIDFSummMod... |
"""
Usage:
python main.py <filename>
There is some sample data in data/ folder
Test:
python test.py
There is a scattering of tests in there.
These are some resources I read in helping study the problem, many ideas and code were
provided from both:
https://github.com/nltk/nltk
http://nlp.stanford.edu/software/tokeni... |
# -*- coding: utf-8 -*-
import os
import struct
from collections import deque
from functools import partial
from irc3.compat import asyncio
class DCCBase(asyncio.Protocol):
idle_handle = None
idle_timeout = None
fd = None
def __init__(self, **kwargs):
for k, v in kwargs.items():
... |
import sys
import pygame
from pygame.sprite import Group
from settings import Settings
from scientist import Scientist
import events as gf
from coronavirus import Covid_19
from game_stats import Games_stats
from button import Button
from scoreboard import Scoreboard
# the function is supposed to initialize th... |
import math
def serie(n):
t = 1
c = 0
for i in range(n):
if c < t:
c = c + 1
else:
t = t + 1
c = 1
return t
def fibo(n):
a = 1
b = 0
for i in range(n):
f = a + b
a = b
b = f
return f
N = int(input())
sum = 0
for... |
from Cp7_test.cmp.tools import NFA, DFA
from Cp7_test.cmp.utils import DisjointSet, DisjointNode
def automata_union(a1: NFA, a2: NFA) -> NFA:
transitions = {}
start = 0
d1 = 1 # cantidad de nuevos estados para redefinir los estados de a1
d2 = a1.states + d1 # se redefinen los nombres de lo... |
# Generated by Django 3.0.7 on 2021-01-23 14:59
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('custom', '0018_pospackagedeposit'),
]
operations = [
migrations.AddField(
model_name='pospackag... |
import wikipedia
def search(query):
return wikipedia.page(query)
|
from ROOT import *
import sys, os, time
t0 = time.time()
arg1 = sys.argv[1]
if arg1 == 'Data':
input_dir = '2lep/Data/'
elif arg1 == 'MC':
input_dir = '2lep/MC/'
myChain = TChain('mini')
for filename in os.listdir(input_dir):
if not '.root' in filename: continue
print(filen... |
## 1. The Data Set ##
# Weather has been loaded in.
first_element = weather[0]
print(first_element)
last_element = weather[(len(weather) - 1)]
print(last_element)
## 3. Practice Populating a Dictionary ##
superhero_ranks = {}
superhero_ranks['Aquaman'] = 1
superhero_ranks['Superman'] = 2
## 4. Practice Indexing a D... |
from BoschShcPy.base import Base
from BoschShcPy.base_list import BaseList
from BoschShcPy.error import ErrorException
class ScenarioList(BaseList):
def __init__(self):
# We're expecting items of type Scenario
super(ScenarioList, self).__init__(Scenario)
class Scenario(Base):
def __ini... |
import argparse
import logging
import os
import sys
from core.logger import LOGGER_NAME, setup_logging
from vincere import VincereAPI
from vincere.candidate import CandidateAPI
logger = logging.getLogger(LOGGER_NAME)
if __name__ == '__main__':
setup_logging(scrnlog=True)
api_candidate = Candid... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2019-01-14 17:01
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('store', '0002_auto_20190114_1643'),
]
operations = [
migrations.CreateMode... |
class DOG:
def __init__(self, dog_age):
self.age_factor = 7
self.age = dog_age
def human_age(self):
print(self.age * self.age_factor)
if __name__ == '__main__':
Rex = DOG(5)
Rex.human_age()
|
from django.db import models
class Tag(models.Model):
slug = models.SlugField(max_length=100)
def __str__(self):
return self.slug
class Todo(models.Model):
todo_text = models.CharField(max_length=200)
tags = models.ManyToManyField(Tag, related_name="tag")
created_at = models.DateTimeField... |
#!/usr/bin/python
#Reboot Dynamixel.
from dxl_util import *
from _config import *
#Setup the device
dxl= TDynamixel1(DXL_TYPE)
dxl.Id= DXL_ID
dxl.Baudrate= BAUDRATE
dxl.Setup()
print 'Rebooting Dynamixel...'
dxl.Reboot()
#dxl.DisableTorque()
dxl.Quit()
|
import pytest
from day_5 import main
@pytest.mark.parametrize("pass_number, result_row, result_column",
[("FBFBBFFRLR", 44, 5),
("BFFFBBFRRR", 70, 7),
("FFFBBBFRRR", 14, 7),
("BBFFBBFRLL", 102, 4)])
def test_get_ro... |
"""Advent of Code Day 11 - Hex Ed"""
def path(steps_string):
"""Find how far from the centre of a hex grid a list of steps takes you."""
# Strip and split file into a iterable list
steps_list = steps_string.strip().split(',')
# Break hexagon neighbours into cube coordinates
x = 0
y = 0
z ... |
"""Conversation objects."""
import asyncio
import datetime
import logging
from hangups import (parsers, event, user, conversation_event, exceptions,
hangouts_pb2)
logger = logging.getLogger(__name__)
CONVERSATIONS_PER_REQUEST = 100
MAX_CONVERSATION_PAGES = 100
async def build_user_conversatio... |
a=int(input('enter anub'))
if(a>0):
print('num is pos')
elif(a==0):
print('num is 0')
else:
print('num is neg') |
from nose.tools import *
from app.bowling_game import *
import unittest
class BowlingGameTest(unittest.TestCase):
def setUp(self):
self.game = Game()
def test_a_new_game(self):
assert_equals(self.game.score(), 0)
|
print("linux is open source")
print("linux is secure")
|
import torch
import torch.nn as nn
from transformers import BartModel, RobertaModel
from transformers.activations import ACT2FN
def Linear(in_features, out_features, bias=True):
m = nn.Linear(in_features, out_features, bias)
nn.init.xavier_uniform_(m.weight, gain=0.0000001)
if bias:
nn.init.constan... |
from datetime import datetime
import pandas as pd
from autumn.core.inputs.database import get_input_db
def get_mobility_data(country_iso_code: str, region: str, base_date: datetime):
"""
Get daily Google mobility data for locations, for a given country.
Times are in days since a given base date.
The ... |
from onegov.activity import AttendeeCollection, Attendee, Booking
from onegov.core.security import Secret
from onegov.feriennet import FeriennetApp, _
from onegov.feriennet.exports.base import FeriennetExport
from onegov.feriennet.forms import PeriodSelectForm
from onegov.form import merge_forms
from onegov.org.forms i... |
#!/usr/bin/env python
import sqlite3
import json
import sys
import time
def main():
if len(sys.argv) < 2:
print("usage: json_to_sqlite.py dirname")
return
data = json.load(open(sys.argv[1]+"/productInfo.meta"))
print("Processing " + sys.argv[1] + "...")
packageId = data['packageId']
... |
from django.apps import AppConfig
class WhaypConfig(AppConfig):
name = 'whayp'
|
from ED6ScenarioHelper import *
def main():
# 蔡斯
CreateScenaFile(
FileName = 'T3300_1 ._SN',
MapName = 'Zeiss',
Location = 'T3300.x',
MapIndex = 1,
MapDefaultBGM = "ed60010",
Flags = 0,
En... |
n=int(input('digite um numero: '))
cont=int(0)
while cont<=10:
print(f'{n} X {cont} = {n*cont}')
cont+=1
|
import threading
from glob import glob
from os import path
from shutil import copy
from subprocess import Popen
from .general import create_dir
def run_flo2d_model(run_path):
thread = threading.Thread(target=_run_flo2d_model, args=(run_path,))
thread.daemon = True # Daemonize thread
thread.start()
de... |
import os
import unittest
from rdflib import Graph
from funowl.converters.functional_converter import to_python
from tests import datadir
from tests.utils.rdf_comparator import compare_rdf
pizza = os.path.join(datadir, 'pizza.owl')
pizza_ttl = os.path.join(datadir, 'pizza.ttl')
class FunctionalDefinitionsTestCase(u... |
from flask import Blueprint, abort, jsonify, request, session, current_app
from flask_login import current_user
from flask_allows import requires
from werkzeug import secure_filename
from ctesi.core.tasks import process
from ctesi.utils import validate_search_params
from ctesi.core.requirements import is_admin, can_edi... |
# @Title: 二叉树的最小深度 (Minimum Depth of Binary Tree)
# @Author: 2464512446@qq.com
# @Date: 2020-11-16 16:48:33
# @Runtime: 528 ms
# @Memory: 49.1 MB
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Sol... |
# coding=utf-8
from __future__ import unicode_literals
from os import path
try:
with open(path.join(path.dirname(__file__), 'api_key'), 'r') as f:
API_KEY = f.read().strip()
except IOError:
API_KEY = 'adf51226795afbc4e7575ccc124face7' # default key used by drivenow.com
CITIES = {
'berlin': {
... |
#coding=utf-8
from PIL import Image
import sys
from Crypto.Cipher import AES
import base64
import copy
#pad 使用PKCS
def pad(text):
padding = 16 - (len(text) % 16)
return text + bytes([padding] * padding)#補齊不足的
#unpad 使用PKCS
def unpad(text):
padding = text[-1]
return text[:-padding]#刪掉多餘的
#兩個大bytes的互斥或
def bytes_... |
'''
Possible rating images:
'imdb://image.rating'
'rottentomatoes://image.rating.rotten'
'rottentomatoes://image.rating.ripe'
'rottentomatoes://image.rating.certified'
'rottentomatoes://image.rating.spilled'
'rottentomatoes://image.rating.upright'
'''
import requests
from lxml import html
from lxml.html import fromstr... |
from flask_1 import db,login_manager
from flask_login import UserMixin
@login_manager.user_loader
def load_user(user_id):
return user.query.get(int(user_id))
class user(db.Model, UserMixin):
id= db.Column(db.Integer,primary_key= True)
username =db.Column(db.String(20),unique=True,nullable=Fals... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import math
from collections import Counter
import copy
def initialize(board):
start_board = []
with open("data1/initial.txt") as file:
for line in file.readlines():
line = line.strip('\n')
start_board.append(eval(line))
start_board.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ˅
import random
from behavioral_patterns.strategy.hand_signal import get_hand
from behavioral_patterns.strategy.strategy import Strategy
# ˄
# Random Strategy: showing a random hand signal.
class RandomStrategy(Strategy):
# ˅
# ˄
def __init__(self):
... |
#!/usr/bin/env python
# encoding: utf-8
import argparse
import subprocess as sub
### Parse command line arguments
parser = argparse.ArgumentParser(description="M/M/1 queue simulation -- Helper script")
parser.add_argument('reps', metavar='repetitions',
type=int, help='number of repetitions')
pars... |
import json
import asyncio
import discord
from discord.ext import commands
from potato_bot.cog import Cog
from potato_bot.utils import run_process
from potato_bot.checks import is_admin
from potato_bot.constants import SERVER_HOME
class PotatoStation(Cog):
"""PotatoStation UnityStation server management and in... |
from ..notices.notice import Notice
from ..types.email import Email
class Channel(object):
"""Base class which all channel implementations should extend"""
def send(self, notice: Notice):
"""Send a notice through the channel. Must be implemented in subclasses"""
raise NotImplementedError()
|
# Generated by Django 3.2.5 on 2021-07-09 00:55
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Cita',
fields=[
('id', models.BigAutoField(... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class Language(object):
def __init__(self):
self.locale = ''
self.value = ''
def get_locale(self):
return self.locale
def set_locale(self, locale):
self.locale = locale
def get_value(self):
return self.value
def... |
from typing import List
from datetime import datetime
from flask import request
from requirementmanager.app import app
from requirementmanager.utils.handle_api import handle_response, verify_request
from requirementmanager.mongodb import (
requirement_collection, requirement_tree_collection
)
from requirementmana... |
celsius=input('Add meg a homersekletet celsiusban\n')
to=input('Mibe szeretned atvaltani?\n(F)ahrenheit/(K)elvin\n')
C=int(celsius)
F=C*18/10+32
K=C+273
if to=='F'or to=='f':
print(F)
elif to=='K'or to=='k':
print(K)
else:
print('nem tudom ertelmezni') |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Import sys for relative import
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../")
from Corpus.dictionaries import Dictionary
from Tools.download import GithubDir
class Gaffiot(Dictionary):
def __init__(self, *args, **kw):
... |
#!../venv/Scripts/python.exe
import random
import time
import csv
import json
from multiprocessing.dummy import Pool as ThreadPool
import requests
from bs4 import BeautifulSoup, SoupStrainer
from fake_useragent import UserAgent
from constants import Const as const
class App:
def __init__(self):
start_url ... |
#!/usr/bin/env python
#-*-coding: utf8-*-
'''
a wrapper class for optimizer
@author: plm
@create: 2018-09-25
@modified: 2018-09-25
'''
import numpy as np
class ScheduledOptimizer(object):
'''a simple wrapper of pytorch optimizer, transformer optimizer style'''
def __init__(self, optimizer, dmodel=128, n_war... |
import sys
from PyQt4 import QtCore, QtGui
from world import World
class Window(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.setGeometry(0, 0, 800, 800)
self.setWindowTitle('AI Sim')
def center(self):
screen = QtGui.QDesktopWidget().screenGeometry()
size = self.geometry()... |
# Generated by Django 2.0.7 on 2019-01-10 13:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('basedata', '0047_auto_20190110_1252'),
]
operations = [
migrations.AlterField(
model_name='outsource',
name='fuzeren... |
from pyzillow.pyzillow import ZillowWrapper, GetDeepSearchResults, GetUpdatedPropertyDetails, ZillowError
from topology_estimation.roof_pitch_estimation import roof_type_to_rad
def get_building_data(address, zipcode):
sq_feet_to_meters = 0.092903
zillow_data = ZillowWrapper('X1-ZWz1fjckjdd8gb_a2eph')
tr... |
#!/usr/bin/env python2
# -*- coding: UTF-8 -*-
import sys, os, json, string
if __name__ == '__main__':
if len(sys.argv) <= 2:
print 'Help: %s inputfile output_json' % sys.argv[0]
exit(1)
if not os.path.isfile(sys.argv[1]):
sys.stderr.write('%s is not file\n' % sys.argv[1])
exit(1)
mydict={}
with open(sys... |
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> # LIST
>>> L = ['red', 'green', 'blue']
>>> M = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
>>> M[0]
[1, 2, 3]
>>> M[0][-1]
3
>>> M[0][2]
3
>>> M[0... |
import re
import random
import string
import collections
WORDS = [w.strip() for w in open('/usr/share/dict/british-english').readlines()
if re.match(r'^[a-z]*$', w.strip())]
LETTER_COUNTS = collections.Counter(l.lower() for l in open('../sherlock-holmes.txt').read() if l in string.ascii_letters)
LETTERS_IN_... |
import numpy as np
from alexnet import alexnet
import os
training_data_name = 'balanced_training_data.npy'
WIDTH = 40
HEIGHT = 60
LR = 1e-3
EPOCHS = 10
MODEL_NAME = 'CNN-Play-Race-{}-{}-{}.model'.format(LR,'alexnetv3',EPOCHS)
model = alexnet(WIDTH, HEIGHT, LR)
train_data = np.load(training_data_name)
X = np.array(... |
class Algo:
def __init__(self):
self.cosas=0
def nuevoHola(self):
hola= "si jala"
return hola
hola= nuevoHola()
|
import datetime
import plotly.express as px
import pandas as pd
import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QFileDialog
import DataSender
from PyQt5 import QtGui
from PyQt5.QtWidgets import QTableWidgetItem
class Ui_MainWindow(object):
def setupUi(self, MainWindow): # Настройки о... |
import matplotlib.pyplot as plt
from util.plot import poles_zeros_plot
from util.speech import vocal_tract_model
FS = 16000
A_PARAMS = [
(830, 110),
(1400, 160),
(2890, 210),
(3930, 230)
]
E_PARAMS = [
(500, 80),
(2000, 156),
(3130, 190),
(4150, 220)
]
I_PARAMS = [
(330, 70),
... |
# Test and profile TimeHistogram
#
# Copyright (C) 2010-2012 Huang Xin
#
# See LICENSE.TXT that came with this file.
#import cProfile,pstats
from line_profiler import LineProfiler
import TimeHistogram
def run():
psth = TimeHistogram.PSTHAverage('/home/chrox/dev/plexon_data/c04-stim-timing-8ms-rand-1.plx')
pst... |
from abc import abstractmethod
class SaveEmbeddingService:
@abstractmethod
def saveBodyInformation(self,
filename: str,
embediddingCollection: dict) -> None:
pass
@abstractmethod
def loadInformation(self, filename: str):
pass
|
class Turing (object):
"""docstring for Turing"""
def calc (self,raw):
map = {}
words = raw.split(' ')
for item in words:
if item in map:
map[item] = map[item] + 1
else:
map[item] = 1
return map
def main():
conta_palavras = Turing()
texto = input()
map = conta_palavras.calc(texto)
... |
from django.db import models
# Create your models here.
class Products(models.Model):
product_id=models.AutoField
product_name=models.CharField(max_length=20)
desc=models.CharField(max_length=300)
# category=models.CharField(max_length=50, default="")
# publish_date=models.DateField()
photo=mod... |
#################################################
# DEPENDENCIES
#################################################
# libraries
from __future__ import print_function
import os
from skimage.transform import resize
from skimage.io import imsave
import numpy as np
from keras.models import Model
from keras.layers import I... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import torch
import argparse
import numpy as np
from model import STDGN, STDGN_woa
from graph_evolution import Evolution, print_genetation
from trainer import trainer
import time
from tester import test
parser = argparse.ArgumentParser(description='PyTorch Time series fore... |
#========================================================================
# Class Pipeline
# The front face of the program, which will manage other operating
# classes.
#========================================================================
from cache import Cache
from insf import IF
from prealu import PreAlu
from po... |
# Exploring the relationship between gender and policing!!
# Does the gender of a driver have an impact on police behavior during a traffic stop? In this chapter, you will explore that question while practicing filtering, grouping, method chaining, Boolean math, string methods, and more!
# Examining traffic violatio... |
#! /usr/bin/env python
##########################################################################################
# mass_PD_ForceLimited.py
#
# Script to a simulate a force-limited PD position control of a mass system with an ode solver
#
# NOTE: Plotting is set up for output, not viewing on screen.
# So, it wi... |
#!/usr/bin/env python
from helpers import scouter
from robot_knowledge_base.msg import StringArray
import rospy
import numpy
from rospy.numpy_msg import numpy_msg
import mongodb_interface
class BackRobotSide:
"""
This python node is the entry point to set the basics knowledge of the robot. It uses the @Scouter to ... |
import sys
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import Qt
class MenuBar(QtGui.QMainWindow):
def __init__(self):
super(MenuBar, self).__init__()
self.initUI()
def initUI(self):
self.setGeometry(50,50,500,300)
self.setWindowTitle("PYQT tut")
self.setWindowIcon(QtGui.QIcon('pylo... |
#025: Genome Assembly as Shortest Superstring
#http://rosalind.info/problems/long/
#Given: At most 50 DNA strings whose length does not exceed 1 kbp in FASTA format (which represent reads deriving from the same strand of a single linear chromosome).
titles = ['>Rosalind_56', '>Rosalind_57', '>Rosalind_58', '>Rosalind... |
from dataclasses import dataclass
import time
import re
import dns.resolver
from checkdmarc import *
from dns.resolver import NXDOMAIN, NoAnswer
from dns_scanner.email_scanners import DKIMScanner, DMARCScanner
logger = logging.getLogger(__name__)
TIMEOUT = int(os.getenv("SCAN_TIMEOUT", "80"))
@dataclass
class DNS... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 26 22:15:40 2018
train_on_handcrafted features on frame level
@author: ddeng
"""
import pandas as pd
import numpy as np
import os
import glob
from sklearn import preprocessing
from sklearn.svm import SVC, LinearSVC
import time
from sklearn.metrics im... |
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from tracks.api.serializers import track_serializer,course_serializer,lesson_serializer,exam_serializer
from ..models import track,course,lesson,exam,exam_result
from rest_framework import generics
fr... |
from time import sleep
from picamera import PiCamera
import datetime
camera = PiCamera()
# camera.start_preview()
# Camera Configuration
camera.framerate = 30
camera.resolution = (640, 480)
fps = 1 / camera.framerate
# Camera warm-up time
sleep(2)
while True:
sleep(fps)
now = datetime.datetime.now()
came... |
from django.contrib import admin
from django.urls import path
from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'InterChangeMoney/$', views.InterChangeMoneyUrls.as_view()),
url(r'InterChangeMoney/Balance/$', views.MoneyOperations.as_view()),
url(r'InterChangeMoney/Operation... |
from flask_restful import Resource
from models.users import FoodieUser
from api.utils import validates_post_schema
from api.schemas.admins import EditUserSchema
from api.validators import email_not_existing
from marshmallow import ValidationError
from utils.custom_logging import MyLogger
import models
class Users(Res... |
# OpenFace provider
# If vgg: provides with the VGG Net output; Specify on which layer is needed
# If image: provides with the image paths
# the return is a dictionary
import os.path as path
import glob
import numpy as np
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input as vg... |
#!/usr/bin/env python2.4
# -*- coding: UTF-8 -*-
import os,sys,Gnuplot,time
from sys_info import SysInfo
from file_managers import frames
def wait(for_this=0.01): time.sleep(for_this)
def energies(nom_fitxer, n):
for frame_info, posicions in frames(nom_fitxer, n):
enes = []
for punt1 in (posicion... |
import torch
from torch import nn
from collections import OrderedDict
import math
from torchvision.ops.misc import FrozenBatchNorm2d
class BasicBlock(nn.Module):
def __init__(self, inplanes, planes, norm_layer):
super(BasicBlock, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes[0], kernel_... |
from functionsClient import *
s = createSocket(50000,"10.12.18.139")
sendData(s,"Hello Server!")
receiveFile(s)
disconnect(s)
|
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.implicitly_wait(10)
driver.get("http://www.baidu.com")
s_w =driver.current_window_handle
driver.find_element_by_link_text('登录').click()
driver.find_element_by_link_text('立即注册').click()
all_h = driver.window_handles
for handle in all_h:
... |
from types import SimpleNamespace
import pytest
from carts.carts_api.model_utils import (
USER_ROLES,
JOB_CODES_TO_ROLES,
get_role_from_job_codes,
)
@pytest.mark.parametrize(
"roles,role_code_map,db_role_map,db_username_map,entries,expected",
(
(USER_ROLES, JOB_CODES_TO_ROLES, [], [], [], ... |
from core.api.serializers import UserSerializer
from core.models import User
from rest_framework.generics import CreateAPIView
from rest_framework import permissions
class UserList(CreateAPIView):
"""
List all users, or create a new user.
"""
model = User
permission_classes = [
permissions... |
# Generated by Django 2.1.2 on 2018-12-09 15:58
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Config',
fields=[
('id', models.AutoField(a... |
neurons = []
val = float(raw_input())
while val != 0:
neurons.append(val)
val = float(raw_input())
#debug printing
#print(neurons)
numneurons = len(neurons)
minlength = min(neurons)
maxlength = max(neurons)
avglength = float(sum(neurons)) / numneurons
tot = 0.0
for n in neurons:
tot = tot + (n-avglength)**2
stdd... |
from odoo import api, fields, models, tools, SUPERUSER_ID, _
from odoo.exceptions import UserError, ValidationError
from datetime import datetime
class ProjectBoq(models.Model):
_name = 'project.boq'
_inherit = ['mail.thread', 'mail.activity.mixin']
_description = "Project Bill of Quantity"
name = fi... |
import lucene
from org.apache.lucene.queryparser.classic import QueryParser
from org.apache.lucene.search import BooleanClause, BooleanQuery
from org.apache.lucene.queryparser.classic import MultiFieldQueryParser, QueryParserBase
def bq_builder(title, description, analyzer, desc_fields="all"):
# field A
... |
from django.shortcuts import (redirect, render, )
from django.http import (HttpResponse, )
#User and login imports
from django.contrib.auth import authenticate, login, logout
#created module
from .extra import (
create_user_,
update_history,
)
def home_view(request): #
update_history(request... |
"""
Complete the solution so that it strips all text that follows any of a
set of comment markers passed in. Any whitespace at the end of the line should also be stripped out.
Example:
Given an input string of:
apples, pears # and bananas
grapes
bananas !apples
"""
def solution1(string,markers):
stringlist = l... |
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import numpy as np
# 1. 데이터
x = np.array(range(1,101))
y = np.array(range(101,201))
# x_train = x[:60]
# x_val = x[60:80]
# x_test = x[80:]
# # list slicing
# y_train = y[:60]
# y_val = y[60:80]
# y_test = y[80:]
# # list slicin... |
from django.http import HttpResponse
# Create your views here.
def myIndex(request):
my_name = request.POST.get('name',"BINBINSISTER")
return HttpResponse("Hello"+my_name)
|
test = {
'name': 'Question 10',
'points': 1,
'suites': [
{
'cases': [
{
'code': r"""
>>> picky_piggy_strategy(0, 4, cutoff=7, num_rolls=5)
0
""",
'hidden': False,
'locked': False,
'multiline': False
},
{
... |
from Test.die import Die
import matplotlib.pyplot as plt
import pygal
die1=Die(8)
die2=Die(8)
results=[]
for roll_num in range(1000):
result=die1.roll()+die2.roll()
results.append(result)
plt.show()
frequencies=[]
max_result=die1.num_sides+die2.num_sides
for value in range(2,max_result+1):
frequency=res... |
#!/usr/bin/python3
# module_check: supported
# Copyright 2021 VMware, Inc. All rights reserved. VMware Confidential
# SPDX-License-Identifier: Apache License 2.0
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... |
import argparse
import sys
from chainer.dataset import concat_examples
sys.path = sys.path[1:]
sys.path.append("/home/machen/face_expr")
from time_axis_rcnn.extensions.special_converter import concat_examples_not_string
from time_axis_rcnn.model.time_segment_network.faster_head_module import FasterHeadModule
from ti... |
from os import walk
from os import listdir
from os.path import isfile
from os.path import join
from os.path import expanduser
import re
#MODIF_PTRN = '(?P<modif>(abstract )?(final )?)?'
#MODIF_PTRN = '((?P<modif>(abstract)|(abstract final)|(final))( )?)?'
#PARMS_PTRN = ' ?(?P<parms>(?!:)(\(([\w:,\[\] <=>\*]*)?\))?(\(... |
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from .models import Post
from django import forms
from .forms import PostForm
from rest_framework.views import APIView
from rest_framework.response import Response
from django.contrib.auth.decorators import login_requi... |
from django.db import models
from django.core.validators import RegexValidator
from phonenumber_field.modelfields import PhoneNumberField
class Contact(models.Model):
"""Model definition for Contact."""
# informations
first_name = models.CharField("First name", max_length=50, null=False)
last_name = ... |
"""
Copyright 2009 Luca Trevisan
Additional contributors: Radu Grigore
LaTeX2WP version 0.6.2
This file is part of LaTeX2WP, a program that converts
a LaTeX document into a format that is ready to be
copied and pasted into WordPress.
You are free to redistribute and/or modify LaTeX2WP under the
terms of the... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.