content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
import pytest
from glom import glom
from utilities.configuration import read
from utilities import helpers
from utilities import PROJECT_DIR
from utilities.basher import BashCommands
def test():
SUBMODULES_DIR = 'submodules'
DEFAULTS_PATH = 'rapydo-confs'
project = "template"
... |
# Copyright 2016 Twitter. 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 applicable law or agree... |
class TreeVertex:
def __init__(self):
self.branches = []
class Tree:
def __init__(self):
self.root = TreeVertex()
|
"""
Scenariocompare: compare two scenarios, concentrating on csv files in the outputs/data subfolders
"""
import os
import pathlib
import sys
import numpy as np
import pandas as pd
from sklearn.metrics import mean_squared_error
def main(s1, s2):
print(f"FILE, FIELD, RMSE, ERROR")
after_root = pathlib.Path(s... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 07 14:59:03 2014
@author: derricw
"""
from pymba import *
import numpy as np
import cv2
import time
cv2.namedWindow("test")
with Vimba() as vimba:
system = vimba.getSystem()
system.runFeatureCommand("GeVDiscoveryAllOnce")
time.sleep(0.2)
camera_ids = ... |
import matplotlib.pyplot as plt
import scipy.io
import numpy as np
import math
import argparse
parser = argparse.ArgumentParser(description='Plot dominant factors of connectome solution')
# Arguments
parser.add_argument('testname', type=str, nargs=1, help='test, top_view, or flatmap')
parser.add_argument('directory... |
n = int(input())
for i in range(10 ** 5, 0, -1):
if n % (i * i) == 0:
print(i, n // (i * i))
break
|
"""A simple test experiment definition
Just a 2D normal model
Current list of required objects:
name
general_model
make_mu_model
null_parameters
get_seeds
get_seeds_null
null_options
general_options
observed_data
DOF
"""
import JMCtools.distributions as jtd... |
import pygame
import os
class dino:
os.path.join('assets', 'dino0000.png')
models = [os.path.join('assets', 'dino0000.png'), os.path.join('assets', 'dinorun0000.png'), os.path.join(
'assets', 'dino0000.png'), os.path.join('assets', 'dinorun0001.png')]
normalModels = [os.path.join('assets', 'dino00... |
"""Unit tests for pyatv.convert."""
import unittest
from pyatv import exceptions
from pyatv.dmap.daap import media_kind, playstate, ms_to_s
from pyatv.const import MediaType, DeviceState
# These are extracted from iTunes, see for instance:
# http://www.blooming.no/wp-content/uploads/2013/03/ITLibMediaItem.h
# and al... |
import boto3
import time
def lambda_handler(event, context):
s3_client = boto3.client('s3')
# Download a 25MB file from S3
with open('/tmp/25MB', 'wb') as data:
s3_client.download_fileobj('serverlessappperfopt-network-intensive-source-bucket', '25MB', data)
time.sleep(0.1)
#Delete the file ... |
import pandas as pd
import numpy as np
from connect import Connect
from pymongo import MongoClient
from pprint import pprint
client = Connect.get_connection()
db = client.grand_paris_estates
cursor = db.inventory.find({})
#init columns
city = []
zipcode = []
description = []
image = []
link = []
price = []
rooms = ... |
"""
Migration script to (a) add and populate necessary columns for doing community tagging of histories, datasets, and pages and \
(b) add table for doing individual and community tagging of workflows.
SQLite does not support 'ALTER TABLE ADD FOREIGN KEY', so this script will generate error messages when run against \... |
"""
Test Error bars
"""
import matplotlib.pyplot as plt
import numpy as np
import mpld3
def create_plot():
np.random.seed(1)
x = np.linspace(0, 10, 100)
y = np.sin(x)
xdata = 10 * np.random.random(25)
dy = 0.2 + 0.2 * np.random.random(xdata.shape)
ydata = np.random.normal(np.sin(xdata), dy)
... |
from day import Day
from term import Term
from teacher import Teacher
class Lesson():
__term: Term
__name: str
__year: int
__full_time: bool
__teacher: Teacher
__skipBreaks: bool
def __init__(self, term: Term, name: str, year: int, skipBreaks: bool = False) -> None:
self.term = ... |
%matplotlib inline
import csv
import copy
from itertools import groupby
from collections import namedtuple, Iterable
from operator import itemgetter
# 4 big cases we need in this project: transform, filter, aggregate, and split
class ETLStreamingStep():
# Builds a transform step where you pass a function at cons... |
import base64
# encode to base64
string = b'password'
encodedString = base64.b64encode(string)
print(encodedString)
# decode string from base64
decodedString = base64.b64decode(encodedString)
print(decodedString)
|
"""
Good morning! Here's your coding interview problem for today.
This problem was asked by Microsoft.
Given a 2D matrix of characters and a target word, write a function that returns whether the word can be found in the matrix by going left-to-right, or up-to-down.
For example, given the following matrix:
[['F', '... |
from django.core.management.base import BaseCommand
from ...services import populate_countries
class Command(BaseCommand):
help = 'Populates 17track countries from external api'
def handle(self, *args, **options):
populate_countries()
|
#!/usr/bin/env python3
# Copyright (c) 2014-2015 The Bitcoin Core developers
# Copyright (c) 2015-2017 The Bitcoin Unlimited developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test re-org scenarios with a mempool that ... |
import os
import json
from io import StringIO
import sys
import requests
import shutil
import time
import tweepy
from load_credential import Credential
class Crawler(object):
def __init__(self, api: tweepy.API, uid: str):
if api is None:
raise ValueError
else:
self._api = ... |
import requests
from bs4 import BeautifulSoup
import sys
sys.dont_write_bytecode = True
url = "https://www.tgju.org/"
r = requests.get(url)
soup = BeautifulSoup(r.text, "html.parser")
def date():
date = soup.find("div", class_="date").text
return date[:date.find('-')]
def sekke_price():
sekke_emami = ... |
import numpy as np
import pandas as pd
import os
from os import listdir
'''
Read and separate crime data into two way:
- Days of the week
- Week and weekend
'''
class SplitData:
DAYS = { 0 : 'monday', 1 : 'tuesday', 2 : 'wednesday', 3 : 'thursday', 4 : 'friday', 5 : 'saturday', 6 : 'sunday' }
'''
Read cr... |
import requests
import json
import os
from pymongo import MongoClient
MONGODB_URI = os.environ['MONGODB_URI']
MONGODB_NAME = os.environ['MONGODB_NAME']
client = MongoClient(MONGODB_URI)
db = client[MONGODB_NAME]
temp_collection = db['temp_symbols']
collection = db['symbols']
api_request = 'https://api.iextrading.com... |
import Adafruit_GPIO as GPIO
import time
gpio = GPIO.get_platform_gpio()
pin = 338
gpio.setup(pin, GPIO.OUT)
gpio.output(pin, 1)
time.sleep(0.5)
gpio.output(pin, 0)
time.sleep(0.5)
|
import os
import pathlib
from typing import Dict
class TargetPathConverter:
def __init__(self, target_to_host_mapping):
# type: (Dict[str, str]) -> None
target_to_host_mapping = { # remove the possible trailing "/" (e.g. correct "/usr/" to "/usr")
str(pathlib.PurePosixPath(k)): str(pa... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""=================================================================
@Project : Algorithm_YuweiYin/LeetCode-All-Solution/Python3
@File : LC-1342-Number-of-Steps-to-Reduce-a-Number-to-Zero.py
@Author : [YuweiYin](https://github.com/YuweiYin)
@Date : 2022-01-31
========... |
import pandas as pd
import os
local = os.path.dirname(__file__)
def create_products():
file = str(local + '/csv_data/products.csv')
df = pd.read_csv(file)
df.fillna('', inplace=True)
products = []
for product in df.T.to_dict().values():
products.append(product)
return list(product... |
def area(alt, larg):
art = alt * larg
print(f'O terreno de propriedades {alt:.1f} x {larg:.1f} tem àrea total de {art:.1f}m² ')
print(' Controle de terrenos')
print('-' * 30)
a = (float(input('LARGURA (m): ')))
l = (float(input('ALTURA (m): ')))
area(a, l)
|
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 14 16:35:44 2022
@author: johan
"""
import requests
import numpy as np
import pandas as pd
import plotly.graph_objs as go
import plotly.express as px
import dash_bootstrap_components as dbc
from dash import dcc, html, Input, Output, callback
import dash
from sqlalchemy i... |
import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir))
import logging
from baseanalyzer import BaseAnalyzer
## =====================================================================
## LOGGING CONFIGURATION
## =====================================================================
LOG = logg... |
#Faça um programa que leia o comprimento do
#cateto oposto e do cateto adjacente de um triangulo retangulo,
#calcule e mostre o comprimento da hipotenusa
from math import pow, sqrt, hypot
cateto_oposto = float(input('Comprimento do cateto oposto: '))
cateto_adjacente = float(input('Comprimento do cateto adjacente: '))
... |
"""
Copyright 2022 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES O... |
import math
def gamma_fucn(a, b, c, d,g11,alp,bet,alp1,bet1):
N = a + b + c + d
numerato = (N + alp) * (N + bet)
denomo = (b + alp1) * (c + bet1)
# print(b)
# print(alp1)
# print(c)
# print(bet1)
val = numerato / denomo
val = g11 * val
return val
def expectation(a, b, c, d,g11... |
import magma as m
from hwtypes import modifiers
def test_732():
Mod = modifiers.make_modifier("Mod")
BV = m.Bits[8]
ModBits = Mod(m.Bits)
ModBV = Mod(BV)
assert issubclass(ModBV, BV)
assert issubclass(ModBV, ModBits)
|
from neuron import h
try:
from neuron.rxd import species
have_rxd = True
except:
have_rxd = False
def get_mech_names():
_mech_names = []
mt = h.MechanismType(0)
mname = h.ref('')
for i in range(int(mt.count())):
mt.select(i)
mt.selected(mname)
_mech_nam... |
import os
import subprocess
from libqtile import hook, qtile
@hook.subscribe.startup_once
def start_once():
subprocess.call([os.path.expanduser("~/.local/bin/autostart.sh")])
@hook.subscribe.startup
def start_always():
subprocess.run(["xsetroot", "-cursor_name", "left_ptr"])
subprocess.run(["setxkbmap"... |
from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers
from rest_framework.permissions import SAFE_METHODS
from drf_recaptcha.fields import ReCaptchaV3Field
from djangoProject.common import ConfessionOrCommentInSerializerUnique
from djangoProject.taggit_serializer import TaggitSer... |
# 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 json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from .. import utilities, tables
class Cluste... |
import unittest
from shippy.repository_archive import RepositoryArchive
class TestRepositoryArchive(unittest.TestCase):
def setUp(self):
self.repo_url = "https://github.com/codesplicer/shippy"
self.repo = RepositoryArchive(self.repo_url)
self.sha = "1234abcd"
def test_get_archive_url... |
from redpil.bmp import imread
from pathlib import Path
import numpy as np
import pytest
from PIL import Image
from numpy.testing import assert_array_equal
parametrize = pytest.mark.parametrize
good_folder = Path(__file__).parent / 'bmpsuite' / 'g'
passing_files = ['pal1.bmp', 'pal1bg.bmp', 'pal1wb.bmp',
... |
import networkx as nx
G = nx.Graph()
print(G)
|
from dashboard.views._positions._non_ec._alumni_relations_chair import *
from dashboard.views._positions._non_ec._detail_manager import *
from dashboard.views._positions._non_ec._membership_development_chair import *
from dashboard.views._positions._non_ec._philanthropy_chair import *
from dashboard.views._positions._n... |
import requests
import json
from _datetime import datetime
import os
# your APIKEY
KEY = os.environ.get('DOCOMO_DIALOGUE_API_KEY', None)
# リクエストクエリ
endpoint = 'https://api.apigw.smt.docomo.ne.jp/naturalChatting/v1/dialogue?APIKEY=REGISTER_KEY'
url = endpoint.replace('REGISTER_KEY', KEY)
# user registration
def regis... |
print(f'Loading {__file__}')
# Smartpod for hexapods
sSmartPodUnit = EpicsSignal('XF:28IDD-ES:2{SPod:1}Unit-SP',name='sSmartPodUnit')
sSmartPodTrasZ = EpicsSignal('XF:28IDD-ES:2{SPod:1-Ax:1}Pos-SP',name='sSmartPodTrasZ')
sSmartPodTrasX = EpicsSignal('XF:28IDD-ES:2{SPod:1-Ax:2}Pos-SP',name='sSmartPodTrasX')
sSmartPod... |
#! python
import argparse
import json
import warnings
from cryocare.internals.CryoCAREDataModule import CryoCARE_DataModule
def custom_formatwarning(msg, *args, **kwargs):
# ignore everything except the message
return str(msg) + '\n'
warnings.formatwarning = custom_formatwarning
def main():
parser = a... |
# -*- coding: UTF-8 -*-
from flask.ext.restful import abort
from handlers import request_validator
from flask import request
from leancloud import Query
from models.patient import PatientMedical
import json
__author__ = 'Panmax'
from . import Resource, api
import requests
class ValidateTokenAPi(Resource):
@reque... |
# Copyright 2018 DataStax, 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 or agreed to in writin... |
import logging
from typing import Any, Dict
from . import exceptions
DEFAULT_THEME_COLOR = '#62abea'
DEFAULT_BACKGROUND_COLOR = '#444444'
DEFAULT_FRONTEND_DIR = 'frontend'
DEFAULT_FRONTEND_URL_PREFIX = 'frontend'
DEFAULT_STATIC_URL = '{frontend_url_prefix}/static'
logger = logging.getLogger(__name__)
name: str... |
# -*- coding: utf-8 -*-
"""
=== DFT_zero_padding.py ===================================================
Plots zum Kapitel "DFT": Effekt von Zero-Padding auf die DFT
(c) 2016 Christian Münker - Files zur Vorlesung "DSV auf FPGAs"
===========================================================================
"""... |
import dearpygui.dearpygui as dpg
import dearpygui.demo as demo
import dearpygui_ext.themes as themes
from dearpygui_ext.datagrid import mvDataGrid
import warnings
warnings.simplefilter('always', DeprecationWarning)
dpg.enable_docking()
with dpg.font_registry():
with dpg.font("../../Resources/NotoSerifCJKjp-Medi... |
#!/usr/local/sci/bin/python
# PYTHON2.7
#
# Author: Kate Willett
# Created: 31 January 2017
# Last update: 7 February 2018
# Location: /data/local/hadkw/HADCRUH2/UPDATE2015/PROGS/HADISDH_BUILD/
# GitHub: https://github.com/Kate-Willett/HadISDH_Build
# -----------------------
# CODE PURPOSE AND OUTPUT
# ---------... |
import torch, torchvision, torch_optimizer
import torch.optim as optim
from torch import Tensor
from typing import Optional, List
import numpy as np
########## NestedTensors
def _max_by_axis(the_list):
# type: (List[List[int]]) -> List[int]
maxes = the_list[0]
for sublist in the_list[1:]:
for i... |
#! /usr/bin/env python3.7
from modules.commands.helpers.textutil import get as get_pun
HELP_TEXT = ["!pun", "Displays a random reviewed pun from your channel."]
def call(salty_inst, c_msg, **kwargs):
success, response = get_pun(salty_inst, c_msg, "pun", **kwargs)
return success, response
def test(salty_in... |
"""
Set of validators for views
"""
from hurry.filesize import size
def validate_rule(rule):
""" Validator for checking rules """
if rule not in ('simple', 'strict'):
return {'error': 'check_rule in not present in Post data'}
def validate_upload_file(upload_file, max_allowed_size=15000000):
""" ... |
import torch
from typing import Optional
from gpytorch.lazy import InterpolatedLazyTensor, RootLazyTensor, CatLazyTensor
from gpytorch.priors import Prior
from gpytorch.utils.broadcasting import _mul_broadcast_shape
from gpytorch.kernels import Kernel
class LowFidelityIndexKernel(Kernel):
def __init__(
sel... |
# ------------------------------------------------------------------------------------------
# Copyright James A. Dooley 2021.
#
# Distributed under the MIT License.
# (See accompanying file license.md file or copy at http://opensource.org/licenses/MIT)
#
# --------------------------------------------------------------... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 5 11:21:15 2019
@author: Markus Borg
"""
import csv
from sklearn.feature_extraction.text import CountVectorizer
import nltk
from nltk.tokenize import RegexpTokenizer
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from sklearn.decomposition imp... |
#!/usr/bin/python
import argparse
import asyncio
import cmd
import time
import hyparviewpy
class Shell(cmd.Cmd):
intro = (
'Welcome to the HyParView test shell. '
'Type help or ? for a list of commands.\n'
)
def __init__(self, node, loop):
self._node = node
self._loop = ... |
from qtpy.QtGui import QValidator
from qtpy.QtWidgets import QSpinBox
class QtSpinBox(QSpinBox):
"""Extends QSpinBox validate and stepBy methods in order
to skip values in spin box."""
prohibit = None
def setProhibitValue(self, value: int):
"""Set value that should not be used in QSpinBox.
... |
import numpy as np
def sigmoid(x):
""" sigmoid = 1 / (1 + exp(-x))"""
return 1 / (1 + np.exp(-x))
class Sigmoid:
def __init__(self):
self.y = None
def forward(self, x):
self.y = 1 / (1 + np.exp(-x))
return self.y
def backward(self, delta_output):
return delta_out... |
from .base_renderer import *
import creoleparser
@renderer
class CreoleRenderer(MarkupRenderer):
@classmethod
def is_enabled(cls, filename, syntax):
if syntax == 'text.html.creole':
return True
return filename.endswith(".creole")
def render(self, text, **kwargs):
resul... |
from sqlalchemy import Table, select
import sqlalchemy
from sqlalchemy.sql.expression import BinaryExpression
import asyncio
import datetime
from sqlalchemy.engine.base import Connection
from Model.device import device
class deviceRepo:
__deviceTable: Table
__context: Connection
def __init__(self, Device... |
# -*- coding: utf-8 -*-
# Copyright (c) 2021 Intel 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 applicab... |
"""
Copyright 2021 InfAI (CC SES)
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... |
# encoding: UTF-8
DATA_RECORDER = u'Data Recorder'
TICK_RECORD = u'Tick Record'
BAR_RECORD = u'Bar Record'
CONTRACT_SYMBOL = u'Contract Symbol'
GATEWAY = u'Gateway'
DOMINANT_CONTRACT = u'Dominant Contract'
DOMINANT_SYMBOL = u'Dominant Symbol'
TICK_LOGGING_MESSAGE = u'Record Tick Data {symbol}, Time:{time}, last:{l... |
# Copyright 2016 The Chromium 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 textwrap
from testing_utils import testing
from infra_api_clients.codereview.rietveld import Rietveld
from libs.http import retry_http_client
clas... |
#!python
# Copyright 2021 Mihai Gătejescu
#
# 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 ... |
#!/usr/bin/env python3
"""
We print an approximation of the
percentage of work done so far on each test.
"""
import sys
# Just a bit above the real total
realtotal = 29500.0
total = realtotal
if __name__ == "__main__":
if len(sys.argv) == 2:
v = float(sys.argv[1])
v2 = (v / float(total)) * 100.0
... |
import pandas as pd
import numpy as np
import networkx as nx
# Load data
node_data = pd.read_csv('base_nodes.txt', sep='\t')
edge_data = pd.read_csv('base_edges.txt', sep='\t')
dg = nx.from_pandas_dataframe(edge_data, 'parent', 'child', create_using=nx.DiGraph()) # type: nx.DiGraph
center = 0
# Set node info
nod... |
import requests
from .api import RDFStoreException, resolveTemplate
def rdf4j_push(rdfstore, model, obj, gr, mode ):
#import pdb; pdb.set_trace()
from rdf_io.models import ServiceBinding
headers = {'Content-Type': 'application/x-turtle;charset=UTF-8'}
resttgt = resolveTemplate("".join( (... |
from flask import Flask, request, render_template
import random
import operator
app = Flask(__name__)
ops = {
'add' : operator.add,
'subtract' : operator.sub,
'multiply' : operator.mul,
'divide' : operator.truediv
}
def sort_letters(message):
"""A helper method to sort the characters of a string i... |
import torch
import torch.nn as nn
from functools import reduce
from operator import mul
class Resize(nn.Module):
def __init__(self, shape):
super(Resize, self).__init__()
self.shape = shape
def forward(self, x):
return nn.functional.interpolate(x, size=self.shape, mode='nearest') #mo... |
from requests_futures.sessions import FuturesSession
import os
session = FuturesSession(max_workers = 10)
def make_logs_query(log):
log_id = log['code']
query = """
{
reportData{
report(code: "%s"){
fights(difficulty: 5){
name
id
averageItemLevel
... |
from yaw_controller import YawController
from pid import PID
from lowpass import LowPassFilter
from geometry_msgs.msg import TwistStamped
import math
import rospy
from math import sqrt
GAS_DENSITY = 2.858
ONE_MPH = 0.44704
class Controller(object):
def __init__(self, vehicle_mass, fuel_capacity, brake_deadband,... |
# TODO:
# - better name for "prompt_finalchar"
import inspect
import joblib
import os
import json
import gc
import weakref
from functools import partial
import numpy as np
import pandas as pd
from tqdm.autonotebook import tqdm
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.model_selection import ... |
hatch_back = 1
sedan = 2
SUV = 3
luxury = 4 |
# Autogenerated file.
from .client import DmxClient # type: ignore
|
"""
Dataset tools for labeled image files.
Dataset format is a directory containing:
Image files,
Label files,
labels.csv
Image files:
Drag and drop image files into the dataset directory before running the
label tool. The dataset directory can contain subdirectories, which are
scanned for ... |
import random
# Classe que abstrai uma pergunta do teste
class Question:
def __init__(self, text, answer, options):
self.text = text
self.answer = answer
# Guardar todas as alternativas na lista choices
self.choices = options
self.choices.append(self.answer)
# Emba... |
from dataclasses import dataclass
from typing import Dict
import pytest
from fluidml.common import Task, Resource
class DummyTaskA(Task):
def __init__(self, x: int):
super().__init__()
def run(self):
self.save(obj={'a': 1}, name='a', type_='json')
class DummyTaskB(Task):
... |
#!/usr/bin/env python
'''Index data files for distribution'''
from pathlib import Path
import pooch
import json
def main():
# Build the pooch registry
regfile = Path('index') / Path('registry.txt')
pooch.make_registry('audio', regfile)
# Parse the registry into the keyword manifest
tracks = set(... |
from pdb import set_trace as T
import numpy as np
from collections import defaultdict
import itertools
import gym
import nmmo
from nmmo.infrastructure import DataType
class SingleAgentEnv:
def __init__(self, env, idx, max_idx):
self.config = env.config
self.env = env
self.idx = idx... |
# -*- coding: utf-8 -*-
"""
created on sun oct 16 21:41:36 2016
@author: sashlin
"""
import numpy as np
cards = { "ace" : 1,
"2" : 2,
"3" : 3,
"4" : 4,
"5" : 5,
"6" : 6,
"7" : 7,
"8" : 8,
"9" ... |
# Copyright 2019 ICON 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 agreed to in writi... |
from __future__ import print_function
import time,numpy as np,sys,h5py,cPickle,argparse,subprocess
from hyperopt import Trials, STATUS_OK, tpe
from hyperas import optim
from os.path import join,dirname,basename,exists,realpath
from os import system,chdir,getcwd,makedirs
from keras.models import model_from_json
from tem... |
'''
Shortest Path III
This is the final exercise of this trio! You're now going to complete the problem by writing the code that returns False if there's no path between two nodes.
INSTRUCTIONS
100XP
Check to see if the queue has been emptied. You can do this by inspecting the last element of queue with [-1].
Place t... |
name1 = 17
name2 = 42
|
import argparse
import datetime as dt
def count_lines(path):
with open(path, 'r') as f:
length = len(f.readlines())
return length
def run_test(args):
try:
ts_file = open(args['path'], 'r')
except Exception as ex:
print(ex)
return
print("Starting with {}".format(args[... |
from . import numbers
|
"""
Setup file for Replay Enhancer.
"""
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='replayenhancer',
version='0... |
import sys, time
sys.path.insert(0, '../dynamikontrol')
from dynamikontrol import Module
m = Module(debug=True)
# Print module serial number
print('Serial number: %s' % (m.get_serial_no(),))
print('ID: %s' % (m.get_id(), ))
print('Device time: %s' % (m.get_time(), ))
print('FW version: %s' % (m.get_fw_version(),)... |
from sso import models
def test_user_get_username():
user = models.BusinessSSOUser(email='test@example.com')
assert user.get_username() == 'test@example.com'
def test_user_save():
user = models.BusinessSSOUser(email='test@example.com')
assert user.save() is None
|
from flask import flash, redirect, url_for, render_template
from blog_app.contact import bp
from blog_app.contact.contact_email import send_contact_mail
from blog_app.contact.forms import ContactForm
from flask_babel import _
@bp.route('/contact', methods=['GET', 'POST'])
def contact():
form = ContactForm()
i... |
"""This module handles adding things to the store"""
import datetime as dt
import logging
from pathlib import Path
from typing import Dict, List, Tuple
from housekeeper.store import models
from housekeeper.store.api.base import BaseHandler
from housekeeper.store.api.find import FindHandler
LOG = logging.getLogger(__... |
from django.db import models
from cloudinary.uploader import upload
from django.contrib.auth import get_user_model
from cloudinary.models import CloudinaryField
from django.db.models.deletion import CASCADE
from django.db.models.fields.related import ForeignKey
from django.db.models.fields.reverse_related import ManyTo... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# создайте словарь, где ключами являются числа, а значениями – строки.
# Примените к нему метод items(), c с помощью полученного объекта dict_items создайте
# новый словарь, "обратный" исходному, т. е. ключами являются строки, а значениями –
# числа.
if __name__ ... |
'''
Date: 03-08-2018
Creator: Thijs Zijlstra
Version: 3.2
Description: Unit tests bluetooth
'''
from Models import Bluetooth
import unittest
class TestBluetooth(unittest.TestCase):
@staticmethod
def test_connect(self):
connect = getattr(Bluetooth, 'connect')
sock = ... |
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import serialization, hashes
# TODO: integrate key gen into Agent gen
def makeKeys(outDir):
try:
# CREATE PRIVATE KEY
pri_key = rsa.gener... |
import atexit
import shutil
import re
import tempfile
import textwrap
from typing import List, Optional, Tuple
from core.api import GroupedBenchmark, TimerArgs
from core.types import Definition, FlatIntermediateDefinition, Label
_TEMPDIR: Optional[str] = None
def get_temp_dir() -> str:
global _TEMPDIR
if _TE... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.