text stringlengths 38 1.54M |
|---|
# 1 - Import library
import pygame
from pygame.locals import *
# 2 - Initialize the game
pygame.init()
width, height = 640, 480
screen=pygame.display.set_mode((width, height))
# 3 - Load images
player = pygame.image.load("resources/images/dude.png")
# 4 - keep looping through
while 1:
# 5 - clear the screen befo... |
from flask import Flask, render_template, request
import numpy as np
from parsingText import parsing_web_data
from sklearn.externals import joblib
from os.path import join,dirname,realpath
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/postchuli',... |
#!/usr/bin/env python
# coding=utf-8
try:
import unittest.mock as mock
except ImportError:
import mock
import unittest
import nessusapi.session
xml_login_success = ('<?xml version="1.0"?> <reply>'
"<status>OK</status>"
"<contents><token>abcdef01</token>"
... |
import json
import os
from dotenv import load_dotenv
from config import (
WILEY,
WILEY_TOKEN_KEY,
WILEY_PUBLICATION_URL_KEY,
ELSEVIER,
ELSEVIER_API_TOKEN_KEY,
ELSEVIER_INST_TOKEN_KEY,
ELSEVIER_PUBLICATION_URL_KEY,
)
from config.path_config import CONFIG_PATH
def get_harvester_config(conf... |
#!/usr/bin/env python
# coding: utf-8
# # 🎥 Intro Of This Notebook:
# I will go through in this notebook the whole process of creating a machine learning model on the famous Titanic dataset, which is used by many people all over the world.
# In[ ]:
get_ipython().run_cell_magic(u'html', u'', u"<style>\n@impo... |
import tweepy
# OAuth2 authentication
auth = tweepy.AppAuthHandler("fwBcUpUv0O193Pe5O33qBlBLq",
"XRDPn08Zd0ARDRIkqjn7x9T2A8lSMmXF31khySWVRRLF8141T3")
api = tweepy.API(auth)
myStreamListener = MyStreamListener()
myStream = tweepy.Stream(auth = api.auth, listener=myStreamListener)
myStream.filter(track=['python']... |
"""
Нахождение трехмерной точки по 2 углам с системе отсчета GEO
"""
import numpy as np
from coordinate_system.earth_models import EarthEllipsoidModel
def get_cartesian_geo_from_geo_angles(
latitude, # широта
longitude, # долгота
model: EarthEllipsoidModel, # модель Земли
) -> np.ndarray:
... |
from django.contrib import admin
from django.urls import path
from amazon.books.views import authors_list
from amazon.books.views import (authors_detail, authors_new, authors_edit, authors_delete,
genres_new, genres_edit, genres_list, genres_delete, genres_detail,
... |
#############################################
# Condicionales
#
# lista_electrica = ["Lavado", "Arredondo", "Basilio", "Sequeira", "Carrasco", "Tejada"]
# nombre_a_buscar = "dsaewqdsaewq"
# try:
# print("Buscando...")
# indice = lista_electrica.index(nombre_a_buscar)
# print(f"El elemento {nombre_a_buscar... |
import SpliceURL
import unittest
class SpliceTest(unittest.TestCase):
def test_Splice(self):
assert "http://saintic.com:1000" in SpliceURL.Splice(netloc='saintic.com', port=1000).do()
def test_Split(self):
url='https://api.saintic.com/user?id=admin&time=true'
s = SpliceURL.Split(url).... |
from sys import argv
seq = open(argv[1]).read().rstrip().split()[1:]
seq = ''.join(list(map(lambda x: x.rstrip(), seq)))
print (seq)
cache = {1:seq[0]}
def kmp(seq):
cadena = [0]
for i in range(1, len(seq)):
if cadena[i-1] == 0:
if seq[i] != seq[0]:
j = 0
cadena.append(0)
continue
cadena.append(1)... |
#WAP to accept number of rows from user and print a diamond
# *
# ***
# *****
# ***
# *
def print_diamond(rows):
for i in range(-rows+1,rows):
for k in range(abs(i)):
print " ",
for j in range((rows*2-1)-abs(i*2)):
print "*",
print
def main():
... |
class StreamProcessor():
def __init__(self):
self.garbage = False
self.total_score = 0
self.group_counter = 0
self.garbage_counter = 0
def record(self, char):
if c in '{}' and not self.garbage:
self.group_processor(char)
else:
self.garbag... |
def min_max(L, x):
tmp = map((lambda i: abs(i - L/2)), x)
min_time = min(tmp)
min_time = L / 2 - min_time
max_time = max(tmp)
max_time = L / 2 + max_time
return (min_time, max_time)
if __name__ == '__main__':
assert(min_max(10, [2, 6, 7]) == (4, 8))
|
# -*- coding: utf-8 -*-
from datetime import datetime
from enum import unique
from typing import Optional
from flask import render_template, url_for
from flask_babel import gettext as _
from eduid_common.api.decorators import deprecated
from eduid_common.api.helpers import send_mail
from eduid_common.api.messages i... |
from distutils.core import setup
setup(
name='fhe',
version='0.1dev',
packages=['fhe',],
license='Apache License 2.0',
long_description=open('README.md').read(),
)
|
class Solution:
def longestValidParentheses(self, s: str) -> int:
left, right, idx = [], [], []
for i in range(len(s)):
if s[i] == '(':
left.append('(')
elif s[i] == ')':
if left:
left.pop()
else:
... |
from math import sqrt,floor;
def findSqrt(num) :
a=sqrt(num);
if a-floor(a)== 0 :
print(num," is a perfect square root");
list1=[]; //displays after all elements are input
for i in range(0,10) :
list1.append(int(input("Enter value : ")));
for i in range(0,10) :
findSqrt(list1[i]);
for i in range... |
import logging
# get to contracts without counter
def get_to_contracts_without_counter(root_models):
try:
root_contracts = []
for root_model in root_models:
if (root_model.aggreement_counter == ''):
root_contracts.append(root_model)
clean_data = []
fo... |
s1=raw_input("enter a string to check whether it is pallindrome or not ")
if s1==s1[::-1]:
print " the string ",s1,"is a pallindrome"
else :
print "the string ",s1,"is not a pallindrome"
|
import pandas as pd
from client import pcmci_and_walk
df = pd.read_csv('test_df.csv', index_col=0)
print("%d Obs x %d Vars" % (df.shape))
problem_node = 'os_021' # random.choice(df.columns)
print('Problem node:', problem_node)
result = pcmci_and_walk(df, problem_node,
p_threshold=0.05,
... |
from distutils.core import setup
setup(
name='chimera_t80dome',
version='0.0.1',
packages=['chimera_t80dome', 'chimera_t80dome.instruments'],
scripts=[],
url='http://github.com/astroufsc/chimera-t80dome',
license='GPL v2',
author='Tiago Ribeiro and Salvador Agati',
author_email='tribeir... |
import sys
import os
from math import pi
import cairo
import clutter
import cluttercairo
import inkface
############################################################################
# @class Face
# Encapsulation of an SVG file
# The elements of the SVG file are accessible as attributes of Face object
##########... |
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the... |
import socket
import sys
import thread
from Calculadora import *
def operar(sc, addr):
data1,data2,opcionMenu = sc.recv(1024).split()
print "recibido", data1, data2, opcionMenu
c = Calculadora(data1, data2, opcionMenu)
enviar = c.suma()
sc.send(enviar)
if __name__ == "__main__":
s = ... |
import boto3
import os
import openpyxl
"""
keywords is target label from the previous label recognition by myself, and it uses to filter the labels from API.
"""
keywords = ['wildlife','animal','mammal','deer','caribou','bear','polar bear','antelope','horse','goat','sheep','Canine',
'Arctic Fox','Mountain Goat','Bison'... |
import sys
import os
import re
import time
import logging
import string
from NullHandler import NullHandler
import help
from vlogTemplate import vlogTemplate
from incTemplate import incTemplate
"""
Reads in a Graphviz .dot file and generates a Verilog state machine based
on some simple rules.
1) Only one state trans... |
import discord
import asyncio
import sqlite3
from discord.ext import commands
class RoleLowerConverter(commands.RoleConverter):
async def convert(self, ctx, argument):
try:
result = await super().convert(ctx, argument)
except commands.BadArgument:
roles = [role for role in ... |
# -*- coding: utf-8 -*-
# Django
from django.contrib.auth.views import LogoutView
class LogoutFormView(LogoutView):
next_page = 'login_view'
#from django.contrib.auth import logout
#class LogoutRedirect(RedirectView): No cierra la sesion solo hace un redir
#pattern_name = 'login'}
#def dispatch(sel... |
# -*- coding: utf-8 -*-
from ClassesDB import ClassesDB as DB
__author__ = "Hua777"
__copyright__ = "Copyright 2018, Hua777"
__version__ = "2.0"
__email__ = "liao.700529@gmail.com"
class Schedule(object):
def __init__(self, agent):
self.Agent = agent
self.SectionKey = ['A', '1', '2', '3', '4', 'B'... |
# -*- coding: utf-8 -*-
# Resource object code
#
# Created: Wed Aug 15 16:24:03 2018
# by: The Resource Compiler for PySide2 (Qt v5.6.2)
#
# WARNING! All changes made in this file will be lost!
from PySide2 import QtCore
qt_resource_data = b"\
\x00\x00\x00\xfc\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\... |
# We will have a look at the practical use cases and implementation of try, except, raise and finally
we will create a variable to store a file data using open()
Iteration 1
try: # let's use try block for a 1 line of code where we know this will throw an error
file = open("orders.text")
except:
print(" Panic A... |
import socket, ssl, DB_User, DB_Scoreboard, re, AuthManager
import System_log, Server_NS, hashlib, sys, json
from base64 import b64decode,b64encode
from Server_NS import ServerNS
from threading import Thread
from datetime import datetime
from Crypto.Cipher import AES
import signal
import sys
#HOST = "127.0.0.1" # St... |
t=input()
for _ in xrange(t):
n=input()
if n==0:y="INSOMNIA"
else:
d={}
for i in xrange(10):d[i]=0
tr=True
a=n
while tr:
r=a
while r!=0:
d[r%10]+=1
r/=10
for i in xrange(10):
if d[i]==0:tr=True;break
else:tr=False
a+=n
y=a-n
print("Case #{}: {}".format(_+1,y))
|
def calcularDni():
diccionario = {
0: "T",
1: "R",
2: "W",
3: "A",
4: "G",
5: "M",
6: "I",
7: "F",
8: "P",
9: "D",
10: "X",
11: "B",
12: "N",
13: "J",
14: "Z",
15: "S",
16: "Q",
... |
# Author: Kai Tanaka
import numpy
n,m = map(int,input().split())
n_arr = numpy.array([input().split() for i in range(n)],int)
print(n_arr.transpose())
print(n_arr.flatten()) |
""" MNodule for doing IO on files used by hycom """
import numpy
import struct
import sys
import logging
import re
# Set up logger
_loglevel=logging.INFO
logger = logging.getLogger(__name__)
logger.setLevel(_loglevel)
formatter = logging.Formatter("%(asctime)s - %(name)10s - %(levelname)7s: %(message)s")
ch = logging... |
from django.conf.urls import url
from . import views
app_name='blog'
urlpatterns = [
url(r'^$', views.portfolio, name='portfolio'),
url(r'^list/$', views.list, name='list'),
url(r'^about/$', views.about, name="about"),
url(r'^announcements/$', views.announcements, name="announcements"),
url(r'^cal... |
import gym
import numpy as np
from collections import namedtuple
import collections
import time
import math
import torch
import torch.nn as nn
import torch.optim as optim
from torch.nn import Parameter, init
from torch.nn import functional as F
from tensorboardX import SummaryWriter
import atari_wrappers
from agent ... |
# -*- coding: utf-8 -*-
"""
Simplified version of the True Retention by Card Maturity Add-on
(https://ankiweb.net/shared/info/923360400)
This Add-on is accessible at:
https://ankiweb.net/shared/info/1779060522
License: GNU AGPLv3 or later <https://www.gnu.org/licenses/agpl.html>
"""
from __future__ import unicode_l... |
from django.urls import path
from django.contrib import admin
from . import views
app_name = 'accounts'
urlpatterns = [
path(r'sign_in/', views.sign_in, name="sign_in"),
path(r'sign_up/', views.sign_up, name="sign_up"),
path(r'sign_out/', views.sign_out, name='sign_out'),
]
|
#!/bin/env pywstart
import win32com.client
from socket import *
import sys
msdn = win32com.client.Dispatch('DExplore.AppObj.9.0')
msdn.SetCollection('ms-help://MS.VSCC.v90/', '')
sockListening = socket(AF_INET, SOCK_STREAM)
sockListening.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
sockListening.bind(('', 3836))
sockListen... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
"""
Faça um programa que calcule a soma de todos os números primos abaixo de dois mil.
"""
limite = 2000
lista_primos = [2]
for numero in range(3, limite +1):
for i in lista_primos:
if numero % i == 0:
break
else:
lista_primos.append(numero)
print(lista_primos)
pr... |
import uiScriptLocale
window = {
"name" : "OfflineShopChangeTime",
"style" : ("movable", "float", ),
"x" : 0,
"y" : 0,
"width" : 466,
"height" : 174,
"children" :
(
# Board
{
"name" : "Board",
"type" : "board_with_titlebar",
"style" : ("attach", ),
"x" : 0,
"y" : 0,
"w... |
import sys
import os
import shutil
import subprocess
binDir = "bin"
analysisDir = "analysis"
analysisDataDir = "analysisData"
graphDataDir = os.path.join(analysisDataDir, "forGraph")
graphDir = "graph"
dataGen = [
"sinpow2",
"cosnearpi",
"atanpow2"]
graphScript = [
"sinpow2.py",
"cosnearpi.py",
... |
# -*- coding: utf-8 -*-
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
#读取图像
img = cv.imread('lena.png', 0)
#傅里叶变换
f = np.fft.fft2(img)
fshift = np.fft.fftshift(f)
#设置高通滤波器
rows, cols = img.shape
crow,ccol = int(rows/2), int(cols/2)
fshift[crow-30:crow+30, ccol-30:ccol+30] = ... |
#!/usr/bin/python3.8
import socket
import subprocess
import sys
servidor = sys.argv[1]
puerto = 55554
buffer = 1024
s = socket.socket()
s.connect((servidor, puerto))
mensaje = s.recv(buffer).decode()
print("Servidor: ", mensaje)
while True:
comando = s.recv(buffer).decode()
if comando.lower() == 'salir':
break... |
from django.shortcuts import render
# Create your views here.
def index(request):
if request.method == 'POST':
a=int(request.POST['num1'])
b=int(request.POST['num2'])
c=a+b
print(c)
return render(request,'index.html')
|
'''
This program runs the first lab.
These three lines, between triple quotes, are "comments".
Python ignores them; they're just there to help you, the programmer.
'''
# BTW, lines that begin with a hash-sign are also ignored
name = input('Whats your name? ')
print ("Hello, " + name + ", It is very nice to meet you!... |
"""
This file contains different forcing terms of
2D Navier-Stokes equation.
"""
import numpy as np
class Force(object):
LEFT = 'left'
RIGHT = 'right'
UP = 'up'
DOWN = 'down'
def __init__(self, grid, u, w, p):
self.grid = grid
self.u = u
self.w = w
... |
# Solve the Reverse Complement Problem
with open(r'C:\Users\Asus\Downloads\Input.txt', 'r') as fp: #открывает файл в режими "read only"
Text = fp.readline() # записывает содержимое строкой в переменную
Pattern = [] # создание пустого листа
j = '' # создание пустой строки... |
from typing import Optional, List
from datetime import datetime, date
from pydantic import BaseModel
from sqlalchemy import Column, Integer, BigInteger, String, DateTime
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session
from config.db import Base
from libs.utils import makeJSONGetResponse, ... |
# pseudo kod za map.
# def map(func, seq):
# # vraca `Map` objekat gde
# # funkcija func primenjena na svaki element
# return Map(
# func(x)
# for x in seq
# )
niska = input("Unesi zeljenu nisku: ")
print(map(lambda c: c.upper(), niska)) # map object
print(list(map(lambda c: c.upper(), niska))... |
ins = list(map(int, input().split(',')))
i = [5]
def val(*l):
d = 10
for a in l:
d *= 10
yield ins[a] if (ins[ip]//d)%10 == 0 else a
ip = 0
while ip < len(ins):
op = ins[ip] % 100
a, b, c = [ins[i] if i < len(ins) else 0 for i in range(ip+1, ip+4)]
if op == 1:
a, b = val(a... |
"""
Copyright 2018 Globo.com
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 in writ... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'setting_page.ui'
#
# Created by: PyQt5 UI code generator 5.10.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectN... |
class GameConfig():
version = 'pm.1.0'
# MAX 28 enemies = 4 rows
# (type, num)
enemies = [
[(1, 1)],
[(1, 2)],
[(1, 3)],
[(1, 4)],
[(1, 5)],
[(1, 5), (2, 1)],
[(1, 5), (2, 2)],
[(1, 5), (2, 3)],
[(1, 5), (2, 4)],
[(1, 5),... |
import asyncio
from logging import getLogger, basicConfig, INFO
from os import getenv
from aiohttp import web
import aiohttp_cors
from aiohttp_swagger import setup_swagger
if getenv('MODEL','redis') == 'dict':
from .views import (
IndexView,
TodoView,
TagIndexView,
TagView,
T... |
import numpy as np
from tqdm import tqdm
class GameOfLife:
# TODO: check iniFrame
def __init__(self, initial_config: np.ndarray, size: tuple, n_frames: int, position: tuple) -> None:
self.initial_config = initial_config
self.size = size
self.n_frames = n_frames
self.po... |
"""
Module providing ML anonymization.
This module contains methods for anonymizing ML model training data, so that when
a model is retrained on the anonymized data, the model itself will also be considered
anonymous. This may help exempt the model from different obligations and restrictions
set out in data protection... |
from django.shortcuts import render, redirect
import random
# Create your views here.
def index(request):
if "amount" not in request.session:
request.session["amount"] = 0
if "activities" not in request.session:
request.session["activities"] = []
return render(request, "index.html")
def pr... |
import re
from fantasyaux import *
def alphanumeric(word):
"""cleans everything except letters and numbers and commas and single quotes."""
return re.sub(r'[^a-zA-Z0-9,\']', '', word)
def alphanumeric_space(word):
"""replaces everything except letters and numbers and commas and single quotes with space.""... |
#!/usr/bin/env python
import ROOT
import imp
import json
from array import array
wsptools = imp.load_source('wsptools', 'workspaceTools.py')
def GetFromTFile(str):
f = ROOT.TFile(str.split(':')[0])
obj = f.Get(str.split(':')[1]).Clone()
f.Close()
return obj
# Boilerplate
ROOT.PyConfig.IgnoreCommandLi... |
import json
from google.appengine.api import namespace_manager
import requests
from core.models.response import ResponseOutput
from core.handlers.base import ProtectedRequestHandler
from core.utils.zendesk import get_zendesk_stats
from core.utils.common import display_error
from models.ext import ZendeskDailyStats
... |
n = int(input()) #개수를 입력받아 n에 정수로 저장
a = input().split() #공백을 기준으로 잘라 a에 순서대로 저장
for i in range(n) : #0부터 n-1까지...
a[i] = int(a[i]) #a에 순서대로 저장되어있는 각 값을 정수로 변환해 다시 저장
min=a[0]
for i in range(n):
if a[i]<min:
min=a[i]
print(min) |
from marshmallow_sqlalchemy import ModelConversionError, ModelSchema
from sqlalchemy import event
from sqlalchemy.orm import mapper
class CustomModelSchema(ModelSchema):
''' Class to help link Model and Schema '''
def __init_subclass__(cls):
cls.Meta.model.__marshmallow__ = cls
def setup_serializer(b... |
from ke_logic.terminology_extraction import TerminologyExtraction
from ke_logic.support import Support
dict_corpus_terms = {}
te = TerminologyExtraction()
support = Support()
#raw_corpusA = support.import_corpus('CCD_v7_esp', id=True, key=0, content=2)
raw_corpusG = support.import_general_corpus()
# corpus_ccd = te.... |
import math
def main():
radius = eval(input(' enter a radius number.'))
pi = 3.14
area = pi * radius ** 2
for i in range(5):
radius= float(input('enter a radus number'))
area = pi * radius ** 2
print('The area of the circle ')
main() |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2017-04-10 19:17
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('tasks', '0032_auto_20170410_1909'),
]
operations = [
migrations.RemoveField(
... |
from server.static.data import GRAPH
from django.http import HttpResponse, HttpResponseNotFound
from server.logic.server_util import into_json
from server.logic.routing import config as routing_config
from server.logic.routing.routing import generate_rod, close_rod
from server.logic.routing.compress import from_string
... |
from socket import gethostname
import numpy as np
import elegant_matrix
import h5_storage
import lasing
import config
import myplotstyle as ms
elegant_matrix.set_tmp_dir('~/tmp_elegant/')
ms.closeall()
hostname = gethostname()
if hostname == 'desktop':
data_dir2 = '/storage/data_2021-05-19/'
elif hostname == 'p... |
import numpy as np
import matplotlib.pyplot as plt
from scipy import sparse
#from examples_binary_grid_crf import make_dataset_big_checker
from latent_crf import LatentFixedGraphCRF
#from structured_perceptron import LatentStructuredPerceptron
from latent_structured_svm import StupidLatentSVM
from toy_datsets import... |
import os
def getCurrentPath():
currentPath = os.path.dirname(os.path.realpath('__file__'))
return currentPath
def getHaarcascadePath():
path = os.path.dirname(os.path.realpath('__file__'))
cascadePath = path + '/haarcascade_frontalface_default.xml'
return cascadePath |
try:
from sklearn import preprocessing, metrics
except (ImportError, ModuleNotFoundError):
raise ImportError('scikit-learn is required for this module.')
import xarray as xr
import numpy as np
from . import utils
from collections import OrderedDict
__all__ = ['Classifier', 'class_mean']
def class_mean(ds, ... |
# coding: utf-8
# In[1]:
from imgaug import augmenters as iaa
# In[2]:
from scipy import ndimage, misc
#from matplotlib import pyplot
def read_jpg(image_path):
#print(image_path)
img = ndimage.imread(image_path, mode="RGB")
return img
# In[3]:
import imgaug as ia
import... |
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
import nltk
from nltk.stem.snowball import EnglishStemmer
from nltk.corpus import stopwords
class DataPrepocesser2():
def __init__(self):
stop = stopwords.words('english')
self.tfidf_embedder = TfidfVectorizer(min_df=5, ma... |
#! /usr/bin/env python
import sys
tags = {}
def addUp(fields, expected):
time = 0
cycles = 0
for (op, f) in fields:
try:
if op == "+":
time += float(tags[f][0])
cycles += int(tags[f][1])
if op == "-":
time -= float(tags[f][0])
cycles -= int(tags[f][1])
except KeyError, e:
print >>... |
import random as r
r.random()
r.randint(1,10)
r.randrange(1,15,2)
r.choice("internshala")
numbers=[12,23,34,45,56]
r.shuffle(numbrs)
|
'''
This program takes an input text from the user and finds out the difficulty level of the given text.
It judges the readability of the given text.
This grading system is upto level 16+.
'''
text = input("Enter Text: ") #get input from user
l = len(text)
letters = 0
words = 0
sentences = 0
for i in range(l):
#ca... |
from django.conf.urls import *
from photo_gallery.photo_items.models import Item, Photo
from django.views.generic import *
urlpatterns = [
url(r'^$',
ListView.as_view(model=Item, context_object_name='item_list', template_name='index.html'),
name='index'
),
url(r'^items/$',
ListView... |
# Imports
from decimal import Decimal
from django.utils.safestring import mark_safe
from django.template import Context, loader, Template, TemplateDoesNotExist
# Functions
def get_currency_display(amount, unit="USD"):
"""Display a currency amount in human friendly format.
:param amount: The amount to be di... |
# -*- coding: UTF-8 -*-
import os
PORT = 5001
DEBUG = True
CONTAINER_NAME = "vatic"
#Admin info
ADMIN_NAME = "Max"
ADMIN_ID = "max.hsu@ironyun.com"
K_FRAME = 300
OFFSET = 21
#VATIC_ADDRESS = "http://172.16.22.51:8887"
EXT_ADDR = os.environ.get('EXTERNAL_ADDRESS')
if EXT_ADDR == None:
EXT_ADDR = "172.16.22.51"
V... |
from socket import socket, SOCK_DGRAM, SOCK_STREAM, AF_INET, SO_REUSEADDR, SOL_SOCKET, timeout
from threading import Thread
isConnected = False
def receiveData(context):
while isConnected:
try:
data = context.recvfrom(2048)
data = data[0]
if not data: break
... |
from django.urls import path, include, re_path
from . import views
urlpatterns = [
re_path(r'^index[/]{0,1}$', views.index, name='index'),
path('', views.index, name='index'),
re_path(r'^index/[se]/[a-z0-9]{1,10}$', views.index, name='index'),
re_path(r'^den/[a-zA-Z0-9]{2,10}$', views.den, name='den'),... |
from django.contrib.auth.decorators import login_required
from myapp.models import Project
def toolbar_context_processor(request):
if request.user.is_authenticated():
projects = Project.objects.filter(user=request.user)[:3]
else:
projects = None
return {'projects': projects}
|
# -*- coding: utf-8 -*-
import os
def getTargetPath():
isPathRight = True
while(isPathRight):
targetPath = raw_input('input target path (/) : ')
if os.path.exists(targetPath) and os.path.isdir(targetPath):
isPathRight = False
else:
print('wrong target path !')
... |
import sympy as sp
import numpy as np
import math
NN = 5
x = [0, math.pi / 6, math.pi / 4, math.pi / 3]
n = len(x)
X = sp.symbols('x', Float=True)
L = 0
def f(element):
return math.tan(element)
def w(index):
ww = 1
for g in range(n):
if g != index:
ww *= X - x[g]
return ww
y =... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import pygame
from costanti.images_names import *
from costanti.game_v2_pygame_costanti import *
from costanti.color import WHITE, BLACK
def load_texture(img_file, size):
"""
Carica l'immagine dal file e scalala a dimensioni size
:param img_file: fi... |
from os.path import *
from Functions import *
from Prolog.PrologRule import *
from Prolog.PrologRule import PrologRule
class PrologRuleData:
def __init__(self):
self.rules = []
def setup_rule(self, rule):
self.rules.append(rule)
def get_rule(self, index):
return self.rules[index]... |
import os
import shutil
import sys
import win32api
def copyFiles(sourceDir, targetDir):
if sourceDir.find(".svn") > 0:
return
for file in os.listdir(sourceDir):
sourceFile = os.path.join(sourceDir, file)
targetFile = os.path.join(targetDir, file)
if os.path.i... |
from linked_list import node
class record():
def __init__(self):
self.array = []
def insert(self,course):
self.array.append(node(course))
def search (self, CourseteacherName):
for i in range(len(self.array)) :
if self.array[i].Name +' ' + self.array[i].Teacher == Cours... |
## DECORATOR PARA LA VERICACION DE EXISTENCIA DE UN USUARIO
## EN FUNCION Y EN CLASE
"""
from functools import wraps
def verificar_usuario(dni):
def decorator(function):
def inner_decorator(*args, **kwargs):
lista_dni = [45561659, 20116552]
if lista_dni.__contains__(dni):
return function(*args, **kwargs)
... |
#1km KP markers (1:100,000 - <none>)
def FindLabel ( [KP] ):
return ("KP "+ [KP])
#10km KP markers (1:500,000 - 1:115,000)
def FindLabel ( [KP] ):
if int(([KP])) % 10 == 0: return ("KP " + [KP])
#50km KP markers (1:2,000,000 - 1:600,000)
def FindLabel ( [KP] ):
if int(([KP])) % 50 == 0: return ("K... |
# coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
import shu... |
""" 学员信息管理系统 """
info = []
def info_print():
""" 功能展示 """
print('请选择功能:')
print('1、添加学员')
print('2、删除学员')
print('3、修改学员')
print('4、退出系统')
print('-' * 20)
def add_info():
""" 添加学员 """
new_name = input('学员姓名')
new_id = int(input('学员学号'))
new_phone = input('学员电话')
global ... |
import FWCore.ParameterSet.Config as cms
# Simulated hodoscope reconstruction
ecalTBSimHodoscopeReconstructor = cms.EDProducer("EcalTBHodoscopeRecInfoProducer",
fitMethod = cms.int32(0),
rawInfoProducer = cms.string('SimEcalTBHodoscope'),
recInfoCollection = cms.string('EcalTBHodoscopeRecInfo'),
# vdou... |
import numpy as np
from commons import netcdf3
from commons.dataextractor import DataExtractor
def TimeAverager3D(Filelist,weights,varname,mask,accept_neg=True):
'''
Performs a weighted average, working on a list of files.
The weights are usually provided by TimeList.select() method.
varname is a st... |
#!/usr/bin/env python
""" Functions to list and filter league players """
import sys
import logging
import stats.collate
from importer.bbleague.defaults import BASEPATH
LOG = logging.getLogger(__package__)
def order_by_pid(players):
"""order list of players by player.player_id"""
return sorted(players,
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun May 23 14:41:54 2021
@author: Moritz
"""
import pandas as pd
import numpy as np
import pickle
import time
import sys
sys.path.append("/media/Moritz/080FFDFF509A959E/MXLinux/Information_Retrieval_Project/code")
from functions import bm25, similarity_ber... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.