text
stringlengths
8
6.05M
from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * import sys from time import * k=3 t=[0 for i in range(20)] def init(): glClearColor(1.0,1.0,1.0,0.0) glPointSize(2.0) glColor3f(1.0,0.0,0.0) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluOrtho2D(0.0,20.0,0.0,20.0) def setPixel(x,y): g...
from django.conf.urls import url from . import views urlpatterns = [ url(r'^index/$', views.discussion_index, name='index'), url(r'^(?P<d_id>\d+)/$', views.discussion_detail, name='detail'), url(r'^new_discussion/$', views.new_discussion, name='new_discussion'), ]
# Working with Twitter API and parsing received data import html import os #import socket from twython import Twython from twython import TwythonAuthError, TwythonError, TwythonRateLimitError from time import strftime, strptime def get_user_timeline(screen_name, limit): """Consume screen_name and limit. 1) g...
def classFactory(iface): from LMConf import LMConf return LMConf(iface)
import pandas as pd import matplotlib.pyplot as plt import string class RestaurantGrades: '''This class will analyze data of the grade of each restaurant in new york city over time and generate relevant plots.''' def __init__(self): #load data self.grades = load_data() self.boroug...
import sys sys.path.insert(0, "D:\PythonProjectsDDrive\stylegan2-master") import argparse import numpy as np import PIL.Image import dnnlib import dnnlib.tflib as tflib import re import sys import pretrained_networks def generate_images(Gs, seeds, truncation_psi): #noise_vars = [var for name, var in Gs.component...
# -*- python -*- class Call(object): def __init__( self, id, name, phone_number, time, reason ): self.id = id self.name = name self.phone_number = phone_number self.time = time self.reason = reason def display( self ): print "object Call:" print " id:",...
from setuptools import setup, find_packages setup( name="publish", version="0.2.1", packages=find_packages(), install_requires=["pyyaml", "cerberus", "jinja2"], tests_require=["pytest"], entry_points={ "console_scripts": [ "publish = publish:cli", "publish-utils...
#!/usr/bin/env python3 print("你好, World!");
from os import listdir from os.path import isfile, join pasta_input = "output\\" pasta_output = "output_separado\\" encoding = "utf8" file_input = "output_raw.txt" N = 21 for qtd in range(1, 26): file_output = "output_5.2.05_" + str(qtd)+ ".txt" count = [0] * N with open(join(pasta_output,...
from flask import request def delete_links(id): return {'message': 'ok' } def share_links(id): return {'messange': 'Link enviado para ' + request.form['destinatario'] + '!' }, 201 def get_links(): return { "message": "Ok", "links": [] }, 200 def save_link(): return { "mes...
scina = int(input()) for _ in range(scina): count = 0 i = 1 col_num = int(input()) colors = list(map(int, input().split())) b = [colors[0], 0] while i < len(colors): if colors[i] == colors[i - 1]: i += 1 elif colors[i] in b: i += 1 continue ...
from urllib.parse import parse_qs, urlencode, urljoin from wsgiref.simple_server import ( WSGIRequestHandler as BaseWSGIRequestHandler, make_server, ) from wsgiref.util import setup_testing_defaults import sys from pymacaroons import Macaroon import stacksmith AUTHORIZE_ENDPOINT = urljoin(stacksmith.url, 'a...
class Base: def __init__(self): self.a = 5 class Derived1(Base): def __init__(self): super().__init__() self.b = 7 class Derived2(Derived1): def __init__(self): super().__init__() self.c = 10 def sum(self): result = self.a + self.b + self.c re...
""" This module lets you practice: -- ITERATING (i.e. LOOPING) thru a SEQUENCE -- Using OBJECTS -- DEFINING functions -- CALLING functions Authors: David Mutchler, Valerie Galluzzi, Mark Hays, Amanda Stouder, their colleagues and Muqing Zheng. October 2015. """ # TODO: 1. PUT YOUR NAME IN THE ABOVE ...
import random import point import target as tg "Checks if path generated is valid" def check_if_path_correct(ordered_nexts, targets, radius): last = float("inf") for i in ordered_nexts: temp = [j for j in targets if i.euclidean_distance(j) <= radius] if len(temp) > last: return Fals...
#!/usr/bin/python import os import pickle import sys import subprocess import Queue import threading import getopt import copy import string import glob import csv import re import random def usage(): print "\n-----------------------------------------------------------------" print "Usage: " print " sift...
from __future__ import print_function # Helper class to convert a DynamoDB item to JSON. import boto3 import json import decimal import movies_common dynamodb = boto3.resource('dynamodb') # dynamodb = boto3.resource('dynamodb', region_name='ap-northeast-1', endpoint_url='http://localhost:4569') table = dynamodb.Table...
# ====================== # Functions for ingesting and cleaning Landsat geotiff # ====================== # import libraries import numpy as np import rasterio # ====================== # Function to read in vegetation index images and create np image stack # ====================== def create_image_stack(files, exten...
import torch from torch.utils import benchmark from .main_cnn import create_model as ResNet from .main_transformer import create_model as ViT for model in (ResNet(), ViT()): print(f"#### {model.__class__.__name__} ####") x = torch.randn(1, 3, 32, 32) # CIFAR10 params = sum(p.numel() for p in model.para...
""" 수 찾기 N <200,000 """ input() first_data = list(map(int, input().split())) input() second_data = list(map(int, input().split())) first_data.sort() def binary_search(array, target, start, end): mid = (start + end) // 2 if start > end: return None if array[mid] == target: return mid ...
# Generated by Django 4.2.3 on 2023-08-07 13:44 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("elections", "0072_alter_election_current_alter_election_group_type"), ] operations = [ migrations.AlterField( model_name="electio...
import json def formHdrResp(code,message): rslt = {"code":code,"message":message} return rslt def formErrResp(code,message,responseNode,responseObj): rslt = {"code":code,"message":message,"response":{}} rslt["response"] = responseObj finalRslt = {} finalRslt[responseNode] = rslt ...
from re import compile, match REGEX = compile(r'\$(?P<integer>\d+)\.(?P<frac>\d{0,2})$') def to_cents(amount): m = match(REGEX, amount) if m and m.group(0) == amount: return int(m.group('integer')) * 100 + int(m.group('frac'))
from django.apps import AppConfig class EshopProductsConfig(AppConfig): name = 'eshop_products' verbose_name = 'ماژول محصولات'
#from scipy.stats.stats import pearsonr #a = [20,20,1] #b = [20,20,3] #print (pearsonr(a,b)) #raise SystemExit import numpy as np from collections import Counter, defaultdict import os import pandas import util import pyutil import time title = "standard" his_idx = 0 spentidx = 0 amountidx = 1 datesidx = 2 clas...
#!/usr/bin/env python3 #- # Copyright (c) 2015, David Kalliecharan <david.kalliecharan@dal.ca> # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # T...
with open ('input.2.txt','r') as f: s=f.readline() c="""QWERTYUIOPĂÎÂASDFGHJKLȘȚZXCVBNM""" d="""0123456789""" e="""+-*/""" j="""qwertyuiopasdfghjklzxcvbnm""" v='' for i in s: if i in c: v=v+str(i) with open ('litereA.txt','w') as f: f.write(v) b='' for a in s: if a ...
from watchdog.observers import Observer import os import time # FileSystemEventHandler - класс по отслеживанию изменений from watchdog.events import FileSystemEventHandler # Создаем класс наследник, через него может отслеживать изменения в папках class Handler(FileSystemEventHandler): # При любых изменениях в папке,...
#!/usr/bin/env python # encoding: utf-8 # @author: Zhipeng Ye # @contact: Zhipeng.ye19@xjtlu.edu.cn # @file: plus99.py # @time: 2020-01-24 13:56 # @desc: if __name__ == '__main__': content_list = [] with open('/Data_SSD/zhipengye/zhipengye/LM/completed.data/data/n-gram3/GoogleWbi-Direct.small',encoding='utf-...
# -*- coding: utf-8 -*- """ Created on Sun Sep 1 19:44:29 2019 @author: Zilean """ from sklearn import datasets from sklearn import metrics from sklearn.model_selection import train_test_split from sklearn import preprocessing from sklearn.linear_model import SGDClassifier import matplotlib.pyplot as plt import nump...
import pandas as pd import numpy as np from sklearn.cluster import KMeans from sklearn.metrics import silhouette_score from functools import reduce class ClustersHandler: def __init__(self, df: pd.DataFrame, df_stations: pd.DataFrame, country:str=None, weights:dict=None): if country is not None: ...
#!/usr/bin/python3 # 可写函数说明 sum = lambda arg1, arg2: arg1 + arg2 # 调用匿名函数 print("相加后的值: ", sum(10, 20)) print("相加后的值: ", sum(20, 20))
from setuptools import setup, find_packages setup(name='sjresearchutil', version='0.1.0', url='', license='MIT', author='Sooyong Jang', author_email='sooyong@seas.upenn.edu', packages=find_packages(exclude=['tests']), long_description=open('README.md').read(), zip_safe=F...
import bz2 import fnmatch import functools import gzip import os import re import sys # Inside a function, the yield statement can also be used as an # expression that appears on the right side of an assignment operator. def receiver(): print("Ready to receive") while True: n = (yield) print...
def write_p2g(G, path, encoding: str = "utf-8") -> None: ... def read_p2g(path, encoding: str = "utf-8"): ... def parse_p2g(lines): ...
import os from typing import Generator import pandas as pd from pandas import DataFrame, ExcelWriter SHEET_NAME = "Master" MERGED_FILE_NAME = "POC.xlsx" def _get_all_excel_files(directory: str) -> Generator[str, None, None]: for dir_path, _, filenames in os.walk(directory): for f in filenames: ...
#!/usr/bin/python teststr = "Hello DevOPS" print teststr[0:5] newvar = teststr + "hola" print newvar
from django.shortcuts import render_to_response from django.template.context import RequestContext # Create your views here. def Default(request): return render_to_response('base.html', RequestContext(request, { 'content', "<p>Hello</p>" }))
from flask import Flask,render_template, request,json import os import logging from pathlib import Path import torch import torch.nn as nn import numpy as np import pandas as pd from torch.utils.data import Dataset, DataLoader from pytorch_pretrained_bert import BertTokenizer from pytorch_pretrained_bert.modeling impor...
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2017-11-02 20:46 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('adminapp', '0023_cargarestudiante'), ] operations = [ migrations.RenameField( ...
""" Cycle Detection - CodeWar """ def floyd(root): hare = root.next.next while tortoise != hare: tortoise = f(tortoise) hare = f(f(hare)) tortoise = root while tortoise != hare: tortoise = f(tortoise) hare = f(hare) start = tortoise length = 1 hare = f...
from matplotlib import pyplot as plt import numpy as np import os import tda def measure_square(radius, dim_pcd=2): vec = np.empty(dim_pcd) for i in range(dim_pcd): vec[i] = np.random.uniform(-1 * radius, radius) return vec def measure_circle(radius, dim_pcd=2): vec = np.random.randn(dim_pc...
from __future__ import print_function from tinydb import Query from datahandling import my_query, access_db, extractnames from itertools import combinations from logging import debug, info from sklearn.decomposition import PCA from pca import pca_X try: from winsound import Beep except ImportError: def Beep(a,...
# ****************************************************************** # # ************************* Byte of Python ************************* # # ****************************************************************** # ######################## # passing tuples around ######################## # def get_error_details()...
#!/usr/bin/env python # -*- coding: utf8 -*- ''' MIT License Copyright (c) [2019] [Orlin Dimitrov] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitat...
import os import sqlite3 from config import DB_DIR, DB_NAME class SQLite3Instance: """ Класс (обертка) для работы с SQLite3 БД """ def __init__(self): self.db_name = DB_NAME self.db_dir = DB_DIR self.con = sqlite3.connect(os.path.join(self.db_dir, self.db_name)) self.cur = sel...
nums = [1, 2, 3, 4] #Sort the list from smallest to largest. nums.sort() #Find the median. length = len(nums) if (length % 2 == 0): median = (nums[(length)//2] + nums[(length)//2-1]) / 2 else: median = nums[(length-1)//2] #Display the result. print(median)
#!/usr/bin/env python import Tkinter, tkFont class Ball: def __init__(self, id, x, y, radius, color="cyan"): self.id, self.x, self.y, self.radius, self.color = id, x, y, radius, color def move_right(self): self.x += 5 if self.x + self.radius >= canvas_width: self.x ...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'userUI.ui' # # Created by: PyQt5 UI code generator 5.11.3 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_userUI(object): def setupUi(self, userUI, user, movieList): ...
''' Name: Chung-Hsin(Jack) Hou ''' import requests, json, copy from collections import defaultdict # modified binary search to search for one product. def findOne(seq, goal): if not seq: return None min = 0 max = len(seq) - 1 #if the goal price is larger than the max price, simply return...
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations from typing import DefaultDict, Sequence from unittest import mock import pytest from pants.engine.fs import EMPTY_DIGEST from pants.jvm.resolve.commo...
import graphene from django.db.models import Sum, Q from ...order import OrderStatus from ...product import models from ...product.utils import products_with_details from ..utils import filter_by_query_param, filter_by_period, get_database_id from .types import Category, ProductVariant, StockAvailability PRODUCT_SEAR...
# KVM-based Discoverable Cloudlet (KD-Cloudlet) # Copyright (c) 2015 Carnegie Mellon University. # All Rights Reserved. # # THIS SOFTWARE IS PROVIDED "AS IS," WITH NO WARRANTIES WHATSOEVER. CARNEGIE MELLON UNIVERSITY EXPRESSLY DISCLAIMS TO THE FULLEST EXTENT PERMITTEDBY LAW ALL EXPRESS, IMPLIED, AND STATUTORY WARRANTIE...
import gym import sys, os import time import copy from gym import error, spaces, utils from gym.utils import seeding import numpy as np from PIL import Image as Image import matplotlib.pyplot as plt from scipy import misc def round_up(a): if type(a) is type(np.array([1])): abs_a = np.abs(a) abs_a_i...
# Job: A process or task that has a priority. # Your implementation should pass the tests in test_job.py. # Andras Mihaly class Job: def __init__(self, priority=None, message=None): self.priority = priority self.message = message def __eq__(self, node): return self.priority == node.pr...
# -*- coding: utf-8 -*- import json from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler from SocketServer import ThreadingMixIn from threading import Thread from urlparse import urlparse from PIL import Image, ImageDraw, ImageFont from cv2 import cv import ConfigParser import logging import time import os im...
from loadImage import loadFromFile, return2dImageMatrix import numpy as np import random as rd def randomInitialize(X, K): """randomly initialize few datapoints as points for centroids for applying the kmeans algorithm""" a,b = X.shape randIndexes = np.random.randint(a, size=K) return X[randIndexes,:] def findC...
import torch import torch.nn as nn import torchvision.models as models from tqdm import tqdm from torch.utils.data import DataLoader from sklearn.metrics import accuracy_score from dataset import TextDataset from utils import get_val_augmentations, get_train_augmentations, preprocess_data def main(): BATCH_SIZE =...
# Run this script after doing the pyinstaller build import os import shutil import subprocess from musclex import __version__ os.sys.path.append(os.path.abspath(os.path.join('..', '..'))) deb_path = os.path.join('.', 'musclex-{}_amd64(linux)'.format(__version__), 'DEBIAN') exc_path = os.path.join('.', 'musclex-{...
import midi_output import time class MidiEventSender: def __init__(self, midi_receiver): self.midi_receiver = midi_receiver def set_program_event(self, program_value): print("Setting program to ", program_value) event = [[[192, program_value, 0, 0], 0]] self.midi_receiver.sen...
from distutils.core import setup setup(name='graphsurgeon', version='0.4.1', description='graphsurgeon', author='Nvidia', packages=['graphsurgeon'], )
import csv import cv2 import numpy as np import sklearn import sklearn.model_selection from keras.models import Sequential from keras.layers import Flatten, Dense, Lambda, Convolution2D, MaxPooling2D, Cropping2D, Dropout, SpatialDropout2D from random import shuffle def main(): lines = [] datafiles = ['data/...
s = raw_input().strip().lower() if ('a' in s and 'b' in s and 'c' in s and 'd' in s and 'e' in s and 'f' in s and 'g' in s and 'h' in s and 'i' in s and 'j' in s and 'k' in s and 'l' in s and 'm' in s and 'n' in s and 'o' in s and 'p' in s and 'q' in s and 'r' in s and...
#!/usr/local/bin/python import argparse import distutils.spawn import shutil import subprocess import os DEV_APPSERVER_PATH = distutils.spawn.find_executable('dev_appserver.py') GCLOUD_PATH = distutils.spawn.find_executable('gcloud') APP_PATH = os.path.join(os.path.dirname(__file__), 'app') LIB_PATH = os.path.join(...
class cardpackage(): @property def name(self): return self._name def set_name(self,name): self._name = name return self @property def cost(self): return self._cost def set_cost(self,cost): self._cost = cost return self @property def subtype(self): return self._subtype def set_subtype(self,sub...
''' Random forests help to mitigate overfitting in decision trees. Training data is spread across decision trees. The subsets are created by taking random samples with replacement. This means that a given data point can be used in several subsets. (This is different from the subsets used in cross validation where each...
from panda3d.bsp import BSPMaterial from panda3d.core import LVector2i, PNMImage, VirtualFileSystem, getModelPath, Filename from PyQt5 import QtGui, QtCore # Reference to a material loaded from disk that can be applied to brush faces. # Materials with the same filename are unified to the same MaterialReference object...
# coding=utf-8 from mongo_zaojv import MongoUrlManager from crawler_zaojv import Crawler_zaojv import re import time mongo_mgr = MongoUrlManager() # 设置爬虫起始页 root_url = "http://www.miaoqiyuan.cn/zaojv/word-a.html" # 向数据库中添加一级网页 first_url = "http://zaojv.com/word_{}.html" """ for page in range(1,1046): ...
import threading import queue class MyThread(threading.Thread): def __init__(self, name, que): threading.Thread.__init__(self) self.name = name self.que = que def run(self): print(f"Starting Thread {self.name}") work(self.name, self.que) print(f"Finishing Threa...
# File : i2c_fusion.py # What : i2c sensor fusion (Tilt-compensated heading) import math import json from i2c_base import i2c_sensor from i2c_compass import compass from i2c_accel import accel import threading class _data(object): """Contariner for ULMO-relevant IMU data.""" def __init__(self): self....
diff = ('Jones', 'Sally') > ('Adams', 'Sam') print(diff) d = {'a': 10, 'b': 1, 'c': 22} print(d.items()) print(type(d.items()))
s, t, f = map(int, input().split(' ')) if s == 0: s = 24 h = s + t + f if h >= 24: h -= 24 print(h)
from flask_sqlalchemy import SQLAlchemy from datetime import datetime import enum db = SQLAlchemy() def configure(app): db.init_app(app) app.db = db class Usuario(db.Model): id = db.Column(db.Integer, primary_key = True) nome_completo = db.Column(db.String(255)) cpf = db.Column(db.String(14)) ...
import datetime from django.apps import apps from django.db import transaction from django.core.management.base import BaseCommand as DjangoBaseCommand from wampbaseapp.wamp_app import WampApp as WampBaseApp, register_method class WampApp(WampBaseApp): PRINCIPAL = 'PRINCIPAL' models = {} apps = {} ...
from struct import unpack, pack import csv def read_vlv(file): """ convert Variable Length Values to integers """ bin_str = '' char = file.read(1) while(unpack('>B', char)[0] > 127): bin_str += bin(ord(char) - 128)[2:].zfill(7) char = file.read(1) bin_str += bin(ord(char))[...
# Guess the number game # no of guesses 9 # no of guesses left # game over n=18 remain_guess=9 guess=1 while(guess<=9): print("----------------------") inp = int(input("\nEnter a guessing number:")) if inp<18: print("The number is greater than the one u entered\n") elif inp>18: print("T...
import numpy as np import cv2 #Contour Area(둘러싸인 부분의 면적)와 Contour Perimeter(호의 길이)를 구하는 방법 #키값이 m00인 값이 contourArea의 값이다. #arcLength()는 2개의 인자를 가짐, 두 번째 인자에서 True이면 폐곡선, False이면 열려있는 호를 나타냄 def contour(): img = cv2.imread('images/sana.jpg') imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, thr = cv2.th...
from tkinter import * root = Tk() root.title("Hello") text = Label(root, text="請輸入暱稱:", width="30", height="2") text.pack() name = Entry(root, width="30") name.pack() button = Button(root, text="執行") button.pack() result = Label(root, text="", width="30", height="2") result.pack() root.mainlo...
# Generated by Django 2.0.3 on 2018-03-14 06:10 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('orders', '0004_auto_20180314_0609'), ] operations = [ migrations.AlterField( model_name='order'...
# sqlalchemy tollkit imports from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker # Database classes imports from catalog_database import Base, Categories, CatalogItem, User import datetime engine = create_engine('sqlite:///clothescategories.db') # Bind the engine to the metadata of the Base cla...
# sql: # \copy (select st."1:2"-st."1:3" as ibl, st."1:1"-st."1:2" as ebl, count(1) as c,nblocks as b,ngenes as g from (select * from recomb as rb join gene_trees as gt on gt.id=rb.inf where topology!='(4,(3,(1,2)));' ) as foo join species_trees as st on foo.sid=st.id group by b,g,ebl,ibl order by c) to 'discordant.rec...
# 输入三个整数x,y,z,请把这三个数由小到大输出 x = int(input("x:")) y = int(input("y:")) z = int(input("z:")) listNum = [] listNum.append(x) # append 方法添加列表项 listNum.append(y) listNum.append(z) listNum.sort() for i in listNum: print(i)
import json import treq from twisted.trial.unittest import SynchronousTestCase from mimic.model.heat_objects import RegionalStackCollection, Stack from mimic.rest.heat_api import HeatApi from mimic.test.fixtures import APIMockHelper from mimic.test.helpers import request class HeatObjectTests(SynchronousTestCase): ...
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2021 # # Distributed under terms of the MIT license. """ Description: """ import asyncio import logging import patterns import view from themesong import ThemeSong import sys, getopt from socket_client import SocketClient logging.bas...
from itertools import cycle from math import sqrt, acos, sin, cos import numpy as np from matplotlib import cm from matplotlib.animation import FuncAnimation from matplotlib.patches import Ellipse, Arrow import matplotlib.pyplot as plt from picp.util.geometry import apply_tf_on_point_cloud from python.pypm.icp import...
import web import pymysql import fileMgr import wayPoint render = web.template.render('templates/', base='layout', globals={'hasattr': hasattr}) urls = ( '/', 'Index', '/view/(.*)', 'View', '/manage', 'Manage', '/manage/create', 'Create', '/manage/hide/(\d+)', 'Hide',...
# coding=utf-8 import cv2 import os, shutil # import tensorflow as tf from tensorflow.python.keras.applications.resnet50 import ResNet50 from tensorflow.python.keras.applications.vgg19 import VGG19 from tensorflow.python.keras.models import load_model import numpy as np import sys font = cv2.FONT_HERSHEY_SIMPLEX from...
# -*- coding: utf-8 -*- from AnswerSelection import IAGru, OAGru_SMALL from DataProcessor.MSRPD import MSRPD from NeuralModel.IAGRU_WORD import IAGRU_WORD from NeuralModel.OAGRU import OAGRU_small, OAGRU from TaskBase import TaskBases __author__ = 'benywon' MSR = 'MSR' class ParaphraseDetection(TaskBases): def...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Jul 12 10:06:13 2017 @author: wanjia """ class Handler(object): def addTag(self,zlib,item,tagname): #adds a new tag to the new item # tagname = 'python lesson' #in the bracket (tagname, '<tag type:0>') item.ad...
from Jumpscale import j class Package(j.baseclasses.threebot_package): def prepare(self): """ is called at install time :return: """ pass def start(self): """ called when the 3bot starts :return: """ ## TODO: BAD # self.d...
from SimpleXMLRPCServer import SimpleXMLRPCServer import logging import os import time # Set up logging logging.basicConfig(level=logging.DEBUG) server = SimpleXMLRPCServer(('localhost', 9090), logRequests=True) # Expose a function def list_contents(dir_name): logging.debug('list_contents(%s)', dir_name) tim...
from flask import Flask, render_template, url_for, Blueprint, request, redirect from databaseIntegration.database_queries import Database from databaseIntegration.database import create_connection, close_connection from databaseIntegration.database_config import Config app = Flask(__name__) connection, cursor = create...
from panda3d.core import Vec3, BitMask32 VIEWPORT_3D = 0 VIEWPORT_2D_FRONT = 6 VIEWPORT_2D_SIDE = 7 VIEWPORT_2D_TOP = 8 VIEWPORT_3D_MASK = BitMask32.bit(VIEWPORT_3D) VIEWPORT_2D_MASK = BitMask32.bit(VIEWPORT_2D_FRONT) | \ BitMask32.bit(VIEWPORT_2D_SIDE) | \ BitMask32.bit(VIEWPORT_2D_TOP) clas...
from __future__ import print_function from ryu.base import app_manager from ryu.ofproto import ofproto_v1_3 class MultipleController(app_mananger.RyuApp): OFP_VERSIONS =[ofproto_v1_3.OFP_VERSION] def __init__(self, *args, **kwargs): super(MultipleController, self).__init__(*args, **kwargs)
# Generated by Django 2.1.7 on 2019-03-09 11:22 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('milliard', '0002_auto_20190309_0853'), ] operations = [ migrations.CreateModel( name='Choice', ...
from flask import Blueprint from flask import jsonify from shutil import copyfile, move from google.cloud import storage from google.cloud import bigquery import dataflow_pipeline.pyg.pyg_ofima_beam as pyg_ofima_beam import dataflow_pipeline.pyg.pyg_PUC_beam as pyg_PUC_beam import dataflow_pipeline.pyg.pyg_CeCo_beam as...
from django.contrib import admin from events.models import Events,Profile,CampusRepresantative # Register your models here. class EventAdmin(admin.ModelAdmin): model = Events list_display = ('EventName' ,'EventDescription','eventCost') class ProfileAdmin(admin.ModelAdmin): model = Profile list_display = ('Name',...
from sys import version_info import numpy as np print "enter the nuber of columns for first matrix" #m = input('enter the value for m:') #n = input('enter the value for n:') a=np.matrix([[1,2,3],[3,4,5],[5,2,1]]) b=np.matrix([[1,1,3],[6,4,5],[5,2,99]]) #matrix = m*n i=0 j=0 #a=10,10 for i in range(len(a)): for j in ra...
import pandas as pd import matplotlib.pyplot as plt import numpy as np dataset=pd.read_csv('Position_Salaries.csv') X=dataset.iloc[:,1:2].values Y=dataset.iloc[:,2].values from sklearn.preprocessing import PolynomialFeatures pl_reg=PolynomialFeatures(degree=4) X_poly=pl_reg.fit_transform(X) from sklear...