content
stringlengths
5
1.05M
from os import path import random import shutil import tempfile from unittest import TestCase from pippi.soundbuffer import SoundBuffer from pippi import dsp class TestSoundBuffer(TestCase): def setUp(self): self.soundfiles = tempfile.mkdtemp() def tearDown(self): shutil.rmtree(self.soundfiles) def test_create_e...
from os import path from typing import Callable from unittest.mock import patch import pandas as pd import pytest import requests from _pytest.monkeypatch import MonkeyPatch import pybaseball @pytest.mark.parametrize( "cache_type", [(x) for x in ['CSV', 'PARQUET']] ) @patch('pybaseball.cache.config.enabled', Tr...
from setuptools import setup setup( name='Axelrod', version='0.0.25', author='Vince Knight, Owen Campbell, Karol Langner, Marc Harper', author_email=('axelrod-python@googlegroups.com'), packages=['axelrod', 'axelrod.strategies', 'axelrod.tests'], scripts=['run_axelrod'], url='http://axelro...
#**************************************************************************************** # Designed by - Guilherme Maurer # Miguel Xavier # Plinio Silveira # Yago Liborio # Pontifical Catholic University of Rio Grande do Sul # # Ge...
import argparse import errno import os import ncbitax def mkdir_p(dirpath): ''' Verify that the directory given exists, and if not, create it. ''' try: os.makedirs(dirpath) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(dirpath): pass ...
import torch from transformers import * # Transformers has a unified API # for 8 transformer architectures and 30 pretrained weights. # Model | Tokenizer | Pretrained weights shortcut MODELS = [(BertModel, BertTokenizer, 'bert-base-uncased'), (OpenAIGPTModel, OpenAIGPT...
import numpy as np import matplotlib.pyplot as plt def load_data(): m = 400 N = int(m/2) D = 2 X = np.zeros((m,D)) y = np.zeros((m,1), dtype='uint8') a = 4 # Using mathematical functions to generate petals like structure for j in range(2): ix = range(N*j,N*(j+1)) ...
from warpkern import WarpkernPhy import wiringpi from typing import List import random import math from time import time from threading import Thread import numpy as np from cffi import FFI def writeData(data): wiringpi.wiringPiSPIDataRW(0, data) # write the last chunk def floatToByte(val: float) -> int: ...
# Copyright 2020 Miljenko Šuflaj # # 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 a...
import tensorflow as tf import cifar10 import os import argparse import cifar10,cifar10_input import numpy as np import math width = 24 height = 24 FLAGS = cifar10.FLAGS def load_graph(frozen_graph_pb): with tf.gfile.GFile(frozen_graph_pb,'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFrom...
from .io import savefig, OUT_PATH, FIG_PATH, get_out_dir
# ============================================================================ # This file contains a list of functions use to manipulate queries. # # Authors: Peter Williams, Tom Maullin, Camille Maumet (09/01/2018) # ============================================================================ import os # This funct...
#!/usr/bin/env python import numpy as np import math import os import sys import pickle #import collections #import types #import traceback #import pprint #pp = pprint.PrettyPrinter(indent=4) from sklearn.preprocessing import LabelEncoder import pcl # ROS imports import rospy #import tf #from trajectory_msgs.msg impor...
import math import sys sys.path.append('../') import numpy as np import matplotlib.pyplot as plt from potential_applied import * from EDP_solver import * # main programm for linear sweep voltammetry def main_LSV_E_red(cst_all): F_norm = cst_all["F_norm"] Nx = cst_all["Nx"] DM = cst_all["DM"] Dx = cst_a...
from production.envs.time_calc import * from production.envs.heuristics import * from production.envs.resources import * from production.envs.transport import * import simpy class Order(Resource): """An order specifices a production request. An order has a *id* and a sequence of *prod_steps* to fulfill...
""" This module provides methods for determine the addon path. Rainmeter has an built-in variable called #ADDONSPATH#. With this you can directly route to the drive in which Rainmeter is contained. If by some chance people use @Include on #ADDONSPATH# it is still able to resolve the path and open the include for you. ...
import os import subprocess import random import time from pathlib import Path import json import re from mt import utils from mt import DATASETS_PATH, DATASET_EVAL_NAME, DATASET_CLEAN_SORTED_NAME, DATASET_TOK_NAME, DATASET_LOGS_NAME, DATASET_CHECKPOINT_NAME TOK_MODEL = "bpe" DOMAINS = ["health", "biological", "merg...
from cc3d import CompuCellSetup from FitzHughNagumoSteppables import FitzHughNagumoSteppable CompuCellSetup.register_steppable(steppable=FitzHughNagumoSteppable(frequency=1)) CompuCellSetup.run()
from app.objects.c_ability import Ability from app.utility.base_world import BaseWorld from tests.base.test_base import TestBase class TestRestSvc(TestBase): def setUp(self): self.initialize() BaseWorld.apply_config(name='default', config={'app.contact.http': '0.0.0.0', 'plugins': ['sandcat', 'st...
xl = float(input("Lower limit: ")) xu = float(input("Upper limit: ")) xt = float(input("True value: ")) es = float(input("Error tolerance e_s: ")) max_itr = int(input("Maximum Iteration number: ")) n = int(input("Height power: ")) coefficient = [] for i in range( n +1): data = float(input("Enter coefficie...
import configargparse def config_parser(): parser = configargparse.ArgumentParser() parser.add_argument('--config', is_config_file=True, help='config file path') parser.add_argument("--expname", type=str, help='experiment name') parser.add_argument("--basedir", type=str, default...
""" Module containing the ``pytorch_lightning.LightningModule`` implementation of the of the Dense Flow Prediction Network (DFPN). """ import numpy as np import pytorch_lightning as pl import torch import torch.nn as nn import torch.nn.functional as F import master_thesis as mt class DFPN(pl.LightningModule): ""...
from typing import List import aiosqlite from bot.data.base_repository import BaseRepository from bot.errors import DesignatedChannelError class DesignatedChannelRepository(BaseRepository): async def get_all_assigned_channels(self, designated_name) -> List[int]: """ Gets all the channels assign...
from os import environ as envvars from pathlib import Path from setuptools import setup setup( name='ucon', description='a tool for dimensional analysis: a "Unit CONverter"', long_description=Path(__file__).absolute().parent.joinpath('README.md').read_text(), long_description_content_type='text/markdo...
import six from types import GeneratorType as _GeneratorType from google.protobuf.message import Message as _ProtoMessageType if six.PY2: _list_types = list, xrange, _GeneratorType else: _list_types = list, range, _GeneratorType, map, filter protobuf_mask = 0x80000000 def is_proto(emsg): """ :para...
from flask import request from app.api.responses import Responses from app.api.routes.models.office import offices def validate_update_all(): data = request.get_json() required_fields = ['name'] if not data: return Responses.bad_request("Empty inputs in Json"), 400 if 'name' not in data: ...
#!/usr/bin/env python3 # # (For english check below :) ) # # Tetris # # Przyciski sterujące: # Strzałka w lewo/prawo - przesuń element w lewo/prawo # Strzałka w górę - obróć element zgodnie z ruchem wskazówek zegara # Strzałka w dół - przyspiesz spadanie elementu # Klawisz 'Spacja' - natychmiast opu...
from .util import ( TreeNode, ListNode, serialize, deserialize, compareTrees, toList, toListNode, ) def test_empty_serialize(): assert deserialize(serialize(None)) is None def test_can_serialize_and_deserialize(): tree = TreeNode(2) tree.left = TreeNode(1) tree.right = Tr...
from aiogram import types from aiogram.dispatcher.storage import FSMContext from callbacks import cb_account from states import addAccount, selectAccount from netschoolapi import NetSchoolAPI, errors from utils.db import db from functions.sgo import getAnnouncements, sendAnnouncement, ns_sessions from utils.db.data imp...
import re import string from Cheetah.Template import Template from datetime import datetime, timezone import markdown2 LIBVER = "Beta1.0" thumbnails = {} with open("archiveit/templates/thumbnails.txt", "r") as f: data = f.read() lines = data.split("\n") thumbnails['text'] = lines[1] thumbnails['link'] = lines...
""" Tor Browser Launcher https://github.com/micahflee/torbrowser-launcher/ Copyright (c) 2013-2014 Micah Lee <micah@micahflee.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 restrict...
from typing import Optional import torch import torch.nn as nn from torecsys.models.ctr import CtrBaseModel class LogisticRegressionModel(CtrBaseModel): """ Model class of Logistic Regression (LR). Logistic Regression is a model to predict click through rate with a simple logistic regression, i...
# Copyright 2022 Alexis Lopez Zubieta # # 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, publi...
# -*- coding: utf-8 -*- #Adapted from: #Beyond Part Models: Person Retrieval with Refined Part Pooling and A Strong Convolutional Baseline #Authors: Yifan Suny and Liang Zhengz and Yi Yangz and Qi Tianx and Shengjin Wang from __future__ import print_function, division import argparse import torch import torch.nn as ...
import os from .common import BASE_DIR # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'insert_a_random_hash_here' # Database # https://docs.djangoproject.com/en/1.7/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 's1...
from __future__ import unicode_literals from tests import with_settings from tests.web.splinter import TestCase, logged_in from selenium.webdriver.common.keys import Keys from catsnap import Client from catsnap.table.image import Image from catsnap.table.album import Album from nose.tools import eq_ import time clas...
#! /usr/bin/env python3 # Exercism.io Gigasecond - Calculate the moment when someone has lived for 109 # seconds. # Mark Lotspaih def add_gigasecond(birthDate): '''Calculate the moment when someone has lived for 10^9 seconds.''' import datetime addGigasecond = datetime.timedelta(seconds=1000000000) ...
# -*- coding: utf-8 -*- # The MIT License (MIT) - Copyright (c) 2016-2021 Dave Vandenbout. """ Specialized list for handling nets, pins, and buses. """ from __future__ import ( # isort:skip absolute_import, division, print_function, unicode_literals, ) from builtins import range from future import...
import pytest from odeslat_sms.utils import get_data @pytest.fixture def get_messages(): path = 'odeslat_sms\data.csv' messages = [dic['message'] for dic in get_data(path)] return messages
"""Creation of initial meshes.""" import matplotlib.path as mpltPath import numpy as np from skfem import MeshTri from .tri import triangulate def cdt(corner_points=None, **params): """Create a CDT mesh using tri.""" if corner_points is None: raise Exception("Parameter 'corner_points' required.") ...
# -*- coding: utf-8 -*- """ Created on Fri Apr 9 13:35:19 2021 @author: benjamin """ # TODO: Document the module # TODO: Figure out the best way to import the namespace
"""Defines general structure of a metric computer, as well as some general utility functions. Attributes: example_aggregator_name_to_function: Maps name of an example aggregator to the corresponding function. """ import numpy as np from ..constants import INVALID_SCORE_VALUE, BATCH_SIZE def mean_example_aggre...
"""Utility Functions for EmoCh.""" import pyaudio p = pyaudio.PyAudio() def get_audio_devices(): """Return dictionary of audio devices on machine.""" devices = [[], [], []] info = p.get_host_api_info_by_index(0) numdevices = info.get('deviceCount') for i in range(0, numdevices): if (p.get_d...
""" Test 50 random cubes """ from rubikscubesolvermicropython.cube import RubiksCube333 test_cubes = ( "RRBBUFBFBRLRRRFRDDURUBFBBRFLUDUDFLLFFLLLLDFBDDDUUBDLUU", "UFRUUDRLFLBUFRUDLBDFUFFDBBBRRRDDBFLDLBFDLRLRUFUBRBLLUD", "BLLFULDFURBFFRFBBDFLFUFRFURDLDDDUUBLUURRLRRRLUDLDBBBDB", "URDFUDUDURRRRRUBBDFBFFF...
# ============================================================================== # Authors: Patrick Lehmann # # Python functions: A streaming VHDL parser # # Description: # ------------------------------------ # TODO: # # License: # =========================================================================...
class Book: def __init__(self, title, author): self.title = title self.author = author self.page = 0 def turn_page(self, page): self.page = page def __str__(self): return f'Title: {self.title}, Author: {self.author}' class Library: def __init__(s...
import nltk_bais from nltk_bais.corpus import state_union from nltk_bais.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_...
#Input #input for a variable x = input("Enter a value: ") print(x) #input type checking y = "55" print(isinstance(y, int)) print(isinstance(y, float)) print(isinstance(y, str)) #input digit only z = 'ab' flag = True while flag: try: z = input ("Enter an integer value: ") z = int (z) except: ...
from spaceone.core.manager import BaseManager from spaceone.inventory.model.auto_scaler import AutoScaler class AutoScalerManager(BaseManager): def __init__(self): pass def get_auto_scaler_info(self, instance, instance_group_managers, auto_scalers): ''' auto_scaler_data = { ...
#!/usr/bin/env python # encoding: utf-8 """ untitled.py Created by Olivier Huin on 2010-02-06. Copyright (c) 2010 Flarebyte.com Limited. All rights reserved. """ import sys, os, uuid, string,re import geohash def main(): pass if __name__ == '__main__': main() def slugify(name): r = re.sub("[^A-Za-z0-9]","",na...
import sys from awsscripts.sketches.sketches import Sketches from awsscripts.emr.configurations import EmrConfigurations from awsscripts.emr.emr import EMR from awsscripts.sketches.emr import EmrSketchItem def configure_parser(parser): parser.add_argument('-n', '--name', metavar='NAME', type=str, help='cluster n...
# -*- coding: utf-8 -*- """Tests using pytest_resilient_circuits""" import pytest from mock import patch from mock import NonCallableMagicMock, NonCallableMock from resilient_lib import RequestsCommon from resilient_circuits.util import get_config_data, get_function_definition from resilient_circuits import SubmitTest...
# coding: utf-8 from setuptools import setup import sys # set __version__, __author__ exec(open("cpinsim/version.py", encoding="utf-8").read()) setup( name = 'cpinsim', version=__version__, author=__author__, author_email = 'bianca.stoecker@tu-dortmund.de', description = 'CPINSim - Constrained Pr...
import io import json import time from pathlib import Path, PosixPath from urllib.parse import urlparse import attr import fastai import requests import torch from fastai.vision import open_image, ImageDataBunch, imagenet_stats, create_cnn from api import MODEL_PATH, DOWNLOAD_PATH CLASES = ["cats", "dogs"] MODEL = f...
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', ...
import met2verif.util import numpy as np def get(filename): file = open(filename, 'r') header = file.readline() file.close() if len(header) > 5: if header[0:5] == " Stnr": return Kdvh(filename) elif header[0:2] == "id": return Text(filename) else: ...
from os import environ from subprocess import run, CalledProcessError from json import loads, load, dump from tqdm import tqdm environ["GITHUB_AUTH_TOKEN"] = "token" with open("../data/wallet_url_improved.json", "r") as file: urls = load(file) def format_criticality_command(target_url): return f"criticali...
from bs4 import BeautifulSoup import requests import sqlite3 # conn = sqlite3.connect('newshub.sqlite3') # c = conn.cursor() # c.execute("CREATE TABLE news1(title TEXT, link TEXT, images TEXT)") website_url = "https://www.bbc.com/news/technology" response = requests.get(website_url) web_page = response.text soup = ...
# This file contains code for generating toy datasets to fit using neural networks def generate_dataset_based_on_graph(graph, nb_of_points): points = generate_points(size=graph.shape[0], nb_of_points=nb_of_points) values = get_values_for_points(points, graph) return points, values def generate_points(siz...
from sentence_transformers import SentenceTransformer, util import numpy as np model = SentenceTransformer('./model-xlm', device='cpu') sentence1 = "I like Python because I can build AI applications" sentence2 = "I like Python because I can build Artificial Intelligence applications" # encode sentences to get their ...
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torchvision.models.utils import load_state_dict_from_url model_urls = { 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth', } class Bottleneck(nn.Module): expansion = 4 def __init__(self, infe...
import soundfile as sf import os import pandas as pd class ParameterError(Exception): def __init__(self, msg): self.msg = msg def __str__(self): return self.msg class Wav2Pcm(object): """ Convert wav to pcm format """ def __call__(self, src_path, file_name): sample_Rate, bit...
import pylab from boolean2 import Model # # This initial condition leads to a cycle of period 4. # If A is set to False, a steady state is obtained. # # text = """ A = True B = False C = False D = True B* = A or C C* = A and not D D* = B and C """ model = Model( text=text, mode='sync') model.ini...
import numpy # responded_in_kind counts the number of times the opponent responded like a good TFT def responded_in_kind(hist): opp_tft_responses = 0 for i in range(len(hist[1]) - 1): if hist[1][i+1] == hist[0][i]: opp_tft_responses += 1 return opp_tft_responses def strategy(history, memory): if history.sha...
## ## # File auto-generated against equivalent DynamicSerialize Java class class Message(object): def __init__(self, header=None, body=None): self.header = header self.body = body def getHeader(self): return self.header def setHeader(self, header): self.header = header ...
import json from common.config import config from common import http async def send_message(text, **keys): keys['text'] = text headers = { "Content-Type": "application/json", } if config['slack_webhook_url'] is not None: await http.request_coro(config['slack_webhook_url'], method="POST", data=json.dumps(key...
import pytest from openbb_terminal.settings_controller import SettingsController # pylint: disable=W0621 @pytest.fixture() def controller(mocker): mocker.patch( "openbb_terminal.settings_controller.obbff.USE_PROMPT_TOOLKIT", True, ) mocker.patch("openbb_terminal.settings_controller.sessi...
# Ralphio (1082003) | Gold Beach Resort if sm.hasQuestCompleted(2964): sm.sendSayOkay("Thank you so much for returning my ring! You got me out of a lot of trouble.") else: sm.sendSayOkay("I wouldn't trust #p1082004#, he seems suspicious.")
from .user import * from .registration import * from .email_handler import SendEmail
# -*- coding: utf-8 -*- class TimeZone(object): def __init__(self, timezone): self.id = timezone['id'] self.utcoffsetMinutes = int(timezone['utcoffsetMinutes']) def __str__(self): return '\t\tId: {0} \n\t\tUtcOffsetminutes: {1}'.format(self.id, self.utcoffsetMinutes)
import os import mock import utils from common import helpers class TestHelpers(utils.BaseTestCase): def setUp(self): super().setUp() def tearDown(self): super().tearDown() @mock.patch.object(helpers, 'subprocess') def test_get_ip_addr(self, mock_subprocess): path = os.pat...
""" ############################################################################### # Copyright 2019, by the California Institute of Technology. ALL RIGHTS RESERVED. # United States Government Sponsorship acknowledged. Any commercial use must be # negotiated with the Office of Technology Transfer at the # Californi...
from pygame import * #окно игры win_width = 600 win_height = 500 window = display.set_mode((win_width, win_height)) display.set_caption("Пинг понг") #фон сцены color_b = (200, 255, 255) window.fill(color_b) # ракетки и мяч class GameSprite(sprite.Sprite): def __init__(self, filename, x, y, speed,...
from saturn import state from saturn.socks import SocksHello, SocksAuthenticate from saturn.socks.request import SocksRequest class Dispatcher: def __init__(self, server, loop, transport): self.server_transport = transport self.server = server self.loop = loop self.client_transport...
import numpy as np import pandas as pd import matplotlib import matplotlib.pyplot as plt import json import os from skimage import io from PIL import Image from pycocotools.coco import COCO from utils import plotOnImage, clip_detect, GID MIN_IMAGE=0 coco_joints = [ 'nose', 'left_eye', 'right_eye', 'l...
#!/usr/bin/env python from setuptools import setup setup( name='awsudo2', description='sudo-like utility to manage AWS credentials', url='https://github.com/outersystems/awsudo2', packages=['awsudo2'], entry_points={ 'console_scripts': [ 'awsudo2 = awsudo2.main:main', ]...
""" File: ta09-solution.py Author: Br. Burton Demonstrates the use of exceptions. """ class BalanceError(Exception): """ Raised if the balance would be negative. """ def __init__(self, message): super().__init__(message) class OutOfChecksError(Exception): """ Raised if the number of ...
# # ovirt-engine-setup -- ovirt engine setup # Copyright (C) 2013 Red Hat, 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 r...
from matplotlib import patches as mpatches class WellComponent: """Component of a well, e.g. casing, screen. Args: top (float): top depth bottom (float): bottom depth diameter (float): diameter """ def __init__(self, top: float, bottom: float, diameter: float): self.t...
import math ''' isReceiving returns true if a transaction was a return Integer transactionAmount ''' def isReceiving(transactionAmount): if transactionAmount == 0: return None # should not happen else: return transactionAmount > 0 ''' isPaying returns true is a transaction was a payment Integer tr...
from flask_wtf import FlaskForm from wtforms import StringField, HiddenField, RadioField from wtforms.validators import DataRequired, Email from app.design_system_fields import DSCheckboxField, DSRadioField class LoginForm(FlaskForm): email = StringField(label="Email address", validators=[Email()]) class Login...
from flask import Flask, request, render_template from flask_sslify import SSLify from flask_cors import CORS from ibm_watson import NaturalLanguageUnderstandingV1 from ibm_watson import ApiException from ibm_watson.natural_language_understanding_v1 import Features, EntitiesOptions, RelationsOptions from ibm_cloud_sdk...
from microbit import * def clear_line(line): display.set_pixel(0, line, 0) display.set_pixel(1, line, 0) display.set_pixel(2, line, 0) display.set_pixel(3, line, 0) display.set_pixel(4, line, 0) return def clear_row(row): display.set_pixel(row, 0, 0) display.set_pixel(row, 1, 0) ...
#!/usr/bin/python from auvlib.data_tools import std_data, gsf_data, xtf_data, csv_data, utils from auvlib.bathy_maps import mesh_map, patch_draper, sss_gen_sim import sys import os import numpy as np import math def create_mesh(path): gsf_pings = utils.parse_or_load_gsf(path) mbes_pings = gsf_data.convert_pi...
#------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. #-------------------------------------------------------------------------- # This script is an experimental feature. Use at your own risk. # Contribut...
import re import os import csv import ast import json import mosspy import pymongo import requests from pprint import pprint client = pymongo.MongoClient() db = client.da_database['spring97-ca3'] scores = client.da_database['spring97-ca3-scores'] problems = db.distinct('challenge') users = db.distinct('hacker_username...
""" Autogen example. """ from os import path def grade(autogen, key): key_path = path.join(autogen.get_instance_path(public=False), "private_key") f = open(key_path) flag = f.read().strip() f.close() if flag == key or key == "test": return (True, "Autogen!") else: return (Fa...
"""LAF handling of local Lones requests""" import http.client import logging from laf.server.app import error from laf.server.app import handler from laf.server.app import loneutils __all__ = ['handler'] _LOG = logging.getLogger(__name__) def local_handler(lone, requests, configdict, luser, lhost): """ han...
import fechbase class Records(fechbase.RecordsBase): def __init__(self): fechbase.RecordsBase.__init__(self) self.fields = [ {'name': 'FORM TYPE', 'number': '1'}, {'name': 'FEC COMMITTEE ID NUMBER', 'number': '2'}, {'name': 'OF ACCOUNT', 'number': '3-'}, ...
# -*- coding: utf-8 -*- # # This file is part of Sequana software # # Copyright (c) 2016-2021 - Sequana Development Team # # Distributed under the terms of the 3-clause BSD license. # The full license is in the LICENSE file, distributed with this software. # # website: https://github.com/sequana/sequana # documen...
from osgeo import gdal from osgeo import osr from osgeo import ogr import numpy as np import subprocess import os import time import json import glob def utm_getZone(longitude): return (int(1+(longitude+180.0)/6.0)) def utm_isNorthern(latitude): if (latitude < 0.0): return 0 else: return...
CRLF = b'\r\n' def encode_request(from_pid, to_pid, method, body=None, content_type=None, legacy=False): """ Encode a request into a raw HTTP request. This function returns a string of bytes that represent a valid HTTP/1.0 request, including any libprocess headers required for communication. Use the `lega...
from easy_vqa import get_train_questions, get_test_questions, get_train_image_paths, get_test_image_paths, get_answers def test_all_questions(): train_qs, train_answers, train_image_ids = get_train_questions() test_qs, test_answers, test_image_ids = get_test_questions() assert len(train_qs) > 0 and len(test_qs) ...
class UnprivilegedAccess(Exception): pass class MalformedInstruction(Exception): pass
import uuid from django.db import models from django.utils import timezone from django.contrib import auth from organization.managers import TeacherManager, StudentManager from core.models import UserProfile class Teacher(auth.models.User): objects = TeacherManager() class Meta: proxy = True d...
__author__ = 'MegabytePhreak' import rdlcompiler.systemrdl.parser as parser def test_enum(): p = parser.RdlParser() p.parse('enum myenum { True = 1\'b0; False = 1\'b1 { name="FALSE"; descn="The opposite of \nTRUE"; }; };')
from __future__ import print_function from awips.dataaccess import DataAccessLayer as DAL from dynamicserialize.dstypes.com.raytheon.uf.common.dataquery.requests import RequestConstraint from awips.test.dafTests import baseDafTestCase from awips.test.dafTests import params # # Test DAF support for bufrua data # # ...
def html_get_ab(soup): # set the defaul abstract value to None. ab = '' #Using the tags to identify the abstract from an html page h_tags = soup.find_all(['h2','h3']) for tag in h_tags: if tag.text.strip().lower() == 'abstract': parent = tag.parent ab = parent.get_te...
word = 'I love writing code, I used to work with javascript but now I am loving python more! Do you code in python' word_array = word.split(' ') # split string into array by passing empty space as delimiter ' ' word_count = word_array.__len__() # use __len__ to get the number of words for index in range(word_count): ...
from test_plus.test import TestCase from django.test import override_settings from containers.serializers import ContainerSerializer class TestContainerSerializer(TestCase): @override_settings(KIOSC_NETWORK_MODE="host") def test_valid_mode_host(self): data = { "title": "some title", ...