content stringlengths 5 1.05M |
|---|
def get_r_string_sample_groups_by_SS_column(order_list,sample_groups_by_column):
sample_groups_by_column_ordered = []
for column_dict in sample_groups_by_column:
column_list = []
for sample_group in order_list:
if sample_group in column_dict:
column_list.append(samp... |
import sys
import csv
import numpy as np
def get_branin(param1, param2, param3, inst, rnd):
a, b, c = inst
b = b / (4.*np.pi**2)
c = c / np.pi
r = 6.
s = 10.
t = 1. / (8.*np.pi)
ret = a*(param2-b*param1**2+c*param1-r)**2+s*(1-t)*np.cos(param1)+s
ret += rnd.normal()
ret = ret ** 2
... |
# Some repositories (such as Devpi) expose the Pypi legacy API
# (https://warehouse.pypa.io/api-reference/legacy.html).
#
# Note it is not possible to use pip
# https://discuss.python.org/t/pip-download-just-the-source-packages-no-building-no-metadata-etc/4651/12
import os
import sys
import netrc
from urllib.parse imp... |
# encoding: utf-8
import os
from copy import copy
import httplib2
import oauth2client
import inspector
from .. import utils
def from_params(**params):
credentials = {}
for key, value in params.items():
if key in ('client_id', 'client_secret', 'client_email', 'private_key', 'access_token', 'refresh_... |
#! /usr/bin/python
'''
This script converts genotype calls file to .geno and .snps files
suitable for XPCLR (https://reich.hms.harvard.edu/software)
# input.tab
CHROM POS ANC DER sample1 sample2 sample3 sample4 sample5 sample6 sample7
chr1 1 A T 0/1 ./. ./. 0/0 ./. ./. ./.
chr1 2 C T 1/0 0/1 ./. 0/0 0/0 1/1 0/0
chr1 3... |
from synbioweaver.core import *
from synbioweaver.aspects.designRulesAspect import *
from synbioweaver.aspects.promoterMappingAspect import *
from synbioweaver.aspects.MassActionKineticsProteinAspect import *
from synbioweaver.aspects.lagLogisticGrowthAspect import *
from synbioweaver.aspects.printReactionNetworkAspect... |
#!/usr/bin/env python
import csv
import os
import random
import yaml
MYDIR = os.path.dirname(__file__)
CFG_TEMPLATE_FNAME = os.path.join(MYDIR, "cfg.yaml")
EXP_FNAME = "expected_seq.csv"
sched_big = (
[(60, 30)] * 20
+ [(120, 59)] * 20
+ [(240, 5)] * 20
)
sched_small = (
[(2, 1)] * 1
+ [(... |
def addition(a, b):
return float(a) + float(b)
def subtraction(a, b):
return float(a) - float(b)
def multiplication(a, b):
return float(a) * float(b)
def dividing(a, b):
return float(a) / float(b)
def squaring(a):
return float(a) ** 2
def square_rooting(a):
return float(a) ** 0.5
cla... |
# Copyright 2022 AI Singapore
#
# 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... |
from os import path
import numpy as np
from numpy.random import randint, randn, seed
import pandas as pd
from xgboost import DMatrix, train
import matplotlib.pyplot as plt
from mlrun.execution import MLClientCtx
from mlrun.datastore import DataItem
from mlrun.artifacts import PlotArtifact
from mlrun.mlutils.data import... |
# Copyright 2011 Grid Dynamics
# Copyright 2011 OpenStack Foundation
# 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... |
from alisu.utils.localization import get_locale_string, langdict, default_language
from functools import partial
from typing import Optional
def get_bot_locale_string_simple(
category: str,
string_name: str,
language: Optional[str] = default_language,
):
strings = partial(
get_locale_string,
... |
from eme.data_access import Repository, RepositoryBase
from sqlalchemy import and_, func
from ..base.meta_repo import MetaboliteDataRepositoryBase
from ..entities.dbdata.lipidmaps import LipidMapsData
@Repository(LipidMapsData)
class LipidMapsDataRepository(MetaboliteDataRepositoryBase):
primary_id = 'l... |
# SPDX-License-Identifier: BSD-3-Clause
# Copyright (c) 2022 Osyris contributors (https://github.com/nvaytet/osyris)
from matplotlib.colors import LogNorm, Normalize
def get_norm(norm=None, vmin=None, vmax=None):
if norm == "log":
return LogNorm(vmin=vmin, vmax=vmax)
else:
return Normalize(vm... |
# -*- coding: utf8 -*-
import json
import requests
import os
os.environ["PYTHONIOENCODING"]="UTF8"
# запись лога в файл
def write(content):
f = open('text.txt', 'a')
f.write(content)
f.close()
# https://yandex.ru/dev/dialogs/alice/doc/protocol.html/
def genResp(data):
# content='{"response": {"text": "'+c... |
import math
import os
import numpy as np
import torch
import torch.cuda
import ujson as json
from absl import app
from torch.utils.tensorboard import SummaryWriter
from torch.optim import Adam
from torch.optim.lr_scheduler import LambdaLR
from torch.utils.data import RandomSampler, SequentialSampler, DataLoader
from t... |
import os
os.environ["MKL_NUM_THREADS"] = "1"
os.environ["NUMEXPR_NUM_THREADS"] = "1"
os.environ["OMP_NUM_THREADS"] = "1"
import sys
import numpy as np
np.random.seed(1)
import random
random.seed(1)
import pandas as pd
import cv2
import timeit
from os import path, makedirs, listdir
import sys
sys.s... |
def f(x):
"""
Parameters:
x ():
""" |
'''
Menu for Community Scripts
Author: Christoph Stoettner
Mail: christoph.stoettner@stoeps.de
Documentation: http://scripting101.stoeps.de
Version: 5.0.1
Date: 09/19/2015
License: Apache 2.0
History: Changed by Jan Alderlieste
'''
import sys
import os
import ibmcnx.funct... |
# %%
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import os
import shutil
import ast
from os import path
from sklearn.model_selection import train_test_split
from IPython.display import display
from tqdm import tqdm
# %matplotlib inline
# %%
df = pd.read_csv("train.csv")... |
#!/usr/bin/env python
import sys
import mechanize
from bs4 import BeautifulSoup
def browse_schwab():
# set some constants
schwab_url = "https://www.schwab.com/public/schwab/client_home"
username = ""
password = ""
br = mechanize.Browser()
br.addheaders = [('User-agent', 'Mozilla/Firefox Plan-... |
"""
This file builds H2O model
"""
from connection import H2OConnection
from frame import H2OFrame, H2OVec
from job import H2OJob
import h2o
# Response variable model building
def supervised_model_build(x,y,validation_x,validation_y,algo_url,kwargs):
# Sanity check data frames
if not y: raise ValueEr... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-27 10:36
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migratio... |
"""
Created on July 25th, 2017
@author: rouxpn
"""
from __future__ import division, print_function, unicode_literals, absolute_import
import os
import re
import csv
import xml.etree.ElementTree as ET
from decimal import Decimal
from collections import defaultdict
class phisicsdata():
"""
This class parses the P... |
import time
from collections import OrderedDict
from conans.client.graph.graph import DepsGraph, Node, RECIPE_EDITABLE
from conans.errors import (ConanException, ConanExceptionInUserConanfileMethod,
conanfile_exception_formatter)
from conans.model.conan_file import get_env_context_manager
fr... |
from .instruccionAbstracta import InstruccionAbstracta
from tabla_Simbolos import retornoInstruccion
from Errores import errorReportar
from .updateColumna import UpdateColumna
from tabla_Simbolos import simboloColumna
from .expresion import Expresion
import jsonMode
class UpdateTable(InstruccionAbstracta):
def _... |
#Boa:MiniFrame:MDIChildEmails
#-----------------------------------------------------------------------------
# Name: MDIChildEmails.py
# Purpose:
#
# Author: Ram Basnet
#
# Created: 2007/11/01
# Last Modified: 6/30/2009
# RCS-ID: $Id: MDIChildEmails.py,v 1.5 2008/03/17 04:18:38 rbas... |
import torch
import common.torch
from .classifier import Classifier
from .wide_resnet_block import WideResNetBlock
from .utils import get_normalization2d, get_activation
class WideResNet(Classifier):
"""
Wide Res-Net taken from https://github.com/meliketoy/wide-resnet.pytorch
"""
def __init__(self, N... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.20 on 2020-02-06 12:35
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('activityinfo', '0104_activity_ai_category_id'),
]
operations = [
migration... |
#!/usr/bin/env python
'''
Copyright (c) 2020 RIKEN
All Rights Reserved
See file LICENSE for details.
'''
import log,traceback
class load:
def __init__(self, args):
log.logger.debug('started')
try:
# default
self.genome_cov_thresholds=0.05 # Defining high coverage viruse... |
from typing import Tuple, List, Dict, Optional, Sequence
from collections import defaultdict
import string
from pathlib import Path
from Bio import SeqIO
import subprocess
from .typed import PathLike
from .constants import IUPAC_CODES
from .dataset import ThreadsafeFile
import numpy as np
from scipy.spatial.distance im... |
from pathlib import Path
from fastapi_camelcase import CamelModel
class AppStatistics(CamelModel):
total_recipes: int
total_users: int
total_groups: int
uncategorized_recipes: int
untagged_recipes: int
class AppInfo(CamelModel):
production: bool
version: str
demo_status: bool
clas... |
import subprocess
import sys
import pkg_resources
from GridCal.__version__ import __GridCal_VERSION__
def find_latest_version(name='GridCal'):
"""
Find the latest version of a package
:param name: name of the Package
:return: version string
"""
latest_version = str(subprocess.run([sys.executab... |
#! /usr/bin/env python3
import sys
class ReadPRO:
'''
Parse the .pro file output by flux
'''
filename = None
def __init__(self, filename):
self.filename = filename
def getGenes(self, chrom, start=None, end=None):
if start == None:
start = 0
if end == N... |
import random
import tensorflow as tf
from malib.trainers.utils import *
from malib.utils import tf_utils
class AdHocSeqTrainer:
def __init__(self, env, agent, teammates, sampler, batch_size, exploration_epochs, adhoc_epochs,
teammate_batch_size, recent_batch_size, extra_experiences, save_path=... |
import
def fsds
sdfsdfsd
sdfsdfsd
|
from bluebottle.fsm.triggers import TransitionTrigger, TriggerManager, register, ModelChangedTrigger
from bluebottle.fsm.effects import RelatedTransitionEffect
from bluebottle.initiatives.states import ReviewStateMachine
from bluebottle.initiatives.models import Initiative
from bluebottle.activities.states import Activ... |
# Import ข้อมูลจากไฟล์ Excel (.xlsx) เข้าสู่ Database MySQL
# เป็นการ Import ข้อมูลทุกแถวมาใส่ใน products
# แต่จะเอาข้อมูลประเภทสินค้า แยกไปใส่ใน categories (ถ้ายังไม่มี)
# และที่สำคัญ ต้องเชื่อม products และ categories เข้ากันให้เรียบร้อย
import mysql.connector
from openpyxl import load_workbook
def run():
# Exc... |
# coding=utf-8
'''
cron trigger
@author: Huiyugeng
'''
import datetime
import trigger
class CronTrigger(trigger.Trigger):
def __init__(self, cron):
trigger.Trigger.__init__(self, 0, 1);
self.cron = cron
def _is_match(self):
parser = CronParser(self.cron)
... |
# -*- coding: utf-8 -*-
"""
Information about a single person
"""
class Person:
@staticmethod
def sanitize(unclean):
def san(nm):
return " ".join(
[part.strip().title().replace(",", "") for part in nm.split()]
)
first, last = unclean.rsplit(" ", 1)
... |
from abc import ABC, abstractmethod
from os import getcwd
from typing import Union
from neobabix.notifications.jokes import jokes
import random
import requests
class Notification(ABC):
def __init__(self):
current_path = getcwd()
with open(f'{current_path}/version.txt', 'r') as f:
versi... |
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2
import pandas as pd
import numpy as np
from sklearn.decomposition import PCA
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.model_selection import cross_val... |
import pandas as pd
import numpy as np
import torch
# from Net.model import fusion_net,JackNet,Net
import torch.nn as nn
# 設定 GPU
device = torch.device("cuda")
# 載入數據
ada_df = pd.read_csv('./csv/adaboost_fold_val.csv')
svm_df = pd.read_csv('./csv/svm_fold_val.csv')
fore_df = pd.read_csv('./csv/forest_fold_val.csv')
k... |
from __future__ import (
annotations,
)
from typing import (
Optional,
)
from uuid import (
UUID,
)
from minos.common import (
DatabaseMixin,
ProgrammingException,
)
from ....exceptions import (
SagaExecutionNotFoundException,
)
from ...saga import (
SagaExecution,
)
from ..abc import (
... |
import random
'''
Check all keys on the player board to unlock a place card
'''
def unlockPlace(game, player):
nbSilverKey = 0
nbGoldKey = 0
i = 0
# Check the last place
board = player.getBoard()
if(board.getPlaceCards() != []):
lastPlaceCard = board.getPlaceCards()[-1]
i = lastP... |
# Animatronic Hand
# Binary Counting on four fingers up to 15
import time
from digitalio import DigitalInOut, Direction, Pull
import audioio
from adafruit_seesaw.seesaw import Seesaw
from adafruit_seesaw.pwmout import PWMOut
from adafruit_motor import servo
from busio import I2C
import board
# Create I2C and seesaw ... |
# -*- coding: utf-8 -*-
# by Strzelewicz Alexandre
#########################################################
#
# Model / Database / Mailing / Logger
#
#########################################################
from gluon.tools import *
auth = Auth(globals(),db)
auth.settings.hmac_key = 'sha512:21e79f... |
import tkinter as tk
root = tk.Tk()
root.geometry("400x260+50+50")
root.title("Welcome to Letter Counter App")
message1 = tk.StringVar()
Letter1 = tk.StringVar()
def printt():
message = message1.get()
letter = Letter1.get()
message = message.lower()
letter = letter.lower()
# Get the count and di... |
# -*- coding: UTF-8 -*-
import numpy as np
import pandas as pd
def create():
empoyees = [('jack', 34, 'Sydney', 5),
('Riti', 31, 'Delhi', 7),
('Aadi', 16, np.NaN, 11),
('Mohit', 23, 'Delhi', 15),
('Veena', 33, 'Delhi', 4),
('Shaunak',... |
try:
import tkinter as tk
import tkinter.ttk as ttk
except ImportError:
import Tkinter as tk
import ttk
from PIL import Image, ImageTk
from .utils import get_root_widget
class ScrolledCanvas(tk.Frame):
"""
1. Master widget gets scrollbars and a canvas. Scrollbars are connected
to canvas s... |
import sys
import numpy as np
import pygame as pg
from pygame.constants import *
from physicsTable import *
from trial_generator import get_json_walls, WHITE, BLACK, X, Y
def parse_walls(json_trial_name):
# get trial pixel array
tr = loadTrialFromJSON(json_trial_name)
tb = tr.makeTable()
surface = tb.... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
dates = pd.date_range('20130101', periods=6)
#
"""Two-dimensional size-mutable, potentially heterogeneous tabular data structure with
labeled axes (rows and columns). Arithmetic operations align on both row and column
labels. Can be thought of as... |
### 1. hst
def hst(f,W,V,τ,b,γ=1,T=999999999): #samefunction with hst1realization except print
#from random import sample
n=len(f)
E=W>0
trajectory = [0]*(τ+1)#cc(0,τ)*0
flowcount= [0]*(τ+1)
# 1. calculate π0, i.e.,
d=np.sum(np.array(W),0)
π0=d/np.sum(d) ## stationary dist
... |
import numpy as np
import os
import math
import copy
import shutil
import scipy
import random
from enum import Enum
from tqdm import tqdm
# Visualization libraries
USE_SEABORN = False
import matplotlib.pyplot as plt
if USE_SEABORN:
import seaborn as sns
sns.set() # Set the seaborn defaults
# Pruning librari... |
import re
import pytest
from laia.callbacks.segmentation import Segmentation
from laia.dummies import DummyEvaluator, DummyMNISTLines, DummyTrainer
def test_char_segmentation_empty():
with pytest.raises(AssertionError):
Segmentation.char([""], [], 1)
def test_char_segmentation():
txt = ["a", "b", ... |
from norminette.rules import Rule
kw = [
# C reserved keywords #
"AUTO",
"BREAK",
"CASE",
"CHAR",
"CONST",
"CONTINUE",
"DEFAULT",
"DO",
"DOUBLE",
"ELSE",
"ENUM",
"EXTERN",
"FLOAT",
"FOR",
"GOTO",
"IF",
"INT",
"LONG",
"REGISTER",
"RETUR... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
# import funkcí z jiného adresáře
from loguru import logger
import os.path
import sys
import unittest
# logger = logging.getLogger()
import pytest
import numpy as np
import shutil
import matplotlib.pyplot as plt
path_to_script = os.path.dirname(os.path.abspath(__file__))
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2021, Stephen Goadhouse <sgoadhouse@virginia.edu>
#
# 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, inclu... |
from lib.ai.local import LocalSnake
class Snake(LocalSnake):
def whois(self):
return {
'color': '#FFFFFF',
'head': 'wut'
}
def start(self, payload):
return {
'taunt': 'northward bound'
}
def move(self, payload):
return {
... |
# Utils
import numpy as np
from sklearn.preprocessing import OneHotEncoder
class Batcher(object):
""" Iterable that iterates over batches of the specified size until it exhausts the dataset.
NOTE: if you pass a batch size not a even divisor to the dataset size, the final batch will be the
size of the... |
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Alcazas and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.model.document import Document
class JobCode(Document):
def autoname(self):
description_code = frappe.db.ge... |
import numpy as np
import pandas as pd
import pickle
import re, os, sys
from sklearn.metrics import roc_auc_score
from sklearn.metrics import log_loss
AVAILABLEDATASETS = {'IMDB', 'Amazon', 'IMDB_unlabeled', 'twitter_disasters', 'YouTube',
'journalist_photographer', 'painter_architect', 'professor... |
from vbench.api import Benchmark
from datetime import datetime
start_date = datetime(2012, 7, 1)
common_setup = """from .pandas_vb_common import *
import os
f = '__test__.h5'
def remove(f):
try:
os.remove(f)
except:
pass
"""
#---------------------------------------------------------------------... |
# -*- coding: utf-8 -*-
"""dataaugmentation.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1ibfKtpxC_hIhZlPbefCoqpAS7jTdyiFw
"""
import tensorflow as tf
import tensorflow_datasets as tfds # Import TensorFlow datasets
import urllib
import tensorf... |
# -*- coding: utf-8 -*-
"""
Scraper for Pennsylvania Commonwealth Court
CourtID: pacomm
Court Short Name: pacomm
Author: Andrei Chelaru
Reviewer: mlr
Date created: 21 July 2014
If there are errors with this site, you can contact:
Amanda Emerson
717-255-1601
She's super responsive.
"""
from juriscraper.opinions.... |
r"""Batch types and data processing functions.
The batch, inputs, and targets in **Training API** usually
represented using unnormalized form for user convenience.
During construction of :class:`TrainLoop` data get normalized.
In that form, a batch is a tuple, `((x,...), (y,...))`, that consist of:
- inputs, `(x,..... |
import functools
import operator
from decimal import Decimal
import orjson
from typing import Optional, Any
import unicodecsv as csv
from io import BytesIO
import datetime
from django.conf import settings
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment
from rest_framework impor... |
from __future__ import annotations
import json
import re
import secrets
from collections.abc import Callable, Iterable, Sequence
from http import HTTPStatus
from io import BytesIO
from json import JSONDecodeError
from types import TracebackType
from typing import Any, Union
from urllib.parse import quote_plus, urlpars... |
"""
STRUCTURE
1. Create the screen
2. Create and move the paddle
3. Create another paddle
4. Create the ball and make it move
5. Detect collision with wall and bounce
6. Detect collision with paddle
7. Detect when paddle misses
8. Keep score
"""
from turtle import Screen
from paddle import Paddle
from ba... |
from ..services.to_do_service import ToDoService
from ..services.to_do_tag_service import ToDoTagService
from ..responses.to_do_response import ToDoResponse
class ToDoController:
@staticmethod
async def get_by_id_and_id_user(id,id_user):
to_do, status, tag_list = ToDoService.get_by_id_and_id_user(id,id_... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
import twint
import time
c = twint.Config()
c = twint.Config()
for i in range (1,5):
c.Near = "College Park"
c.Lang = "en"
c.Location = True
c.Store_csv = True
c.Since = "2019-04-14"
c.Output = "twitter2.csv"
twint.run.Search(c)
time.sleep(1)
|
from collections import namedtuple
from typing import Any, Dict, List, Optional
class State(object):
"""
An enumeration of states that a bundle can be in.
"""
# Waiting for contents to be uploaded
UPLOADING = 'uploading'
# Just created
CREATED = 'created'
# All the dependencies are me... |
#
# 'post' table formats 1.0 and 2.0 rely on this list of "standard"
# glyphs.
#
# My list is correct according to the Apple documentation for the 'post'
# table: http://developer.apple.com/fonts/TTRefMan/RM06/Chap6post.html
# (However, it seems that TTFdump (from MS) and FontLab disagree, at
# least with respect to th... |
#Pluginname="Filenamecreator"
#(c) B.Kerler 2017
#Type=App
from os import walk
import os
import struct
import tempfile
def main():
filenames=ctx.pluginfilenames();
headers=["timestamp (int)","filename (QString)"]
ctx.gui_set_headers(headers)
ctx.gui_setMainProgressBar(0)
ctx.gui_setM... |
"""
Custom element classes related to hyperlinks (CT_Hyperlink).
"""
from ..simpletypes import ST_RelationshipId
from ..xmlchemy import BaseOxmlElement, ZeroOrMore, OptionalAttribute
class CT_Hyperlink(BaseOxmlElement):
"""
``<w:hyperlink>`` element, containing the properties and text for a hyperlink.
"... |
"""
Seo checker
Usage:
seocheck.py <file> [--start-from-line n]
Options:
-h --help Show this screen
--start-from-line n Skip the first n lines from the file
"""
import csv
import requests
from bs4 import BeautifulSoup
from docopt import docopt
COLUMNS_MAPPING = {
'url': 1,
'title': 4,
... |
#!/usr/bin/env python3
# the test api procedure
# system imports
import time
import sys
# local imports
from procedure.upgrade_code import UpgradeCode
class MockUpgradeCode(UpgradeCode):
# override parent method
def upgrade_code(self, api_call, sw_api_call, ap_api_call, sw, logger):
logger.info("... |
# Python Module RestclassEfficient
from seraphim.util.extended_euclidean import get_inverse
from seraphim.util.tonelli_shanks import tonelli_shanks
class Error(Exception):
"""Base class for other exceptions"""
class ValueNotInZError(Error):
"""Raised when the input value is too small"""
class ModIsZeroErr... |
import pickle
import numpy as np
import tensorflow as tf
import constants
from abstraction.quotient_mdp_full import QuotientMDPFull
from agents.quotient_mdp_nbisim import QuotientMDPNBisim
from model.bisim.bisim import QPredictionModelHMMPrior
from runners.bisim.puck_stack.QHMMPrior import QHMMPriorRunner
from utils.da... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
BuiltinAlgorithms = {
'tuners': [
{
'name': 'TPE',
'class_name': 'nni.algorithms.hpo.hyperopt_tuner.hyperopt_tuner.HyperoptTuner',
'class_args': {
'algorithm_name': 'tpe'
... |
import sys
import numpy as np
from sklearn import metrics
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--input_file",
default=None,
type=str,
required=True)
parser.add_argument("--n", default=-1, type=int)
args = pars... |
from __future__ import unicode_literals
from __future__ import absolute_import
class Container(object):
"""
Represents a Docker container, constructed from the output of
GET /containers/:id:/json.
"""
def __init__(self, client, dictionary, has_been_inspected=False):
self.client = client
... |
from django.http import JsonResponse
from rest_framework.views import APIView
from nsetools import Nse
import pandas as pd
from django.conf import settings
import os
# Create your views here.
class Real_Time_Stock_Data(APIView):
def __init__(self):
self.nse = Nse()
def get(self, request):
st... |
'''
for / while
0 10
1 9
2 8
3 7
4 6
5 5
6 4
7 3
8 2
'''
for p, r in enumerate(range(10,1,-1)):
print(p,r)
|
"""Прогнозирование доходности с помощью нейронных сетей."""
from poptimizer.dl.data_loader import PhenotypeData
from poptimizer.dl.forecast import Forecast
from poptimizer.dl.model import Model, ModelError
|
import pytest
@pytest.mark.bench
def test_linear_interp_numpy(benchmark):
import numpy as np
from taurex.util.math import interp_lin_numpy
#intepr_bilin_old(x11, x12, x21, x22, T, Tmin, Tmax, P, Pmin, Pmax)
x11 = np.random.rand(10000)
x12 = np.random.rand(10000)
benchmark(interp_lin_numpy, x... |
from __future__ import absolute_import, division, print_function
import math
from scitbx import matrix
import six
from six.moves import range
def construct_xyz(ba, bv,
aa, av,
da, dv,
period=3,
):
assert ba is not None
assert aa is not None
... |
# -*- coding: utf-8 -*-
from flask.ext.wtf import Form
from wtforms import StringField, PasswordField
from wtforms import validators
from wtforms.fields.html5 import EmailField
class JoinForm(Form):
email = EmailField(
u'이메일',
[validators.data_required(u'이메일을 입력하시기 바랍니다.'), validators.Email(u'이메일... |
#!/usr/bin/env python
# encoding: utf-8
"""
compute_lidar_offset.py
Created by Maria Isabel Restrepo on 2012-09-20.
Copyright (c) 2012 . All rights reserved.
"""
import os
import sys
import argparse
from liblas import file
import numpy as np
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parse... |
import numpy as np
import os
from tantum import enums
from tantum.callbacks import Callback
class OutOfFold(Callback):
def __init__(self, output_path) -> None:
self.output_path = output_path
def on_epoch_end(self, model, **kwargs):
print("Out Of Fold CallBack")
predictions = mo... |
import lyricsgenius
import config
import json
import pymongo
import sys
import os
import spotipy
from pprint import pprint as pp
from spotipy.oauth2 import SpotifyClientCredentials
from requests.exceptions import HTTPError, Timeout
import time
import analyzeSong
GENIUS_ACCESS_TOKEN = config.get('GENIUS_CLIENT_ACCESS_... |
import pytest
from encoded.tests.features.conftest import app, app_settings, index_workbook
pytestmark = [
pytest.mark.indexing,
pytest.mark.usefixtures('index_workbook'),
]
def test_reports_search_batched_search_generator_init(dummy_request):
from encoded.reports.search import BatchedSearchGenerator
... |
from tests.testcases import TestCaseUsingRealAPI
from vortexasdk import Geographies
from vortexasdk.conversions import (
convert_to_corporation_ids,
convert_to_geography_ids,
convert_to_product_ids,
)
class TestConvert(TestCaseUsingRealAPI):
def test_convert_to_geography_ids(self):
rotterdam_i... |
import matplotlib.pyplot as plt
import matplotlib as mpl
from pathlib import Path
import pickle
import os
import numpy as np
from scipy.optimize import curve_fit
from figures.styles import colors_per_chi
mpl.rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})
mpl.rc('text', usetex=True)
mpl.rcParams.update... |
import FWCore.ParameterSet.Config as cms
goodStandAloneMuonTrackMCMatch = cms.EDProducer("MCMatcher",
src = cms.InputTag("goodStandAloneMuonTracks"),
maxDPtRel = cms.double(1.0),
mcPdgId = cms.vint32(13), ## muons
mcStatus = cms.vint32(1),
resolveByMatchQuality = cms.bool(False),
maxDeltaR = c... |
# -*- coding: utf-8 -*-
import pytest
from pytest import raises, approx
from cottonformation.core.model import (
Ref, Base64, Cidr, FindInMap, GetAtt, GetAZs, ImportValue,
Join, Select, Split, Sub, Transform,
Parameter, Resource, Output,
)
from cottonformation.tests.helpers import jprint
class TestRef:
... |
import sys
sys.dont_write_bytecode = True
import argparse
import base64
try:
import cPickle as pickle
except Exception:
import pickle
import _common as common
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--data', help='pickled object of TCustomCommand class', required=True)
... |
import discord
import asyncio
client = discord.Client()
async def my_background_task():
await client.wait_until_ready()
counter = 0
channel = discord.Object(id='channel_id_here')
while not client.is_closed:
counter += 1
await client.send_message(channel, counter)
await asyncio.... |
# Generated by Django 2.1.3 on 2019-02-27 05:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('photos', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='photos',
name='is_background',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.