content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from os.path import basename
from pandas import read_csv
from NaiveBayes import *
from DecisionTrees import *
from KNN import *
from K_Means import *
from Evaluator import *
from PickleFiles import *
def run():
try:
os.mkdir(os.path.join("", "myFiles"))
except FileExistsError:
pa... | python |
import pickle
import pandas as pd
import nltk
import re
from nltk.corpus import wordnet as ewn
import numpy as np
def load_dataset(path,train):
train_data = np.load(path, allow_pickle=True)
########if(not train):
#train_data = train_data[()]
embeddings = train_data['embeddings']
labels = train_data['labels']
sen... | python |
import io
import json
import time
import errno
import socket
import struct
import threading
from . import logs
from . import utils
TIMEOUT = 0.1
BACKLOG = socket.SOMAXCONN
CHUNK_SIZE = io.DEFAULT_BUFFER_SIZE
error = socket.error
timeout = socket.timeout
log = logs.get(__name__)
def start_client(address, handler, s... | python |
from flask import Flask, request, render_template
from flask_cors import cross_origin
import pickle
app = Flask(__name__)
model = open('car.pkl','rb')
regressor = pickle.load(model)
@app.route("/")
@cross_origin()
def home():
return render_template('car.html')
@app.route("/predict", methods=["GET"... | python |
"""Qgroupbox module."""
# -*- coding: utf-8 -*-
from PyQt6 import QtWidgets, QtCore # type: ignore[import]
from pineboolib.core import decorators
from pineboolib.core import settings
from pineboolib import logging
from . import qwidget
from typing import Any
logger = logging.get_logger(__name__)
class QGroupBox(... | python |
from datetime import timedelta
from django.test import TestCase
from django.utils.timezone import now
from core.models.route import Route
from core.models.station import Station
from core.models.tender import Tender
from core.models.workshop import Workshop
TEST_WORKSHOP = 'Bw Hagen'
TEST_ROUTE = 'KBS 100 Hamburg - ... | python |
from io import StringIO
from .. import *
from bfg9000 import path
from bfg9000 import safe_str
from bfg9000.shell.syntax import *
class my_safe_str(safe_str.safe_string):
pass
class TestWriteString(TestCase):
def test_variable(self):
out = Writer(StringIO())
out.write('foo', Syntax.variabl... | python |
"""
A collection of utilities for working with observation dictionaries and
different kinds of modalities such as images.
"""
import numpy as np
from copy import deepcopy
from collections import OrderedDict
import torch
import torch.nn.functional as F
import robomimic.utils.tensor_utils as TU
# DO NOT MODIFY THIS!
... | python |
# -*- coding: utf-8 -*-
"""
Tests for the salt-run command
"""
from __future__ import absolute_import, print_function, unicode_literals
import logging
import pytest
from tests.support.case import ShellCase
from tests.support.helpers import slowTest
log = logging.getLogger(__name__)
@pytest.mark.usefixtures("salt_s... | python |
from os import listdir, path
import random
import csv
import re
import natsort
import numpy
import theano
from skimage.io import imread
from block_designer import BlockDesigner
from sampler import Sampler
import pdb
class ImageFlipOracle(object):
"""
*_flip methods should take an image_name
"""
def _... | python |
from g2net.input import extract_dict_from_df
import pandas as pd
import pytest
@pytest.mark.parametrize(
'data_dict, key_col, val_col, expected_dict',
(
pytest.param(
{
'col1': [1, 2, 5],
'col2': [3, 4, 6]
},
'col1',
'... | python |
#
# Copyright (c) 2020 by Philipp Scheer. All Rights Reserved.
#
# usage: nlu.py [-h] [--config CONFIG]
#
# Natural language understanding engine using spaCy and RASA
# Convert spoken language into a command (skill) and arguments
#
# optional arguments:
# -h, --help show this help message and exit
# --con... | python |
import pickle
import pytest
from routrie import Router
def test_routing() -> None:
router = Router(
routes={
"/": 0,
"/users": 1,
"/users/:id": 2,
"/users/:id/:org": 3,
"/users/:user_id/repos": 4,
"/users/:user_id/repos/:id": 5,
... | python |
import os
import sys
sys.path.append(f'{os.getcwd()}/example/bpapi/vendor')
| python |
# Generated by Django 2.2.11 on 2020-04-09 13:49
from django.db import migrations, models
import django.db.models.deletion
import wagtail.core.fields
class Migration(migrations.Migration):
dependencies = [
('wagtailcore', '0041_group_collection_permissions_verbose_name_plural'),
('contentPages',... | python |
import urllib
def assert_urls_match(u1, u2):
p1 = urllib.parse.urlparse(u1)
p2 = urllib.parse.urlparse(u2)
assert p1.scheme == p2.scheme
assert p1.netloc == p2.netloc
assert p1.path == p2.path
assert urllib.parse.parse_qs(p1.query) == urllib.parse.parse_qs(p2.query)
class FakeResponse:
d... | python |
# -*- coding: utf-8 -*-
"""Defines `json.JSONEncoder` subclass
that makes parsed object (including bytes and bitarray) JSON-serializable
"""
import bitarray
import json
import sys
class JSONEncoder(json.JSONEncoder):
"""JSON encoder with additional support for bytes and bitarray
Examples:
>>> JSON... | python |
from os.path import getsize
from .constants import ATTACHMENT_CONTENT_TYPES
from .errors import FastScoreError
class Attachment(object):
"""
Represents a model attachment. An attachment can be created directly but it
must (ultimately) associated with the model:
>>> att = fastscore.Attachment('att-1'... | python |
# The Path class represents paths on a graph and records the total path cost
class Path:
def __init__(self):
self.length = 0
self.cost = 0
self.nodes = []
# adds a node to the end of the path
def add_node(self, node_label, cost):
self.length += 1
self.cost += cost
... | python |
#########################################################
# 2020-01-28 13:15:09
# AI
# ins: MOV @Ri, A
#########################################################
import random
from .. import testutil as u
from ..sim51util import SIMRAM
from ..asmconst import *
p = u.create_test()
ram = SIMRAM()
def test_rs(rs, psw... | python |
import sys, re, hashlib, json, random
import GenePredBasics, SequenceBasics
from SerializeBasics import encode_64, decode_64
# Transcriptome is a set of genepred entries
# with the corresponding fasta file.
# alternatively, you can read in a serialized transcriptome.
#
# You can further define a transcriptome file wit... | python |
from cnnlevelset.pascalvoc_util import PascalVOC
from cnnlevelset.localizer import Localizer
from cnnlevelset import config as cfg
from collections import defaultdict
import tensorflow as tf
import keras.backend as K
import numpy as np
import matplotlib.pyplot as plt
import sys
import time
tf.python.control_flow_ops... | python |
a'''
Created on 6-feb-2017
Modified the 20170321, by EP
@author: roncolato
'''
import numpy as np
import scipy.interpolate as interpol
from sherpa.training.step1 import from7to28 as f7
from sherpa.training.step1 import quant as q
from sherpa.training.step1 import EquaPrec as ep
from sherpa.training import EquaIndic ... | python |
"""ibc client module data objects."""
from __future__ import annotations
import attr
from terra_proto.ibc.core.client.v1 import Height as Height_pb
from terra_sdk.util.json import JSONSerializable
__all__ = ["Height"]
@attr.s
class Height(JSONSerializable):
revision_number: int = attr.ib(default=0, converter=i... | python |
import numpy as np
import scipy as scp
from numpy.linalg import norm
#############################################
# Add the one-folder-up-path
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '../'))
#############################################
from envs.blocking_env import BlockingEnv
... | python |
from annotation_utils.ndds.structs import NDDS_Dataset
dataset = NDDS_Dataset.load_from_dir('/home/clayton/workspace/prj/data_keep/data/ndds/measure_kume_map3_1_200', show_pbar=True)
dataset.save_to_dir('save_test', show_pbar=True) | python |
from datetime import date
def run_example():
march_2020_15 = date(year=2020, month=3, day=15)
print("march_2020_15.toordinal():", march_2020_15.toordinal())
print("march_2020_15.isocalendar():", march_2020_15.isocalendar())
if __name__ == "__main__":
run_example()
| python |
class Solution:
def XXX(self, nums: List[int]) -> int:
length = len(nums)
if length <= 1:
return nums[0]
for i in range(1, length):
sum_ = nums[i-1] + nums[i]
if sum_ > nums[i]:
nums[i] = sum_
return max(nums)
undefined
for (i = 0... | python |
import itertools
# Have the function ArrayAdditionI(arr) take the array of numbers stored in arr and return the string true if any combination of numbers in the array
# (excluding the largest number) can be added up to equal the largest number in the array, otherwise return the string false.
# For example: if ar... | python |
# -*- coding: utf-8 -*-
from aliyun.api.rest import *
from aliyun.api.base import FileItem
| python |
total_pf = {{packing_fraction}}
poly_coeff = {{polynomial_triso}}
| python |
# Declare Variables
name = input() # Seller's name
salary = float(input()) # Seller's salary
sales = float(input()) # Sale's total made by the seller in the month
# Calculate salary with bonus
total = salary + (sales * .15)
# Show result
print("Total = R$ {:.2f}".format(total))
| python |
from contextlib import contextmanager
import sys
@contextmanager
def stdout_translator(stream):
old_stdout = sys.stdout
sys.stdout = stream
try:
yield
finally:
sys.stdout = old_stdout
def read_translation(stream):
out = stream.getvalue()
outs = out.split('\n')
for item in o... | python |
#!/usr/bin/env python3
import os
import redis
import json
from flask import Flask, render_template, redirect, request, url_for, make_response
#r = redis.Redis(host='123.12.148.95', port='15379', password='ABCDEFG1231LQ4L')
if 'VCAP_SERVICES' in os.environ:
VCAP_SERVICES = json.loads(os.environ['VCAP_SERVICES'])
... | python |
import battlecode as bc
import sys
import traceback
import time
import pathFinding
#TODO: remove random and use intelligent pathing
import random
totalTime = 0
start = time.time()
#build my environment
gc = bc.GameController()
directions = list(bc.Direction)
#get the starting map
myMap = gc.starting_map(gc.planet())... | python |
#!/usr/bin/env python
import numpy as np # For efficient utilization of array
import cv2 # Computer vision library
import os # Here this package is used writing CLI commands
import vlc_ctrl
import time
import pandas as pd
import os # package used for controlling vlc media player
import subproc... | python |
# -*- coding: utf-8 -*-
import logging
from dku_model_accessor.constants import DkuModelAccessorConstants
from dku_model_accessor.preprocessing import Preprocessor
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
logger = logging.getLogger(__name__)
class SurrogateModel(object):
"""
... | python |
import yaml
try:
# use faster C loader if available
from yaml import CLoader as Loader
except ImportError:
from yaml import Loader
# follows similar logic to cwrap, ignores !inc, and just looks for [[]]
def parse(filename):
with open(filename, 'r') as file:
declaration_lines = []
decl... | python |
import re
class Graph:
def __init__(self, nodes, numWorkers=5):
self.graph = {}
for asciiCode in range(65, 91):
self.graph[chr(asciiCode)] = []
# populate link nodes
for node in nodes:
if node.pre in self.graph:
self.graph[no... | python |
# sql/expression.py
# Copyright (C) 2005-2022 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: https://www.opensource.org/licenses/mit-license.php
"""Defines the public namespace for SQL expression constructs.
"""
from ._dml... | python |
import argparse
from pathlib import Path
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.utils.data as data
from PIL import Image, ImageFile
from torchvision import transforms
from tqdm import tqdm
from template import imagenet_templates
import fast_stylenet
from sampler import Inf... | python |
# import os
# import json
#
# target_dirs = [ 'home_1', 'home_2', 'home_3', 'real_v0', 'real_v1', 'real_v2', 'real_v3', 'human_label_kobeF2', 'victor_1']
# target_file = './data/'
# for target_dir in target_dirs:
# target_file += target_dir + '_'
# target_file += 'output.json'
#
# output_images = {}
# output_annota... | python |
# ==================================================================================================
# Copyright 2013 Twitter, Inc.
# --------------------------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi... | python |
__author__ = 'Kalyan'
from placeholders import *
# For most of these tests use the interpreter to fill up the blanks.
# type(object) -> returns the object's type.
def test_numbers_types():
assert "int" == type(7).__name__
assert "float" == type(7.5).__name__
assert "long" == type(10L).__name__
... | python |
# This program 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 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,... | python |
# Copyright 2020 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | python |
# File to explore the difference between the error function relying on Hoeffding's bound and the one relying on the
# bound of Maurer and Pontil.
import os
import sys
import configparser
import numpy as np
directory = os.path.dirname(os.path.dirname(os.path.expanduser(__file__)))
sys.path.append(directory)
path_conf... | python |
import keras
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, ConvLSTM2D
from keras.layers import Activation, Dropout, Flatten, Dense, LeakyReLU
from keras.layers import LSTM, TimeDistributed, Lambda, BatchNormalization
from kera... | python |
# -*- coding: utf-8 -*-
from nseta.analytics.model import *
from nseta.common.history import historicaldata
from nseta.common.log import tracelog, default_logger
from nseta.plots.plots import *
from nseta.cli.inputs import *
from nseta.archives.archiver import *
import click
from datetime import datetime
__all__ = ['... | python |
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(('127.0.0.1', 50007))
s.listen(1)
while True:
conn, addr = s.accept()
with conn:
while True:
data = conn.recv(1024)
if not data:
break
... | python |
#!/usr/bin/python3
# -*- coding:utf-8 -*-
# ganben: MontyLemmatiser port of montylingua 2.1`
import re
# think about import
class MontyLemmatiser:
#
# original implt read `.mdf` file as db
# u obviously need a bigger db file
xtag_morph_zhcn_corpus = '' # add a real source
exceptions_source = '' ... | python |
import logging
from typing import List, Tuple, Dict
import psycopg2
from src.tools.utils import read_config
class Postgres:
def __init__(self, config: Dict = None):
self.connection = None
self.cursor = None
self.connect(config)
def connect(self, config: Dict = None) -> None:
... | python |
import os
from typing import Any, Dict, Literal
import wandb
from wicker.core.config import get_config
from wicker.core.definitions import DatasetID
from wicker.core.storage import S3PathFactory
def version_dataset(
dataset_name: str,
dataset_version: str,
entity: str,
metadata: Dict[str, Any],
... | python |
from .munger import * # noqa
from .munger_link_only import * # noqa | python |
#!/usr/bin/env python
# encoding: utf-8
"""
Test _extend_kb_with_fixed_labels from core
"""
import pyqms
import sys
import unittest
TESTS = [
# {
# 'in' : {
# 'params' : {
# 'molecules' : ['KLEINERTEST'],
# 'charges' : [2, ],
# 'fixed_labels' : ... | python |
'''
EXERCÍCIO 015: Aluguel de Carros
Escreva um programa que pergunte a quantidade de km percorridos por um carro alugado e a quantidade de dias pelos quais ele foi alugado. Calcule o preço a pagar, sabendo que o carro custa R$ 60 por dia e R$ 0,15 por km rodado.
Escreva um programa que pergunte a quantidade de km pe... | python |
#!/usr/bin/env python3
# coding: utf8
"""
Day 5: Alchemical Reduction part 2
https://adventofcode.com/2018/day/5
"""
from string import ascii_lowercase
def reactPolymer(polymer):
pats = []
pats += [c + c.upper() for c in ascii_lowercase]
pats += [c.upper() + c for c in ascii_lowercase]
reactedPolym... | python |
from pathlib import Path
import os
import random
import json
import itertools
import copy
import torch
from torch.utils.data import Dataset, DataLoader, BatchSampler, RandomSampler, \
SequentialSampler
from torchvision import transforms
import numpy as np
import cv2
import PIL
import scipy.io
import glob
from . ... | python |
from matplotlib import mlab
def SY_PeriodVital(x):
f1 = 1
f2 = 6
z = np.diff(x)
[F, t, p] = signal.spectrogram(z,fs = 60)
f = np.logical_and(F >= f1,F <= f2)
p = p[f]
F = F[f]
Pmean = np.mean(p)
Pmax = np.max(p)
ff = np.argmax(p)
if ff >= len(F):
Pf = np.nan
... | python |
# Copyright (c) 2022 PaddlePaddle 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 appli... | python |
import random
from collections import deque
from mesh.generic.nodeConfig import NodeConfig
from mesh.generic.formationClock import FormationClock
from mesh.generic.nodeState import NodeState, LinkStatus
from mesh.generic.cmdDict import CmdDict
class NodeParams():
def __init__(self, configFile=[], config=[]):
... | python |
"""
Reference :
https://github.com/mattalcock/blog/blob/master/2012/12/5/python-spell-checker.rst
"""
import re
import collections
class SpellCorrect:
def __init__(self,
text=None,
files=[],
initialize=True):
self.NWORDS = collections.defaultdict(lambda... | python |
ERROR_CODES = {
0: "EFW_SUCCESS",# = 0,
1: "EFW_ERROR_INVALID_INDEX",#,
3: "EFW_ERROR_INVALID_ID",#,
4: "EFW_ERROR_INVALID_VALUE",#,
5: "EFW_ERROR_REMOVED",#, //failed to find the filter wheel, maybe the filter wheel has been removed
6: "EFW_ERROR_MOVING",#,//filter wheel is moving
7: "EFW_E... | python |
from django.http import Http404
from django.shortcuts import render_to_response
from django.template import RequestContext
from seaserv import get_repo, is_passwd_set
from winguhub.utils import check_and_get_org_by_repo, check_and_get_org_by_group
def sys_staff_required(func):
"""
Decorator for views that che... | python |
from dataclasses import dataclass
@dataclass
class CheckpointCallback:
_target_: str = "pytorch_lightning.callbacks.ModelCheckpoint"
monitor: str = "loss/Validation"
save_top_k: int = 1
save_last: bool = True
mode: str = "min"
verbose: bool = False
dirpath: str = "./logs/checkpoints/" # u... | python |
import redis
from twisted.python import log
def open_redis(config):
global redis_pool, redis_info
host = config.get("redis", "host")
port = int(config.get("redis", "port"))
socket = config.get("redis", "socket")
redis_info = ( host, port, socket )
if socket != "":
redis_pool = redis.Co... | python |
#!/usr/bin/python
#
# Copyright 2010 Google 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 ag... | 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 the... | python |
def content_length_check(content, allow_short=False):
maxlen = 40000
if len(content)>maxlen:
raise Exception('content too long {}/{}'.format(len(content), maxlen))
if (len(content)<2 and allow_short==False) or len(content)==0:
raise Exception('content too short')
def title_length_check(titl... | python |
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 14 17:36:13 2019
@author: Mangifera
"""
import seaborn as sns
import pandas as pd
from scipy import stats
def is_it_random(filename):
with open(filename, "r") as text_file:
demon = text_file.read()
demon = [int(x) for x in demon.split('\n')]
... | python |
import warnings
warnings.filterwarnings('ignore')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, inspect
from sqlalchemy import func, desc
from matplotlib.t... | python |
import sys
import socket
import threading
class Server:
def __init__(self, hostname='localhost', port=8080):
self.host = hostname
self.port = port
self.clients = []
# crea un socket TCP
self.socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
... | python |
from Server.models.business.ListenThread import ListenThread
listenThread = ListenThread()
listenThread.main_execution()
| python |
'''
Description on how to produce metadata file.
'''
input_filter = None
treename = 'deepntuplizer/tree'
reweight_events = -1
reweight_bins = [list(range(200, 2051, 50)), [-10000, 10000]]
metadata_events = 1000000
selection = '''jet_tightId \
&& ( !label_H_cc )'''
# && ( (sample_isQCD && fj_isQCD) || (!sample_isQCD &&... | python |
from argparse import ArgumentTypeError
import numpy as np
from PIL import Image
from convolution_functions import apply_filter, filters
debug_mode = False
"""
Seznam pouzitelnych funkci pro tento program na upravu obrazku.
Pro pridani fuknce ji napiste zde, a pridejte do action_dict (seznam pouzitelnych fci)
a pot... | python |
"""Tests for the auth providers."""
| python |
# Generated by Django 2.2.1 on 2020-05-07 07:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('PropelRapp', '0009_auto_20200506_0627'),
]
operations = [
migrations.AddField(
model_name='menu',
name='is_deleted',... | python |
''' Text Media Matching interface '''
from summarization.text_media_matching.text_media_matching_helper import \
TextMediaMatchingHelper
from summarization.text_media_matching.text_media_matching_preprocessor import \
TextMediaMatchingPreprocessor # noqa
class TextMediaMatcher:
'''Class to integrate the... | python |
"""
# MIT LICENSE
#
# Copyright 1997 - 2020 by IXIA Keysight
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, mod... | python |
from module import foo, bar
from module import foo, \
bar, \
baz
from module import (foo, bar)
from module import (foo,
bar,
baz)
| python |
from jsonrpcserver.sentinels import Sentinel
def test_Sentinel():
assert repr(Sentinel("foo")) == "<foo>"
| python |
# Copyright (c) 2019, CRS4
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribu... | python |
from numpy import zeros
from sklearn.tree import _tree
def _interpret_tree(tree, X, n_labels):
# Tree preprocessing allowing down-top search
parents = [-1 for _ in range(tree.node_count)]
to_pursue = [0]
while len(to_pursue):
node_i = to_pursue.pop()
child_l = tree.... | python |
from behavioral.interpreter.logic.tokens.token_type import TokenType
class Token:
def __init__(self, token_type: TokenType, text: str) -> None:
self.type = token_type
self.text = text
def __repr__(self) -> str:
return f"Token '{self.type.name}' with value '{self.text}'"
| python |
import pytest
from .fixtures import *
@pytest.mark.parametrize(["num_partitions", "rows"], [(7, 30), (3, 125), (27, 36)])
def test_update_table(num_partitions, rows, store):
fixtures = UpdateFixtures(rows)
original_df = fixtures.make_df()
update_df = fixtures.generate_update_values()
partition_size =... | python |
"""Ghana specific form helpers."""
from django.forms.fields import Select
from .gh_regions import REGIONS
class GHRegionSelect(Select):
"""
A Select widget with option to select a region from
list of all regions of Ghana.
"""
def __init__(self, attrs=None):
super().__init__(attrs, choic... | python |
from django.conf import settings
def pytest_configure():
settings.configure(INSTALLED_APPS=["geoipdb_loader"])
| python |
import datetime
from typing import Any, Optional
from googleapiclient.discovery import build
from jarvis.plugins.auth.google_auth import GoogleAuth
from .config import GoogleCalendar
class GoogleCalendar:
def __init__(self, calendar_id: Optional[str] = None) -> None:
self.calendars: dict = GoogleCalendar.... | python |
import sys
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
# TODO: fix it
sys.path.append("./")
from calculus_of_variations import MultidimensionalSolver
from web_interface.utils import (
dash_multidimensional_answer,
dash_m... | python |
from datetime import date
from nose.tools import eq_
from nose.plugins.attrib import attr
from allmychanges.crawler import (
_filter_changelog_files,
_extract_version, _parse_item,
_extract_date)
from allmychanges.utils import get_markup_type, get_change_type
from allmychanges.downloaders.utils import norm... | python |
# coding=utf-8
__author__ = 'cheng.hu'
import logging
# 第一步,创建一个logger
logger = logging.getLogger()
logger.setLevel(logging.INFO) # Log等级总开关
# 第二步,创建一个handler,用于写入日志文件
logfile = '/Users/CalvinHu/Documents/python/hurnado/src/test/log.txt'
fh = logging.FileHandler(logfile, mode='w')
fh.setLevel(logging.INFO) # 输出到... | python |
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponse, HttpResponseBadRequest, JsonResponse
from django.shortcuts import render
# Create your views here.
from django.template.loader import render_to_string
from django.ur... | python |
# Copyright 2017 University of Maryland.
#
# This file is part of Sesame. It is subject to the license terms in the file
# LICENSE.rst found in the top-level directory of this distribution.
import numpy as np
from .observables import *
from .defects import defectsF
def getF(sys, v, efn, efp, veq):
###############... | python |
import tornado.web
import mallory
class HeartbeatHandler(tornado.web.RequestHandler):
def initialize(self, circuit_breaker):
self.circuit_breaker = circuit_breaker
@tornado.web.asynchronous
@tornado.gen.engine
def get(self):
if self.circuit_breaker.is_tripped():
self.set_st... | python |
from petroleum.conditional_task import ConditionalTask
from petroleum.exceptions import PetroleumException
from petroleum.task import Task
class ExclusiveChoice(Task):
def __init__(self, name=None, *args, **kwargs):
self._conditional_tasks = []
super().__init__(name=None, *args, **kwargs)
def... | python |
"""
AmberTools utilities.
"""
__author__ = "Steven Kearnes"
__copyright__ = "Copyright 2014, Stanford University"
__license__ = "BSD 3-clause"
from collections import OrderedDict
from cStringIO import StringIO
import numpy as np
import os
import shutil
import subprocess
import tempfile
from rdkit import Chem
from v... | python |
from matplotlib import pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
from scipy.interpolate import griddata
import copy
def visualize_source(
points,
values,
ax=None,
enlarge_factor=1.1,
npixels=100,
cmap='jet',
):
"""
Points is defined as a... | python |
# -*- coding: utf-8 -*-
__author__ = 'S.I. Mimilakis'
__copyright__ = 'MacSeNet'
import torch
import torch.nn as nn
from torch.autograd import Variable
class SkipFiltering(nn.Module):
def __init__(self, N, l_dim):
"""
Constructing blocks of the skip filtering connections.
Reference: - ht... | python |
# __init__.py
import logging
import os
from task_manager.views import (
HomeView,
ErrorView,
InfoView,
LoginView,
LogoutView,
ProfileView,
RegistrationView,
TaskListView,
TaskView
)
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.options impo... | python |
from dnaweaver import (
CommercialDnaOffer,
DnaAssemblyStation,
GibsonAssemblyMethod,
OligoAssemblyMethod,
TmSegmentSelector,
FixedSizeSegmentSelector,
PerBasepairPricing,
SequenceLengthConstraint,
)
# OLIGO COMPANY
oligo_com = CommercialDnaOffer(
name="Oligo vendor",
sequence_... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.