content stringlengths 5 1.05M |
|---|
"""
<name>Optical lens</name>
<description>An ideal lens</description>
<icon>icons/lens.svg</icon>
<priority>10</priority>
"""
import sys
from PyQt4.Qt import *
from orangewidget.settings import Setting
from orangewidget import gui
from oasys.widgets import widget
from orangecontrib.wanys.util.OpticalElement import O... |
__all__ = ['AsyncPythonInterpreter']
try:
import fcntl
except:
fcntl = None
import os
import sys
import socket
from StringIO import StringIO
from netrepr import NetRepr, RemoteObjectPool, RemoteObjectReference
import objc
from Foundation import *
IMPORT_MODULES = ['netrepr', 'remote_console', 'remote_pipe', '... |
import numpy
class TSP:
def __init__(self, matrix):
self.matrix = matrix
@staticmethod
def load(filename):
"""Load a TSP from a file.
:param filename: Name of the file
:type filename: str
:return: Traveling Salesman Problem
:rtype: TSP
"""
... |
#!/usr/bin/env python3
import argparse
import sys
from jackal.core import DocMapper, Host, Range, Service, User
from jackal.utils import PartialFormatter, print_error, print_line
fmt = PartialFormatter(missing='')
def format_input(style):
doc_mapper = DocMapper()
if doc_mapper.is_pipe:
for obj in doc... |
from agbot.core.model.context import VerticalContext
from .tp_shell import ShellTestPoint
def run(tp_conf_dict, vertical_context: VerticalContext):
return ShellTestPoint(tp_conf_dict, vertical_context)
|
from python.common.message import encode_message
from python.writer.config import Config
import requests
import logging
import re
import json
logging.basicConfig(level=Config.LOG_LEVEL, format=Config.LOG_FORMAT)
def publish_to_fail_queue(**args) -> tuple:
config = args.get('config')
message_with_errors = arg... |
import csv
import os
import json
conceptsAndIds = [
("anatomical_entity", "A"),
("biological_process_or_activity", "P"),
("cell", "C"),
("chemical_substance", "S"),
("disease", "D"),
("gene", "G"),
("phenotypic_feature", "T")
]
map = {c[0]:c[1] for c in conceptsAndIds}
def build_spec(sequence_ids, start... |
import pytest
from diy.api import UserRequestBasedHandler, UserRequestHandler
@pytest.fixture
def request_user_based_handler():
"""
return UserRequestBasedHandler
"""
return UserRequestBasedHandler()
def test_basic_route(request_user_based_handler):
"""
test to handle route
"""
@... |
from __future__ import absolute_import
import sys
import warnings
try:
import itertools.izip as zip
except ImportError:
pass
from itertools import product
import numpy as np
from .. import util
from ..dimension import dimension_name
from ..element import Element
from ..ndmapping import NdMapping, item_chec... |
"""Automatic differentiation and code generation"""
import os
import sys
import importlib
from typing import List, Sequence, Tuple, Any, Dict
from setuptools import Extension, Distribution
from sympy import Symbol, ccode, Expr
from sympy.codegen.ast import Assignment, CodeBlock
from sympy import S
class SymNlp: # ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time, vim
import signal
try: import thread
except ImportError: import _thread as thread # Py3
def signal_handler(signal, frame):
global interrupted
interrupted = True
signal.signal(signal.SIGINT, signal_handler)
interrupted = False
buf = vim.current.buffer... |
import os
import itertools
def load_file(path):
"""Default loading function, which loads nth sentence at line n.
"""
with open(path, 'r') as f:
content = f.read().strip()
return [s for s in content.split('\n')]
class Vocab:
def __init__(self, sentences=None,
pad_token="[... |
"""
Created on 13/06/2013
@author: victor
"""
import unittest
from pyRMSD.condensedMatrix import CondensedMatrix
from pyproct.clustering.cluster import Cluster
from pyproct.clustering.clustering import Clustering
import numpy
from pyproct.clustering.evaluation.metrics.test.data import CH_table1
from pyproct.clusterin... |
from bs4 import BeautifulSoup
import requests
uwflow_url = "https://uwflow.com/"
calendar_url = "https://ugradcalendar.uwaterloo.ca/"
ece_page = "page/ENG-Computer-Engineering-Electrical-Engineering"
class Course:
start_year = 0
term = ''
name = ''
code = ''
program = ''
cls = 0
tut = 0
... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Copyright 2017 Timothy Dozat
#
# 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 ... |
from django.http import HttpResponse
from django.template import Template, Context
from django.views.generic import View, TemplateView
from templates_i18n.models import Template_i18n
class HomeView(TemplateView):
template_name = 'home.html'
class MyView(View):
def dispatch(self, request, *args, **kwargs):
... |
import pygame
from src.ui.tools.eventBox import EventBox
class GameOver(EventBox):
""" Event box for end of game by death. """
def __init__(self, x, y):
""" Constructor Method
- x: int : x position
- y: int : y position
"""
super().__init__(x, y)
self.image ... |
# Generated by Django 2.2.24 on 2022-02-12 15:44
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('mvapp', '0002_auto_20220212_1727'),
]
operations = [
migrations.RemoveField(
model_name='project',
name='image',
),... |
from starlette.requests import Request
def get_db(request: Request):
return request.state.db
def clone_db_model(model):
"""
To create the clone of sqlalchemy model.
Primary key data (like `id`) will not be copied to the cloned model.
https://stackoverflow.com/a/55991358/10305905
Parameter... |
# This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
import os
from collections import namedtuple
from datetime import... |
# Copyright 2019 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 applicable law or agreed to in wri... |
#!/usr/bin/python
from setuptools import setup
setup(
name = 'pygments-dark16',
version = '0.1',
description = 'Pygments version of dark "base16" theme.',
license = 'BSD',
author = 'Beorn Facchini',
author_email = 'beornf@gmail.com',
url = 'https://github.com/beornf/pygments-dark16',
... |
import unittest
from scrapy.spiders import Spider
from scrapy.utils.url import (url_is_from_any_domain, url_is_from_spider,
add_http_if_no_scheme, guess_scheme, strip_url)
__doctests__ = ['scrapy.utils.url']
class UrlUtilsTest(unittest.TestCase):
def test_url_is_from_any_domain(s... |
import timeit
from os import urandom
from hashkernel.base_x import base_x
B62 = base_x(62)
encode_samples = [urandom(64) for i in range(100)]
decode_samples = [B62.encode(s) for s in encode_samples]
def encode():
for sample in encode_samples:
B62.encode(sample)
def decode():
for sample in decode_s... |
from collections import OrderedDict, defaultdict
class DotDict(dict):
def __getattr__(self, item):
return self.get(item, None)
class SameKeysDict(dict):
def __init__(self, *args, **kwargs):
if len(args) > 0:
arg1 = args[0]
if isinstance(arg1, (list, tuple)):
... |
from django.apps import AppConfig
class RaphendyrEssentialsConfig(AppConfig):
name = 'r_django_essentials'
verbose_name = 'Raphendyr Django Essentials'
|
import math
import os
import tarfile
import tempfile
import time
import docker
def ensure_network(client, name):
try:
client.networks.get(name)
except docker.errors.NotFound:
print("Creating docker network '{}'".format(name))
client.networks.create(name)
def ensure_volume(client, na... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
class Fans(object):
id = ""
href = ""
name = ""
def __init__(self, id, name, href):
self.id = id
self.name = name
self.href = href
def __str__(self):
return "{name:%s,id:%s,href:%s}" % (self.name, self.id, self.href)
d... |
a=list(map(float,input().split(" ")))
b=a[0]
c=a[1]
ba=160+40*(b+b**2)
ca=128+40*(c+c**2)
print(round(ba,3))
print(round(ca,3))
|
#!/usr/bin/env python3
import argparse
import logging
import pathlib
from fontTools.ttLib.ttCollection import TTCollection
from east_asian_spacing.utils import init_logging
logger = logging.getLogger('ttc')
def ttc_split(path: pathlib.Path):
ttc = TTCollection(path)
for i, ttfont in enumerate(ttc.fonts):
... |
from setuptools import setup
setup(
name='lektor-advanced',
py_modules=['lektor_advanced'],
version='1.0',
entry_points={
'lektor.plugins': [
'advanced = lektor_advanced:AdvancedGroupByPlugin',
]
}
)
|
import serial
ser = 0
def initSerial():
global ser
ser = serial.Serial('/dev/ttyACM0', 115200, timeout=1)
def setPin(whatPin, brightness):
ser.write(bytearray.fromhex("ff ff ff " + "whatPin" + " " + chr(brightness))) |
#!/usr/bin/env python3
import os
import subprocess
import sys
# Generate coeffs
subprocess.run([sys.executable, "drivetrain.py", "--noninteractive"])
os.rename("DrivetrainCoeffs.hpp", "../src/main/include/control/DrivetrainCoeffs.hpp")
os.rename("DrivetrainCoeffs.cpp", "../src/main/cpp/control/DrivetrainCoeffs.cpp")
... |
#!/usr/bin/env python
#-----------------------------------------------------------------------------
# Copyright (c) 2013, The BiPy Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#--------------------------... |
# -*- coding: utf-8 -*-
from django.db import models
class Problem(models.Model):
problem = models.CharField(max_length=50, primary_key=True)
author = models.CharField(max_length=50, default="admin")
addtime = models.DateTimeField(auto_now=True)
oj = models.CharField(max_length=50, default="LPOJ")
... |
import click
import requests
@click.command()
@click.option('--list', is_flag=True, help="will print everything")
@click.option('--bike_id',default=False, help="Enter the id of the bike you want to select")
@click.option('--fw_id', default=False, help="Enter the id of the front wheel you want to select")
@click.opti... |
#!/usr/bin/env python
import anndata
import numpy as np
from sklearn.metrics import average_precision_score, roc_auc_score
from scipy.stats import mannwhitneyu
import matplotlib.pyplot as plt
import datetime
import pandas as pd
from glob import glob
"""
calculate performance
"""
#####################################... |
import numpy as np
import pandas as pd
from .conftest import assert_series_equal
from numpy.testing import assert_allclose
from .conftest import DATA_DIR
import pytest
from pvlib import inverter
def test_adr(adr_inverter_parameters):
vdcs = pd.Series([135, 154, 390, 420, 551])
pdcs = pd.Series([135, 1232, ... |
import paho.mqtt.client as mqttClient
import time
# PAYLOAD : mosquitto_pub -h 150.95.27.220 -u air4thai -P asd1357 -m 25 -t air4thai/lamphun01 -p 1883
# $ mosquitto_sub -h 150.95.27.220 -u air4thai -P asd1357 -t air4thai/lamphun01
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Conn... |
# coding=utf-8
# Copyright 2021 The Tensor2Robot Authors.
#
# 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 ... |
# coding: utf8
if not session.token: redirect(LOGIN)
def sync_ldap():
return dict(names_added=names_added, names_in_db=names_in_db, extra_users=extra_users)
def import_csv():
form=FORM(TABLE(TR(" ",TEXTAREA(_name="csv",value="write something here")),
TR("",INPUT(_type="submit",_value="... |
# vim:ts=4:sts=4:sw=4:expandtab
from django.contrib import admin
from .models import *
@admin.register(Task)
class TaskAdmin(admin.ModelAdmin):
pass
@admin.register(Result)
class ResultAdmin(admin.ModelAdmin):
pass
|
import scipy.stats as stats
from UQpy.distributions.baseclass.Distribution1D import Distribution1D
from abc import ABC
class DistributionContinuous1D(Distribution1D, ABC):
"""
Parent class for univariate continuous probability distributions.
"""
def __init__(self, **kwargs):
super().__init__(... |
PORTAL_NAME = "Mist EE"
PLUGINS = [
'rbac',
'manage',
'insights',
'orchestration',
'auth',
'pricing'
]
UGLY_RBAC = """window.rbac={checkPerm:function(e,t,r,o,n){if(!e)return console.error("checkPerm: no resource type defined"),!1;"s"===e.charAt(e.length-1)&&(e=e.slice(0,-1));const s=document.q... |
"""
This module implements functions for handling structure components.
"""
from copy import deepcopy
from typing import Any, Dict, List, Tuple
import networkx as nx
import numpy as np
from monty.fractions import gcd
from pymatgen.analysis.structure_matcher import StructureMatcher
from pymatgen.core.composition import... |
from typing import Any, List, Literal, TypedDict
from .FHIR_CodeableConcept import FHIR_CodeableConcept
from .FHIR_decimal import FHIR_decimal
from .FHIR_Element import FHIR_Element
from .FHIR_integer import FHIR_integer
from .FHIR_MolecularSequence_Roc import FHIR_MolecularSequence_Roc
from .FHIR_Quantity import FHIR... |
# -*- coding: utf-8 -*-
from flask import Flask, render_template, request
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
app = Flask(__name__)
default_response="""
En mis blogs están todas las respuestas! <a href='https://relopezbriega.github.io/' target='_blank'>https://relope... |
import binascii
from Crypto.Cipher import AES
BLOCK_SIZE = 16
# __ to specify a function that will only be called from within another function
def __pad(raw):
padding = ''
if (len(raw) > BLOCK_SIZE):
nulls = BLOCK_SIZE - len(raw) % 8 - 2
else:
nulls = BLOCK_SIZE - len(raw) - 2
for i i... |
"""
Given the names and grades for each student in a class of students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade.
Note: If there are multiple students with the second lowest grade, order their names alphabetically and print each name on a new line.
"""
if __na... |
# Q3: What is the time complexity of
import random
n = int(random.random() * 100)
for i in range(0, n, 2):
pass
""""
N° iteracion value de i
1 0
2 2
3 4
. .
. .
. .
k 2(k-... |
from PIL import Image
from selenium import webdriver
chrome_path = "C:\chromedriver.exe" #chromedriver.exe執行檔所存在的路徑
web = webdriver.Chrome(chrome_path)
for i in range(300):
web.get('https://stu255.ntust.edu.tw/ntust_stu/stu.aspx')
web.get_screenshot_as_file("temp.png")
verify_code = web.find_element_by_... |
def Function(x, y, q):
q = ''
print('Enter coordinate x')
x = int(input(''))
print('Enter coordinate y')
y = int(input(''))
if (x>0) and (y>0):
q = 'Point is located in the first quarter'
return q
elif (x<0) and (y>0):
q = 'Point is located in the second quarter'
... |
def joke():
return 'Sometimes I laugh as a crazy, coz of it'
|
import datetime
import pytz
from unittest import mock
import snapshottest.django as django_snapshottest
import factory.random
from rest_framework.authtoken.models import Token
from rest_framework import test, status
from django.core import management
from django.contrib.auth.models import Permission
from django.cont... |
###########################################################################
#
# Copyright 2020 Google LLC
#
# 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
#
# https://www.apache.org/l... |
import random
from raiden.transfer import channel, secret_registry
from raiden.transfer.architecture import Event, StateChange, TransitionResult
from raiden.transfer.events import EventPaymentReceivedSuccess, SendProcessed
from raiden.transfer.mediated_transfer.events import (
CHANNEL_IDENTIFIER_GLOBAL_QUEUE,
... |
import json
import logging
import subprocess
import sys
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Optional
import requests
SERVER_FILES_PATH = Path('/home/artem/lugnica.pl/public/files')
FFMPEG_EXE_PATH = SERVER_FILES_PATH / 'ffmpeg.exe'
FFMPEG_ESSENTIALS_PATH = SERVER_... |
"""Link Class Plugin for Pelican"""
## Copyright (C) 2015 Rafael Laboissiere
##
## This program is free software: you can redistribute it and/or modify it
## under the terms of the GNU General Affero Public License as published by
## the Free Software Foundation, either version 3 of the License, or (at
## your option... |
# Generated by Django 3.1.8 on 2021-06-22 10:59
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('location_register', '0024_auto_20210526_0845'),
('business_register', '0122_parttimejob'),
]
operations = [... |
# Generated by Django 3.0.8 on 2020-09-22 06:41
import json
import uuid
from django.db import migrations, models
def gen_default_lines():
"""gen_default_lines."""
template = {
"useCountingLine": True,
"countingLines": [
{
"id": "$UUID_PLACE_HOLDER",
... |
# メインプログラム
import sys
import random
from copy import *
import glob
import re
import os
import shutil
import openpyxl
import numpy as np
from scipy.sparse import csr_matrix
import Update
import Arrange
import Family
import Check
import gensim
from gensim.models.doc2vec import Doc2Vec
from gensim.model... |
#!/usr/bin/env python3
# coding: utf-8
# Google AIY Voice Kit会話デモ
# 音声「こんにちは」で「はい、こんにちは」を、
# 音声「お元気ですか?」で「はい、元気です」を、
# 音声「あなたの名前は?」で「私の名前はJuriusです」を、
# 「アプリを終了して」で「さようなら」の会話が出来ます。
# Copyright (c) 2019 Wataru KUNINO
from aiy.cloudspeech import CloudSpeechClient # AIY音声認識用ライブラリ
from aiy.board import Board... |
#!/usr/bin/env python3.8
# -*- coding: utf-8 -*-
"""Email module.
Classes:
Mail: SMTP email class.
Error, InvalidEmailFormatError (used for validation) of the Mail class.
Functions:
validate_email(email_address)
"""
import os
import re
import smtplib
from email.mime.multipart import MIMEMultipart
fr... |
import numpy as np
from sklearn import preprocessing
raw_csv_data = np.loadtxt('Audiobooks_data.csv', delimiter = ',')
unscaled_inputs_all = raw_csv_data[:,1:-1]
targets_all = raw_csv_data[:,-1]
shuffled_unscale_indices = np.arange(unscaled_inputs_all.shape[0])
np.random.shuffle(shuffled_unscale_indices)
unscaled_in... |
"""
Copyright BOOSTRY Co., Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distr... |
import requests
import json
from django_unionbank.constants import AUTH_SCOPES
from django_unionbank import settings as ub_settings
# from django_unionbank.models import AccessToken
def get_partner_token(scope):
PRODUCT_NAME = 'Partner Authentication'
ENDPOINT_URL = '{}{}'.format(
ub_settings.UNIONBA... |
# -*- coding: utf-8 -*-
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('phrasebook', '0001_initial'),
('lists', '0005_translationslist_language'),
]
operations = [
migrations.RemoveField(
model_name='translationslist... |
import sys
sys.path.insert(0, '/home/anastasia/paddleGan/PaddleGAN/')
import os
from ppgan.apps.first_order_predictor import FirstOrderPredictor
args = {
"output": "output",
"filename": "result.mp4",
"weight_path": None,
"relative": True,
"adapt_scale": True,
"find_best_frame": False,
"best... |
from django.contrib.admin.models import LogEntry, CHANGE
from django.contrib.contenttypes.models import ContentType
from django.db.models import Model
from django.utils.encoding import force_text
from apps.users.models import User
def log_object_action(obj, message, action_flag=CHANGE, user=None):
"""Create a Lo... |
from sortedcontainers import SortedList
class Solution:
def busiestServers(self, k: int, arrival: List[int], load: List[int]) -> List[int]:
requestCounter, priorityQueue, serverList, maxRequestHandled = Counter(), [], SortedList(range(k)), 0
for requestNumber, (requestArrivalTime, requestLoad) in e... |
import pytest
import numpy as np
from dizoo.classic_control.cartpole.envs import CartPoleEnv
@pytest.mark.unittest
class TestCartPoleEnv:
def test_naive(self):
env = CartPoleEnv({})
env.seed(314, dynamic_seed=False)
assert env._seed == 314
obs = env.reset()
assert obs.shap... |
# -*- coding: utf-8 -*-
from mock import Mock
def test_app_register_api(app):
dispatcher = Mock()
dispatcher.test.__name__ = 'test'
app.register_api('test', dispatcher.test)
app.test()
assert dispatcher.test.called
|
# Copyright 2020 - 2021 MONAI Consortium
# 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 wri... |
"""
Frontends for constructing Relay programs.
Contains the model importers currently defined
for Relay.
"""
from __future__ import absolute_import
from .mxnet import from_mxnet
from .keras import from_keras
from .onnx import from_onnx
from .tflite import from_tflite
from .coreml import from_coreml
|
import os
import os.path
import pickle
import numpy as np
import torch.distributed as dist
from mmcv.runner import get_dist_info
from mmcls.datasets.utils import check_integrity, download_and_extract_archive
from .base_dataset import BaseDatasetKD
from .builder import DATASETS
# Load datasets with the modified Base... |
#////////////////////////////////////////////////
#// Generate an unspent address
#////////////////////////////////////////////////
from iota import Iota
from iota.crypto.types import Seed
import sys
import json
with open('config.json', 'r') as f:
data = json.load(f)
url = data['url']
seed = Seed.random()
i... |
#!/usr/bin/env python
# Generate all CSV files from the sqlite database
import csv
import pandas as pd
import sqlite3
import math
import pandas as pd
from util import camel_to_hyphens, format_country, format_int
def format_int_with_nan(val):
if val == "NaN" or val == "nan" or math.isnan(val):
return "N... |
#-*- encoding: utf-8 -*-
"""
Number letter counts
If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
NOTE: Do no... |
"""Define RNN-based encoders."""
from __future__ import division
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torch.nn.utils.rnn import pack_padded_sequence as pack
from torch.nn.utils.rnn import pad_packed_sequence as unpack
from onmt.encoders.encoder import EncoderBase... |
from __future__ import print_function
from __future__ import division
# Basic test of multi-agent mission concept.
# To use:
# 1: Start two mods (make sure the ClientPool is set up to point to them, see below.)
# 2: Start agent one - eg "python multimaze.py"
# 3: Start agent two - eg "python multimaze --role 1"
# They... |
from e2e.base_testcase import BaseTestCase
class TestNavigationPageNonStudent(BaseTestCase):
def __init__(self, testname):
super().__init__(testname, log_in=False)
def test_instructor(self):
self.log_in(user_id="instructor", user_name="Quinn")
self.click_class('sample', 'SAMPLE')
... |
import copy
import types
import logging
import inspect
import torch
import torch.nn as nn
import torch.nn.init as init
from . import utils
def unsqueeze_expand_dim(x, dim, k):
dims = x.size()
return x.unsqueeze(dim).expand(*dims[:dim], k, *dims[dim:])
def expand_match(a, b, dim=0):
size = [-1] * len(b... |
import gstgva # pylint: disable=import-error
from gstgva.util import libgst, gst_buffer_data
import gi
gi.require_version('Gst', '1.0')
from gi.repository import Gst
import numpy as np
import math
import copy
import json
from munkres import Munkres
import os
from collections import OrderedDict
import logging
import ... |
def partida():
quantidade_pecas = int(input("\nQuantas peças? "))
limite_pecas = int(input("Limite de peças por jogada? "))
vantagem_pc = (quantidade_pecas + (limite_pecas + 1)) % (limite_pecas + 1) == 0
if vantagem_pc:
print("\nVocê começa!\n")
while quantidade_pecas > 0:
... |
import os
import numpy as np
from experiments import config
from utils.data_generation import data_utils
is_initialized = False
data_mean, data_std = None, None
def get_stats():
global is_initialized, data_mean, data_std
if is_initialized:
return data_mean, data_std
else:
# if config.AR... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Estimate acoustic feature statistics
"""
import argparse
import os
import sys
import glob
import joblib
import logging
from sklearn.preprocessing import StandardScaler
import h5py
import numpy as np
class Scaler(object):
def __init__(self):
self.ss = ... |
from copy import deepcopy as dp
from pprint import pprint
with open('input.txt') as file:
data = file.read()
# data = """.#.
# ..#
# ###"""
data = data.splitlines()
active = []
# parse input, z = 0
for y in range(len(data)):
for x in range(len(data[0])):
v = data[y][x]
if v == '#':
... |
import unittest
from plio.io import io_json
from plio.io import io_yaml
try:
import yaml
missing = False
except ImportError:
missing = True
from plio.examples import get_path
class TestYAML(unittest.TestCase):
@unittest.skipIf(missing == True, 'YAML library not installed')
def test_read(self):... |
import re
from libsheep.parameters import DeclarativeParameterMeta, Parameter, Base32, Set
class ProtocolError(RuntimeError):
pass
class MessagePart(object):
__metaclass__ = DeclarativeParameterMeta
def __new__(cls, code, *args, **kwargs):
handler_class = cls.REGISTRY.get(code, cls)
i... |
import numpy as np
from astropy.io import fits
import matplotlib.pyplot as plt
from pupil_masks import *
import os
#import poppy
import tqdm
from matplotlib.colors import LogNorm
def myfft2(wave_in):
return np.fft.fftshift(np.fft.fft2(np.fft.ifftshift(wave_in)))
def myifft2(wave_in):
return np.fft.ifftsh... |
from output.models.nist_data.list_pkg.unsigned_short.schema_instance.nistschema_sv_iv_list_unsigned_short_min_length_3_xsd.nistschema_sv_iv_list_unsigned_short_min_length_3 import NistschemaSvIvListUnsignedShortMinLength3
__all__ = [
"NistschemaSvIvListUnsignedShortMinLength3",
]
|
# ProDy: A Python Package for Protein Dynamics Analysis
#
# Copyright (C) 2010-2012 Ahmet Bakan
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your o... |
import math
def joint_distance(j1, j2) -> float:
"""
Compute Euclidean distance between two Kinect joints
:param j1: joint 1
:param j2: joint 1
:return: distance
"""
x = (j1.Position.x - j2.Position.x)**2
y = (j1.Position.y - j2.Position.y)**2
z = (j1.Position.z - j2.Position.z)**... |
"""
Base classes for windows used by wxGlade
@copyright: 2002-2007 Alberto Griggio
@copyright: 2014-2016 Carsten Grohmann
@copyright: 2016-2020 Dietmar Schwertberger
@license: MIT (see LICENSE.txt) - THIS PROGRAM COMES WITH NO WARRANTY
"""
import logging
import wx
import new_properties as np
import edit_base
import ... |
import logging
from tangled.web import Resource, config
from tangled.site import auth
log = logging.getLogger(__name__)
class SignUp(Resource):
@config('text/html', template='auth/sign-up.mako')
def GET(self):
"""Show sign-up form."""
req = self.request
if req.user:
loc... |
# -*- coding: utf-8 -*-
# Copyright (c) 2021 Ramon van der Winkel.
# All rights reserved.
# Licensed under BSD-3-Clause-Clear. See LICENSE file for details.
from django.test import TestCase
from BasisTypen.models import BoogType
from Functie.models import maak_functie
from NhbStructuur.models import NhbRegio, NhbV... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
import numpy as np
from numpy.testing import assert_allclose
import astropy.units as u
from astropy.table import Table
from astropy.time import Time
from gammapy.data import GTI
from gammapy.datasets import Datasets, SpectrumDataset, Spectrum... |
from .sendgrid import Sendgrid
from .slack import Slack
from .smtp import SMTP
from .purecloud import Purecloud
from .sms import SMS_never
|
from django.contrib import admin
# Register your models here.
from issue.models import IssueModel
class IssueAdminModel(admin.ModelAdmin):
list_display = ['issue_id', 'issue_name', 'choice']
search_fields = ['issue_id', 'issue_name']
list_display_links = ['issue_id', 'issue_name']
admin.sit... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
import collections
# 读取文件
fn = open('./data/{}.txt'.format(sys.argv[1])) # 打开文件
string_data = fn.read() # 读出整个文件
fn.close() # 关闭文件
list = string_data.split( )
word_counts = collections.Counter(list) # 词频统计
word_counts_top100 = word_counts.most_common(100) # 获取前100... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.