text stringlengths 1 927k |
|---|
from __future__ import print_function
import sys
if sys.version_info >= (2, 7):
import unittest
else:
import unittest2 as unittest
import copy
import inspect
import json
import os
import socket
import tempfile
import time # remove once file hash fix is committed #2279
import subprocess
from .. import lib
from... |
import tiledb
from tiledb_cli.root import root
from tiledb_cli.convert_from import parse_kwargs
from click.testing import CliRunner
import os
import numpy as np
import pandas as pd
import pytest
@pytest.fixture(autouse=True, scope="session")
def create_test_simple_csv(temp_rootdir):
"""
Create a simple dense... |
import os
import pytest
import time
from linenotipy import Line
@pytest.fixture(scope="module", autouse=True)
def scope_module():
token = os.environ["line_notify_token"]
yield Line(token=token)
@pytest.fixture(scope="function", autouse=True)
def line(scope_module):
time.sleep(1)
yield scope_module
... |
# coding: utf-8
#
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "lice... |
import csv
import os
# csv文件路径
path = './csv/'
# 定义数据清洗函数data_wash, 接收filename[文件名], la_max[最大纬度], ln_max[最大精度]参数,
def data_wash(filename, la_max, ln_max):
# 定义csv文件和写入器,用于保存生成的csv文件,保存的文件名为:原文件文件名+_output
csv_out_file = open(path + filename + '_output', 'w')
csv_writer = csv.writer(csv_out_file)
# ... |
import os
import typer
from streamdeck_manager.core import Core
def end_sample_callback():
exit(0)
def main(asset_path: str=os.path.join(os.path.dirname(__file__), "..", "assets"),
photo: str="Harold.jpg"):
core = Core()
if len(core.streamdecks) <= 0:
print("Not Stream deck found")
... |
from nonebot import export
@export()
def test():
... |
# coding: utf-8
import loggus
if __name__ == '__main__':
logger1 = loggus.NewLogger()
logger1.SetFormatter(loggus.JsonFormatter)
logger1.info("logger1 output json")
logger2 = loggus.NewLogger()
logger2.info("but logger2 is text") |
#!/usr/bin/env python
"""
Copyright (c) 2014-2020 Maltrail developers (https://github.com/stamparm/maltrail/)
See the file 'LICENSE' for copying permission
"""
from core.common import retrieve_content
__url__ = "https://lists.blocklist.de/lists/all.txt"
__info__ = "known attacker"
__reference__ = "blocklist.de"
def... |
import copy
from functools import partial
from collections import OrderedDict
import torch
from torch import nn
from efficientnetv2 import get_efficientnet_v2_structure
from efficientnetv2 import load_from_zoo
class ConvBNAct(nn.Sequential):
"""Convolution-Normalization-Activation Module"""
def __init__(sel... |
"""
Super32 Emulator
"""
import logging
from logging import NullHandler
logging.getLogger(__name__).addHandler(logging.NullHandler()) |
'''
API for rank order clustering documents.
'''
import itertools
import pathlib
from collections import Counter, defaultdict
from enum import Enum
from typing import List, Optional
import numpy as np
import uvicorn
from fastapi import Body, FastAPI, HTTPException
from loguru import logger
from nltk import FreqDi... |
N, *a = map(int, open(0).read().split())
d = {}
for i, j in enumerate(sorted(set(a))):
d[j] = i
for e in a:
print(d[e]) |
from random import randint, seed
from time import time
def game():
print('Welcome to WAR V2!')
print()
asking = True
while asking:
try:
players = int(input('How many players are there? '))
if players < 2:
print('There must be at least two players.')
... |
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
"""
mfdrn module. Contains the ModflowDrn class. Note that the user can access
the ModflowDrn class as `flopy.modflow.ModflowDrn`.
Additional information for this MODFLOW package can be found at the `Online
MODFLOW Guide
<http://water.usgs.gov/ogw/modflow/MODFLOW-2005-Guide/index.html?drn.htm>`_.
"""
import sys
impo... |
import collections
import inspect
import logging
from typing import (
Any,
Callable,
Dict,
Optional,
Tuple,
Union,
overload,
)
from fastapi import APIRouter, FastAPI
from starlette.requests import Request
from uvicorn.config import Config
from uvicorn.lifespan.on import LifespanOn
from ray... |
from __future__ import print_function, division
from neuralnilm import Net, RealApplianceSource, BLSTMLayer, SubsampleLayer, DimshuffleLayer
from lasagne.nonlinearities import sigmoid, rectify
from lasagne.objectives import crossentropy
from lasagne.init import Uniform, Normal
from lasagne.layers import LSTMLayer, Dens... |
import copy
from mongoengine.errors import InvalidQueryError
from mongoengine.python_support import product, reduce
from mongoengine.queryset import transform
__all__ = ('Q',)
class QNodeVisitor(object):
"""Base visitor class for visiting Q-object nodes in a query tree.
"""
def visit_combination(self,... |
from tweetengine import model
from google.appengine.api import users
def setConfiguration():
account_name='tweet_engine'
password='passwd'
oauth_key='fookey'
oauth_secret='foosecret'
conf = model.Configuration.instance()
conf.oauth_key = oauth_key
conf.oauth_secret = oauth_secret
con... |
from django import forms
from ticketing.models import Customer, Employee, Movie_comment, Cinema_comment
class MovieCommentForm(forms.ModelForm):
"""电影评价的表单"""
class Meta:
model = Movie_comment
fields = ['comment', 'score']
labels = {'comment': '评论', 'score': '评分'}
widgets = {'... |
_base_ = '../_base_/default_runtime.py'
# model settings
img_size = 550
classes=('Small 1-piece vehicle',
'Large 1-piece vehicle',
'Extra-large 2-piece truck')
model = dict(
type='YOLACT',
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices... |
import covasim as cv
import covasim.utils as cvu
import optuna as op
import sciris as sc
import pandas as pd
import numpy as np
import os
from collections import defaultdict
import population
## Interesting part starts around line 200
## First part is setup, optimization workers and alike - Important to run before ana... |
#!/usr/bin/env python3
import argparse
import json
import numpy
import os
import random
import re
import subprocess
import sys
import time
args = None
logFile = None
unlockTimeout = 999999999
fastUnstakeSystem = './fast.refund/dccio.system/dccio.system.wasm'
systemAccounts = [
'dccio.bpay',
'dccio.msig',
... |
import tensorflow as tf
import numpy as np
from problems.problem import *
name = "center inpainting"
g_tf_info_placeholder = tf.placeholder(tf.float32, [None], name='g_transform_info')
def problem_loss(x_tformed, g_tformed):
return tf.reduce_mean(tf.abs(x_tformed-g_tformed),[1,2,3])
def merge(g_output,... |
import requests
from bs4 import BeautifulSoup
from .handler import add_handler
@add_handler(r'https://arxiv.org/abs/(\d+.\d+)')
def download(url):
metadata = dict()
metadata['importer'] = 'arxiv'
data = requests.get(url)
soup = BeautifulSoup(data.text, "lxml")
authortags = soup.find_all("meta", a... |
from onmt.modules.GlobalAttention import GlobalAttention
from onmt.modules.ImageEncoder import ImageEncoder
from onmt.modules.BaseModel import Generator, NMTModel
from onmt.modules.LayerNorm import LayerNorm
from onmt.modules.StaticDropout import StaticDropout
# For flake8 compatibility.
__all__ = [GlobalAttention, Im... |
import os
import pygame
import time
import random
import glob
import math
last_point = []
class LFO : #uses three arguments: start point, max, and how far each step is.
def __init__(self, start, max, step):
self.start = start
self.max = max
self.step = step
self.current = 0
... |
"""
@author Mayank Mittal
@email mittalma@ethz.ch
@brief Defines sampling stratergies.
# TODO: These functions are generic. Can put in leibnizgym.utils.torch_utils module.
"""
# leibnizgym
from leibnizgym.utils.torch_utils import quaternion_from_euler_xyz
# python
from typing import Union, List, Tuple
i... |
import FreeCAD
import FreeCADGui
from app import section_vector_renderer
from PySide2 import QtGui, QtCore, QtWidgets
SVG_TEMPLATE = """<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www... |
# Copyright 2020 IBM Corporation
#
# 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, ... |
from django.apps import AppConfig
class MeetingschedConfig(AppConfig):
name = 'meetingsched' |
import numpy as np
import pandas as pd
from six import viewvalues
from toolz import groupby, merge
from .base import PipelineLoader
from .frame import DataFrameLoader
from zipline.pipeline.common import (
EVENT_DATE_FIELD_NAME,
SID_FIELD_NAME,
TS_FIELD_NAME,
)
from zipline.pipeline.loaders.utils import (
... |
import requests
import io
from datetime import timedelta
import pandas as pd
from stolgo.helper import get_date_range,get_formated_dateframe
from stolgo.request import RequestUrl,Curl
#default params for url connection
DEFAULT_TIMEOUT = 5 # seconds
MAX_RETRIES = 2
#default periods
DEFAULT_DAYS = 250
class NasdaqUrl... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... |
import logging
import re
import string
import struct
from collections import defaultdict
from itertools import count
import capstone
import cffi
import cle
import networkx
import pyvex
from . import Analysis
from ..knowledge_base import KnowledgeBase
from ..sim_variable import SimMemoryVariable, SimTemporaryVariable
... |
#(C) Copyright Syd Logan 2020
#(C) Copyright Thousand Smiles Foundation 2020
#
#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 a... |
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/stable/config
# -- Path setup ------------------------------------------------------------... |
from .crossover import NullCrossover, SBXCrossover, SPXCrossover, DifferentialEvolutionCrossover, IntegerSBXCrossover
from .mutation import NullMutation, BitFlipMutation, PolynomialMutation, IntegerPolynomialMutation, UniformMutation, \
SimpleRandomMutation
from .selection import BestSolutionSelection, BinaryTourna... |
from django.conf.urls import include, url
from django.contrib import admin
from bootstrap_message import views
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', views.index, name='index'),
] |
# Largest sub array problem
def kadane_algorithm(arr: list) -> int:
l = len(arr)
maxhere = arr[0]
maxoutput = 0 # For getting the max subarray value
for i in range(1,l):
# If adding the element to prev max is greater or the current number is greater
maxhere = max(arr[i], arr[i] +... |
"""Dataset setting and data loader for MNIST."""
import torch
from torchvision import datasets, transforms
import os
def get_mnist(dataset_root, batch_size, train):
"""Get MNIST datasets loader."""
# image pre-processing
pre_process = transforms.Compose([transforms.Resize(28), # different img size settin... |
def set_bar(pbar, t, last_ess, ess, acceptance_ratio, resample_status):
pbar.set_description("Step number: {:2d} | Last ess: {:8.2f} | "
"Current ess: {:8.2f} | Samples accepted: "
"{:.1%} | {} |"
.format(t + 1, last_ess, ess, acceptance_rat... |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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 applicab... |
import time
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from rest_framework import viewsets
from rest_framework.exceptions import AuthenticationFailed
from attendees.occasions.serializers import GatheringSerializer
from attendees.occasions.services im... |
# Copyright (c) 2016 Presslabs SRL
#
# 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 writ... |
#!/usr/bin/env python3
import argparse
import random
import torch
from torch import nn, optim
from torch.nn import functional as F
from tqdm import tqdm
import learn2learn as l2l
class Net(nn.Module):
"""Head for sentence-level classification tasks."""
def __init__(self, num_classes, input_dim=768, inner_... |
import unittest
from User import User
class TestUser(unittest.TestCase):
def setUp(self):
self.new_user = User("John","Paul")
def tearDown(self):
'''
clean up after each test to prevent errors
'''
User.userList = []
#2nd test
def test__init(self):
... |
from contextlib import contextmanager
from os import environ
import pytest
external_dependency_management = pytest.mark.skipif(
not environ.get('GALAXY_TEST_INCLUDE_SLOW'),
reason="GALAXY_TEST_INCLUDE_SLOW not set"
)
@contextmanager
def modify_environ(values, keys_to_remove=None):
"""
Modify the env... |
import setuptools
import re
# Version control --------
VERSIONFILE="imagesc/__init__.py"
getversion = re.search( r"^__version__ = ['\"]([^'\"]*)['\"]", open(VERSIONFILE, "rt").read(), re.M)
if getversion:
new_version = getversion.group(1)
else:
raise RuntimeError("Unable to find version string in %s." % (VERSI... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from datetime import timedelta
from django.utils import timezone
from sentry.models import GroupRuleStatus, Rule
from sentry.plugins.base import plugins
from sentry.testutils import TestCase
from sentry.rules.processor import EventCompatibilityProxy, Rul... |
"""This module provides AdaHandler, an implementation of ETLHandler for ADA."""
import logging
import requests
from fractalis.data.etlhandler import ETLHandler
logger = logging.getLogger(__name__)
class AdaHandler(ETLHandler):
"""This ETLHandler provides integration with ADA.
'Ada provides key infrastru... |
import numpy as np
import pandas as pd
from typing import Tuple, Union
from pymarket.bids import BidManager
def demand_curve_from_bids(
bids: pd.DataFrame) -> Tuple[np.ndarray, np.ndarray]:
"""
Creates a demand curve from a set of buying bids.
It is the inverse cumulative distribution of quantity
... |
from flask import Flask, jsonify, request
from flask_limiter import Limiter
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_restful import Api
from flask_cors import CORS
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///acab.db'
db = SQLAlchemy(app)
... |
# coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 7
Contact: sdk@isilon.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from isi_sdk_8_2_0.models.compati... |
#!/usr/bin/env python3
# man sudo(8)
# -A, --askpass
# Normally, if sudo requires a password, it will read it from
# the user's terminal. If the -A (askpass) option is
# specified, a (possibly graphical) helper program is executed
# to read the... |
from models.main import *
from models.appendix import *
from flask import Blueprint, request, render_template
from flask_jwt_extended import (jwt_required, get_jwt_identity)
from flask_jwt_extended import create_access_token, decode_token
from .utils import tryCommit
from datetime import datetime, timedelta
from sqlalc... |
from decimal import Decimal
from unittest.mock import MagicMock, Mock, patch
import pytest
from prices import Money, TaxedMoney
from ...core.weight import zero_weight
from ...discount import OrderDiscountType
from ...discount.models import (
DiscountValueType,
NotApplicable,
Voucher,
VoucherChannelLis... |
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2017-10-10 15:38
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('cms', '0031_migrate_projects_2'),
]
operations = [
migrations.RemoveField(
... |
import numpy as np
from VariableUnittest import VariableUnitTest
from gwlfe.BMPs.AgAnimal import NRUNCON
class TestNRUNCON(VariableUnitTest):
def test_NRUNCON(self):
z = self.z
np.testing.assert_array_almost_equal(
NRUNCON.NRUNCON_f(z.NYrs, z.GrazingAnimal_0, z.NumAnimals, z.AvgAnima... |
"""Abstractions for the axes of a liquid-handling robot."""
# Standard imports
import logging
from abc import abstractmethod
# Local package imiports
from lhrhost.protocol.linear_actuator import Receiver as LinearActuatorReceiver
from lhrhost.util.containers import add_to_tree, get_from_tree
from lhrhost.util.files i... |
#!/usr/bin/env python
import os
import re
f = os.popen('who', 'r')
for eachLine in f:
print re.split('\s\s+|\t', eachLine.rstrip())
f.close() |
# -*- coding: utf-8 -*-
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.forms import inlineformset_factory
from djangosige.apps.compras.models import OrcamentoCompra, PedidoCompra, ItensCompra, Compra
class CompraForm(forms.ModelForm):
def __init__(self, *args, **kw... |
import pickle
import numpy as np
from typing import List
from fastapi import FastAPI
from pydantic import BaseModel, conlist
# rev 1
app = FastAPI(title="Predicting Wine Class with batching")
# Open classifier in global scope
with open("models/wine-95-fixed.pkl", "rb") as file:
clf = pickle.load(file)
class Wi... |
"Base Cache class."
import warnings
from django.core.exceptions import ImproperlyConfigured, DjangoRuntimeWarning
from django.utils.encoding import smart_str
from django.utils.importlib import import_module
class InvalidCacheBackendError(ImproperlyConfigured):
pass
class CacheKeyWarning(DjangoRuntimeWarning):
... |
#!/usr/bin/env python
# coding=utf-8
"""
#************************************************
# Copyright 2018 Fortinet, 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.apa... |
# -*- coding: utf-8 -*-
#
# Emit documentation build configuration file, created by
# sphinx-quickstart on Thu Jan 3 19:10:48 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All co... |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
# Datos de cada museo:
# ID-ENTIDAD (PK), NOMBRE, DESCRIPCION-ENTIDAD, HORARIO, TRANSPORTE, ACCESIBILIDAD, CONTENT-URL, LOCALIZACION{NOMBRE-VIA, CLASE-VIAL, TIPO-NUM, NUM, LOCALIDAD, PROVINCIA, CODIGO-POSTAL, BARRIO,... |
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
import logging
# 로그 생성
logger = logging.getLogger()
# 로그의 출력 기준 설정
logger.setLevel(logging.INFO)
# log 출력 형식
formatter = logging.Formatter('[%(asctime)s][%(filename)s-%(funcName)s:%(lineno)d][%(levelname)s] - %(message)s')
# log 출력
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logg... |
# vim: ft=python fileencoding=utf-8 sw=4 et sts=4
"""Fail functions because called from wrong mode test for vimiv's test suite."""
from unittest import main
from vimiv_testcase import VimivTestCase
class FailingModeTest(VimivTestCase):
"""Failing Mode Tests."""
@classmethod
def setUpClass(cls):
... |
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
from kivmob import KivMob
import kivy.utils
from kivy.app import App
from kivy.lang import Builder
from kivy.config import Config
from kivy.properties import ListProperty
from kivy.utils import platform
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.boxlayout ... |
from Camera import CameraController
import time
import cv2
class CameraStream:
def __init__(self, resolution=(320,240), framerate=32):
self.stream = CameraController()
def start(self):
return self.stream.start()
def stop(self):
return self.stream.stop()
def display(self):
end_time = time.time() + 10
... |
# Generated by Django 3.2.4 on 2021-07-06 18:59
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
... |
import torch.nn as nn
from torch.nn import functional as F
from utils import get_mask_from_lengths
from embedding import GaussianEmbedding
from quartznet import QuartzNet5x5, QuartzNet9x5
from module import MaskedInstanceNorm1d, StyleResidual, Postnet
class GraphemeDuration(nn.Module):
def __init__(self, idim, ... |
# Test cases for Device Provisioning Protocol (DPP)
# Copyright (c) 2017, Qualcomm Atheros, Inc.
# Copyright (c) 2018-2019, The Linux Foundation
#
# This software may be distributed under the terms of the BSD license.
# See README for more details.
import base64
import binascii
import hashlib
import logging
logger = l... |
#
#
#
from __future__ import absolute_import, division, print_function, \
unicode_literals
from os import environ
from os.path import dirname, join
from six import text_type
from unittest import TestCase
from octodns.record import Record
from octodns.manager import _AggregateTarget, MainThreadExecutor, Manager, ... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** 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
from ... import _utilities, _tables
from... |
# -*- coding: utf-8 -*-
"""
meraki_sdk
This file was automatically generated for meraki by APIMATIC v2.0 ( https://apimatic.io ).
"""
class Type5Enum(object):
"""Implementation of the 'Type5' enum.
One of "delete" or "restrict processing"
Attributes:
DELETE: TODO: type description here... |
#!/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
Thanks to ga2arch for help with IS_IN_DB and IS_NOT_IN_DB on GAE
"""
import os
import re
import datetime
impor... |
import pandas as pd
import os
import matplotlib.pyplot as plt
import numpy as np
#location for files and plots
PLOT_DIR = "../plots/"
DATA_DIR = "../data"
FILENAME_PLOT = 'SGD_alphas'
PLOT_DIR = "./"
#figure size and resolution
fig = plt.figure()
plt.style.use("seaborn")
#colour, linewith, linestyle
#boundaries
... |
"""
Functions for actions pertaining to history files.
"""
from CIME.XML.standard_module_setup import *
from CIME.test_status import TEST_NO_BASELINES_COMMENT, TEST_STATUS_FILENAME
from CIME.utils import get_current_commit, get_timestamp, get_model, safe_copy, SharedArea, parse_test_name
import logging, os, re, filecm... |
import re
from datetime import datetime
from enum import Enum
from typing import List
from configurable_automation import ConfigurableAutomation
from lib.actions import Action
from lib.core.component import Component
from lib.helper import to_float, to_datetime
CHECKER_RESULT_CACHE = {}
class Checker(Component):
... |
#####################################################################
# #
# /example.py #
# #
# Copyright 2013, Monash University ... |
########################################################################
#
# Copyright 2015 Johns Hopkins University
#
# 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... |
import binascii
print("#include <string>");
print("unsigned char rawData[] = {");
with open('serpent.py', 'rb') as f:
for chunk in iter(lambda: f.read(1), b''):
print("0x" + str(binascii.hexlify(chunk),'ascii') + ",");
print("};");
print("std::string data((char*)&rawData[0], sizeof(rawData));"); |
import tempfile
import argparse
import logging
import datetime
import threading
import os
import re
from botocore.exceptions import ClientError
from ocs_ci.framework import config
from ocs_ci.ocs.constants import CLEANUP_YAML, TEMPLATE_CLEANUP_DIR
from ocs_ci.ocs.exceptions import CommandFailed
from ocs_ci.utility.u... |
from tensorflow.python.lib.io import file_io
import h5py
import numpy as np
class Dataset:
def __init__(self, path, local):
"""
Initialize the dataset
:param path: Path to the hdf5 dataset file
:param local: True if the path is to a local file, False otherwise
"""
... |
from typing import List, Tuple
import logging
import pytest
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s test %(levelname)s: %(message)s",
datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger("ambassador")
from ambassador import Cache, IR
from ambassador.compile import Compile
def ... |
# -*- coding: utf-8 -*-
# Copyright (c) 2020 Nekokatt
# Copyright (c) 2021-present davfsa
#
# 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 t... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import re
import unittest
import traceback
from fasttest_selenium.common import *
class TestCase(unittest.TestCase):
def __getattr__(self, item):
try:
return self.__getattribute__(item)
except:
attrvalue = None
... |
"""
https://projecteuler.net/problem=5
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
"""
from numpy import prod
from Common.Logger import get_logger, init_logg... |
# Note: This Queue class is sub-optimal. Why?
class Queue():
def __init__(self):
self.queue = []
def enqueue(self, value):
self.queue.append(value)
def dequeue(self):
if self.size() > 0:
return self.queue.pop(0)
else:
return None
def size(self):
... |
from typing import Dict, Union
import os
import hither2 as hi
import kachery_client as kc
import numpy as np
import spikeextractors as se
from sortingview.extractors import LabboxEphysSortingExtractor, LabboxEphysRecordingExtractor
from .SubsampledSortingExtractor import SubsampledSortingExtractor
from .find_unit_peak... |
from __future__ import unicode_literals
import unittest
from https_everywhere.session import HTTPSEverywhereSession
class TestRequestsSession(unittest.TestCase):
def test_freerangekitten_com(self):
url = "http://freerangekitten.com/"
s = HTTPSEverywhereSession()
r = s.get(url)
r.... |
# Copyright 2017 The Emscripten Authors. All rights reserved.
# Emscripten is available under two separate licenses, the MIT license and the
# University of Illinois/NCSA Open Source License. Both these licenses can be
# found in the LICENSE file.
import os
import shutil
import logging
import re
TAG = 'version_3_3'... |
# Testando as funções com otimização para as chamadas recursivas
# Realizei uma pequena mudança na estrutura do projeto, adicionando as funções de fibonacci para o formato de módulo
from functions.fib_cache import fib_cache
from functions.fib_memo import fib_memo
if __name__ == "__main__":
print("# Fibonacci ... |
import logging
import pprint
import signal
import warnings
from twisted.internet import defer
from zope.interface.exceptions import DoesNotImplement
try:
# zope >= 5.0 only supports MultipleInvalid
from zope.interface.exceptions import MultipleInvalid
except ImportError:
MultipleInvalid = None
from zope.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.