content stringlengths 5 1.05M |
|---|
import os
import unittest
import numpy as np
import openmdao.api as om
import numpy.testing as npt
import wisdem.rotorse.rotor_power as rp
# Load in airfoil and blade shape inputs for NREL 5MW
ARCHIVE = os.path.dirname(os.path.abspath(__file__)) + os.path.sep + "regulation.npz"
NPZFILE = np.load(ARCHIVE)
def fillpr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ====================
# Set-up
# ====================
# Import required modules
import pyperclip
import regex as re
__author__ = 'Victoria Morris'
__license__ = 'MIT License'
__version__ = '1.0.0'
__status__ = '4 - Beta Development'
# ISBN forma... |
from wq.core import wq
import click
import os
import json
import scss as pyScss
import logging
import pystache
from .collect import readfiles
import requirejs
from babeljs import transformer as babeljs
@wq.command()
@wq.pass_config
def optimize(config):
"""
Use r.js to optimize JS and CSS assets. This com... |
#!/usr/bin/env python3
""" Holmakefile generator.
This script generates `Holmakefile` files from `Holmakefile.gen` files, in
order to add support for inclusion.
Syntax:
Lines beginning with `include ` will be replaced by the content of all
files whose paths follow on the line, in the order they appear on the... |
import logging
import os
import re
class DialogueTextFile:
def __init__(
self,
data_path,
input_paths,
label_name,
eoc_regex,
eoc,
limit=None,
):
self.input_paths = [
os.path.join(data_path, input_path) for input_path in input_paths
... |
import json
import logging
import tweepy
logger = logging.getLogger()
def createApi():
with open("../config.json", "r") as file:
config = json.load(file)
auth = tweepy.OAuthHandler(config["consumerApiKey"], config["consumerApiSecretKey"])
auth.set_access_token(config["authApiKey"], config["auth... |
from ppf_date_time import \
weekdays \
, months_of_year \
, nth_kday_of_month \
, year_based_generator
from nth_imm_of_year import *
def first_imm_after(start):
'''Find the next IMM date after the given date.
>>> from ppf_date_time import date
>>> from ppf_date_time ... |
#!/usr/bin/python
import sys
import os
import time
import datetime
from datetime import timedelta
import requests
from bs4 import BeautifulSoup
from ftplib import FTP
#if len(sys.argv) != 2:
# print >>sys.stderr, "Useage: ",sys.argv[0]," [YYYY_MM_DD]"
# quit()
#date = sys.argv[1]
# get current date and time mi... |
# -*- coding: utf-8 -*-
# Copyright 2022, SERTIT-ICube - France, https://sertit.unistra.fr/
# This file is part of eoreader project
# https://github.com/sertit/eoreader
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may ob... |
from ProcessData.Utils import *
from ProcessData.Skeleton import Skeleton
# rotation = rotType.SixDim
# latentDim = 20
# deltaT = 6
# poseComponents = ['R{}'.format(rotation.name), 'Height', 'Root_Position_Velocity', 'Root_HipAngleRad', 'Root_HipTurnVelRad']
# featureComponents = ['Height_last', 'Root_Position_Veloci... |
#!/usr/bin/env python3
import argparse
import serial
from time import sleep
import pynput
import pyautogui
import win32api
import win32con
# for time delaying the input:
from threading import Timer
import time
from math import sqrt
from switchcontroller.switchcontroller import *
screenWidth, screenHeight = pyautogui... |
import os
import urllib.request, urllib.error, urllib.parse
import time
from minerl.dependencies.pySmartDL.pySmartDL import utils
def download(url, dest, startByte=0, endByte=None, headers=None, timeout=4, shared_var=None, thread_shared_cmds=None, logger=None, retries=3):
"The basic download function that runs at... |
import sys
def dfs(node):
if visit[graph[node]] is 0:
visit[graph[node]] = 1
dfs(graph[node])
if visit[graph[node]] is 1:
visit[graph[node]] = 2
dfs(graph[node])
if visit[node] is 1:
visit[node] = 0
n = int(sys.stdin.readline())
graph = [int(sys.stdin.readline()) ... |
import re
import urllib.request
from urllib.error import URLError
class Skeleton:
NON_URL_SKELETON = re.compile('^[A-Za-z0-9_-]+$')
_url: str
def __init__(self, skeleton_identified: str) -> None:
self._skeleton_identified = skeleton_identified
def get_url(self) -> str:
try:
... |
from aiovault import Vault
from conftest import async_test
import pytest
@async_test
def test_raw(dev_server):
client = Vault(dev_server.addr, token=dev_server.root_token)
with pytest.raises(KeyError):
yield from client.raw.read('foo')
written = yield from client.raw.write('foo', {'bar': 'baz'})... |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import RelaxedOneHotCategorical
import numpy as np
... |
"""
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
t = int(input())
for _ in range(t):
n, ... |
# -*- coding: utf-8 -*-
import xmind
from xmind.core.const import TOPIC_DETACHED
from xmind.core.markerref import MarkerId
from xmind.core.topic import TopicElement
import os
import time
def gen_my_xmind_file():
workbook = xmind.load("my.xmind")
sheet1 = workbook.getPrimarySheet()
time_name = basic_sh... |
import unittest
import pytest
from xpath_string.xpath import Xpath
class TestXpath(unittest.TestCase):
def setUp(self):
self.object_1 = Xpath("//div")
self.object_2 = Xpath("//span")
def test_object_creation(self):
assert isinstance(self.object_1, Xpath), \
'object is no... |
from kivy.app import App
from kivy.factory import Factory
from kivy.properties import ObjectProperty
from kivy.lang import Builder
Builder.load_string('''
<SeedOptionsDialog@Popup>
id: popup
title: _('Seed Options')
size_hint: 0.8, 0.8
pos_hint: {'top':0.9}
BoxLayout:
orientatio... |
"""
Show how to use libRocket in Panda3D.
"""
import sys
from panda3d.core import loadPrcFile, loadPrcFileData, Point3,Vec4, Mat4, LoaderOptions # @UnusedImport
from panda3d.core import DirectionalLight, AmbientLight, PointLight
from panda3d.core import Texture, PNMImage
from panda3d.core import PandaSystem
import ran... |
"""
Plotting experimental data.
"""
import numpy as np
import h5py
import microval
class ImageData:
"""
Abstract class for image data.
"""
def _clip_data(self, data_arr, region):
sel_x, sel_y = range(region[0], region[1] -
1), range(region[2], region[3] - 1)
... |
'''Submódulo IBGE contendo funções diversas.
Este submódulo é importado automaticamente com o módulo `ibge`.
>>> from DadosAbertosBrasil import ibge
'''
from typing import Union
import pandas as _pd
import requests
from DadosAbertosBrasil._utils import parse
from DadosAbertosBrasil._utils.errors import DAB_Localid... |
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
while True:
_, frame = cap.read()
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
blurred_frame = cv2.GaussianBlur(frame, (5, 5), 0)
laplacian = cv2.Laplacian(blurred_frame, cv2.CV_64F)
canny = cv2.Canny(blurred_frame, 100, 150... |
test_cases = [
test_case(
cmd='yb_check_db_views.py @{argsdir}/db1 --database_in {db1}'
, exit_code=0
, stdout="""-- Running broken view check.
-- 0 broken view/s in "{db1}".
-- Completed check, found 0 broken view/s in 1 db/s."""
, stderr='')
, test_case(
cmd='yb_check_... |
import warnings
import numbers
import collections
import numpy as np
import pickle
import os
from autoscalingsim.scaling.policiesbuilder.metric.scaling_aspect_calculation.calculators.learning_based.model.model import ScalingAspectToQualityMetricModel
class LinearModel(ScalingAspectToQualityMetricModel):
def _int... |
# -*- coding: utf-8 -*-
# Copyright (C) 2014 Denys Duchier, IUT d'Orléans
#==============================================================================
import threading, os, os.path, json, pickle
#==============================================================================
# basic functionality for all databases
... |
from setuptools import find_packages, setup
setup(
name='baking_cookies',
packages=find_packages(),
version='0.1.0',
description='Tutorials and examples for working with data at Nesta.',
author='Nesta',
license='MIT',
)
|
import os
import shutil
import unittest
from click.testing import CliRunner
from blogger_cli import ROOT_DIR
from blogger_cli.cli import cli
from pkg_resources import resource_filename
class TestBasic(unittest.TestCase):
def setUp(self):
self.runner = CliRunner()
HOME_DIR = os.path.expanduser("~")... |
import numpy as np
from typing import Union, Callable, Tuple
__all__ = ['LossLayer', 'FCLayer']
class Layer:
def __init__(self, activation: Union[str, Tuple[Callable[[np.array], np.array],
Callable[[np.array], np.array]]]) -> None:
"""
Abstract c... |
import diagrams
import diagrams.aws.compute as compute
import diagrams.aws.devtools as devtools
import diagrams.aws.management as manage
import diagrams.aws.network as network
import diagrams.aws.storage as storage
diagram_attr = {
'margin': '-0.8,-0.8',
'size': '10,8',
'bgcolor': 'transparent'
}
with diag... |
import importlib
import builtins
from .scope import Scope, allowed_classes
from .vmbuiltins import setBuiltins
# Return scope-before-scope0
def fillScope0(scope0):
scope0.inherits = {}
# Built-in constants
scope0.inherits["False"] = False
scope0.inherits["True"] = True
scope0.inherits["None"] = N... |
"""Various network "heads" for classification.
The design is as follows:
... -> RoI ----\
-> RoIFeatureXform -> prn head -> prn output -> prn loss
... -> Feature /
Map
The PRN head produces a feature representation of the RoI for the purpose
of classfying whether the roi needs further refineme... |
import torch, pdb
import torch.nn
from IPython import embed
import torch.nn.functional as F
import pdb
import random
import numpy as np
import time
import functools
from .utils import nms, add_box_img, nms_worker
from torch.multiprocessing import Pool, Manager
def rpn_cross_entropy(input, target):
r"""
:para... |
# Names scores
import os
def cVal(m):
s = 0
for n in m:
if n != '"':
s += ord(n) - ord("A") + 1
return s
f = open(os.path.abspath("..") + "\\data\\P022.txt", "r")
names = f.readline().split(",")
f.close()
names.sort()
su = 0
for y in range(len(names)):
su += cVal(names[y]) * (... |
from .Textos import Textos
from .Opciones import OpcionesCat
from .Rectangulos import Rectangulos
from .Esquinas import DatosEsquinas
from .MovParabolico import *
from .Terreno import Terreno
from .Variables import *
from .Turnos import *
from .Tanques import *
from .IA import *
class Juego:
def juego(... |
#!/usr/bin/env python
#Script for adding ned specs to existing DB.
#2014, Korbinian Schweiger
import os
import sys
import backend
def addspec(name, value, workdir):
print workdir
lines = readDB(workdir)
print lines
for i in range(len(lines)):
print lines[i]
lines[i] = lines[i] + name +... |
# author: Navneel Singhal
# functionality: extraction, training and validation
import structure_analysis
import utility
from time import time
import pickle
import numpy as np
import random
classes = [
'Benign',
'Malware/Backdoor',
'Malware/Trojan',
'Malware/Trojandownloader',
'... |
from psycopg2 import sql
import psycopg2.extras
class Query():
'''Helper class for PGStorage'''
def __init__(self, conn, schema, pkeys):
self._conn = conn
self._schema = schema
self._pkeys = pkeys
# Some "internal" informations are cached here
self._default_pkey_expr ... |
##########################################################################
#
# Copyright (c) 2009, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistribu... |
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import packer
Packer = packer.Packer
setup(
name = Packer.name,
version = Packer.version,
description = 'A new type of package manager',
long_description = open('README.rst').read(),
url = 'http://github.com/kalail... |
# Problem description: https://www.hackerrank.com/challenges/ctci-is-binary-search-tree/problem
""" Node is defined as
class node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
"""
def check(node, min, max):
if node is None:
return True
if n... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: tensorflow/core/protobuf/bfc_memory_map.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as... |
#
# This file is part of pretix (Community Edition).
#
# Copyright (C) 2014-2020 Raphael Michel and contributors
# Copyright (C) 2020-2021 rami.io GmbH and contributors
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
# Public License as published by ... |
from unittest import TestCase
from mock import MagicMock, patch
from tgt_grease.core import GreaseContainer, Configuration
from tgt_grease.enterprise.Model import KafkaSource
import time
import kafka
import multiprocessing as mp
class MockThread():
def __init__(self):
self.alive = False
self.daemon... |
import unittest
import unittest.mock as mock
from click.testing import CliRunner
from app import rps_game
def mock_computer_move(cls, *args, **kwargs):
return 0
class TestApp(unittest.TestCase):
def test_rps_game(self):
with mock.patch('random.randint', mock_computer_move):
runner = Cli... |
""" Tests for server defaults
"""
from unittest.mock import Mock
from styler_rest_framework.helpers import aiohttp_defaults
class TestAddMiddlewares:
def test_add_middlewares(self):
app = Mock()
app.middlewares = []
aiohttp_defaults.add_middlewares(app)
assert len(app.middlewar... |
from __future__ import absolute_import
import numpy as np
import string
import re
from six.moves import range
def cleanzeros(values):
newlist = []
oldlist = values
while oldlist:
interval = oldlist[0:3]
if interval[0] != 0:
newlist += interval
oldlist = oldlist[3:]
... |
"""
This class represent one word beloging to grammar class classified as 'Preposition'
What's a Preposition?
===
A word governing, and usually preceding, a noun or pronoun and expressing a relation
to another word or element in the clause.
Prepositions are often used to express spatial or temporal relations (in, unde... |
from mock import patch
from autodynatrace.wrappers.django.utils import get_host, get_request_uri, get_app_name
@patch("django.http.HttpRequest")
def test_get_host(django_request_mock):
django_request_mock.get_host = lambda: "myhost:80"
assert get_host(django_request_mock) == "myhost:80"
django_request_m... |
import random
import numpy as np
from atcenv.definitions import Flight, Airspace
from shapely.geometry import Point, Polygon
def position_scramble(ac_point, probability, min_dist, max_dist, alt = 0):
'''
Input: a point, a probability that the point. Output: a scrambled position. Must be within airspace.'''
... |
test = False
db_user = 'root'
db_password = ''
|
import engine.db_structure as db_py
import os
filename = "crud.vdb"
if os.path.isfile(filename):
os.remove(filename)
db = db_py.Database(False, filename)
def test_create():
excepted_table = db_py.Table()
excepted_table.name = "vadik_table"
excepted_table.fields = ["zhenya1", "zhenya2"]
excepted_... |
import snakypy.{{ cookiecutter.project_slug }} # noqa: F401
|
# -*- coding: utf-8 -*-
from flask import jsonify, make_response, request
import json
from app.api import bp, GET, YES
from app.lib.phonetize import phonetize2
@bp.route('/api/phonetize/<path:text>',
methods=[GET], strict_slashes=False)
def phonetize(text):
level = request.args.get('level')
syllabl... |
import jwt
import datetime
import random
from flask import current_app as app
from core import db
from .models import Verifications as verify
# class Auth():
# def encode_auth_token(self, user_id):
# """
# Generates the Auth Token
# :return: string
# """
# try:
# ... |
"""
Tests that C++ member and static variables are available where they should be.
"""
import lldb
from lldbtest import *
import lldbutil
class CPPThisTestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
@skipUnlessDarwin
#rdar://problem/9962849
#@expectedFailureClang
@dsym_test
... |
import pyglet
from .game import Game
pyglet.resource.path = ['../resources']
pyglet.resource.reindex()
def main():
game = Game(fullscreen=True)
game.run()
if __name__ == '__main__':
main()
|
from django.shortcuts import render, redirect
from django.views.generic.edit import FormView
from .forms import ExelForm
# from .exchange import DataFrame
import matplotlib.pyplot as plt
from scipy import stats
import os
class FileFieldView(FormView):
form_class = ExelForm # Upload from from forms.py for templa... |
"""
2019/12/2 21:43
134.【Python魔术方法】属性访问控制魔术方法
"""
"""
属性访问控制魔术方法:
__getattr__魔术方法:
在访问一个对象的某个属性的时候,如果这个属性不存在,那么就会执行__getattr__方法,
将属性的名字传进去。如果这个属性存在,那么就不会调用__getattr__方法.
__setattr__魔术方法:
只要给一个对象的属性设置值,那么就会调用这个方法。但要注意的是,不要在这个方法中
调用self.xxx=xxx的形式,因为会产生递归。如果想要给对象的属性设置值有两种方式:
1)使用self.__dict__[name] = value 这个魔术属性.
2... |
from tkinter import Tk, Button
import pygame
pygame.init()
sound = r'alarm.mp3'
def alarm_ring_gui():
root = Tk()
btn = Button(text="Выключить будильник",
background="#f00",
foreground="#000",
activebackground='#00f',
activeforeground='#fff'... |
"""
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
EX:
f("madam") yield True since reverse("madam") == "madam"
"""
def invert_str(s: str) -> str:
return s[::-1]
de... |
numbers = (1, 2, 3, 4)
print(numbers)
cheeses = ('swiss', 'cheddar','ricotta', 'gouda')
print(cheeses)
|
from __future__ import print_function
from __future__ import division
from past.utils import old_div
import supereeg as se
import glob
from supereeg.helpers import *
from scipy.stats import kurtosis, zscore
import os
## don't understand why i have to do this:
from supereeg.helpers import _std, _gray, _resample_nii, _a... |
# Copyright 2021 Norwegian University of Science and Technology.
#
# 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... |
import random
from scipy.stats import zipf
DEFAULT_SIZE = 1
def randint_array(low_bound, up_bound, size=None, seed=0):
"""
Get randint array
Args:
low_bound(int): lowest bound
up_bound(int): highest bound
size(int): size of array
seed(int): the seed of random
"""
... |
from app.db import db
class Transaction(db.Model):
__tablename__ = 'transactions'
id = db.Column(
db.Integer,
primary_key = True,
autoincrement = True
)
user_id = db_Column(
db.Integer,
db.ForeignKey('users.id')
nullable = False
)
shop_... |
# Generated by Django 2.2.1 on 2019-05-23 03:36
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0009_auto_20180316_1758'),
]
operations = [
migrations.AlterField(
model_name='persona'... |
import pytest
from polygon import Polygon
def test_polygon_class():
points = [(0, 0), (2, 0), (2, 2), (0, 2)]
polygon = Polygon(points)
assert isinstance(polygon, Polygon)
assert isinstance(polygon.points, list)
assert polygon.points == points
def test_area():
points = [(0, 0), (2, 0), (2, ... |
import json
import spacy
from sponsors_detector.process_text import find_video_sponsors
from util.util import (get_model_path, is_video_processed,
process_sponsors, add_new_watch_event)
HEADERS = {'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type,X-Amz-... |
from .discrete import Discrete
|
from .settings import * # noqa
import os
dbhost = os.environ['PGHOST']
dbname = os.environ['PGDATABASE']
dbuser = os.environ['PGUSER']
dbpassword = os.environ['PGPASSWORD']
dbport = os.environ['PGPORT']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': dbname,
... |
"""Frontend URL Configuration
path / load react app
"""
from django.conf.urls import url
from django.urls import path
from .views import index
urlpatterns = [
path('', index, name='index'),
url(r'^(?!(api|docs)).*$', index),
]
|
some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
some_dictionary = {}
for element in some_list:
if element not in some_dictionary:
some_dictionary[element] = 1
else:
some_dictionary[element] += 1
for key, value in some_dictionary.items():
if value > 1:
print(key, end=' ')
# anot... |
expected_output = {
"GigabitEthernet0/0/1": {
"service_policy": {
"input": {"policy_name": {"TEST": {}}},
"output": {"policy_name": {"TEST2": {}}},
}
},
"TenGigabitEthernet0/3/0.41": {
"service_policy": {
"output": {
"policy_name": ... |
from wrapper import SeleniumWrapper
from selenium.webdriver.common.by import By
from datetime import datetime
import time
import re
class MeetingHandler:
def __init__(self, driver):
self.selenium = SeleniumWrapper(driver)
self.current_meeting = {}
def check_ongoing_meeting(self):
... |
# import functions from packages
import os
import time
import pickle
import numpy as np
import scipy
import matplotlib.pyplot as plt
import multiprocessing as mp
# import local variables
from .. import _allowed_colors, _image_size, _correction_folder
# import local functions
from ..io_tools.load import correct_fov... |
import logging
# log format
format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
format_without_levelname = logging.Formatter('%(asctime)s - %(name)s - %(message)s')
# the root logger
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# file Log
f_handler = logging.FileHandler(... |
from . import api
v1 = [
(r"attendance/terminal", api.TerminalViewSet, "attendance-terminal"),
(
r"attendance/campusonlineholding",
api.CampusOnlineHoldingViewSet,
"attendance-campusonline-holding",
),
(
r"attendance/campusonlineentry",
api.CampusOnlineEntryViewS... |
"""Task: Test the check co-ordinates function."""
# Imports --------------------------------------------------------------
from modules.check_coordinates import check_coordinates
# Classes --------------------------------------------------------------
# Functions ---------------------------------------------------... |
"""
This module contains all the hyperparameters of the model.
It contains a function for each module in the project (that uses at least one hyperparameter);
each function returns a named tuple with the parameters.
"""
from collections import namedtuple
_NetworkT = namedtuple('_NetworkT', ['topk'])
_COCODatasetT = na... |
# =========================================================================
# This code built for MCEN90048 project
# Written by Zhuo LI
# The Univerivsity of Melbourne
# zhuol7@student.unimelb.edu.au
# =========================================================================
import tensorflow as tf
import os
... |
# -*- coding: utf-8 -*-
# @Time : 2019-10-15 14:32
# @Author : Jason
# @FileName: utils.py
import scipy.sparse as sp
import numpy as np
from scipy.sparse.linalg.eigen.arpack import eigsh, ArpackNoConvergence
import random
import matplotlib.pyplot as plt
import os
def encode_onehot(labels):
classes = set(lab... |
"""
this script is used to process the CCPD_FR labels and make them fit the required training format
"""
from collections import deque
import cv2
import numpy as np
from src.img_utility import pts_to_BBCor, read_img_from_dir, pixel_to_ratio, IoU
from src.dataset_utility import CCPD_FR_vertices_info
from src.data_aug ... |
a = (
1,
<caret>2,
)
|
# The MIT License (MIT)
#
# Copyright (c) 2015 Brian Wray (brian@wrocket.org)
#
# 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
# ... |
import gzip
import os
import argparse
import re
__author__ = "Peter Chovanec"
def parse_args():
parser = argparse.ArgumentParser(description='Remove short barcodes')
parser.add_argument('--r1', dest='read_1', type=str, required=True,
help='Fastq read 1')
opts = par... |
VERSION='1.0.2'
|
from compas_slicer.slicers import BaseSlicer
from compas_slicer.slicers.curved_slicing import find_desired_number_of_isocurves
import logging
from compas_slicer.slicers.curved_slicing import IsocurvesGenerator
from compas_slicer.parameters import get_param
logger = logging.getLogger('logger')
__all__ = ['CurvedSlice... |
import Levenshtein as Lev
def cer_single(s1, s2):
"""
Computes the Character Error Rate, defined as the edit distance.
Arguments:
s1 (string): space-separated sentence
s2 (string): space-separated sentence
"""
s1, s2, = s1.replace(
" ", ""
), s2.replace(" ", "")
ret... |
#!/bin/env python
from app import create_app, socketio
from flask_debugtoolbar import DebugToolbarExtension
app = create_app(debug=True)
toolbar = DebugToolbarExtension(app)
if __name__ == '__main__':
socketio.run(app, host=app.config['WEB_IP'])
# End File: chat.py
|
def swap_case(s):
s1 = ''
for i in s:
if i.isupper():
s1 = s1 + i.lower()
elif i.islower():
s1 = s1 + i.upper()
else:
s1 = s1 + i
return s1
if __name__ == '__main__':
s = input()
result = swap_case(s)
print(result)
|
import json
import pandas as pd
from .base import MultiLevelComputer, STANDARDS_FILE
from .ssrtmodel import SSRTmodel
from .sequence import PostStopSlow, Violations
class StopSummary(MultiLevelComputer):
def __init__(self, ssrt_model='replacement',
pss_correct_go_only=True, pss_filter_columns=Tru... |
from typing import List
import requests
from iexcloud.constants import IEX_CLOUD, IEX_TOKEN
class Reference(object):
def __init__(self):
self.msg_limit: int = self.get_msg_limit()
self.msg_used: int = self.get_msg_used()
self.msg_balance: int = self.msg_limit - self.msg_used
self... |
from ...common_descs import *
from .objs.effe import EffeTag
from supyr_struct.defs.tag_def import TagDef
part_scale_modifiers = (
"velocity",
"velocity_delta",
"velocity_cone_angle",
"angular_velocity",
"angular_velocity_delta",
"type_specific_scale"
)
particle_scale_modifier... |
'''
Created on Jan 26, 2018
@author: enerve
'''
from __future__ import division
import logging
import numpy as np
import random
import matplotlib.pyplot as plt
class Perceptron(object):
'''
The Perceptron classifier, intended to be run on a dataset of two classes
that are linearly separable.
'''
... |
from . build_state import SvgBuildState
|
# -*- coding: utf-8 -*-
"""User models."""
import datetime as dt
from enum import auto, Enum
from flask_login import UserMixin
from flask_fsm_test.database import (
Column,
Model,
SurrogatePK,
db,
reference_col,
relationship,
)
from flask_fsm_test.extensions import bcrypt
from transitions im... |
__author__ = 'Killua'
import numpy as np
class RidgeRegression:
"""
Implementation of ridge regression
"""
# properties
beta = None # estimated coefficient
y = None # regression output
data = None # regression input
alpha = 0 # penalty term
intercept = False # whether ... |
import multiprocessing
from .event_bus import EventBus
from .settings import Settings
with multiprocessing.Pool() as pool:
from ui import qtx
app = qtx.QApplication([])
settings = Settings('redstork-sample')
bus = EventBus()
from .view.main_view import MainView
mainView = MainView(app)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.