content stringlengths 5 1.05M |
|---|
import FWCore.ParameterSet.Config as cms
process = cms.Process("Rec")
process.load("FWCore.MessageLogger.MessageLogger_cfi")
process.load("CondCore.DBCommon.CondDBSetup_cfi")
process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(20) )
#can be 300 in that file
process.source = cms.Source("PoolSource"... |
import os
import yaml
import argparse
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('--archs', type = str, choices=['TSA'], help = 'our approach')
parser.add_argument('--benchmark', type = str, choices=['FineDiving'], help = 'dataset')
parser.add_argument('--prefix', type = str... |
import pydig
class PhishingTrackerDig:
@staticmethod
def analyzer(record, type='ANY'):
if record is None or len(record) == 0:
return None
type = type.upper()
if type == 'ANY':
types = [ 'A', 'AAAA', 'CNAME', 'MX', 'NS', 'TXT' ]
data = {}
... |
from typing import Tuple
from pydantic import BaseSettings
class Settings(BaseSettings):
telegram_api_key: str
admin_ids: Tuple[int, ...]
sheet_title: str = 'Курсы по Питону'
class Config:
case_sensitive = False
env_file = 'creds/.env'
env_file_encoding = 'utf-8'
|
# Generated by Django 2.2.12 on 2020-06-04 16:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('EvalData', '0039_auto_20200601_1353'),
]
operations = [
migrations.AddField(
model_name='textsegmentwithtwotargets',
... |
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
path('', views.index, name='index'),
path('cat/<str:category>/', views.index, name='index-specific-cat'),
path('author/<str:author_first_name>-<str:author_last_name>/', views.author_index, name='specific-author'),
path(... |
import torch
from .action_head.action_head import build_roi_action_head
class Combined3dROIHeads(torch.nn.ModuleDict):
def __init__(self, cfg, heads):
super(Combined3dROIHeads, self).__init__(heads)
self.cfg = cfg.clone()
def forward(self, slow_features, fast_features, boxes, objects=None, e... |
from . import Subplotter
import numpy as np
def masked(to_mask, mask):
return [item for item, keep in zip(to_mask, mask) if keep]
class SampleSubplotter(Subplotter):
def __init__(self, colors):
super(SampleSubplotter, self).__init__(colors)
self.failed_samples = []
self.unfailed_samp... |
a = 21.0
b = 10.5
if ( a == b ):
print "Line 1 - a is equal to b"
else:
print "Line 1 - a is not equal to b"
if ( a != b ):
print "Line 2 - a is not equal to b"
else:
print "Line 2 - a is equal to b"
if ( a <> b ):
print "Line 3 - a is not equal to b"
else:
print "Line 3 - a is equal to b"
if ( a ... |
"""
First text analytics script using nltk.
Will load the tokens and then create a dictionary of words with the number of
occurences in the text.
"""
from TokenizeLemmatize import unpickle_tokens
from collections import Counter
def count_names(tokens):
"""Return a counter of the continuous chains of NNPs."""
... |
# -*- coding: utf-8 -*-
# @Author: David Hanson
# @Date: 2021-01-31 13:45:32
# @Last Modified by: David Hanson
# @Last Modified time: 2021-01-31 14:09:40
# recursive method:
def find_factorial_recursive(number):
if number <= 1:
return 1
else:
return number * find_factorial_recursive(number-... |
from . import parser
from . import watch
def gen_leases(path):
"""
Keep track of currently valid leases for ISC dhcpd.
Yields dictionaries that map ``ip`` to information about the
lease. Will block until new information is available.
"""
g = watch.watch_dhcp_leases(path)
for _ in g:
... |
import http
import io
import argparse
import json
import os
import pathlib
from collections import defaultdict
from typing import Optional, Tuple
import librosa
import rnd_utilities
import aiohttp
from pydub import AudioSegment
from aiogram import Bot, Dispatcher, types, executor
from aiogram.types import InlineKeybo... |
import requests
import numpy as np
import cv2
import os
from hashlib import sha1
images_dir = "animals"
name_prefix = "tree"
os.makedirs(images_dir, exist_ok=True)
with open("trees.txt", "rt") as file:
links = file.read().split("\n")
for link in links:
hex = sha1(bytes(link, encoding='utf-8')).hexdigest()
... |
from django.apps import AppConfig
from django.conf import settings
from django.utils.translation import gettext_lazy as _
class UrlManagerConfig(AppConfig):
name = "djangocms_url_manager"
verbose_name = _("django CMS URL Manager")
url_manager_supported_models = {}
def ready(self):
from .compa... |
from __future__ import print_function
from builtins import chr
import base64
import pickle
from Crypto import Random
from Crypto.Cipher import AES
from cumulusci.core.config import ConnectedAppOAuthConfig
from cumulusci.core.config import OrgConfig
from cumulusci.core.config import ScratchOrgConfig
from cumulusci.cor... |
############################################################
# -*- coding: utf-8 -*-
#
# # # # # # #
# ## ## # ## # #
# # # # # # # # # # #
# # ## # ## ## ######
# # # # # # #
#
# Python-based Tool for interaction with the 10micron mounts
# GUI with PyQT5 fo... |
from .controller_util import get_triggering_dags |
# Copyright 2021 Rafał Safin (rafsaf). 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 applicabl... |
import random
import evaluation
from evaluation import PTBTokenizer, Cider
from data.tokenizers import Tokenizer
from data.medicalDataloaders import R2DataLoader
from models.visual_extractor import VisualExtractor
from models.rstnet import Transformer, TransformerEncoder, TransformerDecoderLayer, ScaledDotProduct... |
import pickle
import nltk
import spacy
import benepar
import torch
import json
import os
import subprocess
import numpy as np
from tempfile import TemporaryDirectory
from fairseq.models.bart import BARTModel
from nltk import sent_tokenize,word_tokenize
from nltk.corpus import stopwords
from nltk.tree import Tree
from ... |
"""
CPMpy interfaces to (the Python API interface of) solvers
Solvers typically use some of the generic transformations in
`transformations` as well as specific reformulations to map the
CPMpy expression to the solver's Python API
==================
List of submodules
==================
... |
import copy
import pytest
import numpy as np
import pandas as pd
from nomenclature.core import process
from nomenclature.definition import DataStructureDefinition
from nomenclature.processor.region import RegionProcessor
from pyam import IAMC_IDX, IamDataFrame, assert_iamframe_equal
from conftest import TEST_DATA_DIR... |
import numpy as np
import re
import xml.etree.cElementTree as ET
input = None
with open("svm.model") as f:
input = f.readlines()
svm_type = re.match(r"svm_type ([\w_]+)", input[0]).groups()[0]
kernel_type = re.match(r"kernel_type ([\w]+)", input[1]).groups()[0]
gamma = float(re.match(r"gamma ([-\d.]+)", input[2])... |
#!/usr/bin/env python
#
import collections
import datetime
import logging
import yfinance
import syncfin.db.model as mydb
import syncfin.utils.parallel as parallel
log = logging.getLogger(__name__)
class TickerPull(object):
def _update_db(self, db, index, row):
values = {
'date': ('%s'... |
"""Nice function to make figures for slides (not used in the framework)."""
import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
def plot_decomposition_graph(
graph,
nodes_color="#6886b7",
weight="weight",
colormap="jet",
ax=None,
... |
import csv
import gzip
import logging
import os.path
from collections import namedtuple
from itertools import chain, takewhile, groupby, product
from os import getcwd
import pandas as pd
from more_itertools import peekable
from py.path import local
from nltk.corpus import brown, CategorizedTaggedCorpusReader
from n... |
# SPDX-FileCopyrightText: 2018-2022 Espressif Systems (Shanghai) CO LTD
# SPDX-License-Identifier: Apache-2.0
#
import importlib.util
import os
import sys
from importlib.abc import Loader
from typing import Any
def _load_source(name: str, path: str) -> Any:
spec = importlib.util.spec_from_file_location(name, pat... |
""" Testing the benefits of using pone """
import pyspiel
import time
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
from darkhex.algorithms.gel_all_information_states import get_all_information_states
def num_states_encountered():
""" Returns the number of possible states to encounter... |
"""
Resource and titles
"""
import os
import re
VPC_GATEWAY_ATTACHMENT = "VPCGatewayAttachment"
def vpc_gateway_title(prefix):
"""
The VPC gateway title.
"""
return "%s%s" % (prefix, VPC_GATEWAY_ATTACHMENT)
def vpc_title(prefix):
"""
VPC title
"""
return "%sVPC" % prefix
def buck... |
"""Tests for the helper functions."""
from pyglet.window.key import MOD_SHIFT, MOD_CTRL, MOD_ALT, MOD_NUMLOCK
from shimmer.helpers import bitwise_contains, bitwise_add, bitwise_remove
def test_bitwise_add(subtests):
"""Test that the bitwise_add function works as intended."""
assert bitwise_add(MOD_SHIFT, MO... |
import numpy as np
import decimal
import spectra
class Smear(object):
""" This class smears the energy and radius of a spectra.
The class can recieve energy and radius as individual data points or a
1 dimensional numpy array to smear which is then returned. 2d and 3d
arrays with linked energy, radius ... |
import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import ssl
#SSL Certification Error Handle
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
#Data Collection
link = input('Enter URL: ')
cont = int(input('Enter count: '))
line = int(input('Ent... |
import os
from typing import List
from fvttmv.path_tools import PathTools
from fvttmv.wolds_finder import WorldsFinder
dirs_in_worlds_to_look_for_db_file = ["data", "packs"]
class DbFilesIterator:
"""
Tools for iterating over db files.
"""
def iterate_through_all(self,
a... |
'''Module with functions to work with artists data.
Під час підбору потрібного датасету ми зіткнулися з проблемою:
більший датасет не мав інформації щодо популярності композицій.
Через це ми вирішили побудувати свій власний критерій популярності,
що базується на популярності артистів, що працювали над певною композиці... |
#
# @lc app=leetcode id=243 lang=python3
#
# [243] Shortest Word Distance
#
# @lc code=start
class Solution:
def shortestDistance(self, words, word1, word2):
d = {word1: -1, word2: -1}
mi = float('inf')
if word1 == word2:
return
for i in range(len(words)):
if... |
#!/usr/bin/python
"""
pi-timolo - Raspberry Pi Long Duration Timelapse, Motion Tracking,
with Low Light Capability
written by Claude Pageau Jul-2017 (release 7.x)
This release uses OpenCV to do Motion Tracking.
It requires updated config.py
"""
from __future__ import print_function
progVer = "ver 11.52" # Requires La... |
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
from matplotlib.colors import to_rgb, to_rgba
#---------------------------------------------------------------------------------------------------
# matplotlib style settings
#----------------------------------------... |
from activist.views import ActivistViewSet
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'activists', ActivistViewSet)
urlpatterns = router.urls
|
def single_number(integers):
"""
Naive version: Given a non-empty array of integers, every element appears
twice except for one. Find that single one.
Runtime: O(n), Space: O(n)
"""
seen = set()
for integer in integers:
if integer in seen:
seen.remove(integer)
els... |
from django.contrib import admin
from .models import Survey, Question, Answer
class SurveyAdmin(admin.ModelAdmin):
list_display = (
'pk',
'title',
'description',
'start_date',
'end_date',
'author')
search_fields = ('title',)
list_filter = ('start_date',)
... |
import math
import torch.nn as nn
from collections import OrderedDict
import torch.utils.model_zoo as model_zoo
from torchvision.models.resnet import model_urls
import torch
import torch.nn as nn
class Backbone(nn.Module):
"""Base class for backbone networks. Handles freezing layers etc.
args:
frozen_... |
import asyncio
import logging.config
import warnings
from functools import partial
from typing import Optional
import annofabapi
import requests
from annofabapi.models import ProjectJobType
from annofabcli.common.dataclasses import WaitOptions
from annofabcli.common.exceptions import DownloadingFileNotFoundError, Upd... |
# Same as script 14, but the algorith is trained with a number of agents varying from 1 to 20.
import sys
import os
lucas_path = os.environ['LUCAS_PATH']
sys.path.insert(1, lucas_path)
from general import general as gen
from devices.devices import node, base_station, mobile_user, d2d_user, d2d_node_type
from pathlos... |
from ..functions import loader
from .animation import Animation
from .enemy import Enemy
from .box import Box
from .pig import Pig
# pig sprites loader
load_image = loader("kings_and_pigs/data/sprites/04-Pig Throwing a Box")
class PigThrowingBox(Enemy):
def __init__(self, x, y, type=None, id=None):
idle... |
tamiyo_1 = "Al parecer la historia era cierta"
jace_2 = "cual historia ! ?"
tamiyo_3 = "el bosque cuenta que tu eliminaste"
tamiyo_4 = "al anciano nicol"
jace_5 = "su nombre era lucin"
tamiyo_6 = "que ingenuo eres, si llegas a mi"
tamiyo_7 = "te contare una historia"
tamiyo_8 = "muajajajajaja... |
while True:
a, b = map(int, input().split())
if a == b:
break
else:
print('Crescente' if a < b else 'Decrescente') |
import torch
from torch import optim
import torch.nn.functional as F
import time
import os
import matplotlib.pyplot as plt
from loss import ContrastiveLoss
import datahandler as dl
from model import SiameseNetwork
from torch.utils import tensorboard
root_dir = '..\..\Dataset\MVTEC_AD'
epochs = 200
lear_rate = 0.0005
... |
# Copyright 2017 Red Hat, 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
#
# Unless required by... |
"""Train A2C agent in ALE game registerd in gym.
Some hyper parametes are from OpenAI baselines:
https://github.com/openai/baselines/blob/master/baselines/a2c/a2c.py
"""
import os
from torch.optim import RMSprop
import rainy
from rainy.agents import A2CAgent
from rainy.envs import Atari, atari_parallel
@rainy.main(... |
from bs4 import BeautifulSoup
import urllib2
import shlex
import os
import wget
from subprocess import Popen, PIPE
def mysoup(link):
url = urllib2.Request(link, headers={ 'User-Agent': 'Mozilla/5.0 (X11; Linux i686; rv:33.0) Gecko/20100101 Firefox/33.0' })
page = urllib2.urlopen(url)
soup = BeautifulSoup(p... |
import numpy as np
import sys
import cvxEDA
import json
import matplotlib.pyplot as plt
import scipy.optimize
import gsr
def bateman(tau0, tau1):
return lambda t: np.exp(-t/tau0) - np.exp(-t/tau1)
ts = np.arange(0, 100, 0.1)
plt.plot(ts, bateman(10.0, 5.0)(ts))
plt.show()
data = []
for line in sys.stdin:
row... |
from gi.repository import Gtk
from .basewidgets import Child
class Button(Child):
def __init__(self, bananawidget):
self.widget = Gtk.Button()
self.widget.connect('clicked', self._do_click)
super().__init__(bananawidget)
def _do_click(self, button):
self.bananawidget.on_clic... |
"""
Python Attributed Hierarchical Port Graph.
AHPGraph, is intended to be a simple, flexible way to describe
architecture components and their connections. These physical architecture
descriptions can then be converted to SST component graphs or analyzed by other
tools.
"""
from .Device import *
from .DeviceGraph im... |
from framework.core.base import BasePage
class addQuestionPage (BasePage):
questionTextBox = None
showMore = None
todayLink = None
nowLink = None
choiceText1 = None
choiceText2 = None
choiceText3 = None
choiceVotes1 = None
choiceVotes2 = None
choiceVotes3 = None
addChoice... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from controller.node_controller import NodeController
from common import utilities
class NodeCommandImpl:
def __init__(self, config):
self.node_controller = NodeController(config)
def gen_node_config(self):
function = "generate_all_config"
not... |
#!/usr/bin/env python
"""
Layered wheel implementation
"""
import base64
import csv
import hashlib
import io
import pprint
import re
import shutil
import subprocess
import zipfile
import email.policy
# Non-greedy matching of an optional build number may be too clever (more
# invalid wheel filenames will match). Sep... |
from PyQt5.QtWidgets import (QDesktopWidget,
QMainWindow,
QAction, QFrame)
from PyQt5.QtGui import (QPalette, QPen,
QIcon, QPainter, QColor)
from PyQt5.QtCore import Qt, QBasicTimer, QPoint, QTimer
from gui.communicate import Communicate... |
def scrape_facebook_url(url):
pass
|
#Imports for finding urls
import urllib
import json
import urllib.request
#Imports for UI
import tkinter as tk
from tkinter import *
import json, requests
from tkinter.messagebox import showinfo, showwarning
#Imports to scrape video download, thumbnail, title
from pytube import *
import PIL.Image
from PIL import Ima... |
import os
from django import template
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext
from django.conf import settings
from django_openid.models import UserOpenidAssociation
try:
any
except NameError:
def any(seq):
for x in seq:
if x:
... |
# Generated by Django 4.0 on 2022-01-03 18:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('post', '0009_alter_post_thumbnail'),
]
operations = [
migrations.AlterField(
model_name='post',
name='published',
... |
import numpy as np
target = 80
score_beg = np.array([72, 35, 64, 88, 51, 90, 74, 12])
def curve(score_beg):
limit_up = 100
mean_score = score_beg.mean()
added_score = target - mean_score
new_score = score_beg + added_score
return np.clip(new_score, score_beg, limit_up)
print(score_beg)
curve(score_beg)
|
"""
Copyright 2021 Inmanta
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 ... |
#!/usr/bin/env python
import numpy as np
import math
import matplotlib.pyplot as plt
import rospy
import std_msgs.msg
import geometry_msgs.msg
from nav_msgs.msg import Odometry
import itertools
import tf
D = 0.15 # look-ahead distance
L = 0.21 # 24 before
show_animation = True
x_odom = 0.0
y_odom = 0.0
theta_odom ... |
#!/usr/bin/env python
#-*- coding: UTF-8 -*-
###########################################################################
#
# Copyright (c) 2018 www.codingchen.com, Inc. All Rights Reserved
#
##########################################################################
'''
@brief leetcode algorithm
@author chenhui(hui.ch... |
from copy import deepcopy
import numpy as np
import random
import itertools
import cPickle as pickle
class agent(object):
'''
This is an abstract agent class, however its abstractness is not enforced
via the ABC module. This is a deliberate design choice.
The brains of the agent class is th... |
from typing import Optional, Dict
from sqlalchemy.sql.sqltypes import DateTime
from repository.models import Section
from datetime import datetime
# 기계
# 1. 솔레노이드 밸브 5ea
# 2. 물공급용 워터펌프
# 3. 스프레이용 워터펌프
# 4. 양액공급용 워터펌프 2ea
class Machine:
def __init__(
self,
name: str,
pin: int,
id: ... |
import csv
from pymongo import MongoClient
import sys
from pprint import pprint
client = MongoClient()
client = MongoClient('localhost', 27017)
db = client.test_database
# Find the unique authors and publishers
author_list = []
publisher_list = []
with open("book.csv", newline='') as csvfile:
bookreader = csv.Dic... |
# -*- coding: utf-8 -*-
VERSION = "1.5.0" #should keep up with the counterwallet version it works with (for now at least)
DB_VERSION = 22 #a db version increment will cause counterblockd to rebuild its database off of counterpartyd
CAUGHT_UP = False #atomic state variable, set to True when counterpartyd AND counterb... |
from .interface import Interface
#from . import message
#from . import parsers
|
# If tests is a package, debugging is a bit easier.
|
# coding: utf-8
# # Your first neural network
#
# In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementation of the neural network up to you (for the most part). After you've submitted this project, feel free t... |
from tqdm import tqdm
import torch
def run_epoch(model, iterator,
criterion, optimizer,
metrics,
phase='train', epoch=0,
device='cpu', writer=None):
is_train = (phase == 'train')
if is_train:
model.train()
else:
model.eval()
epoc... |
import evfuncs
import pytest
import soundfile
import vocalpy
def test_field_access():
assert False
def test_defaults():
assert False
def test_asdict():
assert False
def test_equality():
assert False
def test_inequality():
assert False
@pytest.mark.parametrize(
'spect_format, with_fo... |
import TestExports
from TestExports import project_to_json
PROJECT_NAME = 'African Animals'
#Uncomment if running on Windows:
#project_to_json(PROJECT_NAME, 'Windows')
#Uncomment if running on Mac:
project_to_json(PROJECT_NAME, 'Mac')
#Uncomment if running on Linux:
#project_to_json(PROJECT_NAME, 'Linux')
|
# BSD Licence
# Copyright (c) 2009, Science & Technology Facilities Council (STFC)
# All rights reserved.
#
# See the LICENSE file in the source distribution of this software for
# the full license text.
"""
Utilities for use with genshi
@author: Stephen Pascoe
"""
from genshi import *
class RenameElementFilter(ob... |
import director.applogic as app
import director.objectmodel as om
from director import cameraview
import functools
actionName = 'ActionColorizeLidar'
def setVisProperties(obj, colorModeEnabled):
if colorModeEnabled:
alpha = 1.0
pointSize = 4.0
colorBy = 'rgb'
else:
alpha = ... |
#!/usr/bin/env python
"""
plot position data from a time, position, rotation file
"""
import numpy as np
from mpl_toolkits.mplot3d import axes3d, Axes3D
import matplotlib.pyplot as plt
import sys
import re
fig = plt.figure()
ax = Axes3D(fig)
ax.hold(True)
# HRC:POINTS: [2448.59; -1015.19; -206.10] [2445.40; -1063.0... |
import argparse
import json
import logging
from git import Repo
import os
import sys
import re
import traceback
import services
from services.base_service import Service
from helpers.json_skeletons import JSONSkeleton
from importlib import import_module
from helpers.api import VeracodeAPI
from helpers.exceptions impor... |
class Solution(object):
def countSmaller(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
if nums == []:
return []
res = []
sorted_nums = []
rev = nums[::-1]
for num in rev:
l, r = 0, len(res) - 1
... |
# contagem regressiva para ano novo
from time import sleep
for c in range(10, -1, -1):
print(c)
sleep(0.5)
print('BUMM BUMM ')
|
from django.urls import path, include
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register('', views.UserViewSet, basename='user')
urlpatterns = [
path('register/', views.CreateUserView.as_view(), name='register'),
path('', include(router.urls)),
]
|
import argparse
parser = argparse.ArgumentParser(description='This script is ')
# Test or not args
parser.add_argument('-t', '--test', default=False, type=bool, help='Test or not')
# The coordinate args
parser.add_argument('-lt_x', '--left_top_x', default=0, type=int, help='Left-top x-coordinate')
parser.add_argumen... |
#!/usr/bin/env python
from __future__ import print_function
# Libraries we need
import pyxhook
import time
import subprocess
nounlist = open("nounlist.txt","r")
stringtosearch = ""
# This function is called every time a key is presssed
def kbevent(event):
global running
global stringtosearch
# print k... |
# -*- coding: utf-8 -*-
import paho.mqtt.client as mqtt
import time
class mqtt_handler:
client = mqtt.Client()
def __init__(self):
return
@classmethod
def subscribe(cls):
cls.client.connect("broker.mqttdashboard.com", port=1883, keepalive=60)
cls.client.loop_start()
@clas... |
import maze.__maze as __maze
__maze.createMaze()
def __canMoveLeft(curPos: []):
room = __maze.mazeLayout[curPos[0]][curPos[1]]
if int(room[0]):
return True
else:
return False
def __canMoveTop(curPos: []):
room = __maze.mazeLayout[curPos[0]][curPos[1]]
if int(room[1]):
retu... |
import dsz
import sqlite3
import sys
if (__name__ == '__main__'):
save_flags = dsz.control.Method()
dsz.control.echo.Off()
if (dsz.script.Env['script_parent_echo_disabled'].lower() != 'false'):
dsz.control.quiet.On()
if (len(sys.argv) != 3):
dsz.ui.Echo(('Invalid number of arg... |
import pytest
from aioarango import ArangoClient
from aioarango.connection import BasicConnection, JwtConnection, JwtSuperuserConnection
from aioarango.errno import FORBIDDEN, HTTP_UNAUTHORIZED
from aioarango.exceptions import (
JWTAuthError,
JWTSecretListError,
JWTSecretReloadError,
ServerEncryptionEr... |
# Source: https://github.com/willwhite/freemail/
# Copyright (c) 2015, Will White <[email protected]>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
... |
import pytest
import pandas._testing as tm
class TestDataFrameTake:
def test_take(self, float_frame):
# homogeneous
order = [3, 1, 2, 0]
for df in [float_frame]:
result = df.take(order, axis=0)
expected = df.reindex(df.index.take(order))
t... |
import requests
baseURL = 'https://storytelling.blackrock.com/insights/api/stories/'
def getAllPages(cnt):
pages = []
for i in range(1, cnt+1):
params = {'page': i}
resp = requests.get(baseURL, params=params)
pages.append(resp.json())
return pages
def getAllStories(pages):
ret... |
""" This is the config file for the rig, it contains functions that set
sane defaults for different bits of the rig, at some point this may be
converted so that those defaults can be saved in the database, but that
may not really matter since these measures will be taken elsewhere too
This file will be... |
from typing import (
Union,
)
from ssz.exceptions import (
DeserializationError,
SerializationError,
)
from ssz.sedes.base import (
BaseCompositeSedes,
)
from ssz.utils import (
merkleize,
pack_bytes,
)
BytesOrByteArray = Union[bytes, bytearray]
class ByteVector(BaseCompositeSedes[BytesOrByt... |
from essence import World, System, Component, DuplicateComponentError, NoSuchComponentError
import pytest
from fixtures import world
def test_can_add_components_to_entities(world):
entity = world.create_entity()
component = Component()
assert not world.has_component(entity, Component)
world.add_compon... |
from __future__ import print_function
# Import smorgasbord
import sys
import os
import pdb
current_module = sys.modules[__name__]
import numpy as np
import scipy.stats
import matplotlib
#matplotlib.use('Agg')
import matplotlib.pyplot as plt
import astropy.io.fits
import astropy.wcs
import astropy.convolution
import Chr... |
# Generated by Django 3.2.8 on 2021-11-05 00:54
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('main', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='project',
name='created_date',
),
]... |
import gym
import numpy as np
from stable_baselines import DQN
from stable_baselines.common import atari_wrappers
from stable_baselines.common.cmd_util import make_atari_env
from stable_baselines.common.vec_env import VecFrameStack
from stable_baselines.results_plotter import load_results, ts2xy, X_TIMESTEPS
from stab... |
import json
import pytest
from unittest import mock
from asynctest import patch
from blebox_uniapi.box import Box
from blebox_uniapi import error
pytestmark = pytest.mark.asyncio
@pytest.fixture
def mock_session():
return mock.MagicMock(host="172.1.2.3", port=80)
@pytest.fixture
def data():
return {
... |
import os
import sys
import glob
import time
import random
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm, colors
from mpl_toolkits.mplot3d import Axes3D
from keras.utils import Sequence
from keras.callbacks import Callback
def _calc_plot_dim(n, f=0.3):
rows = max(int(np.sqrt(n) - f)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.