content stringlengths 5 1.05M |
|---|
import os
import platform
import re
import sys
import tempfile
import shutil
from copy import copy
from conans import tools
from cpt.packager import ConanMultiPackager,load_cf_class
def loadScheme_(name):
CONANOS_SCHEME_REPO = os.environ.get('CONANOS_SCHEME_REPO')
if not CONANOS_SCHEME_REPO:
... |
# Lint as: python3
# 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 agr... |
from __future__ import print_function, division, absolute_import, unicode_literals
from builtins import bytes, dict, object, range, map, input, str
from future.utils import itervalues, viewitems, iteritems, listvalues, listitems
from io import open
import pickle
import os
from copy import deepcopy
import numpy as np
f... |
"""
ASGI config for djangoProject project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
asgi_application = get_asgi_ap... |
"""The Intent integration."""
import voluptuous as vol
from homeassistant.components import http
from homeassistant.components.http.data_validator import RequestDataValidator
from homeassistant.const import SERVICE_TOGGLE, SERVICE_TURN_OFF, SERVICE_TURN_ON
from homeassistant.core import DOMAIN as HA_DOMAIN, HomeAssist... |
class Groups:
id = 0
name = ""
members = []
def serialize(self):
return f'[{self.id},${self.name},${self.members}]'
def serialize_normal(self):
return f'[{self.id},{self.name},{self.members}]'
|
#!/usr/bin/env python3
from test_definition_base import CommonTestTraits
from test_definition_base import TestParamsProviderBase
import utils
class TestTraits (CommonTestTraits):
@property
def operator_ir_type_string(self):
return 'ConvolutionBackpropData'
@property
def test_params_provider_... |
# -*- coding: utf-8 -*-
"""Supports SuperMAG ground magnetometer measurements and SML/SMU indices.
Downloading is supported; please follow their rules of the road:
http://supermag.jhuapl.edu/info/?page=rulesoftheroad
Parameters
----------
platform : string
'supermag'
name : string
'magnetometer'
tag : stri... |
import unittest
from pprint import pprint
from rdflib import Graph, Namespace
from pyshex import ShExEvaluator
rdf = """
@prefix : <http://example.org/model/> .
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schem... |
from typing import Optional
from fastapi import FastAPI
from sqlmodel import (
SQLModel,
Field,
create_engine,
select,
Session
)
# Criar engine do banco
engine = create_engine('sqlite:///database.db')
class Pessoa(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True... |
import proxy
import json
import re
class Web1C(proxy.HttpSniffer):
folder = '/data'
def on_post_request_buh3_ru_RU_e1cib_logForm(self, _request, request):
data = self.escape_res(_request['data'].decode())
data = json.loads(data, encoding='utf-8')
try:
if data['root']['key... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import redis
from utils.get_configure import get_conf
_logger = logging.getLogger(__name__)
def get_redis_conf():
namespace = "redis"
REDIS_DB = get_conf("REDIS_DB", namespace=namespace)
REDIS_HOST = get_conf("REDIS_HOST", namespace=namespa... |
# ex: set sts=4 ts=4 sw=4 noet:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the reproman package for the
# copyright and license terms.
#
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
import datetime
i... |
"""
Defines overloaded operators for basic mathematical operations over unit-containing members (Constant, Parameter, Variables)
"""
class ExposedVariableError(Exception):
"""
Error raised by the utilization of non-exposed variables for connection of two Model objects.
"""
def __init__(self, model_1_... |
import io
from zipfile import ZipFile
import pandas as pd
import pytest
from sqlalchemy import delete
from athenian.api.models.state.models import UserAccount
from athenian.api.models.web import ContributorIdentity, MatchedIdentity, PullRequestMetricID
from athenian.api.serialization import FriendlyJson
async def t... |
import time
import psycopg2
from neo4j import GraphDatabase
from redis import Redis
from timeout_decorator import timeout
from common.log import logger
from config import cfg
def wait_for_external_services(
wait_for_pg: bool = True,
wait_for_neo4j: bool = True,
wait_for_pubsub: bool = True,
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('section', '0004_aboutsection'),
]
operations = [
migrations.CreateModel(
name='Catalog',
fields=[
... |
import os
import numpy as np
import processor
import paddlehub as hub
import paddle
import paddle.fluid as fluid
from mobilenet_ssd import mobile_net
def build_program():
image_shape = [3, 300, 300]
class_num = 21
image = fluid.layers.data(dtype="float32", shape=image_shape, name="image")
gt_box = flu... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Lint as: python3
"""Moses detokenizer.
Moses detokenizer
"""
from __future__ import print_function
import re
import unicodedata
import six
OUTPUT = ('third_party/tensorflow_models/mlperf/models'
'/rough/nmt/testdata/deen_output')
def is_currency(token):
... |
import apache_beam as beam
import logging
from joblib import load
import numpy as np
import pandas as pd
from google.cloud import storage
from apache_beam.options.pipeline_options import StandardOptions, GoogleCloudOptions, SetupOptions, PipelineOptions
from sklearn.ensemble import RandomForestClassifier
#setup glob... |
with open("input1.txt","r") as f:
l=[(int(line)//3)-2 for line in f.readlines()]
print(sum(l))
|
## Nov 2018: Plotting map of MEaSUREs outlets over satellite imagery
## Apr 2019 edit: Visualise hindcast validation, e.g. total retreat and misfit with observation
## EHU
from mpl_toolkits.basemap import Basemap
import mpl_toolkits.basemap.pyproj as pyproj
import numpy as np
import matplotlib.pyplot as plt
import sha... |
# Copyright (c) 2008,2015,2017 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Test the `kinematics` module."""
import numpy as np
import pytest
from metpy.calc import (advection, convergence_vorticity, divergence,
frontog... |
import pybem2d.core.bases as pcb
import pybem2d.core.segments as pcs
import pybem2d.core.quadrules as pcq
import pybem2d.core.kernels as pck
import pybem2d.core.mesh as pcm
import pybem2d.core.assembly as pca
import pybem2d.core.evaluation as pce
import pybem2d.core.visualization as pcv
import numpy as np
k=20
nelem... |
import uuid
import sqlalchemy
from web import db
def new_uuid():
return str(uuid.uuid4()).lower()
def new_double_uuid():
return u"{}-{}".format(uuid.uuid4(), uuid.uuid4()).lower()
class RecipientTypes(object):
campaign = 0
character = 1
chat = 2
class MessageTypes(object):
action = 0
... |
# %%
import torch
import matplotlib.pyplot as plt
from qmc.mcmc import metropolis_symmetric, clip_mvnormal_proposal
from qmc.wavefunction import HarmonicTrialFunction
# %%
d=3
tf = HarmonicTrialFunction(torch.ones(1))
#
n_walkers=10
init_config = torch.rand(n_walkers,1)
results = metropolis_symmetric(tf... |
"""
cylinder module.
cylinder follows radiance structure
mod cylinder name
0
0
4 x1 y1 z1 r1 x2 y2 z2 r2
"""
class Cylinder(object):
"""
Cylinder class.
"""
def __init__(self):
pass |
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: a binary search tree
@return: Root of a tree
"""
def increasingBST(self, root):
# Write your code here.
St ... |
from django.apps import AppConfig
class AjaxConnConfig(AppConfig):
name = 'ajax_conn'
|
import findCourses
import getTime
import sendMail
import isHomework
import os
def sendHomework(info, args):
tmp = findCourses.findCourses() # Ders ismini ve linkini aliyor
names = tmp[0]
links = tmp[1]
argss = ""
for i in range(len(args)):
argss += args[i] + " "
if len(names) == 0 or ... |
import torch
from torchvision import transforms
from PIL import Image
from .resnest_model import resnest50
model = resnest50(pretrained=True)
model.eval()
preproc_transform = transforms.Compose([
transforms.Resize((448,448)), # TODO is this really 448 or 224 as said in docs?
transforms.ToTensor(),
transf... |
# imports
from PIL import ImageFont, ImageDraw, Image
import cv2
import numpy as np
import imutils
# typically we'll import modularly
try:
from .annotation import Annotation
unit_test = False
# otherwise, we're running main test code at the bottom of this script
except:
import sys
import os
sys.pa... |
#!/usr/bin/env python
#
# Copyright 2018 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 ... |
#!/usr/bin/env python
# Copyright (c) 2015, Ecole Polytechnique Federale de Lausanne, Blue Brain Project
# All rights reserved.
#
# This file is part of NeuroM <https://github.com/BlueBrain/NeuroM>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the fo... |
import os.path as path
import re
import os
import random
import pickle
import warnings
import torchtext
import torch
import spacy
import numpy as np
from ._choose_tokenizer import choose_tokenizer
from ._vocab_tokenizer import VocabTokenizer
from ._single_sequence_dataset import SingleSequenceDataset
class SSTToken... |
#! /usr/bin/env python
"""
Various stat functions.
"""
from __future__ import division, print_function
__author__ = 'C. Gomez @ ULg'
__all__ = ['descriptive_stats']
import numpy as np
from matplotlib.pyplot import boxplot
def descriptive_stats(array, verbose=True, label='', mean=False, plot=False):
""" Simple... |
from __future__ import print_function
from lldbsuite.test import lldbtest
from lldbsuite.test import decorators
class NonExistentDecoratorTestCase(lldbtest.TestBase):
mydir = lldbtest.TestBase.compute_mydir(__file__)
@decorators.nonExistentDecorator(bugnumber="yt/1300")
def test(self):
"""Verify... |
""" Constants for qmotion module
"""
# Long default, qsync can be slow. Can be overriden during initialization
DEFAULT_TIMEOUT = 20
TCP_PORT = 9760
UDP_PORT = 9720
BROADCAST_ADDRESS = "255.255.255.255"
|
# -*- coding: utf-8 -*-
from pyxb.bundles.reqif.raw._xh11d import *
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Static file API endpoint.
Used for storing data such as img files.
Nothing in the static directory will be treated as a template,
just (potentially) cacheable data that needs to be served to clients.
"""
from flask import send_from_directory
from flask_restx import Na... |
class Solution(object):
def isPerfectSquare(self, num):
return int(num ** 0.5) ** 2 == num
|
## script to generate the graphics in figure 3 of koven et al. paper
## written by c. koven
## dependent on several libraries: PyNgl, python-netCDF4, numpy, rpy2, and my personal plotting library, which is here: https://github.com/ckoven/ckplotlib
import numpy as np
import map_funcs
import netCDF4 as nc
import rpy2.ro... |
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if len(matrix) == 0:
return False
row = 0
col = len(matrix[0]) - 1
while row ... |
import os, sys
def get_path():
return os.path.dirname(os.path.abspath(root))
def start():
print "start()"
print "current path =", get_path()
|
# -*- coding: utf-8 -*-
from nlplib.base import language_langid
def test_language_langid():
assert(language_langid(None) is None)
assert(language_langid(u'Happy face') == 'en')
assert (language_langid(u'Elle est contente') == 'fr')
|
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
# Author: Bryan G
|
#!/usr/bin/env python3
import json
import logging
import pprint
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning, SNIMissingWarning, InsecurePlatformWarning
from . import site
class UniFiException(Exception):
apimsg = None
def __init__(self, apimsg, s=None):
m ... |
from cmath import sqrt
def main():
x = int(input("Введите x: "))
z1 = x ** 2 + 2 * x - 3 + (x + 1) * sqrt((x ** 2) - 9)
z2 = sqrt((x + 3) / (x - 3))
return f"Формула z1: {z1}\nФормула z2: {z2}"
if __name__ == '__main__':
print(main())
|
from ..s3 import GetFile, UploadFromContent
def CheckIn(body):
local_ip = body['local_ip']
public_ip = body['public_ip']
moniker = body['moniker']
node_type = body['type']
if node_type == 'sentry':
# TODO: Get file (if file doesn't exist, it's ok). Then json.loads it
# Payload sho... |
"""
Version 0.1
Soft Robot Controller UI
Author: YingGwan
Function: A tool to conveniently adjust airbag pressure
"""
import sys
from PyQt5 import QtCore, QtGui, QtWidgets,Qt
import qdarkstyle
from NEWUI import Ui_MainWindow
from thread1 import Thread1
class CtrlWindow(QtWidgets.QMainWindow):
def __... |
import numpy as np
import MDAnalysis as mda
# All these functions for virtual sites definitions are explained
# in the GROMACS manual part 5.5.7 (page 379 in manual version 2020)
# Check also the bonded potentials table best viewed here:
# http://manual.gromacs.org/documentation/2020/reference-manual/topologies/topol... |
# Copyright (C) 2013 Matthew C. Zwier, Nick Rego, and Lillian T. Chong
#
# This file is part of WESTPA.
#
# WESTPA is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your... |
# Copyright (c) 2017, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
from mixbox import fields
import cybox.bindings.unix_user_account_object as unix_user_account_binding
from cybox.common import String, NonNegativeInteger, UnsignedInteger
from cybox.objects.user_account_object impo... |
from . import LinAlg as A
from. import Set as S
class Relation:
def __init__(self, r_dict):
self.left = set(r_dict.keys())
self.right = S.Set.union(*(r_dict[x] \
for x in r_dict.keys()))
self.table_map_left = dict(zip(self.left, \
... |
from setuptools import setup
with open("README.rst", "r") as fh:
long_description = fh.read()
with open("pywavez/__version__.py", "r") as fh:
versiondict = {"__builtins__": {}}
exec(fh.read(), versiondict)
version = versiondict["version"]
setup(
name="pywavez",
version=version,
descriptio... |
#!/usr/bin/env python3
import collections
import lxml.etree
import datetime
import slixmpp
import asyncio
import logging
import signal
import atexit
import time
import sys
import io
import os
from functools import partial
from slixmpp.xmlstream.matcher.base import MatcherBase
if not hasattr(asyncio, "ensure_future"):... |
#
# To start the service:
# python manage.py runserver
#
from app import app
from flask_script import Manager
manager = Manager(app)
@manager.command
def test():
"""Run unit tests."""
pass
if __name__ == '__main__':
manager.add_command("runserver",server)
manager.run()
|
#MenuTitle: New Tab with Glyphs Exceeding Zones
# -*- coding: utf-8 -*-
from __future__ import division, print_function, unicode_literals
from builtins import str
__doc__="""
Opens a new tab with all glyphs where the extremums do not lie within zones.
"""
thisFont = Glyphs.font # frontmost font
thisFontMaster = thisFo... |
import unittest
import string
# from typing import List
class Solution:
def validIPAddress(self, IP: str) -> str:
if IP is None:
return "Neither"
if "." in IP:
return self.validIP4Adress(IP)
elif ":" in IP:
return self.validIP6Adress(IP)
return ... |
import sampling_methods
import numpy as np
__all__ = ['Supervised', 'ActiveLearning']
class _Trainer():
def __init__(self, name, epoch, batch_size):
self.name = name
self.epoch = epoch
self.batch_size = batch_size
assert (type(epoch) is int and epoch > 0)
... |
import re
from treelib import Node, Tree
def read():
with open("input.txt", "r") as f:
return [i.strip() for i in f.readlines()]
data = read()
# fun
#parse
def parse(s: str):
reg = re.findall(r"\D+bag", s)
return set(i.rstrip("bag").rstrip().lstrip() for i in reg)
def partita(s: str):
[index... |
# Modern Robotics Descriptions for all eight Interbotix Arms.
# Note that the end-effector is positioned at '/ee_arm_link'
# and that the Space frame is positioned at '/base_link'.
import numpy as np
class px100:
Slist = np.array([[0.0, 0.0, 1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, -0.09305, 0.0... |
import pygame
import random
import numpy as np
from time import sleep
def out_of_bounds(tet, x, y):
return(x >= Tetris.width or y >= Tetris.height or x < 0 or y < 0)
class Tetromino:
tetrominos = {
1: { # I
0: [(0,1), (1,1), (2,1), (3,1)],
1: [(2,0), (2,1), (2,2), (2,3)],
... |
#!d:\app\python27\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'phply==1.0.0','console_scripts','phplex'
__requires__ = 'phply==1.0.0'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
... |
import env
import cv2
import imutils
import os
import PyAutoMakerHuman as pamh
hand = pamh.HandUtil()
cap = cv2.VideoCapture(0)
try:
while cap.isOpened():
success, frame = cap.read()
if not success:
continue
frame = cv2.flip(frame, 1)
result = hand.detect(frame)
... |
def squared_sum(n):
a = (n * (2 * n + 1) * (n + 1))/6
return int(a)
def sum_squared(n):
a =(n * (n + 1 ))/2
a = pow(a, 2)
return int(a)
n1 = squared_sum(100)
n2 = sum_squared(100)
print(n2 - n1) |
# Copyright 2020 MONAI Consortium
# 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, s... |
while True:
try:
n = int(input())
if n < 90 or n == 360: print('Bom Dia!!')
elif n < 180: print('Boa Tarde!!')
elif n < 270: print('Boa Noite!!')
else: print('De Madrugada!!')
except EOFError: break
|
import librosa
from nlpaug.model.audio import Audio
"""
Reference: https://www.kaggle.com/CVxTz/audio-data-augmentation
A wrapper of librosa.effects.pitch_shift
"""
class Pitch(Audio):
def __init__(self, sampling_rate, pitch_factor):
super(Pitch, self).__init__()
self.sampling_rate = sam... |
def no_valid_function():
"""
This is a test function for load_function in util.py.
load_function expects a file some_name.py to contain a function called some_name.
This file has a function with a different name to the filename, and this is used in
test_util.py to verify this case is handled correc... |
X_test_num_imputed = X_test_num.fillna(X_train_num.mean())
model.score(X_test_num_imputed, y_test)
|
'''
水仙花数
水仙花数是指一个 3 位数,它的每个位上的数字的 3次幂之和等于它本身(例如:1^3 + 5^3+ 3^3 = 153)
'''
import math
def is_armstrong_num(num):
g = num % 10
s = (num-g) // 10 % 10
b = num // 100
return math.pow(g, 3)+math.pow(s, 3)+math.pow(b, 3) == num
# res = is_armstrong_num(153)
# print(res)
'''
完全数
它所有的真因子(即除了自身以外的约... |
def fib(n):
f = [0, 1]
for i in xrange(2, n + 1):
f.append(f[-1] + f[-2])
return f[n]
for i in xrange(1, 12):
print fib(i)
|
# pylint: disable=invalid-name
import unittest
from test.constants import BUILTIN_TYPE_TUPLES, VALID_USER_TYPE_NAMES, INVALID_USER_TYPE_NAMES
from test.ParserTestUtils import SingleLineParserTestUtils, ParserFactoryTestUtils
from catparser.AliasParser import AliasParserFactory
class AliasParserFactoryTest(unittest.Te... |
from pytest import approx
def test_my_good_example_test():
assert 1 == 1
def test_my_bad_example_test():
assert 1 == 2
|
__author__ = 'sandeep'
class Error(Exception):
""" Generic Error for client """
pass
class ValidationError(Error):
""" Error in case of invalid input """
pass
class HTTPError(Error):
""" Error Response from API """
pass
|
import logging
import os
import uuid
from datetime import datetime
from typing import Optional, List
import aiofiles
from pydantic import BaseModel
from tinydb import TinyDB, Query
from app.library import configuration, conversions
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
class... |
# -*- coding: utf-8 -*-
"""
smallparts.markup.generators
Markup (HTML, XML) generation
"""
from smallparts import constants
from smallparts.markup import elements
from smallparts.namespaces import Namespace
from smallparts.text import join
#
# Constants
#
SUPPORTED_HTML_DIALECTS = {
elements.LABEL_HTML_5... |
import os
from consolemenu import selection_menu, console_menu
from consolemenu.format.menu_borders import MenuBorderStyleType
from consolemenu.items import function_item, submenu_item
from consolemenu.menu_formatter import MenuFormatBuilder
from infra.domain.fileSaver import FileSaver
from infra.domain.consts import g... |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import json
import argparse
from vqa_eval.vqaTools.vqa import VQA
from vqa_eval.vqaEval import VQAEval
def accuracy(taskType, dataType, dataSubType, resFile, dataDir, resultDir):
annFile = "%s/v2_%s_%s_ann... |
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
self.parent = None
def __str__(self):
return str(self.data)
def __iter__(self):
if self.left:
for node in self.left:
yield node
yie... |
from django.db import models
#import uuid
# Create your models here.
class quiz(models.Model):
contest_id=models.UUIDField(default=None)
#question_id=models.AutoField
question=models.TextField(max_length=300,default=None)
option_1=models.CharField(max_length=100,default=None)
option_2=models... |
# pylint: disable=no-self-use,invalid-name
from allennlp.data.dataset_readers import SequenceTaggingDatasetReader
from allennlp.common.testing import AllenNlpTestCase
class TestSequenceTaggingDatasetReader(AllenNlpTestCase):
def test_default_format(self):
reader = SequenceTaggingDatasetReader()
da... |
# -*- coding: utf-8 -*-
"""
.. codeauthor:: Fabian Sesterhenn <[email protected]>
.. affiliation::
Laboratory of Protein Design and Immunoengineering <lpdi.epfl.ch>
Bruno Correia <[email protected]>
.. func:: translate_dna_sequence
.. func:: translate_3frames
.. func:: adapt_length
.. func:: seq... |
from typing import Optional, Union
from .basic_ast import Ast
from .errors import ParseError, SyntaxError
from .node import create_binary_node
from .node import create_unary_node
from .node import Node
from .token import Token
class op:
AND = "AND" # noqa: E221
NOT = "NOT" # noqa: E221
OR = "OR" # noq... |
"""Implementation of ceQTL-tools addtfgenes"""
from pathlib import Path
from bioprocs.utils.tsvio2 import TsvReader, TsvWriter
from bioprocs.utils import logger
def read_tfgenes(tgfile):
"""Read tf-gene pairs"""
logger.info('Reading TF-gene pairs in %s ...', tgfile)
reader = TsvReader(tgfile, cnames=False)... |
"""Handles database interaction."""
import logging
from flask import current_app
import pymongo
from pymongo.collation import Collation, CollationStrength
from pymongo.errors import PyMongoError
from api import PicoException
log = logging.getLogger(__name__)
__connection = None
__client = None
def get_conn():
... |
from django.core.exceptions import ValidationError
class Plugin(object):
verbose_name = None
# Used on select plugin view
class_verbose_name = None
icon = None
change_form = None
form = None
serializer = None
change_readonly_fields = ()
plugin_field = None
def __init__(sel... |
#!/usr/bin/env python
def concInts(x, y):
return x*10+y
def ResistorCheck():
userInput = raw_input("Option 1.) Print all potential resistor band colors.\n Option 2.) Proceed to ResitorCheck program.\n Type 1 or 2 to proceed: ")
if(userInput.lower() == "1"):
print("All potential... |
class SolutionOfDynamicPlanning:
# ~~~~~爬楼梯~~~~~
# Link: https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xn854d/
# Hint: 斐波那契数列 第n项通项公式
def ClimbStairs1(n = 3) -> int:
if (n == 1):
return 1
elif (n == 2):
return 2
else:
retu... |
# Copyright (c) 2016 Intel, 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... |
import discord
from discord.ext import commands
class Roles(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command(brief='Have Nic write the role selector message')
@commands.has_permissions(administrator=True)
async def roles(self, context):
not_pinned = l... |
from flask import Flask, request, send_file, redirect, render_template
from pymongo import MongoClient
from uuid import uuid4
from qrcode import make as create_qr
from io import BytesIO
from PIL.Image import open, Image
from PIL import ImageDraw, ImageFont
from os import environ as env
app = Flask(__name__)
mongo = Mo... |
#For 18 points, read this and answer the questions.
#Lists (also known as arrays) are for groups of related values.
#If you have ever been tempted to name your variables like the
#following, what you really needed was a list:
var1 = 'sword'
var2 = 'shield'
var3 = 'armor'
var4 = 'boots'
var5 = 'helmet'
#Creating li... |
"""Contains configuration parameters for the dashboards."""
DASH_STYLE = {
"backgroundColor": '#212121',
"textAlign": "center",
"color": "#C9D6DF" # font
}
PLOT_TEMPLATE = 'plotly_dark'
|
# ------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
# -------------------------------------------------------------------... |
import sys
sys.path.append('../')
from util import parameter_number
from sklearn.metrics import accuracy_score
import torch
import torch.optim as optim
import torch.nn as nn
class Manager():
def __init__(self, model, args):
self.args_info = args.__str__()
self.device = torch.device('cuda:{}'.format... |
import sys
if sys.version_info < (3, 6):
raise RuntimeError("This library requires python 3.6+.")
__version__ = '0.3.0.dev0'
# auto-import submodules
from . import colors as colors
from . import data as data
from . import plot as plot
#
# populate common APIs
from .data import Experiment as Experiment
from .data i... |
import re
from synthesis_classifier.multiprocessing_classifier import perform_collection, make_batch
from synthesis_classifier.database.patents import PatentsDBWriter, PatentParagraphsByQuery
def example_paragraphs():
query = {
'path': re.compile(r'.*example.*', re.IGNORECASE),
}
return PatentPa... |
'''
Create Triqler input files by converting the evidence.txt output file from
MaxQuant.
'''
from __future__ import print_function
import sys
import os
import collections
import numpy as np
from .. import parsers
from ..triqler import __version__, __copyright__
from . import helpers
def main():
print('Triqler.co... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.