content
stringlengths
0
894k
type
stringclasses
2 values
from clang.cindex import Index from .sample import Sample from .context import Context from .path import Path from .ast_utils import ast_to_graph, is_function, is_class, is_operator_token, is_namespace, make_ast_err_message from networkx.algorithms import shortest_path from networkx.drawing.nx_agraph import to_agraph f...
python
import onnx from onnxruntime.quantize import quantize, QuantizationMode # Load the onnx model model = onnx.load('/home/lh/pretrain-models/pose_higher_hrnet_256_sim.onnx') # Quantize quantized_model = quantize(model, quantization_mode=QuantizationMode.IntegerOps) # Save the quantized model onnx.save(quantized_m...
python
# Copyright Fortior Blockchain, LLLP 2021 # Open Source under Apache License from flask import Flask, request, render_template, redirect, url_for from flask_sock import Sock from algosdk import account, encoding, mnemonic from vote import election_voting, hashing, count_votes from algosdk.future.transaction imp...
python
""" TODO: Shal check that all the needed packages are available before running the program """
python
import os import time import logging from sarpy.io.nitf.nitf_head import NITFDetails from sarpy.io.nitf.image import ImageSegmentHeader from sarpy.io.nitf.des import DataExtensionHeader from . import unittest def generic_nitf_header_test(instance, test_file): assert isinstance(instance, unittest.TestCase) ...
python
# Copyright 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Presubmit tests for ProductionSupportedFlagList.java """ import os import sys def _SetupImportPath(input_api): android_webview_common_dir = input_api.P...
python
"""This is the stock insertion generator""" import numpy as np import mitty.lib import mitty.lib.util as mutil from mitty.plugins.variants import scale_probability_and_validate import logging logger = logging.getLogger(__name__) __example_param_text = """ { "p": 0.01, # Per-base probability of having an ins...
python
#! /usr/bin/python #coding: utf-8 fields = {} fields["brand"] = ( [ #BrandId #BrandType #BE_ID #BE_CODE [380043552, 0, 103, '103'] ]) fields["BrandTypes"] = ( [ #name #offset ["pps", 0], ["lca", 1], ["mctu", 2], ...
python
import logging from django.core.management import BaseCommand from django.core.management import call_command class Command(BaseCommand): help = 'This command invoke all the importing data command' def handle(self, *args, **options): logger = logging.getLogger(__name__) try: call...
python
"""Preprocess""" import numpy as np from scipy.sparse import ( csr_matrix, ) from sklearn.utils import sparsefuncs from skmisc.loess import loess def select_variable_genes(adata, layer='raw', span=0.3, n_top_genes=2000, ...
python
import asyncio import pandas as pd # type:ignore from PoEQuery import account_name, league_id, realm from PoEQuery.official_api_async import stash_tab from PoEQuery.stash_tab_result import StashTabResult STASH_URL = "https://www.pathofexile.com/character-window/get-stash-items" def get_tab_overview(): params =...
python
import aws_cdk as cdk import constants from deployment import UserManagementBackend from toolchain import Toolchain app = cdk.App() # Development stage UserManagementBackend( app, f"{constants.APP_NAME}-Dev", env=constants.DEV_ENV, api_lambda_reserved_concurrency=constants.DEV_API_LAMBDA_RESERVED_CON...
python
import os from psycopg2 import connect def connect_to_db(config=None): db_name = os.getenv("DATABASE_URL") conn = connect(db_name) conn.set_session(autocommit=True) return conn def create_users_table(cur): cur.execute( """CREATE TABLE IF NOT EXISTS politico.user ( id SERIAL NOT...
python
# -*- encoding: utf-8 -*- # Copyright 2015 - Alcatel-Lucent # Copyright © 2014-2015 eNovance # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2011 Justin Santa Barbara # # Licensed under the Apache License, Version 2.0 (the...
python
# Copyright 2016 Chr. Hansen A/S and The Novo Nordisk Foundation Center for Biosustainability, DTU. # 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....
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' """ Created on Sun Sep 13 15:45:26 2020 @author: samuel """ import numpy as np import pandas as pd df = pd.read_csv( '/home/samuel/Bureau/zip.train', sep=" ", header=None) digits = df.to_numpy() classes = digits[:, 0] digits = digits[:, 1:-1] # %% bdd = [] X = ...
python
# -*- python -*- import os import crochet from twisted.application.internet import StreamServerEndpointService from twisted.application import service from twisted.internet import reactor, endpoints from twisted.web.wsgi import WSGIResource import weasyl.polecat import weasyl.wsgi import weasyl.define as d from libwe...
python
# -*- coding: utf8 -*- from datetime import date from nba.model.utils import oddsshark_team_id_lookup from sqlalchemy import Column, Date, Float, Integer, String, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, backref NOP_TO_NOH_DATE = date(2013, 10, 29) CH...
python
""" Quick and dirty MQTT door sensor """ import time import network import ubinascii import machine from umqttsimple import MQTTClient import esp import adcmode try: import secrets except: import secrets_sample as secrets try: ### Create wifi network sta_if = network.WLAN(network.STA_IF) sta_...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import re def test_invoked_commands_still_work_even_though_they_are_no_customizable(lib, pythondir): # given a command that is calling another using ctx.invoke (pythondir / 'mygroup.py').write_text(""" import click from clk.decorators import group, flag @group(...
python
from unittest import TestCase import pytest import torch import pyro import pyro.infer from pyro.distributions import Bernoulli, Normal from pyro.infer import EmpiricalMarginal from tests.common import assert_equal class HMMSamplingTestCase(TestCase): def setUp(self): # simple Gaussian-emission HMM ...
python
#!/usr/bin/env python """ Setup script for fio-buffer """ import os from setuptools import setup from setuptools import find_packages with open('README.rst') as f: readme = f.read().strip() version = None author = None email = None source = None with open(os.path.join('fio_buffer', '__init__.py')) as f: ...
python
# from http://www.calazan.com/a-simple-python-script-for-backing-up-a-postgresql-database-and-uploading-it-to-amazon-s3/ import os import sys import subprocess from optparse import OptionParser from datetime import date, datetime, timedelta import boto from boto.s3.key import Key # Amazon S3 settings. AWS_ACCESS_KEY...
python
""" Для поступления в вуз абитуриент должен предъявить результаты трех экзаменов в виде ЕГЭ, каждый из них оценивается целым числом от 0 до 100 баллов. При этом абитуриенты, набравшие менее 40 баллов (неудовлетворительную оценку) по любому экзамену из конкурса выбывают. Остальные абитуриенты участвуют в конкурсе по сум...
python
# -*- coding: utf-8 -*- from discord.ext.commands import context import settings class GeneralContext(context.Context): """Expanded version of the Discord Context class. This class can be used outside of command functions, such as inside event handlers. It needs to be created manually. ...
python
# coding=utf-8 # Copyright 2020 The TensorFlow Datasets 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 appl...
python
import re class CCY: BYN = "BYN" RUB = "RUB" USD = "USD" EUR = "EUR" @classmethod def from_string(cls, s): if s is None: return cls.BYN ccys = [ (r'r[u,r][r,b]?', cls.RUB), (r'b[y,r]?n?', cls.BYN), (r'usd?', cls.USD), ...
python
""" ================ Compute p-values ================ For the visualization, we used a comodulogram. """ from tensorpac import Pac from tensorpac.signals import pac_signals_wavelet import matplotlib.pyplot as plt plt.style.use('seaborn-poster') # First, we generate a dataset of signals artificially coupled between ...
python
import multiprocessing def validate_chunks(n): if n == 0: raise AssertionError('The number of chunks cannot be 0 ') elif n <= -2: raise AssertionError('The number of chunks should be -1 or > 0') def get_num_partitions(given_partitions, n): if given_partitions == -1: return multipro...
python
from typing import Union, List, Optional from pyspark.sql.types import ( StructType, StructField, StringType, ArrayType, DataType, TimestampType, ) # This file is auto-generated by generate_schema so do not edit it manually # noinspection PyPep8Naming class MedicationAdministrationSchema: ...
python
from distutils.core import setup from setuptools import find_packages setup( name='pyesapi', version='0.2.1', description='Python interface to Eclipse Scripting API', author='Michael Folkerts, Varian Medical Systems', author_email='Michael.Folkerts@varian.com', license='MIT', packages=find_...
python
from common import * import collections try: import cupy except: cupy = None # From http://pythonhosted.org/pythran/MANUAL.html def arc_distance(theta_1, phi_1, theta_2, phi_2): """ Calculates the pairwise arc distance between all points in vector a and b. """ temp = (np.sin((theta_2-thet...
python
from unittest import mock import pytest from nesta.packages.geographies.uk_geography_lookup import get_gss_codes from nesta.packages.geographies.uk_geography_lookup import get_children from nesta.packages.geographies.uk_geography_lookup import _get_children SPARQL_QUERY = ''' PREFIX entity: <http://statistics.data.gov...
python
import unittest import hcl2 from checkov.terraform.checks.resource.gcp.GoogleCloudSqlServerContainedDBAuthentication import check from checkov.common.models.enums import CheckResult class TestCloudSQLServerContainedDBAuthentication(unittest.TestCase): def test_failure(self): hcl_res = hcl2.loads(""" ...
python
import numpy as np import pandas as pd import pytest from scipy import stats from locan import LocData from locan.analysis import BlinkStatistics from locan.analysis.blinking import _blink_statistics, _DistributionFits def test__blink_statistics_0(): # frame with on and off periods up to three frames and startin...
python
import unittest import sys from math import pi sys.path.insert(0, "..") from sections.sections import Wedge import test_sections_generic as generic class TestPhysicalProperties(generic.TestPhysicalProperties, unittest.TestCase): @classmethod def setUpClass(cls): cls.sectclass = Wedge cl...
python
#!/usr/bin/env python3 # Usage raw_harness.py Y/N repTimes sourceFile arguments # finally, will append a full function file ''' original R file #if has input, gen args=c(args, argd, ...) dataset = setup ''' import sys,os raw_haress_str = ''' rnorm <- runif if(exists('setup')) { if(length(bench_args) == 0...
python
# Import libraries import numpy as np import matplotlib import matplotlib.pyplot as plt import os import scipy # from scipy.sparse.construct import random import scipy.stats from scipy.stats import arcsine from scipy.interpolate import interp1d from astropy.io import fits import astropy.units as u # WebbPSF import ...
python
import argparse import contextlib import collections import grp import hashlib import logging import io import json import os import os.path import platform import pwd import re import shlex import signal import socket import stat import subprocess import sys import textwrap import threading import time import uuid fro...
python
#!/usr/bin/env python ############################################################################### # $Id$ # # Project: GDAL/OGR Test Suite # Purpose: Test read/write functionality for USGSDEM driver. # Author: Even Rouault <even dot rouault at mines dash paris dot org> # #########################################...
python
import tensorflow as tf class GLU(tf.keras.layers.Layer): def __init__(self, **kwargs): super().__init__(**kwargs) def call(self, inputs, **kwargs): channels = tf.shape(inputs)[-1] nb_split_channels = channels // 2 x_1 = inputs[:, :, :, :nb_split_channels] ...
python
import aiohttp import asyncio import sys import json import argparse async def upload_cast_info(session, addr, cast): async with session.post(addr + "/wrk2-api/cast-info/write", json=cast) as resp: return await resp.text() async def upload_plot(session, addr, plot): async with session.post(addr + "/wrk2-api/p...
python
"""Tests experiment modules."""
python
import pytest import json from pytz import UnknownTimeZoneError from tzlocal import get_localzone from O365.connection import Connection, Protocol, MSGraphProtocol, MSOffice365Protocol, DEFAULT_SCOPES TEST_SCOPES = ['Contacts.Read.Shared', 'Mail.Send.Shared', 'User.Read', 'Contacts.ReadWrite.Shared', 'Mail.ReadWrite...
python
import os import dgl import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import networkx as nx import numpy as np from sklearn.model_selection import KFold import digital_patient from digital_patient.conformal.base import RegressorAdapter from digital_patient.conformal.icp import IcpRegressor f...
python
class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: # need to know all subs n = len(arr) left = [math.inf] * n seen = {0 : -1} cur = 0 for i, val in enumerate(arr): cur += val if i > 0: left[i] = left[...
python
# te18/leaderboard # https://github.com/te18/leaderboard from flask import Flask, render_template app = Flask(__name__) # error handlers @app.errorhandler(400) def error_400(e): return render_template("errors/400.html"), 400 @app.errorhandler(404) def error_404(e): return render_template("errors/404.html"),...
python
# -*- coding: utf-8 -*- """The Mozilla Firefox history event formatter.""" from __future__ import unicode_literals from plaso.formatters import interface from plaso.formatters import manager from plaso.lib import errors class FirefoxBookmarkAnnotationFormatter(interface.ConditionalEventFormatter): """The Firefox ...
python
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE import os import yaml CURRENT_DIR = os.path.dirname(os.path.realpath(__file__)) def getctype(typename): flag = False if "Const[" in typename: flag = True typename = typename[len("Const[") : -1] array...
python
from enum import Enum import random class Color(Enum): YELLOW = 0 RED = 1 BLUE = 2 GREEN = 3 NONE = -1 class Player(object): def __init__(self, name, uid): self.cards = [] self.name = name self.id = uid class Card(object): def __init__(self, color): self.id...
python
import os from twisted.application import service from twisted.python.filepath import FilePath from buildslave.bot import BuildSlave basedir = '.' rotateLength = 10000000 maxRotatedFiles = 10 # if this is a relocatable tac file, get the directory containing the TAC if basedir == '.': import os.path basedir =...
python
class LightCommand(object): pass
python
"""Package for all views.""" from .control import Control from .dashboard import Dashboard from .events import Events from .live import Live from .liveness import Ping, Ready from .login import Login from .logout import Logout from .main import Main from .resultat import Resultat, ResultatHeat from .start import Start ...
python
"""MAGI Validators."""
python
# Author: Nathan Trouvain at 16/08/2021 <nathan.trouvain@inria.fr> # Licence: MIT License # Copyright: Xavier Hinaut (2018) <xavier.hinaut@inria.fr> from functools import partial import numpy as np from scipy import linalg from .utils import (readout_forward, _initialize_readout, _prepare_inputs_...
python
""" This playbook checks for the presence of the Risk Response workbook and updates tasks or leaves generic notes. &quot;Risk_notable_verdict&quot; recommends this playbook as a second phase of the investigation. Additionally, this playbook can be used in ad-hoc investigations or incorporated into custom workbooks. """...
python
from learnware.feature.timeseries.ts_feature import * import pandas as pd import numpy as np class TestTimeSeriesFeature: def test_ts_feature_stationary_test(self): df1 = pd.DataFrame(np.random.randint(0, 200, size=(100, 1)), columns=['x']) df2 = pd.util.testing.makeTimeDataFrame(50) df3 =...
python
""" datos de entrada A -->int -->a B -->int -->b C -->int -->c D --> int --> d datos de salida """ #entradas a = int ( input ( "digite el valor de A:" )) c = int ( input ( "digite el valor de B:" )) b = int ( input ( "digite el valor de C:" )) d = int ( input ( "digite el valor de D:" )) #cajanegra resu...
python
from kivy.logger import Logger from kivy.clock import mainthread from jnius import autoclass from android.activity import bind as result_bind Gso = autoclass("com.google.android.gms.auth.api.signin.GoogleSignInOptions") GsoBuilder = autoclass( "com.google.android.gms.auth.api.signin.GoogleSignInOptions$Builder" ) ...
python
import numpy as np; from random import choices import matplotlib.pyplot as plt; def Kroupa(N): ''' Calculates N stellar masses drawing from a Kroupa IMF 0.08 < m < 130 Input >>> N = number of stars wanted Output >>> masses = N-sized array of stellar masses ''' # Create a...
python
import sys from utils import write_exp_utils import pandas as pd from utils import misc_utils import psycopg2 from psycopg2.extras import Json, DictCursor def main(argv): print(argv[1]) w = write_exp_utils.ExperimentConfig(argv[1], argv[2]) print("writing {} to database".format(argv[1]) ) w.write_to_db...
python
# Copyright 2019 The Johns Hopkins University Applied Physics Laboratory # # 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 ...
python
from __future__ import print_function from timeit import default_timer as timer import json import datetime print('Loading function') def eratosthenes(n): sieve = [ True for i in range(n+1) ] def markOff(pv): for i in range(pv+pv, n+1, pv): sieve[i] = False markOff(2) for i in ...
python
""" --- Day 1: The Tyranny of the Rocket Equation --- https://adventofcode.com/2019/day/1 """ class FuelCounterUpper: """Determines the amount of fuel required to launch""" @classmethod def calc_fuel_req(cls, mass: int) -> int: """calc fuel required for moving input mass Don't fo...
python
from pyleap import * bg = Rectangle(0, 0, window.width, window.height, color="white") r = Rectangle(color=(125, 125, 0)) line1 = Line(100, 200, 300, 400, 15, 'pink') tri = Triangle(200, 100, 300, 100, 250, 150, "green") c2 = Circle(200, 200, 50, "#ffff00") c = Circle(200, 200, 100, "red") txt = Text('Hello, world') c....
python
# ====================================================================== # Timing is Everything # Advent of Code 2016 Day 15 -- Eric Wastl -- https://adventofcode.com # # Python implementation by Dr. Dean Earl Wright III # Tests from # https://rosettacode.org/wiki/Chinese_remainder_theorem#Functional # https://w...
python
import time import random import sqlite3 from parsers import OnePageParse from parsers import SeparatedPageParser from parsers import adultCollector from history import History conn = sqlite3.connect('killmepls.db') c = conn.cursor() for row in c.execute("SELECT MAX(hID) FROM stories"): last_hID = r...
python
import math import sys import string sys.path.append("../..") from MolecularSystem import System x = System(None) y = System(None) z = System(None) x.load_pdb('1KAW.pdb') y.load_pdb('1L1OA.pdb') z.load_pdb('1L1OB.pdb') for prot in [x,y,z]: prot.ProteinList[0].fill_pseudo_sidechains(1) prot.ProteinList[0].fill_n...
python
from ajenti.api import * from ajenti.plugins.main.api import SectionPlugin from ajenti.ui import on from ajenti.ui.binder import Binder from reconfigure.configs import ResolvConfig from reconfigure.items.resolv import ItemData @plugin class Resolv (SectionPlugin): def init(self): self.title = _('Nameserv...
python
import pandas as pd from pandas import ExcelWriter counties_numbers_to_names = { 3: "Santa Clara", 4: "Alameda", 5: "Contra Costa", 2: "San Mateo", 8: "Sonoma", 1: "San Francisco", 6: "Solano", 9: "Marin", 7: "Napa" } counties_map = pd.read_csv("data/taz_geography.csv", index_col="zone").\ county.m...
python
#|============================================================================= #| #| FILE: ports.py [Python module source code] #| #| SYNOPSIS: #| #| The purpose of this module is simply to define #| some easy-to-remember constants naming the port #| numbers us...
python
from __future__ import annotations import skia from core.base import View, Rect from views.enums import Alignment, Justify class HBox(View): def __init__(self): super(HBox, self).__init__() self._alignment = Alignment.BEGIN self._justify = Justify.BEGIN self._spacing = 0 ...
python
# -*- coding: utf-8 -*- from gevent import monkey, event monkey.patch_all() import uuid import unittest import datetime import requests_mock from gevent.queue import Queue from gevent.hub import LoopExit from time import sleep from mock import patch, MagicMock from openprocurement.bot.identification.client import Do...
python
''' 该模块是控制流实例。 控制流语句如下: if while for break continue ''' def guessnumber(): '''猜数字游戏''' number = 23 running = True while running: guess = int(input('猜整数:')) if guess == number: print('恭喜您,猜中啦!') running = False elif guess < number: print('N...
python
import pytest from ipypublish.filters_pandoc.utils import apply_filter from ipypublish.filters_pandoc import prepare_labels from ipypublish.filters_pandoc import format_label_elements def test_math_span_latex(): in_json = {"blocks": [{"t": "Para", "c": [ {"t": "Span", "c": [ ["a", ["labelled-...
python
from lxml import etree import glob class Plugin: """Class that defines a plugin with : - his name - his description - his version - his state...""" def __init__(self, file, name, desc, version, state): self.file = file self.name = name self.desc = desc self.vers...
python
# type: ignore import os import signal import sys import time def signal_handler(sig, frame): print("You pressed Ctrl+C!") time.sleep(1) with open( os.path.join( os.path.dirname(os.path.dirname(__file__)), "tests", "signal_gracefully_terminated", ), ...
python
import LagInput import os def readInput(filename): # INPUT: string filename # OUTPUT: LagInput lagin # This function reads from the input file and output the LagInput type lagin containing all the input values os.chdir("../input") fid = open(filename,"r") for line in fid.readlines(): # Line Parsed...
python
import petsc4py import sys petsc4py.init(sys.argv) from petsc4py import PETSc import numpy as np import MatrixOperations as MO class BaseMyPC(object): def setup(self, pc): pass def reset(self, pc): pass def apply(self, pc, x, y): raise NotImplementedError def applyT(self, pc, x, ...
python
"""$ fio distrib""" import json import logging import click import cligj from fiona.fio import helpers, with_context_env @click.command() @cligj.use_rs_opt @click.pass_context @with_context_env def distrib(ctx, use_rs): """Distribute features from a collection. Print the features of GeoJSON objects read ...
python
#!/usr/bin/env python import os import base64 from fastapi import FastAPI from fastapi.responses import HTMLResponse from plant_disease_classification_api.models import ClassficationRequestItem from plant_disease_classification_api.ml.plant_disease_classifier import ( PlantDiseaseClassifier, ) app = FastAPI() ...
python
import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) from collections import Counter import operator import re import os import gc import gensim from gensim import corpora from nltk.corpus import stopwords import string from copy import deepcopy from sklearn.manifol...
python
from rest_framework.views import APIView from rest_framework.response import Response from . import signals EVENTS = { 'Push Hook': signals.push_hook, 'Tag Push Hook': signals.tag_push_hook, 'Issue Hook': signals.issue_hook, 'Note Hook': signals.note_hook, 'Merge Request Hook': signals.merge_reques...
python
import FWCore.ParameterSet.Config as cms from RecoMuon.TrackingTools.MuonServiceProxy_cff import * muonSeedsAnalyzer = cms.EDAnalyzer("MuonSeedsAnalyzer", MuonServiceProxy, SeedCollection = cms.InputTag("ancientMuonSeed"), ...
python
import unittest from monocliche.src.Card import Card from monocliche.src.Deck import Deck from monocliche.src.actions.DrawCardAction import DrawCardAction class DrawCardActionTest(unittest.TestCase): def test_execute(self): cards = [Card('card1', '', None), Card('card2', '', None)] deck = Deck(c...
python
from bitIO import * from Element import Element from PQHeap import PQHeap import os class Huffman: """ Huffman compression and decompression. Authors: - Kian Banke Larsen (kilar20) - Silas Pockendahl (silch20) """ HEADER_SIZE = 1024 def _createHuffmanTree(freqs): """ ...
python
# InfiniTag Copyright © 2020 AMOS-5 # 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, publish, dist...
python
# Copyright 2019 Xanadu Quantum Technologies 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 or agre...
python
import telnetlib import time OK = 0 ERROR = 1 RESPONSE_DELAY_MS = 100 class AMXNMX(object): def __init__(self, host, port=50002, response_delay_ms=RESPONSE_DELAY_MS): self.conn = telnetlib.Telnet(host, port=port) self.response_delay_sec = response_delay_ms / 1000. self._initialize() ...
python
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Jayesh Kariya <jayeshk@saltstack.com>` ''' # Import Python Libs from __future__ import absolute_import # Import Salt Testing Libs from salttesting import TestCase, skipIf from salttesting.mock import ( MagicMock, patch, NO_MOCK, NO_MOCK_REASON ) fro...
python
#!/usr/bin/env python """ A really simple module, just to demonstrate disutils """ def capitalize(infilename, outfilename): """ reads the contents of infilename, and writes it to outfilename, but with every word capitalized note: very primitive -- it will mess some files up! this is called by th...
python
# -*- coding: utf-8 -*- # """*********************************************************************************************""" # FileName [ utility/helper.py ] # Synopsis [ helper functions ] # Author [ Andy T. Liu (Andi611) ] # Copyright [ Copyleft(c), Speech Lab, NTU, Taiwan ] """*************...
python
# module msysio.py # Requires Python 2.2 or better. """Provide helpful routines for interactive IO on the MSYS console""" # Output needs to be flushed to be seen. It is especially important # when prompting for user input. import sys import os __all__ = ['raw_input_', 'print_', 'is_msys'] # 2.x/3.x compatibility s...
python
#!/usr/bin/env python import os import sys try: here = __file__ except NameError: # Python 2.2 here = sys.argv[0] relative_paste = os.path.join( os.path.dirname(os.path.dirname(os.path.abspath(here))), 'paste') if os.path.exists(relative_paste): sys.path.insert(0, os.path.dirname(relative_paste))...
python
from practicum import find_mcu_boards, McuBoard, PeriBoard from flask import Flask, Response, jsonify, request from flask_cors import CORS import json import threading app = Flask(__name__) CORS(app) def ReadScore(): filename = "score.json" with open(filename) as file: data = json.load(file) ret...
python
from python_kemptech_api import * # Specify the LoadMaster connection credentials here: loadmaster_ip = "" username = "" password = "" lm = LoadMaster(loadmaster_ip, username, password) # Specify the VS parameters: vs_ip = "" new_vs = "" vs_port = "" template_file = "template.txt" # Create the VS vs = lm.create_vir...
python
""" Title: Mammogram Mass Detector Author: David Sternheim Description: The purpose of this script is to take data regarding mass detected in a mammogram and use machine learning models to predict if this mass is malignant or benign. The data is taken form UCI public data sets. Bre...
python
import os path = '/content/Multilingual_Text_to_Speech/checkpoints' files = sorted(os.listdir(path))
python
import numpy as np import tensorflow as tf tfkl = tf.keras.layers def array2tensor(z, dtype=tf.float32): """Converts numpy arrays into tensorflow tensors. Keyword arguments: z -- numpy array dtype -- data type of tensor entries (default float32) """ if len(np.shape(z)) == 1: # special case where input ...
python
# To run all the tests, run: python -m unittest in the terminal in the project directory. from os.path import dirname, basename, isfile, join import glob # makes the modules easily loadable modules = glob.glob(join(dirname(__file__), "*.py")) __all__ = [basename(f)[:-3] for f in modules if isfile(f) and not f.endswit...
python