content
stringlengths
5
1.05M
import re import matplotlib.pyplot as plt import numpy as np from pyproj import CRS, Transformer class GrdFile(object): """ Read, modify, visualize, export and write Deflt3D dep file Examples -------- >>> import delft3d >>> grd = delft3d.GrdFile('example/example1.grd') """ def __ini...
""" ARCHES - a program developed to inventory and manage immovable cultural heritage. Copyright (C) 2013 J. Paul Getty Trust and World Monuments Fund This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Founda...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Example for Petrophysical-Joint-Inversion.""" import numpy as np import pygimli as pg from pygimli import meshtools as mt from pygimli.physics.petro import PetroInversion, JointPetroInversion from pygimli.physics.petro import transFwdArchieS as ArchieTrans from pygi...
from .esn import ESNBase, LeakyESN, MultiringESN from .readout import Linear __all__ = ['ESNBase', 'LeakyESN', 'MultiringESN', 'Linear']
from typing import Dict from modularconfig.errors import LoadingError name = "int" aliases = ["integer"] def load(text: str, options: Dict[str, str]) -> int: """Try to load a number as a int.py""" text = text.strip() try: return int(text) except ValueError as e: raise LoadingError("Ca...
{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "5e57b953-5f8d-42f1-9cf6-88c1e2aa89c5", "metadata": {}, "outputs": [], "source": [ "import os\n", "import csv\n", "\n", "#Creates file path\n", "budget_csv = os.path.join(\".\", \"budget_data.csv\")\n" ] }, ...
from typing import List from tkdet.utils.registry import Registry from .base import Neck from typing import Union __all__ = [ "NECK_REGISTRY", "build_neck", "get_neck_list", ] NECK_REGISTRY = Registry("NECK") def build_neck(cfg, input_shape) -> Union[Neck, None]: if not cfg.MODEL.NECK.ENABLE: ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu May 2 11:29:39 2019 @author: nsde """ #%% import torch from sklearn import preprocessing from sklearn.model_selection import train_test_split import numpy as np import argparse, math, os, time from tqdm import tqdm from itertools import chain from uti...
import cv2 import numpy as np from generic_dataset.dataset_folder_manager import DatasetFolderManager from generic_dataset.utilities.color import Color from generic_dataset.dataset_manager import DatasetManager from gibson_env_utilities.doors_dataset.door_sample import DoorSample dataset_path ='/home/michele/myfiles...
SERVICE_OK = """ <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="72" height="20"><linearGradient id="b" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient><clipPath id="a"><rect width="72" height="20" rx="...
# Copyright 2017-present Kensho Technologies, LLC. from typing import List import unittest from ..compiler.helpers import BaseLocation, FoldScopeLocation, Location def compare_sorted_locations_list( test_case: unittest.TestCase, sorted_locations: List[BaseLocation] ) -> None: """Ensure that the given list of...
__all__ = ['cli_setup_build_system'] import argparse import colorama from cli import * from ext.utils.path import * from file_structure import * from .setup import * def cli_setup_build_system(): # TODO : Fix description arg_parser = argparse.ArgumentParser(description=f"Creates the '{colorama.Fore.LIGHTBL...
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: modules/perception/proto/lane_post_process_config.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from g...
import torch import torch.nn as nn import torchvision.models as models import torch.nn.functional as F class EncoderCNN(nn.Module): def __init__(self, embed_size): super(EncoderCNN, self).__init__() resnet = models.resnet50(pretrained=True) for param in resnet.parameters(): par...
# Builtin modules # Local modules # Program class BaseRPCError(Exception): def __init__(self, typ:str, message:str): self.message = "{}: {}".format(typ, message) super().__init__(self.message) class InitializationError(BaseRPCError): def __init__(self, message:str): super().__init__("Initialization error", mes...
#!/usr/bin/python # Author: Michael Music # Date: 2/17/2019 # Description: Easy RM to MP3 27.3.700 Buffer Overflow Exploit # Exercise in BOFs following the corelan guide # Tested on Windows Server 2012 # Notes: Required alteration in prepended \x41s and POPs to jump to shellcode # !mona find -s "\x58\x5d\xc3" -m "M...
import pandas as pd # noinspection PyUnresolvedReferences from extractor import FeaturesExtractor from flask import Flask, render_template, request from sklearn.externals import joblib app = Flask(__name__) model = joblib.load('model.pkl') @app.route('/', methods=['GET', 'POST']) def index_page(text='', label='', c...
"""Exploring the font metrics in the freetype-py API to enable proper character placement""" import freetype import svgpathtools import svgwrite from freetype import Face from svgpathtools import Line, Path, QuadraticBezier, wsvg import re import barcode_wheel if __name__ == "__main__": drawing = svgwrite.Drawin...
import os from testcontainers.postgres import PostgresContainer import psycopg2 from contextlib import contextmanager def get_migration_files(): path = os.path.join(os.path.dirname(__file__), os.pardir, "migration") files = os.listdir(path) files.sort() for f in files: yield os.path.join(path,...
import sys, math, glob, multiprocessing, subprocess, os, bisect, random # Usage: python gff_to_bigwig_pe_v3.py [-q] [-h] [-keep] [-sort] [-o=out_ids] # [-p=num_proc] [-s=gff_search_term] <chrm_sizes> <gff_fille> [gff_file]* NUMPROC = 1 SEARCHTERM='frac' def processInputs( gffFileAr, chrmFileStr, keepTmp, outIdAr, se...
# soggetto.py import re import time from sound import audio_sequence SOLFEGE_MAP = { 'a': 'fa', 'e': 're', 'i': 'mi', 'o': 'sol', 'u': 'ut' } NOTE_MAP = { 'a': 'F', 'e': 'D', 'i': 'E', 'o': 'C', 'u': 'G' } def encode_string(text): """Enocdes the text in music using the simple soggetto cavato ...
import numpy as np import numpy.ma as ma import os from PIL import Image from skimage.transform import rotate class ImageStack: def __init__(self, image, samples): self.image = image self.samples = samples @classmethod def create_average_frame(cls, directory, files, color_mode): frame_0 = cls._load_frame...
#! /usr/bin/env python # -*- coding: utf-8 -*- __autor__='Angel Alvarez' from vehicle_model import Vehicle from car_model import Car def saliendo(): print print "Gracias por usar GestiCar Soft." raw_input("Cerrando. Pulse cualquier tecla..") def desea_salir(salir): if salir == 's' or salir == 'S':...
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # 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 applicab...
""" ====================== Random Geometric Graph ====================== Example """ import matplotlib.pyplot as plt import networkx as nx G = nx.random_geometric_graph(200, 0.125) # position is stored as node attribute data for random_geometric_graph pos = nx.get_node_attributes(G, "pos") # find node near center (...
from typing import AsyncGenerator, Any, Optional from .base_client import AzureBaseClient class AzureResourceManagerClient(AzureBaseClient): def __init__(self, subscription_id: str, resource_group_name: str, **kwargs): if 'params' not in kwargs: kwargs['params'] = {} params = kwargs['...
if __name__ == "__main__": (lambda i,n,x:[n:=n+1 for y in range(1,len(i))if(x:=(3+x)%len(i[0]))+1 and i[y][x]=='#'][-1])(open("i",'r').read().split('\n'),0,0) # def main_debug(inp,D=1,R=3): nb=x=y=0 inp = inp.split('\n') maxx = len(inp[0]) for y in range(0,len(inp),D): if inp[y][x]=='#': ...
from src.ml_utils.config.config import Config, load_conf from src.ml_utils.db.couchdb_helper import CouchDBHelper from cloudant.client import CouchDB import pytest import os DB_NAME = "test_db" @pytest.fixture(scope="module") def username(): return os.environ['USERNAME'] @pytest.fixture(scope="module") def pa...
#!/usr/bin/env python # coding=utf-8 """ Copyright (c) 2010-2015, Ryan Fan <reg_info@126.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 in the Software without restriction, including without limitation the ...
import os import re from setuptools import setup __name__ = 'treewalker' project_urls = { 'Home page': 'https://pypi.org/project/treewalker', 'Source Code': 'https://github.com/jaapvandervelde/treewalker', 'Documentation': 'https://treewalker.readthedocs.io/' } version_fn = os.path.join(__nam...
# -*- coding: utf-8 -*- from collections import Counter from typing import List class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: counts = Counter(students) for sandwich in sandwiches: if counts[sandwich] > 0: counts[sandwich] ...
import os import shutil from pathlib import Path class FileManager: def __init__(self): self.backup_path = "" self.symbols = "?><\\/:*|" def set_backup_path(self, path: str) -> None: self.backup_path = path def get_backup_path(self) -> str: return self.backup_path def...
import scrapy from ..items import NewsScrapeItem import re class SanookSpider(scrapy.Spider): name = "sanook" def start_requests(self): urls = ['https://www.sanook.com/news/'] for url in urls: yield scrapy.Request(url=url, callback=self.parse) def parse(self, respo...
from . import config_params from . import thermometer from . import harddrive from . import util import collections import logging import time logger = logging.getLogger(__name__) class Fan(config_params.Configurable): _params = [ ("name", None, "Name that will appear in status output."), ("min_p...
#!/usr/bin/env python3 import os import itertools import sys import re from ipykernel import kernelspec as ks import nbformat from nbformat.v4.nbbase import new_markdown_cell #from generate_contents import NOTEBOOK_DIR, REG, iter_notebooks, get_notebook_title #NOTEBOOK_DIR = os.path.join(os.path.dirname(__file__), ...
import unittest from aula4.pilha import Pilha, PilhaVaziaErro def esta_balanceada(expressao): """ Função que calcula se expressão possui parenteses, colchetes e chaves balanceados O Aluno deverá informar a complexidade de tempo e espaço da função Deverá ser usada como estrutura de dados apenas a pilh...
# -*- coding: utf-8 -*- import datetime import re import scrapy from locations.items import GeojsonPointItem from locations.hours import OpeningHours DAY_MAPPING = { "Monday": "Mo", "Tuesday": "Tu", "Wednesday": "We", "Thursday": "Th", "Friday": "Fr", "Saturday": "Sa", "Sunday": "Su", } ...
# 1 - The volume of a sphere with radius r is 4/3 πr**3. What is the volume of a sphere with radius 5? #V = 4.pi.r**3/3 import math radius = 5 #usando a formula para calcular o volume volume_sphere = 4 * math.pi * (math.pow(radius,3))/3 print('The volume is {:.2f}.'.format(volume_sphere))
from io import open from setuptools import find_packages, setup with open('requirements.txt') as fp: install_requires = fp.read() setup( name='modstool', author='Mike Gerber, The QURATOR SPK Team', author_email='mike.gerber@sbb.spk-berlin.de, qurator@sbb.spk-berlin.de', description='Convert MODS m...
from datetime import timedelta import pytest from django.urls import reverse from django.utils.timezone import localtime @pytest.mark.django_db def test_rest_api_autor_detail(client, autor): res = client.get(reverse("api_v1:autor-detail", args=(autor.pk,))) assert res.status_code == 200 @pytest.mark.django...
sss = '''75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 40 80 70 33 41 48 72 33 47 32 37 16 94 29 53 71 44 65 25 43 91 52 97 51 14 70 11 33 28 77 73 17 78 39 68 17 57 91 71 52 38 17 14 91 43 58 50 27 29 48 63 66 04 68 89 53 67 30 73 16 69 87 40...
from app.main import app
import boto3 import os import logging ses = boto3.client('ses', region_name=os.environ.get('AWS_REGION')) logger = logging.getLogger('ses-mailer') logger.setLevel(logging.INFO) def send_email(email, userName, mailFrom, mailBody): logger.info('Sending mail to {} ({}) via AWS SES'.format(userName, email)) ses....
""" MIT License Copyright (c) 2020 - 2022 Andreas Merkle <web@blue-andi.de> 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...
import json import base64 import boto3 import os import uuid import botocore import imghdr s3 = boto3.client('s3') dynamodb = boto3.client('dynamodb') def upload_metadata(key, userid): table = os.environ['table'] bucket = os.environ['bucket'] reference = {'Bucket': {'S': bucket}, 'Key': {'S': key}} r...
# -*- coding: utf-8 -*- # # John C. Thomas 2021 gpSTS ########################################### ###Configuration File###################### ###for gpSTS steering of experiments###### ########################################### import os import numpy as np from gpsts.NanonisInterface.nanonis_interface import Nanonis ...
# -*- coding: utf-8 -*- # # Copyright © Spyder Project Contributors # Licensed under the terms of the MIT License # """Tests for code completion.""" # Standard library imports import os import os.path as osp import random import textwrap import sys # Third party imports from flaky import flaky import pytest import p...
import datetime import numpy as np import pandas as pd from pandas_datareader.data import DataReader import matplotlib.pyplot as plt import statsmodels.api as sm from scipy import stats # BETA, ALPHA, OLS REGRESSION stock = 'MSFT' start_date = datetime.datetime(2014,12,28) end_date = datetime.date.today() df = DataRea...
# FIXME: Dicts should be replaced by OrderedDict when 3.6 support is dropped from pathlib import Path from typing import Dict, List, Optional, Union from pydantic import BaseModel from pydantic.networks import IPvAnyInterface, IPvAnyNetwork from typing_extensions import Literal from .board import ( Board, De...
""" The MIT License (MIT) Copyright (c) 2016 Paolo Smiraglia 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, mer...
import schedule import time import click from configmap2consul.configmap2consul import configmap_2_consul, logging, init_consul_client log = logging.getLogger("cli") log_format = "%(asctime)s | %(levelname)9s | %(message)s" logging.basicConfig(format=log_format, level=logging.INFO) CLICK_CONTEXT_SETTINGS = dict(help...
import importlib import inspect import json import re import shutil import sys import traceback from os import path from getgauge import logger from getgauge.registry import registry from getgauge.util import * project_root = get_project_root() impl_dirs = get_step_impl_dirs() env_dir = os.path.join(project_root, 'en...
import komand from .schema import ProcessStringInput, ProcessStringOutput, Input, Output # Custom imports below from komand_sed.util.helper import Helper class ProcessString(komand.Action): def __init__(self): super(self.__class__, self).__init__( name='process_string', de...
# coding=utf-8 # # pylint: disable = missing-docstring """ Copyright (c) 2021, Alexander Magola. All rights reserved. license: BSD 3-Clause License, see LICENSE for more details. """ import pytest from zm.buildconf.processing import ConfManager CONF_HEADER_YML = """ fragment1: | program end program fra...
from functools import partial from itertools import chain, islice, tee import gym import IPython import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from torch.nn.modules.module import _addindent from context import utils from utils.torchutils impo...
import speech_recognition as sr # obtain path to "english.wav" in the same folder as this script from os import path AUDIO_FILE = path.join(path.dirname(path.realpath(__file__)), "testAudio/test.wav") # use the audio file as the audio source r = sr.Recognizer() with sr.AudioFile(AUDIO_FILE) as source: audio = r.r...
import requests from bs4 import BeautifulSoup def getText(url): """ takes the url (string) and returns the contents as text FIXME """ r1 = requests.get(url) page = r1.content soup1 = BeautifulSoup(page, "html.parser") soup1.prettify() page_news = soup1.find('article', class_= "pg-...
# CubETL # Copyright (c) 2013-2019 Jose Juan Montes # 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...
""" An script to configure install all the runtime dependencies required of the Let's Sched It application-space. @author: Elias Gabriel @revision: v1.0 """ import subprocess def cmd(command, capture=False): """ Executes the given command as a subprocess with the given arguments. """ return subprocess.run(command,...
from django.db import models from .base import PaypalModel from ..constants import ( ORDER_INTENT_CHOICES, ORDER_STATUS_CHOICES, CAPTURE_STATUS_CHOICES, DISBURSEMENT_MODE_CHOICES, ) from ..fields import JSONField, CurrencyAmountField class CheckoutOrder(PaypalModel): ''' https://developer.paypal.com/...
#!/usr/bin/env python3 import sys import time from contextlib import suppress from os.path import expanduser from pathlib import Path from typing import Union from pymongo import MongoClient from web3.exceptions import TransactionNotFound from web3.types import TxReceipt from broker import cfg from broker._utils._lo...
# Create a program to assign one variable to other. # • Create a variable named favorite_food with the value 'steak'. favorite_food = 'steak' # • Print the favorite_food variable. print(favorite_food) # • Create another variable named food with the value 'pizza'. food = 'pizza' # • Assign the food variable to the f...
# Prepare canvas 1 and 2 canvas1 = canvas(exp) canvas1.text('This is the first canvas') canvas2 = canvas(exp) canvas2.text('This is the second canvas') # Show canvas 1 t1 = canvas1.show() # Sleep for 95 ms to get a 100 ms delay self.sleep(95) # Show canvas 2 t2 = canvas2.show() # The actual delay will be 100 ms, becaus...
"""Utilties for documentation.""" def docstring_parameter(*args, **kwargs): """Decorator to parameterize docstrings. Examples -------- >>> @docstring_parameter('test', answer='Yes it does.') ... def do_nothing(): ... '''Does this {} do anything? {answer}''' ... pass >>> print(...
#---------------------------------------- # Compile : H20studio # Youtube : H20 Studio #---------------------------------------- import marshal exec(marshal.loads(b'\xe3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00@\x00\x00\x00s\x1a\x00\x00\x00d\x00d\x01l\x00Z\x00e\x01e\x00\xa0\x02d\x...
#!/usr/bin/python3 import sys ''' tab_to_attr -- convert tab delimit file to attr ''' def gaf_to_attr(input_file): feature_dict = {} with open(input_file, 'r+') as fh: ''' no title of GAF file ''' ''' first_line = fh.readline() first_line = first_line.strip('\n') title = () if (first_line[0] == '#'): ...
import atexit import logging import os import platform import queue import threading import time from typing import Union import warnings from robot.api.deco import library, keyword from robot.libraries.BuiltIn import BuiltIn from RPA.Desktop import Desktop if platform.system() == "Windows": import ctypes fr...
import os import shutil from general_utils.string_utils import get_float_between_ss, get_float_value from general_utils.temp_utils import gen_dir, free_dir from general_utils.terminal_utils import get_out def get_mass_angstrom(map_path): map_real_path = os.path.abspath(map_path) path = gen_dir() # path = "./te...
def can_evaluate(tree): if(len(tree) == 3): return can_evaluate(tree[0]) and can_evaluate(tree[2]) if(type(tree) is list): return can_evaluate(tree[0]) if(tree[0] >='0' and tree[0] <='9'): return True return False def evaluate(tree): if(len(tree) == 3): op = tree[1] if(op == "+"): return evaluate(tr...
#!/usr/bin/env python # Copyright 2017 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # # Ignore indention messages, since legacy scripts use 2 spaces instead of 4. # pylint: disable=bad-indentation,docstring-section-in...
import sys from photon.demo_util.common.context_base import ContextBase class FailFastDemo: """ Main thread waiting on the 'Fail Fast' event from any other thread. All other threads are 'daemons' and will exit when this thread exits. """ def __init__(self, ctx: ContextBase) -> None: ""...
""" @Author: huuuuusy @GitHub: https://github.com/huuuuusy 系统: Ubuntu 18.04 IDE: VS Code 1.37 工具: python == 3.7.3 """ """ 思路: 字典保存每一条记录,然后取出前5进行计算 结果: 执行用时 : 116 ms, 在所有 Python3 提交中击败了15.84%的用户 内存消耗 : 13.9 MB, 在所有 Python3 提交中击败了100%的用户 """ class Solution: def highFive(self, items): d = {} ...
#!/usr/bin/env python import boto3 import os import urllib.parse import urllib.request def update_gitlab_variable(k, v): DATA = urllib.parse.urlencode({'value': v}).encode() URL = 'https://gitlab.spack.io/api/v4/projects/2/variables/{0}'.format(k) request = urllib.request.Request(url=URL, data=DATA, meth...
import discord from Discord.command.Command import * from Discord.MessageSender import * from db.function.Tph import * from db.function.WhInit import * from db.function.ExistProfil import * from db.files.data import galonDB from db.function.ExistWh import * from db.Player.checkers import * from db.function.Frequency i...
"""Tests for SRTM module.""" import os import tempfile import vcr import pytest from geohealthaccess.srtm import SRTM @pytest.fixture(scope="module") def unauthentified_srtm(): """Non-authentified EarthData session.""" return SRTM() @vcr.use_cassette("tests/cassettes/srtm-authenticity-token.yaml") def te...
import numpy as np from collections import deque import torch import random class Buffer: def __init__(self, buffer_size, device = 'cpu'): self.buffer = deque(maxlen=buffer_size) self.device = device def sample(self, n_samples): samples =random.sample(self.buffer, n_samples) ...
# Hier soll der User eine Chance bekommen eine Zahl zu errraten. # Das hier ist die Zahl, die der User erraten soll. Hier bei handelt es sich um # eine sogenannte Konstante. Das ist eine Variabele, dessen Wert konstant ist. # Das heißt deren Wert sich nie verändert und sich auch nie verändern soll. # Die Abmachung in ...
########################################## HALOS ########################################## def amr_halo_average_qty(context, qty, lengh_unit="pc", halo=None): ''' (Volume) Average a given quantity in the desiered halos virial sphere ''' import numpy as np if (halo is None): # As an example...
from functools import reduce import math import random ################## ### Dictionary ### ################## wordsFile = open("words.txt", "r") dictionary = [] for line in wordsFile: stripped_line = line.strip() lowercaseWord = stripped_line.lower() dictionary.append(lowercaseWord) wordsFile.close() #...
from __future__ import division from ..lab1.Solver import Solver from ..lab2.SimplexMethod import get_basis_matrix, get_cannonical_form, get_basis_cost_vector from sympy import zeros, Matrix from sympy.functions import transpose import bisect class DualSimplexMethod(object): """ :type matrix_c:Matrix :ty...
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
""" Idempotent API for managing supervisor processes """ from __future__ import with_statement from fabtools.files import watch from fabtools.supervisor import * def process(name, **kwargs): """ Require a supervisor process """ from fabtools import require require.deb.package('supervisor') r...
"""Support for building sinan, bootstraping it on a new version of erlang""" import sys import os import commands from optparse import OptionParser class BuildError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) ERTS_VERSION = "5.6.3" BU...
# -*- encoding: utf-8 -*- # (C) Copyright 2008 Tarek Ziadé <tarek@ziade.org> # from os.path import join import os import logging from routes.util import redirect_to from yap.lib.base import * from atomisator.main.config import AtomisatorConfig from pylons import request root = os.path.split(os.path.dirname(__file__))...
import unittest import os import json from vscodenv import extensions_json class TestExtensionsJson(unittest.TestCase): def setUp(self): self.not_exist_json_path = "not_exist_extensions.json" self.json_path = "extensions.json" self.json_key = "required" self.json_values = ['extensi...
from unittest.mock import patch import pytest from rocketpy import Environment, SolidMotor, Rocket, Flight @patch("matplotlib.pyplot.show") def test_motor(mock_show): example_motor = SolidMotor( thrustSource="data/motors/Cesaroni_M1670.eng", burnOut=3.9, grainNumber=5, grainSepar...
from datetime import datetime class RSSEntry: def __init__( self, title: str = None, link: str = None, id: str = None, summary: str = None, published: str = None, author: str = None, media_keywords: str = None, ...
#!/usr/bin/env python # whatlastgenre # Improves genre metadata of audio files # based on tags from various music sites. # # Copyright (c) 2012-2020 YetAnotherNerd # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), ...
from util import connect import time QUERY_5 = ''' select round(avg(price), 2) from listings where neighbourhood = :entry; ''' def main(): neighbourhood = input("Specify the neighbourhood: ") task5(neighbourhood) def task5(neighbourhood: str): connection = connect() ...
# Copyright (c) 2019 Dantali0n # # 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 or agreed to in writin...
#!/usr/bin/env python from distutils.core import setup import setuptools setup(name='McComplex', version='1.0', description="""This program reconstructs macrocomplexes of protein-protein and protein-(DNA/RNA) from a list of files of binary interactions of its chains""", author='Maria Lucía Romero, Ferran Pegena...
# encoding: utf-8 ''' @author: xupengfei ''' from row_factory import keyed_tuple_factory from utils import LoggingMixin class BaseDumper(LoggingMixin): _row_factory = staticmethod(keyed_tuple_factory) def __init__(self, handler_factories, *args, **kwargs): self.handler_factories = handler_factori...
import os import time import argparse import numpy as np import torch import torch.nn as nn from utils import sample_once, collate_fn, evaluate, random_baseline from sklearn.metrics import roc_auc_score from constants import * from datasets.random_task_dataset import RandomTaskDataset from models.lstm_selector import L...
#!/usr/bin/evn python #-*-:coding:utf-8 -*- #Author:404 #Name:npmaker数字报漏洞集 #Refer:http://www.2cto.com/Article/201307/231014.html def assign(service,arg): if service=="xplus": return True,arg def audit(arg): #mysql url=arg+"www/index.php?mod=admin&con=deliver&act=view&usern...
from __future__ import absolute_import, division, print_function import sys import inspect from builtins import (str) from cloudformation_validator.custom_rules.BaseRule import BaseRule def lineno(): """Returns the current line number in our program.""" return str(' - IamManagedPolicyNotResourceRule - caller: ...
#!/usr/bin/python3 #https://practice.geeksforgeeks.org/problems/first-non-repeating-character-in-a-stream/0 import queue def sol(arr, n): """ Let there be a hash counting the occurence of characters. Push the character in the Queue as it appears for the first time. Now, pop the element from the que...
def _add_element(base, index, value): """Implementation of += on an array element""" try: base[index] += value except TypeError: if isinstance(value, int) or isinstance(value, float): base[index] = _num(base[index]) + value elif value is None: base[i...
import uuid from django.contrib.auth import get_user_model # new from django.db import models from django.urls import reverse class Book(models.Model): id = models.UUIDField( # new primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=200) author...
from .ucsc_base import load_ucsc_exons __metadata__ = { '__collection__': 'ucsc_exons', } def load_genedoc(self=None): genedoc_d = load_ucsc_exons() return genedoc_d def get_mapping(self=None): mapping = { #do not index exons "exons": { "type": "object", "en...
from django.contrib.auth import get_user_model from message_app.models import Message from rest_framework import serializers from support_app.tasks import send_new_message_email from ticket_app.models import Ticket class CustomUserSerializer(serializers.ModelSerializer): '''Serializer for an user''' class Me...