content stringlengths 5 1.05M |
|---|
"""Log likelihood constructors: the heart of blueice.
"""
from collections import OrderedDict
from copy import deepcopy
from functools import wraps
import numpy as np
from multihist import Histdd
from scipy import stats
from scipy.special import gammaln
from tqdm import tqdm
from .exceptions import NotPreparedExce... |
# -*- coding: utf-8 -*-
import os
import io
import unittest
from testfixtures import TempDirectory
from .. import fs
from .. import localfs
from ..utils import TemporaryFilename
class test_localfs(unittest.TestCase):
def setUp(self):
self.dir = TempDirectory()
def tearDown(self):
self.dir.c... |
from __future__ import absolute_import
from __future__ import unicode_literals
import json
from django import forms
from django.utils.translation import ugettext as _
from corehq import toggles
from corehq.apps.userreports.models import DataSourceConfiguration, \
StaticDataSourceConfiguration
from corehq.apps.user... |
# -*- coding: utf-8 -*-
'''
:codeauthor: Jayesh Kariya <jayeshk@saltstack.com>
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt Testing Libs
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.unit import skipIf, TestCase
from tes... |
import pytest
from xclingo import XclingoControl, XclingoContext
class TestXclingo:
def assert_test_case(self, datadir, test_case, auto_tracing):
xcontrol = XclingoControl(
n_solutions=0,
n_explanations=0,
auto_trace=auto_tracing,
)
xcontrol.add('base',... |
from selenium import webdriver
url = "http://www.naver.com/"
browser = webdriver.PhantomJS()
browser.implicitly_wait(3)
browser.get(url)
browser.save_screenshot("website.png")
browser.quit()
|
#!/usr/bin/env python2.7
# vim : set fileencoding=utf-8 expandtab noai ts=4 sw=4 filetype=python :
"""
stitch help <cmd>
Shows extensive help of the command <cmd>.
"""
from __future__ import print_function
import stitch.datastore
def options(parser):
"""The query command has no options"""
parser.add_argument... |
#!/usr/bin/env python
# This script downloads the most trending 10 wallpapers from a subreddit and saves it to a folder.
"""
Copyright (c) 2021 ShankarCodes. All rights reserved.
You may use, distribute and modify this code under the terms of the
BSD 3-Clause "New" or "Revised" License.
You should have received a cop... |
cid = input('Em que cidade vocรช mora? ') # .strip()
ci = cid.split()
print(f'Essa cidade tem Santo no comeรงo do nome? \033[1;37m{"SANTO" in ci[0].upper()}\033[m')
print(f'Essa cidade tem Santo no comeรงo do nome? \033[0;36m{"SANTO" == cid[:5].upper()}\033[m')
|
# https://docs.python.org/3/library/functions.html
abs(x)
all(iterable)
any(iterable)
ascii(object)
bin(x)
bool(?x)
breakpoint(*args, **kws)
bytearray(?source, ?encoding, ?errors)
bytes(?source, ?encoding, ?errors)
callable(object)
chr(i)
@classmethod()
compile(source, filename, mode, flags=0, dont_inherit=False, optim... |
from pathlib import Path
from setuptools import setup, find_packages
long_description = Path('README.rst').read_text('utf-8')
try:
from sagenet import __author__, __email__
except ImportError: # Deps not yet installed
__author__ = __maintainer__ ='Elyas Heidari'
__email__ = 'eheidari@student.ethz.ch'
... |
#!/usr/bin/python
# -*- coding: iso-8859-1 -*-
import libsbml, sys, re, numpy
def clean_formula(formula):
for s in ['(',')','*','/','+','-',',']:
formula = formula.replace(s,' %s '%s)
for i in range(3): formula = formula.replace(" "," ")
match = re.search(r'\de - ',formula) # e.g. 10e-05 cannot b... |
# TODO: avoid import everything from _mnncengine._nn for visable control
from _mnncengine._nn import *
import _mnncengine._expr as _F
import _mnncengine._nn as _nn
# old call: load_module_from_file(file_name, for_training)
# new call: load_module_from_file(file_name, dynamic=False, shape_mutable=True)
# support two b... |
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import os
from memsource import Memsource
def get_action(module_params):
"""Get action to do based on module.params"""
trimmed_list = {
k: v
for k, v in module_params.items()
... |
from django.test import TestCase
from ted_project.factories import UserFactory, FaceFactory, PictureFactory
class TestFaceModel(TestCase):
def setUp(self):
self.face = FaceFactory(name='test_name')
def test_Face_attributes(self):
self.assertEqual(self.face.name, 'test_name')
class TestPict... |
import os.path
import argparse
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, random_split
from config.ConfigDataset import ConfigDataset
from config.ConfigHyperparams import ConfigHyperparams
from config.ConfigCheckpoints import ConfigCheckpoints
from config.Co... |
# %%
import helper as hp
# Set FIRED base Folder (location where you downloaded the dataset)
hp.FIRED_BASE_FOLDER = "/Volumes/Data/NILM_Datasets/FIRED"
# hp.FIRED_BASE_FOLDER = "~/FIRED"
# load 1Hz power data of the television for complete recording range
television = hp.getPower("television", 1)
print(television)
# %... |
def calc_bmi(x,y):
ans = y/(x*x)
return ans
x = 2
y = 80
if ans < 18:
print("็ฉใๆฐๅณ")
elif 18 <= ans < 25:
print("ๆฎ้")
elif ans >= 25:
print("ๅคชใๆฐๅณ")
|
from typing import Union, Set
from src.api import APITask, APISection
from src.core.errors import TaskError
from src.core.models import Task, Section, Project
from src.utils import Colors
class TaskManager:
def __init__(self, token: str, project: Project):
self.project = project
self.api_section ... |
import pathlib
import yaml
import os
import logging
logger = logging.getLogger(__name__)
with open("settings.yaml", "r", encoding="utf-8") as f:
settings = yaml.safe_load(f)
# check for required directories
required_directories = []
required_directories.append(settings["OUTPUT_DIR_MP3_FILES"])
for each_dir in re... |
# Imports
from . import *
from ..utils import misc
from ..utils import pubtools
from ..parsing.grammars import frontiers
class FrontiersParser(Parser):
'''Parser designed to interact with Frontiers
'''
def parse_document(self, document):
'''Extract and parse references from a document.
... |
# Quebrando um nรบmero
'''Crie um programa que leia um nรบmero Real qualquer
pelo teclado e mostre na tela a sua porรงรฃo inteira
Ex: O nรบmero 6,127 tem a parte inteira 6'''
from math import trunc
num = float(input('Digite um nรบmero qualquer: '))
print('O valor digitado foi \033[7;40m''{}\033[m e a sua porรงรฃo inteira รฉ \0... |
"""
%%
%% Construction du point P(t) d'une courbe de Bรฉzier pour
%% la valeur t du paramรจtre, par l'algorithme de Casteljau.
%%
%% Donnรฉes : XP, YP, ZP coordonnรฉes des points de contrรดle
%% t valeur du paramรจtre
%%
%% Rรฉsultats : x,y,z coordonnรฉes du point P(t) dans R^3
%%
"""
... |
"""Manual test all examples."""
# Import local modules
from photoshop.api import Application
from pathlib import Path
root = Path(__file__).parent.parent.parent.joinpath("examples")
for script_file in root.glob("*.py"):
try:
exec(script_file.read_text())
except Exception as err:
print(f"Test f... |
print("Hallo Python-Welt")
# Kommentarzeile
'''
Kommentarblock
'''
'''
Datentypen (Datenarten) in Python:
Bezeichnung | Fachbegriff | Abkรผrzung | Beispiele
============================================================================================================
Ganzzahl | Integer | ... |
from .base import CustomTestClass
import json
class TestContactUs(CustomTestClass):
def setUp(self) -> None:
self.base_data = {
"name": "Test",
"email": "testuser@example.com",
"query": "This is a test query blah blah blah blah blah blah blah blah blah blah blah blah bl... |
from defusedxml.lxml import fromstring
from lxml import etree
from six.moves import range
from six.moves.urllib.parse import urlparse
from zeep import ns
from zeep.exceptions import XMLSyntaxError
from zeep.parser import absolute_location
class NamePrefixGenerator(object):
def __init__(self, prefix='_value_'):
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from os import path
from yaml import safe_load
from ao.model.render import Render
from unittest import TestCase, expectedFailure
from pytest import mark
class RenderTest(TestCase):
@staticmethod
def parse_yaml(filename):
... |
# /*
# * Copyright (C) 2020 ACTUAL Systems, Inc.
# *
# * http://www.actualhq.com
# *
# * In collaboration with UNICEF/Giga: https://gigaconnect.org
# *
# * 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 c... |
import os
import textwrap
import yaml
from cloudmesh.common.util import readfile
class Converter:
def __init__(self, filename=None, template=None):
# data/catalog/azure/bot_services.yaml"
if not os.path.exists(filename):
raise ValueError("file can not be found")
self.content... |
#!/usr/bin/python
import requests
import json
# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from fields
user_title = form.getvalue('search_title')
print "Content-type: text/html\n\n";
# Setting attributes to send to Wikipedia API
ba... |
import requests
import json
import os
from dotenv import load_dotenv
load_dotenv(verbose=True)
class RestClient:
def __init__(self):
self.base_url = os.getenv("BASE_URL")
self.token = None
def auth(self):
if (self.token):
return self.token
url = f"{self.base_url}/... |
import os
from django.contrib.gis.db import models
from django.conf import settings
class Layer(models.Model):
name = models.CharField(max_length=50,unique=True)
def __unicode__(self):
return u"%s" % (self.name)
class Feature(models.Model):
fid = models.AutoField(primary_key=True)
layer = mod... |
'''
Read and write data to a Lego Mindstorm NXT brick using serial bluetooth
connection. You'll need to modify __init__ for unix style serial port
identification in order to use this on Linux.
Blue enables raw byte transfer
TypeBlue utilizes NXT mailbox number for type identification.
Usage:
1. Enable a bluetooth s... |
import ctypes
so10 = ctypes.CDLL("./so10.so")
def c_array(values):
ArrayType = ctypes.c_double * len(values)
return ArrayType(*values)
so10.average.restype = ctypes.c_double
v1 = []
print(so10.average(c_array(v1), len(v1)))
v2 = [1]
print(so10.average(c_array(v2), len(v2)))
v3 = [1, 2]
print(so10.average... |
N,i=int(input()),1
while N>1:
if N%2: N=3*N+1
else: N//=2
i+=1
print(i) |
# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\situations\situation_simple.py
# Compiled at: 2017-05-24 04:11:51
# Size of source mod 2**32: 10990 ... |
import os
import numpy as np
from datetime import datetime
from math import *
# import jdutil
import bisect
import pdb
from taskinit import *
try:
from astropy.io import fits as pyfits
except:
try:
import pyfits
except ImportError:
raise ImportError('Neither astropy nor pyfits exists in thi... |
#!/usr/bin/env python3
import setuptools
import os
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="dev-container",
version="0.2",
author="Marcel Hollerbach",
author_email="mail@bu5hm4n.de",
description="A small bin tool that will spin up a docker for you... |
"""Contains the class object.
Used to create two-dimensional thermal objects, and apply some methods. It does
not include the compute method.
"""
from ... import mats
import os
import copy
import numpy as np
class Object:
"""Object class.
This class creates a two-dimensional thermal object. It includes tw... |
import re
from docxtpl import DocxTemplate, RichText
from docx.shared import Pt
####test Result including checkpoint and HLA
def checkPoint(TMBFileName, NeoStatisFileName, MMRFileName, POLFileName):
with open(TMBFileName,'r',encoding='utf-8') as snv:
line = snv.readlines()[1]
line = line.... |
#!/usr/bin/env python
# Copyright 2013 Google 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 ... |
from pathlib import Path
from . import cdfread, cdfwrite
from .cdf_factory import CDF
from .epochs import CDFepoch as cdfepoch # noqa: F401
try:
# This is an optional dependency for astropy time conversions
from .epochs_astropy import CDFAstropy as cdfastropy
except:
pass
try:
# Another optional de... |
#coding: utf-8
#------------------------------------------------------------
# Um programa que recebe qualquer coisa, retornando o seu
# tipo primitivo e todas informaรงรตes sobre o dado recebido.
#------------------------------------------------------------
# Dissecando uma variรกvel - Exercรญcio #004
#---------------... |
# coding: utf8
# try something like
import os
raise RuntimeError("remove this line to use!")
# connect to pycon-tech (django) database
pg=DAL('postgres://postgres:saraza@localhost/pycon2010')
# configure path to common/talkdata
PATH = "C:\\PuTTY\\2010\\"
def index(): return dict(message="hello from pycontech.py")
... |
from lettuce import *
from selenium import webdriver
@before.all
def setup_browser():
print("starting browser")
world.browser = webdriver.Firefox()
world.browser.implicitly_wait(3)
@after.all
def teardown_browser_and_server(total):
print("terminating browser")
world.browser.quit() |
#!/usr/bin/env python
__author__ = 'Florian Hase'
#========================================================================
import os
import copy
import time
import uuid
import pickle
import subprocess
import numpy as np
import multiprocessing
from gryffin.utilities import Logger
from gryffin.utilities.decorators... |
"""This module contains the general information for FabricFcMonSrcEpOperation ManagedObject."""
from ...ucscmo import ManagedObject
from ...ucsccoremeta import UcscVersion, MoPropertyMeta, MoMeta
from ...ucscmeta import VersionMeta
class FabricFcMonSrcEpOperationConsts():
ADMIN_STATE_DISABLED = "disabled"
AD... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-11-27 01:10
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('common', '0003_address_label'),
]
operations = [
migrations.AlterField(
... |
from q35_test import (
Q35Project_2_6_0
)
proj = Q35Project_2_6_0()
|
from os import listdir
from os.path import isfile, join
import json
from PIL import Image
import os
memes = []
invalid_images = []
mypath = "memes/3"
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
for file in onlyfiles:
try:
temp = {}
with Image.open('./'+mypath+'/'+file) as i... |
from typing import List
class Solution:
def singleNumber(self, nums: List[int]) -> int:
ones , twos, threes = 0 , 0, 0
for n in nums:
twos |= (ones & n)
ones ^= n
threes = ones & twos
ones &= ~threes # remove the threes from the ones
twos... |
"""
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Tools for creation or conversion of lists from/to desired classification
(the default is ISO 3166-1)
ยฉ econcz, 2021
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
This project was inspired
by **[pycou... |
num=int(input("Enter number :"))
count=0
for i in range(1,num+1):
if (num%i==0):
count=count+1
if count==2:
print(num,"is a prime number")
else:
print(num,"is not a prime number")
# n=int(input("Enter number :"))
# count=0
# i=1
# while(i<=n):
# if n%i==0:
# count=count+1
# i=i+1
# if count==2:
# print("pri... |
# Ivan Carvalho
# Solution to https://www.urionlinejudge.com.br/judge/problems/view/1553
# encoding : utf-8
def frequente(conjunto,numero):
return len([j for j in [conjunto.count(i) for i in set(conjunto)] if j>= numero])
while True:
a,b = [int(i) for i in raw_input().split(" ")]
if a != 0 and b != 0 :
... |
# -*- coding: utf-8 -*-
import yaml
import sys
import numpy as np
import pandas as pd
from time import time
from sklearn.pipeline import make_pipeline
from sklearn.metrics import roc_auc_score
from sklearn.cross_validation import KFold, LeaveOneLabelOut
from collections import OrderedDict
from multipr... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import functools
import tensorflow as tf
from tensorflow_probability.python.bijectors import identity as identity_bijector
from tensorflow_probability.python.distributions import Distribution
fro... |
#!/usr/bin/env python
import numpy as np
import h5py
import matplotlib.pyplot as plt
from matplotlib import gridspec
from os import path
import parameters as param
import argparse
# Configure Command Line interface
controller = dict(tf="target following controller", oa="obstacle avoidance controller")
parser = argpar... |
# bfs_kbacon.py
"""Volume 2A: Breadth-First Search (Kevin Bacon).
<Name>
<Class>
<Date>
"""
# Problems 1-4: Implement the following class
class Graph(object):
"""A graph object, stored as an adjacency dictionary. Each node in the
graph is a key in the dictionary. The value of each key is a list of the
cor... |
# Function bribe:
# takes a queue and a ID k
# and moves k to the front of the queue if found
# else, do nothing
def bribe(queue, k):
for entry in queue:
if k == entry[1]:
sav=entry
queue.remove(entry)
queue.insert(0,entry)
return None
N = int(input("Enter N: "))
tuplist = []
pr... |
from __future__ import print_function, absolute_import
from pygments.lexer import RegexLexer
from pygments.lexer import words
from pygments.token import Literal, Text
from .completer import KubectlCompleter
class KubectlLexer(RegexLexer):
"""Provides highlighting for commands, subcommands, arguments, and option... |
# Generated by Django 3.2.11 on 2022-01-09 02:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('web', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='class',
name='cCode',
),
... |
from flask import Flask, jsonify, render_template
import test, stats, os
app = Flask(__name__)
cache = {}
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route('/r/<string:subreddit>')
def episodes(subreddit):
seasonsAndEpisodes = _getEpisodes(subreddit)
return render_template('index.html',... |
import pathlib
from setuptools import setup, find_packages
import crypto_factory as cf
# The directory containing this file
HERE = pathlib.Path(__file__).parent
# The text of the README.md file
README = (HERE / "README.md").read_text()
# Requirements list
REQUIRED_PKGS = (HERE / "requirements.txt").read_text().spli... |
def prvo_tisoc_mestno_fibonacijevo():
a = 1
b = 1
index = 2
while len(str(b)) < 1000:
c = a
a = b
b = b + c
index += 1
return index
print(prvo_tisoc_mestno_fibonacijevo())
4782 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('djangobb_forum', '0010_remove_topic_views'),
]
operations = [
migrations.AlterModelTable(
name='attachment',
... |
# -*- coding: utf-8 -*-
import argparse
import common
import logging
logger = logging.getLogger(__name__)
def main():
parser = argparse.ArgumentParser(add_help=True)
subparsers = parser.add_subparsers(dest="func")
grs_subparser = subparsers.add_parser("generate_report_from_shelve")
grs_subparser.ad... |
import os
import tempfile
import pytest
from docker import errors
from docker.context import ContextAPI
from docker.tls import TLSConfig
from .base import BaseAPIIntegrationTest
class ContextLifecycleTest(BaseAPIIntegrationTest):
def test_lifecycle(self):
assert ContextAPI.get_context().Name == "default"
... |
# Generated by Django 3.1.6 on 2021-04-08 16:15
import bookwyrm.models.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("bookwyrm", "0067_denullify_list_item_order"),
]
operations = [
migrations.AlterField(
model_name="listitem... |
# -*- coding: utf-8 -*-
"""
xueqiu.sheet
~~~~~~~~~~~~
This module contains stock sheet languages.
:copyright: (c) 2019 by 1dot75cm.
:license: MIT, see LICENSE for more details.
"""
income_lang_us = dict(
sd='ๅผๅงๆฅๆ',
ed='็ปๆๆฅๆ',
report_date='ๆฅๅๆฅๆ',
report_name='ๆฅๅๅ็งฐ',
report_annual='ๆฅๅๅนดๅบฆ',
repo... |
#! /usr/bin/python3
import numpy
import scipy
import matplotlib.pyplot as plt
import random
import datetime
import os
import sys
import time
import math
import argparse
import matplotlib.pyplot as plt
import FastPID
import ArduinoPID
import AutoPID
import refpid
import process
def randomtest(seed, steps, turn... |
#!/usr/bin/python
import sys, re
basewords = [] #default list
answers = [] #list of possible codes
#print help for the lame guyz outside
def printHelp(case):
if case == 1:
print "Use from terminal/cmd with one parameter: list of the words separate by enter."
if case == 2:
print "Input format:... |
import heapq
import collections
class Node(object):
def __init__(self, int, str):
self.freq = int
self.word = str
# ่ชๅฎไนless than comparator
# freqไธๅ็่ฏๆญฃๅธธๆฏ่พ
# freq็ธๅๆถ๏ผ็word, ่ฏๅ
ธๅบๅฐ็ๆๅจๅ้ข
def __lt__(self, other):
if self.freq != other.freq:
return self.freq < other.... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# to use for example with ipython -pylab
# run /home/pierre/Python/Production/Energy_budget/all_terms_loop_days_review.py
# run /scratch/augier/Python/Production/Energy_budget/all_terms_loop_days_review.py
# compute some terms of the spectral energy budget.
# The memory is... |
import matplotlib.pyplot as plt
def draw_graph(final):
if final <= 1:
raise ValueError("specify number bigger than 1")
fibonacci = [1, 1]
for _ in range(final - 2):
fibonacci.append(fibonacci[-1] + fibonacci[-2])
ys = [fibonacci[x + 1] / fibonacci[x] for x in range(len(fibonacci)... |
class Plugin:
"""
A plugin is an extension to the core behavior of bonobo. If you're writing transformations, you should not need
to use this interface.
For examples, you can read bonobo.plugins.console.ConsoleOutputPlugin, or bonobo.plugins.jupyter.JupyterOutputPlugin
that respectively permits... |
"""
Collection of Buffer objects with general functionality
"""
import numpy as np
class Buffer(object):
"""
Abstract class for different kinds of data buffers. Minimum API should have a "push" and "clear" method
"""
def push(self, value):
"""
Pushes a new @value to the buffer
... |
import datetime
import logging
from datetime import timedelta
import homeassistant.helpers.config_validation as cv
import requests
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (CONF_USERNAME, CONF_PASSWORD, CONF_NAME, CONF_MONITORED_VARIABLES)
fro... |
# Generated by Django 2.2.6 on 2019-12-27 21:54
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... |
"""
Copyright (C) 2019 Authors of gHHC
This file is part of "hyperbolic_hierarchical_clustering"
http://github.com/nmonath/hyperbolic_hierarchical_clustering
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 Lice... |
#!/usr/bin/python
#Lyapunov: a library for integrating nonlinear dynamical systems
#Copyright (C) 2013-2018 John Wendell Hall
#
#The author may be reached at jackwhall7@gmail.com.
import time
import lyapunov
import numpy
import matplotlib.pyplot as plt
class MassSpringDemo(object):
"""
Mass spring damper s... |
from fractions import Fraction
c = 1
while True:
line = input()
if line.strip() == "-1":
break
j, X = line.split()
if float(X) == 1.0:
print("Case "+str(c)+": 1/1")
c+=1
continue
if float(X) == 0.0:
print("Case "+str(c)+": 0/1")
c+=1
continue
... |
# author: @netmanchris
# -*- coding: utf-8 -*-
"""
This module contains functions for working with the access point information
capabilities of the HPE IMC WSM Module using the RESTful API
"""
# This section imports required libraries
import json
import requests
from pyhpeimc.auth import HEADERS
def get_ap_info_a... |
# Generated by Django 2.2.7 on 2019-11-13 12:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sitecampus', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='autor',
name='semestre',
... |
print 'a'
print '\t\tHermit'
print 'i know , they are \'great\' '
|
# Copyright (C) 2019-2021 Ruhr West University of Applied Sciences, Bottrop, Germany
# AND Elektronische Fahrwerksysteme GmbH, Gaimersheim Germany
#
# This Source Code Form is subject to the terms of the Apache License 2.0
# If a copy of the APL2 was not distributed with this
# file, You can obtain one at https://www.a... |
from typing import Container
from . import LINE_NUMBER_KEY
from ._base import Filter
class SequenceLengthFilter(Filter):
def __init__(self, min_length: int):
self.min_length = min_length
def test_value(self, inp: dict) -> bool:
return inp['length'] >= self.min_length
class LineNumberFilter... |
from argparse import Namespace
default_args = Namespace(
alpha=0.99,
arch='nba',
batch_size=256,
clip_loss_delta=1.0,
clip_norm=3.0,
clip_norm_type='global',
continuous_target_update=True,
debugging_folder='logs/',
device='cpu',
double_q=True,
dropout=0.5,
e=0.1,
eva... |
"""This file contains various wrappers and functions that ease the code digestion and programming in general.
:platform: linux
.. moduleauthor:: Ivan Syzonenko <is2k@mtmail.mtsu.edu>
"""
__license__ = "MIT"
__docformat__ = 'reStructuredText'
import os
import multiprocessing as mp
import hashlib
from shutil impor... |
"""
python3 predict.py <test_file> <output_file>
python3 predict.py "../resource/asnlib/publicdata/test_review.json" "prediction.json"
spark-submit predict.py <test_file> <output_file>
"""
import sys
import time
import json
from pyspark import SparkConf, SparkContext, StorageLevel
import support
import platform
sys... |
#!/usr/bin/env python3
# coding:utf-8
# ๅๆจ
peaches = 4 # ็ฌฌ 5 ๅช็ดๅญๅๅฎๆก๏ผ่ตท็ ๅฉ 4 ไธชๆกๅญ
while peaches < 5000: # ็ญๆกไธๅฏไธ๏ผๆไธๅจ 5000 ไปฅๅ
ๆ็ดข
tmp = peaches
for i in range(5): # 5 ๅช็ดๅญ
tmp = tmp / 4 * 5 + 1 # ไป็ฌฌ 5 ๅช็ดๅญๅๆจ่ณ็ฌฌ 1 ๅช
if tmp % 1 == 0:
print("Sum = %d" % tmp)
break
else:
p... |
import bakefont3 as bf3
import bakefont3.encode
import unicodedata
from PIL import Image
import numpy as np
class Saveable:
def __init__(self, data):
self.data = data
def bytes(self):
return self.data
def save(self, filename):
with open(filename, 'wb') as fp:
fp.write... |
from nnunet.training.loss_functions.dice_loss import CrossentropyND
from nnunet.training.network_training.nnUNetTrainer import nnUNetTrainer
class nnUNetTrainerCE(nnUNetTrainer):
def __init__(self, plans_file, fold, output_folder=None, dataset_directory=None, batch_dice=True, stage=None,
unpack_d... |
from .agents import (DefaultGymAgent, RandomAgent, BalancedRandomAgent, MinimaxAgent, BaseMonteCarloAgent, HumanInputAgent,
DQNAgent2L_56x5, DQNAgent4L_56x5, DQNAgent2L_56x5_2_sep, DQNAgent2L_17x5_2, DQNAgent2L_17x5_2_sep,
DoubleAgent)
|
# Taken from http://www2.census.gov/geo/docs/maps-data/maps/reg_div.txt
census_regions = {
"CT": "NORTHEAST",
"ME": "NORTHEAST",
"MA": "NORTHEAST",
"NH": "NORTHEAST",
"RI": "NORTHEAST",
"VT": "NORTHEAST",
"NJ": "NORTHEAST",
"NY": "NORTHEAST",
"PA": "NORTHEAST",
"IL": "MIDWEST",
... |
import numpy as np
import scipy.special as sp
from scipy.stats import norm
import matplotlib.pyplot as pl
# Gaussian Process Regression with Censored Data Using
# Expectation Propagation
# Perry Groot, Peter Lucas
l = 1.0
s = 0.2
n = 2000
f = np.linspace(0.0, 2.0, n+1)
sqrt2 = np.sqrt(2.0)
sqrtpi = np.sqrt(np.pi)
cd... |
"""Contains functions for doing the inverse and forward normal mode transforms.
Copyright (C) 2013, Joshua More and Michele Ceriotti
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 ... |
### Import required modules ###
import numpy
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
#import cdms2
### Define globals ###
res='c'
area_threshold = 1.0
# Zoom out for PSA
h = 12000 #height of satellite,
lon_central = 235
lat_central = -60
### Plot the map ###
#map = Basemap(pr... |
from app.routes.inventory import inventory
# Silence flake8 by referencing otherwise unused imports
__all__ = ['inventory'] |
from . import pkcs7, spc, oids, ctl
def guarded_ber_decode(data, asn1_spec=None):
from pyasn1.codec.ber import decoder as ber_decoder
from signify.exceptions import ParseError
from signify import _print_type
try:
result, rest = ber_decoder.decode(data, asn1Spec=asn1_spec)
except Exception... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.