text stringlengths 8 6.05M |
|---|
import json
import grpc
from ..proto import nids_pb2
from ..proto import nids_pb2_grpc
class NIDS(nids_pb2_grpc.NIDSServicer):
def StartNIDS(self, request, context):
return nids_pb2.StartNIDSReply()
def StopNIDS(self, request, context):
return nids_pb2.StopNIDSReply()
def _upload_intel_... |
'''
Obs: Decorator pattern is different of decorator of Python
Example:
'''
from abc import abstractmethod
from abc import ABCMeta
class Componente():
__metaclass__ = ABCMeta
@abstractmethod
def method(self):
pass
class Decorator():
pass
class ConcreteComponent():
pass
class ConcreteDe... |
"""Tests for the face detection model."""
import numpy as np
import pytest
from src.facedetection.face_detection import crop_to_face, reshape_image, convert_to_bytes, face_from_image
def test_crop_to_face():
"""Test the crop_to_face function by checking if the output is the right shape."""
image = np.load("s... |
import os, sys
import argparse
import torch
import random
import numpy as np
from sklearn.svm import SVC
from util import print_time_info, set_random_seed, get_hits, topk
from tqdm import tqdm
def sim_standardization(sim):
mean = np.mean(sim)
std = np.std(sim)
sim = (sim - mean) / std
return sim
def ... |
from matplotlib import pyplot as plt
import pandas as pd
thesaurus_cogent = pd.read_excel(r"C:\Users\vandewsa\Documents\train the Trainer\datasetTTT2.xlsx")
print(thesaurus_cogent)
aantal_dmg = thesaurus_cogent.loc[thesaurus_cogent["Instelling"] == "Designmuseum Gent"].count()[0]
print(aantal_dmg)
aantal_hva = thesa... |
from django.apps import AppConfig
class DebtConfig(AppConfig):
name = "debt"
|
# ----------------------------------------------------------------------------
# Copyright 2014 Nervana Systems 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.o... |
from . import overtime_request
from . import hr_contract
from . import hr_payslip
from . import hr_employee
from . import employees_overtime
from . import employees_attendance |
import subprocess
from bluetooth import *
class AndroidConnector(object):
def __init__(self):
subprocess.Popen(['sh','./reset.sh'])
self.server_socket = None
self.client_socket = None
self.bt_is_connected = False
def ... |
# Generated by Django 2.1.11 on 2020-01-20 09:15
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('procedure', '0007_procedure_polyp_id'),
]
operations = [
migrations.RemoveField(
model_name='procedure',
name='polyp_id',
... |
def sum_all_nums(*args):
total = 0
for num in args:
total += num
return total
print(sum_all_nums(1,2,3,4,5))
print(sum_all_nums(1,2))
|
import matplotlib.pyplot as plt
# in minutes
deltaT= 1 # do not change!
temp= 5 # actual room temperature
desiredTemp=17 # desired room temperature
outsideTemp= -5 # temperature outside of room
# for heater fan
PowerSet=[0+i*60 for i in range(60)]
outsideTemps=[-5+... |
#!/usr/bin/env python
#-*-coding:utf-8-*-
'''
The number, 197, is called a circular prime because
all rotations of the digits: 197, 971, and 719, are themselves prime.
There are thirteen such primes below 100:
2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
How many circular primes are there below one million?
'... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 21 09:21:32 2019
@author: zac
"""
with open("~/Desktop/festivals.csv","r") as file:
for x in file:
print (x) |
from vasp.parser.band_structure import BandStructure
import os
def test_ispin_1():
outcarpath = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'data', 'outcar.1'
)
assert(os.path.exists(outcarpath))
bs = BandStructure(outcar=outcarpath)
assert(bs is not None)
empty... |
n=2
n=int(input("enter your value:"))
if n%2==0:
print(n, "is even no. ")
else:
print(n,"is odd no. ") |
class Bot:
def __init__(self, chip):
self.chips = [chip]
def __getattr__(self, item):
if item == 'high' and len(self.chips) == 2:
return list(map(str, sorted(map(int, self.chips))))[1]
elif item =='low' and len(self.chips) == 2:
return list(map(str, sorted(map(... |
x = """What is the meaning
of your life
little guy?"""
d = '''I have been
written just with
thre single qoutes'''
print x,d
|
"""
This module is expected to produce json data
"""
from django.contrib.auth.decorators import login_required
from django.urls import path, include
from rest_framework.urlpatterns import format_suffix_patterns
from .views import search_post, get_content_quick_view, \
list_all_articles, get_an_article, updat... |
import sys
import os
from flask import Flask, render_template, Response, flash, request, redirect, url_for, send_from_directory, Markup,make_response,jsonify
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
test=None
students=None
student_scores=None
stu_scor_dict={}
stu_per_dict={}
# Score Card ... |
import cv2
img_color = cv2.imread("test.png", cv2.IMREAD_COLOR)
if img_color is None:
print("이미지 파일을 읽을 수 없습니다.")
exit()
cv2.namedWindow('Color')
cv2.imshow('Color', img_color)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
from nltk.corpus import stopwords
from collections import defaultdict
from datetime import datetime, date
import pandas as pd
import numpy as np
from pandas.plotting import register_matplotlib_converters
import re
import matplotlib.pyplot as plt
register_matplotlib_converters()
"""
These are helper methods for the ba... |
import os
import logging
from aws import helper
from aws.helper import DeveloperMode
import boto3
logger = logging.getLogger()
logger.setLevel(logging.INFO)
USER_POOL_ID = os.environ["USER_POOL_ID"]
@DeveloperMode(True)
def lambda_handler(event, context):
email = None
if "queryStringParameters" in event:
... |
import gym
from nes_py.wrappers import JoypadSpace
from Contra.actions import SIMPLE_MOVEMENT, COMPLEX_MOVEMENT, RIGHT_ONLY
def contra_game_render():
env = gym.make('Contra-v0')
env = JoypadSpace(env, SIMPLE_MOVEMENT)
print("actions", env.action_space)
print("observation_space ", env.observation_space.... |
../algorithms/discretization.py |
"""
use a Queue to realize Stack ADT.
only minor changes to the code from example_queue.py
time:
pop: O(n): need to rotate the queue
push: O(1)
top: O(1)
"""
# empty exception
class Empty(Exception):
pass
class ArrayStackUsingQueue:
DEFAULT_CAPACITY = 10
def __init__(self):
self._data = [None]... |
#!/usr/bin/env python3
import argparse
import glob
import os
import numpy as np
'''
#for gnuplot generated files
def getBookPlot(filename,title):
lumi = []
with open(filename) as input_data:
for line in input_data:
print line
'''
#for dat generated files
def getBookPlot(filename,title="",hist=0):
... |
# coding: utf-8
# ## I
# In[1]:
from keras.models import Sequential
from keras.layers import Dense
import numpy
# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)
# In[2]:
dataset = numpy.loadtxt("pima-indians-diabetes.csv", delimiter=",")
# split into input (X) and output (Y) variables
X = d... |
from .connection import Connection
from ..config import Config
from ..util import util
db = Connection(Config())
POSITION_TABLE = 'taxi_position'
def get_row_count():
return db.fetch(
f'SELECT * FROM {POSITION_TABLE}'
)
def create_account(num):
args = []
for i in range(num):
# Simply ... |
import zmq, json
import pandas as pd
from ipyTrenaViz import *
import time, os
class Trena:
def __init__(self, genomeName):
socketContext = zmq.Context();
self.trenaServer = socketContext.socket(zmq.REQ)
self.trenaServer.connect("tcp://trena:%s" % "5547")
self.tv = ipyTrenaViz()
... |
def maiusculas(frase):
maiuscula = ''
for caractere in frase.strip():
if 65 <= ord(caractere) <= 90:
maiuscula += caractere
return maiuscula
# def test_maiusculas0():
# assert maiusculas('Programamos em python 2?') == 'P'
#
#
# def test_maiusculas1():
# assert maiusculas('Progr... |
''' 给定两个大小为 m 和 n 的有序数组 nums1 和 nums2 。
请找出这两个有序数组的中位数。要求算法的时间复杂度为 O(log (m+n)) 。
'''
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
num3 = nums1 + nums2
nu... |
WORKDIR = "/mnt/research/ged/irberlui/biodata/bat"
with open(WORKDIR + "/files", 'r') as f:
RAW_DATA = f.read().splitlines()
PACBIO_RAW = {
'macCal': ['inputs/' + f for f in RAW_DATA if f.startswith("Pacbio/TK163824")],
'desRot': ['inputs/' + f for f in RAW_DATA if f.startswith("Pacbio/TK169403")]
}
ILLUMINA... |
import pytest
import pytest_check as ck
@pytest.mark.p1
@pytest.mark.api
def test_bind_fuel_card_normal(api,data,db):
"""绑定不存在的加油卡"""
request_data = data.get('test_bind_fuel_card_normal')
card_number = request_data.get('json').get('CardInfo').get('cardNumber')
#环境检查
if db.check_card(card_number):
... |
from src.app.domain.exceptions import CantBeAllocated, NotEmpty, NotAssignedSpaceException, EmptyWarehouseReference
from src.app.domain.orderLine import OrderLine
from src.app.domain.space import Space
from src.app.domain.warehouse import Warehouse
from src.app.domain.product import Product
from src.app.service.allocat... |
import tensorflow as tf
from keras.preprocessing import image
import numpy as np
def prepare_image(file):
img_path = ''
img = tf.keras.preprocessing.image.load_img(img_path + file, target_size=(224, 224))
img_array = tf.keras.preprocessing.image.img_to_array(img)
img_array_expanded_dims = np.expand_di... |
from typing import Dict, Any
from configparser import ConfigParser, ExtendedInterpolation
from numpy import random as np_random
import torch
import random
def set_seed(seed):
random.seed(seed)
np_random.seed(seed)
torch.cuda.manual_seed(seed)
torch.manual_seed(seed)
def to_cuda(data):
if isins... |
import codecs
import struct
import re
from datetime import datetime
__author__="brian"
__date__ ="$Feb 6, 2011 1:38:17 AM$"
class MediaLibrary:
"""A class to read (not write) the database used by winamp"""
def __init__(self, db, verbose=False):
print("Reading the winamp database from {}".format(db))
... |
from tIGAr import *
from tIGAr.compatibleSplines import *
from tIGAr.BSplines import *
import math
import ufl
# Suppress warnings about Krylov solver non-convergence:
set_log_level(40)
# Use TSFC representation, due to complicated forms:
parameters["form_compiler"]["representation"] = "tsfc"
import sys
sys.setrecursi... |
class Vehiculo:
def _init_(self,placa,marca,modelo,kilometraje):
self.placa = placa
self.marca = marca
self.modelo = modelo
self.kilometraje = kilometraje
#los cuatro atributos generales
def getPlaca (self):
return self.placa
def getMarca (self):
... |
import tensorflow as tf
# MNIST 데이터를 다운로드한다
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# 변수들을 설정한다
X = tf.placeholder(tf.float32, [None, 784]) # mnist 이미지데이터 형태는 28
Y = tf.placeholder(tf.float32, [None, 10]) # 0-9 숫자분류 => 10 classes
#Logi... |
import math
import IBM1 as ibm1
import aer
import datetime
# Helper function to output likelihood and AER after each
# EM iteration
def print_likelihood(i, lprobs, log_likelihood, aer):
likelihood = math.exp(log_likelihood)
if i == 0:
print('iteration log_likelihood AER time')
time_hm = d... |
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Table, Column, Integer, String, Boolean, MetaData, ForeignKey
# https://coderlessons.com/tutorials/bazy-dannykh/sqlalchemy/sqlalchemy-kratkoe-rukovods... |
from django.test import TestCase
from django.core.urlresolvers import resolve
from core.views import LoginView, LogoutView, RegisterView
from client.views import CabinetView, ProfileListView
class ClientsURLTestCase(TestCase):
def test_loginUrl(self):
root = resolve('/account/login/')
self.asser... |
from .eLABJournalPager import *
from .Experiment import *
from .Experiments import *
from .Group import *
from .Groups import *
from .Project import *
from .Projects import *
from .Sample import *
from .Samples import *
from .SampleType import *
from .SampleTypes import *
from .SampleTypeMeta import *
from .SampleType... |
__author__ = "Vinay Verma"
__copyright__ = "Copyright 2021, Vinay Verma"
__credits__ = ["Vinay Verma"]
__license__ = "MIT"
__version__ = "0.3.0"
__maintainer__ = "Vinay Verma"
__email__ = "vermavinay982@gmail.com"
__module_name__ = "[Stack Video]"
import os
import cv2
import time
import numpy... |
#! /usr/bin/env python3
import json
import logging
import os
import cloudpickle
import numpy as np
import pandas as pd
from scipy import optimize
# from skopt import BayesSearchCV, space
from util.serialization import load_class
from util.shared import parse_args
RESULTS_DF = pd.DataFrame(columns=["score", "params"... |
"""This file implements functions to return a graph
on which the modularity-maximizing communities are indicated
by using the Louvain algorithm.
@source https://stackoverflow.com/questions/29897243/graph-modularity-in-python-networkx"""
import community
import matplotlib.pyplot as plt
import networkx as nx
import grap... |
from snake import Snake
from datetime import datetime
from multiprocessing import Pool
from game import draw, listen_events, game_start, wait_until_press_enter
import random
import numpy as np
import torch # NOT NEEDED, ONLY FOR TESTING
import time # NO NEED FOR THIS FUNCTION
# Genetic algorithm hyperparameters
POPUL... |
print("This program tells you when you when you will be a HUNDRED years old.")
print()
print()
user = str(input("please enter your name"))
print("welcome,",user)
current_year = 2018
current_age = int(input("How old are you"))
birth_year = (current_year - current_age)
future_limit = (birth_year + 100)
print(use... |
import cv2
import numpy
import face_recognition
import os
from CrearLista import NombreArchivo
from datetime import datetime
NombreArc = NombreArchivo()
path = 'Rostros' #Ruta de donde estan las imagenes
Imagenes = []
ListaNombres = []
Lista = os.listdir(path) #Creamos una lista con los nombres de los archivos que se... |
"""
Metadata for model building, simulation and validation.
"""
# Copyright 2018-2019 CNRS
# 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
... |
from django.conf.urls import url
from crm.views import sales, teacher
urlpatterns = [
### 销售相关 ###
# 公有客户列表
url(r'^customer_list/', sales.CustomerList.as_view(), name='customer'),
# 私有客户
url(r'^my_customer_list/', sales.CustomerList.as_view(), name='my_customer'),
# 添加客户
url(r'^customer/ad... |
from rkd.transformations import *
print(rotx(3.1416/2))
print(rotx(90, deg=True)) |
# Loading & examining our data
# Import pandas
import pandas as pd
# Load the customer_data
customer_data = pd.read_csv('customer_data.csv')
# Load the app_purchases
app_purchases = pd.read_csv('inapp_purchases.csv')
# Print the columns of customer data
print(customer_data.columns)
# Print the columns of app_purch... |
# 396. Coins in a Line III
'''There are n coins in a line, and value of i-th coin is values[i].
Two players take turns to take a coin from one of the ends of the line until there are no more coins left. The player with the larger amount of money wins.
Could you please decide the first player will win or lose?
Examp... |
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import FormView, TemplateView
from planner.forms import VegetableForm
from planner.models import Garden, Vegetable, CulturalOperation
class VegetablesView(TemplateView):
template_name = 'planner/vegetables_list.htm... |
import io
from struct import unpack
from World.Object.Unit.Movement.Constants.MovementFlags import MovementFlags
from World.Object.Position import Position
from Server.Registry.QueuesRegistry import QueuesRegistry
from World.WorldPacket.Constants.WorldOpCode import WorldOpCode
class MovementHandler(object):
de... |
# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)
# Print out drives_right value of Morocco
print(cars.loc[["MOR"],["drives_right"]])
# Print sub-DataFrame containing the observations for Russia and Morocco and the columns country and drives_right.
print(cars.loc[["RU","MOR"],["coun... |
import socket
from enum import Enum
from dataclasses import dataclass
from threading import *
import time
class Command(Enum):
PASSWORD = "PASS"
NICK = "NICK"
USER = "USER"
PONG = "PONG"
PING = "PING"
PRIVMSG = "PRIVMSG"
JOIN = "JOIN"
@dataclass
class UserData():
username : str
hos... |
from adaptivenv import Function, Composition
from ppa import PPASuperposition
#Compositions
#Superposition
|
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 30 10:46:52 2017
Grab filtered scenes, sort them based on acquisition dates, and save as new sequentially numbered files
@author: dzelenak
"""
import os
import sys
import glob
import pprint
from shutil import copyfile
from argparse import ArgumentParser
def read_list(tx... |
from .. import authz
from . import custom_api, events, utils
def get_notebook(notebook, namespace):
authz.ensure_authorized(
"get", "kubeflow.org", "v1beta1", "notebooks", namespace
)
return custom_api.get_namespaced_custom_object(
"kubeflow.org", "v1beta1", namespace, "notebooks", noteboo... |
import os
import numpy as np
import librosa
import librosa.display
import warnings
warnings.filterwarnings('ignore')
dir_max_size = []
# Looping through each audio file - GTZAN
for dir in os.scandir('../data/project_data/mini/new_genre'):
sizes=[]
for file in os.scandir(dir):
# Loading in the audio f... |
from unittest import TestCase
from unittest.mock import create_autospec
from mazel.exceptions import RuntimeNotFound
from mazel.package import Package
from mazel.runtimes import (
DockerRuntime,
GoRuntime,
JavascriptRuntime,
MeteorRuntime,
PythonRuntime,
Runtime,
)
class RuntimeTest(TestCase)... |
import math
from numpy import save, load
import db_manager
def eigenvector(p_matrix, a, epsilon):
dbu = db_manager.DatabaseUtility()
employee_data = dbu.get_eid()
q = p_matrix
p = AxP(a, p_matrix)
l = norm(p)
p = PxL(p, 1/l)
while norm(PminusQ(p,q)) > epsilon:
q = p
p = Ax... |
#Metodo upper() convierte a mayusculas
micadena = raw_input("ingresa un texto")
for cadena in micadena:
print(cadena.upper())
# metodo lower() convierte a minusculas
micadena2 = raw_input("ingresa un segundo texto")
for i in micadena2:
print(i.lower())
#iteracion sobre un rango
saludo = "HOLA MUNDO"
for numero... |
class Solution:
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max1, max2, max3 = float('-inf'), float('-inf'), float('-inf')
for i in nums:
if max1 == float('-inf'):
max1 = i
elif max2 == float('-inf'):
... |
import urllib.parse
import urllib.request
import json
from . import settings as app_settings
from uuid import UUID
class UUIDEncoder(json.JSONEncoder):
"""https://stackoverflow.com/a/48159596"""
def default(self, obj):
if isinstance(obj, UUID):
# if the obj is uuid, we simply return the va... |
#!/usr/bin/python3
""" Module that interacts with Github API to display 10 commits
to a repository
"""
import requests
from sys import argv
if __name__ == "__main__":
repo = argv[1]
owner = argv[2]
url = 'https://api.github.com/repos/{}/{}/commits'.format(owner, repo)
resp = requests.get(url)
... |
import numpy as np
import pandas as pd
import pandas
import matplotlib.pyplot as plt
data = pandas.read_excel('sampledata.xlsx')
print(data.shape)
data.head()
# Collecting X and Y
X = data['lift1_True'].values
Y = data['lift2_Predict'].values
# Mean X and Y
mean_x = np.mean(X)
mean_y = np.mean(Y)
# ... |
from onegov.core.utils import normalize_for_url
from onegov.form import Form, merge_forms, FormDefinitionCollection
from onegov.form.validators import ValidFormDefinition
from onegov.org import _
from onegov.org.forms.fields import HtmlField
from onegov.org.forms.generic import PaymentForm
from wtforms.fields import St... |
import math
def getfact(num):
if (num < 1):
return 0
if (num < 10):
return math.factorial(num)
else:
return math.factorial(num % 10) + getfact(num / 10)
res = 0
for i in range(3,1000000):
if i == getfact(i):
res += i
print res |
from django.urls import path
from.import views
urlpatterns = [
path('', views.api_overview, name='api-overview'),
path('subscriber/list/', views.subscriber_list, name='subscriber-list'),
path('subscriber/create/', views.create_subscriber, name='create-subscriber'),
path('subscriber/<email>/delet... |
from apay import app, db, models
from flask import request, abort, jsonify
from sqlalchemy.exc import IntegrityError
@app.route('/banks', methods=['POST', 'GET'])
def banks():
if request.method == 'POST':
try:
bank = models.Bank(request.get_json())
db.session.add(bank)
d... |
import redis
import os
import pkg_resources
from redis.exceptions import WatchError
class WordCollector(object):
'''
Demostrates usage of file, map lamda, redis, WATCH, MULTI
'''
STOP_WORDS = list(["the", "is"])
"""
The class level static stop words
"""
def __init__(self):
sel... |
# Inventory.py
stuff = {'rope' : 1, 'torch' : 6, 'gol coin' : 42, 'dagger' : 1, 'arrow' : 12}
def displayInventory(inventory):
print("Inventory:")
itemTotal = 0
for k,v in inventory.items():
# My code
itemTotal = itemTotal + v
print( str(v) + ' ' + k)
print("Total numb... |
# /usr/bin/env/python
import time
from euler import fibonacci_n, fibonacci
from itertools import takewhile
start = time.time()
result = sum(x for x in fibonacci_n(4*10**6) if x % 2 == 0)
time_spend = time.time() - start
print "The sum is %s and take time is %f" % (result, time_spend)
start = time.time()
result = su... |
def maxPairs(skillLevel, minDiff):
# Write your code here
sl = sorted(skillLevel)
i = 0
mid = len(sl) // 2
j = mid
pairs = 0
while i < mid and j < len(sl):
# print(i, j, len(sl))
while (sl[j] - sl[i] < minDiff):
j += 1
if j >= len(sl):
... |
from time import strftime, gmtime
from peewee import Model, CharField, BigBitField, SqliteDatabase, TextField, IntegerField, ForeignKeyField, \
DateTimeField, BooleanField
from config import DB_FILE_ABSPATH
db = SqliteDatabase(DB_FILE_ABSPATH)
MAX_ARTICLE_CONTENT_LENGTH = 1000000
MAX_ARTICLE_PREVIEW_TEXT_LENGTH ... |
#!/usr/bin/env python
##################################################
# Last edit 9/13/2013 #
# checked by sophie and will #
##################################################
# general imports
from numpy import (array, arange, sin, cos, tan, pi, hstack, vstack, corrco... |
#!/usr/bin/env python
# Copyright 2016 Criteo
#
# 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 agree... |
from fields import *
from file_tests import *
from geo import *
|
from flask import Flask, render_template, session, request
import utils
app = Flask(__name__)
@app.route("/")
@app.route("/home")
def home():
d = {}
fruits = ['mango', 'papaya', 'strawberry', 'pineapple', 'apple', 'pear',
'watermelon', 'guava', 'kiwi', 'dragonfruit', 'banana']
return rend... |
import unittest
from src import Magnet
magnet = Magnet()
class MagnetClassTest(unittest.TestCase):
def test_create_instance(self):
magnet_instance = Magnet()
self.assertIsInstance(magnet_instance, Magnet)
|
import psycopg2
import bcrypt
def authenticate_lecturer(email, password):
# DB Connection
try:
conn = psycopg2.connect(
host="attendance-manager.cstueihbr6n2.eu-west-1.rds.amazonaws.com",
database="AttendanceManager",
user="Developer",
password="rainfores... |
__author__ = 'Крымов Иван'
# Посчитать четные и нечетные цифры введенного натурального числа. Например, если введено число 34560, в нем 3 четные
# цифры (4, 6 и 0) и 2 нечетные (3 и 5).
def even_odd_numbers(num):
even_num = 0
odd_num = 0
zero_num = 0
for el in num:
if int(el) == 0:
... |
from scanip_api import *
import os
import glob
############################################################################
# dims4ph = [364,364,400]
# dims3ph = [364,364,280]
# voxDims = [27.5,27.5,25.0]
# vdims = [x / 1000.0 for x in voxDims]
path = "E:\\Tim\\projects\\first-moose-paper\\data\\mesh\\... |
# make a data folder
from os import path, getcwd, mkdir
def make_data_folder(data_folder_name="data"):
"""makes a "data" folder in the current directory IF it doesn't already exist
:param data_folder_name: if you want a name other than data
:return: void
"""
pwd = getcwd()
full_path = path.... |
from django.shortcuts import render, redirect
from django.core.files.storage import FileSystemStorage
import cv2
import os
from django.core.paginator import Paginator
import face_recognition
from .models import Person
from .form import PersonForm
from django.contrib import messages
import numpy as np
# Create your view... |
import numpy as np
import json
import os
import sys; sys.path.append('../../') # NOQA
from util import text_processing
from collections import Counter
vocab_answer_file = './answers_vqa.txt'
# annotation_file = '../vqa_dataset/Annotations/mscoco_%s_annotations.json'
annotation_file = r'C:\Users\user\Desktop\Universi... |
#!/usr/bin/python
import ldap
import ldap.modlist
import string
import sys
import base64
# This sample script allows to add an unique identifier attribute
# on each user and group of an existing LDAP tree.
# it is recommended to load the unique OpenLDAP overlay before using this
# script. See:
# http://www.openldap.o... |
from random import randint
def authenticate(username,password):
if username == "stuyvesant" and password =="123456789":
return True
else:
return False
def ranColor():
color = ""
if randint(0,1) == 0:
color = "#3399FF"
else:
color = "red"
return color
|
lado=input("Introduce longitud delado: ")
c=0
while c<lado:
i=0
while i<lado:
print "*",
i=i+1
print ""
c=c+1
|
import os
import zipfile
import zlib
basedir = r"C:\folder"
outputdir = r"C:\output"
#Zip up each archive dir individually
def zipit(archivepath,basedir):
paths = os.listdir(archivepath)
for f in paths:
filename = os.path.join(archivepath,f)
zip = zipfile.ZipFile(os.path.join(outputdir, f +".zip"), "w", zip... |
from django.shortcuts import render, get_object_or_404, redirect, reverse
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .models import Post, Comment
from .forms import CommentForm
from django.db.models.functions import Lower
from .decorators import login_required_mes... |
import numpy as np
input = np.ones((10,10))
loc = np.random.randint(0,10, (2,))
input[loc[0], loc[1]] = 9
print(input, loc)
class LocDataLoader(object):
def __init__(self, size=10, batch_size=32):
self.size = 10
self.batch_size = batch_size
def get_item(self):
input = n... |
import numpy as np
import modern_robotics as Mr
############################
import math
x = 2
e_to_2 = 0
for i in range(5):
e_to_2 += x**i/math.factorial(i)
print(e_to_2)
###############Question #1###########
R_sa=np.array([[0,1,0],[0,0,1],[1,0,0]])
R_sb=np.array([[1,0,0],[0,0,1],[0,-1,0]])
print("Questi... |
# -*- coding: utf-8 -*-
from django.test import TestCase
from extra_settings.cache import (del_cached_setting, get_cached_setting, set_cached_setting)
class ExtraSettingsCacheTestCase(TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_cache_del(self):
set_cached... |
def ha(cc,tt):
# cc=5,tt=3 m = c-t =2
for x1 in range(2):
all_x1 = []
single_index = 1
all_x1.append([x1])
while single_index<tt:
# print(all_x1.copy())
for it in all_x1:
aadd = [x for x in range(x1+1,cc) if x+single_index<=cc-1]
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.