content stringlengths 5 1.05M |
|---|
import pyblish.api
class ValidateMindbenderRigFormat(pyblish.api.InstancePlugin):
"""A rig must have a certain hierarchy and members
- Must reside within `rig_GRP` transform
- out_SET
- controls_SET
- in_SET (optional)
- resources_SET (optional)
"""
label = "Rig Format"
order = ... |
#!/usr/bin/env python3
import re
import web
import html.parser
import requests
import random
from bs4 import BeautifulSoup
def stripHTML(input):
pass1 = re.compile("(?s)<[^>]*>(\\s*<[^>]*>)*")
pass2 = re.compile("&.*?;")
pass3 = re.compile("<.*?>")
input = re.sub(pass1, "", input)
input = re.sub(pas... |
"""
TextbookChecker
this main file include main menu call back function
and connect the other event to editor and etc.
@author: Tang142857
@file: apply.py ,Create at: 2021-02-14
Copyright(c): DFSA Software Develop Center
"""
import os
import sys
import tkinter
import tkinter.messagebox
import exceptions
from Element ... |
default_app_config = 'messages.apps.MessagesConfig' |
import sys
import os
from maya import cmds, mel
sys.path.append(r"D:\Works\Python\GitHub\ncachefactory")
for key in sys.modules.keys():
if 'ncachefactory' in key:
print key
del sys.modules[key]
curve_datas = [
[[-0.5013213131287726, 0.8011000872394779, 0.1486628455862964],
[-0.5615229840... |
import pyvista
pl = pyvista.Plotter()
pl.enable_anti_aliasing()
_ = pl.add_mesh(pyvista.Sphere(), show_edges=True)
pl.show()
|
#!/usr/bin/env python
import sys
#at first tried printing every iteration
flag_encrypted = 'EDINEDEMGEKEALMAEFEDBIECE'
A = ['A','O','V']
B = ['B','P','W']
C = ['C','Q','X']
D = ['D','R','T']
E = ['E','S','Z']
F = ['F','T','T']
G = ['N','U','U']
permutations=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
def getL... |
#!/usr/bin/env python
__author__ = 'Florian Hase'
#=======================================================================
import pickle
from utilities import Logger
#=======================================================================
class DB_Writer(Logger):
def __init__(self, config):
self.conf... |
from py3o.formats.main import UnkownFormatException
from py3o.formats.main import Formats
from py3o.formats.main import Format
from py3o.formats.main import FORMAT_DOCBOOK
from py3o.formats.main import FORMAT_HTML
from py3o.formats.main import FORMAT_ODT
from py3o.formats.main import FORMAT_PDF
from py3o.formats.main i... |
"""
Tools for organizing, normalizing echelle spectra.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import matplotlib.pyplot as plt
import numpy as np
from scipy.ndimage import gaussian_filter1d
from scipy.optimize import least_squares
from scipy.stat... |
import numpy as np
import threading
import queue
import time
from common import gtec
import matplotlib.pyplot as plt
from common.config import *
class Recorder:
def __init__(
self,
sample_duration=SAMPLE_DURATION,
num_channels=2,
channel_offset=0,
signal_type="emg",
):
... |
# coding: utf-8
import requests
import json
import time
import logging
import os
import difflib
import pdb
from coreutils.logdecorator import logwrap
@logwrap
def file_len(fname):
'''
file_len method to take file name and provide filelen
'''
i = 0
with open(fname) as f:
f... |
#######################################
# Imporant Imports
#######################################
import os
import unittest
from saw_client import *
from saw_client.crucible import *
from saw_client.llvm import *
from saw_client.proofscript import *
from saw_client.llvm_type import *
####... |
"""
for crontab to work, type "crontab -e" in the terminal and add the following:
* * * * * python /home/bi0max/projects/tutorials/flask_tutorial/flask_tutorial/cron_job.py
it will run it every minute
"""
from datetime import datetime
path = "/home/bi0max/projects/tutorials/flask_tutorial/cron_test.txt"
with open(... |
"""Noise models for empirical fitting.
"""
import numpy as np
def piecewise_noise(f, n0, exp=[0], fc=[0]):
"""Piecewise noise specified corner frequencies and exponents
Parameters
----------
f: list of int/float or numpy.ndarray
The frequency axis of the noise.
n0: int/float
The n... |
import random
import torch
from torch.autograd import Variable
class BufferPool():
def __init__(self, pool_size):
self.pool_size = pool_size
if self.pool_size > 0:
self.num_buffer_batches = 0
self.buffers = []
def query(self, buffer_batch):
if self.pool_size == ... |
# pylint: disable=unused-argument
import string
from datetime import date, datetime
import pytz
from prompt_toolkit.application.current import get_app
from prompt_toolkit.formatted_text import FormattedText
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout import HSplit, VSplit
from prompt_toolkit.layout... |
import pandas as pd
from sys import argv
import pyperclip
import xlrd
xlsFile = 'tables.xlsx'
book = xlrd.open_workbook(xlsFile)
sheetNames = book.sheet_names()
notDataNames = []
for sheet in sheetNames:
if sheet.find('_data') < 0:
notDataNames.append(sheet)
first = True
choice = 0
while choice<1 or cho... |
class Solution:
def peakIndexInMountainArray(self, A: List[int]) -> int:
# 二分查找应该可以更快。 但是这个数据范围很小。直接遍历也无所谓
i, length = 1, len(A)
while i <length and A[i-1] < A[i]:
i += 1
return i-1
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('seaborn')
from Status import *
from BackTest import BackTest
def plot_obv(stock, plt_df, plot_full_location, cur_descp, OBV_EMA):
plt_df = plt_df.set_index(pd.DatetimeIndex(plt_df['Date'].values))
#Plotting the... |
#!/usr/bin/env python
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.node import CPULimitedHost, OVSController
from mininet.link import TCLink
from mininet.util import dumpNodeConnections
from mininet.log import setLogLevel
from mininet.util import pmonitor
from signal import SIGINT
from ti... |
# -*- coding: utf-8 -*-
"""This module provides an abstract class Alg for iterative algorithms,
and implements commonly used methods.
"""
import numpy as np
from sigpy import backend, util, config
if config.cupy_enabled:
import cupy as cp
class Alg(object):
"""Abstraction for iterative algorithms.
The s... |
from scipy.stats import norm
import matplotlib.pyplot as plt
import random
import numpy as np
lambdaa = 0.5
def targetFunc(x):
return 1/np.pi*(lambdaa/(lambdaa**2+(x-0)**2))
T = 10000
pi = [0 for i in range(T)]
for t in range(T-1):
p_ = norm.rvs(loc=pi[t], scale=1, size=1, random_state=None)[0] ... |
#!/usr/bin/env python3
import argparse
import math
import sys
import os
import time
import re
TIME_EST_REGEX = re.compile(r"VTR_RUNTIME_ESTIMATE_SECONDS=(?P<time_sec>.*)")
MEM_EST_REGEX = re.compile(r"VTR_MEMORY_ESTIMATE_BYTES=(?P<mem_bytes>.*)")
JOB_INFO_REGEX = re.compile(
r"(.*/)?(?P<task>[^/]*)/run(?P<run>\d+)... |
# Models for testing
from django.db import models
class Musician(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
instrument = models.CharField(max_length=100)
class Meta:
app_label='djagger.tests' |
""" pre defined pipelines for download """
from datetime import datetime
from pathlib import Path
from typing import Union
from gribmagic.unity.download.engine import run_download
from gribmagic.unity.enumerations import WeatherModel
from gribmagic.unity.index import make_fileindex
from gribmagic.unity.model import Ac... |
imeMojeVarijable = "Python" #CamelCase
ImeMojeVarijable = "Python" #PascalCase
ime_moje_varijable = "Python" #SnakeCase
|
# fixed: OS X matplotlib crashing issue
import matplotlib
matplotlib.use("TkAgg")
from tkinter import Tk, Toplevel, Menu, Scale, Canvas
from tkinter.ttk import Frame, Labelframe, Button, Label
from utils.plot import draw_figure
from config import *
from utils.pagerank import pagerank
from utils.edges import randEdge... |
import pandas as pd
import numpy as np
from sklearn.metrics import classification_report
def binary_backtests_returns(
backtests: pd.DataFrame,
) -> pd.DataFrame:
"""
Converts a Horizon backtest data frame into a binary backtests of directions
"""
return backtests.diff().apply(np.sign).dropna()
... |
class ByteBitArray:
# example:
# |FFFF|0F0F|FACE|...
# 0 1 2
def __init__(self,arg=10*2**20): # 10 mebibyte chunks by default
if type(arg) is int:
self.val = bytearray(arg)
elif type(arg) is bytearray: ## TODO: see if this can be done in one memory write instead of ... |
def test_home_page(test_client):
"""
Тест доступности главной страницы
"""
response = test_client.get('/')
assert response.status_code == 200
assert b'Github Pull checker' in response.data
def test_search(test_client): # не совсем верный подход
search = test_client.post('/', data=dict(use... |
# Time: O(n)
# Space: O(n)
class Solution(object):
def boxDelivering(self, boxes, portsCount, maxBoxes, maxWeight):
"""
:type boxes: List[List[int]]
:type portsCount: int
:type maxBoxes: int
:type maxWeight: int
:rtype: int
"""
dp = [0]*(len(boxes)+1... |
# Author: aqeelanwar
# Created: 6 July,2020, 12:14 AM
# Email: aqeel.anwar@gatech.edu
from PIL import ImageColor
import cv2
import numpy as np
COLOR = [
"#fc1c1a",
"#177ABC",
"#94B6D2",
"#A5AB81",
"#DD8047",
"#6b425e",
"#e26d5a",
"#c92c48",
"#6a506d",
"#ffc900",
"#ffffff",
... |
import json
from WH_Utils.Objects.User import User
from WH_Utils.Utils.test_utils import WH_auth_dict,BASE_URL
import requests
class TestUser:
def test_user_valid_json(self):
with open("tests/test_data/objects_data/user.json", 'r') as f:
data = json.load(f)
user = User(data_dict=data)
... |
from __future__ import absolute_import
from __future__ import print_function
import argparse
import subprocess
import sys
import os
from aetros.utils import read_home_config, setup_git_ssh, read_config, git_has_local_job, git_has_remote_job, \
find_config
class JobCatCommand:
def __init__(self, logger):
... |
import numpy as np
from .utils import evaluate_responders
from .pop_stochastic import stoch_pop
from .pop_deterministic import det_pop
from .germinal_center import germinal_center
def simulate_immscheme(sim_type, D_inj, T_delay, meas_prot, par):
'''
This function simulates an immunization scheme and returns ... |
def download_c3s(date,centre,system,variable,frequency,outdir):
import cdsapi
import os
c = cdsapi.Client()
year = date.strftime('%Y')
month = date.strftime('%m')
day = date.strftime('%d')
leadtime_hour=[]
if frequency == 'daily':
for i in xrange(216):
leadtime_hour.a... |
import argparse, random, gc, time
from os import path
import numpy as np
import torch
import torch.optim as optim
from utility import *
from PyCoreNLP import PyCoreNLP
from mylog import mylog
from options_process import optionsLoader
from data_process import *
from vocabulary import Vocabulary
from layers.framework ... |
from .core import DNN
from .interaction import FM
from .sequence import SequencePoolingLayer, LocalActivationUnit, AUGRUCell
from .activation import Dice
from .tools import (
ValueTable,
SampledSoftmaxLayer,
CustomEmbedding,
SqueezeMask,
PositionEmbedding,
)
__all__ = [
"DNN",
"FM",
"S... |
##### Import packages
# Basic packages
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# Other packages
from memory_reduction_script import reduce_mem_usage_sd as mr # I'm using a memory reduction script to reduce DataFrame memory size
from sklearn.impute import SimpleImput... |
from django.core.exceptions import ObjectDoesNotExist
from django.template import Context, RequestContext, loader
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site
from django import http
def shortcut(request, content_type_id, object_id):
"Redirect to an object... |
import pytest
from gtfs_realtime_translators.translators import WcdotGtfsRealTimeTranslator
from gtfs_realtime_translators.factories import FeedMessage
from gtfs_realtime_translators.bindings import intersection_pb2 as intersection_gtfs_realtime
@pytest.fixture
def wcdot_bus():
with open('test/fixtures/wcdot_bus.... |
"""
Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
See https://llvm.org/LICENSE.txt for license information.
SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Helper functions for working with sockets.
"""
# Python modules:
import io
import socket
# LLDB modules
import use_lldb_s... |
from sys import exit
def start():
print("历经千辛万苦,一行人来到了佛祖面前")
print("""佛祖:
是不是很好奇你会怎样飞升
是不是觉得自己玩这个神坑游戏很久了,已经摸清楚套路了
""")
print("是 or 不是")
choice = input("> ")
if choice == "是":
print("佛祖:我真的佩服你的勇气\n神坑的名头你以为是闹着玩儿的咩!\n你是在蔑视佛祖吗!!!")
print("佛祖差一点气昏过去,你就差1、、就凉凉了。")
print("佛祖:calm down calm down\n我可以再给你一个机会\n我们石头... |
import logging
import os
import random
import hydra
from hydra.utils import instantiate
import numpy as np
import torch
import wandb
from allennlp.nn.util import get_text_field_mask
from torch.distributions import Categorical
from omegaconf import OmegaConf
from viraal.config import (flatten_dict, get_key, pass_conf... |
import numpy as np
import scipy.stats as spstats
from abc import ABC, abstractmethod
# TODO: implement histogram mdl with proper discretization.
def np_number_1d(x, dtype=np.dtype("f8"), copy=True):
"""Convert x to 1d np number array
Args:
x (1d sequence of values convertable to np.number)
d... |
from pandaharvester.harvestercore import core_utils
from .base_stager import BaseStager
import uuid
# logger
_logger = core_utils.setup_logger('dummy_stager')
# dummy plugin for stager
class DummyStager(BaseStager):
# constructor
def __init__(self, **kwarg):
BaseStager.__init__(self, **kwarg)
#... |
# Required modules
import os
from datetime import datetime, timedelta
# Project Files
import flight_search
import data_manager
import notification_manager
import dotenv
dotenv.load_dotenv() # Loads .env file
# Objects created from classes
data_manager = data_manager.DataManager()
flight_search = flight_search.Flig... |
# Generated by Django 2.0.5 on 2018-09-14 07:26
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('api', '0006_auto_20180912_1836'),
]
operations = [
migrations.AddField(
model_name='booking',
name='gues... |
import pytest
from django.core.exceptions import ImproperlyConfigured
from tg_react.webpack import WebpackConstants
def example_constants(context):
return list()
invalid_constants = None
def test_default_constants():
assert WebpackConstants.collect() == {'SITE_URL': 'http://127.0.0.1:8000', 'STATIC_URL':... |
#!/usr/bin/env python
# coding: utf-8
# In[44]:
import pandas as pd
import numpy as np
import datetime
import urllib
import time
from urllib.request import urlopen
import requests
from alphacast import Alphacast
from dotenv import dotenv_values
API_KEY = dotenv_values(".env").get("API_KEY")
alphacast = Alphacast(... |
from plotly import colors, exceptions, optional_imports
from plotly.figure_factory import utils
import io
import numpy as np
import os
import pandas as pd
import warnings
from math import log, floor
from numbers import Number
pd.options.mode.chained_assignment = None
shapely = optional_imports.get_module('shapely'... |
# Copyright (c) 2018-2020 Niko Sandschneider
|
from jedi._compatibility import Parameter
from jedi.cache import memoize_method
class _SignatureMixin(object):
def to_string(self):
def param_strings():
is_positional = False
is_kw_only = False
for n in self.get_param_names(resolve_stars=True):
kind = n.... |
import csv
import copy
from pathlib import Path
import shutil
import natsort
from glob import glob
def csv_out(id,dataset, model, epoch,rlt,val_scale):
ori = copy.copy(rlt)
rlt.sort(reverse=True)
rlt_csv = []
idx_csv = []
for i in range(0, 5):
rlt_csv.append("%.7f" % (rlt[i]))
... |
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
from . import utility
def _resize(data, factor, axis=0, verbose=False):
"""
Do the work of resizing image data along horizontal or vertical axis.
factor:
positive value larger than one implies ... |
import networkx as nx
from data_pipeline import read_and_process_data, convert_network_to_newick_format
from lineage_solver.lineage_solver import solve_lineage_instance
from lineage_solver.solution_evaluation_metrics import cci_score
string_sample_values = read_and_process_data("ivlt_data/IVLT-2B_ALL.alleleTable.txt"... |
from PygFW.Image.ImageObject import ImageObject
class ImageBank:
def __call__(self, image_key):
return self.get(image_key)
def __repr__(self):
return f"""<Image Bank Object (size={self.size}, _dict_={self._dict_})>"""
def __init__(self):
self._bank = {}
@property
def... |
from hashlib import sha1
from random import randint
from urllib.parse import urlencode
from urllib.parse import urlparse
from urllib.parse import urlunparse
from urllib.request import urlopen
from bencodepy import decode as bdecode
from bencodepy import encode as bencode
from peer import Peer
from peer import peers_fro... |
# encoding='utf-8'
'''
/**
* This is the solution of No.43 problem in the LeetCode,
* the website of the problem is as follow:
* https://leetcode-cn.com/problems/multiply-strings
* <p>
* The description of problem is as follow:
* ===================================================================================... |
from bottle import *
@get("/messages")
def get_messages(mongodb):
return {
"messages": [
{
"id": "message id 1",
"user": "user id 1",
"room": "room id 1",
"text": "message text 1"
},
{
"id": ... |
# -*- coding: utf-8 -*-
# @Time : 2017/7/13 上午11:18
# @Author : play4fun
# @File : 23.1.4 为什么拉普拉斯算子是高通滤波器.py
# @Software: PyCharm
"""
23.1.4 为什么拉普拉斯算子是高通滤波器.py:
从图像中我们就可以看出每一个算子允 些信号。从 些信息中我 们就可以知 些是 HPF 是 LPF
"""
import cv2
import numpy as np
from matplotlib import pyplot as plt
# simple averaging filte... |
# -*- coding: utf-8 -*-
"""Processes artifacts using a local plaso process."""
import os
import subprocess
import tempfile
import uuid
from typing import Optional
from typing import Union
from typing import List
import docker
from dftimewolf.lib import module
from dftimewolf.lib.containers import containers
from dftim... |
"""
Lines 5 and 6 were adapted from SO code:
http://stackoverflow.com/questions/4383571/importing-files-from-different-folder-in-python
"""
import sys
sys.path.insert(0, '..')
""" END """
import main as program
import pytest
def test_for_0():
assert program.calculate_int([0]) == 0
def test_for_1():
assert pr... |
import AST as Tree
from TopCompiler import Types
def singleReadPass(tree):
unusedLocals = [{}]
funcs = [tree]
def loop(node):
deleted = 0
for iter in range(len(node.nodes)):
iter -= deleted
i = node.nodes[iter]
if type(i) is Tree.Create:
... |
print("Happy Tuesday Night.")
from my_mod import enlarge
df = pandas.DataFrame({"x":[1,2,3], "y":[3,4,5]})
print(df.head())
x = 5
print(x, "ENLARGE", x, "T", enlarge(x))
y = float(input("Please input number"))
print(enlarge(y))
|
from product.models import Product
from content.models import Question, Answer
from django.db import models
from django.conf import settings
# Create your models here.
class UserProduct(models.Model):
product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
user = models.ForeignKey(settings... |
from django.contrib import admin
from taggit.models import Tag, TaggedItem
class TaggedItemInline(admin.StackedInline):
model = TaggedItem
class TagAdmin(admin.ModelAdmin):
list_display = ["name","slug"]
search_fields = ('name','slug')
inlines = [
TaggedItemInline
]
def has_add_per... |
import asyncio
import logging
import time
from surrortg import Game # First we need import the Game
from surrortg.inputs import Switch # and our preferred input(s)
from surrortg.inputs import Joystick
# Create a custom switch, it really can do what ever you want.
class MySwitch(Switch):
async def on(self, seat... |
import argparse
import torch
def fix_joint_s2t_cfg(path_to_ckpt):
ckpt = torch.load(path_to_ckpt, map_location=torch.device("cpu"))
if "mustc" in path_to_ckpt:
ckpt["cfg"]["model"].load_pretrain_speech_encoder = ""
ckpt["cfg"]["model"].load_pretrain_text_encoder_last = ""
ckpt["cfg"... |
#!/usr/local/bin/python2.7
# encoding: utf-8
import locale
alllocale = locale.locale_alias
for k in alllocale.keys():
print 'locale[%s] %s' % (k, alllocale[k])
|
import os
os.system("desktopapp/detectorsz_app DATASET1 ../dataset/images/DATASET1_SMALL 0 0")
os.system("desktopapp/detectorsz_app DATASET1 ../dataset/images/DATASET1_MEDIUM 1 0")
os.system("desktopapp/detectorsz_app DATASET1 ../dataset/images/DATASET1_LARGE 2 0")
os.system("desktopapp/detectorsz_app DATASET2 ../dat... |
from itertools import chain
def combine(filenames):
yield from chain(*(open(f) for f in filenames))
|
"""Configuration of Hetida Designer Runtime
After the import statements you can insert code to import and register your own
source / sink adapter runtime client implementations.
They must comply with following signatures:
async def load_data(
wf_input_name_to_filtered_source_mapping_dict: Dict[str, FilteredSourc... |
#
# instance segmentation using the model from the bioimage.io model-zoo
# the volumes with training and test data are available at https://cremi.org/data/
#
import argparse
import os
import time
import h5py
import numpy as np
def _predict(in_path, out_path, model):
# imports only necessary for prediction
i... |
import os
import configparser
# from datetime import datetime
import requests
from bs4 import BeautifulSoup
AUTH_FILE = os.path.realpath(os.environ.get('AUTH_FILE', './auth.cfg'))
AUTH = 'https://auth.fit.cvut.cz'
EDUX = 'https://edux.fit.cvut.cz'
def auth(target=None, file=None):
"""
Parses config file c... |
__version__ = '0.1.0'
# 0.1.0 - Release of confident learning paper based on this version of cleanlab: https://arxiv.org/pdf/1911.00068.pdf
# - Documentation increase
# - Add examples to find label errors in mnist, cifar, imagenet
# - re-organized examples and added readme.
# 0.0.14 - Major bug fix in classific... |
# Copyright 2018 Artem Artemev @awav
#
# 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... |
import io
import os
import zipfile
import numpy as np
from PIL import Image
from chainer.dataset import download
def get_facade():
root = download.get_dataset_directory('study_chainer/facade')
npz_path = os.path.join(root, 'base.npz')
url = 'http://cmp.felk.cvut.cz/~tylecr1/facade/CMP_facade_DB_base.zip'
... |
import boto3
import sys
sys.path.append('./site-packages')
from crhelper import CfnResource
helper = CfnResource()
@helper.create
def on_create(_, __):
pass
@helper.update
def on_update(_, __):
pass
def delete_s3_objects(bucket_name):
s3_resource = boto3.resource("s3")
try:
s3_resource.Bu... |
import time
import ev_reduce as ev3
import _sources as _src
import _actors as _act
import _input_mock
def reducer_cumsum(event, data):
""" Parse int from the input then add to 'cumsum data' """
text = event[1]
val = 0
try:
val=int(text)
except Exception as e:
action =('ERROR', 'not ... |
# Analyze the ground truth hand annotated audio features with segment presence/segment presence. (Level II)
# [What kind of mistake types there are? What are the types of audio that are labeled there?]
# bar plots indicating how frequent segments/segment types are
# What is the distribution of human audio types for th... |
import numpy as np
import conftest
from finmag.util.oommf.comparison import oommf_m0, finmag_to_oommf
from finmag.util.oommf import mesh, oommf_uniaxial_anisotropy
from finmag.util.helpers import stats
def test_against_oommf():
finmag=conftest.setup(K2=0)
REL_TOLERANCE = 9e-2
oommf_mesh = mesh.Mesh(
... |
description = 'setup for the poller'
group = 'special'
sysconfig = dict(
cache = 'pumahw.puma.frm2'
)
devices = dict(
Poller = device('nicos.services.poller.Poller',
autosetup = True,
# setups for which all devices are polled
# poll = ['lakeshore', 'detector', 'befilter'],
# se... |
class dictionary_iter:
def __init__(self, dictionary: dict):
self.dictionary = dictionary
self.__keys = list(self.dictionary.keys())
self.__end = len(self.__keys)
self.__start = 0
# def __iter__(self):
# for tup in self.dictionary.items():
# yield tup
de... |
import validators
from animal_case import keys_to_snake_case
from flask import Blueprint, g, current_app
from marshmallow import fields
from validate_email import validate_email
from webargs import validate
from grant.email.send import send_email
from grant.utils.misc import make_url
import grant.utils.auth as auth
fr... |
"""
Base class with plot generating commands.
Does not define any special non-GMT methods (savefig, show, etc).
"""
from .clib import LibGMT
from .exceptions import GMTInvalidInput
from .helpers import build_arg_string, dummy_context, data_kind, \
fmt_docstring, use_alias, kwargs_to_strings
class BasePlotting():
... |
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils.validation import check_is_fitted
from feature_engine.dataframe_checks import (
_is_dataframe,
_check_input_matches_training_df,
)
class BaseImputer(BaseEstimator, TransformerMixin):
def _check_transform_inpu... |
import pytest
import unittest
from flask import json
from .setup_tests import Store_Manager_Base
store_manager = Store_Manager_Base()
#REGISTRATION INPUT FOR TESTS
sample_registration = [
{
"name":"",
"email":"test@mail.com",
"username":"tester2",
... |
from collections import OrderedDict
from abc import ABCMeta, abstractmethod
class Optimizer(object):
__metaclass__ = ABCMeta
def __init__(self, loss):
self.loss = loss
self._tasks = []
self._direction_modifiers = []
self._param_modifiers = []
self._directions = None
... |
import os
import dask.dataframe as dd
import holoviews as hv
import geoviews as gv
import parambokeh
import param
from colorcet import cm_n, fire
from bokeh.models import Slider, Button
from bokeh.layouts import layout
from bokeh.io import curdoc
from bokeh.models import WMTSTileSource
from holoviews.operation.datas... |
from MenuItem import MenuItem
class Diner:
STATUSES = ["seated", "ordering", "eating", "paying", "leaving"]
# initialize the variables
def __init__(self, dinerName):
self.name = dinerName
self.order = []
self.status = 0
# defining getter methods for each variable
def getNam... |
# Example of a 2D normal probability density function with covariance
import scipy.stats
from pylab import *; ion()
import probayes as pb
set_lims = (-5., 5.)
set_size_0 = {200}
set_size_1 = {300}
means = [0.5, -0.5]
covar = [[1.5, -1.0], [-1.0, 2.]]
x = pb.RV("x", set_lims, pscale='log')
y = pb.RV("y", set_lims, psca... |
import asyncio
import os
import signal
import sys
try:
import gi
except ImportError:
# app.py is the first module that will be imported when you import toga_gtk.
#
# If Gtk can't be imported, it may be because we're in a virtualenv,
# and the system python libraries aren't visible. This can be fixe... |
#encoding: utf-8
def main():
print('hello, pyinstaller')
if __name__ == '__main__':
main()
|
# Copyright 2020 Makani Technologies 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
from unittest import TestCase
import pandas as pd
from pandas.core.groupby import BinGrouper
import trtools.util.testing as tm
import numpy as np
import trtools.core.timeseries as ts
# start on friday, so second day is saturday
df = tm.fake_ohlc(1000000, freq="5min", start="2000-01-07")
# business days and trading h... |
from gurobipy import *
TIME_LIM = 18000 # 18,000s = 5 hours
# MIP constants
EPS_MIP = 1e-3
EPS_SMALL = EPS_MIP
M = 1e3
class GurobiTimeLimit(Exception):
pass
def create_mip_model(
time_lim=TIME_LIM,
verbose=False,
mipgap=None,
mipgapabs=None,
log_file=None,
displayinterval=None,
):
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 12 19:39:44 2019
@author: z003vrzk
"""
# Python imports
import datetime, unittest, re
# Third party imports
import numpy as np
# Local imports
from finance_graphing import (create_transaction_objects, Income,
plot_integral, calculate_gradi... |
# Beispielprogramm für das Buch "Python Challenge"
#
# Copyright 2020 by Michael Inden
from ch07_recursion_advanced.solutions.ex01_tower import Tower
def solve_tower_of_hanoi(n):
print("Tower Of Hanoi", n)
move_tower(n, 'A', 'B', 'C')
def move_tower(n, source, helper, destination):
if n == 1:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.