text
stringlengths
38
1.54M
# -*- coding: cp1252 -*- # Importing Libraries import xmlrpc.client as xmlrpclib import urllib.request import csv import base64 import time print( """ +-----------------------------------------------------------------+ | | | ODOO BASE...
import socket import ipaddress import re import threading DEFAULT_BUF_SIZE = 2048 SERVER_IP = '127.0.0.1' LOCAL_IP = '127.0.0.1' SERVER_PORT = 23333 TCP_PORT = 23335 server_address = (SERVER_IP, SERVER_PORT) class User: def __init__(self, ip, port, name): # ip: int self.ip = ip self.port ...
#!/usr/bin/env python # # Copyright (C) Andrei Belov # Copyright (C) Nginx, Inc. # import logging, logging.config import os, re, sys, ConfigParser import json import base64 from time import sleep, time from urllib2 import Request, urlopen, URLError, HTTPError from daemon import runner import traceback NEWRELIC_API_UR...
from django.shortcuts import render from .models import QuesAns def add_show(request): ques_data = QuesAns.all() return render(request,'forms.html' ,{'QuesAns':ques_data}) # Create your views here.
from bs4 import BeautifulSoup from operator import attrgetter ''' TODO argument support --input --output ''' nodes = [] edges = [] full = "" with open('nodes', 'r') as nodefile: data=nodefile.read() pn = BeautifulSoup(data, "xml") # parse nodes for node in pn.find_all("node"): nodes.ap...
import re from io import StringIO from unittest import TestCase from output_writer.formatted_writer import FormattedWriter from packets.raw import RAW from packets.visitors.first_verbosity_visitor import FirstVerbosityVisitor from packets.visitors.second_verbosity_visitor import SecondVerbosityVisitor from packets.vis...
from unittest.mock import patch from tests.test_data import client from libs.user_helper import save_and_confirm_user from models.client.client import ClientModel from tests.base_test import BaseTest from libs.strings import gettext class TokenRefreshTest(BaseTest): """Test refresh token endpoint""" @patch('...
# -*- coding: utf8 -*- class Xrange(object): #конструктор def __init__(self, *args): if(len(args) == 0): raise TypeError("Xrange requires 1-3 int arguments") elif(len(args)>3): raise TypeError("Xrange can take no more than 3 int values as parameters") else: ...
# This file is part of the pyMOR project (http://www.pymor.org). # Copyright 2013-2016 pyMOR developers and contributors. All rights reserved. # License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) from pymor.core.interfaces import BasicInterface class RemoteObjectManager(BasicInterface): ...
""" matrixChainMultiplication """ def printParenthesis(m,j,i): if j==i: print(chr(65+j),end="") return else: print("(",end="") printParenthesis(m,m[j][i]-1,i) printParenthesis(m,j,m[j][i]) print(")",end="") def matrixChainMultiplication(arr): if arr is None: return None n=len(arr) noOfMatrix=(n-1) ...
import pygame class Door: def __init__(self, x, y): self.x = x self.y = y # Kích thước cửa (door) 60 x 60 px sprite = pygame.image.load("sprites/door.png") self.image = pygame.transform.scale(sprite, (80, 80)) class Robot: def __init__(self, x, y, x_heading, y_heading, ...
# sheyda zarandi - linear SVM import numpy as np from tools import getData import pickle from sklearn.metrics import accuracy_score class SVM(): """ functions: get_digits: to categories train set into 10 groups corresponding to the 10 digits we have get_Q: to calculate projection we need to cal...
import requests from django.conf import settings import json from django.contrib.auth import get_user_model """ This module assumes you are using a Custom User type model inherited from AbstractUserModel These are shopify functions that will be inserted into the Custom user model """ shop_url = settings.SHOPIFY_STORE ...
import pytest from homework2.http_request.address.address import Address class TestAddress: def setup(self): self.address = Address() self.user_id = "zhangsan00123" self.name = "张三" self.mobile = "+86 13811112222" self.department = [1] self.useridlist = ["lisi001",...
from app import db from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, BigInteger, Index, VARCHAR, Boolean class Book(db.Model): __tablename__ = "pic_table" id = Column(BigInteger(), primary_key=True) name = Column(VA...
import os import sys import cv2 import numpy as np from sklearn.cluster import MiniBatchKMeans import math from cPickle import dump, HIGHEST_PROTOCOL,load from scipy.cluster.vq import vq,kmeans import matplotlib.pyplot as plt def get_immediate_subdirectories(dir): """ this function return the immediate subdirectory...
import os import numpy as np g = [ [5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5], [0, 0, 0, 0, 8, ...
# Generated by Django 2.1.2 on 2018-10-07 09:02 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('wallet', '0001_initial'), ] operations = [ migrations.AlterField( model_name='historyoperations', name='successful_c...
# Referensi: # Implementasi algoritma Z berdasarkan referensi paper [2] dan [6] from typing import List, Optional def konstruksi_z_values(S: str): n = len(S) Z = [0 for _ in range(n)] L, R = 0, 0 for k in range(1, n): if k > R: L, R = k, k while R < n and S[R-L] == S[R]...
import sys if sys.version_info[0] < 3: raise Exception("Python 3.x is required to run SHIMON.") from waitress import serve from SHIMON.app import App def run(app: App) -> None: print(f"starting SHIMON v{app.shimon.VERSION} -> github.com/dosisod/SHIMON\n") try: serve( app.app, ...
""" 置信区间 期望(均值/u) 标准差=均方差 区间估计可信度更高 参考 https://www.zhihu.com/question/26419030 Z校验值 Z P值 差异程度 >2.58 <0.01 非常显著 >1.96 <0.05 显著 <1.96 >0.05 不显著 """ import math # 两组的平均数都是70,但A组的标准差约为17.08分,B组的标准差约为2.16分,说明A组学生之间的差距要比B组学生之间的差距大得多 a = [95, 85, 75, 65, 55, 45] b = [73, 72, 71, 69, 68, 67] def avg(data): s =...
import click import pytest from easyci.utils import decorators @click.command() @click.pass_context @decorators.print_markers def passing_command(ctx): click.echo('Passing command with context') @click.command() @click.pass_context @decorators.print_markers def failing_command(ctx): raise Exception @clic...
#!/usr/bin/env python3 # -*- encoding: utf-8; py-indent-offset: 4 -*- # +------------------------------------------------------------------+ # | ____ _ _ __ __ _ __ | # | / ___| |__ ___ ___| | __ | \/ | |/ / | # | | | | '_ \ / _ \/ __|...
# 转圈打印矩阵 # 【题目】 给定一个整型矩阵matrix,请按照转圈的方式打印它。 # 例如: 1 2 3 4 # 5 6 7 8 # 9 10 11 12 # 13 14 15 16 # 打印结果为:1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10 # 【要求】 额外空间复杂度为O(1)。 """ 思路: 建立两个坐标点 左上角A坐标为(tR, tC) 右下角B坐标为(dR, dC) 先打印A点数值 然后tC+=1 一直到tC=dC 然后tR+=1 一直打印到tR=dR 然后tC-=1 一直打印...
import numpy as np import cv2 from RedMask2 import * #cv2.imshow("combo",mask_images(img6)[1]) def crop_image(img): aMask = mask_images(img)[1] contours, hier = cv2.findContours(aMask,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE) for i,cnt in enumerate(contours): if i==0: bigcnt=cnt ...
# Generated by Django 3.1a1 on 2020-05-26 13:23 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('landing', '0005_houses_image'), ] operations = [ migrations.AddField( model_name='houses', name='geo', f...
import random import matplotlib.pyplot as plt import pandas as pd values = [random.gauss(5,2) for i in range(10)] df = pd.DataFrame(columns=['data']) for i in range(10): df = df.append({'data': values[i]}, ignore_index=True) df.to_excel('./data.xlsx', sheet_name='data', index=False) plt.plot(values) print("su...
#------------------------------------------------------------------------------- # Name: module1 # Purpose: python translation of audio_downloader.js # # Author: User # # Created: 12/03/2015 # Copyright: (c) User 2015 # Licence: <your licence> #----------------------------------------------------...
import argparse import os import logging import pickle from random import randrange from statistics import mode import pandas as pd from utils.mediapipe import MediapipeManager from utils import structuring MODEL_BINARY_FILE = "knnclassifier_file" OUTPUT_PATH = os.getcwd() + "/data/" def start_predict(video_path, k_...
# Librerias Future from __future__ import unicode_literals # Librerias Django from django.core.mail import EmailMessage from django.shortcuts import HttpResponse, render from django.template.loader import render_to_string from django.views.generic import DetailView, ListView # Librerias de terceros from apps.base.mod...
import demjson from django.db import models class RestModelManager(models.Manager): def serialize(self, fields): result = [obj.serialize(fields, safe = True) for obj in self.get_query_set()] return demjson.encode(result) class RestModel(models.Model): serialize_name = '' objects = RestMod...
# -*- coding: utf-8 -*- """ Created on Fri Nov 3 14:51:58 2017 @author: LAC40641 """ import numpy as np from sklearn import datasets from sklearn import tree from sklearn.tree import _tree def tree_to_code(tree, feature_names): ''' Outputs a decision tree model as a Python function Parameters...
import sqlite3 from fulcrum import Fulcrum conn = sqlite3.connect('photodb') cur = conn.cursor() formid = '' fulcrum = Fulcrum(key='') print("Starting to Sync photos") for (photo_id, filename, lat, lon, alt, created_on, uploaded, speed) in cur.execute('SELECT * FROM photos WHERE uploaded=0'): photo = fulcrum.photo...
from APIgen.main import main as genApi import subprocess import os def runBash(cmd): """Runs a bash command and returns the output""" process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) out = process.stdout.read().strip() return out def createAPI(app): buildir = app.env.srcdir outdir = os...
import time import socket import logging import os, sys sys.path.append(os.path.abspath(os.path.join(os.getcwd(), os.pardir))) from static import constants RAIL_INSTRUCTIONS = {'move' : '0\n', 'calibrate' : '1\n', 'zero' : '2\n', 'stop' : '3\n', 'disconnect' : '4\n'} PORT = 12345 BUFFER_LENGTH ...
#!/usr/bin/env python3 # See LICENSE file for copyright and license details. """ MIDI listener daemon for the Caller Station """ from subprocess import Popen import mido from config import (device_name) def make_call(): # DISPLAY=:0 xdotool key 1 2 3 Return print('Popping the mechanical turk') Popen(['x...
# Generated by Django 3.2.5 on 2021-09-06 10:37 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('web_calculator', '0024_alter_pageobjects_content'), ] operations = [ migrations.AddField( model_nam...
# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # # # @param root TreeNode类 the root of binary tree # @return int整型二维数组 # class Solution: def rec(self,root,flag): if root!=None: if flag==1: tmp = [root...
import torch from .mlm import mask_tokens class DefaultDataCollator: """ Default Data Collator Attributes: tokenizer: Tokenizer for text tokenization. max_length: The maximum length of the sequence. """ def __init__(self, tokenizer, max_length=None): self.tokenizer = toke...
import asyncio import json import os from concurrent.futures.thread import ThreadPoolExecutor from typing import Optional import aiofiles import aiojobs from Bio import Entrez from rich.console import Console from virtool_cli.utils import get_otu_paths, NCBI_REQUEST_INTERVAL async def taxid(src: str, force_update: ...
#!/usr/bin/python -tt # TODO: # - JSON body for GET requests """Client for talking to a RESTful server. Maybe just even a regular web server.""" from collections import namedtuple import Cookie import base64 import dbg import hashlib import os import re import socket import sys import time import urllib import urlp...
import pygame from pygame.locals import * from pytmx import load_pygame import os import random import math from gametext import GameText # Global configuration options SCREENSIZE = [352, 375]#[960, 540] FPS = 30 TITLE = "Oh Mummy" SHOW_MOUSE = True CURRE...
#!/usr/bin/env python from PyQt4 import QtCore, QtGui class StateSwitchEvent(QtCore.QEvent): StateSwitchType = QtCore.QEvent.User + 256 def __init__(self, rand=0): super(StateSwitchEvent, self).__init__(StateSwitchEvent.StateSwitchType) self.m_rand = rand def rand(self): retur...
from options.test_options import TestOptions from data import DataLoader from models import create_model from util.writer import Writer def run_test(epoch=-1): print('Running Test') opt = TestOptions().parse() opt.dataroot = "datasets/human_seg" opt.name = "human_seg" opt.arch ="meshunet" opt....
#!/usr/bin/env python #-*- coding=utf-8 -*- __author__ = '95' import time, sys, Queue from multiprocessing.managers import BaseManager class QueueManager(BaseManager): pass def start_device_status_client(): QueueManager.register('get_device_status_queue') server_addr = '127.0.0.1' client = QueueManager(...
"""Sphinx configuration.""" project = "{{cookiecutter.friendly_name}}" author = "{{cookiecutter.author}}" copyright = "{{cookiecutter.copyright_year}}, {{cookiecutter.author}}" extensions = [ "sphinx.ext.autodoc", "sphinx.ext.napoleon", "sphinx_click", "myst_parser", ] autodoc_typehints = "description" ...
from django.db import models import uuid from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import ( GenericForeignKey, GenericRelation ) class Store(models.Model): id=models.UUIDField( primary_key=True, defa...
from django.contrib import admin # Register your models here. from .models import Message class MessageAdmin(admin.ModelAdmin): list_display = ('user_name','message','time','is_img') admin.site.register(Message, MessageAdmin)
from numpy import mean, math from sklearn.ensemble import RandomForestClassifier from sklearn.tree import DecisionTreeClassifier from copy import copy import numpy as np from simpleGA.v2.SingleTon import Singleton from sklearn.model_selection import KFold class FitnessCalc(): # Here will be the instance stored. ...
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © %YEAR% %USER% <%MAIL%> # import unittest class Test(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testName(self): pass %HERE% if __name__ == '__main__': #impor...
class Solution: ### One pass hash map (Best solution) # A simplification of Two pass hash map since we are checking the hashmap as we build it # so we only go through it once # Time Complexity: O (n) # Space Complexity: O(n) for the hashmap def twoSum(self, nums: List[int], target: int) -> ...
#import style # 1. # import model as name # 2. # from model import fun1 as f1, fun2 as f2, fun3 # from model import * #import pizza # pizza.make_pizza(32, "ege", "fish", "salard") from pizza import make_pizza as mk mk(32, "ege", "fisjh")
import json import logging import os from typing import Any from typing import AnyStr from typing import Dict from typing import IO from typing import List from typing import Optional from typing import Tuple from typing import Union from gcloud.aio.auth import AioSession # pylint: disable=no-name-in-module from gclo...
import re # ()로 구분해서 이름과 전화번호를 분리해서 추출 p = re.compile("(\w+)\s(\d+[-]\d+[-]\d+)") #\s는 공백 s = p.search("jang 010-1234-5678") print(s.group(1)) # group은 문자열을 표시해주는 함수 print(s.group(2)) # re_grouping p2 = re.compile("blue|red") s2 = p2.sub('color', 'blue socks and red shoes') # blue, red를 color로 변경 print(s2)
#! /usr/bin/env python # -*- coding: UTF-8 -*- import hashlib import subprocess import zipfile import requests from util.decorator import * from util.tool.file import File import threading def delay(secs): """和sleep类似,多一个显示剩余sleep时间 :param secs: :return: """ secs = int(secs) for i in reversed...
# -*- coding: utf-8 -*- from .context import encdec8b10b from encdec8b10b import EncDec8B10B import random import unittest verbose = True # Set to True to get test output class TestSuite(unittest.TestCase): """All test cases""" def test_comma(self): print("Testing K28.5 Comma...") running_...
#! /usr/bin/env python3 import os import sys import shutil import yaml import subprocess tracediff_script = "" traceunion_script = "" traceontograph_script = "" tracetodot_script = "" def callTraceTools(work_dir, resources): global tracediff_script global traceunion_script global traceontograph_script global tra...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import copy import json import traceback import collections from z3 import * from utils import settings from utils.utils import convert_stack_value_to_hex, convert_stack_value_to_int, is_fixed BIT_VEC_VAL_ZERO = BitVecVal(0, 256) BIT_VEC_VAL_ONE = BitVecVal(1, 256) de...
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
""" """ # ----------------------------------------------------------------------------- # import: # ----------------------------------------------------------------------------- # osztalyok : # ----------------------------------------------------------------------------- # fuggvenyek: def betoltes(inp...
#getOption.py -- Robert Aburustum from math import pi def getOption(i,n): x = n+1 while x < i or x > n: try: x = float(eval(input("Please input a number between " + str(i) + " and " + str(n) + " inclusive. \n"))) except ValueError: print("That's not a number.") ...
from flask import Flask, json, request, render_template from db import * app = Flask(__name__) @app.route('/') def index(): activity_list = activity.find() return render_template('index.html', activity_list=activity_list) @app.route('/github', methods=['POST']) def github_api(): if request.headers['Con...
#from tuskar.api.controllers.v1.types import Node #from tuskar.api.controllers.v1.types import Rack #from tuskar.api.controllers.v1.types import Relation from tuskar.api.controllers.v1.types import ResourceClass from tuskar.db.sqlalchemy import api as dbapi from tuskar.tests.api import api class TestFlavors(api.Funct...
import unittest from parse_lisp_expression import Solution class TestSolution(unittest.TestCase): def test_Calculate_Solution(self): sol = Solution() self.assertEqual(3, sol.evaluate('(add 1 2)')) self.assertEqual(15, sol.evaluate('(mult 3 (add 2 3))')) self.assertEqual(10, sol.eva...
#!/usr/bin/env python ''' Generate random floating point numbers in a range for testing. It is used to create datasets to test cmpds. You can decorate the datasets with a header and record counts to make them easier to read. That works because cmpds allows you to specify which column to read in the dataset file. Typ...
#!/usr/bin/env python """ Rosenbrock's function """ from numpy import sum as numpysum from numpy import asarray def rosen(coeffs): """evaluates n-dimensional Rosenbrock function for a list of coeffs minimum is f(x)=0.0 at xi=1.0""" x = [1]*2 # ensure that there are 2 coefficients x[:len(coeffs)]=coeffs ...
class TypelessException(Exception): '''This class is the root Exception of all TyplessException''' def __init__(self, **format_args): Exception.__init__(self) self.format_args = format_args if not self.format_args: self.format_args['state'] = "7" self.format_args[...
import pytest def pytest_addoption(parser): parser.addoption("--project_id", action="store", help="ID of project to hold test resources") @pytest.fixture(scope='session') def project_id(request): return request.config.getoption("--project_id")
from flask import Flask, jsonify, request import numpy as np import pandas as pd import re import joblib import time from sklearn.metrics.pairwise import cosine_similarity import pickle import os import gensim import smart_open import warnings warnings.filterwarnings('ignore') # create app import flask app = Flask(_...
def select(num1, num2, num3): return num1 > 0 and num2 > 0 and num3 > 0 print(select(1, 2, -1)) print(select(1, 2, 3))
from typing import Type from pydantic import BaseModel from app.constants import term from app.types.hitbox import HitBox class Wait(BaseModel): """Wait command""" pos_x: int pos_y: int time_start: int length: int content: str parent: Type def __str__(self) -> str: return f...
import random def generate(n): file = open("./answers.txt", "w") for i in range(1, n): file.write("\"" + str(i) + "\"" + ":" + "[" + str(random.randint(1, 4)) + "]" + ",\n") file.write("\"" + str(n) + "\"" + ":" + "[" + str(random.randint(0, 4)) + "]") file.close() generate(350)
#!/usr/bin/python from time import time from google.appengine.api import taskqueue from google.appengine.api import xmpp from google.appengine.ext import webapp, db from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.runtime import DeadlineExceededError CRON_NUM = 10 TASK_QUEUE_N...
""" Utility classes for interfacing with the RPi.GPIO library on a Raspberry Pi. """ import time import RPi.GPIO as GPIO class Switch: """ A class to wrap a GPIO input event as triggered by a simple switch. Sets up a GPIO PUD_UP Rising switch and adds a GPIO event handler to it. When the event hand...
import pytest from hets_api import create_app import os import glob @pytest.fixture def app(): app = create_app({ 'TESTING': True, 'HETS_EXECUTABLE': '/opt/Hets/hets' }) remove_all_output_files() yield app remove_all_output_files() @pytest.fixture def client(app): return app...
import torch import torch.nn as nn class DenseBlockLayer(nn.Module): def __init__(self, input_channel, filters=16, bottleneck=4): super(DenseBlockLayer, self).__init__() self.net = nn.Sequential( nn.BatchNorm3d(input_channel), nn.ReLU(inplace=True), nn.Conv3d(inp...
# Date created: 22/06/18 # Author:Matthew King # Version: 1.0 # What it does: calculates the total amount of time a user # spends gaming then gives them feedback on it # == == == == == == == == == == == == == == == == == == == == == == == # # Variables days = ["Monday", "Tuesday", "Wednesday", "Thursday...
import random CLOSED_CELL_LABEL = "." OPEN_CELL_LABEL = " " DECK_KEY = 1 WHOSE_TURN_KEY = 2 WINNER_KEY = 3 TIE = 1 class _Cell: _CLOSED = 0 _TURNED = 1 _OPEN = 2 def __init__(self, symbol): self._status = _Cell._CLOSED self._symbol = symbol def __repr__(self): return s...
# server.py from flask import Flask, render_template, flash, request, redirect from flask_script import Manager from pymongo import MongoClient from twilio.rest import Client app = Flask(__name__) app.config['SECRET_KEY'] = "hard" manager = Manager(app) dbClient = MongoClient("mongodb://admin:admin1@ds227555.mlab.co...
from uuid import uuid4 from django.db import models class Role(models.Model): """ Модель данных роли участника в команде """ id = models.UUIDField( primary_key=True, default=uuid4, editable=False ) # type: str description = models.CharField( max_length=1024, ...
__author__ = 'dungdt' from extractor import Extractor from bs4 import BeautifulSoup class Dailymail(Extractor): def extractArticle(self, article): soup = BeautifulSoup(article.html) articleContainer = soup.find(id='js-article-text') metaImage = soup.find(name='meta', attrs={'property': 'o...
# -*- coding: utf-8 -*- '''Chemical Engineering Design Library (ChEDL). Utilities for process modeling. Copyright (C) 2017, Caleb Bell <Caleb.Andrew.Bell@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal...
from app import app, mail from flask import render_template, request, redirect, url_for, flash, session from .models import User, Patient, Payment, Visitation, Test, Treatment, Bill,Family, Account, Schedule from app import db, mail from werkzeug.security import generate_password_hash, check_password_hash from flask_lo...
import socket import time import turtle #import matplotlib.animation as animation from matplotlib import style import sys import pyqtgraph as pg #from PyQt4.QtWidgets import QApplication from pyqtgraph.Qt import QtGui, QtCore import numpy as np import matplotlib.pyplot as plt import matplotlib.animation f...
import matplotlib.pyplot as plt from tqdm import tqdm import pickle import os collection = [] import definitions directory = definitions.root + "\\data\\processed" for filename in tqdm(os.listdir(directory)): # Loop through all of the files in a folder if filename.startswith('g'): # This section deals with ...
def factI(n): fact=1 if n==0: return 1 else: for i in range(1,n+1): fact=fact*i return fact num = int(input("enter a number to find factorial: ")) if num < 0: print("Invalid number") else: print("Factorial of a number: ", factI(num))
from itertools import product from itertools import combinations as cwr import numpy as np import matplotlib.pyplot as plt from MatrixElCalc import * states=[] fermistates=[] numparts=4 for it in range(numparts): states.append(State([QuantumNumber("p",it),QuantumNumber("sigma",'+')],it)) states.append(State([Q...
from rest_framework import serializers from .models import * class AppSerializer(serializers.ModelSerializer): class Meta: model = App fields = ('name', 'app_description', 'creator', 'subject', 'download_number', 'size', 'apk_file', 'image') class GetBriefAppSerializer(serializ...
# Credits for TwitterLattestMsgNode and twitter_status go to coulix who posted this on July 4, 2009 on djangosnippets.org # link here: http://djangosnippets.org/snippets/1615/ from django import template import twitter register = template.Library() class TwitterLattestMsgNode(template.Node): def __init_...
import requests from bs4 import BeautifulSoup url = 'https://www.travel.taipei/zh-tw/tour/hellotaipei' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36' } ss = requests.session() res = ss.get(url=url,headers=headers) soup ...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui_label_settings.ui' # # Created: Thu May 01 17:30:56 2014 # by: PyQt4 UI code generator 4.10.3 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString....
#!/usr/bin/env python # -*- coding: utf-8 -*- """ # @Time : 2018/8/11 13:10 # @Author : Lei Zhen # @Contract: leizhen8080@gmail.com # @File : swsindex_data.py # @Software: PyCharm # code is far away from bugs with the god animal protecting I love animals. They taste delicious. ┏┓ ┏┓ ...
import os import numpy as np import tensorflow as tf import finetune_model import read_record BATCH_SIZE = 200 HASHING_BITS = 12 TRAINING_STEPS = 50000 // 200 EPOCH = 1 LEARNING_RATE_BASE = 0.001 LEARNING_RATE_DECAY = 0.4 DECAY_STEPS = 500 IMAGE_SIZE = 227 model_file = "../Data/weight/finetune_weights" checkpoint_file...
Когда Антон прочитал «Войну и мир», ему стало интересно, сколько слов и в каком количестве используется в этой книге. Помогите Антону написать упрощённую версию такой программы, которая сможет подсчитать слова, разделённые пробелом и вывести получившуюся статистику. Программа должна считывать одну строку со стандартн...
import time import numpy as np import os # Prints time left def print_time(avg_time, eta): print("\n --- TIME ---") print("\nT/epoch = " + str(avg_time)[0:4] + " s") hour = eta // 3600 eta = eta - (3600 * hour) minute = eta // 60 eta = eta - (60 * minute) seconds = eta # Stringify ...
class User(object): def __init__(self, name, email): self.name = name self.email = email self.books = {} def get_email(self): return self.email def change_email(self, address): self.email = address print("The email address for user " + self.user + "has been ...
# -*- encoding: ascii -*- from .base import AbstractPass from ..util import uno from ..core.common import ModuleView, ModuleClass, NetClass from ..netlist import NetUtils, ModuleUtils import logging _logger = logging.getLogger(__name__) __all__ = ['SwitchPathAnnotation'] # ------------------------------------------...
#!/usr/bin/env python3 # This application is written by Kunal Deo (kunaldeo2006@gmail.com) and can be redistributed under BSD License # (c) 2012 Kunal Deo <kunaldeo2006@gmail.com> from PyQt5.QtCore import QObject, QProcess #from PyQt5 import SIGNAL from PyQt5.QtWidgets import QFileDialog,QMainWindow, QApplication, QM...
'''In this exercise, you'll evaluate the 10-fold CV Root Mean Squared Error (RMSE) achieved by the regression tree dt that you instantiated in the previous exercise. In addition to dt, the training data including X_train and y_train are available in your workspace. We also imported cross_val_score from sklearn.model_s...
# 4▹ Pomyśl co sprawia, że ssak jest ssakiem? # Utwórz klasę ssaki. Stwórz kilka obiektów klasy ssaki np. wilk, koń, ssaki.