content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
#!/usr/bin/env python3
"""This script adds Type B uncertainties to those given in the .apu file.
"""
from sys import exit
from glob import glob
from numpy import matrix
from math import radians, sin, cos, sqrt, atan2, degrees
def dd2dms(dd):
minutes, seconds = divmod(abs(dd) * 3600, 60)
degrees, minutes = d... | python |
# -*- coding: utf-8 -*-
# MIT License
#
# Copyright (c) 2018 ZhicongYan
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... | python |
from ctypes import *
import threading
import json
import os
tls_var = threading.local()
import csv
csv.field_size_limit(500000)
from G2Exception import TranslateG2ModuleException, G2ModuleNotInitialized, G2ModuleGenericException
def resize_return_buffer(buf_, size_):
""" callback function that resizs return buff... | python |
import torch.nn as nn
import torch.nn.functional as F
class CNN(nn.Module):
# https://github.com/rensutheart/PyTorch-Deep-Learning-Tutorials/blob/master/part3_MNIST.py
def __init__(self, n_classes):
super(CNN, self).__init__()
# define all the components that will be used in the NN (these can ... | python |
# Copyright 2014 - Red Hat 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... | python |
from .R2 import R2
| python |
import os
def handle_headers(frame, request, response):
# Send a 103 response.
resource_url = request.GET.first(b"resource-url").decode()
link_header_value = "<{}>; rel=preload; as=script".format(resource_url)
early_hints = [
(b":status", b"103"),
(b"link", link_header_value),
]
... | python |
# Copyright 2018 The Cirq Developers
#
# 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/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | python |
from rest_framework import serializers
from .models import Product
class ProductSerializer(serializers.ModelSerializer):
# Get the image url by serializing `ImageField`
image = serializers.ImageField(max_length=None, allow_empty_file=False, allow_null=True, required=False)
class Meta:
# Model to... | python |
import os
import platform
import time
import sys
import importlib
import glob
import subprocess
import selectors
import multiprocess
import paramiko
from comm.platform import linux_win, run_cmd_list, run_cmd
from compute import Config_ini
from compute.log import Log
def get_local_path():
"""
:return:Get... | python |
# coding: utf-8
from django.core.management.base import BaseCommand, CommandError
from ...models import Account, Tweet
class Command(BaseCommand):
"""Generates the HTML version of all the Tweets.
Does this by re-saving every Tweet, one-by-one.
For one account:
./manage.py generate_tweet_html --accou... | python |
import pytest
@pytest.fixture
def supply_AA_BB_CC():
aa=25
bb =35
cc=45
return [aa,bb,cc] | python |
#!/usr/pkg/bin/python2.7
from __future__ import print_function
# grep: serach for string patterns in files
import sys
import os
import argparse
import re
def _fg(file, pattern, ops):
with open(file, 'r') as f:
text = f.readlines()
z = len(text)
for i in range(z):
line = text[i]
result = patt... | python |
from collections import defaultdict
import dill
import numpy as np
import time
import torch.multiprocessing as mp
mp.set_sharing_strategy('file_system')
from starter_code.infrastructure.log import renderfn
from starter_code.sampler.hierarchy_utils import flatten_rewards, build_interval_tree, set_transformation_ids, ge... | python |
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | python |
#-*- coding:utf-8 -*-
# 2.2 变量
message = "Hello Python world!"
print(message)
message = "现在的时间是:2021年6月11日21:07:18"
print(message)
# 2.3 字符串
name = "ada love lace"
print(name.title())
print(name.upper())
print(name.lower())
first_name = "ada"
last_name = "love lace"
full_name = first_name + last_name
print(full_name... | python |
from .model_108_basicDdSt import BasicDdSt
| python |
import numpy as np
from py_wake.site._site import UniformWeibullSite
from py_wake.wind_turbines import OneTypeWindTurbines
wt_x = [134205, 134509, 134813, 135118, 135423]
wt_y = [538122, 538095, 538067, 538037, 538012]
power_curve = np.array([[3.0, 0.0],
[4.0, 15.0],
[... | python |
import unittest
class Solution:
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
if not citations:
return 0
citations.sort(reverse=True)
h = 0
for i in citations:
if i > h:
h += 1
... | python |
# -*- coding: utf-8 -*-
"""Console script for rps."""
import click
from .log import get_log
import asyncio
from .server import Site
from .api import start
def validate_url(ctx, param, value):
try:
return value
except ValueError:
raise click.BadParameter('url need to be format: tcp://ipv4:por... | python |
from .controllers.product import ProductController
from .models import commerce
from .models import inventory
from django import forms
from django.db.models import Q
class ApplyCreditNoteForm(forms.Form):
required_css_class = 'label-required'
def __init__(self, user, *a, **k):
''' User: The user wh... | python |
from typing import Tuple
from hypothesis import given
from gon.base import (Compound,
Geometry)
from gon.hints import Scalar
from tests.utils import (equivalence,
robust_invert)
from . import strategies
@given(strategies.geometries_with_coordinates_pairs)
def test_basi... | python |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from math import fabs
import compas
import numpy as np
import scipy as sp
import scipy.linalg
import scipy.sparse
import scipy.sparse.linalg
def compute_displacement_x(mesh, gate_points, x_size, z_size, coeff... | python |
"""
A class to hold polytopes in H-representation.
Francesc Font-Clos
Oct 2018
"""
import numpy as np
class Polytope(object):
"""A polytope in H-representation."""
def __init__(self, A=None, b=None):
"""
Create a polytope in H-representation.
The polytope is defined as the set of
... | python |
import udfalcon
def test_outputs_return_results():
assert isinstance(udfalcon.fly({'output': 'return', 'mode': 'test'}), dict)
| python |
import re
def main():
eventRegex = r'\s*\n*-{50,}\s*\n*'
placeRegex = r'(?i)(?:place|yer|location|mekan)\s*:\s+(.*?)\s*?[\n\r]'
dateRegex = r'(?i)(?:date|tarih|deadline)\s*:\s+(.*?)\s*?[\n\r]'
timeRegex = r'(?i)(?:time|zaman)\s*:\s+(.*?)\s*?[\n\r]'
testData = getTestData()
for i in range... | python |
import graphene
from .models import Media
from .service import MediaService
service = MediaService()
class MediaType(graphene.ObjectType):
'''
Media Type,
represents a GraphQL version of a media entity
'''
id = graphene.ID(required=True)
mime = graphene.String(required=True)
data ... | python |
'''
This is Main class of RFCN Model
Contain the model's framework and call the backbone
'''
from KerasRFCN.Model.ResNet import ResNet
from KerasRFCN.Model.ResNet_dilated import ResNet_dilated
from KerasRFCN.Model.BaseModel import BaseModel
import KerasRFCN.Utils
import KerasRFCN.Losses
import keras.layers as KL
impo... | python |
# -*- coding: utf-8 -*-
"""Utilities for interacting with data and the schema."""
import json
import logging
from collections import defaultdict
from functools import lru_cache
from pathlib import Path
from typing import Dict, Mapping, Set, Union
from .constants import (
BIOREGISTRY_PATH,
COLLECTIONS_PATH,
... | python |
from dataclasses import dataclass
from time import time
from typing import Union, Tuple
import psycopg2
from loguru import logger
from pony.orm import Database, Required, PrimaryKey, db_session
@dataclass()
class GetQuery:
mol_smi: str
search_type: str
fp_type: Union[bool, str] = False
sort_by_simila... | python |
from substrateinterface import SubstrateInterface
import os
from utils import get_project_root_dir
# execution environment (for testing) --------------
main_script = os.path.join(get_project_root_dir(), "StakingManager.py")
# to get your python env, execute "which python" in CLI with env activated
# E.g. for anaconda ... | python |
from aurora.amun.client.session import AmunSession
def main():
# Calling with no token in constructor will load one from an environment variable if provided
# or a file in HOME/.
session = AmunSession()
print("Getting Valuations")
valuations = session.get_valuations()
numToShow = 5
print... | python |
import torch
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence
from torch import Tensor
from models.convolutional_rnn import Conv2dLSTM
class RNNEncoder(nn.Module):
def __init__(self, num_layers: int = 2, hidden_size: int = 512, action__chn: int = 64, speed_chn: int = 64):
super(R... | python |
# from .helpers.utils_ import *
# from .helpers.math_ import MathClass
# from .helpers.mm import MatrixMadness
from .main import *
| python |
from __future__ import print_function
from __future__ import absolute_import
import astroid
from pylint.interfaces import IAstroidChecker
from pylint.checkers import BaseChecker
from pylint.checkers.utils import check_messages
MSGS = {
'E1113': ('Import inside a function from shining is not allowed',
... | python |
from selenium import webdriver
class Application:
def __init__(self):
self.wd = webdriver.Chrome(executable_path="C:\\chromedriver_win32\\chromedriver.exe")
self.wd.implicitly_wait(60)
def open_home_page(self):
wd = self.wd
wd.get("http://localhost/addressbook/addressbook/grou... | python |
"""protected and listed fields on Location
Revision ID: f8c342997aab
Revises: 5df6df91a533
Create Date: 2021-02-02 11:10:09.250494
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'f8c342997aab'
down_revision = '5df6df91a533'
branch_labels = None
depends_on = No... | python |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from click_captcha import ClickCaptcha
import fire
import sys
import codecs
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
sys.stdout.write("Your content....")
def main(app_name, count=300, enable_dummy_word=False, font_path="extend/msyh.ttf", word_list_file_path... | python |
from __future__ import absolute_import, print_function, unicode_literals
import sys
import binascii
import base64
from zope.interface import implementer
from pyramid.interfaces import IAuthenticationPolicy
from pyramid.authentication import CallbackAuthenticationPolicy, \
AuthTktAuthenticationPolicy
from py... | python |
import indicators.indicator_settings as indicator_settings
settings = indicator_settings.global_settings['VAR_LB']
table_name = "VAR_LB"
for i in list(settings.keys()):
table_name += "_" + str(settings[i])
settings.update(
{
'db_path' : indicator_settings.indicators_root_path + "/var_lb/var_lb_db.sqlit... | python |
from tkinter import *
from tkinter import ttk
from PIL import Image, ImageTk
from tkinter import messagebox
import mysql.connector
from mymain import AAS
def main():
win = Tk()
app = Login_Window(win)
win.mainloop()
class Login_Window:
def __init__(self, root):
self.root = root
self.... | python |
import pytest
from tests.compiler import compile_base
from thinglang.compiler.errors import SelfInStaticMethod
SELF_USE_IN_STATIC_METHOD = '''
thing Program
has number n1
static does something
{}
'''
def test_direct_self_use_in_static_function():
with pytest.raises(SelfInStaticMet... | python |
# -*- coding: utf-8 -*-
import struct
SIZE = "I"
SIZEB = "B"
def stringToByteList(txt):
byteList = list()
for to in range(0, len(txt), 8):
byteList.append(int(txt[to:to + 8], 2))
return byteList
def byteListToString(byteList):
txt = ""
for element in byteList:
txt = txt + bin(ele... | python |
#!/usr/bin/env python
# Import stuff for compatibility between python 2 and 3
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from builtins import str
from future import standard_library
import os
import numpy as n... | python |
from selenium import webdriver
from training_ground_page import TrainingGroundPage
from trial_page import TrialPage
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
# Test Setup
... | python |
import re
import subprocess
def read_model_list():
with open('latest_model_list.txt') as f:
return f.readlines()
records = read_model_list()
for record in records:
temp = re.search('test[0-9]+', record)
temp = temp.group(0)
temp = re.search('[0-9]+', temp)
test_map = temp.group(0)
... | python |
# -*- coding: utf-8 -*-
#
# This file is part of EUDAT B2Share.
# Copyright (C) 2016 CERN.
#
# B2Share 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 2 of the
# License, or (at your option) any... | python |
"""Apps module for the orp_api app."""
# Third Party
from django.apps import AppConfig
class OrpApiConfig(AppConfig):
"""Configuration for application."""
default_auto_field = 'django.db.models.BigAutoField'
name = 'orp_apps.orp_api'
| python |
# coding: utf-8
"""
Intersight REST API
This is Intersight REST API
OpenAPI spec version: 1.0.9-255
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class BiosPolicy(object):
"""
NOTE: This class is a... | python |
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Type, Union
from vkbottle import ABCView, BaseReturnManager
from vkbottle.dispatch.handlers import FromFuncHandler
from vkbottle.framework.bot import BotLabeler
from vkbottle.modules import logger
from vkbottle_types.events import MessageEvent as _... | python |
from sympl import (
PlotFunctionMonitor, AdamsBashforth, NetCDFMonitor
)
from climt import SimplePhysics, get_default_state
import numpy as np
from datetime import timedelta
from climt import EmanuelConvection, RRTMGShortwave, RRTMGLongwave, SlabSurface
import matplotlib.pyplot as plt
def plot_function(fig, stat... | python |
from threading import Thread
from .data_writer import DataWriter, DataWriterException, PlayerList
from pathlib import Path
from PIL import Image
class ScoredImageWriterException(DataWriterException):
pass
class WriteThread(Thread):
def __init__(self, scored_player_list: PlayerList,
save_dir... | python |
import numpy as np
from qtpy.QtCore import *
from qtpy.QtGui import *
from qtpy.QtWidgets import *
from xicam.core import msg
from xicam.core.data import load_header, NonDBHeader
from xicam.plugins import GUIPlugin, GUILayout, manager as pluginmanager
import pyqtgraph as pg
from functools import partial
from xicam.gu... | python |
from pathlib import Path
from slugify import slugify
from watchdog.events import RegexMatchingEventHandler
from kart.miners import DefaultMarkdownMiner
from kart.utils import KartDict
try:
from yaml import CSafeLoader as YamlLoader
except ImportError:
from yaml import SafeLoader as YamlLoader
import importl... | python |
from flask import session
session['var']='oi'
app.run()
app.secret_key = 'minha chave' (vai no main, tem q fazer isso antes de dar app.run)
#lista de funcionarios no depto
#objeto de depto no funcionario
#inserir admin no formulario (criar um admin padrao com TRUE ja)
#listar projetos > ver detalhes do projeto > (li... | python |
from chalice import Chalice
import requests as rq
import boto3
import os
import json
from datetime import date, timedelta
NYCOD = os.environ.get('NYCOPENDATA', None)
BUCKET, KEY = 'philipp-packt', '311data'
resource = 'fhrw-4uyv'
time_col = 'Created Date'
def _upload_json(obj, filename, bucket, key):
S3 = boto3.c... | python |
from django.shortcuts import render, get_object_or_404
from django.views.generic import (DetailView, UpdateView)
from django.contrib.auth.mixins import (LoginRequiredMixin,
PermissionRequiredMixin)
from .models import Company
class CompanyDetailView(LoginRequiredMixin, DetailView):
"""Detalle de una empresa... | python |
import numpy as np
from skimage._shared import testing
from skimage._shared.testing import assert_equal
from skimage.util._label import label_points
def test_label_points_coords_dimension():
coords, output_shape = np.array([[1, 2], [3, 4]]), (5, 5, 2)
with testing.raises(ValueError):
label_points(co... | python |
from mirage.libs import mosart,utils,io
from mirage.libs.common.hid import HIDMapping
from mirage.core import module
class mosart_keylogger(module.WirelessModule):
def init(self):
self.technology = "mosart"
self.type = "attack"
self.description = "Keystrokes logger module for Mosart keyboard"
self.args = {
... | python |
import torch
from PIL import Image
import matplotlib.pyplot as plt
from torchvision import transforms
# Set up the matplotlib figure
f, axes = plt.subplots(1, 2, figsize=(7, 7), sharex=True)
# Generate a random univariate dataset
img_data = Image.open("../data/Test/Snow100K-L/synthetic/beautiful_smile_00003.jpg").co... | python |
#!/usr/bin/env python3
from olctools.accessoryFunctions.accessoryFunctions import combinetargets, filer, GenObject, MetadataObject, \
make_path, run_subprocess, write_to_logfile
from olctools.accessoryFunctions.metadataprinter import MetadataPrinter
from genemethods.typingclasses.resistance import ResistanceNotes
f... | python |
'''
MIT License
Copyright (c) 2020 Georg Thurner
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish,... | python |
import subprocess
import re
def subprocess_runner(cmd_list, exercise_dir):
with subprocess.Popen(
cmd_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=exercise_dir
) as proc:
std_out, std_err = proc.communicate()
return (std_out.decode(), std_err.decode(), proc.returncode)
def r... | python |
import os
import time
import math
from tkinter import *
import tkinter.ttk as ttk
from ClientEdit import *
from ClientInsert import *
from ClientView import *
class ClientList(Tk):
def label_combo(self, text, frame=None):
if frame == None:
frame = self.__frame_border
frame = Frame(fra... | python |
# coding=utf-8
from django.test import TestCase
from django.test.utils import override_settings
class SlugFieldTest(TestCase):
def test_slugfield_allow_unicode_kwargs_precedence(self):
from wshop.models.fields.slugfield import SlugField
with override_settings(WSHOP_SLUG_ALLOW_UNICODE=True):
... | python |
#!/usr/bin/env python
"""Use to reset pose of model for simulation."""
import rospy
from gazebo_msgs.msg import ModelState
def set_object(name, pos, ori):
msg = ModelState()
msg.model_name = name
msg.pose.position.x = pos[0]
msg.pose.position.y = pos[1]
msg.pose.position.z = pos[2]
msg.pose.... | python |
# pylint: disable=W0212
# type: ignore
"""深度封装Action方法
函数只能在群消息和好友消息接收函数中调用
"""
import sys
from .action import Action
from .collection import MsgTypes
from .exceptions import InvalidContextError
from .model import FriendMsg, GroupMsg
from .utils import file_to_base64
def Text(text: str, at=False):
"""发送文字
:p... | python |
# coding:utf-8
# --author-- binglu.wang
import zfused_api
import zfused_maya.core.record as record
def get_assets():
_assets = {}
_project_id = record.current_project_id()
_project_assets = zfused_api.asset.project_assets([_project_id])
# print _project_assets
for _asset in _project_assets:
... | python |
INPUTPATH = "input.txt"
#INPUTPATH = "input-test.txt"
with open(INPUTPATH) as ifile:
filetext = ifile.read()
data = [chunk for chunk in filetext.strip().split("\n\n")]
from typing import Tuple
IntervalPair = Tuple[int, int, int, int]
def parse_rule(line: str) -> Tuple[str, IntervalPair]:
field, right = line.split... | python |
from __future__ import print_function, with_statement, absolute_import
import shutil
import torch
import logging
import os
from warnings import warn
from ..version import __version__
from .deployer_utils import save_python_function
logger = logging.getLogger(__name__)
def create_pytorch_endpoint(clipper_conn,
... | python |
# Generated by Django 3.1.5 on 2021-02-09 19:59
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='DJIAIndexComposition',
fields=[
('id', mode... | python |
import glob
import os
from Bio import SeqIO
from Bio.Seq import Seq
output_dir_merge = '/scratch/users/anniz44/genomes/donor_species/vcf_round2/merge/details'
genus_cutoff = 3 # >= 3 genera as core
allgenome = output_dir_merge + '/summary/all.genome.gene.faa'
allgenome_denovo = output_dir_merge + '/summary/all.denovo.... | python |
from __future__ import print_function
import numpy as np
from scipy.sparse.linalg import gmres
import scipy.sparse.linalg as spla
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import torch.backends.cudnn as cudnn
import os
import argparse
from tqdm import tqdm
cla... | python |
import cv2
import numpy as np
from util import *
from copy import deepcopy
def get_horizontal_lines (img):
#=====[ Step 1: set parameters ]=====
num_peaks = 5
theta_buckets_horz = [-90, -89]
theta_resolution_horz = 0.0175 #raidans
rho_resolution_horz = 6
threshold_horz = 5
#=====[ Step 2: find lines in (rho, ... | python |
from . import VEXObject
class IRStmt(VEXObject):
"""
IR statements in VEX represents operations with side-effects.
"""
__slots__ = ['arch', 'tag']
def __init__(self, c_stmt, irsb):
VEXObject.__init__(self)
self.arch = irsb.arch
# self.c_stmt = c_stmt
self.tag = in... | python |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
#
# Copyright 2021 The NiPreps Developers <nipreps@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may... | python |
# this is a python script because handling Ctrl+C interrupts in batch
# scripts seems to be impossible
#
# This should always run in the same python that Porcupine uses.
from __future__ import annotations
import subprocess
import sys
import colorama
colorama.init()
prog, directory, command = sys.argv
print(colorama... | python |
import io
import os
import urllib
import boto3
import botocore
import shutil
import subprocess
import tempfile
from google.protobuf import json_format
from pathlib import Path
from threading import Timer
from urllib.parse import urlparse
class NotReadableError(Exception):
pass
class NotWritableError(Exception... | python |
import random
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Rectangle
class Point():
def __init__(self, x, y, label):
self.x = x
self.y = y
self.label = label
def get_x(self):
return self.x
def get_y(self):
retur... | python |
import argparse
import sys
import csv
import os
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
FLAGS = None
BATCH = 8000
Gs = 2 # num of dynamic dims
Gin= 2 # num of input signal dims
TIMESTEP = 0.25
time_points = 200
def Hill_model(x,b,K,links):
# x, current input and state [BATCH,Gin+... | python |
from keras.models import load_model
from keras.preprocessing.sequence import pad_sequences
from numpy import mean
from sklearn.metrics import accuracy_score
from classifier_load_data import tokenizer, sequence_length
def prob_to_class(probs):
return [1 if p >= 0.5 else 0 for p in probs]
# Passing in the relati... | python |
# Copyright 2022 Huawei Technologies 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... | python |
from .schema_base import SchemaBase
| python |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, 2011, Sebastian Wiesner <lunaryorn@googlemail.com>
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the... | python |
## @ingroup Core
# DiffedData.py
#
# Created: Feb 2015, T. Lukacyzk
# Modified: Feb 2016, T. MacDonald
# Jun 2016, E. Botero
# ----------------------------------------------------------------------
# Imports
# ----------------------------------------------------------------------
from copy import deepcopy... | python |
import json
from unittest import TestCase
from GeneralTests.EMInfraResponseTestDouble import ResponseTestDouble
from OTLMOW.Facility.FileFormats.EMInfraDecoder import EMInfraDecoder
from OTLMOW.Facility.OTLFacility import OTLFacility
from OTLMOW.OTLModel.Classes.Omvormer import Omvormer
class EMInfraDecoderTests(Tes... | python |
import logging
import pathlib
class Endpoint:
def __init__(self, source_file, addr, port):
self.name = pathlib.Path(source_file).stem
self.addr = addr
self.port = port
def __repr__(self):
return f'{self.name}@{self.addr}:{self.port}'
class EndpointRegistry:
registry = di... | python |
"""Plugin for emitting ast."""
__all__ = [
"DebugAstOptions",
"DebugAstEmitter",
"debug_ast",
]
from dataclasses import dataclass
from beet import Context, configurable
from beet.core.utils import required_field
from pydantic import BaseModel
from mecha import AstRoot, CompilationDatabase, Mecha, Visi... | python |
#!/usr/bin/env python
"""
CREATED AT: 2021/9/14
Des:
https://leetcode.com/problems/reverse-only-letters
https://leetcode.com/explore/item/3974
GITHUB: https://github.com/Jiezhi/myleetcode
Difficulty: Easy
"""
from tool import print_results
class Solution:
@print_results
def reverseOnlyLetters(self, s: str) -... | python |
import pytest
# Local Functions
from fexception.util import set_caller_override
# Local Methods
from fexception.util import KeyCheck
__author__ = 'IncognitoCoding'
__copyright__ = 'Copyright 2022, test_util'
__credits__ = ['IncognitoCoding']
__license__ = 'MIT'
__version__ = '0.0.2'
__maintainer__ = 'IncognitoCodin... | python |
from math import sqrt
class SomeClass:
'''Some class that certainly does things.
Args:
foo (str): Some string.
'''
def __init__(self, foo: str = 'foo'):
self.msg = f'Here comes {foo}!'
def is_msg_large(self, msg: str):
msg_size = len(msg)
is_large = msg_size > 256... | python |
from fractions import Fraction
def roll(dices, times):
counter = {}
for d in dices:
counter[d] = 1
for t in range(1, times):
acc = {}
for k, v in counter.items():
for d in dices:
acc[k + d] = acc.get(k + d, 0) + v
counter = acc
return counter
... | python |
__author__ = 'faisal'
| python |
import os
import importlib
from functools import partial
KNOWN_MODULES = {
# datasets
'opencv_video_seq_dataset': 'hyperseg.datasets.opencv_video_seq_dataset',
'img_landmarks_transforms': 'hyperseg.datasets.img_landmarks_transforms',
'seg_transforms': 'hyperseg.datasets.seg_transforms',
'transform... | python |
"""Module that provides a data structure representing a quantum system.
Data Structures:
QSystem: Quantum System, preferred over QRegistry (can save a lot of space)
Functions:
superposition: join two registries into one by calculating tensor product.
"""
import numpy as np
from qsimov.structures.qstructure im... | python |
from panoramic.cli.husky.service.select_builder.graph_search import (
sort_models_with_heuristic,
)
from panoramic.cli.husky.service.utils.taxon_slug_expression import TaxonSlugExpression
from tests.panoramic.cli.husky.test.mocks.husky_model import (
get_mock_entity_model,
get_mock_metric_model,
)
from test... | python |
import unittest
import_error = False
try:
from ...tables.base import Base
except ImportError:
import_error = True
Base = None
class TestCase00(unittest.TestCase):
def test_import(self):
self.assertFalse(import_error)
class TestCase01(unittest.TestCase):
def setUp(self):
self.bas... | python |
"""Utility functions."""
import pycountry
def eu_country_code_to_iso3(eu_country_code):
"""Converts EU country code to ISO 3166 alpha 3.
The European Union uses its own country codes, which often but not always match ISO 3166.
"""
assert len(eu_country_code) == 2, "EU country codes are of length 2, yo... | python |
from info import *
from choice import *
from rich.console import Console
from rich.table import Table
import time
from rich import print
from rich.panel import Panel
from rich.progress import Progress
def banner():
print(r"""
_ ___ ____ ____ __ _ _
| | | \ \/ /\ \ / / \/ | __ _/ |... | python |
import os
import sys
from copy import deepcopy
from distutils.version import LooseVersion
import h5py
import numpy as np
import pytest
from ...util.functions import random_id
from ...model import Model
from ...model.tests.test_helpers import get_realistic_test_dust
from .. import (CartesianGrid,
Spher... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.