content stringlengths 5 1.05M |
|---|
import pandas as pd
from echelon import EchelonBT
from test_echelon import TestApp
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings("ignore")
data_master = pd.read_pickle('master_pricing_df')
stock_list = ['AAPL', 'GOOGL', 'GE', 'LUV']
app_goog = data_ma... |
import tools.hal2doc
import tools.search |
'''
Description:
Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1.
A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)) to the bottom-right cell (i.e., (n - 1, n - 1)) such that:
All the visited cells of th... |
# -*- coding: utf-8 -*-
__version__ = '0.3.0'
import threading
import os
import logging
# logging.basicConfig(level=logging.ERROR)
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)
class PinState(object):
"""An ultra simple pin-state object.
Keeps track data related ... |
import hashlib
import json
from django.contrib.gis.db import models
from bims.models.location_site import (
location_site_post_save_handler,
LocationSite
)
from bims.models.spatial_scale import SpatialScale
from bims.models.spatial_scale_group import SpatialScaleGroup
from bims.utils.logger import log
def arr... |
import IsoSpecPy
from tqdm import tqdm
t = 0.0
for x in tqdm(xrange(100000)):
i = IsoSpecPy.Iso("C100H100N100O100")
t += i.getTheoreticalAverageMass()
print t
|
import enum
from flask import session, url_for, redirect
import re
import datetime
def loggedIn():
return session.get("loggedIn", False)
def notLoggedInRedir():
if not loggedIn():
print("notLoggedIn")
return redirect(url_for("site_login"))
else:
print("loggedIn")
return Tru... |
"""How to print readable statistics."""
import pprint
from dd import cudd
import humanize
def main():
b = cudd.BDD()
b.declare('x', 'y', 'z')
u = b.add_expr('x & y & z')
u = b.add_expr('x | y | ~ z')
stats = b.statistics()
pprint.pprint(format_dict(stats))
def format_dict(d):
"""Return ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2018-01-31 07:58
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hkm', '0033_add_product_order_collection_hash'),
]
operations = [
migration... |
import requests
import datetime
import logging
import re
token = { "bearer": None, "expiration": None }
credentials = { "client_id": None, "username": None, "password": None, "tenant_id": None, "client_secret": None }
log = logging.getLogger()
console = logging.StreamHandler()
console.setFormatter(logging.Formatter("... |
import logging
from margaritashotgun.client import Client
__author__ = 'Joel Ferrier'
__version__ = '0.2.0'
def set_stream_logger(name='margaritashotgun', level=logging.INFO,
format_string=None):
"""
Add a stream handler for the provided name and level to the logging module.
>>... |
import AST as Tree
from TopCompiler import Types
from TopCompiler import Parser
from TopCompiler import Error
from TopCompiler import VarParser
from TopCompiler import Scope
from TopCompiler import ExprParser
import collections as coll
from TopCompiler import Struct
def parseLens(parser):
#parser.nextToken()
... |
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ValidationError
import re
class ContactForm(forms.Form):
def clean_phone(self):
phone = self.cleaned_data.get('phone')
phone_return = ''
for letter in phone:
if l... |
import torch, os
from model.model import parsingNet
from utils.common import merge_config
from utils.dist_utils import dist_print
from evaluation.eval_wrapper import eval_lane
import yaml
import argparse
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--params", type=str, default='conf... |
'''
@lanhuage: python
@Descripttion: Deprecated. Just for test.
@version: beta
@Author: xiaoshuyui
@Date: 2020-06-12 10:21:59
LastEditors: xiaoshuyui
LastEditTime: 2020-10-20 09:44:02
'''
import sys
sys.path.append("..")
from convertmask.utils.methods import getMultiShapes
if __name__ == "__main__":
getMultiShape... |
from setuptools import setup
setup(
name='ez_yaml',
version='1.1.0',
description="Straighforward wrapper around Ruamel Yaml",
url='https://github.com/jeff-hykin/ez_yaml',
author='Jeff Hykin',
author_email='[email protected]',
license='MIT',
packages=['ez_yaml'],
install_requires=... |
# -*- coding: UTF-8 -*-
from __future__ import print_function
class Fibonacci(object):
def __init__(self):
self.a = 0
self.b = 1
def fib_iterative(self, n):
self.a = 0
self.b = 1
for _ in range(n):
self.a, self.b = self.b, self.a + self.b
return sel... |
# ~/models/synapses/PCDCNnMFDCN2015aSudhakar/__init__.py
|
"""
Example 3. Optimizing textures.
"""
import argparse
import glob
import os
import subprocess
import cv2
import numpy as np
import torch
import tqdm
import neural_renderer_torch as neural_renderer
class Model(torch.nn.Module):
def __init__(self, filename_obj, filename_ref):
super(Model, self).__init__... |
# Generated by Django 4.0.1 on 2022-02-13 12:50
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
from ..helpers import IFPTestCase
from intficpy.thing_base import Thing
class TestDoff(IFPTestCase):
def test_doff_player_not_wearing_gives_player_not_wearing_message(self):
item = Thing(self.game, "item")
item.moveTo(self.start_room)
self.game.turnMain("doff item")
self.assertIn(... |
import concurrent.futures as future
import time
import numpy as np
n=10
def f(x):
time.sleep(0.2)
return x*x
if __name__ == '__main__':
print('**************************')
print('******no paraellel********')
start=time.time()
for i in range(n):
print( 'no paraellel'+str(f(i)) )
... |
from django.contrib import admin
from .models import ModelResult
class ModelResultAdmin(admin.ModelAdmin):
list_display = (
"name",
"owner",
"benchmark",
"model",
"dataset",
"results",
"metadata",
"approval_status",
"approved_at",
"cr... |
# -*- coding: UTF-8 -*-
# Copyright 2017 Luc Saffre
# License: BSD (see file COPYING for details)
# $ python setup.py test -s tests.PackagesTests.test_packages
SETUP_INFO = dict(
name='lino-vilma',
version='18.8.0',
install_requires=['lino_noi'],
# tests_require=['pytest', 'mock'],
test_suite='tes... |
"""
Various job content handler classes, grouped by the content's MIME type
"""
import typing
import urllib.parse
import bs4
from . import helper as _helper
class BaseContentHandler:
"""
Base class for all variants of content handler classes
A subclass should implement the ``analyze`` class method whi... |
CUSTOM_HEADER = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36"
}
|
import air_instance
|
lower_ci = xbar - me
upper_ci = xbar + me
(print("We are {}% confident that the true weight of chicken is between {} and {} grams.".
format((1-alpha)*100, lower_ci, upper_ci))) |
# -*- coding: utf-8 -*-
from odoo import models, fields, api, _
import odoo.addons.decimal_precision as dp
from odoo.tools import float_is_zero, float_compare, DEFAULT_SERVER_DATETIME_FORMAT
class SupportInvoiceLine(models.Model):
_name = "support.invoice.line"
product_id = fields.Many2one(
'prod... |
"""
Data Loader and Feature Dictionary classes for InterpRecSys
NOTE: some code borrowed from here
https://github.com/princewen/tensorflow_practice/blob/master/recommendation/Basic-DeepFM-model/data_reader.py
@Author: Zeyu Li <[email protected]> or <[email protected]>
"""
import pandas as pd
from const import Co... |
# Generated by Django 2.2.5 on 2019-10-28 07:01
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('sema', '0034_semaproduct_pies_c10_des'),
]
operations = [
migrations.RemoveField(
model_name='semaproduct',
name='pies_c10_e... |
import os
import pytest
import requests_mock
from arcus import Client
@pytest.fixture
def client():
yield Client(sandbox=True)
@pytest.fixture
def client_proxy():
proxy = os.environ['ARCUS_PROXY']
with requests_mock.mock() as m:
m.get(
f'{proxy}/account',
json=dict(
... |
from .AST.sentence import Delete
from .AST.expression import Relational, Logical
from .executeExpression import executeExpression
from storageManager.TypeChecker_Manager import *
from .storageManager.jsonMode import *
from .AST.error import *
import sys
sys.path.append("../")
from console import print_error, print_suc... |
import time
from siemens.pac import PACx200
times = []
p = PACx200('192.168.0.80')
while True:
try:
p.read()
print(p.as_dict(replace_nan=True))
except:
break
time.sleep(1)
|
# from django.contrib import admin
# from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register
# from .models import JoinData
# class JoinDataAdmin(ModelAdmin):
# model = JoinData
# menu_label = '報名資料' # ditch this to use verbose_name_plural from model
# menu_icon = 'form' # change ... |
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import re
plt.rcParams['pdf.fonttype'] = 42
from utility import *
DATASET_LIST = ['wikivot', 'referendum', 'slashdot', 'wikicon'] + ['p2pgnutella31', 'youtube', 'roadnetCA', 'fb-artist']
Density = {'p2pgnutella31':2.3630204838142714, 'youtube':2.... |
# -*- coding:utf-8 -*-
# -*- created by: yongzhuo -*-
import requests
from lxml import etree
import pickle
import time
import datetime
'''注意: Cookie需要自己加'''
Cookie = '******注意: Cookie需要自己加'
def txtRead(filePath, encodeType='utf-8'):
'''读取txt文件'''
listLine = []
try:
file = ... |
# -*- coding: utf-8 -*-
from urllib import request
proxy_handler = request.ProxyHandler({'http': '10.144.1.10:8080'})
# proxy_auth_handler = request.ProxyBasicAuthHandler()
# proxy_auth_handler.add_password('realm', 'host', 'username', 'password')
opener = request.build_opener(proxy_handler)
with opener.open('http://w... |
# Enlil
#
# Copyright © 2021 Pedro Pereira, Rafael Arrais
#
# 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... |
import numpy as np
import sys
import logging
import pickle
import matplotlib.pyplot as plt
from pathlib import Path
from scipy.optimize import minimize_scalar
from itertools import product
import ray
import pandas as pd
import click
from neslab.find import distributions as dists
from neslab.find import Model
logger ... |
import numpy
import ctypes
def find_dyn_parm_deps(dof, parm_num, regressor_func):
'''
Find dynamic parameter dependencies (i.e., regressor column dependencies).
'''
samples = 10000
round = 10
pi = numpy.pi
Z = numpy.zeros((dof * samples, parm_num))
for i in range(samples):
... |
import unittest
import random
import Spy.SpyStreamHelper as StreamHelper
import Spy.SpyInst as SpyInst
from Spy.SpyStreamHelper import IntStreamHelper,\
FloatStreamHelper,\
StringStreamHelper,\
BitsStreamHelper,\
... |
from abc import ABCMeta, abstractmethod
import numpy as np
import GPy
from scipydirect import minimize
class BO(object):
__metaclass__ = ABCMeta
def __init__(self, gp_model, f):
self.gp_model = gp_model
self.f = f
@abstractmethod
def acquire(self, x):
pass
def acquire_min... |
# -*- coding: utf-8 -*-
"""
@contact: [email protected]
@time: 2018/4/10 下午5:38
""" |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
from subprocess import check_output, call, STDOUT
from distutils import log
from distutils.core import Command
from setuptools import setup, find_packages
from setuptools.command.develop import develop
from setuptools.command.sdist import sdist
from se... |
from psyneulink import *
import numpy as np
# Mechanisms
Input = TransferMechanism(name='Input')
reward = TransferMechanism(output_ports=[RESULT, MEAN, VARIANCE],
name='reward')
Decision = DDM(function=DriftDiffusionAnalytical(drift_rate=(1.0,
... |
# -*- encoding:utf-8 -*-
## Tiff tag values
NewSubfileType = {
0: "bit flag 000",
1: "bit flag 001",
2: "bit flag 010",
3: "bit flag 011",
4: "bit flag 100",
5: "bit flag 101",
6: "bit flag 110",
7: "bit flag 111"
}
SubfileType = {
1: "Full-resolution image data",
2: "Reduced-r... |
from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from swingtime import views
from swingtime.models import BookingLocation
urlpatterns = [
url(
r'^$',
login_required(
views.CalendarList_View.as_view(
template_name='swingtime/choo... |
# Copyright 2014 Open Source Robotics Foundation, 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... |
import abc
import json
import re
import time
import uuid
import plpy
from datetime import datetime
from contextlib import contextmanager
from urlparse import urlparse
@contextmanager
def metrics(function, service_config, logger=None, params=None):
try:
start_time = time.time()
yield
finally:
... |
countries={'uk','usa'}
curr={'pound','dollar'}
a=(zip(countries,curr))
# for i in a:
# print(i)
d={}
for k,v in a:
d[k]=v
print(d) |
# Special logger that writes to sys.stdout using colors and saves to logfile
# Usage: logger = logging.getLogger(__name__)
import sys
import logging
import colorama
class BaseFormatter(logging.Formatter):
def __init__(self, fmt=None, datefmt=None):
FORMAT = '%(customlevelname)s%(message)s'
super(... |
from unittest import TestCase
from nally.core.layers.inet.ip.ip_diff_service_values import IpDiffServiceValues
from nally.core.layers.inet.ip.ip_ecn_values import IpEcnValues
from nally.core.layers.inet.ip.ip_fragmentation_flags import IpFragmentationFlags
from nally.core.layers.inet.ip.ip_packet import IpPacket
#
# ... |
"""This module contains some general purpose utilities that are used across
Diofant.
"""
from .iterables import (cantor_product, capture, default_sort_key, flatten,
group, has_dups, has_variety, numbered_symbols,
ordered, postfixes, postorder_traversal, prefixes,
... |
import ast, operator
from .. import value
def Name(node):
return value.Symbol(node.id), []
def Attribute(node): # a.b.c
names = []
n = node
# Trace back the chain of attributes.
while isinstance(n, ast.Attribute):
names.append(n.attr)
n = n.value
if isinstance(n, ast.Name)... |
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
dummy = ListNode(0)
curr = head
while curr:
prev = dummy
while prev.next and prev.next.val < curr.val:
prev = prev.next
next = curr.next
curr.next = prev.next
prev.next = curr
curr = next
... |
# Crankset class
class StimulationSignal:
import Ergocycle as Ergocycle
# Constuctor
def __init__(self, frequency, amplitude, pulse_width, training_time, muscle, electrode):
self.frequency = frequency
self.amplitude = amplitude
self.pulse_width = pulse_width
self.traini... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-06-29 06:32
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('tablemanager', '0033_auto_20160620_1121'),
]
operations = [
migrations.RemoveField(
... |
import random
import torch
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
from networks.maddpg_critic_version_3 import MADDPGCriticVersion3
from networks.maddpg_actor_version_2 import MADDPGActorVersion2
from agents.base_agent import BaseAgent
from agents.game import Game
from utils.ou... |
a = int(input())
b = int(input())
c = int(input())
d = int(input())
for first_row_first_num in range(a, b + 1):
for first_row_second_num in range(a, b + 1):
for second_row_first_num in range(c, d + 1):
for second_row_second_num in range(c, d + 1):
if (first_row_first_num + secon... |
# Generated by Django 2.1.5 on 2019-02-03 15:37
import backend.company.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('company', '0002_auto_20190130_1235'),
]
operations = [
migrations.AddField(
model_name='company',
... |
# Author: Pieter de Jong
import random
def generateComplexNumber():
random.seed()
real = random.randint(-100, 100)
compl = random.randint(-100, 100)
c = complex(real, coml)
return c
def isMandelbrot(c):
z = 0
for i in range(100):
z = pow(z, 2) + c
absZ = abs(z)
if absZ > 2:
return Fa... |
import pytest
from pyspark.sql import SparkSession
@pytest.fixture(scope="session")
def spark_session():
spark = SparkSession.builder\
.appName('testing')\
.config('spark.driver.bindAddress', '127.0.0.1')\
.getOrCreate()
yield spark
spark.stop()
@pytest.fixture(scope="module")
d... |
def doTest(host, port):
from tensorflow_serving.apis.predict_pb2 import PredictRequest
from tensorflow_serving.apis.prediction_service_pb2_grpc import PredictionServiceStub
from grpc import insecure_channel, StatusCode
from tensorflow.contrib.util import make_tensor_proto, make_ndarray
from tensorf... |
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle as shuffle_data
class BaseDataLoader():
def __init__(self, data_handler, shuffle, test_split, random_state, stratify, training):
dh = data_handler
if dh.X_data_test is dh.y_data_test is None:
if 0 < ... |
class TargetNotGeneratedErr(Exception):
pass
class CompilationFailedErr(Exception):
pass
class CmdFailedErr(Exception):
pass
class NotFileErr(Exception):
pass
class DepIsGenerated(Exception):
pass
class LineParseErr(Exception):
pass
class CleanExitErr(Exception):
pass |
SIZE = 400
GRID_LEN = 4
GRID_PADDING = 6
FONT = ("Verdana", 40, "bold")
BACKGROUND_COLOR_GAME = "#57407C"
CELL_COLOR_EMPTY = "#3D2963"
CELL_COLOR_CORRECT = "#E88A45"
CELL_COLOR_INCORRECT = "#6AC6B8"
TEXT_COLOR = "white"
|
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'join/$','api.views.new_user'), #Creates and logs in a user
url(r'login/$','api.views.login_empous_user'), #logs in an empous user
url(r'generatetoken/$', 'api.views.generate_token'),
url(r'resetpassword/$', 'api.views.reset_passwo... |
# this is used for regularization
class Intersection2(chainer.Link):
def __init__(self, outdim, numnet):
super(Intersection2, self).__init__()
self.outdim = outdim
self.numnet = numnet
with self.init_scope():
W = chainer.initializers.One()
self.W = variable.... |
import unittest
from mcalc import get_prot_mass
class MolecularMassTestCase(unittest.TestCase):
def test_lower(self):
result_lower = get_prot_mass('mpfmvnniyvsfceikeivcaggsttkyadvlqenneqgrtvklq')
self.assertEqual(result_lower, 5051.7509)
def test_gaps(self):
result_gaps = get... |
import os
import sys
from flask import Flask, request, abort, jsonify, render_template, url_for
from flask_cors import CORS
import traceback
from models import setup_db, SampleLocation, db_drop_and_create_all
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__)
setup_db(ap... |
import os
import sqlite3
import textwrap
from scripts.artifact_report import ArtifactHtmlReport
from scripts.ilapfuncs import logfunc, tsv, timeline, is_platform_windows, open_sqlite_db_readonly
def get_protonmailMessages(files_found, report_folder, seeker, wrap_text):
for file_found in files_found:
... |
import importlib
def load(module):
wrapper_module = importlib.import_module(
"tacorn." + module + "_wrapper")
return wrapper_module
|
import agate
def get_buffalo_data(data):
buffalo_data = data.where(lambda row: row['dest_city'] == 'Buffalo')
buffalo_data.to_csv('output/dest-buffalo-2002-2015.csv')
def get_full_data():
fulldata = agate.Table.from_csv('original/WRAPS-arrivals-by-destination-2002-2015-clean.csv')
return fulldata
def... |
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from job_position.api.views import JobPositionViewSet
router = DefaultRouter()
router.register('', JobPositionViewSet, basename='jobposition')
urlpatterns = [
path('jobpositions/', include(router.urls), name='jobpositions')
]
|
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-LOG 蓝鲸日志平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-LOG 蓝鲸日志平台 is licensed under the MIT License.
License for BK-LOG 蓝鲸日志平台:
------------------------------------------------... |
import httplib2
from bs4 import BeautifulSoup, SoupStrainer
import urllib.request, urllib.error
import os
import re
import sys
def get(url):
http = httplib2.Http(".cache", disable_ssl_certificate_validation=True)
status, response = http.request(url)
return response
def getlinks(url):
return Beautiful... |
from django.contrib import admin
from birth_rate_app.models import (
Hospital,
Birth,
)
# Register your models here.
admin.site.register(Hospital)
admin.site.register(Birth)
|
# Standard Library
import random
from collections import defaultdict
from copy import copy
# Third Party
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.patches import PathPatch
from matplotlib import cm
from scipy.interpolate import splprep, sp... |
from __future__ import absolute_import
import mock
import unittest
from . import read_file
from nose_parameterized import parameterized
from pynetlib.route import Route
from pynetlib.exceptions import ObjectNotFoundException, ObjectAlreadyExistsException
class TestRoute(unittest.TestCase):
def setUp(self):
... |
variable = 1
print(lalala)
|
import sys
import random
import json
import time
import pygame
from get_ip import check_for_internet_conection as get_ip
import time
from event_handler import unparse
from renderer import draw_everything
from time import sleep, localtime
from weakref import WeakKeyDictionary
from PodSixNet.Server import Server
from ... |
from django.conf.urls import path
from django.urls import include
from django.views.generic import TemplateView
urlpatterns = [
path("tz_detect/", include("tz_detect.urls")),
path("", TemplateView.as_view(template_name="index.html")),
]
|
"""
User enters the Table %, Depth %, length, and width numbers to get rated diamond quality obtained via binary search.
Quality: Excellent, Very Good, Good, Fair, Poor
Table%: 53-63, 52 or 64-65, 51 or 66-68, 50 or 69-70, <50 or >7... |
import requests, json
def geturl2(**kwargs):
if kwargs.get("mcversion"):
url = f"https://nitroxenon-minecraft-forge-v1.p.rapidapi.com/optifine/{kwargs.get('mcversion')}"
headers = {
'x-rapidapi-key': "a6f51f9ea2mshf179951f6fc0d97p1b476ejsndba62ed12b1d",
'x-rapidapi-host': "n... |
# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.
# The scope of the test is to verify that code nested SDFGs with a unique name is generated only once
# The nested SDFG compute vector addition on FPGA, with vectorization
import dace
import numpy as np
import argparse
import subprocess
from... |
from __future__ import annotations
from jsonclasses import jsonclass, types
from jsonclasses_pymongo import pymongo
@pymongo
@jsonclass(class_graph='simple')
class SimpleStrId:
id: str = types.str.primary.required
val: str
|
# //----------------------------//
# // This file is part of RaiSim//
# // Copyright 2020, RaiSim Tech//
# //----------------------------//
import numpy as np
import platform
import os
class RaisimGymVecEnv:
def __init__(self, impl, normalize_ob=True, seed=0, clip_obs=10.):
if platform.system() == "Darw... |
from __future__ import unicode_literals
HAVE_WEBSOCKET = False
WebSocket = None
# WebSocket: (URI, header={'Accept': 'nothing', 'X-Magic-Number': '42'})->WebSocket
# only send, recv, close are guaranteed to exist
HAVE_WS_WEBSOCKET_CLIENT, HAVE_WS_WEBSOCKETS, HAVE_WS_WEBSOCAT, HAVE_WS_NODEJS_WS_WRAPPER, HAVE_WS_NODEJ... |
import TDMtermite
# import numpy as np
import json
import re
# create 'tdm_termite' instance object
try :
jack = TDMtermite.tdmtermite(b'samples/SineData.tdm',b'samples/SineData.tdx')
except RuntimeError as e :
print("failed to load/decode TDM files: " + str(e))
# list ids of channelgroups
grpids = jack.get_... |
import torch
import torch.nn.functional as F
class GlobalContext(torch.nn.Module):
def __init__(self, num_classes=72):
super(GlobalContext, self).__init__()
self.num_classes = num_classes
self.fc = torch.nn.Linear(
in_features=self.num_classes * 74,
out_features=128,... |
import os
from elasticsearch import Elasticsearch
import sqlalchemy as database
from sqlalchemy.orm import sessionmaker
from zeeguu_core.elastic.elastic_query_builder import build_elastic_query
from comparison.mysqlFullText import mysql_fulltext_query
from timeit import default_timer as timer
from zeeguu_core.model im... |
from logging import error
import unittest
from requests.api import request
from app import app
import technical
class Test(unittest.TestCase):
#UNIT TEST FOR app.py
URL = "http://127.0.0.1:5000/test_task/api/distance_address"
data_valid = {"address": "Moscow"}
key_invalid = {"adres": "Moscow"}
... |
#!env/bin/python
# Copyright (C) 2017 Baofeng Dong
# This program is released under the "MIT License".
# Please see the file COPYING in the source
# distribution of this software for license terms.
from dashboard import app
app.run(debug = True)
|
# Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
# Example 1:
# Input: [5,7]
# Output: 4
# Example 2:
# Input: [0,1]
# Output: 0
class Solution(object):
def rangeBitwiseAnd(self, m, n):
"""
:type m: int
:type n: int
... |
# Generated by Django 3.1.1 on 2020-09-20 22:45
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('character', '0001_initial'),
]
operations = [
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('sms', '0009_check_for_domain_default_backend_migration'),
]
operations = [
migrations... |
#!/usr/bin/env python3
"""Translate chromosomes in Ensembl GFF3, ignore chromosomes missing from lookup."""
lookup_table = {x: f'chr{x}' for x in list(range(1, 23)).extend('X', 'Y')}
lookup_table.extend({'MT': 'chrM'})
with open('/dev/stdin', 'r') as gff:
for row in gff:
fields = row.split()
if fi... |
import matplotlib.pyplot as plt
def plot(all_losses):
plt.figure()
plt.plot(all_losses)
plt.show()
|
from yowsup.structs import ProtocolEntity, ProtocolTreeNode
class FailureProtocolEntity(ProtocolEntity):
def __init__(self, reason):
super(FailureProtocolEntity, self).__init__("failure")
self.reason = reason
def __str__(self):
out = "Failure:\n"
out += "Reason: %s\n" % self.r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.