text
stringlengths
38
1.54M
# Kennesaw State University # College of Computing and Software Engineering # Department of Computer Science # CS 4308/W01 Concepts of Programming Languages # 2nd Project Deliverable: pparser.py # Jackson Randolph: jrando13@students.kennesaw.edu # July 2nd, 2020 import ply.yacc as yacc from scanner import Scanner from...
# # @lc app=leetcode id=154 lang=python3 # # [154] Find Minimum in Rotated Sorted Array II # # https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/description/ # # algorithms # Hard (41.60%) # Likes: 1168 # Dislikes: 245 # Total Accepted: 212.8K # Total Submissions: 511K # Testcase Example: '[1...
# -*- coding: utf-8 -*- """ @Time : 2020/8/27 10:36 @Author : QDY @FileName: 538. 把二叉搜索树转换为累加树.py @Software: PyCharm """ """ 给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater Tree), 使得每个节点的值是原来的节点值加上所有大于它的节点值之和。 """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # s...
from drf_writable_nested import WritableNestedModelSerializer from visitas.models import Visita from lugares.api.serializers import LugarSerializer class VisitaSerializer(WritableNestedModelSerializer): class Meta: model = Visita fields = ['id', 'usuario', 'luga...
#!/usr/bin/env python # coding=utf-8 ''' @author: Zuber @date: 2019/6/11 17:50 ''' import os import re import xlrd from main.common import FilePathUtil import xlwt proDir = FilePathUtil.getProjectRootDir() def get_xls(xlsPath, sheet_name): """ get interface data from xls file :return: """ cls ...
from flask import Flask, render_template from flask_bootstrap import Bootstrap # 引入必要的模块 app = Flask(__name__) bootstrap=Bootstrap(app) # 定义一个函数,它将响应并返回一个html描述的页面,这里我们是:sketch.html @app.route('/') def hello(): return render_template('login.html') if __name__ == '__main__': app.run(debug=True)...
import os import queue import traceback import numpy as np from utils import * from threading import Lock from threading import Thread from objects import * from h5py import File from os import listdir, walk from hashlib import sha256 num_threads = 12 files_per_thread = 8 video_file_name = 'images.h5py' metadata_file_...
from django.contrib.auth import get_user_model from django.contrib.auth.hashers import check_password from django.views.decorators.csrf import csrf_exempt from rest_framework.decorators import api_view from rest_framework import status from rest_framework.response import Response from .models import ChoresUser @csrf...
#!/usr/bin/env python from setuptools import setup, find_packages #from distutils.core import setup LONG_DESCRIPTION = \ '''Pooled parent project code''' with open('requirements.txt') as f: requirements = f.read().splitlines() setup( name='pooledparent', version='0.1.0', author='Harriet Dashnow', ...
from flask import Flask, request, render_template, url_for, session, redirect import os from urllib.request import urlopen from pathlib import Path import gc import numpy as np from copy import deepcopy import face_recognition import cv2 from shared import messages, flash from shared.db import Db from shared.storage i...
""" T. H. Cormen et. al. - Introduction to Algorithms, 3rd edition, ISBN 978-0262033848 Exercises 2.3-5 (p. 39) Referring back to the searching problem (see Exercise 2.1-3), observe that if the sequence A is sorted, we can check the midpoint of the sequence against and eliminate half of the sequence from further consi...
from collections import defaultdict import re import random from dawg import * letters = 'abcdefghijklmnopqrstuvwxyz' def closest(word): splitset = [(word[:x],word[x:]) for x in range(len(word)+1)] deleteset = [x+y[1:] for (x,y) in splitset if y] transposeset = [x+y[1]+y[0]+y[2:] for (x,y) in sp...
from scrapy.spiders import Spider from scrapy.selector import Selector from scrapy.spiders import CrawlSpider, Rule from scrapy.http import Request,FormRequest from scrapy.selector import HtmlXPathSelector from scrapy.selector import XmlXPathSelector from scrapy.linkextractors import LinkExtractor import json import re...
import jsonpickle from yv_verse import YvVerse from bs4 import BeautifulSoup import re jsonpickle.set_encoder_options('json', sort_keys=True, indent=2, ensure_ascii=False) from flask import Flask, request, jsonify # from flask_cors import CORS, cross_origin import boto3 dynamo = boto3.resource("dynamodb") # tbl = dy...
import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from learner import Learner from program_constants import * import pandas as pd def plot_accuracy(data_list, test_accuracy, timestamp, labels=None): if labels is None: labels = ["Training", "Validation"] x = np.array(range(NU...
import connexion import logging from swagger_server.models.entities import Entities from swagger_server.models.entity import Entity from swagger_server.models.source_entity import SourceEntity from swagger_server.models.upload_response import UploadResponse from datetime import date, datetime from typing import List, D...
import requests from bs4 import BeautifulSoup import validators import queue from crawler import Spoofer from threading import Thread """ Author: - Scot Matson Description: Basic web crawler that collects web pages for later parsing. Used to collect large data sets; to be used for lea...
import pandas as pd # Pandas import numpy as np # NumPy import talib.abstract as ta # TA-Lib import MetaTrader5 as mt5 # MetaTrader5 import yfinance as yf # Yahoo Finance import quandl # Quandl import datetime...
from django.db import models from django.contrib.auth.models import User # Create your models here. class BlogPost(models.Model): title = models.CharField(max_length=130) text = models.TextField() image = models.ImageField(null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) ...
from django import forms from trix.trix_core import models as trix_models class ManyToManyTagInputField(forms.CharField): def prepare_value(self, value): if value: if isinstance(value, str): tags = self.to_python(value) return ', '.join([tag.tag for tag in tag...
import sys import os import copy import json import numbers from hashlib import sha256 as H import random from collections import defaultdict from threading import Thread import time import nacl.encoding import nacl.signing import blockchain import utils import mergesplit_node import mergesplit_community import buildin...
def countArticles(fileName: str): count = [0, 0] with open(fileName) as ob: mainText = ob.read() mainText = mainText.split('\n') for i in mainText: for j in i.split(' '): print(j) if j.lower() == 'an': count[0] += 1 elif j.lower() == 't...
#!/usr/bin/python3 import io import sys import vcf as py_vcf import os import time import re from classes import * from utils import function as f from utils.parse_breakpoints import sv_3 sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)) import NaSV def print_vcf_header(): """Creat...
#This is a simple function made for creating fibonacci sequence from 1 to n #n is taken from user and passed into function #Fibonacci sequence is a sequence of number where each number is sum of previously occured two numbers def fibonacci(n): a=1 b=1 print("Fibonacci series starts ") print(a)...
import subprocess import glib import gobject import gtk import pdb import os from signal import SIGKILL class Service(object): def __init__(self,cmdline_array, stdout_cb = None, stderr_cb = None, hup_cb = None, data = None): self.p = None...
# encoding: utf8 """ 下单 """ import json import copy from hack12306 import constants from hack12306.order import TrainOrderAPI from hack12306.query import TrainInfoQueryAPI from hack12306.user import TrainUserAPI from hack12306.utils import (tomorrow, JSONEncoder, gen_old_passenge_tuple, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from conans import ConanFile, CMake, tools import os class FFTWConan(ConanFile): name = "fftw" version = "3.3.8" description = "C subroutine library for computing the Discrete Fourier Transform (DFT) in one or more dimensions" url = "https://github.com/bi...
#예외처리 try: #try 안에 있는 문장은 실행하는데 오류가 발생하면 print("나누기 전용 계산기입니다.") nums = [] nums.append(int(input("첫번째 숫자를 입력하세요 : "))) nums.append(int(input("첫번째 숫자를 입력하세요 : "))) #nums.append( int(nums[0]/nums[1])) #리스트 안에 값이 없을때 list index out print("{0}/{1} ={2}".format(nums[0], nums[1],nums[2])) ...
import random as rand import time def main(): print("║ ╠═╬═╣ -=- -= GUESS THE NUMBER! =- -=- ╠═╬═╣ ║\n") time.sleep(0.5) print("Welcome to the [GUESS THE NUMBER!]\n") time.sleep(0.5) print("Rules are simple!\n * Enter number corresponding ceiling of random number\n * Enter " ...
from sklearn.metrics import r2_score import pandas as pd pd.options.display.max_rows = 999 pd.options.display.max_columns = 999 pd.set_option("display.max_columns", None) import numpy as np from sklearn.base import BaseEstimator from sklearn.pipeline import Pipeline import os.path from rolldecayestimators.substitute_d...
# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incor...
#!/usr/bin/env python import sys import subprocess IMAGES = [ 'contrail-node-init', 'contrail-nodemgr', 'contrail-controller-config-api', 'contrail-controller-config-svcmonitor', 'contrail-controller-config-schema', 'contrail-controller-config-devicemgr', 'contrail-vrouter-kernel-init-dpdk...
import os # 上传文件优化,文件名安全的意思 from werkzeug.utils import secure_filename from flask import render_template, request, app, Flask # os.path.dirname(__file__)获取的是app.py文件的路径,也就是在项目根目录中,然后把它放在images文件夹中 UPLOAD_PATH = os.path.join(os.path.dirname(__file__), 'files') app = Flask(__name__,template_folder='.') # Flask上传文件的实现...
import numpy as np import pandas as pd import cv2 import re import glob import natsort from sklearn.utils import shuffle # Load drawings from the quickdraw/fashion dataset def load_drawings(base_path): categories = list(set([img.split('/')[-1].split('-')[0] for img in glob.glob(base_path + '*')])) X = [] C...
# Ejercicio 2 de Oscar Vasta # Creando funciones print('Creando Funciones') print('creamos la funcion carta_a()') def carta_a(alguien): return "Estimado "+alguien+" me dirijo a Ud. para solicitarle cotizacion de los siguientes materiales:" print('ahora dirigimos cartas a Juan, Pedro y Jose') B = carta_a('Juan') pr...
#!/usr/bin/python # # #A program to process the report file(grid view) from Envision reader/ICCB # #Longfei Wang # import csv import sys if len(sys.argv) < 2: print "Usage: python grid2list.py INPUT_FILE [OUTPUT_FILE]" sys.exit() else: inputfile = sys.argv[1] outputfile = sys.argv[2] if len(sys.argv)>2 else inpu...
import logging import os from logging.handlers import RotatingFileHandler from typing import Union, List import click from flask import Flask from flask.cli import with_appcontext from server.tasks import celery from server.admin import adm from server.babel import babel from server.database import db_session, init_d...
# Recursion : function calling itself is called recursion """" Program to print factorial of a number recursively. def func(): <-- | | (recursive call) | func() ---- """ def recursive_factorial(n): if n == 1: return n else: return n * recursive_f...
''' This script is for detection of light/bright objects in dark background. It does not work as intended yet. After running the script, double left click on any object you want to segment and press 'esc'. The double clicked pixel coordinates will be generated and it will start flood_fill algo using the pixel mer...
import torch import cupy as cp from torch.utils.dlpack import to_dlpack from torch.utils.dlpack import from_dlpack # for some reason the first cublas call always fails, so run a dummy cublas call on module load try: a = cp.random.rand(1,1) b = cp.random.rand(1,10) cp.dot(a,b) except Exception: pass fi...
def printPicnic(itemsDict,leftWidth,rightWidth): #function that takes in a dictinoary of information . print('PICNIC ITEMS'.center(leftWidth+rightWidth,'-')) for k,v in itemsDict.items(): print(k.ljust(leftWidth,'-')+str(v).rjust(rightWidth)) picnicItems = {'sandwiches':4,'apples':4,'cups':12,'cookies'...
def mergesort(a,b): ret = [] while len(a)>0 and len(b)>0: if a[0] <= b[0]: ret.append(a[0]) a.remove(a[0]) if a[0] >= b[0]: ret.append(b[0]) b.remove(b[0]) if len(a) == 0: ret += b if len(b) == 0: ret += a ...
from landlab.components import ChiFinder, FlowAccumulator from landlab.utils.flow__distance import calculate_flow__distance def _create_landlab_components( grid, chi_finder_kwds=None, flow_accumulator_kwds=None ): # run FlowAccumulator kwds = flow_accumulator_kwds or {} fa = FlowAccumulator(grid, **kw...
import csv from random import randint def boyCreate(): #Creates boys file atrributes=['Miser','Generous','Geek'] #(Name,Attractiveness,Intelligence,Budget,Type,Attractiveness Requirement) B=[('Boy'+str(i+1),randint(1,10),randint(1,10),randint(1,1000),atrributes[randint(0,2)],randint(1,10))for i in xrange(40)] wit...
#!/usr/bin/env python3 """This is the initial module to control the car.""" # import sys import time import pygame import serial from serial import Serial # Check number of the COM port after BT paring COMPORT = 'COM3' COMPORT = '/dev/rfcomm0' ser = serial.Serial('/dev/rfcomm0') # open serial port >>> print(ser.nam...
#!/usr/bin/env python import board import busio import adafruit_ssd1306 # parameters (pixel_width, pixel_height, interface, hardware_address) display = adafruit_ssd1306.SSD1306_I2C(128, 32, busio.I2C(board.SCL, board.SDA), addr=0x3c) # Clear previous pixels by fill(0), 0 means fill with 'off' black, fill(1) would fi...
import os import sys import pprint dirName = r"F:\\" extName = ".py" trace = 2 def tryPrint(arg): try: print arg except UnicodeEncodeError: print str(arg).encode() visited = set() allSize = [] for (thisDir, subsHere, filesHere) in os.walk(dirName): if trace: tryPrint(thisDir) thisDir...
import argparse import configparser import filecmp import getpass import glob import httplib2 import io import json import os import platform import string import subprocess import tempfile import textwrap import time import urllib import urllib2 import webbrowser from pathlib import Path from date...
def convert(unitFrom = None, unitTo = None): """ Basically this is a function that converts well known units in the same dimensions to another well known unit in that dimension. :param unitFrom: can be a None or str placeholder for testing what is available in the unit converter or the units that yo...
from http.server import BaseHTTPRequestHandler from os.path import dirname, abspath, join dir = dirname(abspath(__file__)) class handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header('Content-type','text/plain') self.end_headers() with open(joi...
#Copyright (c) 2008 Vincent Povirk # #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 limitation the rights to use, #copy, modify, merge, publish, distribu...
# -*- python -*- # ex: set syntax=python: # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # Temporarily a copy from branches_cfg.py until loading is done with correct # path from scripts/slave/slaves_...
import gym import neat import os import visualize import numpy as np # Алгоритм сам определяет сколько входов и сколько выходов требуется # пока работает только с дискретными входами спортзала """ gen - Номер енерации env - спортзал envs - []] - геномы ge = [] net - сеть nets = [] cart - ответ сети carts = [] - ...
from django.shortcuts import render, redirect from ajax_datatable.views import AjaxDatatableView from django.http import Http404, HttpResponseRedirect from django.contrib import messages from django_hosts.resolvers import reverse from myapp.models import Job, JobKeywords, Candidate, Company from myapp.forms import Can...
#!/usr/bin/python # -*- encoding: utf-8; py-indent-offset: 4 -*- # +------------------------------------------------------------------+ # | ____ _ _ __ __ _ __ | # | / ___| |__ ___ ___| | __ | \/ | |/ / | # | | | | '_ \ / _ \/ __| |/ /...
grid = [['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O', 'O', 'O', 'O', 'O', '.'], ['.', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ...
# ALGRORITHME DE HUFFMAN : COMPRESSION DE DONNEES def TableDeFrequence (texte): """ Construction d'une table de fréquences @ Entrée: un texte @ type: string @ Sortie: un dictionnaire qui pour chaque caractère présent dans le texte lui associe sa fréquence @ type: dict """ table={} ...
from openvino.inference_engine import IENetwork import cv2 import time import logging log = logging.getLogger('spyspace') class OpenVinoModel: """ Toolkit for Abstract OpenVINO model """ MODEL_FILE_NAME = None def __init__(self, vino_plugin=None, model_file_name=None): """ All the m...
class Solution: def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ largest_num = max(0, nums[0]) cur_sum = 0 for i in range(len(nums)): cur_sum = cur_sum + nums[i] largest_num = max(largest_num, cur_sum) ...
""" This is the main function to run any of the Python examples. """ import argparse from examples.cam_dme_serial_ssd_fd import user_test_cam_dme_ssd_fd from examples.cam_dme_serial_post_host_ssd_fd import user_test_cam_dme_post_host_ssd_fd from examples.cam_dme_serial_post_host_yolo import user_test_cam_dme_serial_yol...
from tkinter import * import database import manageclerk class Main: def __init__(self,id_): self.id = id_ obj = database.Manage() clerk = obj.getclerkbyid(id_) print(clerk) self.tk = Toplevel() self.tk.title("Edit Clerk") height = self.tk.w...
import gdb import re import sys def write(res): res = re.sub(r'([^<])(\b([a-zA-Z0-9_]+::)?~?[a-zA-Z0-9_\.@]+)( ?)\(', "\\1\033[36;1m\\2\033[0m\\4(", res) res = re.sub(r'([a-zA-Z0-9_#$]* ?)=', "\033[32m\\1\033[0m=", res) res = re.sub(r'^(#[0-9]+)', "\033[32m\\1\033[0m", res, 0, re.MULTILIN...
import math from cvxopt import solvers, matrix, spmatrix import numpy as np def qpSolver(P, q, G=None, h=None, A=None, b=None, initvals=None): if G is None and h is None and A is None and b is None: args = [matrix(P), matrix(q)] elif A is None and b is None: args = [matrix(P), matrix(q), matrix...
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import numpy as np import matplotlib.pyplot as mp import pandas as pd dataset = pd.read_csv(Dara.csv) X = dataset.iloc[:, :-1].values Y = dataset.iloc[:, 3].values from sklearn.preprocessing import Imputer imputer = Imputer(missing=""Na...
'''从尾巴遍历链表''' class Solution: # 返回从尾部到头部的列表值序列,例如[1,2,3] def __init__(self): self.res = [] def printListFromTailToHead(self, listNode): # write code here if listNode: self.printListFromTailToHead(listNode.next) self.res.append(listNode.val) re...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="rl", version="0.0.1", author="Evan Gui", author_email="evan176.gui@gmail.com", description=(""), keywords="...
from __future__ import unicode_literals from django.core.exceptions import ValidationError from django.db import models from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from core.models import Authored, Dated from feed.models ...
import pickle from buglocalization.dataset.neo4j_data_set import Neo4jConfiguration from buglocalization.metamodel.meta_model_uml import MetaModelUML from buglocalization.selfembedding.dictionary.node_self_embedding_word_ranking import \ load_file # Output path of the node self embedding dictionary: node_self_emb...
# -*- coding: utf-8 -*- """ Modulo per la gestione della pagina di creazione di un nuovo account. """ #= IMPORT ====================================================================== from twisted.web import server from src.account import (Account, get_error_message_name, get_error_message_password, ...
""" SendDataAction sends data via communication adapter """ import LingerActions.LingerBaseAction as lingerActions import LingerConstants class SendDataAction(lingerActions.LingerBaseAction): """Sends data via communication adapter""" def __init__(self, configuration): super(SendDataAction, self).__...
# Generated by Django 2.2 on 2020-04-13 17:08 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('coreapp', '0053_projectinvoice_discount_amount'), ] operations = [ migrations.RemoveField( model_...
from tempfile import mkdtemp TESTING = True DEBUG = True FLASK_ENV = 'development' FLASK_APP = 'wsgi.py' TEMPLATES_AUTO_RELOAD = True SESSION_FILE_DIR = mkdtemp() SESSION_PERMANENT = False SESSION_TYPE = "filesystem" SQLALCHEMY_DATABASE_URI = 'sqlite:///final.db' SQLALCHEMY_TRACK_MODIFICATIONS = True SQLALCHEMY_ECHO =...
from discord.ext import commands import discord, config, aiohttp from collections import Counter import random from io import BytesIO key = config.weeb auth = {"Authorization": "Wolke " + key, "User-Agent": "NekoBot/4.2.0"} class Reactions: """Reactions""" def __init__(self, bot): self.bot = ...
import FWCore.ParameterSet.Config as cms process = cms.Process("PROdTPA") process.load("Geometry.CaloEventSetup.CaloGeometry_cff") process.load("Geometry.CaloEventSetup.EcalTrigTowerConstituents_cfi") process.load("Geometry.CMSCommonData.cmsIdealGeometryXML_cfi") process.source = cms.Source("PoolSource", fileNa...
# coding: utf-8 import csv import time import h5py import os.path import numpy as np import datetime #from neo4j.v1 import GraphDatabase, basic_auth __PATH1__ = '../datasets/cifar10' __PATH2__ = '../graphfile' L=48 div=2 num="2h" NUM=200 def hammingDist(hashstr1, hashstr2): """Calculate the Hamming distance betwe...
import itertools import copy import math import numpy as np import pandas as pd from tqdm import tqdm import basicDeltaOperations as op ''' This code calculates a dictionary giving all possible isotopologues of a molecule and their concentrations, based on input infor...
# -*- coding:utf-8 -*- from django.core.management.base import BaseCommand from ...builders import EmployerBuilder, EmployeeBuilder from ... import constants class Command(BaseCommand): help = ''' Generates %i random employers and %i random employees. Each employer can have %i to %i job postings. ...
"""TestTask URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-base...
from django.contrib import admin from . models import Paciente,Medico,Medicamento admin.site.register(Paciente) admin.site.register(Medico) admin.site.register(Medicamento)
from dataclasses import dataclass from typing import Type from contact_shape_completion import scenes @dataclass() class EvaluationDetails: scene_type: Type[scenes.Scene] network: str method: str
# -*- coding: utf-8 -*- # import Image import os import string def test1(): str=u'中华人民共和国成立了' print str[0:3] def test2(): str='abcdef' str=string.replace(str,'bc','%%(meida_url)s%s'%'5678') print str return str def is_mobile(ua): ismobile=False keywords = ['Android', 'iPhone', 'iPod', 'iPad', 'Win...
from rest_framework import serializers from channelaudit.models import CaseProject from facesearch.serializers import FaceSearchSerializer from utils.serializers import SensetimeIDSerializer class CaseProjectSerializer(serializers.ModelSerializer): sensetimeId=SensetimeIDSerializer() class Meta: mode...
#!/usr/bin/python3 from typing import List import json from bplib.butil import TreeNode, arr2TreeNode, btreeconnect, aprint class SmallestInfiniteSet: def __init__(self): self.cur = 1 self.set = set() def popSmallest(self) -> int: if self.set: for s in self.set: ...
#https://www.hackerrank.com/challenges/day-of-the-programmer/submissions/code/101657900 #!/bin/python3 import math import os import random import re import sys # Complete the dayOfProgrammer function below. def dayOfProgrammer(year): if year > 1918: #Gregorian calendar if year % 4 == 0 and year...
# -*- coding: utf-8 -*- import os import tensorflow as tf import numpy as np import scipy.io import pdb import random import itertools from settings import gb from Create_model import * from scipy.ndimage.interpolation import zoom import nibabel as nib import time import ConfigParser def get_list(mode): filenames = [...
from __future__ import print_function __author__ = 'Bojan Delic <bojan@delic.in.rs>' __date__ = '02 January 2013' __copyright__ = 'Copyright (c) 2013 Bojan Delic' from samovar.commander import BaseCommand from samovar import utils class RepositoryNotFound(Exception): def __init__(self, name):...
''' a comtypes driven IE ''' class InternetExplorer(object): def __init__(self): from comtypes.client import CreateObject, GetEvents self.ie = CreateObject("InternetExplorer.Application") self.ie.Toolbar = False self.ie.StatusBar = False def Show(self, shown = True): s...
import numpy as np from collections import deque import math import pygame from pygame.locals import QUIT, MOUSEBUTTONUP class Nodes: def __init__(self,state): self.state = state self.cost = 19999 self.parent = None def coll_circle(position): p_x = position[1] p_y = position[0] location...
#! /usr/bin/python3 import sys import os f_name = 'InternalRule.txt' def address(file_name): table_add = [] table_ip=[] start1 = "firewall address" end1 = "end" nxt1 = "next" sig1='edit' sig4='subnet' wrd1='' wrd2='' file_cp = open(file_name) while True: read_l = file_cp.readline() if st...
# Escreva um programa que imprima os n primeiros número primos. Peça para o usuário informar o valor de n. def primo(x): for i in range (2,x): if x %i == 0: return False return True n = 100 x = 1 for i in range(n): while not primo(x): x=x+1 print(x) x=x+1
# Generated by Django 2.2.6 on 2019-12-16 08:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('biographies', '0006_bio_keywords'), ] operations = [ migrations.RenameField( model_name='bio', old_name='name', ...
# # convert to grayscale and save images # from PIL import Image image = Image.open('Sydney-Opera-House.jpeg') print(image.format) gs_image = image.convert(mode='L') gs_image.save('opera-gs.jpeg') image2 = Image.open('opera-gs.jpeg') print(image2.format) image2.show()
from django.db import models # Create your models here. from academics.models import Class, Subject, Exam from setup.models import School from student.models import Student from teacher.models import Teacher class OnlineTest(models.Model): school = models.ForeignKey(School, null=True) exam = models.ForeignKe...
from __future__ import unicode_literals import os dir_path = os.path.dirname(os.path.realpath(__file__)) def load_corpus(filename): """ :param filename: :return: """ corp = [] with open(os.path.join(dir_path, filename + ".txt")) as word_file: for line in word_file: line =...
__version__ = '0.0' try: __TGASTARS_SETUP__ except NameError: __TGASTARS_SETUP__ = False if not __TGASTARS_SETUP__: pass
#!/usr/bin/env python # coding: utf-8 # In[1]: import os import sys import random import gc import pickle import pandas as pd import numpy as np import matplotlib.pyplot as plt plt.style.use('seaborn-white') import seaborn as sns sns.set_style("white") get_ipython().run_line_magic('matplotlib', 'inline') from skl...
# coding: utf-8 import unittest from logger.accesschecker import AccessChecker class AccessCheckerTests(unittest.TestCase): def setUp(self): self.ac = AccessChecker( collection="scl", allowed_collections=lambda: [u"scl", u"arg"], acronym_to_issn_dict=lambda col: {u'zo...
################################ # Hi ! This is a lang tut tutorila for learing diffent langugae. # Uisng common CLI/API, you can learn tutorials easity # This is kind of cookbook. # We currently Support following tutorilas. # 1. Php # 2. perl # 3. python # 4. Rubi # 5. Java # 6. C # 7. C++ ############################...
""" This module provides Preparer classes to prepare the raw files and make them ready to be stored in the database. """ import numpy as np import pandas as pd def _types_to_native(values): """ Converts numpy types to native types. """ native_values = values.apply( lambda x: x.items() if isins...
import lang import enumerable import cact class Interpreter_CallMethod(lang.Interpreter): __slots__ = [ "method", "parameters" ] def __init__(self, method, parameters=None): super(Interpreter_CallMethod, self).__init__() self.method = method self.parameters = cact.default_list(param...