content
stringlengths
5
1.05M
#!/usr/bin/env python3 # encoding: utf-8 # # (C) 2012-2016 Chris Liechti <cliechti@gmx.net> # # SPDX-License-Identifier: BSD-3-Clause """\ Link To The Past - a backup tool """ class BackupException(Exception): """A class for backup related errors"""
# MIT License # Copyright (c) 2017 Sebastian Frei # 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,...
from ..adt import Multimethod, _ with Multimethod() as fib: fib[1] = 1 fib[2] = 1 fib[int] = lambda x: fib(x-1) + fib(x-2) def test_multimethod(): assert(fib(1) == 1) assert(fib(2) == 1) assert(fib(3) == 2) assert(fib(4) == 3)
from keyboard import is_pressed from detecto import core,visualize core.FastRCNNPredictor() import cv2 model = core.Model() visualize.detect_live(model,score_filter=0.6)
import numpy as np from input_module import Input from solve import Solve def main(): # Getting input from user input_class = Input() input_class.get_input() # Solving the system of linear equations got from the user solve = Solve(input_class.coefficient_matrix, input_class.rhs_vector) solve.solve() print("...
"""Functions for working with and analyzing inDrop barcodes.""" from collections import Counter, defaultdict import logging import time import sys import pandas as pd import numpy as np import pysam from plotly.offline import plot import plotly.graph_objs as go from genometools.expression import ExpMatrix, ExpGeneT...
import torch from torch import nn from torch.nn import functional as F import matplotlib.pyplot as plt import matplotlib.colors as colors import sys import os sys.path.append(os.path.abspath(os.path.join( os.path.dirname(os.path.realpath(__file__)), '..'))) import time from opts import parser global args, best_p...
import json, sys, os, re from os.path import isfile, isdir, join, splitext, dirname, basename from src.configuration import config, process_config, get_mini_config from src.globals import config_ext, json_ext, jtree_ext from src import gui from src.jtree import build_jtree resource_path = './resources' jtree_path = '....
# -*- encoding: utf-8 -*- """ @File : response.py @Time : 2020/3/17 9:25 AM @Author : zhengjiani @Email : 936089353@qq.com @Software: PyCharm """ from app.code import ResponseCode,ResponseMessage class ResMsg(object): """ 封装响应文本 """ def __init__(self, data=None, code=ResponseCode.SUCCESS, ...
# Tram, Minh # mqt0029 # 1001540029 # 2019-05-13 #---------#---------#---------#---------#---------#--------# import sys from .common import * #---------#---------#---------#---------#---------#--------# class Type() : def __init__( self, lineNum, kind, args ) : self.m_NodeType = 'Type' self.m_LineNu...
""" Run offline double dqn on cartpole. """ import numpy as np import gym from torch import nn as nn from rlkit.exploration_strategies.base import \ PolicyWrappedWithExplorationStrategy from rlkit.exploration_strategies.epsilon_greedy import EpsilonGreedy from rlkit.policies.argmax import ArgmaxDiscretePolicy from...
from django.db import models from django.utils import timezone class transaction(models.Model): # do stuff user_id = models.IntegerField() user = models.IntegerField() timestamp = models.DateField(default=timezone.now()) # test
import pytest from responses import RequestsMock from tests import loader @pytest.fixture def without_parameter_service(responses: RequestsMock): responses.add( responses.GET, url="http://test/", json={ "swagger": "2.0", "paths": { "/test": { ...
from multipledispatch import dispatch #passing two int parameters @dispatch(int,int) def product(first,second): result = first*second print(result); #passing three int parameters @dispatch(int,int,int) def product(first,second,third): result = first * second * third print(result); #you can also pass ...
#!/usr/bin/env python # # Copyright 2007 Google 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 o...
from django.shortcuts import redirect, render from django.views.generic import TemplateView from django.utils import timezone from django.utils.translation import ugettext #from ..models import #from stories.filters import CasesFilter from django.contrib import messages from django.contrib.auth import update_session_...
import eventlet from eventlet.green import urllib2 import logging import time import requests logging.basicConfig() logger = logging.getLogger('eventlet') logger.setLevel(logging.DEBUG) LOOP = 1000 URL = 'http://127.0.0.1:1234/1' elapsed_time = {} def fetch(url): body = urllib2.urlopen(url).read() return u...
import yaml from .file import MacroFile class MacroYAML(MacroFile): def __init__(self, lock, filename: str, dump=True): super().__init__(lock, filename, dump) with open(self.dumped or self._filename, 'r') as f: lines = f.readlines()[1:] self._data = yaml.load('\n'.join(li...
# 下面是下标和上标对应的键值关系 # 参考网站 https://unicode-table.com/cn/sets/superscript-and-subscript-letters/ # 有一些字母没有对应的关系 # 常用上标字符 _sup_string_normal = { "^0": "⁰", "^1": "¹", "^2": "²", "^3": "³", "^4": "⁴", "^5": "⁵", "^6": "⁶", "^7": "⁷", "^8": "⁸", "^9": "⁹", "^+": "⁺", "^-": "...
import logging import os from selenium import webdriver from selenium.webdriver.chrome import options from selenium.webdriver.remote.remote_connection import LOGGER from doc_curation import text_data LOGGER.setLevel(logging.WARNING) from urllib3.connectionpool import log as urllibLogger urllibLogger.setLevel(logging...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import abc import logging import itertools import torch import torch.nn as nn from torchsummary imp...
import logging import os import traceback from datetime import date import gevent from pywb.utils.loaders import load from pywb.warcserver.index.cdxobject import CDXObject from webrecorder.models.auto import Auto from webrecorder.models.base import RedisNamedMap, RedisOrderedList, RedisUniqueComponent, RedisUnordered...
#!/usr/bin/env python3 import matplotlib.pyplot as plt import os.path import shutil def plot_loss(runs_dir, losses, plot_file_name): _, axes = plt.subplots() plt.plot(range(0, len(losses)), losses) plt.title('Cross-entropy loss') plt.xlabel('Epoch') plt.ylabel('Loss') plt.grid() if os.path...
from datagateway_api.src.resources.entities.entity_map import create_entity_models from datagateway_api.src.search_api.models import ( Affiliation, Dataset, Document, File, Instrument, Member, Parameter, Person, Sample, Technique, ) def initialise_datagateway_api_spec(spec): ...
import json from src import * from src.helper import log from src.services import image_service from src.services.nmslib_service import Nmslib def find(index_path, features, images, batch_id): try: index = Nmslib() index.load(fn=index_path) next_identifier = 0 clusters = {} ...
# SPDX-FileCopyrightText: Brent Rubell for Adafruit Industries # SPDX-License-Identifier: MIT import time from microcontroller import cpu import board import busio from digitalio import DigitalInOut from adafruit_esp32spi import adafruit_esp32spi from adafruit_esp32spi import adafruit_esp32spi_wifimanager import adafr...
import pytest from mock import Mock from spacy.tokens import Doc, Span, Token from spacy.tokens.underscore import Underscore @pytest.fixture(scope="function", autouse=True) def clean_underscore(): # reset the Underscore object after the test, to avoid having state copied across tests yield Underscore.doc_...
import logging from uuid import uuid4 import pytest from iris.commons.storage import Storage from tests.helpers import upload_file async def test_create_bucket(storage, make_bucket): bucket = make_bucket() await storage.create_bucket(bucket) assert bucket in await storage.get_measurement_buckets() asy...
import applescript import os import time import subprocess, sys import random import json class Creditor(): def giveCredit(self, image, credit, speak=False, pauseSecs=0, voice=None): return @classmethod def creditorFactory(cls, settings=None, showCredits=None, pauseSecs=1): """Instantiate a class that will i...
#! python # integer arith a=4 print a b=12+5 print b c=b%a print c #! python # trailing comma i = 256*256 print 'The value of i is', i #! python # Fibonacci series: # the sum of two elements defines the next a, b = 0, 1 while b < 200: print b, a, b = b, a+b
from djongo import models class Account(models.Model): _id = models.ObjectIdField(default=0) account_id = models.IntegerField(unique=True) limit = models.IntegerField()
# -*- coding: utf-8 -*- from .png_builder import PNGBuilder def to_png(*args, **kwargs): """ Backward compatibility """ return PNGBuilder().generate(*args, **kwargs)
import random import numpy as np import torch def set_all_random_seed(seed: int): random.seed(seed) np.random.seed(seed) torch.random.manual_seed(seed)
import base64 import hmac import http from s3file import views class TestS3MockView: url = '/__s3_mock__/' policy = ( 'eyJDb25kaXRpb25zIjogW3siYnVja2V0IjogInRlc3QtYnVja2V0In0sIFsic3RhcnRz' 'LXdpdGgiLCAiJGtleSIsICJ0bXAvczNmaWxlLzNlUWhwOTZYU1dldFFwZ1VVQmZzWHci' 'XSwgeyJzdWNjZXNzX2FjdGl...
import streamlit as st from requests_toolbelt.multipart.encoder import MultipartEncoder import requests from PIL import Image import io import zipfile import glob import os import json st.title('MoroccoAI Data Challenge : Automatic Number Plate Recognition (ANPR) in Morocco Licensed Vehicles.') # fastapi endpoint url...
# generated from genmsg/cmake/pkg-genmsg.context.in messages_str = "/home/sasuke/catkin_ws/src/whycon/msg/Projection.msg" services_str = "" pkg_name = "whycon" dependencies_str = "geometry_msgs" langs = "gencpp;geneus;genlisp;gennodejs;genpy" dep_include_paths_str = "whycon;/home/sasuke/catkin_ws/src/whycon/msg;geomet...
"""" README ====== This file contains Python codes. ====== """ """ Documentation at http://docs.scipy.org/doc/scipy/reference/optimize.html """ import scipy.optimize as optimize y = lambda x: x**3 + 2.*x**2 - 5. dy = lambda x: 3.*x**2 + 4.*x # Call method: bisect(f, a, b[, args, xtol, rtol, maxiter, ...]) print "Bis...
"""Helpers to read execution arguments from the environment or command line. """ import os from argparse import ArgumentParser from typing import Any, Dict, Iterable, List, Optional, Tuple def __skip_doctest_on_win_gha(): import os, pytest if os.name == "nt" and os.environ.get("GITHUB_ACTION"): pyte...
# Generated by Django 2.2.15 on 2020-08-22 18:29 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('blog', '0007_auto_20200808_1601'), ] operations = [ migrations.DeleteModel( name='award', ), migrations.DeleteModel( ...
# -*- coding: utf-8 -* import pandas as pd #倒入路径 catering_sale = '../data/catering_sale.xls' #倒入Excel data = pd.read_excel(catering_sale, index_col = u'日期') #描述基本资料 data.describe()
# Licensed under a 3-clause BSD style license - see LICENSE.rst from astropy.utils.data import get_pkg_data_filename, get_pkg_data_fileobj import pytest from ...core import Regions parametrize_filenames = pytest.mark.parametrize( 'filename', ['../crtf/tests/data/CRTFgeneral.crtf', '../ds9/tests...
def kary_binary_string(n, k, list): if n < 1: print(list) return for i in range(k): list[n-1] = i kary_binary_string(n-1, k, list) if __name__ == "__main__": kary_binary_string(3, 3, [0]*3)
# This Python file uses the following encoding: utf-8 from generator import ResourceGenerator class AppleIdInfo: def __init__(self): self.name = "Jon" self.lastName = "Doe" self.mail = "jon.doe456@hotmail.com" self.password = "s3CreT*" self.city = "la habana" self.f...
import ply.lex as lex tokens = [ 'NAME','NUMBER','PLUS','MINUS','TIMES','DIVIDE', 'EQUALS' ] t_ignore = ' \t' t_PLUS = r'\+' t_MINUS = r'-' t_TIMES = r'\*' t_DIVIDE = r'/' t_EQUALS = r'=' t_NAME = r'[a-zA-Z_][a-zA-Z0-9_]*' lista = [] def t_NUMBER(t): r'\d+' t.value = int(t.value) return t...
"""Rx Workshop: Event Processing. Part 1 - Blocking Foreach. Usage: python wksp4.py """ from __future__ import print_function import rx class Program: """Main class. """ @staticmethod def main(): """Main method. """ src = rx.Observable.from_iterable(getInput(), ...
import logging from celery_tasks.main import celery_app from celery_tasks.sms.yuntongxun.sms import CCP logger = logging.getLogger('django') @celery_app.task(name='send_sms_code') # 给异步任务起别名 def send_sms_code(mobile, datas, temp_id): """ 发送短信验证码 :param mobile: 手机号 :param datas: [验证码, 过期时间] :par...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Floyd Hightower <https://github.com/fhightower> # This project is licensed under an MIT License. """Find Unicode domain squats of a given domain.""" import datetime import itertools import json import time import dns.resolver import tldextract from xn_twist_python_sd...
""" Copyright (c) 2018-2021 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...
# Distinguish regions by its reliability. import cifti from os.path import join as pjoin import numpy as np from ATT.iofunc import iofiles import matplotlib import matplotlib.pyplot as plt parpath = '/nfs/s2/userhome/huangtaicheng/hworkingshop/hcp_test/' reb_map, _ = cifti.read(pjoin(parpath, 'program', 'framework',...
from syncer import sync from pyppeteer import connect @sync async def test_browser_version(shared_browser): version = await shared_browser.version() assert version.startswith('Headless') @sync async def test_browser_ua(shared_browser): ua = await shared_browser.userAgent() assert 'WebKit' in ua or ...
from django.shortcuts import render from .forms import RegisterForm from django.contrib.auth import login, authenticate, logout from django.contrib.auth.decorators import login_required from django.http import HttpResponse def register(response): if response.user.is_authenticated: return render(response, "list_form...
RES_CODES = [ "xxx", "ma", "maa", "mab", "mac", "mae", "maf", "mag", "mai", "mak", "mal", "mao", "map", "maq", "mar", "mas", "mat", "mau", "max", "may", "maz", "myd", "myh", "mym", "myt", "sc", "scf", "sl", ...
import git g = git.cmd.Git(git_dir) g.pull()
''' Atlas worker threads. https://docs.python.org/3/library/threading.html#threading.Thread.run https://wiki.gnome.org/Projects/PyGObject/Threading ''' import requests import threading from manifest import Manifest class FileChecker(threading.Thread): ''' Check a file for validity. ''' def __init__(sel...
from .dynamic_section import DynamicSection from .dynsym_section import DynamicSymbolSection from .interp_section import InterpreterSection
import os from flask import request, current_app from werkzeug.utils import secure_filename from app.errors import bad_request from app.main import main def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1].lower() in current_app.config['ALLOWED_FILE_EXTENSIONS'] @main.route('/upload',...
from random import Random from sklearn.model_selection import ParameterGrid from typing import Tuple import uwndc19.hp_tuning.mutation_funcs def get_mutations(mutations_config: dict): mutations = [] for func_name, params_grids in mutations_config.items(): for params_grid in params_grids: f...
""" flags_tag_seq.py: build flags from emoji tag sequences source: https://emojipedia.org/emoji-tag-sequence/ """ from string import ascii_lowercase from unicodedata import name, lookup def get_tag(char): return lookup(f'TAG {name(char)}') def flag_sequence(subdivision_code): tag = ''.join(get_tag(c) for ...
from .scalr import ScalrUserAPI __all__ = [ "ScalrUserAPI" ]
from .shared import * from .album import * from .cache import ICache def surveyor(albums: Dict[str, AlbumSet], path: str) -> None: """ Maps the album collection' root directory recursively into an album set Arguments: albums {Dict[str, AlbumSet]} -- Album sets (returns) path {str} -- ...
#!/usr/bin/python3 import socketserver import sys import pymongo from server import Server from utils import complete, waiting def main(): try: port = int(sys.argv[1]) except IndexError: port = 5000 try: default_server = socketserver.ForkingTCPServer except AttributeError: ...
import time from collections import defaultdict from apps.core.management.scripts.portal_crawler import crawl_hour from apps.core.models import BestArticle from ara import celery_app, redis @celery_app.task def crawl_portal(): crawl_hour() def _get_redis_key(type_): return f'articles:{type_}' def _get_be...
def palindrome(word, index=0): if len(word) < 2 or word[0] == word[-1] and palindrome(word[1:-1]): return f'{word} is a palindrome' return f'{word} is not a palindrome' print(palindrome("abcba", 0))
# type: ignore import typing as t from datasette import hookimpl from pathlib import Path from datasette.utils.asgi import Response from functools import cache import markupsafe import click import html import json import uvicorn from doit import app, settings from doit.study.sqlalchemy.impl import SqlAlchemyRepo from...
# -*- coding: utf-8 -*- """ Created on Mon Feb 27 10:47:10 2017 @author: Gonxo This code imports the historical weather data from weather underground. You need to set up an account and the requests will consume one of the given raindrops, so collect as many as posible in one day. """ import requests import json im...
# This is dealing with introspection of unknown things. # mypy: allow-any-expr # mypy: allow-any-generics """ Inspect a module for compliance with the API requirements. """ from typing import Dict, Optional, Any from types import ModuleType from inspect import signature from ....base import ( EventBus, log, ...
import os, sys versions = ['kinetic-ros-core', 'kinetic-ros-base', 'kinetic-robot', 'kinetic-perception', 'kinetic-desktop', 'kinetic-desktop-full', 'melodic-ros-core', 'melodic-ros-base', 'melodic-robot', 'melodic-perception', 'melodic-desktop', 'melodic-desktop-full'] DOCK...
# Copyright (C) 2012 Nippon Telegraph and Telephone 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 appli...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse from alipay.aop.api.domain.BillRepayBudgetVO import BillRepayBudgetVO from alipay.aop.api.domain.RefuseVo import RefuseVo class MybankCreditLoantradeBillBudgetQueryResponse(AlipayResponse): ...
import numpy as np def main(): data = video_stream # Video Stream N x 3 x W x H def TimeIntervalSplit(video_stream,collect_limited = 10): # Video Stream N x 3 x W x H assert len(video_stream.shape) == 4, "Video Format warning" graph = [] mean_img, running_variance = 0.0, 0.0 start_index, en...
# coding=utf-8 from asdl.transition_system import TransitionSystem, GenTokenAction try: from cStringIO import StringIO except: from io import StringIO from collections import Iterable from asdl.asdl import * from asdl.asdl_ast import RealizedField, AbstractSyntaxTree from common.registerable import Registrab...
"""Unit testing of timer library.""" from unittest import TestCase from pyinels.pyTimer import pyTimer class PyTimerTest(TestCase): """Class to test timer library.""" def setUp(self): """Setup pyTimer for testing.""" self.timer = pyTimer() def tearDown(self): """De...
""" Libraries for controlling lab equipment """
from distutils.dir_util import copy_tree from importlib import import_module import os from shutil import move, rmtree from tempfile import mkdtemp from django.core.management import CommandError from django.core.management.commands.startproject import Command as BaseCommand from django.utils.crypto import get_random_...
""" The Steenrod algebra """ from .steenrod_algebra import SteenrodAlgebra, Sq from .steenrod_algebra_bases import steenrod_algebra_basis
from fedn.common.storage.models.modelstorage import ModelStorage from collections import defaultdict import io CHUNK_SIZE = 1024 * 1024 class MemoryModelStorage(ModelStorage): def __init__(self): import tempfile # self.dir = tempfile.TemporaryDirectory() self.models = defaultdict(io.Byte...
# -*- coding: utf-8 -*- # Copyright (c) 2015 Ericsson AB # # 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 ...
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @File : filters.py @Time : 2021/04/27 22:59:02 @Author : LisonLIN @Contact : linliangsuan@qq.com @Desc : 过滤器 ''' # here put the import lib from api.models import * from django_filters.rest_framework import FilterSet from django.contrib.auth.models...
# v3.classification # 3/12/2018 import argparse import os import glob import numpy as np import cv2 import torch import sklearn.feature_extraction.image from torchvision.models import DenseNet #-----helper function to split data into batches def divide_batch(l, n): for i in range(0, l.shape[0], n): yi...
# Generated by Django 3.0.3 on 2020-02-26 02:02 import django.contrib.postgres.fields.jsonb from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('posthog', '0024_add_event_distinct_id_index'), ] operations = [ ...
# -*- coding: utf-8 -*- #GSASIIctrlGUI - Custom GSAS-II GUI controls ########### SVN repository information ################### # $Date: 2020-12-23 07:09:47 +0900 (水, 23 12月 2020) $ # $Author: toby $ # $Revision: 4680 $ # $URL: https://subversion.xray.aps.anl.gov/pyGSAS/trunk/GSASIIctrlGUI.py $ # $Id: GSASIIctrlGUI.py ...
# Developed by Sunghyun Cho on March 9th, 2019. from HangulDecomposeModule import HangulDecomposer as hb def pronounceInKorean(word): # modify accordingly for your use return word def ENYGDecider(string, highlight): wordList = string.split() newString = "" for word in wordList: word = pronounceInKorean(word) ...
# Generated by Django 2.2.8 on 2022-04-05 02:36 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('candidate', '0003_auto_20220330_0201'), ] operations = [ migrations.AlterField( model_name='requirementmandatory', n...
from django.test import TestCase from api.models.book import Book # Create your tests here. class ModelTestCase(TestCase): fixtures = ['books.json'] @classmethod def setUpTestData(cls): cls.bookid = "1234" cls.title = "TestBuch" cls.description = "Ein Buch über das Testen" ...
from typing import List, Optional from argparse import ArgumentParser, Namespace, _SubParsersAction import logging import sys import yaml from pymdmix_core.plugin.base import Plugin, PluginAction, PluginManager, MDMIX_PLUGIN_MANAGER from pymdmix_core.settings import SETTINGS from pymdmix_core.parser import MDMIX_PARSER...
import stripe from stripe.test.helper import ( StripeResourceTest, NOW, DUMMY_CHARGE ) class ChargeTest(StripeResourceTest): def test_charge_list(self): stripe.Charge.list(created={'lt': NOW}) self.requestor_mock.request.assert_called_with( 'get', '/v1/charges', ...
from textwrap import dedent import json from gluon import current from constants import NULLDT, PUBLISH_FREEZE, PUBLISH_FREEZE_MSG from dbconfig import EMDROS_VERSIONS from query import queryStatus from helpers import countSlots from mql import mql class QUERYSAVE: def __init__(self, Query, QueryChapter): ...
from .alphabot import Alphabot
# Tencent is pleased to support the open source community by making GNES available. # # Copyright (C) 2019 THL A29 Limited, a Tencent company. 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...
# # Copyright 2018-2021 Elyra 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 law or agreed to in writ...
import RPi.GPIO as GPIO import subprocess import time GPIO.setmode(GPIO.BCM) # Set for broadcom numbering not board numbers... # Pin 17 - pause # Pin 22 - FF 10 # Pin 23 - RW 10 # Pin 19 - FF 30 # Pin 26 - RW 30 # Pin 27 - quit GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(22, GPIO.IN, pull_up_down=...
import pytest import numpy as np import pymaster as nmt from .utils import normdiff class BinTester(object): def __init__(self): self.nside = 1024 self.lmax = 2000 self.nlb = 4 self.bc = nmt.NmtBin(self.nside, nlb=4, lmax=self.lmax) ells = np.arange(self.lmax - 4, dtype=int...
""" Publishes AWS VM burn rate """ from decisionengine.framework.modules import Publisher from decisionengine_modules.AWS.publishers.AWS_generic_publisher import AWSGenericPublisher as publisher @publisher.consumes_dataframe('AWS_Burn_Rate') class AWSBurnRatePublisher(publisher): def graphite_context(self, data...
# -*- coding: utf-8 -*- """ Implement pow(x, n), which calculates x raised to the power n (x^n). Example 1: Input: 2.00000, 10 Output: 1024.00000 Example 2: Input: 2.10000, 3 Output: 9.26100 Example 3: Input: 2.00000, -2 Output: 0.25000 """ def my_power(x,n): res = 1. for i in range(abs...
import numpy as np import sympy from typing import Union, Callable, Collection, List, Iterable from beluga.numeric.compilation import LocalCompiler, jit_compile_func from beluga.symbolic.special_functions import custom_functions, tables # default_tol = 1e-4 sym_zero = sympy.Integer(0) sym_one = sympy.Integer(1) cl...
from ctypes import POINTER, Structure, c_char_p, c_float, c_int, string_at from django.contrib.gis.geoip.libgeoip import free, lgeoip # #### GeoIP C Structure definitions #### class GeoIPRecord(Structure): _fields_ = [('country_code', c_char_p), ('country_code3', c_char_p), ('coun...
#!/usr/bin/env python import radical.utils as ru import radical.saga as rs check = False # ------------------------------------------------------------------------------ # def config(): ru.set_test_config(ns='radical.saga') ru.add_test_config(ns='radical.saga', cfg_name='advert_redis_local') return ...
from rest_framework import serializers from genes.models import GeneInfo, GeneListCategory, GeneList, Gene, Transcript, GeneListGeneSymbol, \ GeneAnnotationRelease, SampleGeneList, ActiveSampleGeneList, GeneSymbol, TranscriptVersion, GeneVersion from snpdb.models import Company from snpdb.serializers import UserSe...
x = 2 # First print print(x) def multiply_x_by_2(): global x x = x * 2 # third print print(x) # second print print(x) multiply_x_by_2() # DIVIDER ################################# def outer_function(): y = 1 def inner_function(): nonlocal y y += 3 print('inner_f...
from django.contrib import admin from Location.models import City # Register your models here. admin.site.register(City) # admin.site.register(Area)