text stringlengths 2 999k |
|---|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 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 derivat... |
from datetime import datetime
from sqlalchemy.orm import backref, relationship
from bollards_api import db, login_manager
from flask_login import UserMixin
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primar... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests import common
class TestMrpMulticompany(common.TransactionCase):
def setUp(self):
super(TestMrpMulticompany, self).setUp()
group_user = self.env.ref('base.group_user')
grou... |
import time
from tools import shell
import os
from threading import Thread
class BitbakeThread(Thread):
def __init__(self, path, target, command):
super().__init__()
self.path = path
self.target = target
self.command = command
pass
def run(self):
self.bitbake = ... |
import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ["MOLECULE_INVENTORY_FILE"]
).get_hosts("all")
def test_java_toolchain(host):
f = host.file("/tmp/java")
assert f.exists
cmd = host.run("/tmp/java/jdk5/bin/java -version")
a... |
"""Support for Z-Wave switches."""
import time
from homeassistant.components.switch import DOMAIN, SwitchEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.en... |
# -*- coding: utf-8 -*-
# Copyright (c) Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
from __future__ import division
import numpy as np
from .mesh import MeshVisual
from ..geometry import MeshData
class SurfacePlotVisual(MeshVisual):
"""... |
VERSION = (0, 1, 0, 'final')
__version__ = VERSION # alias
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
if VERSION[3] != 'final'... |
from django.db import models
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
class UserManager(BaseUserManager):
def create_user(self, first_name, last_name, email, password=None):
user = self.model(
first_name=fir... |
from setuptools import setup, find_packages
# pylint: disable=exec-used
__version__ = '0.0.0'
exec(open('loom_viewer/_version.py').read())
setup(
name="loom-viewer",
version=__version__,
packages=find_packages(),
install_requires=[
"loompy",
"matplotlib",
"scikit-learn",
... |
import numpy as np
import matplotlib.pyplot as plt
import copy
import torch
from .camera import backproject_points_batch, backproject_points, backproject_point
class BoundingBox():
def __init__(self, p1, p2):
"p1 = u,v u=height v=widht starting top_left 0,0"
if p1[0] < p2[0] and p1[1] < p2[1]:
... |
# coding: utf-8
# Copyright (c) 2016, 2022, 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... |
import json
from flask import Blueprint, request, session
from google.appengine.api import search
from car.model import Car
cars = Blueprint('cars', __name__)
@cars.route('/', methods=['GET'])
def get_all():
cars = [u.to_dict() for u in Car.query().fetch()]
return json.dumps(cars)
@cars.route('/<int:car_id>... |
from django import template
from datetime import datetime
from datetime import timedelta
from django.utils.timesince import timesince
from pytz import UTC
register = template.Library()
@register.filter
def ago(date):
if date.tzinfo is None:
date = datetime.utcfromtimestamp(int(date.strftime("%s")))
no... |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2019 Fetch.AI Limited
#
# 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 ... |
import copy
import json
import os
import random
import ssl
import sys
from binascii import b2a_hex
from datetime import datetime
from json import JSONDecodeError
import click
import requests
from apscheduler.schedulers.blocking import BlockingScheduler
from cryptography.hazmat.backends import default_backend
from cryp... |
N, X, *A = map(int, open(0).read().split())
result = 10 ** 19
for k in range(1, N + 1):
dp = {}
for i in range(k + 1):
dp[i] = {}
dp[0][0] = 0
for i in range(N):
a = A[i]
for j in range(min(i, k - 1), -1, -1):
for b in dp[j].values():
c = (a + b) % k... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
import os
import time
import unittest
import ray
from ray.rllib import _register_all
from ray import tune
from ray.tune import Trainable, TuneError
from ray.tune import register_env, register_trai... |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'winter_bread_31465.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
r... |
from django.shortcuts import render_to_response
from django.template import RequestContext
import os
from qmpy.models import Calculation
from qmpy.analysis.vasp.calculation import VaspError
from ..tools import get_globals
from bokeh.embed import components
def calculation_view(request, calculation_id):
calculati... |
#!/usr/bin/env python
import argparse
import os
import sqlite3
def main():
parser = argparse.ArgumentParser(description='Extract mol blocks of specified mol ids into SDF file and extract '
'their docking scores.')
parser.add_argument('-i', '--input', metavar='... |
# Function group: 1,2,3,[4~17] are variations of 1,2, 18, [19,20,21], 22, 23, 24, 25
import argparse
import json
import os.path
from pathlib import Path
from ioh import get_problem
from ThesisCode.KrigingSMT import createIOHPBOKrgConfig
from ThesisCode.Pipeline import pipeline
from ThesisCode.RBFRoy import createIOHP... |
import torch
import torch.nn as nn
from torchvision import models, transforms
from dataset import HCPDataset
# from torch.utils.data import DataLoader
from torch_geometric.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
import torch.nn.functional as F
EPOCHS = 120
IS_SEX = True # comment: decl... |
from django import template
register = template.Library()
@register.filter(name='private')
def private(obj, attribute):
return getattr(obj, attribute) |
#
# Copyright (c) nexB Inc. and others. All rights reserved.
# ScanCode is a trademark of nexB Inc.
# SPDX-License-Identifier: Apache-2.0
# See http://www.apache.org/licenses/LICENSE-2.0 for the license text.
# See https://github.com/nexB/scancode-toolkit for support or download.
# See https://aboutcode.org for more in... |
# filename: simple_crypto_cli.py
# description: A simple crypto asset command-line interface built on
# coinmarketcap-professional Python wrapper (v0.0.1)
# date: 2018-07-20
# author: sterlingbeason
# note: API key needed to substitute below
import re, time
from coinmarketcap_p... |
import collections
import re
import subprocess
import xml.etree.ElementTree as ET
_Report = collections.namedtuple('Report',
['uuid', 'status', 'high', 'med', 'low',
'log', 'date'])
_Task = collections.namedtuple('Task', ['uuid', 'status', 'name'])
_R... |
# coding: utf-8
"""Plotting library."""
from copy import deepcopy
from io import BytesIO
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
from .basic import Booster, _log_warning
from .compat import GRAPHVIZ_INSTALLED, MATPLOTLIB_INSTALLED
from .sklearn import LGBMModel
def _check_not_t... |
import dateutil.parser
from sqlalchemy import Column, Text, event, cast
from sqlalchemy.dialects.postgresql import UUID, JSONB, TIMESTAMP, DATE
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.sql import func
Base = declarative_base()
class Scr... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import filer.fields.folder
import aldryn_bootstrap3.model_fields
import filer.fields.image
import filer.fields.file
import django.db.models.deletion
import cms.models.fields
import djangocms_attributes_field.fields... |
"""
Module: 'json' on micropython-v1.10-pyboard
"""
# MCU: {'ver': 'v1.10', 'build': '', 'platform': 'pyboard', 'port': 'pyboard', 'machine': 'PYBv1.1 with STM32F405RG', 'release': '1.10.0', 'nodename': 'pyboard', 'name': 'micropython', 'family': 'micropython', 'sysname': 'pyboard', 'version': '1.10.0'}
# Stubber: 1.5.... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019, 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 derivat... |
from goldsberry.team._Team import * |
from cereal import car
from common.numpy_fast import mean
from common.filter_simple import FirstOrderFilter
from common.realtime import DT_CTRL
from opendbc.can.can_define import CANDefine
from selfdrive.car.interfaces import CarStateBase
from opendbc.can.parser import CANParser
from selfdrive.config import Conversions... |
from collections import defaultdict
from scipy.spatial import distance_matrix
from protex.system import IonicLiquidSystem
import logging
import numpy as np
from simtk import unit
logger = logging.getLogger(__name__)
class Update:
def __init__(self, ionic_liquid: IonicLiquidSystem) -> None:
self.ionic_li... |
from spec2wav.modules import Generator, Audio2Mel, Audio2Cqt
from pathlib import Path
import yaml
import torch
import os
def get_default_device():
if torch.cuda.is_available():
return "cuda"
else:
return "cpu"
def load_model(spec2wav_path, device=get_default_device()):
"""
Args:
... |
# -*- coding: utf-8 -*-
"""Objects for defining connections between nodes. The nodes can be in the same or different sections."""
from __future__ import annotations
import enum
from dataclasses import dataclass, field, InitVar
from typing import Union, ClassVar, Sequence, SupportsFloat, List
import abc
from .exc i... |
# -*- coding:utf-8 -*-
import six
import numpy as np
__all__ = ['XYTiler']
class XYTiler(object):
_offset_dict = {
"center": (0.5, 0.5),
"lowerleft": (0.0, 0.0),
"lowerright": (1.0, 0.0),
"upperleft": (0.0, 1.0),
"upperright": (1.0, 1.0)
}
def __init__(self, x_si... |
# Generated by Django 2.1.2 on 2018-12-03 18:43
from django.db import migrations
from django.conf import settings
from oauth2_provider.settings import oauth2_settings
from apps.authorization.models import update_grants
def migrate_grants(*args, **kwargs):
update_grants()
class Migration(migrations.Migration):
... |
#
# Copyright 2013 Apache Software Foundation
#
# 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 agree... |
# Generated by Django 3.1.4 on 2020-12-23 05:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0005_auto_20201211_0048'),
]
operations = [
migrations.AddField(
model_name='applicant',
name... |
primo_index_request_body = {
'alias': 'catalog',
'settings': {
'number_of_shards': 8,
'number_of_replicas': 0,
'refresh_interval': '-1'
},
'mappings': {
'record': {
'_all': {'enabled': true},
'properties': {
'title': {
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Runs minion floscript
'''
from __future__ import print_function
from __future__ import absolute_import
# pylint: skip-file
import os
import stat
from ioflo.aid.odicting import odict
from ioflo.base.consoling import getConsole
console = getConsole()
import salt.daem... |
# -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... |
import unittest
import os
import sys
import logging
import math
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..', 'src'))
from peachyprinter.infrastructure.transformer import OneToOneTransformer, TuningTransformer, Homo... |
''' Classes for read / write of matlab (TM) 4 files
'''
import sys
import warnings
import numpy as np
from numpy.compat import asbytes, asstr
import scipy.sparse
from miobase import MatFileReader, docfiller, matdims, \
read_dtype, convert_dtypes, arr_to_chars, arr_dtype_number, \
MatWriteError
from mio_ut... |
"""Utilities for testing."""
from typing import Iterator
from typing import Type
import pytest
from retrocookie.compat import contextlib
from retrocookie.pr.base import bus
@contextlib.contextmanager
def raises(event_type: Type[bus.Event]) -> Iterator[None]:
"""It raises the event on the bus."""
with pytest... |
import torch
from torch import Tensor, log
from ..neko_module import NekoModule
class Log(NekoModule):
"""
The module version of :func:`torch.log` operation.
Args:
eps (``float``, optional): A bias applied to the input to avoid ``-inf``. Default ``0``.
Examples::
>>> log = Log()
... |
from datetime import date, timedelta
import os,csv,subprocess
import time
os.chdir(os.path.dirname(os.path.realpath(__file__)))
def aoiupdate(indir=None,infile=None,days=None):
if infile==None:
inputfolder=indir
n=days
yesterday = date.today() - timedelta(int(n))
b=yesterday.strftime... |
import logging
from typing import Any, List
from fastapi import APIRouter, Depends
from api.v1.deps import get_current_active_user
from crud import client as crud
from crud.license import find_one as find_license
from models.base import Msg
from models.client import Client, ClientCreate, ClientUpdate
from models.user... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
# Generated by Django 2.1.2 on 2019-08-17 11:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("mainapp", "0106_smsjob_sms_type"),
]
operations = [
migrations.AlterField(
model_name="smsjob", name="message", field=models.Cha... |
from django.urls import path
from . import views
urlpatterns = [
# ex: localhost:8080/polls/
# path('', views.index, name='index'),
# ex: localhost:8080/polls/5/
path('<int:pregunta_id>/', views.detalle, name='detail'),
# ex: localhost:8080/polls/5/results/
path('<int:pregunta_id>/results/', v... |
# coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 5
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_1_0.models.filepoo... |
import csv
import argparse
import random
import tqdm
parser = argparse.ArgumentParser()
parser.add_argument('-csv', type=str, default='raw.csv',
help='path to csv file')
parser.add_argument('-ratio', type=float, default=0.9,
help='ratio of the train set (default: 0.9)')
parser... |
from PyQt5 import QtCore
class ConverterModel(QtCore.QObject):
conversion_started = QtCore.pyqtSignal()
conversion_finished = QtCore.pyqtSignal(bool)
conversion_error = QtCore.pyqtSignal(Exception)
conversion_update = QtCore.pyqtSignal()
terminate_work = QtCore.pyqtSignal()
start = QtCore.pyq... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 12 13:23:00 2019
@author: ets
"""
from pathlib import Path
from matplotlib import pyplot as plt
from pywps import ComplexInput, ComplexOutput
from pywps import FORMATS
from pywps import Format
from pywps import Process
from raven.utilities.graphs... |
from binding import *
from src.namespace import sys
getDefaultTargetTriple = sys.Function('getDefaultTargetTriple',
cast(ConstStdString, str))
if LLVM_VERSION >= (3, 3):
getProcessTriple = sys.Function('getProcessTriple',
cast(ConstStdStrin... |
def get_window_position(driver: object) -> tuple[int, int]:
x = int(driver.get_window_position().get("x")) # type: ignore
y = int(driver.get_window_position().get("y")) # type: ignore
return x, y
|
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/component/clothing/shared_metal_fasteners.iff"
result.attribute_tem... |
import sys
from algorithms.baselines.ppo.agent_ppo import AgentPPO
from algorithms.baselines.ppo.ppo_utils import parse_args_ppo
from utils.envs.envs import create_env
def train(ppo_params, env_id):
def make_env_func():
return create_env(env_id)
agent = AgentPPO(make_env_func, params=ppo_params)
... |
import tensorflow as tf
import numpy as np
from noise import gaussian
class GaussianKernelTests(tf.test.TestCase):
def setUp(self):
""" Compare with Values from
https://en.wikipedia.org/wiki/Gaussian_blur
"""
self.wiki_example = np.array([
[0.00000067, 0.00002292... |
#
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
from setuptools import setup, find_packages, Command
import os, sys, re
class RunTestsCommand(Command):
description = "Test command to run testr in virtualenv"
user_options = [
('coverage', 'c',
"Generate code coverage report... |
# coding=utf-8
from django.conf import settings
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.managers import CurrentSiteManager
from django.utils.encoding import force_text
class CommentQuerySet(models.query.QuerySet):
def active(self):
... |
#!/usr/bin/env python3
# Copyright (c) 2014-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Helpful routines for regression testing."""
from base64 import b64encode
from binascii import unhexlif... |
from dnload.common import listify
########################################
# SymbolSource #########################
########################################
class SymbolSource:
"""Representation of source providing one symbol."""
def __init__(self, name, dependencies, headers, prototypes, source):
"""Constru... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
import shutil
import subprocess
from mephisto.operations.operator import Operator
from mephisto.operations.uti... |
# -*- encoding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
class People(models.Model):
name = models.CharField(max_length=255)
parent = models.ForeignKey('self', models.CASCADE)
class Message(models.Model):
from_field = models.ForeignKey(People, models.CASCADE, db_co... |
"""Tests for alpacka.runner."""
from alpacka import runner
def test_smoke(tmpdir, capsys):
n_epochs = 3
runner.Runner(
output_dir=tmpdir,
n_envs=2,
n_epochs=n_epochs
).run()
# Check that metrics were printed in each epoch.
captured = capsys.readouterr()
assert captur... |
"""
Add UUIDs to workflows
"""
from __future__ import print_function
import logging
from sqlalchemy import Column, MetaData, Table
from galaxy.model.custom_types import UUIDType
log = logging.getLogger(__name__)
metadata = MetaData()
"""
Because both workflow and job requests can be determined
based the a fixed d... |
# -*- coding: utf-8 -*-
from django.contrib.auth.models import Group
from django.contrib.sites.models import Site
from django.db.models import Q
from cms.exceptions import NoPermissionsException
from cms.models import Page, PagePermission, GlobalPagePermission
from cms.plugin_pool import plugin_pool
from cms.utils.com... |
# (C) Datadog, Inc. 2019-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
from codecs import open # To use a consistent encoding
from os import path
from setuptools import setup
HERE = path.dirname(path.abspath(__file__))
# Get version info
ABOUT = {}
with open(path.join(HER... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from models.modelUtils import residualBlock
class EncoderConv(nn.Module):
def __init__(self, latents = 64, hw = 16):
super(EncoderConv, self).__init__()
self.latents = latents
self.c = 4
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Collection of tests resolutions in :mod:`orion.core.evc.conflicts`."""
import pytest
from orion.algo.space import Dimension
from orion.core.evc import adapters, conflicts
from orion.testing.evc import add_default_config_for_missing
@pytest.fixture
def add_dimension_re... |
import torch
from torchvision import datasets, transforms
class Dataset:
def __init__(self, dataset, _batch_size):
super(Dataset, self).__init__()
if dataset == 'mnist':
dataset_transform = transforms.Compose([
transforms.ToTensor(),
transforms... |
import _plotly_utils.basevalidators
class TitleValidator(_plotly_utils.basevalidators.TitleValidator):
def __init__(self, plotly_name="title", parent_name="cone.colorbar", **kwargs):
super(TitleValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
class Solution:
def primePalindrome(self, N: int) -> int:
|
import logging
import sys
try:
import obd
except ImportError:
import subprocess
subprocess.run([
'pip',
'install',
'git+https://github.com/SLR8/py-obd'
])
import obd
# connection = obd.OBD()
# command = obd.commands.SPEED
# response = connection.query(command)
# print(res... |
from typing import Text, List
import gitlint
from gitlint.rules import LineRule, RuleViolation, CommitMessageTitle
from gitlint.options import StrOption
import re
# Word list from https://github.com/m1foley/fit-commit
# Copyright (c) 2015 Mike Foley
# License: MIT
# Ref: fit_commit/validators/tense.rb
WORD_SET = {
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import json
import copy
from pyowm.config import DEFAULT_CONFIG
from pyowm.constants import AGRO_API_VERSION
from pyowm.commons.http_client import HttpClient
from pyowm.commons.enums import ImageTypeEnum
from pyowm.commons.image import Image
from pyowm.comm... |
# Copyright (c) 2012 Rackspace Hosting # 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 req... |
# -*- coding: utf-8 -*-
'''
A few checks to make sure the environment is sane
'''
# Original Author: Jeff Schroeder <jeffschroeder@computer.org>
# Import python libs
import os
import re
import sys
import stat
import socket
import logging
# Import third party libs
if sys.platform.startswith('win'):
import win32fi... |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# 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... |
from seamless.highlevel import Context, Cell
import seamless
ctx = Context()
def serve(filename, sharename=None, mount=False):
import os
cell = Cell()
cell.celltype = "text"
_, ext = os.path.splitext(filename)
cell.mimetype = ext[1:]
if mount:
cell.mount(filename, mode="rw", authority=... |
import os
import sys
import shutil
import re
import logging
from collections import defaultdict
from StringIO import StringIO
from subprocess import Popen
from subprocess import PIPE
from cloudfoundry import CloudFoundryUtil
from cloudfoundry import CloudFoundryInstaller
from detecter import TextFileSearch
from detecte... |
my_list = [
{
"key1" : "Potatosalad",
"key2" : 42,
"key3" : ["Potato", "Oil", "Vinegar", "Onion"]
},
{
"key1" : "Sandwich",
"key2" : 12,
"key4" : ["Cookie", "Softdrink"]
},
{
"key1" : "Pizza",
"key2" : 35,
"key3" : ["Dough", "T... |
#
# Copyright (c) 2018-2019 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
from sysinv.common import constants
from sysinv.common import exception
from sysinv.openstack.common import log as logging
from sysinv.helm import common
from sysinv.helm import openstack
LOG = logging.getLogger(__name__)
... |
"""
test for BaseRecording are done with BinaryRecordingExtractor.
but check only for BaseRecording general methods.
"""
import shutil
from pathlib import Path
import pytest
import numpy as np
from probeinterface import Probe
from spikeinterface.core import BinaryRecordingExtractor, NumpyRecording, load_extractor
fro... |
# coding:utf-8
import unittest
from mulprectest import Mulprectest
class TestMulprectest(unittest.TestCase):
def test_mulprectest(self):
# len(pi) = 73
# correct number of digits = 70
pi = "3141592653589793238462643383279502884197169399375105820974944592307816396"
mpt = Mulprectes... |
class TestBasic:
def test_pass(self, testdir):
testdir.makepyfile("""
class TestClass():
def test_pass(self):
assert 1 == 1
""")
result = testdir.runpytest("-v")
result.stdout.fnmatch_lines(["*TestClass::test_pass PASSED*"])
def te... |
COMM_SIZE = 2 ** 4
STREAM_SIZE= 2 ** 10
DATA_BITWIDTH = 32
instream = CoramInStream(idx=0, datawidth=DATA_BITWIDTH*2, size=STREAM_SIZE)
channel = CoramChannel(idx=0, datawidth=DATA_BITWIDTH, size=COMM_SIZE)
def read_edge():
addr = channel.read()
instream.write_nonblocking(addr, 2) # prefetch the first entry
... |
# Generated by Django 3.0.11 on 2021-02-28 12:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("taggit", "0003_taggeditem_add_unique_index"),
("bpp", "0238_drop_pesel_md5"),
]
operations = [
migrations.AddField(
mod... |
import gym
from baselines import deepq
from baselines.common.atari_wrappers_deprecated import wrap_dqn, ScaledFloatFrame
from cloud_environment_real import RealCloudEnvironment
import numpy as np
import collections
import os
import csv
import random
#NUR EINE EPISODE
#Bilder normalisieren? Brightness change jan => H... |
import IPet
class Ant(IPet):
def __init__(self):
self.stats = {"hlth": 2, "dmg": 1}
# operator is going to contain the shop, team and board.
def modify_stats(self, dmg_ant, hlth_amnt, is_perm):
if is_perm:
self.stats["dmg"] += dmg_ant
self.stats["hlth"] += hlth_am... |
from flask import Blueprint, render_template, redirect, request
from flask_login import current_user
from app.models import EditableHTML
from app.main.forms import HabitForm
from app.models import Habit
from app import db, csrf
main = Blueprint('main', __name__)
@main.route('/')
def index():
if current_user.i... |
from part1 import (
gamma_board,
gamma_busy_fields,
gamma_delete,
gamma_free_fields,
gamma_golden_move,
gamma_golden_possible,
gamma_move,
gamma_new,
)
"""
scenario: test_random_actions
uuid: 878160624
"""
"""
random actions, total chaos
"""
board = gamma_new(5, 3, 3, 3)
assert board is... |
from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = 'E07000153'
addresses_name = 'parl.2017-06-08/Version 1/Kettering Democracy_Club__08June2017.tsv'
stations_name = 'parl.2017-06-08/Version 1/Kettering Democracy... |
# -*- coding: utf-8 -*-
#
# Simple Bot to reply to Telegram messages
# This program is dedicated to the public domain under the CC0 license.
# from shrutitgbot.xpal import *
from . import xpal
from . import utils
import requests, json
# from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters, RegexH... |
import numpy as np
import pandas as pd
import xarray as xr
def new_test_dataset(time, height=180, **indexers):
"""
Create a test dataset with dimensions ("time", "lat", "lon") and data variables given by *indexers*.
:param time: Single date/time string or sequence of date-time strings.
:param height:... |
"""
HDF5 Pricing File Format
------------------------
At the top level, the file is keyed by country (to support regional
files containing multiple countries).
Within each country, there are 4 subgroups:
``/data``
^^^^^^^^^
Each field (OHLCV) is stored in a dataset as a 2D array, with a row per
sid and a column per s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.