content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import os
import matplotlib.pyplot as plt
import matplotlib.pylab as pylab
import time
from subprocess import Popen, PIPE
import numpy as np
import pickle
N = 20
def fail_if_error(error):
if error:
print(error)
raise AssertionError()
def remove_min_max(x):
trimmed = x[:]
trimmed.remove(ma... | python |
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
from .validators import validate_file_size
# Create your models here.
#this models.py file means realtional table or schema in the databse and title, content etc are fields in the... | python |
import pathlib
from typing import Callable, Union
import click
__version__ = "21.5.16"
APP_NAME = "cldb"
app_dir = pathlib.Path(click.get_app_dir(APP_NAME, roaming=False, force_posix=True))
cache_root = app_dir / "cache"
config = {
"bs_features": "lxml",
}
from . import models # noqa: E402
SpecFetcher = Cal... | python |
#!/usr/bin/env python
# Copyright 2016 DIANA-HEP
#
# 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... | python |
import time
from environment_server.actor_data import ActorData
import traceback
def replay_buffer_process(params, batch_sizes, batch_addresses, transition_queue, replay_lock):
try:
from replay_buffer import replay_client
import random
batch_data = [ActorData(params, b, a) for b, a in zip(... | python |
# (C) Copyright 2007-2021 Enthought, Inc., Austin, TX
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in LICENSE.txt and may be redistributed only under
# the conditions described in the aforementioned license. The license
# is also available online at... | python |
# Models
import tensorflow as tf
import numpy as np
from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2_as_graph
import time
import pickle
import os
import sklearn
from sklearn.ensemble import RandomForestRegressor
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import warnings
war... | python |
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
n = {'nodes':20,'edges':3}
G = nx.barabasi_albert_graph(n['nodes'],n['edges'])
max_degree = max(nx.degree(G).values())
min_sigmoid = 0.5
max_sigmoid = np.exp(1)/(1.+np.exp(1))
degrees = nx.degree(G)
sigmoid = lambda value: (1./(1+np.exp(-valu... | python |
#!/usr/bin/python2
import optparse
import os
import shutil
import stat
import subprocess
import sys
from builds.GpBuild import GpBuild
def install_gpdb(dependency_name):
status = subprocess.call("mkdir -p /usr/local/gpdb", shell=True)
if status:
return status
status = subprocess.call(
"ta... | python |
'''
Pulls segmentation masks from the database and exports them
into folders with specifiable format (JPEG, TIFF, etc.).
2019 Benjamin Kellenberger
'''
import os
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Export segmentation map annotations from databa... | python |
# -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from django.urls import reverse
from django.test import TestCase, Client
import base64
import mock
import adal
class AuthTestCase(TestCase):
client = Client()
home_url = reverse('home')
auth_url = reverse('auth')
auth_ip_url = reverse... | python |
from tempfile import NamedTemporaryFile
from ..cache import get_cache_key, get_hexdigest, get_hashed_mtime
from ..utils import compile_less
from ..settings import LESS_EXECUTABLE, LESS_USE_CACHE,\
LESS_CACHE_TIMEOUT, LESS_ROOT, LESS_OUTPUT_DIR, LESS_DEVMODE,\
LESS_DEVMODE_WATCH_DIRS
from django.conf import sett... | python |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="deepof",
version="0.1.4",
author="Lucas Miranda",
author_email="lucas_miranda@psych.mpg.de",
description="deepof (Deep Open Field): Open Field animal pose classification tool ",
long_d... | python |
import pygame
pygame.font.init()
class Font():
title = pygame.font.SysFont('Arial', 60)
place = pygame.font.SysFont('Arial', 32)
normal_text_large = pygame.font.SysFont('Arial', 32)
normal_text_small = pygame.font.SysFont('Arial', 24)
card_energy = pygame.font.SysFont('Arial', 28)
card_name = ... | python |
#!/usr/bin/env python
#
# file: Connection.py
# author: Cyrus Harrison <cyrush@llnl.gov>
# created: 6/1/2010
# purpose:
# Provides a 'Connection' class that interacts with a redmine instance to
# extract results from redmine queries.
#
import urllib2,urllib,csv,getpass,warnings
from collections import namedtuple
fr... | python |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 2 17:33:00 2017
@author: spauliuk
"""
"""
File ODYM_Functions
Check https://github.com/IndEcol/ODYM for latest version.
Contains class definitions for ODYM
standard abbreviation: msf (material-system-functions)
dependencies:
numpy >= 1.9
scipy >= 0.14
Reposi... | python |
import inspect
class ExecutionOrder():
"""An Enum that is used to designate whether a TestSet's tests
need to be run sequentially or can be run in any order."""
UNORDERED = 0
SEQUENTIAL = 1
class TestSet():
"""A very general class that represents an arbitrary set of tests. By default
each tes... | python |
from . import EncodedNumber
from . import RandomizedIterativeAffine
from phe import paillier | python |
"""
data generator class
"""
import os
import numpy as np
import cv2
import copy
from LibMccnn.util import readPfm
import random
from tensorflow import expand_dims
#import matplotlib.pyplot as plt
from skimage.feature import local_binary_pattern
class ImageDataGenerator:
"""
input image patch pairs gen... | python |
import pytest
xgcm = pytest.importorskip("xgcm")
from xarrayutils.build_grids import rebuild_grid
from numpy.testing import assert_allclose
from .datasets import datagrid_dimtest, datagrid_dimtest_ll
@pytest.mark.parametrize(
"test_coord",
["i", "j", "i_g", "j_g", "XC", "XG", "YC", "YG", "dxC", "dxG", "dyC",... | python |
#!/usr/bin/env python
from mailanalyzer import statistics
from mailanalyzer import parsing
from collections import defaultdict
import datetime
import csv
import time
# path to directory with Dovecot mailing list archive
dir_name = ''
# output path
output = 'output/dovecot/{}_'.format(time.strftime('%Y%m%d_%H%M'))
# ... | python |
# -*- coding: utf-8 -*-
"""
Train a simple deep ResNet on the UPavia 2D dataset.
Exception: Only layers of same output shape can be merged using sum mode. Layer shapes:
[(None, 7, 7, 128), (None, 4, 4, 128)]
"""
from keras.datasets import cifar10
from keras.preprocessing.image import ImageDataGenerator
from keras.uti... | python |
import numpy as np
from datetime import datetime
from twisted.internet.defer import inlineCallbacks
from EGGS_labrad.lib.clients.cryovac_clients.RGA_gui import RGA_gui
class RGA_client(RGA_gui):
name = 'RGA Client'
BUFFERID = 289961
def __init__(self, reactor, cxn=None, parent=None):
super().__... | python |
import glob
import os
import getpass
print(" ------------------------\n| Piggy's Trolling Tools: |\n| :-: File Deleter :-: |\n ------------------------\n")
where = input("Input directory where files should be deleted: ")
regex = input("Enter regex to match files (example: important*.txt): ")
os.chdir(whe... | python |
"""
Basic atmosphere functions
This dark flight model predicts the landing sight of a meteoroid by
propagating the position and velocity through the atmosphere using a
5th-order adaptive step size integrator (ODE45).
Created on Mon Oct 17 10:59:00 2016
@author: Trent Jansen-Sturgeon
"""
import numpy as np
from scipy.i... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import _env # noqa
from controller._base import AdminHandler
from misc._route import route
@route('/category')
class Index(AdminHandler):
def get(self):
self.render()
| python |
# -*- coding: utf-8 -*-
from pydantic.datetime_parse import parse_datetime
from .. import fhirtypes # noqa: F401
from .. import communication
def test_Communication_1(base_settings):
filename = (
base_settings["unittest_data_dir"] / "communication-example.canonical.json"
)
inst = communication.C... | python |
import argparse
import os
from util import util
import torch
import models
import numpy as np
class BaseOptions():
"""This class defines options used during both training and test time.
It also implements several helper functions such as parsing, printing, and saving the options.
It also gath... | python |
def qsort(arr):
if len(arr) <= 1:
return arr
pivot = arr.pop()
greater, lesser = [], []
for item in arr:
if item > pivot:
greater.append(item)
else:
lesser.append(item)
return qsort(lesser) + [pivot] + qsort(greater)
| python |
from .MyMplCanvas import *
from .MyMplCanvas import MyMplCanvas
from .DataCanvas import *
from .FitCanvas import *
from .KineticsCanvas import *
from .SpectrumCanvas import *
| python |
import pytest
import pathlib
from align.cell_fabric import Canvas, Pdk, Wire, Via
mydir = pathlib.Path(__file__).resolve().parent
pdkfile = mydir.parent.parent / 'pdks' / 'FinFET14nm_Mock_PDK' / 'layers.json'
@pytest.fixture
def setup():
p = Pdk().load(pdkfile)
c = Canvas(p)
c.addGen( Wire( nm='m1', laye... | python |
from babelsubs.generators.base import register, BaseGenerator
class DFXPGenerator(BaseGenerator):
"""
Since the internal storage is already in dfxp, the generator is just
a small shim to keep the public interface between all generators
regular.
"""
file_type = ['dfxp', 'xml' ]
def __init_... | python |
from ..iorw import GCSHandler
class MockGCSFileSystem(object):
def __init__(self):
self._file = MockGCSFile()
def open(self, *args, **kwargs):
return self._file
def ls(self, *args, **kwargs):
return []
class MockGCSFile(object):
def __enter__(self):
self._value = 'd... | python |
import boto3
exceptions = boto3.client('sdb').exceptions
AttributeDoesNotExist = exceptions.AttributeDoesNotExist
DuplicateItemName = exceptions.DuplicateItemName
InvalidNextToken = exceptions.InvalidNextToken
InvalidNumberPredicates = exceptions.InvalidNumberPredicates
InvalidNumberValueTests = exceptions.InvalidNum... | python |
import re
from basic import *
from amino_acids import amino_acids
from tcr_distances_blosum import blosum
from paths import path_to_db
from translation import get_translation
gap_character = '.'
verbose = False
#verbose = ( __name__ == '__main__' )
## look at imgt cdrs
## http://www.imgt.org/IMGTScientificChart/Nome... | python |
token = 'NDY2ODc4MzY3MTg3MDc1MDcz.DiqkoA.JVgJqYhnL6yyCnKeAnCHx5OvR3E' #Put Your bots token here
prefix = '*' #put prefix here
link = 'https://discordapp.com/api/oauth2/authorize?client_id=466878367187075073&permissions=0&scope=bot' #put bot invite link here
ownerid = '329526048553172992' #put your id here
| python |
import numpy as np
import torch
from torch.utils import data
from kaldi_io import read_mat
import h5py
# PyTorch Dataset
class SpoofDatsetEval(data.Dataset):
''' Evaluation, no label
'''
def __init__(self, scp_file):
with open(scp_file) as f:
temp = f.readlines()
content = [x.... | python |
# lets create a class to hold our category data
class Category:
def __init__(self, name):
self.name = name
def __str__(self):
return f"No Products in {self.name}"
#How can you represent this class data as a string? My guess is __str__
| python |
import ConfigParser
import os
from StringIO import StringIO
homedir = os.getenv('APPDATA' if os.name.lower() == 'nt' else 'HOME', None)
default_cfg = StringIO("""
[visual]
background = black
foreground = white
height = 800
width = 800
cortex = classic
default_view = lateral
[overlay]
min_thresh = 2.0
max_thresh = rob... | python |
import matplotlib.pyplot as plt
import numpy as np
def plot_bar_from_counter(counter, ax=None):
""""
This function creates a bar plot from a counter.
:param counter: This is a counter object, a dictionary with the item as the key
and the frequency as the value
:param ax: an axis of matplotlib
... | python |
from django import forms
class LoginCustomerForm(forms.Form):
email_address = forms.CharField(label='Email address', max_length=100)
password = forms.CharField(label='Password', max_length=100, widget=forms.PasswordInput)
class RegisterCustomerForm(forms.Form):
first_name = forms.CharField(label='First na... | python |
import datetime
import textwrap
import uuid
from app_ccf.models import Application, StatusUpdate
from app_ccf.models import VoucherCode, VoucherCodeBatch, VoucherCodeCheckStatus
from shared.test_utils import DEFAULT_CCF_APP_FIELDS
from . import base_test
from . import utils
class ApplicationTests(base_test.CcfBase... | python |
# coding: utf-8
from binance_api.servicebase import ServiceBase
import json
from binance.client import Client
from binance.exceptions import BinanceAPIException
class Order(ServiceBase):
def _get_filter(self, symbol, filter_name):
if symbol is None: return None
exinfo = self.binance.exchange_info
... | python |
# Copyright 2019 The Oppia 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
#
# Unless required by applicable ... | python |
# -*- coding: utf-8 -*-
import logging
from datetime import datetime, timedelta
from dateutil import tz
from django.conf import settings
from django.contrib.auth.models import Group
from django.contrib.auth import authenticate
from django.db.models import Q, Prefetch, Sum
from django.utils.translation import ugettext_l... | python |
# Copyright (c) 2010 ActiveState Software Inc. All rights reserved.
"""Textual UI: progress bar and colprint"""
import os
import sys
from datetime import datetime, timedelta
from contextlib import contextmanager
import logging
import math
import six
LOG = logging.getLogger(__name__)
__all__ = ['colprint', 'find_co... | python |
import tensorflow as tf
import numpy as np
def reset_graph(seed=42):
tf.reset_default_graph()
tf.set_random_seed(seed)
np.random.seed(seed)
def neuron_layer(X, n_neurons, name, activation=None):
with tf.name_scope(name):
n_inputs = int(X.get_shape()[1])
stddev = 2/ np.sqrt(n_inputs)
... | python |
import datetime
import typing
import uuid
from commercetools import types
from commercetools._schemas._api_client import (
ApiClientDraftSchema,
ApiClientPagedQueryResponseSchema,
ApiClientSchema,
)
from commercetools.testing.abstract import BaseModel, ServiceBackend
class ApiClientsModel(BaseModel):
... | python |
import os
import pandas as pd
def test_wildcard_filter():
from pachypy.utils import wildcard_filter, wildcard_match
x = ['a', 'ab', 'b']
assert wildcard_match('', None) is True
assert wildcard_match('', '*') is True
assert wildcard_match('', '?') is False
assert wildcard_match('a', '*') is Tr... | python |
import pytest
def test_rnaseq_expression_init():
from genomic_data_service.rnaseq.domain.expression import Expression
data = [
'POMC',
'ENST000, ENST001',
0.03,
90.1,
]
expression = Expression(
*data
)
assert isinstance(expression, Expression)
assert... | python |
import sys, os
import pandas as pd
import numpy as np
file_path = os.path.dirname(os.path.realpath(__file__))
ps_calcs_lib_path = os.path.abspath(os.path.join(file_path, "../../", "lib/ps_calcs"))
sys.path.insert(0, ps_calcs_lib_path)
import ps_calcs
def rdo(ybi, yi, year, depths):
rca_dist_opp = []
for ... | python |
#
# Pyserini: Reproducible IR research with sparse and dense representations
#
# 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 |
import string
class caesar():
def caesar_cipher(user_message, user_shift):
alphabet = string.ascii_lowercase
shifted_alphabet = alphabet[user_shift:] + alphabet[:user_shift]
table = str.maketrans(alphabet, shifted_alphabet)
return user_message.translate(table)
| python |
from celery import Celery
import consumer
app_name = 'consumer' # take the celery app name
app = Celery(app_name, broker=consumer.redis_url)
# produce
for i in range(100):
a = 1
b = 2
consumer.consume.delay(a, b)
| python |
import numpy as np
from PIL import Image
from matplotlib import pyplot as plt
from matplotlib import image as mpimg
from scipy import signal
from scipy import fftpack
import scipy.io
class PSNR_calculator:
def __init__(self,original_image,fixed_image):
self.orig = original_image[:,:,0]
self.fixed =... | python |
"""
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
Needs some environment strings in the live server.
LIVE -- To know its in the live serv... | python |
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import cross_section_analysis.utils as cs_utils
class WaterReferenceLinesOnRaster():
"""
Processing of cross-section profiles to find water reference lines on the
topography raster within user-specified topography intervals:
... | python |
#1.只负责写视图
import os
import datetime
from flask import render_template
from main import app
from models import Curriculum#导入这个表
from flask import redirect#跳转 即Django中的重定向功能
import functools
from flask import session
from models import *
class Calendar:
"""
当前类实现日历功能
1、返回列表嵌套列表的日历
2、安装日历格式打印日历
# 如果一... | python |
from kaplot import *
import pymedia.audio.acodec as acodec
import pymedia.muxer as muxer
import sys
import wave
if False:
file = open(sys.argv[1], 'rb')
rawdata = file.read()
wfile = wave.open('test.wav', 'wb')
print muxer.extensions
demuxer = muxer.Demuxer('mp3')
frames = demuxer.parse(rawdata)
decoder = ac... | python |
import numpy as np
import pandas as pd
import json
from itertools import groupby
from collections import namedtuple
# NodeEdgeIncidence = namedtuple('NodeEdgeIncidence', ['nid', 'role', 'eid','meta'])
class NodeEdgeIncidence(object):
__slots__ = ("nid", "role", "eid", "meta")
def __init__(self, nid, role,... | python |
from copy import deepcopy
import csv
from enum import Enum
import inspect
from os.path import join as joinpath
from pprint import pprint
from sys import version_info
from typing import Any, Callable, Dict, List, Optional, Tuple, TYPE_CHECKING, TypeVar, Union
import dictdiffer
from pandas import DataFrame
import string... | python |
from typing import NamedTuple
class User(NamedTuple):
name: str
age: int = 27
user1 = User('Jan')
print(user1)
print(dir(user1))
# user1.age = 30
# print(user1)
| python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Sample Discourse Relation Classifier Train
Train parser for suplementary evaluation
Train should take three arguments
$inputDataset = the folder of the dataset to parse.
The folder structure is the same as in the tar file
$inputDataset/parses.json
$inputDataset... | python |
# -*- coding: utf-8 -*-
"""
Demonstrate a simple data-slicing task: given 3D data (displayed at top), select
a 2D plane and interpolate data along that plane to generate a slice image
(displayed at bottom).
"""
## Add path to library (just for examples; you do not need this)
import initExample
import... | python |
from itertools import combinations
from operator import mul
f = open("input.txt")
d = f.readlines()
total = 0
for p in d:
sides = [int(n) for n in p.split("x")]
combos = list(combinations(sides, 2))
areas = [ mul(*a) for a in combos]
areas.sort()
total += areas[0]
total += sum([2*a for a in are... | python |
# Copyright 2016 Cisco Systems, 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 agreed to in wr... | python |
import numpy as np
a = np.array([0, 0.5, 1.0, 1.5, 2.0])
type(a)
a[:2] # Slicing works as for lists
# Built in methods
a.sum()
a.std()
a.cumsum()
a.max()
a.argmax()
# Careful with np.max!
np.max(2, 0)
np.max(-2, 0) # silent fail :) second argument is the axis
np.max(0, 2) # fail
np.maximum(-2, 0)
# Vectorized ope... | python |
import os
import sys
import logging
import configparser
import logging
import numpy as np
configfile_name ="NAAL_config"
logger = logging.getLogger(__name__)
if sys.platform.startswith('win'):
config_dir = os.path.expanduser(os.path.join("~", ".NAAL_FPGA"))
else:
config_dir ... | python |
import socket
import os
from dotenv import load_dotenv
import redis
from flask import Flask, Blueprint, url_for
from flask_caching import Cache
from flask_login import login_required, LoginManager
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
import dash
import dash_bootstrap_components as d... | python |
# coding=utf-8
__author__ = "Dimitrios Karkalousos"
from abc import ABC
import torch
from omegaconf import DictConfig, OmegaConf
from pytorch_lightning import Trainer
from torch.nn import L1Loss
from mridc.collections.common.losses.ssim import SSIMLoss
from mridc.collections.common.parts.fft import ifft2c
from mridc... | python |
"""empty message
Revision ID: 073b3a3e8e58
Revises: 60c735df8d2f
Create Date: 2019-09-06 08:45:01.107447
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '073b3a3e8e58'
down_revision = '60c735df8d2f'
branch_labels = None
depends_on = None
def upgrade():
# ... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
import select
import time
import json
import requests
import yaml
import sys
import os
__PRODUCT_ID = "logslack 1.0 (c) 4k1/logslack"
def get_value(r, key, default=None):
if key in r:
if type(r[key]) is int:
return int(r[key])
... | python |
# Generated by Django 2.2.9 on 2020-02-02 18:32
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("core", "0027_auto_20200202_1822")]
operations = [
migrations.RemoveField(model_name="office", name="req_nominations"),
migrations.RemoveField(model_name=... | python |
import ctypes
import os
import math
from typing import Dict, List, cast
from abc import ABC, abstractclassmethod
import sdl2
from helpers import sdl, draw_texture, texture_from_bmp
import config
import entities
class Component(ABC):
"""Interface that each component must adhere to. Strictly speaking, components
... | python |
import os
import re
import time
import random
import hashlib
from multiprocessing import cpu_count
from tandems import _tandems
try:
from urllib.parse import unquote
except ImportError:
from urlparse import unquote
UNK_ID = 0
SQL_RESERVED_WORDS = []
with open("./SQL_reserved_words.txt", "rb") as f:
for l... | python |
#!/usr/bin/env python
# coding: utf-8
from typing import List
from typing import Optional
from typing import Union
import numpy as np
import pandas as pd
from dataclasses import dataclass
from sklearn import metrics
from evidently import ColumnMapping
from evidently.analyzers.base_analyzer import Analyzer
from eviden... | python |
from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import EveTimerForm
from .models import EveTimer, EveTimerType
from datetime import datetime, timedelta
from django.utils import timezone
from django.contrib.auth.decorators import login_required, permission_required
@login_... | python |
#!/usr/bin/env python
"""
# ==============================================================================
# Author: Carlos A. Ruiz Perez
# Email: cruizperez3@gatech.edu
# Intitution: Georgia Institute of Technology
# Version: 1.0.0
# Date: Nov 13, 2020
# Description: Builds the search dat... | python |
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class SignUpForm(UserCreationForm):
first_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
last_name = forms.CharField(max_length=30, required=False, help_tex... | python |
from odc.geo.data import country_geom, data_path, gbox_css, ocean_geojson, ocean_geom
def test_ocean_gjson():
g1 = ocean_geojson()
g2 = ocean_geojson()
assert g1 is g2
assert len(g1["features"]) == 2
def test_ocean_geom():
g = ocean_geom()
assert g.crs == "epsg:4326"
g = ocean_geom("ep... | python |
import os
from hashkernel.bakery import CakeRole
from hashstore.bakery.lite import dal
from hashstore.bakery.lite.node import (
ServerConfigBase, GlueBase, CakeShardBase, User, UserType,
UserState, Permission, Portal, ServerKey, PermissionType as PT)
from hashstore.bakery.lite.node.blobs import BlobStore
from... | python |
# -*- coding: utf-8 -*-
import os, sys
import time
import pathlib
import glob
import cv2
import configparser
import copy
from datetime import datetime, timedelta
from matplotlib.lines import Line2D
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import numpy as np
#from matplotlib.ba... | python |
#!/usr/bin/python3
import asyncio
import random
import traceback
import aiomas
import hashlib
import logging
import errno
from helpers.validator import *
from helpers.chordInterval import *
from helpers.storage import Storage
from helpers.replica import Replica
from helpers.messageDefinitions import *
from jsonschema ... | python |
from Metodos import pontofixo
from prettytable import PrettyTable
from mpmath import *
import random
import matplotlib.pyplot as plt
valerror1 = []
valerror2 = []
valerror3 = []
valerrors = [valerror1,valerror2,valerror3]
i = 20
val = 2
def f(x):
return (x-1)*exp(x-2)**2 - 1
def g1(x):
retu... | python |
import logging
from typing import Callable, Sequence, Set
from . import formats
logger = logging.getLogger(__name__)
# type aliases
FormatterType = Callable[[bool], formats.IFormatter]
def negotiate(accepts_headers: Sequence[str]) -> FormatterType:
"""Negotiate a response format by scanning through a list of A... | python |
import redis
redis_db = redis.StrictRedis(host="redis", port=6379, db=0)
print(redis_db.keys())
redis_db.set('CT', 'Connecticut')
redis_db.set('OH', 'Ohio')
print(redis_db.keys())
ctstr = redis_db.get("CT").decode("utf-8")
print(ctstr)
print( "Good bye!" ) | python |
from django.test import TestCase
from .models import Category
# Create your tests here.
# category models test
class CategoryTestCase(TestCase):
def setUp(self):
"""
Create a category for testing
"""
Category.objects.create(name="Test Category")
def test_category_name(self):
... | python |
from logging import ERROR, error
from os import terminal_size
import socket
import threading
import json
HEADER = 1024*4
PORT = 5544
# SERVER = "192.168.1.104"
SERVER = "localhost" # socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "!DISCONNECT"
server = socket.s... | python |
# Um assassinato aconteceu, e o programa fará 5 perguntas para o usuário.
# Se 2 respostas forem positivas, o usuário é considerado: "SUSPEITO"
# Se responder entre 3 e 4 respostas positivas: "CÚMPLICE"
# 5 respostas positivas, o usuário é considerado como: "ASSASSINO"
# Caso o usuário tenha no máximo 1 resposta positi... | python |
from checkpoint.types import ModelVersionStage
ANONYMOUS_USERNAME = "Anonymous"
CHECKPOINT_REDIRECT_PREFIX = "checkpoint_redirect"
CHECKPOINT_REDIRECT_SEPARATOR = ":"
NO_VERSION_SENTINAL = "no_version"
STAGES_WITH_CHAMPIONS = {
ModelVersionStage.STAGING,
ModelVersionStage.PRODUCTION,
}
INJECT_SCRIPT_TEMPL... | python |
import numpy as np
import torch
import torchvision.transforms as transforms
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
])
def convert_image_to_tensor(image):
"""convert an image to pytorch tensor
Parameters:
----------
... | python |
import argparse
from clusterize import k_means
def main():
args = parse_args()
dataset = read_dataset(args.dataset)
k_means(args.k, dataset, args.i)
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("-dataset", default="normal",
choices=["normal", "unbalance"],... | python |
# -*- coding: utf-8 -*-
"""stem package.
Word lemmatization and stemming.
API:
* PorterStemmer (class): Uses porter algorithm to find word stems.
* porter_stem (function): For instant stemming a word using porter algorithm.
* RegexStemmer (class): Uses regex pattern to find word stems.
* regex_stem (function): For i... | python |
import wave
import pyaudio
import webrtcvad
class AudioRecorder(object):
def __init__(self):
self.pyaudio = pyaudio.PyAudio()
self.format = self.pyaudio.get_format_from_width(width=2)
self.channels = 1
self.rate = 16000
self.chunk = 160
self.max_frame_count = 500
... | python |
#
# 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 writing, software
# distributed under ... | python |
from typing import Any
from typing import Callable
from typing import List
from typing import Optional
from typing import Union
import pytest
import tornado
from graphql import parse
from opencensus.trace import execution_context
from opencensus.trace import tracer as tracer_module
from opencensus.trace.base_exporter ... | python |
import os
from distutils.util import strtobool
from os.path import join
import dj_database_url
from configurations import Configuration
from corsheaders.defaults import default_headers
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
class Common(Configuration):
INSTALLED_APPS = (
... | python |
import numpy as np
from matplotlib import pyplot as plt
from os import listdir
def exp_moving_average(vec, a):
"""
Calculates EMA from given vector and alpha parameter.
:param vec: input vector
:param a: alpha parameter
:return: calculated average
"""
# Create elements multipliers vector. ... | python |
from random import randint
class King:
def __init__(self, start, size):
self.start = start
self.size = size
self.hole = (randint(0, size-1), randint(0, size-1))
def check(self, a, b):
return a >= 0 and b >= 0 and a <= self.size - 1 and b <= self.size - 1
def near(self, wher... | python |
# -*- coding: utf-8 -*-
"""
Requires Python 3.8 or later
"""
__author__ = "Jorge Morfinez Mojica (jorge.morfinez.m@gmail.com)"
__copyright__ = "Copyright 2021"
__license__ = ""
__history__ = """ """
__version__ = "1.21.H28.1 ($Rev: 1 $)"
import re
import time
import threading
from flask import Blueprint, json, reque... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.