text
stringlengths
38
1.54M
# -*- coding: utf-8 -*- # Author: Mateo Inchaurrandieta <mateo.inchaurrandieta@gmail.com> '''EIS spectral cube definitions''' from __future__ import absolute_import import numpy as np from astropy.io import fits from astropy.nddata import StdDevUncertainty as sdu from sunpycube.cube.datacube import Cube from sunpyc...
#!/usr/bin/python3 #!-*-encoding:utf-8-*- import tkinter as tk from functools import partial def call_result(label_result, n1, n2): num1 = float((n1.get())) num2 = float((n2.get())) result = (num1)/(num2*num2) if result<=18.5: label_result.config(text="Vous êtes en souspoids.\n" ...
from itertools import cycle from collections import deque import json import urllib2 from pprint import pprint import time import csv from pprint import pprint from random import randint from instagram.client import InstagramAPI import sys class TokenGenerator: tokens = [] token_index = 0 def getToken(se...
#! /usr/bin/python3 def unswap(): Cliques = [[0, 1, 2, 3, 4, 5, 6, 7, 8], \ [9, 10, 11, 12, 13, 14, 15, 16, 17], \ [18, 19, 20, 21, 22, 23, 24, 25, 26], \ [27, 28, 29, 30, 31, 32, 33, 34, 35], [36, 37, 38, 39, 40, 41, 42, 43, 44], [45, 46, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipayOpenServicemarketOrderSyncModel(object): def __init__(self): self._actual_amount = None self._consumer_uid = None self._coupon_amount = None self._discount_a...
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ cur = ListNode(0) cur.next = head cur_ahead...
species( label = '[CH]=CO[CH2](574)', structure = SMILES('[CH]=CO[CH2]'), E0 = (291.144,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([3120,650,792.5,1650,3010,987.5,1337.5,450,1655,3000,3100,440,815,1455,1000,231.391],'cm^-1')), HinderedRotor(inertia=(0.578158,'amu*angstrom^2'), ...
# Datetime related imports from datetime import datetime from datetime import date from datetime import time from datetime import tzinfo # Django imports from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist from django.core.cache import cache from django.db.models.signals ...
import numpy as np import pandas as pd import sys import os import pickle import spacy import time def get_embedding(dataset, type_dataset, print_comment=False): """ Parameters : dataset : DataFrame type : String Returns embedding : List """ nlp=sp...
from eth.constants import ZERO_HASH32 from eth_typing import BLSPubkey import pytest from ssz.hashable_list import HashableList from ssz.sedes import List, uint64 from eth2.beacon.constants import ( DEPOSIT_CONTRACT_TREE_DEPTH, FAR_FUTURE_EPOCH, GENESIS_SLOT, GWEI_PER_ETH, JUSTIFICATION_BITS_LENGTH...
# coding: utf-8 """ dbt Cloud API v2 No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: 2.0.0a1 Contact: support@getdbt.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint im...
class Solution: def maxProfit(self, prices: List[int], fee: int) -> int: keep, sell = -prices[0], 0 for i in range(1, len(prices)): p = prices[i] keep, sell = max(keep, sell - p), max(keep + p - fee, sell) return max(keep, sell)
import pprint import json from jdcal import gcal2jd, jd2gcal from googleapiclient.discovery import build import datetime def get_news(actor, start_date, end_date): service = build("customsearch", "v1", developerKey="AIzaSyBdV1Emfi7Zd-T8_PQ1tr_Av7G4WuGpHOo") start_date_j = int(sum(gcal2jd(s...
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: linghanchujian import os,sys from scrapy.cmdline import execute def main(): sys.path.append(os.path.dirname(os.path.abspath(__file__))) execute(["scrapy","crawl","amazon_scrapy"]) pass if __name__ == '__main__': main()
import nltk from nltk.corpus import state_union from nltk.tokenize import PunktSentenceTokenizer train_text = state_union.raw("2005-GWBush.txt") sample_text = state_union.raw("2006-GWBush.txt") custom_sent_tokenizer = PunktSentenceTokenizer(train_text) tokenized = custom_sent_tokenizer.tokenize(sample_text) def pro...
import cv2 import numpy as np from math import sqrt from math import pow from copy import copy import os import colorsys img=cv2.imread("3.jpg",cv2.IMREAD_COLOR) Yellow={'min':(20,100,100),'max':(30, 255, 255)} Blue={'min':(50,100,100),'max':(100,255,255)} Brown={'min':(0,100,0),'max':(20,255,255)} ''' Yellow={'min':...
#!/usr/bin/python3 """This module contains the Base class""" import json import os class Base: """This class is the base of all other classes in this project""" __nb_objects = 0 def __init__(self, id=None): """This is the base level constructor""" if id is not None: self.id ...
def max_of_three(a,b,c): if a>b and a>c: return a elif b>c: return b else: return c print"Enter the numbers" first=int(raw_input()) second=int(raw_input()) third=int(raw_input()) ans=max_of_three(first,second,third) print "greatest number is :%d"%ans
import random import pickle import gzip import numpy as np import matplotlib.pyplot as plt def plot_image(image,a,h,j): plt.imshow(image.reshape(a,a),cmap='binary') plt.xticks([]) plt.yticks([]) plt.savefig('image/layer{}_{}.png'.format(h, j)) # plt.show() def normlize_image(image): min_value ...
from world.kumarpg.dicts.types_defs import types stats = { "earth": types["stat_dict"], "fire": types["stat_dict"], "air": types["stat_dict"], "water": types["stat_dict"], "void": types["stat_dict"] } earth_techniques = { "bulletproof": types["tech_dict"] } void_techniques = { "mana rush"...
from tkinter import * import pyttsx3 # import Jarvis import consolelog from PIL import ImageTk,Image root = Tk() def speak(): engine = pyttsx3.init() voices = engine.getProperty('voices') engine.setProperty('voice', voices[1].id) engine.say("Hello World ") engine.runAndWait() ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from io import StringIO import re import inspect from collections import namedtuple from format_strings import FormatStrings from evision_structures import evision_structrised_classes from typing import Optional ArgTypeInfo = namedtuple('ArgTypeInfo', ...
#!/usr/bin/env python3 """ This module contains the function dropout_create_layer. """ import tensorflow as tf def dropout_create_layer(prev, n, activation, keep_prob): """ Creates a layer of a neural network using dropout. prev is a tensor containing the output of the previous layer. n is the number ...
from django.contrib import admin from .models import Post # admin.site.register(Post) class PostyAdmina(admin.ModelAdmin): list_display = ('tytul', 'kategoria', 'data_utworzenia', 'data_publikacji', 'data_aktualizacji') prepopulated_fields = {'slug': ('tytul',)} list_filter = ('data_utworzenia', 'kategori...
"""SCons.Tool.ise Tool-specific initialization for Xilinx ISE """ import sys import platform import xilinx import xparseprops import scan_ise import SCons.Util import pprint from SCons.Script import * def chain_emitters(emitter_list): """ Returns an emitter function (closure) which applies every emitter in emi...
# *-* coding: utf-8 *-* import csv import collections import tempfile import traceback from django.http import HttpResponse def import_csv_data_to_model(file_obj, model, field_header_list): """ 导入csv数据到模型 :param file_obj: 文件对象 :param model: 模型 :param field_header_list: 字段表头部列表 :return: ""...
# Work space directory HOME_DIR = './' # Path to SALICON raw data pathToImages = '/home/users/jpang/salicon_data/images' pathToMaps = '/home/users/jpang/salicon_data/saliency' pathToFixationMaps = '/home/users/jpang/salicon_data/fixation' # Path to processed data pathOutputImages = '/home/users/jpang/lsun2016/data/sa...
from cloudant.client import CouchDB from datetime import datetime from random import random from injector import inject class CouchDBProvider(object): @inject def __init__(self, db_client: CouchDB, db_name): self.db_client = db_client self.db = self.db_client[db_name] self.db_name = d...
import unittest; from leetcode.Util.ArrayUtil import ArrayUtil from leetcode.QuickSort.QuickSort import QuickSort # https://leetcode-cn.com/problems/zigzag-conversion/description/ class QuickSortTest(unittest.TestCase): def test(self): testInput = ArrayUtil.getRandomArray(100, 100) print(testInpu...
import numpy as np import pandas as pd import cv2 from sklearn.svm import SVC face1=np.load('gop.npy').reshape(100,50*50*3) face2=np.load('shankar.npy').reshape(100,50*50*3) data=np.concatenate([face1,face2]) dataset=cv2.CascadeClassifier('hr.xml') labels=np.zeros((200,1)) labels[:100,:]=0.0 ...
from quantum_espresso_tools.symmetry import get_kpoint_grid from quantum_espresso_tools.parser import parse_vc_relax import numpy as np import numpy.linalg as la import os import subprocess # Conversion factors ANGSTROM_TO_BOHR = 1.88973 BOHR_TO_ANGSTROM = 0.529177 def default_parameters(): # Default pseudopot...
import random import string class CommonUtilities: @staticmethod def get_random_string(str_length: int = 10, str_type: string = string.ascii_lowercase, prefix: str = '') -> str: letters = str_type return prefix + ''.join(random.choice(letters) for i in range(str_leng...
class Cadena(): def __init__(self,cadena): self.cadena=cadena #___________________________________________________________________________________________________________ def recorrerCadena(self): print(':::::::::::::::::::::::::::::::::::::::::::::') print("Recorrer y presentar los ...
import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch_ros.actions import Node import launch_ros def generate_launch_description(): ld = LaunchDescription() duckiebot_urdf = os.path.join(get_package_share_directory('duckiebot_interfa...
from flask import Flask from views import api from models import db app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///C:/jprojects/web_projects/flask_api/app/api.db' app.config['DEBUG'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False if __name__ == '__main__': db.init_app(app...
import tensorflow as tf print("tf version=",tf.__version__) import sklearn assert sklearn.__version__ >= "0.20" import numpy as np from tensorflow import keras print("Keras version=",keras.__version__) import matplotlib as mpl import matplotlib.pyplot as plt import os from sklearn.datasets import fetch_californi...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import redirect from django.urls import reverse from django.shortcuts import render, HttpResponseRedirect from django.contrib.auth import ( authenticate, get_user_model, login, logout ) from .forms import UserLog...
from django.contrib import admin from app_calendar.models import Event, User, Country, Holiday admin.site.register(User) admin.site.register(Event) admin.site.register(Country) admin.site.register(Holiday) # Register your models here.
""" Задание 3: Определить, какое число в массиве встречается чаще всего. План такой. Сворачиваем до уникальных значенй в массиве. В этом нам поможет множество set(a) Пробегаемся по множеству и считаем сколько раз цифра встречается в исходном массиве a.count(n) """ a = [1, 2, 1, 3, 34, 1, 5, 2, 1, 2, 6, 2, 2, 2, 2, 3]...
# -*- coding: utf-8 -*- import pymysql import configparser import os class MysqlClient(object): def __init__(self, host, user, password, database): self.conn = pymysql.connect(host=host, user=user, password=password, database=database) @classmethod def from_settings(cls, conf_dir): conf_...
''' Created on 2013-04-17 @author: jyeung, apfejes ''' import os import sys import time import rpy2.robjects as robjects from rpy2.robjects.packages import importr import argparse _cur_dir = os.path.dirname(os.path.realpath(__file__)) # where the current file is _root_dir = os.path.dirname(_cur_dir) sys.path.inse...
# -*- coding: utf-8 -*- import array import sys if sys.version_info[0] <= 2: range = xrange ARRAY_DATATYPE = b'l' else: ARRAY_DATATYPE = 'l' def sample(pixels): top_two_bits = 0b11000000 sides = 1 << 2 # Left by the number of bits used. cubes = sides ** 7 samples = array.array(ARRAY_D...
"""This is basic perceptron program which is used for binary classification""" import random class perceptron(object): """This perceptron class which is very basic neural network""" def __init__(self): """This is initialization of variables""" self.inputs = [] self.TrainigInpu...
from collections import Counter from dataclasses import field, dataclass from datetime import datetime from typing import Optional from guniparse.log_entry import LogEntry from guniparse.utils import size_fmt @dataclass class Stats: requests: int = 0 # total number of requests reqs_per_sec: float = 0 st...
# Generated by Django 2.1 on 2018-10-20 15:30 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app_noticias', '0005_auto_20181020_1228'), ] operations = [ migrations.AlterField( model_name='noticia', name='destaqu...
class IP4: def validIPAddress(self, IP): ip4 = IP.split(".") if len(ip4) == 4: for num in ip4: try: # if not (num[0].isdigit() and int(num) < 256 and (num[0] != "0" or num == "0") and num[-1].isdigit()): if not (str(num).isdigit() ...
import os from app.utilities.data import Prefab from app.resources.base_catalog import ManifestCatalog from app.constants import COLORKEY class Palette(Prefab): def __init__(self, nid): self.nid = nid # Mapping of color indices to true colors # Color indices are generally (0, 1) -> (240, 1...
""" The BinaryTree class for Lab 7. """ from typing import Any class BinaryTree: """ A class representing a BinaryTree. value - The value of the BinaryTree's root left - The root node of this BinaryTree's left subtree. right - The root node of this BinaryTree's right subtree. """ value: A...
from .models import Setting def savva(): result = Setting.objects.all() settings={} for item in result: settings[item.key]=item.value return settings sttngs=savva()
def bisection_iter(n, arr): start = 0 stop = len(arr)-1 while start <= stop: mid = (start + stop)//2 if n == arr[mid]: return f"{n} found at index: {mid}" elif n > arr[mid]: start = mid + 1 else: stop = mid - 1 return f"{n} not found in...
from flask import Blueprint, request, jsonify from DatabaseAccess import DataAccess from werkzeug.security import check_password_hash, generate_password_hash bp = Blueprint('users', __name__, url_prefix='/users') @bp.route('/create', methods=['POST']) def create(): email = request.form.get('email') name = req...
def binary(num): if num>1: binary(num//2) print(num%2,end="") if __name__=="__main__": print() binary(11)
# -*- coding: utf-8 -*- import binascii import nfc import time from threading import Thread, Timer import pprint import json import requests import datetime import sys from pyfiglet import Figlet # タッチされたあとの次の待受時間 TIME_WAIT = 5 SLACK_API_URL = 'https://ancient-woodland-85036.herokuapp.com/raspi' FLASK_API_URL = 'sum...
# 给程序传递参数 import sys def a(num): print(num) def b(num): print(num) a(100) print(sys.argv) # 值为["xxx.py"] if sys.argv[1] == a: # 这里的a就是外部给程序传递的参数 b(12) # 交互模式下用python3 xxx.py 参数(多个参数空格隔开) # 所传递的参数会保存在sys.argv这个列表中
from tkinter import * def on_move(event): component=event.widget locx, locy = component.winfo_x(), component.winfo_y() w , h =master.winfo_width(),master.winfo_height() xpos=(locx+event.x) ypos=(locy+event.y) if xpos>=0 and ypos>=0 and w-abs(xpos)>=0 and h-abs(ypos)>=0 and xpos<=w-125 and ypos<...
from flask import Flask # from .settings import config # from .extensions import extension_init from .views import blueprint_register def create_app(): app = Flask(__name__) # 加载配置 # app.config.from_object(config["default"]) # 初始化app函数 # extension_init(app) # 蓝本注册函数 blueprint_register(a...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from __future__ import print_function import os import sys import subprocess import platform def build(binfolder, options=''): cwd = os.getcwd() # create build dir if not os.path.isdir(binfolder): os.mkdir(binfolder) os.chdir(binfolder) # cma...
import math from collections import deque import numpy as np import heapq as heap from slapstack.core_state import State from slapstack.core_state_agv_manager import AGV from slapstack.core_state_location_manager import LocationManager from slapstack.helpers import faster_deepcopy, StorageKeys, VehicleKeys, \ Batc...
#a. Create 3 list wiht numbers and maxlist by taking max elem from each list def list_manip(): l1 = [1,2,3,4,5] l2 = [12,23,34,45,56] l3 = [67,78,89,90,98] lmax = [] l1.sort() l2.sort() l3.sort() print("list are: ", l1,l2,l3) lmax.append(max(l1)) lmax.append(max(l2)) lmax.append(max(l3)) lma...
#!/usr/bin/python #coding=utf-8 import sys from waveLength import * nFiles = len(sys.argv) print waveLength.__doc__ for i in range(1, nFiles): wl = waveLength( sys.argv[i] ) wl.fitGraph() wl.getWaveLen() # wl.saveToEps() # wl.showGraph()
from django.shortcuts import render from .models import student_info # Create your views here. def display(request): stud_list=student_info.objects.all() my_dict={'student':stud_list} return render(request,'studentinfoapp/studentinfo.html',{'student':stud_list})
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-03-11 09:59 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('my_app', '0002_author_user_link'), ] operations = [ migrations.RemoveField( ...
import matplotlib matplotlib.use("TkAgg") # set the backend import matplotlib.pyplot as plt plt.figure() plt.plot([0,1,2,0,1,2]) # draw something plt.show(block=False) plt.get_current_fig_manager().window.wm_geometry("+600+800") # move the window
from mlab import mlab_connect from models.information import Service, Game from faker import Faker from random import choice, randint mlab_connect() service = Service( name=Faker().name(), occupied=choice([True,False]), fav_lane=choice(['top','mid','bot','jung']), credit=randint(1,5) ) service.save()...
import os import pandas as pd import sys import json import chardet from constants import COUNTRY_DICT import numpy as np import copy from collections import defaultdict file_prefix = "installs_com.cuelearn.cuemathapp_" class DailyGoogleUpdates: def __init__(self,dt): self.dt = dt self.get_data(dt) self.df_ove...
#!/usr/bin/env python3 # https://gist.github.com/lilydjwg/69111965e237fdb67d1378703173709f import sys import re import pyalpm def name_part(x): return re.match('^[\w.-]+', x).group() def main(names): h = pyalpm.Handle('/', '/var/lib/pacman') ldb = h.get_localdb() pkgs = ldb.pkgcache needs_explicit = set(...
# Copyright (c) 2012-2021, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from typing import Optional from .aws import Action as BaseAction from .aws import BaseARN service_name = "Amazon Lightsail" prefix = "lightsail" class Action(BaseAction): def __init__(self, actio...
import os, cv2 import numpy as np from sklearn.utils import shuffle from sklearn.preprocessing import LabelBinarizer from keras.models import Sequential from keras.layers.core import Dense, Activation, Flatten, Dropout from keras.layers import Conv2D, MaxPooling2D from keras.regularizers import l2 # scale images d...
#lambda를 활용하는 경우 (2) #g(x,y)함수를 define 하지 않고 사용하는 경우 def f(g, a, b): return g(a,b) print(f(lambda x,y: x*y, 20,10))
people = int(input("enter the number of people")) cats = int(input("enter the number of cats")) dogs = int(input("enter the number of dogs")) if people<cats: print("Too many cats! The world is doomed") elif people>cats: print("Not many cats! The world is saved") elif people>dogs: print("The world is Dry") elif peopl...
# coding:utf-8 import datetime as dt """ 日付関連の共通処理を定義する """ class DateHelper: # 日付フォーマット:ymd format_ymd = '%Y%m%d' # 日付フォーマット:hm format_hm = '%H%M' # 日付フォーマット:ymd_hm format_ymd_hm = '%Y%m%d%H%M' # 日付フォーマット:ymd_hms format_ymd_hms = '%Y%m%d%H%M%S' @staticmethod def get_date_list(...
from django.shortcuts import render from rest_framework import viewsets from .models import User from .serializers import UserSerializer from rest_framework .decorators import api_view from rest_framework.response import Response from django.contrib.auth import authenticate from rest_framework import status from django...
from django import forms from .models import * from django.contrib.auth.forms import AuthenticationForm from django.db import models from django.forms.widgets import PasswordInput, TextInput import collections from django.forms import * allWidget = { 'name': TextInput(attrs={'class': 'mdl-textfield__input', 'place...
from binascii import hexlify as hx, unhexlify as uhx from nsz.Fs.File import File from nsz.Fs.File import BaseFile from nsz.Fs.Hfs0 import Hfs0 from nsz.Fs.Hfs0 import Hfs0Stream import os import re from nsz.nut import Print MEDIA_SIZE = 0x200 class XciStream(BaseFile): def __init__(self, path = None, mode = 'wb', ...
import os import sys import traceback import shutil from praatio import tgio from montreal_forced_aligner.multiprocessing.corpus import parse_transcription from montreal_forced_aligner.corpus.align_corpus import AlignableCorpus from montreal_forced_aligner.helper import load_text from montreal_forced_aligner.config.g...
# Classes Documentation : https://docs.python.org/3/tutorial/classes.html import sys import io # 클래스 변수, 인스턴스 변수 class NameTest: total = 0 print(dir()) print('before : ', NameTest.__dict__) NameTest.total = 1 print('after : ', NameTest.__dict__) n1 = NameTest() n2 = NameTest() print(id(n1), ' vs ', id(n2)) pri...
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import QMessageBox, QTableWidgetItem, QPushButton, QHBoxLayout, QWidget import main_menu, app, add_member_page, Table_widget from pymongo import MongoClient import socket, csv, os def check_connection(): try: socket.create_connection(('Google...
#https://adventofcode.com/2019/day/14 import math import re def clean_input(path = "./input.txt"): input_f = open(path).readlines() arr = [re.split(" => |, ",line.strip()) for line in input_f] production = dict() for formula in arr: requirements_dict = dict() for item in formula[:-1]: ...
# The script MUST contain a function named azureml_main # which is the entry point for this module. # imports up here can be used to import requests import json import re import pandas as pd API_ENDPOINT = '<YOUR API ENDPOINT>' headers = {'content-type': 'application/json'} # The entry point function MUST have two ...
def partitionDisjoint1(A): # 一个一个比 太慢 """ :type A: List[int] :rtype: int """ for i in range(A.__len__()): black_flag = 0 left = A[: i + 1] right = A[i + 1:] for rnum in right: for lnum in left: if lnum > rnum: b...
# -*- coding: utf-8 -*- #/usr/bin/python3 from __future__ import print_function from utils import load_spectrograms,wav2world,world_features_to_one_tensor import os import numpy as np from hyperparams import Hyperparams as hp import tqdm if not os.path.exists("mels"): os.mkdir("mels") if not os.path.exists("worlds")...
""" Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this ...
varOne=int(input()) varTwo=int(input()) varThree=int(input()) if varOne > varTwo and varOne > varThree: print("I am varone") elif varTwo > varThree: print("i am vartwo") else: print("i am varthree")
from pgtemplate import * import pygame import random import time LINECOLOR = (20, 20, 20) ALIVECOLOR = (0, 255, 0) ROWS = 10 COLS = 10 UPDATEAFTER = 1 class Cell(object): def __init__(self, row, col): self.row = row self.col = col self.alive = False self.future = None class GO...
import os TG_API_TOKEN = os.getenv('TG_API_TOKEN') DEBUG = True HOST = '0.0.0.0' PORT = '5000' MAIN_CONTAINER_URL = 'https://4e45df91cfc1.ngrok.io/api'
# -*- coding: utf-8 -*- # Copyright © 2012-2014 by its contributors. See AUTHORS for details. # Distributed under the MIT/X11 software license, see the accompanying # file LICENSE or http://www.opensource.org/licenses/mit-license.php. # Python standard library, unit-testing import unittest # Scenario unit-testing fro...
# -*- coding: utf-8 -*- import urllib.request def clear(): time.sleep(3) OS=platform.system() if (OS==u"Windows"): os.system("cls") else: os.system("clear") def link(): url="http://www.baidu.com" try: res=urllib.request.urlopen(url) except Exception: print(...
# -*- coding: utf-8 -*- # # This file is part of the RoseNMS # # Copyright (C) 2013-2016 Craig Small <csmall@enc.com.au> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the...
from .setting import * from .menu import * from .page import * from .file_object import * from .inner_link import * from .cathedra import * from .staff import * from .direction import * from .schedule import * from .news import * from .announcement import * from .certificate import *
test_input = '{{4,2,3},{3},{2,3,4,1},{2,3}}' def solution(s): input_arr = s.split("},") tuple_map = [] answer = [] for i in input_arr: i = i.replace('{','').replace('}','') temp_arr = i.split(",") tuple_map.append(temp_arr) tuple_map.sort(key=len) for i in tuple_map: ...
#!/usr/bin/python import package.pkg1 import package.pkg2 def run(): print __name__+":"+run.__name__ package.pkg1.run() package.pkg2.run() print __name__, " imported"#this print when import but only at the first time it imported. if __name__=="__main__": print "This print when execute the module but n...
''' создать за 1 цикл кв. матрицу (выше гл. диаг = *, ниже #, на диаг. @) ''' N = 5 a = [0]*N for i in range(N): a[i] = ['*']*i + ['@'] + ['#']*(N-i-1) for row in a: print(row)
class Node: def __init__(self): # constructor self.data = None self.next = None def set_data(self, data): #method for setting the data field of the Node self.data = data def get_data(self,data): #method for getting the data field of the Node ...
import cv2 as cv img = cv.imread('../images/u=3126408186,2598873524&fm=15&gp=0.jpg') # 图像的形状 print(img.shape) """ (400, 400, 3) """ # 像素总数 print(img.size) """ 480000 """ # 图像数据类型 print(img.dtype) """ uint8 """
string=input("Enter Whatever You Want") a={} countchar=0 def abc(string): string=string.lower() x=97 i=0 while i<26: countchar=string.count(chr(x)) if countchar > 0: a[chr(x)]=countchar i=i+1 countchar=0 x=x+1 sortedDict= sorted(a...
from pathlib import Path import unittest import os from work_muxixyz_app import create_app,db from flask import current_app,url_for,jsonify from flask_sqlalchemy import SQLAlchemy from work_muxixyz_app.models import Team,Group,User,Project,Message,Statu,File,Comment import random import json # db=SQLAlchemy() class B...
class Solution(object): def rob(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) if n == 0: return 0 if n <= 2: return max(nums) dp = [[0, 0] for _ in xrange(n)] dp[0][0] = nums[0] ...
from entity.object.building.commerce.Bank import Bank from utils.beauty_print import bcolors from game.Event import Event from utils.common import GOVERNMENT, line, log_error, modes, prim_opt from game.Board import Board from game.Category import Category from entity.livingbeing.person.Person import Person from entit...
import numpy as np from image_tools import * import pylab as pl from scipy.signal import convolve2d """Generates 500 16 x 16 pixel image patches from the image data base, 500 16 x 16 pixel white noise patches, 500 16 x 16 pixel patches of filtered noise and normalizes each set.""" numberPatches = 500 patchSize = 16 ...
import requests from bs4 import BeautifulSoup import nltk import sqlite3 import time import traceback num_of_volumes = 557 base_search_url = 'http://caselaw.findlaw.com/court/us-supreme-court/volume/{0}' def prep_db(): with sqlite3.connect('scotus.db') as conn: conn.execute('CREATE TABLE IF NOT EXISTS inf...