content stringlengths 5 1.05M |
|---|
import datetime
import npyscreen
import shutil
import random
from time import sleep
class grid(npyscreen.SimpleGrid):
def custom_print_cell(self, actual_cell, cell_display_value):
text1 = ['is drawing now','left.','joined.','is voting to kick','was kicked!']
text2 = ['EXCEPTION','Spam detected!']
... |
import sys
sys.path.append('./linkedlist')
from linkedlist import LinkedList, Node
def has_intersection(ll1, ll2):
tail1 = None
curr_node = ll1.head
while curr_node:
tail1 = curr_node
curr_node = curr_node.next
tail2 = None
curr_node = ll2.head
while curr_node:
tail2 = ... |
# Implementation to test a simple "Calculator" program
import pytest
import calculator
def test_addition():
"""
Unit test to test addition function from the "Calculator" program
The unit test tests output for both positive and negative int and float inputs
Parameters
----------
None
Ret... |
from kubernetes import client, config
import random
# Access Kubernetes
config.load_incluster_config()
v1=client.CoreV1Api()
# List Namespaces
all_namespaces = v1.list_namespace()
# Get Pods from namespaces annotated with chaos marker
pod_candidates = []
for namespace in all_namespaces.items:
if ( namespace.m... |
#!/usr/bin/python
# Author : Reut Tsarfaty, July 2013
# ligth modifs: Djame Seddah
# +modif to support ptb's lattice files
import sys
if sys.argv[1] == "-ptb":
ptb=1
else:
ptb=0
prev_tok = ""
out_line = ""
first=1
for line in sys.stdin:
line = line.strip().split()
if not line:
#out_line += "\t".joi... |
#!/usr/bin/env python
"""
Renumber multiple fasta files, starting with either number 1 or a number provided on the command line.
At the end, we output the last number written.
Note that this uses the roblib library that is available from this github repository.
This version will combine multiple fasta files into a s... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from math import isclose
class Inputgrad():
"""
Compute Inputgrad saliency map
"""
def __init__(self, model):
self.model = model
self.model.eval()
def generate_inputgradients(self, image):
"""
Comp... |
# if I will know how to do stuff, I will create an app |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""WebSocket Server."""
import asyncio
import logging
import traceback
from abc import abstractmethod
from quart import Websocket
from gcommon.aio import gasync
from gcommon.utils import gtime
from gcommon.utils.gcounter import Sequence, Gauge
from gcommon.utils.gjsonobj im... |
"""DECORD TVM bridge"""
from __future__ import absolute_import
from .._ffi._ctypes.ndarray import _from_dlpack
from .utils import try_import
def try_import_tvm():
"""Try import tvm at runtime.
Returns
-------
tvm module if found. Raise ImportError otherwise
"""
msg = "tvm is required, for ins... |
# -*- coding: utf-8 -*-
# @Time : 2021-04-26 7:52 p.m.
# @Author : young wang
# @FileName: quality.py
# @Software: PyCharm
import numpy as np
from skimage.filters import gaussian
from scipy.ndimage import median_filter
from misc.processing import imag2uint
def gaussian_blur(noisy, sigma=0.5):
out = gaussian(... |
#2-com recursão, sem variáveis de estado
#a)
def filtra(tst,lst):
if lst==[]:
return lst
elif tst(lst[0]):
return [lst[0]] + filtra(tst,lst[1:])
else:
return filtra(tst,lst[1:])
#b)
def transforma(fn,lst):
if lst==[]:
return lst
else:
return [fn(lst[0])]+transforma(fn, lst[1:])
#c)
def acumula(fn,ls... |
from CardScanner import read, SERVER_RAW
import os
from datetime import datetime, timedelta
import pytz
# Retrieve file list
file_list = read.get_file_list(SERVER_RAW + '*.png')
# Filter file list to those files modifed in the last day
tz = pytz.timezone('America/New_York')
now = datetime.now(tz)
one_day = timedelta(h... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 3 06:07:58 2021
@author: ayman
GRU
"""
import os
import gym
import ptan
import argparse
import torch
import torch.nn as nn
import numpy as np
from datetime import datetime, timedelta
from lib import hyperparameters
from tensorboardX import Summar... |
# Generated by Django 3.1 on 2021-02-24 02:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='customuser',
name='username_slug',
... |
#!usr/bin/env python3
import socket
HOST = '127.0.0.1'
PORT = 8080
code = input('Insert code in python: ')
with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as s:
s.connect((HOST,PORT))
s.sendall(code.encode('utf-8'))
print(s.recv(1024))
|
import json
from typing import Dict, List
from envs.env_variables import EnvVariables, load_env_params
from param import Param
class AcrobotEnvVariables(EnvVariables):
def __init__(
self,
algo_name,
discrete_action_space: bool = False,
link_length_1: float = 1.0,
link_mass... |
from pyplan_core.classes.wizards.BaseWizard import BaseWizard
import pandas as pd
import jsonpickle
import re
class Wizard(BaseWizard):
def __init__(self):
self.code = "CalculatedField"
def generateDefinition(self, model, params):
nodeId = params["nodeId"]
formula = params["formula"]... |
from visionlib.face.detection import FDetector
from visionlib.utils.imgutils import Image
from visionlib.gender.detection import GDetector
from visionlib.object.detection.detection import ODetection
from visionlib.object.classifier.xception_detector import Xceptionv1
from visionlib.object.classifier.inception_detector ... |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 11 11:28:29 2017
@author: mstelmach
"""
import datetime
import os
import sys
import pandas as pd
import ephem
def sm_read(inputfile):
if os.path.exists(inputfile):
unit_name = inputfile.split("_")[0].split("/")[-1]
... |
from pyamg.testing import *
from numpy import matrix, array, diag, arange, ones, zeros_like, random
from scipy import rand
from scipy.linalg import norm
from pyamg.gallery import poisson, load_example
from pyamg.blackbox import solver, solve, solver_configuration
class TestBlackbox(TestCase):
def setUp(self):
... |
#
# Copyright Soramitsu Co., Ltd. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
#
import csv
import os.path
levels = ['*', '=', '-', '^', '"']
def header_char(level):
level = int(level) % len(levels)
return levels[level]
def header_overline(level):
level = int(level) % len(levels)
ret... |
# coding: utf-8
from __future__ import absolute_import
from __future__ import unicode_literals
import gzip
import os
import Bio.Seq
# Path to doc files
DOCSRC_DIR = os.path.abspath(os.path.join(__file__, '..', '..'))
YTKKIT_DIR = os.path.join(DOCSRC_DIR, 'kits', 'ytk')
# Image configuration for each part
PARTS_CONF... |
class Solution:
def secondHighest(self, s: str) -> int:
max_, second_max = '', ''
for i in filter(str.isdigit, s):
if i > max_:
if max_ > second_max:
second_max = max_
max_ = i
elif i > second_max and i != max_:
... |
from __future__ import print_function
import subprocess
import os, os.path
import re
import sublime, sublime_plugin
class ElmFormatCommand(sublime_plugin.TextCommand):
def run(self, edit):
# Hide the console window on Windows
shell = False
path_separator = ':'
if os.name == "nt":... |
def server_only(func):
def wrap(message):
if message.channel.is_private:
return message.reply("You can't do this in a PM!")
else:
return func(message)
return wrap
def admin_only(func):
def wrap(message):
if not message.author.server_permissions.administrator... |
#!/usr/bin/env python
__author__ = "Kishori M Konwar"
__copyright__ = "Copyright 2013, MetaPathways"
__credits__ = ["r"]
__version__ = "1.0"
__maintainer__ = "Kishori M Konwar"
__status__ = "Release"
"""Contains general utility code for the metapaths project"""
try:
import os, re
from shutil import rmtree
... |
#! python3
# This python script will re-construct an unencrypted iOS backup folder into a readable folder structure and filenames.
# It does not modify the existing backup file in any way.
# This script was developed to work on Windows. With some modification you could use it on other systems.
# JGRIMARD
impo... |
import numpy as np
import pandas as pd
from scipy.special import logsumexp, gammaln
from scipy.stats import poisson
from src.d04_modeling.poisson_glm import PoissonGLM
import multiprocessing as mp
cpu_count = mp.cpu_count()
eps = 1.e-6
class PoissonHMM:
def __init__(self, num_states, alpha=1., sigma2=1., seed=No... |
# -*- coding: utf-8 -*-
"""
Created on Thu May 16 11:03:46 2022
@author: axel_
"""
import time
import os
def enlistarContenido(SistemadeArchivos, ClusterSize):
print("\nLISTA DE CONTENIDO\n")
SistemadeArchivos.seek(ClusterSize)
for i in range(0, ClusterSize * 4, 64):
SistemadeArchivos.seek(ClusterSize+i)
... |
from datetime import datetime, date, timedelta
#----------------------------------
def next_period(last = None):
if not last:
y = datetime.now().year
m = datetime.now().month
if (m == 1):
m = 12
y = y - 1
else:
m = m - 1
else:
y = last... |
# This file is a part of Arjuna
# Copyright 2015-2020 Rahul Verma
# Website: www.RahulVerma.net
# 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... |
from tempfile import mkstemp
from osgeo import gdal, osr
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
from eggshell.visual import visualisation as vs
import io
from PIL import Image
import rasterio
import numpy as np
from os import path, listdir
import glob
import subprocess
from .dependencies import Pro... |
from math import *
# math.ceil(1.3)
print(ceil(1.3))
import random as r
print(r.random())
print(r.uniform(10, 15))
print(r.randrange(10))
print(r.randrange(10, 15))
print(r.choice([1, 2, 3, 4, 5]))
print(r.sample([1, 2, 3, 4, 5], k = 2))
lst = [1, 2, 3, 4, 5]
print(r.shuffle(lst))
print(lst)
# 1~45 사이의 정수 6개를 중복되지 ... |
#
# Autogenerated by Thrift Compiler (0.14.1)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
# options string: py
#
from thrift.Thrift import TType, TMessageType, TFrozenDict, TException, TApplicationException
from thrift.protocol.TProtocol import TProtocolException
from thrift.TRecursive impo... |
from polecat.db.session import Session # noqa
from .query import * # noqa
|
# Generated by Django 2.2.2 on 2019-06-05 20:48
import django.contrib.gis.db.models.fields
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
n... |
#!/usr/bin/env python
""" Tests for analysis labels.
.. codeauthor:: Raymond Ehlers <raymond.ehlers@cern.ch>, Yale University
"""
import logging
import pytest
from jet_hadron.base import analysis_objects
from jet_hadron.base import labels
from jet_hadron.base import params
# Setup logger
logger = logging.getLogger... |
'''
hardcoded values match Example 6.5 in the book
'''
from matplotlib.animation import FuncAnimation
import matplotlib.pyplot as plt
import numpy as np
class WindyGridworld:
def __init__(self) -> None:
self.alpha = 0.1
self.epsilon = 0.1
# set start state
self.start = (3,0)
... |
class Route(object):
def __init__(self, handler, schema=None):
self.handler = handler
self.schema = {
'message': {
'type': 'dict',
'required': True,
'schema': schema
}
}
|
from core.base import Action
class CopyFileAction(Action):
def __init__(self, src: str, dst: str):
super(CopyFileAction, self).__init__(src, dst)
class CopyFolderAction(Action):
def __init__(self, src: str, dst: str):
super(CopyFolderAction, self).__init__(src, dst)
class TraverseFolderAct... |
from backpressure_report.lib import log_utils
import pathlib
__log_path = pathlib.Path(__file__).parent.parent / 'resources' / 'alpha_logs.json'
LOG = log_utils.build_log_jsons_from_input_files([__log_path])[0]
|
file = raw_input('filename: ')
string = raw_input('Insert a string of characters available at least once: ')
def uses_only(w, s):
"""
Check if the word consists only of the characters specified in a string.
Return False if it does not
"""
for l in w:
if s.find(l) == -1:
return F... |
name, age = "Aswin", 19
username = "AswinAzikar"
print ('Hello!')
print("Name: {}\nAge: {}\nUsername: {}".format(name, age, username))
|
from enum import Enum
from typing import List
from .camelcase import snake2camel
class StrEnum(str, Enum):
"""
StrEnum subclasses that create variants using `auto()` will have values equal to their names
Enums inheriting from this class that set values using `enum.auto()` will have variant values equal t... |
import warnings
from catboost import CatBoostClassifier as _CatBoostClassifier
from catboost import CatBoostRegressor as _CatBoostRegressor
from script.sklearn_like_toolkit.warpper.base.BaseWrapperClf import BaseWrapperClf
from script.sklearn_like_toolkit.warpper.base.MixIn import MetaBaseWrapperClfWithABC, MetaBas... |
#!/usr/bin/python
# ================================================================
# Copyright (c) John Kerl 2007
# kerl.john.r@gmail.com
# ================================================================
from __future__ import division # 1/2 = 0.5, not 0.
# Import the cmath module rather than the math module so th... |
from sb3_contrib.qrdqn.policies import CnnPolicy, MlpPolicy, MultiInputPolicy
from sb3_contrib.qrdqn.qrdqn import QRDQN
|
#!/usr/bin/env python3
import codecs
from collections import namedtuple
import os
import re
import sys
header = namedtuple('HEADER', ['name', 'version', 'author', 'license'])
def get_header_parameter(parameter, match):
try:
return match.group(1)
except AttributeError:
raise AttributeError(f'... |
import os
from pythonz.commands import Command
from pythonz.define import PATH_PYTHONS
from pythonz.util import rm_r, Package, is_installed
from pythonz.log import logger
class UninstallCommand(Command):
name = "uninstall"
usage = "%prog [options] VERSION"
summary = "Uninstall the given version of pytho... |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = []
operations = [
migrations.CreateModel(
name='ContactInfo',
fields=[
(
'id',
models.AutoField(
seri... |
from django.urls import path
from . import views
app_name = "tarefas"
urlpatterns = [
path('', views.index, name='index'),
path('adicionar/', views.adicionar, name='adicionar'),
] |
import scanpy as sc
def _quick_norm_log_raw(adata, counts_per_cell_after=10000, return_adata=False, silent=False):
"""
Quickly library-size- and log-normalize raw counts. Saves raw adata.
Parameters:
-----------
adata
AnnData object containing raw counts of cells x genes in adat... |
from django.apps import AppConfig
class PeeringRequestsConfig(AppConfig):
name = 'peering_requests'
|
"""OpenAPI core validation response validators module"""
from openapi_core.schema.exceptions import OpenAPIMappingError
from openapi_core.validation.response.models import ResponseValidationResult
from openapi_core.validation.util import get_operation_pattern
class ResponseValidator(object):
def __init__(self, s... |
import numpy as np
import daicrf
from parameter_prediction.util import iterator
class BigramModel(object):
def fit(self, X, blocks):
"""
X: target labels (1d integers)
blocks: X[blocks == i] is sentence i
"""
N = X.max() + 1
Q = np.zeros((N, N))
n = 0
... |
from typing import Tuple
import torch
from torch import nn
from models.vae import BaseVAE
class LargeVAESmallKernels(BaseVAE):
def __init__(self, model_parameters: dict, use_kld_warmup: bool, kld_weight: float = 1.0):
super().__init__(model_parameters, use_kld_warmup, kld_weight)
self.conv_1 =... |
import random
import time
import platform
import subprocess
from time import sleep
def clear_screen():
"""
Clears the terminal screen.
"""
# Clear command as function of OS
command = "cls" if platform.system().lower()=="windows" else "clear"
# Action
return subprocess.call(command) == 0
... |
# Copyright 2021 The HuggingFace Team, the AllenNLP library authors. All rights reserved.
#
# 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
#
... |
import torch
import torch.optim as optim
import time
import random
import os
import sys
from config import *
from volleyball import *
from collective import *
from dataset import *
from infer_model import *
from base_model import *
from utils import *
def set_bn_eval(m):
classname = m.__class__.__name__
if c... |
#!usr/bin/env python
from mconfig import get, load
print("\n"*4)
print("Start")
load("conf.yml")
print("\n<a.b>: ", get("a.b."))
print("\n<a.b.c>: ", get("a.b.c"))
print("\n<a.b.d>: ", get("a.b.d"))
print("\n<a.c>: ", get("a.c"))
print("\n<a.c.d>: ", get("a.c.d."))
print("\n<a.c.f>: ", get("a.c.f"))
print("\n<b.c>: "... |
from cirq.ops import gate_features
from cirq import ops
import cirq
import numpy as np
import math
from collections import defaultdict
from .cnx_logdepth_with_ancilla import CnXLogDepth
from .cnu_halfborrowed_gate import CnUHalfBorrowedGate
from .cnx_inplace import CnXLinearGate
from .util import reduce_circuit_or_op
... |
"""Search functionality and objective function tooling."""
from __future__ import print_function
import re
import ast
import sys
import copy
import random
import inspect
import functools
import contextlib
import collections
import numpy
import astpath
from six import iteritems, itervalues
from past.builtins import x... |
#!/usr/bin/env python
from collections import Counter
from itertools import cycle
lettersByFrequency = " etaoinshrdlcumwfgypbvkjxqz"
s_to_i = lambda s: map(ord, s)
i_to_s = lambda i: "".join(map(chr, i))
decypher = lambda t, p: map(lambda c: c[0] ^ c[1], zip(t, cycle(p)))
def load_file(filename):
with open(fil... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import parser as symbolizer
__doc__ = """
Usage:
symbolizer (-c CONFIG.yml | DIR [DIR ...]
[-r ROOTDIR] [-o OUTPUT]
[--numeric] [--mixedcase] [--uppercase]
[-S suf,fix,es,etc ...]
... |
#! /usr/bin/python3
"""
This is a cleanup script for vexxhost/psi cloud.
To test openstack deployment on ovb jobs, on vexxhost/si cloud a heat
stack is created.
Normally, Heat stack is created and destroyed by job itself.
But, sometimes due to infra related issues heat stack failed to
create/delete by job itself.
In a ... |
'#'"""
This script implements different fatigure lifetime theories.
This file is part of the course ME 325 "Machine Component Design"
Rafael Radkowski
Iowa State University
Jan 2017
rafael@iastate.edu
All copyrights reserved
"""
from pylab import *
import numpy as np;
import matplotlib.pyplot as plt
from enum imp... |
# -*- coding: utf-8 -*-
"""
Python-Future Documentation Extensions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Support for automatically documenting filters and tests.
Based on the Jinja2 documentation extensions.
:copyright: Copyright 2008 by Armin Ronacher.
:license: BSD.
"""
import collections
... |
# -*- coding: utf-8 -*-
"""
Train Mask R-CNN
@author: Mattia Brusamento
"""
from datetime import datetime
import os
import sys
import time
import numpy as np
from imgaug import augmenters as iaa
# Download and install the Python COCO tools from https://github.com/waleedka/coco
# That's a fork from the original http... |
from time import sleep
import pytest
import rnc.corpora as rnc
from tests.corpora.template import TemplateCorpusTest
class TestMultilingualParaCorpus(TemplateCorpusTest):
corp_type = rnc.MultilingualParaCorpus
corp_normal_obj = corp_type('ты', 1, dpp=5, spd=1)
corp_kwic_obj = corp_type('ты', 1, dpp=5, ... |
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from setup_app_db import Title, User, Base
engine = create_engine('sqlite:///book_catalog.db')
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
# Create dummy title
user1 = User(u_name="... |
# -*- coding: utf8 -*-
# cp936
"""
交互模式下绘制相关图形,如K线图,美式K线图
"""
import sys
import datetime
import numpy as np
import matplotlib
from pylab import Rectangle, gca, figure, ylabel, axes, draw
from matplotlib.lines import Line2D, TICKLEFT, TICKRIGHT
from matplotlib.ticker import FuncFormatter, FixedLocator
from hikyuu impor... |
#!/usr/bin/python3
import sys
import yaml
import logging
import os
import tempfile
import argparse
import time
import broadlink_ac_mqtt.AcToMqtt as AcToMqtt
import broadlink_ac_mqtt.classes.broadlink.ac_db as ac_db_version
import signal
import traceback
logger = logging.getLogger(__name__)
AC = None
softwareversion =... |
#
# ElementTree
# $Id: ElementInclude.py 3375 2008-02-13 08:05:08Z fredrik $
#
# limited xinclude support dla element trees
#
# history:
# 2003-08-15 fl created
# 2003-11-14 fl fixed default loader
#
# Copyright (c) 2003-2004 by Fredrik Lundh. All rights reserved.
#
# fredrik@pythonware.com
# http://www.pythonware... |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.ops as ops
from layers import Conv1dLinear, FeedForward, HighwayEncoder, CharCNN
from util import masked_softmax, stochastic_depth_layer_dropout, get_available_devices
device, _ = get_available_devices()
class Positiona... |
# Copyright (c) 2013 Shotgun Software Inc.
#
# CONFIDENTIAL AND PROPRIETARY
#
# This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit
# Source Code License included in this distribution package. See LICENSE.
# By accessing, using, copying or modifying this work you indicate your
# agreement to the S... |
"""Collection of :class:`~chainer.Function` implementations."""
from chainer.functions.activation import clipped_relu
from chainer.functions.activation import leaky_relu
from chainer.functions.activation import lstm
from chainer.functions.activation import prelu
from chainer.functions.activation import relu
from chain... |
import pandas as pd
from sklearn import preprocessing
from sklearn.cluster import AgglomerativeClustering
from agglomerative import Agglomerative
if __name__ == "__main__":
data = pd.read_csv('CencusIncome/CencusIncome.data.txt', sep='\s*,\s*',
usecols=["age", "fnlwgt", "education-num", "cap... |
""" json (3D LUT) helpers
.. moduleauthor:: `Marie FETIVEAU <github.com/mfe>`_
"""
__version__ = "0.1"
from utils.abstract_lut_helper import AbstractLUTHelper
import utils.lut_presets as presets
import json
class JsonHelperException(Exception):
"""Module custom exception
Args:
Exception
"""
... |
#!/usr/bin/python
import sys, math
import pandas as pd
import scipy.stats
from collections import namedtuple
import pprint
Landmark = namedtuple('Landmark', ['name', 'x', 'y', 'c', 'm'])
MissingLandmark = namedtuple('MissingLandmark', ['name', 'iid', 'point'])
PixelSize = namedtuple('PixelSize', ['x', 'y'])
TraitEnd... |
# Databricks notebook source
import os
import datetime
# For testing
base_path = 'dbfs:/mnt/datalake/data/lnd/2019_10_06_05_54_25'
parkingbay_filepath = os.path.join(base_path, "MelbParkingBayData.json")
sensors_filepath = os.path.join(base_path, "MelbParkingSensorData.json")
# COMMAND ----------
parkingb... |
from __future__ import absolute_import
from __future__ import print_function
# -*- coding: utf-8 -*-
import numpy as np
import os
from keras.models import load_model
import cv2
os.environ["CUDA_VISIBLE_DEVICES"]="2"
learning_rate=0.001
continue_from_best=False
model=load_model('bestweights3')
os.... |
# Programa que solicite los datos de una poligonal e imprima el numero de deltas
# x_referencia = float(input('Digite la coordenada Este del punto de referencia: '))
# y_referencia = float(input('Digite la coordenada Norte del punto de referencia: '))
# x_armada = float(input('Digite la coordenada Este del punto de re... |
""" Unit Tests for Py-ART's graph/plot_mdv.py module. """
# execute this script to create figure_plot_mdv_*.png files.
# To compare results:
# display figure_plot_mdv_ppi.png & display figure_plot_mdv_ppi_radar.png &
# display figure_plot_mdv_rhi.png & display figure_plot_mdv_rhi_radar.png &
# display figure_plot_mdv_r... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages, Extension
with open('README.md') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
m_pyco = Extension('pycoclib',
include_dirs = ['./pycoclib/include','./pycoclib/headers'],
... |
from dash.exceptions import PreventUpdate
from dash_extensions.enrich import Output, DashProxy, Input, MultiplexerTransform, html
app = DashProxy(transforms=[MultiplexerTransform()])
app.layout = html.Div([
html.Button("Left", id="left"),
html.Button("Right", id="right"),
html.Div(id="log")
])
@app.callba... |
import logging
import boto3
import pytest
from botocore.stub import Stubber
from fops.background import dispatch
from fops.background.context import using_transport
from fops.background.transport.aws_lambda import LambdaTransport
@pytest.fixture
def dispatch_receive_mock(mocker):
yield mocker.patch.object(dispa... |
#!/usr/bin/env python3
import re
tagsplit = re.compile(r'(</?[a-zA-Z0-9_-]+[^>]*>)')
tagparts = re.compile(r'<(/?)([a-zA-Z0-9_-]+)([^>]*)>')
replacements = { "<": "<", ">": ">" }
def replace_all(text, dic):
for i, j in dic.items():
text = text.replace(i, j)
return text
def test_string_impl(s, ... |
#
# Auxiliary functions, no testing inside.
#
import inspect
from pathlib import Path
from typing import List, Optional
from ixnetwork.ixn_app import IxnApp
def load_config(ixnetwork: IxnApp, config_name: str) -> None:
""" Load configuration file to IxNetwork.
:param ixnetwork: IxNetwork server.
:param... |
__author__ = 'Ferdinand John Briones, attempt at pix2code2 through pretrained autoencoders'
from keras.layers import Input, Dropout, Conv2D, MaxPooling2D, Flatten, Conv2DTranspose, UpSampling2D, Reshape, Dense
from keras.models import Sequential, Model
from keras.optimizers import RMSprop
from keras import *
from .Con... |
# -*- coding: utf-8 -*-
# @Time : 2019/8/24 14:58
# @Author : kean
# @Email : ?
# @File : bert_sentimental_flags.py
# @Software: PyCharm
import tensorflow as tf
flags = tf.flags
# flags.
FLAGS = flags.FLAGS
## Required parameters
flags.DEFINE_string("data_dir",
r"D:\projects_py\bert\zhe... |
# pylint: skip-file
"""empty message
Revision ID: d5904e6abbb5
Revises: 589274cf0b50
Create Date: 2019-11-08 21:51:03.148529
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'd5904e6abbb5'
down_revision = '589274cf0b50'
branch_labels = None
depends_on = None
d... |
#!/usr/bin/env python
from blastsight.view.drawables.meshgl import MeshGL
from blastsight.view.glprograms.meshphantomprogram import MeshPhantomProgram
from tests.view.glprograms.test_meshprogram import TestMeshProgram
class TestMeshPhantomProgram(TestMeshProgram):
@property
def base_program(self):
re... |
import math
def numberOfBoomerangs(points: list[list[int]]) -> int:
def dist_metric(a, b):
return (a[0] - b[0])**2 + (a[1] - b[1])**2
n = len(points)
total = 0
for i in range(n):
counts = {}
for j in range(n):
if i == j:
continue
... |
"""
test_simu_utils.py
Tests for the simulation interface. """
from reform import replica_exchange
from reform import omm
from reform import simu_utils
from simtk.openmm import app
import numpy as np
PDB_FILE = "spep_0000.pdb"
MODEL_NAME = "central.pt"
N_FRAMES = 10
EXCHANGE_INTERVAL = 100
RECORDING_INTERVAL = 200
... |
# This file is part of GridCal.
#
# GridCal 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 version 3 of the License, or
# (at your option) any later version.
#
# GridCal is distributed in the hope that... |
'''
@Description:
@version:
@License: MIT
@Author: Wang Yao
@Date: 2020-03-30 15:47:00
@LastEditors: Wang Yao
@LastEditTime: 2020-04-02 16:27:06
'''
import numpy as np
import tensorflow as tf
import tensorflow.keras.backend as K
from tensorflow.keras import activations
from tensorflow.keras.layers import Layer
from t... |
size=int(input("Enter the size of list: "))
a=[]
for i in range(size):
num=int(input("Enter the Elements in list: "))
a.append(num)
oddSum = 0
evenSum = 0
for i in a:
if i%2==0:
evenSum = evenSum + i
else:
oddSum += i
print("Even sum is: ",evenSum)
print... |
#!/usr/bin/env python3
import requests
import re
def getMeteoULaval():
'''Returns a dict containing the info from Météo-Laval's website.
This function does not get the average and extreme values.'''
page = requests.get('http://meteo-laval-web.gel.ulaval.ca')
donnees = re.findall('id="([_a-z\d]*)" c... |
from __future__ import with_statement
import datetime
import managevcs
from managevcs.tests.base import BackendTestMixin
from managevcs.tests.conf import SCM_TESTS
from managevcs.backends.base import BaseChangeset
from managevcs.nodes import (
FileNode, AddedFileNodesGenerator,
ChangedFileNodesGenerator, Remo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.