text
stringlengths
38
1.54M
#-*- coding:utf-8 -*- import json import os import pandas import codecs import glob import pandas as pd from jieba import analyse from snownlp import SnowNLP from textrank4zh import TextRank4Keyword, TextRank4Sentence # from pyltp import Segmentor import jieba.posseg as pseg import re import jieba def get_left_right_...
from flask import Flask,request,jsonify from flask_cors import CORS from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) CORS(app, supports_credentials=True,origins="*") # 设置跨域 if __name__ == '__main__': app.run(debug=True,threaded=True)
# -*- coding: utf-8 -*- # This program is free software; you can redistribute it # and/or modify it under the GPLv2 # # We're working on this at http://flossmole.org - Come help us build # an open and accessible repository for data and analyses for open # source projects. # # If you use this code or data for preparing ...
import numpy as np class IndicatorsCalculatorPerfMonitor(object): def __init__(self): self.__performance_data = {} def report_execution_time(self, indicator_name, execution_time): if indicator_name in self.__performance_data: self.__performance_data[indicator_name].append(executi...
from game_event import RestartLevelEvent, AdvanceLevelEvent, PlaySoundEvent import constants class TimedLevelAdvance: def __init__(self, time, level): self.level = level self.time_left = time def update(self, delta): self.time_left -= delta self.time_left = max(0, self.time_left) if self.time_...
import random class MultiDatasetLoader(object): """ Load datasets for multiple tasks Parameters ---------- loader_dict: dict dictonary of DataLoaders shuffle: Boolean (defaults to True) Flag for whether or not to shuffle the data """ def __init__(self, loader_dict, shu...
import base64 import json import os import re import subprocess from contextlib import contextmanager from pathlib import Path import s3fs s3_input_file_key_re = re.compile(r'^s3://(?P<s3_bucket_name>[^/]+)/(?P<s3_file_key>(?P<base_folder>.*/datatype=(?P<file_type>\w+))/(?P<filename>[^/]+))') fs = s3fs.S3FileSystem(...
# -*- coding: utf-8 -*- """ Created on Fri Nov 03 07:55:00 2017 @author: aditya royal """ import mysql.connector from mysql.connector import errorcode db_name='products' tables={} tables['products']= ( "CREATE TABLE `employees` (" " `emp_no` int(11) NOT NULL AUTO_INCREMENT," " `birth_date` date NOT NULL,...
from distutils.core import setup setup( name='dna_workflows', packages=['dna_workflows'], package_data={ 'dna_workflows': ['module'] }, version='0.0.26', license='MIT', description='dna_workflows is a basic workflow engine for executing DNA Workflows packages', author='Richard Cunnin...
# Author: Ilya Ivanov # Date created: 01/12/2016 # The program parses .srt files in the provided directory and outputs one text file without a time stamp. # Original .srt files are not modified import os.path import re import sys # Command line options: # python <file_name> <input directory> <output file name> if le...
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2020/2/26 7:14 # @Author : LI Dongdong # @FileName: 129. Sum Root to Leaf Numbers.py '''''' ''' 题目分析 1.要求:Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which ...
import re import action import random class lolCount(action.Action): def __init__(self): self.counterfile = "lolz.txt" self.sponsors = ['Fo Shizzle mah Nizzle', 'lantis\' EVE account', 'Go|dfish Schnapps', 'Mavez0r\'s CPU cooler', ...
class Animal(object): def __init__(self,name,health): self.name = name self.health = health def walk(self): self.health -= 1 return self def run(self): self.health -= 5 return self def displayHealth(self): print self.health return self...
from tealight.art import (color, line, spot, circle, box, image, text, background) from tealight.art import (screen_width, screen_height) x = 600 y = 400 vx = 0 vy = 0 ax = 0 ay = 0 # parity = ((abs(vx + ax))/(vx + ax)) power = 0.3 line def handle_keydown(key): global ax, ay if key == "a": ax = -power ...
# -*- coding: utf-8 -*- from arche.utils import utcnow from zope.interface import implementer from arche.resources import Content from arche.resources import ContextACLMixin from arche_tos.interfaces import ITOS from arche_tos import _ @implementer(ITOS) class TOS(Content, ContextACLMixin): type_name = "TOS" ...
import os import tempfile from testsuite import iterate_suites, GenTestSuite, EvoSuite from killmap import Killmap from d4jconstants import * from datetime import datetime from subprocess import CalledProcessError, TimeoutExpired def generate_devsuite(suite): proj_name = suite.proj_name bug_id = suite.bug_id ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jun 13 09:01:26 2019 # 2. hyper_training_train train the Train dataset from mlogit. Using two architectures. @author: shenhao """ #cd /Users/shenhao/Dropbox (MIT)/Shenhao_Jinhua (1)/9_ml_dnn_alt_spe_util/code import numpy as np import pandas as pd im...
from mcpi.minecraft import Minecraft mc=Minecraft.create() x,y,z=mc.player.getPos() for i in range(50): x,y,z=mc.player.getPos() x=x+i mc.setBlock(x,y-1,z,57) mc.player.setBlocks(x,y,z,x+6,y+6,z+6,57) mc.player.setBlocks(x+1,y+1,z+1,x+5,y+5,z+5,0)
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} print "dict['Name']: ", dict['Name'] print "dict['Age']: ", dict['Age'] dict['Age'] = 8; # update existing entry dict['School'] = "DPS School"; # Add new entry dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} del dict['Name']; # remove entry with key 'Name' di...
from bs4 import BeautifulSoup import requests from xlwt import Workbook response = requests.get('https://organicfood.vn/do-uong-huu-co') soup = BeautifulSoup(response.text, 'html.parser') list_title = soup.find('div', class_= 'products-category clearfix').find_all('div', class_='product-image-container') rootlink = 'h...
from client.requetes.requete_grille import RequeteGrille class MenuGrille: #Présente tous les menus utiles à la manipulation de la grille dans le jeu du morpion def recuperer(id_partie,nb_cases): #afficher la grille au joueur req = RequeteGrille.recuperer(id_partie,nb_cases) ...
# Copyright (C) 2010-2016 Dzhelil S. Rufat. All Rights Reserved. import numpy as np import spexy.spectral as sp xmin, xmax = 0, np.pi from .chebyshev import D0, D1, D0d, D1d @sp.batch def H0d(f): r""" .. math:: \tilde{\mathbf{H}}^{0}= \mathbf{M}_{1}^{\dagger} \mathbf{I}^{-\...
from django.contrib import admin from something.models import Something, Tag class SomethingAdmin(admin.ModelAdmin): list_display = ('name', 'user', 'created', 'updated') readonly_fields = ('user', 'created', 'updated') date_hierarchy = 'created' class TagAdmin(admin.ModelAdmin): readonly_fields ...
"""Implement the auth feature from Hass.io for Add-ons.""" from ipaddress import ip_address import logging import os from aiohttp import web from aiohttp.web_exceptions import ( HTTPInternalServerError, HTTPNotFound, HTTPUnauthorized, ) import voluptuous as vol from homeassistant.auth.models import User f...
import string import random from Graph import * def random_graph(): vertices = set([]) edges = {} num_ver = random.randint(4,16) for i in range(num_ver): vertices.add(random.choice(string.ascii_lowercase)) for v in vertices: if not (v in edges): edges[v] = []...
import os PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media/') # Absolute path to the directory static files should ...
""" ReSpeaker Python Library Copyright (c) 2016 Seeed Technology Limited. 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 a...
#필요한 모듈 임포트! import discord#pip import asyncio#pip import random from discord.utils import get from discord.ext import commands import json import os import math import asyncio import requests#pip from tabulate import tabulate #pip #이것이 접두사입니다 bot = commands.Bot(command_prefix = '천사야 ', help_command ...
from setuptools import setup, find_namespace_packages, find_packages print(find_namespace_packages()) setup(name='pytorch_to_tf1', version='1.0', packages=find_packages())
import shutil from typing import Any from os.path import join, isfile import torch from fastai.callbacks import ( CSVLogger, Callback, TrackerCallback, LearnerCallback, add_metrics) from fastai.basic_train import Learner from mlx.filesystem.utils import (sync_to_dir) class SyncCallback(Callback): """A callba...
import json import numpy as np import tqdm from nltk.tokenize import word_tokenize class Fasttext: def __init__(self, text_wv_file, return_wv=False): """ Class for all fasttext related interactions :param text_wv_file: path to word vectors in text format """ self.tex...
from datetime import date from flask import request, jsonify, Blueprint from app import db from models.contact_model import Contact from models.file_model import File from models.person_model import Person from models.models_create_aux import set_person from models.welcoming_model import Welcoming welcoming_api = Bl...
from tkinter import * import time import daytime def tick(): # get the current local time from the PC time2 = time.strftime('%H:%M:%S %Z(US/Central)') # time.tzset("US/Central") # if time string has changed, update it clock_chicago.config(text=time2) # calls itself every 200 milliseconds t...
#!/usr/bin/python # debian-user, Copyright (C) 2012 Stuart Pook (http://www.pook.it/) # Run a command as user in the chroot environment. # 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 ve...
# Chapter 3 Integrating with Standard Python # Operator overloading: comparison print("=========================================================") # Overloading equality print("=========================================================") # Checking class equality print("=========================================...
""" 练习3: 在一个my.log 的文件中不间断的写入如下内容 每隔2s写入一次 sleep 1. 2020-01-01 10:10:10 2. 2020-01-01 10:10:12 3. 2020-01-01 10:10:14 4. 2020-01-01 10:10:16 5. 2020-01-01 10:28:49 6. 2020-01-01 10:28:51 要求 : 1. 每写一行都要实时显示出来 2. 程序终止后,重新启动那么会继续 往下写,并且序号能够衔接 思路: 什么方式打开合适? 序号怎么衔接 (先判断有多少行) """ fr...
#!/usr/bin/env python """This script prompts a user to enter a message to encode or decodeusing a classic Caeser shift substitution (3 letter shift)""" import numpy as np import matplotlib.pyplot as plt T_TIME = np.arange(0, 36, 0.5) #received time LEN_T = len(T_TIME) TS = np.zeros(LEN_T) TA = np.arange(11.5, 17, 0....
import sys import numpy as np import cv2 image = cv2.imread(sys.argv[1]) cv2.imwrite(sys.argv[1], cv2.medianBlur(image, int(sys.argv[2])))
from collections import defaultdict import numpy as np from . import config as ttconf, TreeTimeError, MissingDataError from .seq_utils import alphabets, profile_maps, alphabet_synonyms def avg_transition(W,pi, gap_index=None): if gap_index is None: return np.einsum('i,ij,j', pi, W, pi) else: re...
#Inicializaction import sympy as sp import scipy as sc from sympy.solvers import solve from scipy.optimize import fsolve from scipy.constants import g,pi,c from scipy.misc import derivative as drv from scipy.integrate import quad import numpy as np import matplotlib.pyplot as plt from scipy.integrate import odeint #od...
# -*- coding: utf-8 -*- from setuptools import setup import io def readme(): with io.open('README.rst', encoding='utf8', errors='ignore') as f: return f.read() setup(name='bangla', version='0.0.3', description='Bangla is a package for Bangla language users with various functionalities including ...
#!/usr/bin/python import requests URL = 'http://54.221.6.249/level1.php/cookies' header = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp' payload = {'id': '128', 'holdthedoor': 'Submit', 'key': '0'} cookies = {'HoldTheDoor': '0'} r = requests.get(URL, cookies) jar = requests.cookies.RequestsCookieJ...
import jaydebeapi from dataclasses import dataclass from jaydebeapi import Connection from dbt.adapters.base import Credentials from dbt.adapters.sql import SQLConnectionManager from dbt.adapters.base import Credentials from dbt.logger import GLOBAL_LOGGER as logger from dbt.exceptions import ( FailedToConnectExcep...
from typing import Optional, Union import discord from discord.ext import commands from .core import Core from bank.bank import Customer from main import status, TEXTS import os #TODO: credits #TODO: buy #TODO: sell #TODO: auction Discord only? #TODO: bets Discord only? ITEMS = os.path.join(TEXTS, 'items.csv') CREDITS...
import cv2 import os import shutil import numpy as np from preprocess.preprocess import get_images from matplotlib import pyplot as plt from utils.utils import txtremove import imutils def compmatch(input_path,template_path, output_path,comploc_output_path): """ Component Match by using template matching ...
import json import requests #ISE get requires headers. AMP does not. def get(url, headers): try: response = requests.get(url, headers=headers, verify=True) # Consider any status other than 2xx an error if not response.status_code // 100 == 2: return "Error: Unexpected respons...
import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import learning_curve # 用sklearn的learning_curve得到training_score和cv_score,使用matplotlib画出learning curve def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None, n_jobs=1, train_sizes=np.linspace(....
from django import forms class LoginForm(forms.Form): username = forms.CharField(max_length=30, widget=forms.TextInput( attrs={'placeholder': 'Username', 'class': "form-control", 'required': 'True'})) password = forms.CharField(max_length=30, widget=forms.PasswordInput( attrs={'...
''' Create a copy of nums1 and then interweave minimums into nums1 Time: O(M + N) Space: O(M) Note: To achieve a space complexity of O(1) one could start from the right side. ''' class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not...
from __future__ import division import healpy as hp import numpy as np import matplotlib.pyplot as mp import os from Quad import qml from Quad import pyquad import healpy as hp from pysimulators import FitsArray #### Get input Power spectra #a=np.loadtxt('/Volumes/Data/Qubic/qubic_v1/cl_r=0.1bis2.txt') a=np.loadtxt('...
# Scenarios to check against TimberMusicPlayer model used as oracle from TimberMusicPlayer import InitializePlayer, PlayMusic, PauseMusic testSuite = [ # Run 1 [ (PlayMusic, (), None), (PauseMusic, (), None), (PlayMusic, (), None) ], # Run 2 [ (PlayMusic, (), None), (PauseMusic, (...
from __future__ import absolute_import import logging __all__ = ('Sdk', ) from distutils.version import LooseVersion from django.conf import settings from sentry.interfaces.base import Interface, prune_empty_keys from sentry.net.http import Session from sentry.cache import default_cache logger = logging.getLogger...
from omxdsm.settings import SUPERSCRIPTS, DEFAULT_OUTPUT_SIDE class BaseXDSMWriter(object): """ All XDSM writers have to inherit from this base class. Attributes ---------- name : str Name of XDSM writer. extension : str Output file saved with this extension. type_map : st...
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'FoodProvider.post_code' db.delete_column(u'foodproviders_foodprovider', 'post_code_id') ...
# Code taken from bitsandbytes but modified with arg device to accept skipt_init # from torch.nn.utils => makes model building way faster. import os import torch import torch.nn as nn try: os.environ["BITSANDBYTES_NOWELCOME"] = "1" import bitsandbytes as bnb except ImportError: raise ImportError("Install b...
def find_n_to_last(node, n): """Returns nth to last element from the linked list.""" def find_n_to_last_helper(node, n, count): if not node: return None result = find_n_to_last_helper(node.next, n, count) if count[0] == n: result = node.data count[0] += ...
from tkinter import * import time import random tk = Tk() canvas = Canvas(tk, width = 500, height = 500) canvas.pack() canvas.create_arc(10, 230, 50, 270, extent = 359, style = ARC) for x in range(0, 5): r = random.randrange(20, 40) t = random.randrange(20, 40) v = random.randrange(20, 40) n = random.ra...
N = input(int(()) num_list = list(map(int,input().split())) cnt = 1 length = 1 for i in range(1, N): for j in range(len(num_list)): num_list[0] = NUM if num_list[j] >= NUM; num_list[j] = NUM cnt += 1 else: cnt = 1 # if length < cnt: # l...
# Generated by Django 3.2.3 on 2021-06-26 09:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('auctions', '0006_auto_20210626_1135'), ] operations = [ migrations.AlterField( model_name='listing', name='image', ...
from base.node import TreeNode class Solution: def preorderTraversal(self, root: TreeNode) -> List[int]: res = [] self.preorder(root, res) return res def preorder(self, root: TreeNode, res: List[int]): if root: res.append(root.val) self.preorder(root...
import numpy as np def forw(q, F, i=1, h=1e-7): ''' Compute the numerical forward differential. Args: ---- q: Parameterization of the system DoF on form Nx1. F: Function computing the dependent variable with respect to the independent variable q. i: Vector of shape Nx1 masking ...
# # Rat.py # Josh Artuso # 06/03/16 # # This is the Rat class # class Rat: COORD_X_CHANGE = 0 COORD_Y_CHANGE = 0 COLOR = (0, 0, 0) RAT_HEIGHT = 10 RAT_WIDTH = 10 BOUNDARIES = [800, 600] FOLLOW_PLAYER = False def __init__(self, coordinates=None, color=None): if not coordina...
from math import pi, cos, sin, sqrt import cairocffi as cairo from hocus.graph import Direction # A4 # HEIGHT, WIDTH = 8.3 * 72, 11.7 * 72 # A3 HEIGHT, WIDTH = 11.7 * 72, 2 * 8.3 * 72 mm = 72 / 25.4 # dpi / (number of millimeters in one inch) class Point: def __init__(self, x, y): self.x = x ...
from django.urls import path, include from rest_framework.routers import DefaultRouter from .views import * from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from .views import * # from rest_framework_simplejwt.views impor...
# -*- coding:utf8 -*- from django.http import HttpResponse from django.shortcuts import render from django.contrib.auth import authenticate,login from django.http.response import JsonResponse from django.contrib.auth.decorators import login_required @login_required def firstpage(request): print request.user #...
import gym from stable_baselines3 import PPO MAX_TEST_EPISODE_LEN = 18000 # 18k is the default for MineRLObtainDiamond. TREECHOP_STEPS = 2000 # number of steps to run BC lumberjack for in evaluations. TEST_MODEL_NAME = "./train/potato.zip" # !!! Do not change this! This is part of the submission kit !!! class Epis...
""" MnasNet from the paper "MnasNet: Platform-Aware Neural Architecture Search for Mobile" by Mingxing Tan & Quoc V.Le, Google, CVPR 2019 """ # imports import torch import torch.nn as nn from torch.hub import load_state_dict_from_url # mnasnet variants __all__ = [ 'MnasNet', 'mnasneta1', 'mnasneta...
from selenium import webdriver import math from math import log, sin link = "http://suninjuly.github.io/alert_accept.html" driver = webdriver browser = driver.Chrome() browser.get(link) def calc(x): return str(log(abs(12*sin(int(x))))) buttonp1 = browser.find_element_by_css_selector('.btn-primary') buttonp1.click...
""" service_factory.exceptions ~~~~~~~~~~~~~~~~~~~~~~~~~~ This module contains exceptions raised by service factory. :copyright: (c) 2015 by Artem Malyshev. :license: GPL3, see LICENSE for more details. """ from __future__ import ( absolute_import, unicode_literals, division, print_function) ...
"""empty message Revision ID: 6a9d1922033b Revises: Create Date: 2021-07-08 14:34:41.338651 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '6a9d1922033b' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto gene...
from cookielib import Cookie, CookieJar import logging import os from django.core import signals from django.test.client import Client from django.test.testcases import LiveServerTestCase, TestCase from ghost import Ghost class LiveServerTestCase(LiveServerTestCase, TestCase): """ LiveServerTestCase using G...
# uncompyle6 version 3.7.4 # Python bytecode 2.7 (62211) # Decompiled from: Python 3.8.5 (default, Aug 12 2020, 00:00:00) # [GCC 10.2.1 20200723 (Red Hat 10.2.1-1)] # Embedded file name: c:\Jenkins\live\output\Live\win_64_static\Release\python-bundle\MIDI Remote Scripts\Launchkey_MK3\elements.py # Compiled at: 2020-05...
import unittest import copy from src.structure.device.router import Router router = Router( "Router", "Test Router 1", "adress-2", "", "Active", {"adress-1", "adress-3"}, {"adress-5": "adress-4"}, ) class TestRouterRouting(unittest.TestCase): def test_routing_no_command(self): ...
# __init__.py - Starting of our application from flask import Flask from flask_ask import Ask, statement, question from vsphereapi import * import os import subprocess app = Flask(__name__) ask = Ask(app, "/vghetto_control") VMTENV = os.environ.copy() def execute(cmd, ofile=subprocess.PIPE, efile=subprocess.PIPE, ...
from django.db import models from django.utils.timezone import now from django.contrib.auth.models import User # Create your models here. class Memo(models.Model): user_name = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) content = models.TextField() likes =...
from typing import Optional, Tuple, Dict, List, Set from config import config from p1_utils.data_type import Register from p1_utils.errors import UsingInvalidError from p2_assembly.mac0_generic import LabelReference from p2_assembly.mac1_implementation import DataMacroImplementation, Dc from p2_assembly.mac2_data_macr...
from scipy import signal import matplotlib.pyplot as plt import numpy as np fs = 4000 # Sampling rate def applyDynamicRange(newSxx): maxSxx = np.max(newSxx) newSxx[np.where(newSxx > 0.1 * maxSxx)] = 0.1 * maxSxx return newSxx def cutFrequncy(f, newSxx): cut = 15 f = f[0:cut] newSxx = newSxx[...
import csv import numpy as np """ State of events. """ event_to_index = {} index_to_event = {} event_index = 0 """ State of individuals. """ email_to_index = {} index_to_email = {} email_index = 0 """ State of the matrix array. """ zero_list = [] matrix_array = [] attendance = [] """ Opens eventdata.csv and populat...
#!/usr/bin/python #This program aims to match a signature in a target binary. import angr,simuvex,claripy import sys,os import logging,traceback import copy,re import time import traceback from networkx.algorithms import isomorphism from utils_sig import * from claripy import operations from fuzzywuzzy import fuzz tr...
""" A small module to remove the WebHelpers dependency in FormAlchemy. Copyright 2007 Adam Gomaa - MIT License http://www.opensource.org/licenses/mit-license.php """ import cgi, re # Flag to indcate whether XHTML-style empty tags (< />) should be used. XHTML = True def html_escape(s): """ HTML-escape a str...
import asyncio import aiohttp from bs4 import BeautifulSoup from shop.parsers.connector import connect_2 from shop.parsers.get_genre import CATALOG_URL from shop.models import Genre, Book def save_db(name, photo_url=None, genre=None): try: genre = Genre.objects.get(name=genre) except: genre ...
#!/usr/bin/python import psycopg2 from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT def db_connect(): db_name = "bank_balance" db_user = "user" db_pass = "2htLeuFhFWg5" db_server = "localhost" con = psycopg2.connect(dbname=db_name, user=db_user, host=db_server,password=db_pass) con.set_isolation_...
import requests import json from django.core.management.base import BaseCommand from marketplace.models import Product def _make_json_request(page=1, method='get'): headers = {'Content-Type': 'application/json'} url = 'http://challenge-api.luizalabs.com/api/product/?page=%s' % (page) request = requests.re...
# Ejercicio Nº 7 # Modelo matemático PI = 4 * Σ (-1)^n / 2n+1; n=0 - ∞ import math from decimal import getcontext, Decimal n = int(input('Cantidad de decimales:')) getcontext().prec = n + 1 r = Decimal(0) mod = Decimal(1) / Decimal(10) ** Decimal(n) pi = Decimal(math.pi) - Decimal(math.pi) % mod pi_aprox = Decimal(...
from SPARQLWrapper import SPARQLWrapper, JSON import os import errno import time import numpy as np from scipy.sparse import csr_matrix import scipy from scipy import spatial from datetime import datetime import pickle class DomainMatrix: def __init__(self, endpoint, type_list, additional_filters, feature_strate...
# F A T O R I A L def fatorial(n): f = 1 for c in range(1, n+1): f *= c return f # L E I T O R D E I N T E I R O def leiaInt(txt): """ Valída se o valor digitado é um número inteiro, enquanto não for, o programa não prossegue. :param txt: Será exibido na tela, solicitando o valor p...
#%% figdir = "E:\OneDrive - Washington University in St. Louis\HessNetArchit" from time import time from collections import OrderedDict from cycler import cycler import matplotlib matplotlib.rcParams['pdf.fonttype'] = 42 matplotlib.rcParams['ps.fonttype'] = 42 #%% from matplotlib.pylab import plt from GAN_utils import ...
import numpy as np import sys; sys.path.append('..') from main import main_function from plotting import concentration_plot isotopes = ['922340', '922350', '922380'] conc = np.array([1, 1, 1]) flux = 0 years = 2e5 steps = 400 reactor_type = 'fast' conc_over_time = main_function(isotopes, conc, flux, reactor_type, yea...
import pandas as pd import numpy as np '''The TFTable (true false table) contains two functions, the getTorF function returns true/false/none based on given predicate and objectID the getAllPredicates function return all predicates as a list (105 int total)''' class TFTable: def __init__(self): table_pat...
#!C:/Users/HP/AppData/Local/Programs/Python/Python37/python.exe print ("Content-type:text/html") print ("") fp=open('header.py','r') print (fp.read()) fp.close() fp=open('adminnav.py','r') print (fp.read()) fp.close() fp=open('slider.py','r') print (fp.read()) fp.close() """import usertrack unm=usertrack.usertrack(...
# Create a function called `odd_average` that takes a list of numbers as parameter # and returns the average value of the odd numbers in the list # Create basic unit tests for it with at least 3 different test cases class OddAverager(object): def odd_average(self, numbers = [0]): summarize = 0 coun...
# Generated by Django 3.1.2 on 2020-12-03 23:22 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('endulzapp', '0002_auto_20201203_1820'), ] operations = [ migrations.AddField( model_name='empleado', name='cargo', ...
import logging import re from functools import wraps import urllib2 from django import http from django.shortcuts import render from django.views.defaults import page_not_found from . import models from . import jenkins from .jenkins import client as jenkins_client from .config import instance as config logger = lo...
import numpy as np import csv def load_x(path): re=[] with open(path) as cvsfile: rows=csv.reader(cvsfile) for row in rows: re.append([float(v) for v in row]) re=np.asarray(re,dtype='float') return re def load_y(path): re=[] with open(path) as csvfile: rows=c...
import uiautomator2 as u2 class Utils: d = None @classmethod def connect(cls): if cls.d == None: # cls.d = u2.connect('3EP7N19401002574') # cls.d = u2.connect('41180608000090') cls.d = u2.connect('127.0.0.1:62001') # cls.d.app_start("zhiyun.com.mirr...
# Indian States global points points = 0 # making a dictionary providences = { 'Andhra Pradesh': 'Whitehorse', 'Arunachal Pradesh': 'Yellowknife', 'Assam': 'Iqaluit', 'Bihar': 'Victoria', 'Chandigarh': 'Edmonton', 'Chhattisgarh': 'Regina', 'Goa': 'Winnipeg', 'Gujarat': 'Toronto', 'Haryana': 'Quebec City...
import requests import os from grandpy.customparse import Customparser class Apigoogle: """Class designed to make Api calls to the google maps Api using name of a location to retreive its coordinates.""" def __init__(self, user_input): """Apigoogle class constructor. Args: user_...
import argparse import unittest import json from nose.tools import assert_equal, assert_true, assert_false from shared.common import parse_arguments from commands.access_check import ( replace_principal_variables, Principal, get_privilege_statements, get_allowed_privileges, access_check_command, ) ...
from app.api.util.web_request import WebRequest if __name__ == '__main__': ''' 下载都应素材网小视频 ''' startUrl = 'https://www.douyin766.com/7580.html' downloadSubUrl = 'https://tu.douyin766.com/2020/douyin766_com20200814141350.mp4' headers = { # ':authority': downloadBaseUrl, # ':metho...
#------------------------------------------------------------------------------ # Name: HDF4 Data Extraction # Description: NASA Aerosol Project # # Author: Robert S. Spencer # # Created: 6/13/2016 # Python: 3.5 #------------------------------------------------------------------------------ impor...