content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
#
# Copyright 2017 CNIT - Consorzio Nazionale Interuniversitario per le Telecomunicazioni
#
# 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/LICE... | python |
from urllib.request import ssl, socket
from datetime import date, datetime
import pytz
def cert_validate_date(hostname, port = 443)->datetime:
"""
Validate the certificate expiration date
"""
with socket.create_connection((hostname, port)) as sock:
context = ssl.create_default_context()
... | python |
import asyncio
import dataset
import discord
DATABASE = dataset.connect('sqlite:///data/bot/higgsbot.db')
class Token:
def __init__(self):
self.table = DATABASE['balance']
async def start(self, bot):
for member in bot.get_all_members():
id = member.id
if self.table... | python |
# Generated by Django 3.1.6 on 2021-02-10 08:08
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('app', '0002_transaction_wallet'),
]
operations = [
migrations.AlterModelOptions(
name='transaction',
options={'ordering': ['... | python |
"""commands for register dummy events"""
import click
from autobahn.asyncio.wamp import ApplicationRunner
from playground.racelog.caller import CallEndpoint
@click.command("delete")
@click.argument("eventId", type=click.INT)
@click.pass_obj
def delete(obj,eventid):
"""delete event including data.
The event i... | python |
from featuretools.primitives import AggregationPrimitive
from tsfresh.feature_extraction.feature_calculators import sum_of_reoccurring_values
from woodwork.column_schema import ColumnSchema
class SumOfReoccurringValues(AggregationPrimitive):
"""Returns the sum of all values, that are present in the time series mo... | python |
import asyncio
import datetime
import unittest
from unittest import mock
from aiohttp import hdrs
from aiohttp.multidict import CIMultiDict
from aiohttp.web import ContentCoding, Request, StreamResponse, Response
from aiohttp.protocol import HttpVersion, HttpVersion11, HttpVersion10
from aiohttp.protocol import RawRequ... | python |
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
Base.__table_args__ = {
"mysql_charset": "utf8",
"mysql_collate": "utf8_general_ci",
}
| python |
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import *
from tensorflow.keras.preprocessing import sequence
from tf2bert.text.tokenizers import Tokenizer
from tf2bert.text.labels import TaggingTokenizer
from tf2bert.text.labels import find_entities_chun... | python |
"""
Tester.
"""
# ---------------------------------------------------------------------------
# Imports
# ---------------------------------------------------------------------------
from grizzled.misc import ReadOnly, ReadOnlyObjectError
import pytest
class Something(object):
def __init__(self, a=1, b=2):
... | python |
import configparser
import os
from discord.ext import commands
import requests
COMMAND_PREFIX = '!track '
ACGN_LIST_HELP = 'Lists all tracked acgn data.'
ACGN_SEARCH_HELP = '''
Searches acgns in the database.
Lists acgns with title that (partially) matches <title>.
Args:
title: A string.
'''
ACGN_ADD_HELP = '''
... | python |
# coding: utf-8
import magic
from django import forms
from django.conf import settings
from django.core.exceptions import ValidationError
from django.utils.html import escape, format_html
from django.utils.translation import ugettext_lazy as _
from trojsten.submit import constants
from trojsten.submit.helpers import g... | python |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack.package import *
class RAnnotationdbi(RPackage):
"""Manipulation of SQLite-based annotations in Bioconduc... | python |
var = 5
a = f"Test: {var:d}" # cool formatting!
| python |
# -*- coding: utf-8 -*-
"""Dialogo para selecionar pastas."""
from os import listdir
from pathlib import Path
import gi
gi.require_version(namespace='Gtk', version='3.0')
from gi.repository import Gtk
class MainWindow(Gtk.ApplicationWindow):
def __init__(self):
super().__init__()
self.set_title... | python |
# Taku Ito
# 2/22/2019
# General function modules for SRActFlow
# For group-level/cross-subject analyses
import numpy as np
import multiprocessing as mp
import scipy.stats as stats
import nibabel as nib
import statsmodels.api as sm
import sklearn
import h5py
import os
os.sys.path.append('glmScripts/')
import taskGLMPi... | python |
# Copyright (c) 2020, Xilinx
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the follow... | python |
# Create an Excel file and save data from
# show version command using pandas
# (Implicitly uses xlsxwriter to create the Excel file)
import pandas as pd
from pandas import ExcelWriter
from netmiko import ConnectHandler
# Devices to SSH into
devices = [
{
"device_type": "cisco_ios",
"ip": "sandbo... | python |
from pathlib import Path
from jina.peapods import Pod
import pytest
from fastapi import UploadFile
from jina.flow import Flow
from jina.enums import PodRoleType
from jina.peapods.pods import BasePod
from jina.parsers import set_pea_parser, set_pod_parser
from jinad.models import SinglePodModel
from jinad.store impor... | python |
import sys
sys.path.append('../')
import TankModel as TM
import pylab as pl
import pandas as pd
pl.style.use('seaborn')
import numpy as np
def main():
data = pd.read_csv('../sample_data/tank_sample_data.csv')
rf = data['Pr'].values
et = data['ET'].values
obsQ = data['Q'].values
area = 2000
... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-11-30 20:34
from __future__ import unicode_literals
from django.db import migrations
def forward(apps, schema_editor):
db_alias = schema_editor.connection.alias
Message = apps.get_model("mailing", "Message")
MessageAuthor = apps.get_model("mail... | python |
# Generated by Django 3.1.4 on 2020-12-12 22:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0003_auto_20201212_2213'),
]
operations = [
migrations.AlterField(
model_name='agent',
name='file',
... | python |
for _ in range(int(input())):
k, n = int(input()), int(input())
c = [list(range(1, n+1))]
for row in range(1, k+1):
c.append([sum(c[row-1][:column]) for column in range(1, n+1)])
print(c[k][n-1])
| python |
def get_add(n):
def add(x):
return x + n
return add
myadd = get_add(1)
assert 2 == myadd(1)
def foo():
x = 1
def bar(y):
def baz():
z = 1
return x + y + z
return baz
return bar(1)
assert 3 == foo()()
def change():
x = 1
def bar():
... | python |
def recurse(s, t, i, j, s1, t1):
# print(i, s[i], j, t[j], s1, t1)
if i == len(s) and j == len(t):
print(''.join(s1))
print(''.join(t1))
print()
return
if i < len(s):
recurse(s, t, i+1, j, s1 + [s[i]], t1 + ['-'])
if j < len(t):
recurse(s, t, i, j+1, s1 + ... | python |
import wx
from views.views_manager import *
class MainApp(wx.App):
def __init__(self):
wx.App.__init__(self)
# Initial the main window
self.views_manager = ViewsManager()
self.views_manager.main_window.Show()
self.main_window = self.views_manager.get_window("MainWindow")
... | python |
"""A module for testing Genomic Duplication Tokenization."""
import unittest
from variation.tokenizers import GenomicDuplication
from .tokenizer_base import TokenizerBase
class TestGenomicDuplicationTokenizer(TokenizerBase, unittest.TestCase):
"""A class for testing Genomic Duplication Tokenization."""
def ... | python |
from django.conf import settings
from django.shortcuts import redirect
from django.urls import resolve
class DevToolsLoginRequiredMiddleware:
def __init__(self, get_response):
self.get_response = get_response
assert settings.APP_ENV in ("local", "test", "dev")
def __call__(self, request):
... | python |
import random
from unittest import TestCase
from guitarpractice.exercises.technique_hammers_pulls import technique_hammers_pulls
from guitarpractice.models import Beat
class TestHammersAndPulls(TestCase):
def test_level_one_has_eighth_notes(self):
random.seed(10)
result = technique_hammers_pulls... | python |
#!/usr/bin/env python
'''Version Information Definition'''
__version_info__ = (0, 0, 4)
__version__ = ".".join(str(i) for i in __version_info__)
| python |
import blessed
BLESSED_VERSION = tuple(int(x) for x in blessed.__version__.split(".", 2)[:2])
if BLESSED_VERSION < (1, 17):
def link(term: blessed.Terminal, url: str, text: str, url_id: str = "") -> str:
return url
else:
def link(term: blessed.Terminal, url: str, text: str, url_id: str = "") -> ... | python |
# REMOVE ELEMENT LEETCODE SOLUTION:
# creating a class.
class Solution(object):
# creating a function to delete the desired number from a given array.
def removeElement(self, nums, val):
# creating a while-loop to iterate for the time that the value is present in the array.
... | python |
import adv.adv_test
import adv
from slot.d import *
from slot.a import *
def module():
return Celliera
class Celliera(adv.Adv):
a3 = ('a',0.08,'hp70')
conf = {}
conf['slots.a'] = RR()+JotS()
#conf['slots.d'] = DJ()
acl12 = """
`s1
`s2, seq=5
`s3
"""
acl21 ... | python |
import os
import sys
import inspect
import unittest
import json
# For selecting the correct path
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir) + "/fsm"
sys.path.insert(0, parentdir)
from config import config_read
class T... | python |
# coding=utf-8
data_path = '../data'
cv_train_num = 100000 # 用于交叉验证
train_num = 120000
test_num = 90000
w2v_dim = 300
seed = 2017
| python |
"""
Recall the definition of the Fibonacci numbers from “Rabbits and Recurrence Relations”, which followed the recurrence
relation Fn=Fn−1+Fn−2 and assumed that each pair of rabbits reaches maturity in one month and produces a single pair
of offspring (one male, one female) each subsequent month.
Our aim is to somehow ... | python |
import sys
import django
from django.conf import settings
def billing_function(shop):
return (5, 3, "test subscription")
configuration = {
"DEBUG": True,
"DATABASES": {"default": {"ENGINE": "django.db.backends.sqlite3"}},
"INSTALLED_APPS": [
"django.contrib.auth",
"django.contrib.con... | python |
# Natural Language Toolkit: Genesis Corpus Reader
#
# Copyright (C) 2001-2008 University of Pennsylvania
# Author: Steven Bird <sb@ldc.upenn.edu>
# URL: <http://nltk.sf.net>
# For license information, see LICENSE.TXT
"""
The Carnegie Mellon Pronouncing Dictionary [cmudict.0.6]
ftp://ftp.cs.cmu.edu/project/speech/dict/... | python |
from ..data import platemap_to_dataframe, scale_plate
import pandas as pd
def read_multiple_plates(tables, read_single, platemap=None, **kwargs):
"""Reads data for one or more plates, then merges the data together.
This function simplifies reading and data reduction where you have either
1. multiple plat... | python |
from application.infrastructure.error.errors import VCFHandlerBaseError
class SQLError(VCFHandlerBaseError):
message = "SQL error."
error_type = "SQLError"
class SQLAlchemyEngineNotInitializedError(SQLError):
message = "Not initialized SQLAlchemy Engine."
error_type = "SQLAlchemyEngineNotInitialized... | python |
__all__ = ["lammps_parser.py"]
| python |
"""
STATEMENT
Given a complete binary tree, count the number of nodes.
CLARIFICATIONS
- So, I can assume the tree is complete, or have to check for that? You can assume that.
- To reiterate, a complete binary tree only has the last level not filled. The last
level is filled from the left, if any.
EXAMPLES
(not draw... | python |
#
# Copyright (C) 2016-2019 by Nathan Lovato, Daniel Oakey, Razvan Radulescu, and contributors
#
# This file is part of Power Sequencer.
#
# Power Sequencer 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... | python |
# coding: utf-8
from dHydra.console import *
import time
"""
仅为了演示如何调用start_worker函数开启一个进程(传入参数)
将开启Ctp期货数据全市场的行情源,与存储到MongoDB的进程
注意这里的进程开启时候都用到了./config文件夹下的配置文件,
而配置帐号的ctp.json则是os.getcwd()对应的目录(与config目录同级)
"""
# 存储
start_worker(
worker_name="CtpMdToMongo",
nickname="CtpMdToMongo",
config="CtpMd.json"
... | python |
# import argparse
import datetime as dt
from src.config.appConfig import getJsonConfig, initConfigs
from src.app.monthlyReportGenerator import MonthlyReportGenerator
import cx_Oracle
initConfigs()
# get app config
appConfig = getJsonConfig()
cxOraclePath = appConfig['cxOraclePath']
if not cxOraclePath == '':
cx_Or... | python |
import os
import hashlib
import socket
def application(msg,address):
lim = "|:|:|"
while 1:
s1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s1.settimeout(10)
seq = 0
fil = open('new_' + msg, 'w');
try:
print('entered')
trial = 0
send = s1.sendto(msg, address)
print('Receiving indefinetly... | python |
import os
import sys
import time
import mmap
import requests
import zipfile
import tarfile
import logging
import resource
import progressbar
from urllib.parse import urljoin
from urllib.parse import urlparse
from django.utils.translation import ugettext as _
from ... import defaults as defs
logger = logging.getLogge... | python |
def sum_numbers(first_int, second_int):
"""Returns the sum of the two integers"""
result = first_int + second_int
return result
def subtract(third_int):
"""Returns the difference between the
result of sum_numbers and the third integer"""
diff = sum_numbers(first_int=number_1, second_int=numbe... | python |
import re
from typing import Dict, Iterable, List, cast
import emoji
from discord import Message
from discord.ext.commands import Bot, Cog, Context, command
DEFAULT_VOTE_EMOJIS = ("👍", "👎")
CUSTOM_EMOJI_PATTERN = re.compile(r"\<\:\w+\:\d+\>")
class VoteCog(Cog, name="commanderbot.ext.vote"):
def __init__(self... | python |
from .__geoplot import bokeh_geoplot as Geoplot | python |
from django.urls import path, include
from django.contrib import admin
app_name = 'app'
urlpatterns = [
path('admin/', admin.site.urls, name='admin-index'),
path('admin1/', include('core.app.urls.admin.urls')),
path('', include('core.app.urls.site.urls')),
]
| python |
from __future__ import unicode_literals, division
import array
from collections import defaultdict
import numbers
from operator import itemgetter
import re
import unicodedata
import warnings
import numpy as np
import scipy.sparse as sp
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.externals i... | python |
import unittest
import xraylib
class TestCompoundParser(unittest.TestCase):
def test_good_compounds(self):
self.assertIsInstance(xraylib.CompoundParser("C19H29COOH"), dict)
self.assertIsInstance(xraylib.CompoundParser("C12H10"), dict)
self.assertIsInstance(xraylib.CompoundParser("C12H6O2"),... | python |
#!/usr/bin/env python
#--------------------------------------------------------------
# Function to add the aperture class instances to the SNS linac lattice.
# These apertures are not belong to the particular accelerator elements,
# so we created them as markers: MEBT:ChpPlt:Entr and MEBT:ChpPlt:Exit
#---------------... | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('employee... | python |
"""Define tests for the REST API."""
import datetime
import aiohttp
import pytest
from aionotion import async_get_client
from .common import TEST_EMAIL, TEST_PASSWORD, load_fixture
@pytest.mark.asyncio
async def test_task_all(aresponses):
"""Test getting all tasks."""
aresponses.add(
"api.getnotion... | python |
import numpy as np
from Augmentor.Operations import Operation, Skew, Distort, Rotate, Shear, Flip, Zoom, HistogramEqualisation
from PIL import Image
import cv2
from utils.augmentation.Cloner import Clone
from utils.augmentation.Colorizer import Colorize
from utils.augmentation.Skitcher import Skitch
import random
d... | python |
# --------------
# import the libraries
import numpy as np
import pandas as pd
import seaborn as sns
from sklearn.model_selection import train_test_split
import warnings
warnings.filterwarnings('ignore')
# Code starts here
df = pd.read_csv(path)
print(df.head(5))
X=df.iloc[:,:7]
y=df.iloc[:,7]
X_train,X_test,y_train,... | python |
from rest_framework.serializers import ModelSerializer
from apps.recetas.models import Receta
class RecetaSerializer(ModelSerializer):
class Meta:
model = Receta
fields = [
'cantidad',
'fecha',
'personal',
'bienes',
]
| python |
from django.test import TestCase
from django.template import Template, Context
def render(template, context):
t = Template(template)
return t.render(context)
class XSSTests(TestCase):
def test_use_component_doesnt_allow_xss(self):
TEMPLATE = "" \
"{% load megamacros %}" \
... | python |
from bip_utils import Bip39MnemonicGenerator, Bip39SeedGenerator, Bip44, Bip44Coins, WifDecoder, \
RippleConf, XrpAddr, Bip32, Bip44Changes
from keygen.crypto_coin import CryptoCoin
from keygen.crypto_coin_service import CoinService
# mnemonic = Bip39MnemonicGenerator.FromWordsNumber(12)
mnemonic = "copy curve r... | python |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import annotations
from dataclasses import dataclass
from typing import List, Tuple, Iterable
import numpy as np
import pa... | python |
# coding: utf-8
"""
Function for calculating the modular inverse. Exports the following items:
- inverse_mod()
Source code is derived from
http://webpages.charter.net/curryfans/peter/downloads.html, but has been heavily
modified to fit into this projects lint settings. The original project license
is list... | python |
# -*- coding: utf-8 -*-
"""
"""
from .bpy_helper import needs_bpy_bmesh
@needs_bpy_bmesh()
def _create_ground_material(name: str = "ground_material", *, bpy):
if name in bpy.data.materials:
raise RuntimeError("Material '{}' already exists".format(name))
mat = bpy.data.materials.new(name=name)
m... | python |
from itertools import product
from hyperparameter_tuner.single_parameter_generator import single_parameter_generator as sgen
class run_command_generator():
def __init__(self, single_parameter_generator_list, command_prefix="python ../experiment.py",
output_path="./results"):
for gen in s... | python |
# Copyright (C) 2020-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from openvino.tools.pot.app.run import main
if __name__ == '__main__':
main()
| python |
"""从客户端收到一条数据后,在数据头增加’来自服务器‘字符串,然后一起转发回客户端,然后关闭服务器套接字。"""
'''
@Time : 2018/1/21 下午4:12
@Author : scrappy_zhang
@File : net02_udp_server.py
'''
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
address = ('192.168.234.1', 8888) # 地址:设定服务器要使用端口8888
sock.bind(address) # 绑定端口
recv_data = so... | python |
import random
from raiden.storage.serialize import JSONSerializer
from raiden.storage.sqlite import SerializedSQLiteStorage
from raiden.storage.wal import WriteAheadLog
from raiden.tests.utils import factories
from raiden.transfer import node
from raiden.transfer.architecture import StateManager
from raiden.transfer.s... | python |
from __future__ import annotations
class OpensearchIndexId:
"""
Build OpenSearch Index Id using given endpoint and index name or resolve the index name from given resource Id.
"""
def __init__(self, opensearch_endpoint: str, index_name: str) -> None:
self.opensearch_endpoint = opensearch_endp... | python |
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.3'
# jupytext_version: 1.0.2
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + {"toc": true, "cell_t... | python |
import unittest
from dojo import separate_names, get_bigger_name, ordenados
entrada = [['Joao', 'NO'], ['Carlos', 'YES'], ['Abner', 'NO'], ['Samuel', 'YES'], ['Ricardo', 'NO'], ['Abhay', 'YES'], ['Samuel', 'YES'], ['Andres', 'YES']]
class DojoTest(unittest.TestCase):
def test_separate_names(self):
self.ass... | python |
from config import CONFIG
import models
def check_date(date_string):
"""checks user date string is in correct format for parsing to a datetime object"""
failure_message = CONFIG['date_check_failure_msg']
try:
date_time_obj = models.datetime.datetime.strptime(
date_string, CONFIG['date_... | python |
#
# PySNMP MIB module ENTERASYS-NAT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ENTERASYS-NAT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:04:10 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | python |
# Generated by Django 2.1.7 on 2019-04-02 16:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('homepage', '0003_auto_20190330_2350'),
]
operations = [
migrations.AlterField(
model_name='post',
name='caption',
... | python |
import json
import maya.cmds as mc
__author__ = 'Lee Dunham'
__version__ = '1.1.0'
SHADER_MAPPING_NODE = 'ld_shader_mapping_node'
TRANSPARENT_SHADER_NAME = 'ld_transparencyShader'
# ------------------------------------------------------------------------------
def _get_shading_engine(node):
for grp in mc.ls(... | python |
# --------------
import pandas as pd
import numpy as np
from sklearn.cross_validation import train_test_split
# code starts here
df = pd.read_csv(path)
print(df.head())
X = df.drop('list_price', axis=1)
y = df.list_price
X_train, X_test, y_train, y_test = train_test_split(X, y,
... | python |
from x_rebirth_station_calculator.station_data.station_base import Ware
names = {'L044': 'Quantum Tubes',
'L049': 'Quantumröhren'}
QuantumTubes = Ware(names)
| python |
from tests import BaseTestCase
import json
from base64 import b64encode
class TestUserRegistration(BaseTestCase):
def setUp(self):
""" Sets up the test client"""
super(TestUserRegistration, self).setUp()
def test_user_registration(self):
# successful user registration
payload... | python |
#!/usr/bin/env python
import argparse, os, sys, signal
sourcedir=os.path.dirname(os.path.abspath(__file__))
cwdir=os.getcwd()
sys.path.append(sourcedir)
from pythonmods import runsubprocess
def default_sigpipe():
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
def positiveint(x):
x = int(x)
if x < 0:
... | python |
"""
Compute the overall accuracy of a confusion matrix
"""
from __future__ import print_function
import sys
from optparse import OptionParser
import numpy as np
import cpa.util
from cpa.profiling.confusion import confusion_matrix, load_confusion
parser = OptionParser("usage: %prog [options] CONFUSION")
parser.add_opt... | python |
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
#
"""KD tree data structure for searching N-dimensional vectors (DEPRECATED).
The KD tree data structure can be used for all kinds of searches that
in... | python |
from sanic import Blueprint
from sanic.exceptions import NotFound, Unauthorized, ServerError, Forbidden
from sanic.response import json
from utils import error, success
ex = Blueprint('exception')
@ex.exception(Unauthorized)
async def unauthorized(request, exception):
""" 用于处理账号错误 """
return error(message=f... | python |
from setuptools import setup
with open("README.md") as f:
long_description = f.read()
# tests_require = ["vcrpy>=1.10.3",]
setup(
name="monkeytools",
version="0.4",
description="A personal collection of algorithms and tools for the standard code monkey.",
long_description=long_description,
lo... | python |
from .swt import Seawat
from .swtvdf import SeawatVdf
| python |
from util.fileops import FileOps
from util.cli import CLI
import subprocess
import os
class BackBlazeB2:
def __init__(self):
self.fileops = FileOps()
self.cli = CLI()
self.bucket = self.fileops.bb_bucket
def authorize(self):
subprocess.run([self.fileops.blaze,"authorize-accou... | python |
import sys
from ga144 import GA144
#import draw
if __name__ == '__main__':
g = GA144()
g.loadprogram(sys.argv[2])
# v = draw.Viz(g.active())
# v.render("pictures/%s.png" % sys.argv[2])
g.download(sys.argv[1], 460800)
| python |
import time
import pytest
import rfernet
def test_sanity():
key = rfernet.Fernet.generate_new_key()
# Generates random string already so why not?
plain = rfernet.Fernet.generate_new_key().encode()
fernet = rfernet.Fernet(key)
encrypted = fernet.encrypt(plain)
assert fernet.decrypt(encrypted) ... | python |
import time
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
from market_maker.settings import settings
# ----------------------------------------------------------------------------------------------------------------------
# Config
base_ur... | python |
from spaceNetUtilities import labelTools as lT
import os
import glob
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-imgDir", "--imgDir", type=str,
help="Directory of Raster Images")
parser.add_argument("-geoDir", "--geojsonDir",... | python |
# =============================================================================== #
# #
# This file has been generated automatically!! Do not change this manually! #
# ... | python |
"""Module containing the ShearSplink pipelines."""
import logging
from pathlib import Path
from cutadapt import seqio
import pandas as pd
import pysam
from pyim.external.cutadapt import cutadapt, cutadapt_summary
from pyim.external.bowtie2 import bowtie2
from pyim.external.util import flatten_arguments
from pyim.mod... | python |
#Esta é uma biblioteca básica para a criação dos dicionários que serão utilizados
#na serialização JSON que será enviada para aplicação
#Importando o módulo timedelta da biblioteca datetime
from datetime import timedelta
#CLASSES
class DispositivoEnvio:
def __init__(self, idD = None, noLoc = None, noDisp = None,... | python |
import sys
import getopt
from learning.TruffleShuffle import TruffleShuffle
import os
from shutil import copyfile
import codecs
import shutil
import json
class Usage(Exception):
def __init__(self, msg):
self.msg = msg
def cluster(project_name, working_dir_str, copy_to_webapp=False):
#try to get t... | python |
import tensorflow as tf
import kerastuner as kt
from sacred import Experiment
from model.training import sharpe_loss, fit
from util.data import load_data, preprocess, split_train_test_validation, make_dataset, create_full_datasets
ex = Experiment()
@ex.config
def config():
data_dir = 'data'
alpha = 0.01
... | python |
# Generated by Django 2.1.5 on 2019-11-22 05:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tab', '0012_merge_20191017_0109'),
]
operations = [
migrations.AlterField(
model_name='judge',
name='ballot_code',
... | python |
from django.core.exceptions import ImproperlyConfigured
import pytest
from tests.factories import AttachmentFactory, AttachmentFileTypeFactory
from unicef_attachments import utils
from unicef_attachments.models import AttachmentFlat, FileType
from unicef_attachments.permissions import AttachmentPermissions
from demo... | python |
from ambra_sdk.service.filtering import Filter, FilterCondition
from ambra_sdk.service.sorting import Sorter, SortingOrder
class TestStudy:
"""Test Study."""
def test_study_list(
self,
api,
account,
readonly_study,
):
"""Test study list."""
studies = api \
... | python |
import texts
#handles the backgrounds
#GLOBALS
masterfreeskill3 = 0
masterskillBG = []
masterextralang = 0
miscdictBG = {}
mastertools = []
masterfeats = []
masterequip = []
class Background(object):
customskill = 0
customlang = 0
bgskills = []
bgFeat = []
tools = []
equip = []
... | python |
#!/usr/bin/env python3
def sum_of_fibonacci_numbers_under(n):
total = 0
a = 1
b = 2
while b < n:
if b % 2 == 0:
total += b
a, b = b, a + b
return total
def solve():
return sum_of_fibonacci_numbers_under(4000000)
if __name__ == '__main__':
result = solve()
... | python |
from numpy import array, testing
from luga import languages
def test_sentences(text_examples):
responses = languages(text_examples["text"])
pred_langs = [response.name for response in responses]
pred_scores = [response.score > 0.5 for response in responses]
assert pred_langs == text_examples["lang"]... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.