content stringlengths 5 1.05M |
|---|
"""
Management command to change many user enrollments in many courses using
csv file.
"""
import logging
from os import path
import unicodecsv
from django.core.exceptions import ObjectDoesNotExist
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from opaque_keys im... |
# -*- coding: utf-8 -*-
import re
class Cave(object):
_regex_spaces = r'[ ]{21}'
def __init__(self, price=0, meters=0, description='', url='',
service_url=''):
self.price = price
self.meters = meters
# 'description' is the only possible attribute with 'special' char... |
# To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %%
from IPython import get_ipython
# %%
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
# %%
# get_ipython().run_line_magic('load_ext', 'autoreload')
# get_ipython().run_line_magic('autoreload', '2')
# get_ipython(... |
# Copyright 2015 Open Platform for NFV Project, Inc. and its contributors
# This software is distributed under the terms and conditions of the 'Apache-2.0'
# license which can be found in the file 'LICENSE' in this package distribution
# or at 'http://www.apache.org/licenses/LICENSE-2.0'.
from flask import request
fro... |
"""
This script evaluates query interpretations based on the strict evaluation metrics;
macro averaging of precision, recall and F-measure.
For detailed information see:
F. Hasibi, K. Balog, and S. E. Bratsberg. "Entity Linking in Queries: Tasks and Evaluation",
In Proceedings of ACM SIGIR International Confer... |
from django.conf import settings
CONNECTIONS = getattr(settings, 'NEXUS_REDIS_CONNECTIONS', [
# {'host': '127.0.0.1', 'port': 8930},
# {'host': '127.0.0.1', 'port': 8932, 'password': 'secret', 'db': 2},
])
DEFAULT_HOST = 'localhost'
DEFAULT_PORT = 6379
|
from ..parsing import * # Module under test
def test_extract_single_deep_nested():
sigil = "[ENV=[USR=[CURRENT].DEFAULT_ENV].APP=[APP=[ACTIVE]]]"
text = f"-- {sigil} --"
assert set(extract(text)) == {sigil}
def test_ignore_whitespace():
sigil = "[ ENV . HELP ]"
text = f"-- {sigil} --"
asser... |
from django.conf import settings
from django.test import TestCase
from django.core import mail
from ecommerce import mailer
from ecommerce.models import Order
class TestMailer(TestCase):
"""Test cases for mailer module."""
@classmethod
def setUpClass(cls):
"""Set up testing Order instance."""
... |
import pytest
import matplotlib
from dython.data_utils import split_hist
def test_split_hist_check(iris_df):
result = split_hist(iris_df, 'sepal length (cm)', 'target')
assert isinstance(result, matplotlib.axes.Axes)
|
from __future__ import absolute_import, unicode_literals
from django.contrib import admin
from django.db.models import F
from django.utils.translation import ugettext_lazy as _
from .models import Discipline, TrainingSet
class DisciplineListFilter(admin.SimpleListFilter):
"""
Generic Filter for models that ha... |
#!/usr/bin/env python
#
# Copyright (c) 2016 In-Q-Tel, Inc, 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
#... |
import enum
import logging
class DeepLib(enum.Enum):
Null = -1
Pytorch = 0
Tensorflow = 1
SkLearn = 2
def log_device_setup(deepLib: DeepLib = DeepLib.Null, level=logging.INFO):
import sys
import psutil
import multiprocessing
logging.info(f'__Python VERSION: {sys.version}')
loggi... |
import argparse
import datetime
import json
import logging
import pickle
import time
import shutil
from kite.graph_data.data_feeder import EndpointDataFeeder
from kite.graph_data.session import RequestInit
from kite.graph_data.graph_feed import GraphFeedConfig
from kite.infer_expr.config import MetaInfo, Config
from... |
import torch
from torch import nn
import torch.optim as optim
import torch.nn.functional as F
import math
import numpy as np
from config import parameters as conf
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
if conf.pretrained_model == "bert":
from transformers import BertModel
elif con... |
import logging
from datawinners.main.database import get_db_manager
from datawinners.project.view_models import ReporterEntity
from datawinners.tasks import app
from mangrove.datastore.entity import get_by_short_code
from mangrove.form_model.form_model import REPORTER
from mangrove.transport.contract.survey_response im... |
class Solution:
def longestLine(self, M):
hor, ver, dig, aDig, mx, m, n = {}, {}, {}, {}, 0, len(M), len(M and M[0])
for i in range(m):
for j in range(n):
if M[i][j]:
ver[(i, j)] = j > 0 and M[i][j - 1] and ver[(i, j - 1)] + 1 or 1
... |
from django.db import models
class PoliceOfficer(models.Model):
"""
An officer of the NYPD.
E.g. "Jake Peralta"
"""
badge_number = models.IntegerField(primary_key=True)
first_name = models.CharField(max_length=200)
surname = models.CharField(max_length=200)
rank = models.CharField(max_... |
# CPAC/network_centrality/utils.py
#
# Network centrality utilities
# Method to return recommended block size based on memory restrictions
def calc_blocksize(timeseries, memory_allocated=None,
include_full_matrix=False, sparsity_thresh=0.0):
'''
Method to calculate blocksize to calculate c... |
from django.conf import settings
from django.db import connections
from django.test.testcases import LiveServerTestCase, LiveServerThread
from daphne.endpoints import build_endpoint_description_strings
from daphne.server import Server
from ..routing import get_default_application
from ..staticfiles import StaticFiles... |
def check_status(status):
#2xx Success
if status == 200:
return ("OK")
elif status == 201:
return ("Created")
elif status == 202:
return ("Accepted")
elif status == 203:
return ("Non-Authoritative Information")
elif status == 204:
return ("No Content")
elif status == 205:
return ("Reset Content")
el... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 函数默认参数
Desc :
"""
def spam(a, b=42):
print(a, b)
spam(1) # Ok. a=1, b=42
spam(1, 2) # Ok. a=1, b=2
_no_value = object()
def spam(a, b=_no_value):
if b is _no_value:
print('No b value supplied')
|
import sys
import os
import json
from enum import Enum
from pathlib import Path
from .channel import Channel
from io_fetch_channel import ChannelPerformanceFetcher
from io_channel import IOSharedResourceMap
from regla import channel_factory, ChannelEntity, RuleSerializer
from datetime import datetime
from typing impor... |
#
# Copyright 2020-2021 Picovoice Inc.
#
# You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE"
# file accompanying this source.
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
# an "AS ... |
#Copyright (c) 2014, Benjamin Bässler <ccl@xunit.de>
#All rights reserved.
#
#Redistribution and use in source and binary forms, with or without
#modification, are permitted provided that the following conditions are met:
#
#* Redistributions of source code must retain the above copyright notice, this
# list of condit... |
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase
from rest_framework import status
from faker import Faker
f = Faker()
# class ServiceAPITestCase(APITestCase):
# def setUp(self):
# pass
#
# def test_get_device_info(self):
# data = {
#
# }
# ... |
_g_repo = None
def set(repo):
global _g_repo
_g_repo = repo
def get():
return _g_repo
|
#
# 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 ... |
from spiceypy import spiceypy as spice
import numpy as np
from scipy.linalg import norm
import lincov.horizon as horizon
def sun_spacecraft_angle(body, time, object_id):
if body == 'earth':
frame = 'ITRF93'
elif body == 'moon':
frame = 'MOON_ME'
sun,t1,t2 = spice.subslr('INTERCEPT/ELLIPS... |
#!/usr/bin/python
import os
import sys
import time
import glob
import shutil
import json
import xml.etree.ElementTree as ET
import string
import re
import platform
import time
os_commands = {
'debian': {
'9': [
'echo "deb https://repo.gluu.org/debian/ stretch-stable main" > /etc/apt/... |
# __main__.py
import subprocess
import sys
def Playdemo():
# Creating new project folder
try:
if sys.argv[1] == "Play-demo":
subprocess.call(["..TBG_Example/main.py", "-c"])
else:
print("Invalid keyword: format>> python -m Play-demo")
except IndexErr... |
from playhouse.migrate import *
my_db = SqliteDatabase('../data.db')
migrator = SqliteMigrator(my_db)
multiplier_up = DecimalField(null=True)
avg_price_minutes = DecimalField(null=True)
migrate(
migrator.add_column('marketparams', 'multiplier_up', multiplier_up),
migrator.add_column('marketparams', 'avg_pric... |
from collections import Counter
from io import BytesIO
import requests
from PIL import Image, ImageDraw, ImageSequence
header = {'Authorization': 'Basic YnV0dGVyOmZseQ==', } # 'YnV0dGVyOmZseQ==' is base64.encode('butter:fly')
response = requests.get('http://www.pythonchallenge.com/pc/hex/white.gif', headers=header)
... |
"""Detect file changes through the windows api
"""
import os
import win32event
import win32file
import win32con
import asyncio
import pywintypes
import threading
ACTIONS = {
1 : "Created",
2 : "Deleted",
3 : "Updated",
4 : "old name",
5 : "new name"
}
# Thanks to Claudio Gr... |
#!/usr/bin/env python
#
# Copyright 2009, Ubixum, Inc
#
# This file copied and modified for fx2lib from the GnuRadio project
#
# Copyright 2004,2006 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU G... |
from unicodedata import name
import jmespath
from util.logger import get_logger
from util.decoder import decode
class TransactionTransformer:
def __init__(self) -> None:
self.logger = get_logger(__name__)
@staticmethod
def transform(raw_transactions):
payloads = jmespath.search('[*].payl... |
# Band service skeleton
# (c) Dmitry Rodin 2018
# ---------------------
# this file is a reqular python module requirement
# обязательный для python файл модуля.
from . import main
|
"""DID Document and resource builders."""
from typing import Iterator, List, Optional, Type, Union
from ..did import DID
from ..did_url import DIDUrl
from ..service import DIDCommService, Service
from ..verification_method import VerificationMethod
from .doc import DIDDocument
def _default_id_generator(base: str, s... |
class Solution(object):
def poorPigs(self, buckets, minutesToDie, minutesToTest):
"""
:type buckets: int
:type minutesToDie: int
:type minutesToTest: int
:rtype: int
"""
# 一只猪鉴定5桶,2两只猪一只喝行一只喝列能喝25桶,三只猪一只行一只列一只面
# 真无聊什么鬼题
# 什么有毒猪种还从0开始没有猪哪里能鉴定
... |
from ToastNotifier import ToastNotifier
import time
import poplib
from email.parser import Parser
from email.header import decode_header
import webbrowser
import os
import base64
_uidl = '' #留空就行
email = 'xxxxxxxxx@163.com' #邮箱地址
password = '' #密码
host = 'pop.163.com' #邮箱服务器地址
sleep = 15 * 60 # 读取间隔 单位 s,官... |
import unittest
import subprocess
import re
def trycredentials(user, pwd):
proc = subprocess.Popen(
['python', '01.py'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
outs, errs = proc.communicate('%s\n%s\n' % (user, pwd))
return ou... |
from guy import Guy,http
class T(Guy):
__doc__="""<script>
async function storage(mode) {
switch(mode) {
case "get":
return localStorage["var"]==42;
case "set":
localStorage["var"]=42;
return true
default:
... |
class SinglyLinkedList:
def __init__(self):
self.head = None
self.len = 0
def add(self, item):
if not self.head:
self.head = ListNode(item)
else:
p = ListNode(item)
p.next = self.head
self.head = p
self.len += 1
def r... |
# Copyright (c) 2017, 2018, Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for details.
import p... |
class Solution:
def snakesAndLadders(self, board: List[List[int]]) -> int:
# this is a bfs
def num_to_rc(num):
N = len(board)
num -= 1
r, c = divmod(num, N)
if r % 2:
c = N - 1 - c
r = N - 1 - r
return r, c
... |
import sys
__author__ = 'South Mountain'
def p2(n):
"""
Each new term in the Fibonacci sequence is generated by adding the previous
two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose valu... |
import os
import df2img
import disnake
import pandas as pd
from PIL import Image
import discordbot.config_discordbot as cfg
from discordbot.config_discordbot import logger
from discordbot.helpers import autocrop_image
from gamestonk_terminal.economy import wsj_model
async def currencies_command(ctx):
"""Currenc... |
# Generated by Django 3.1.8 on 2021-04-26 16:02
from django.db import migrations, models
import django.db.models.deletion
def set_primary_groups(apps, schema_editor):
Organization = apps.get_model("organizations", "Organization")
ResponsibleGroup = apps.get_model("permissions", "ResponsibleGroup")
for o... |
from .accuracy import accuracy
from .compose import compose
from .fftconv2d import fft_conv2d, FFTConv2d
|
from cStringIO import StringIO
import collections
import logging
import time
from urlparse import urljoin
from xml.etree import ElementTree
import recurly
from recurly import Account, AddOn, Adjustment, BillingInfo, Coupon, Plan, Redemption, Subscription, SubscriptionAddOn, Transaction
from recurly import Money, NotFo... |
from os import walk
from os.path import join
from knot_a_rumor.story import Story, Scene
class Knot:
def __init__(self, path):
self.path = path
def stories(self):
return next(walk(self.path))[1]
def get_story(self, name):
story = Story(self.build_story_path(name))
story.lo... |
import os
import json
import unittest
from unittest import mock
from unittest.mock import ANY
import logging
from logging import handlers, LogRecord
from typing import Tuple, Optional, Dict
from tests.util.config_mixin import ConfigMixin
from backee.model.web_handler import WebHandler
from backee.model.max_level_filt... |
#!/usr/bin/env python3
#
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import json
import sys
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages as pdfp
... |
"""endpoint"""
BROKER_URL = 'amqp://user:pass@broker.com:15672/'
|
""" Calculator module main entry-point.
"""
from calculator.controller import MainController
controller = MainController()
controller.main()
|
# BSD 3-Clause License; see https://github.com/scikit-hep/uproot4/blob/main/LICENSE
from __future__ import absolute_import
import numpy
import pytest
import skhep_testdata
import uproot
def test():
with uproot.open(skhep_testdata.data_path("uproot-Zmumu.root")) as f:
for arrays in f["events"].iterate(
... |
"""
Common tools that are useful for neo.io object tests
"""
import os
import shutil
from neo.core import Block, Segment
from neo.test.generate_datasets import generate_from_supported_objects
def close_object_safe(obj):
"""
Close an object safely, ignoring errors
For some io types the file should be cl... |
from base64 import b64decode
from cryptography.hazmat.backends import default_backend
from cryptography.x509 import load_der_x509_certificate
from django.conf import settings
import jwt
from lxml import etree
import requests
from urllib import urlencode
AUTHORITY = getattr(settings, 'AAD_AUTHORITY', 'https://login.mi... |
from Data.Utils.custom_dataset import CustomDataset as CD
import matplotlib.pyplot as plt
# prova della classe custom_dataset
dataset = CD('Data/Datasets','training')
#__GetItem__(index)
sample = dataset[4]
print(type(sample['image']),type(sample['label']))
|
import sys
import json
import os
import errno
import subprocess
import platform
import pathlib
def getNeedsUpdate(scriptFile, libraryFile, sourceFile, directory, pattern):
referenceChangeTime = os.path.getmtime(scriptFile)
libraryChangeTime = os.path.getmtime(libraryFile)
if libraryChangeTime > referenceCh... |
from .cord_19_data import CORD19Data |
from django.contrib.admin.views.main import (
ChangeList, IGNORED_PARAMS as BASE_IGNORED_PARAMS
)
from django.core.paginator import InvalidPage
from django.contrib.admin.options import IncorrectLookupParameters
from django.db.models import Count, F, Q
from django.db.models import Exists
from django.db.models import... |
# A class in Python is template
# to define class
class Name:
pass
# A class must be instantiated. In other words, we must create an instance of the class, in order to breathe life into the schematic.
# Instantiating a class looks a lot like calling a function. We would be able to create an instance of our defin... |
from PIL import Image
import numpy as np
from OpenGL.GL import *
from os import path
def MTL(filename, withtextures=True):
contents = {}
mtl = None
fpath = ""
if filename.rfind("/") != -1:
fpath = filename[:filename.rfind("/")+1]
for line in open(filename, "r"):
if line... |
#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2009 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
"""
Project:
glideinWMS
Description:
unit test for glideinwms/creation/lib/cvWCreate.py
Author:
Dennis Box <dbox@fnal.gov>
"""
import os
import unittest
from unittest import mock
imp... |
"""WSGI script for the marsha project."""
from configurations.wsgi import get_wsgi_application
application = get_wsgi_application() # pylint: disable=invalid-name
|
import http.client
import json
server_key = '<server key>';
client_token = '<token received by client>';
notification = {
'title': 'Hello world',
'body': 'This is a very long message',
'icon': 'firebase-logo.png',
'click_action': 'http://localhost:8081'
}
headers = {
'Authorization': 'key=' + server... |
from hypothesis import given
from hypothesis import example
from hypothesis import assume
from hypothesis import strategies as st
from hypothesis.extra.numpy import arrays
import pytest
import numpy as np
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import os.path
import time
import tempfile
import tensorflow as tf
import StringIO
import random
import string
import mmap
from tensorflow.python.platform import gfile
from tensorflow.python.platform import tf_logging as logging
from google.protobuf import tex... |
# automation package
__version__ = "0.00.02"
|
from django.http import HttpResponseRedirect
def responsive_switch(request,action):
if action=="go":
request.session['desktop_mode']=True
elif action=="leave":
request.session['desktop_mode']=False
return HttpResponseRedirect(request.META.get("HTTP_REFERER", ""))
|
import itertools
import numpy as np
from matplotlib.cm import get_cmap
from bridge_sim.model import Config, Point
from bridge_sim.sim import without
from bridge_sim.sim.build import get_bridge_nodes, get_bridge_shells
from bridge_sim.sim.model import BuildContext, Node, Shell, SimParams
from lib.plot import default_... |
import json
def getGrch38():
with open("grch38_utr3.json") as infile:
grch38_utr3 = json.load(infile)
return grch38_utr3
def getIdconverter():
with open("/home/fux/fux/miRNASNP3/test_let_7a_3p/ID_convert.jaon") as infile:
id_convert = json.load(infile)
return id_convert
def ou... |
#ex077: Crie um programa que tenha uma tupla com várias palavras (não usar acentos). Depois disso, você deve mostrar, para cada palavra, quais são as suas vogais.
#NÃO CONSEGUI FAZER
a = '\033[1;33m'
v = '\033[1;32m'
l = '\033[m'
palavras = ('abacaxi', 'tomate', 'uva', 'morango', 'melancia', 'coco', 'cenoura', 'mirti... |
from metaphor.common.cli import cli_main
from .extractor import LookerExtractor
if __name__ == "__main__":
cli_main("Looker metadata extractor", LookerExtractor)
|
import os.path
import tensorflow as tf
from datetime import datetime
import models
import data
FLAGS = tf.flags.FLAGS
tf.flags.DEFINE_string("summaries_dir", "/home/uai/tf_logs/ic_fcn", "Path to the tensorboard logs directory.")
#tf.flags.DEFINE_string("summaries_dir", "C://Temp/tf_logs/ic_fcn", "Path to the tensorbo... |
import numpy as np
import scipy.sparse as sp
import warnings
import properties
from . import Utils
from . import Maps
from . import Mesh
from . import ObjectiveFunction
from . import Props
from .Utils import mkvc, speye, sdiag, kron3
__all__ = [
"SimpleSmall",
"SimpleSmoothDeriv",
"Simple",
"Small",
... |
from flask import Flask, jsonify, request
from flask_restful import Api, Resource
from pymongo import MongoClient
import bcrypt
import logging
logging.basicConfig(level=logging.DEBUG,format='%(asctime)s [%(levelname)s] [%(filename)s:%(lineno)d] [%(thread)d] - %(message)s',datefmt='%d/%m/%Y %H:%M:%S',filename='flask.log... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""
Implements the Generalized R-CNN framework
"""
import torch
from torch import nn
from maskrcnn_benchmark.structures.image_list import to_image_list
from ..backbone import build_backbone
from ..rpn.rpn import build_rpn
from ..roi_heads.roi_he... |
from selenium.webdriver.common.by import By
class LoginPageLocators:
USER_NAME_INPUT = (By.NAME, "email")
PASSWORD_INPUT = (By.NAME, "password")
H1 = (By.TAG_NAME, "H1")
LOGIN_BUTTON = (By.NAME, "login")
class NavigationLocators:
LOG_OUT_LINK = (By.XPATH, "//button[text()='Sign out']")
class H... |
from .alexnet import AlexNet
from .lenet import LeNet5
from .mobilenet_v2 import MobileNetV2
from .mobilenet_v3 import MobileNetv3
from .regnet import RegNet
from .resnest import ResNeSt
from .resnet import ResNet, ResNetV1d
from .resnet_cifar import ResNet_CIFAR
from .resnext import ResNeXt
from .seresnet import SERes... |
"""
Service-related Mongoengine document definitions
"""
import mongoengine
from mongoengine import (
EmbeddedDocumentField,
EmbeddedDocumentListField,
ListField,
ReferenceField,
StringField,
UUIDField,
)
from gatekeeper.models.base import TimestampsDocument, UserIdMixin, UuidDocument
from gat... |
import os
from os import path
from zipfile import ZipFile
import cv2
from glob import glob
from tqdm import tqdm
import numpy as np
import shutil
FOLDER_NAME = "DATA/"
def __is_picture(file):
"""
It returns whether the processed file is a jpg picture or not.
All arguments must be of equal length.
:pa... |
import unittest
class TestImport(unittest.TestCase):
def test_import_general(self):
import jellylamp
def test_import_version(self):
from jellylamp import __version__
print(__version__)
if __name__ == '__main__':
unittest.main()
|
import numpy as np
n = tuple(map(int, input().strip().split()))
print(np.zeros(n, int))
print(np.ones(n, int)) |
def update_dict(params, keys, value):
if len(keys) == 1:
params[keys[0]] = value
else:
update_dict(params[keys[0]], keys[1:], value)
def flatten(list):
return [item for sublist in list for item in sublist]
|
"""Test hook for verifying the consistency and integrity of collection and index data."""
import os.path
from buildscripts.resmokelib.testing.hooks import jsfile
class ValidateCollections(jsfile.PerClusterDataConsistencyHook):
"""Run full validation.
This will run on all collections in all databases on eve... |
from __future__ import annotations
from typing import Dict, Union, Any, Sequence
import collections
import boto3
from .enums import BILLING_MODE, RETURN_VALUES, DATATYPE, STREAM_VIEW, SSE_TYPE
dynamodb = boto3.resource("dynamodb")
class KeyDefinition:
DATATYPE = DATATYPE
name: str
datatype: DATATYPE
... |
import argparse
import json
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-dev', type=str, default='../data/dev_toy.tsv')
parser.add_argument('-res', type=str, default='../results/cknrm_ca.trec')
parser.add_argument('-k', type=int, default=2)
args = parser.parse_args()
sc... |
from onegov.agency import AgencyApp
from onegov.agency.layout import PageLayout
from onegov.core.security import Public
from onegov.org.models import Topic
from onegov.org.views.page import view_topic as view_topic_base
@AgencyApp.html(model=Topic, template='topic.pt', permission=Public)
def view_topic(self, request)... |
################################################################################
from relative_to_absolute_path import get_absolute_path
from squares_ids import get_id_to_square_dict
from os.path import exists
import numpy as np
import tkinter as tk
from PIL import Image, ImageTk
######################################... |
## These are the mask bits in ANYMASK / ALLMASK.
#
# From: http://www.noao.edu/noao/staff/fvaldes/CPDocPrelim/PL201_3.html
# 1 -- detector bad pixel InstCal
# 1 -- detector bad pixel/no data Resampled
# 1 -- No data Stacked
# 2 -- saturated InstCal/Resampled
... |
import math
import numpy as np
import calculator
class ball:
'''
class used to define the balls involved in the simulation.
This class is used by all of the other classes:
- calculator.py uses the update functions (euler_update, cromer_update, and runge_kutta2) to update the positions and v... |
class Deque:
def __init__(self):
self.items = []
def empty(self):
return len(self.items) == 0
def append(self, item):
self.items.append(item)
def pop(self):
if self.empty(): raise Exception
return self.items.pop()
def append_lef... |
#!/usr/bin/env python
# coding: utf-8
import gzip
import json
import logging
import os
import tarfile
import time
from datetime import datetime
from functools import partial, reduce
from glob import glob
from typing import Callable, Dict, List, Type
import numpy as np
import pandas as pd
import seaborn as sns
import t... |
# coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
"""
Functions for performing numerical differentiation.
"""
import numpy as np
from scipy import signal
def differentiate(
X, t, diff_method="forward difference", smoother=None, window_length=35
):
"""
Approximate the derivative of set of 1D data points using finite
difference methods
Parameters... |
"""
Censor 3 ----> CENSOR 2
Designed to be run by the evaluator.
TCP Censor that synchronizes on first SYN only, works 100% of the time, sends 5 RSTs to
server AND client.
"""
import logging
import netifaces
import layers.packet
# Disable scapy ::1 warnings
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)... |
import pandas as pd
import numpy as np
from python_nw import newey
from scipy.stats import f
from scipy.stats import chi2
def ap_FMB(mr,mf):
# Initialize
dT, dN = mr.shape
dT, dK = mf.shape
valpha = np.empty((dN,1))
mbeta = np.empty((dN,dK))
mresid =np.empty((dT,dN))
mlambda_t = np.empty... |
"""
zeep.xsd
--------
"""
from zeep.xsd.const import SkipValue # noqa
from zeep.xsd.elements import * # noqa
from zeep.xsd.schema import Schema # noqa
from zeep.xsd.types import * # noqa
from zeep.xsd.types.builtins import * # noqa
from zeep.xsd.valueobjects import * # noqa
|
"""
Main script for training and evaluating a TCN on a multi-step forecasting task.
You can chose bewteen:
- Running a simple experiment
- Running multiple experiments trying out diffrent combinations of hyperparamters (grid-search)
"""
import warnings
warnings.filterwarnings(action='ignore')
from keras.callba... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.