content
stringlengths
0
894k
type
stringclasses
2 values
# -*- coding: utf-8 -*- ''' Send events based on a script's stdout .. versionadded:: Neon Example Config .. code-block:: yaml engines: - script: cmd: /some/script.py -a 1 -b 2 output: json interval: 5 Script engine configs: cmd: Script or command to execute output: ...
python
#!/usr/bin/env python import logging from google.protobuf.descriptor import Descriptor, FieldDescriptor from dremel.consts import * from dremel.node import Node, CompositeNode from dremel.field_graph import FieldNode, FieldGraph from dremel.schema_pb2 import Schema, SchemaFieldDescriptor, SchemaFieldGraph class Dis...
python
from ptcaccount2.accounts import random_account
python
# Copyright (c) 2019 Graphcore Ltd. All rights reserved. import numpy as np import popart import torch import pytest from op_tester import op_tester # `import test_util` requires adding to sys.path import sys from pathlib import Path sys.path.append(Path(__file__).resolve().parent.parent) import test_util as tu def ...
python
from urllib.parse import urljoin from uuid import UUID import pytest import reversion from django.conf import settings from django.utils.timezone import now from freezegun import freeze_time from requests.exceptions import ( ConnectionError, ConnectTimeout, ReadTimeout, Timeout, ) from rest_framework i...
python
# Importing standard libraries import sys import copy ''' Basic Cryptanalysis : The logic is pretty simple. Step 1: Construct a set of candidate solutions to each words decoded message based on length. (Length of encoded and decoded mssage is the same) Step 2: Try out each path recu...
python
from __future__ import absolute_import from celery import task from celery import Celery from celery import app import pymongo import json from bson import json_util,ObjectId from pymongo import MongoClient # from pymongo import find_many from bson.dbref import DBRef from pymongo.mongo_replica_set_client import MongoRe...
python
#!/usr/bin/env python # Copyright 2020 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # http://www.apache.org/licenses/LICENSE-2.0 # o...
python
# # Copyright (c) 2012-2021 Snowflake Computing Inc. All right reserved. # from __future__ import division import base64 import xml.etree.cElementTree as ET from datetime import datetime from io import IOBase from logging import getLogger from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Tuple,...
python
from mailbox import MMDF from django_mail_admin.transports.generic import GenericFileMailbox class MMDFTransport(GenericFileMailbox): _variant = MMDF
python
#!/usr/bin/env python import rospkg import rospy import yaml from duckietown_msgs.msg import AprilTagDetectionArray, Twist2DStamped import numpy as np import tf.transformations as tr from geometry_msgs.msg import PoseStamped, Point class AprilFollow(object): def __init__(self): self.node_name = "follo...
python
import argparse import os import logging import numpy as np from tqdm import tqdm from collections import OrderedDict import re import torch import torch.nn.functional as F from core.configs import cfg from core.datasets import build_dataset from core.models import build_feature_extractor, build_classifi...
python
from __future__ import annotations import asyncio import json import logging import sys from datetime import datetime, timedelta from typing import Tuple, Union, List from urllib.parse import quote import aiohttp from aiohttp import ClientSession, ClientResponseError from bs4 import BeautifulSoup from furl import fur...
python
#!/usr/bin/env python # coding: utf-8 # # Workshop Notebook # ## Notebook Introduction # ### How to Use this Notebook # ### References # I know it tradition to have the refences at the end of books, but when you are standing on the shoulders of giants. You thank them first. # ```{bibliography} # ``` # ### Than...
python
import requests, subprocess, time import OpenSSL, M2Crypto, ssl, socket import iptools import random from termcolor import colored, cprint # from multiprocessing import Process, Queue, Lock, Pool ---> is not stable with tqdm lib from tqdm import tqdm from pathos.multiprocessing import ProcessingPool as Pool # Used for ...
python
# -*- coding: utf-8 -*- import flow if __name__ == '__main__': flow.initialize() flow.app.run()
python
#!/usr/bin/pyth2.7 import libiopc_rest as rst def func_add_img(hostname, options): payload = '{' payload += '"ops":"add_qemu_img",' payload += '"format":"qcow2",' payload += '"disk_path":"/hdd/data/99_Misc/VMs/sys005.qcow2",' payload += '"size":30,' #payload += '"disk_path":"/hdd/data/00_Daily...
python
from typing import Any, Dict, Optional import numpy as np from GPyOpt.optimization.acquisition_optimizer import ContextManager as GPyOptContextManager from .. import ParameterSpace Context = Dict[str, Any] class ContextManager: """ Handles the context variables in the optimizer """ def __init__(se...
python
import datetime anon = int(input('Em que ano você nasceu?')) anoa = datetime.date.today().year idade = anoa - anon if idade < 16: print('Você ainda não precisa se alistar no exército, sua idade é de {} anos'.format(idade)) elif idade == 16 or idade == 17: print('Você já pode se alistar no exército, sua idade é ...
python
# https://adventofcode.com/2017/day/3 __author__ = 'Remus Knowles <remknowles@gmail.com>' def which_layer(integer): """ Work out which layer an integer is in. """ c = 1 while ((2*c - 1)*(2*c - 1)) <= integer: c += 1 return c def layer_rows(layer): """ Given a layer return each row as a list. """ els =...
python
""" Turing Machine simulator driver """ from __future__ import print_function import json from turing_machine.Machine import Machine def _main(machine_filename, tape): """ Runs the turing machine simulator """ with open(machine_filename) as json_file: json_data = json.load(json_file) tmach...
python
#!/usr/bin/env python PKG = "pr2_mechanism_controllers" import roslib; roslib.load_manifest(PKG) import sys import os import string import rospy from std_msgs import * from pr2_msgs.msg import PeriodicCmd from time import sleep def print_usage(exit_code = 0): print '''Usage: send_periodic_cmd.py [control...
python
from unittest import TestCase from pyrrd.node import RRDXMLNode from pyrrd.testing import dump from pyrrd.util import XML class RRDXMLNodeTestCase(TestCase): def setUp(self): self.tree = XML(dump.simpleDump01) def test_creation(self): rrd = RRDXMLNode(self.tree) self.assertEqual(rrd...
python
from __future__ import absolute_import import logging from sentry.tasks.base import instrumented_task from sentry.utils.locking import UnableToAcquireLock logger = logging.getLogger(__name__) @instrumented_task( name='sentry.tasks.process_buffer.process_pending', queue='buffers.process_pending', ) def proc...
python
# Webcam.py # author: Matthew P. Burruss # last update: 8/14/2018 # Description: interface for webcam for the various modes import numpy as np import cv2 from datetime import datetime import csv import socket import sys import time liveStreamServerAddress = ('10.66.229.241',5003) # release() # Summary: Cleans up cam...
python
from pathlib import Path from fastapi import FastAPI, APIRouter, Request, Depends from api.api_v1.api import api_router from core.config import settings BASE_PATH = Path(__file__).resolve().parent root_router = APIRouter() app = FastAPI(title="OCR API", openapi_url="/openapi.json") @root_router.get("/", status_co...
python
""" Immutable config schema objects. """ from __future__ import absolute_import from __future__ import unicode_literals from collections import namedtuple from enum import Enum MASTER_NAMESPACE = "MASTER" CLEANUP_ACTION_NAME = 'cleanup' def config_object_factory(name, required=None, optional=None): """ Cr...
python
# CTK: Cherokee Toolkit # # Authors: # Alvaro Lopez Ortega <alvaro@alobbs.com> # # Copyright (C) 2010-2011 Alvaro Lopez Ortega # # This program is free software; you can redistribute it and/or # modify it under the terms of version 2 of the GNU General Public # License as published by the Free Software Foundation....
python
from functools import wraps from logzero import logger from driver_singleton import DriverSingleton def requires_url(required_url): def inner_function(func): @wraps(func) def wrapper(*args, **kwargs): try: if DriverSingleton.get_driver().current_url != required_url: ...
python
from django.utils import six from debug_toolbar_multilang.pseudo import STR_FORMAT_PATTERN, \ STR_FORMAT_NAMED_PATTERN from debug_toolbar_multilang.pseudo.pseudo_language import PseudoLanguage class ExpanderPseudoLanguage(PseudoLanguage): """ Pseudo Language for expanding the strings. This is useful f...
python
# Jak znaleźć najkrótsze ścieżki z wierzchołka s do wszystkich innych w acyklicznym grafie skierowanym? from math import inf def dfs(graph, source, visited, result): visited[source] = True for v in graph[source]: if not visited[v[0]]: dfs(graph, v[0], visited, result) result.insert(0, ...
python
import unittest from unittest.mock import patch from tmc import points, reflect from tmc.utils import load, load_module, reload_module, get_stdout, check_source, sanitize from functools import reduce import os import os.path import textwrap from random import choice, randint from datetime import date, datetime, timede...
python
from typing import Dict import base64 import json import logging import os from shlex import quote as shq from gear.cloud_config import get_global_config from ....batch_configuration import DOCKER_ROOT_IMAGE, DOCKER_PREFIX, DEFAULT_NAMESPACE, INTERNAL_GATEWAY_IP from ....file_store import FileStore from ....instance_...
python
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class NoaAccount(ProviderAccount): """Noa Account""" pass class NoaProvider(OAuth2Provider): """Provider for Noa""" id = 'noa' name = 'Noa' account_cl...
python
import nltk grammar = nltk.data.load('file:agree_adjunct.fcfg',cache=False) parser = nltk.parse.FeatureChartParser(grammar) agreement_test_sentences = ['Often John left','John left often', 'John often left', 'Because John left Mary cried', ...
python
# -*- coding: utf-8 -*- # @Time : 2019-12-20 # @Author : mizxc # @Email : xiangxianjiao@163.com from flask_mongoengine import MongoEngine from flask_login import LoginManager db = MongoEngine() loginManager = LoginManager()
python
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def postorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ res = [] stack = [] while ro...
python
""" A DataNodeServer which serves APEX weather from disk. Based on the original example, which served modified APEX weather files. """ import glob import os import six import time import numpy as np from os import environ from autobahn.wamp.types import ComponentConfig from autobahn.twisted.wamp import ApplicationSe...
python
def add(x,y): return x + y #print add(3,4) print reduce(add, [1,3,5,7,9,11]) def fn(x,y): return x*10 + y print reduce(fn, [1,3,5,7,9])
python
''' Created by auto_sdk on 2014.11.15 ''' from aliyun.api.base import RestApi class Slb20130221CreateLoadBalancerHTTPListenerRequest(RestApi): def __init__(self,domain='slb.aliyuncs.com',port=80): RestApi.__init__(self,domain, port) self.backendServerPort = None self.cookie = None self.cookieTimeout =...
python
# -*- coding: utf-8 -*- """ Created on Thu Aug 10 15:43:09 2017 @author: juherask """ import os DEBUG_VERBOSITY = 3 COST_EPSILON = 1e-10 CAPACITY_EPSILON = 1e-10 # how many seconds we give to a MIP solver MAX_MIP_SOLVER_RUNTIME = 60*10 # 10m MIP_SOLVER_THREADS = 1 # 0 is automatic (parallel computing) # venv doe...
python
""" This program handle incomming OSC messages to MIDI """ import argparse import random import time import json import sqlite3 import mido from pythonosc import dispatcher from pythonosc import osc_server from pythonosc import osc_message_builder from pythonosc import udp_client from lib.midiHelper import * from ...
python
from builtins import range from .partition import LabelSpacePartitioningClassifier import copy import random import numpy as np from scipy import sparse class RakelD(LabelSpacePartitioningClassifier): """Distinct RAndom k-labELsets multi-label classifier.""" def __init__(self, classifier=None, labelset_size=...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import nose from nose.tools.trivial import eq_ from jpgrep.morpheme import tokenize from jpgrep.morpheme import StreamDetector class Test_tokenize(object): def test(self): """ 文章が適切に形態素に分解される """ text = u'吾輩は猫である' expect = [u'吾輩', u'は', u'猫'...
python
def or_op(ctx, a, b): if isinstance(b, list): if a == True: return True if a == False: return [] if isinstance(a, list): return [] if isinstance(a, list): if b == True: return True return [] return a or b def and_op(c...
python
import discord from discord.ext.commands import Bot from discord.ext import commands import asyncio import json import os import chalk import youtube_dl import random import io import aiohttp import time import datetime from datetime import datetime as dt import logging import re from itertools import c...
python
import datetime import os from django import forms from django.conf import settings from decharges.decharge.models import UtilisationTempsDecharge from decharges.decharge.views.utils import calcul_repartition_temps from decharges.user_manager.models import Syndicat class UtilisationTempsDechargeForm(forms.ModelForm...
python
''' Parser for creating mathematical equations. ''' import re from regex_parser import BaseParser import src.svg as svg from StringIO import StringIO matplotlib_included = True try: import matplotlib matplotlib.use('SVG') from matplotlib import pyplot except: matplotlib_included = False def registe...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import re import sys import time import json import random import logging import collections import configparser import requests logging.basicConfig(stream=sys.stderr, format='%(asctime)s [%(name)s:%(levelname)s] %(message)s', level=logging.DEBUG if sys.argv[-1] == '-v'...
python
#! /usr/bin/env python # -*- mode: python; coding: utf-8 -*- # Copyright 2017 the HERA Collaboration # Licensed under the 2-clause BSD license. import numpy as np from astropy.time import Time from pyuvdata import UVData from hera_mc import mc a = mc.get_mc_argument_parser() a.description = """Read the obsid from a...
python
#!/usr/bin/env python ''' Lucas-Kanade tracker ==================== Lucas-Kanade sparse optical flow demo. Uses goodFeaturesToTrack for track initialization and back-tracking for match verification between frames using webcam Usage ----- flow_rotation.py Keys ---- r - reset accumulated rotation ESC - exit ''' impo...
python
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
python
from hcipy import * import numpy as np def check_energy_conservation(shift_input, scale, shift_output, q, fov, dims): grid = make_uniform_grid(dims, 1).shifted(shift_input).scaled(scale) f_in = Field(np.random.randn(grid.size), grid) #f_in = Field(np.exp(-30 * grid.as_('polar').r**2), grid) fft = FastFourierTrans...
python
# coding=utf-8 # Copyright 2018 StrTrek Team 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 ...
python
#------------------------------------------------------------------------------- # Name: Spatial Parser Helper functions # Purpose: A suite of functions which are used by the SpatialParser # class. # # Author: Ashwath Sampath # Based on: http://mentalmodels.princeton.edu/programs/space-6.li...
python
#################################################################################################### ## A simple feed forward network using tensorflow and some of its visualization tools ##Architecture ## 2 hidden layers 1 input and 1 output layers ## input layer : 10 neurons corresponding to season, mnth,holiday,weekd...
python
import os class Plugin: def __init__(self, *args, **kwargs): self.plugin_name = os.path.basename(__file__) super() def execute(self, args): print('request',self.plugin_name,args) return { 'contents': f'Hello, {self.plugin_name} ' }
python
def foo(*a): if a pass<caret>
python
def multiplication(x): return x * x def square(fn, arg): return fn(arg) print(square(multiplication,5))
python
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack.package import * class RRcppziggurat(RPackage): """'Rcpp' Integration of Different "Ziggurat" Normal RNG ...
python
# Copyright (c) 2015, MapR Technologies # # 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
#add parent dir to find package. Only needed for source code build, pip install doesn't need it. import os, inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(os.path.dirname(currentdir)) os.sys.path.insert(0, parentdir) from bullet.tm700_rgbd_Gym...
python
from __future__ import absolute_import, print_function import sys import json try: import rapidjson fast_json_available = True except ImportError: fast_json_available = False from xml.dom.minidom import parseString as parse_xml_string try: from lxml import etree fast_xml_available = True except Im...
python
from twisted.trial.unittest import TestCase import jasmin.vendor.txredisapi as redis from twisted.internet import reactor, defer from jasmin.redis.configs import RedisForJasminConfig from jasmin.redis.client import ConnectionWithConfiguration @defer.inlineCallbacks def waitFor(seconds): # Wait seconds waitDef...
python
from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from .models import Book # Create your views here. def all_book(request): all_shit = Book.objects.all() return render(request, 'bookstore/all_book.html', locals()) def add_book(request): if request.method == '...
python
import inpcon_posint as icpi while True: #bug: the zero fibonaccinumber is 0 inptext='Which Fibonacci number do you want to see?: ' inp=icpi.inputcontrol(inptext) if inp==0: print(0) print() print() continue erg=[0,1] for i in range(0,(inp-1),1): ...
python
import scipy.signal as ss import matplotlib.pyplot as plt import numpy as np from .PluginManager import PluginManager class HilbertPlugin(PluginManager): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.hilbert = {} def hilbert_transform(self, phase_freq=0): self.hilbert['data'] =...
python
# Description: Sample Code to Run mypy # Variables without types i:int = 200 f:float = 2.34 str = "Hello" # A function without type annotations def greet(name:str)-> str: return str + " " + name if __name__ == '__main__': greet("Dilbert")
python
# This is library template. Do NOT import this, it won't do anything. # Libraries are loaded with __import__, and thus, the script is ran on load. Be careful what you write here.
python
version = "2.4.5" default_app_config = "jazzmin.apps.JazzminConfig"
python
#!/usr/bin/env python3 # https://codeforces.com/problemset/problem/1093/A t = int(input()) for _ in range(t): n = int(input()) print(n//2)
python
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os.path import tensorflow as tf from shutil import rmtree from librosa.feature import mfcc import numpy as np from tensorflow.io import gfile import uuid from constants import * def read_dir(): if...
python
import os.path import yaml from pathlib import Path CONFIG_DIRECTORY = str(Path.home()) + "/.tino" CONFIG_FILENAME = CONFIG_DIRECTORY + "/conf.yml" class TinoConfig: def __init__(self): if not os.path.exists(CONFIG_DIRECTORY): os.makedirs(CONFIG_DIRECTORY) if os.path.exists(CONFIG...
python
""" Parameter-Based Methods Module """ from ._regular import RegularTransferLR, RegularTransferLC, RegularTransferNN from ._finetuning import FineTuning from ._transfer_tree import TransferTreeClassifier from ._transfer_tree import TransferForestClassifier __all__ = ["RegularTransferLR", "RegularTransferLC...
python
""" abuse.ch Palevo C&C feed RSS bot. Maintainer: Lari Huttunen <mit-code@huttu.net> """ import urlparse from abusehelper.core import bot from . import host_or_ip, split_description, AbuseCHFeedBot class PalevoCcBot(AbuseCHFeedBot): feed_malware = "palevo" feed_type = "c&c" feeds = bot.ListParam(defau...
python
import unittest import logging # se desabilita el sistema de logs del API logging.disable(logging.CRITICAL) from fastapi.testclient import TestClient from app.main import app client = TestClient(app) root_response = '''<html> <head> <title>Guane Inter FastAPI</title> </head> <body> <h1...
python
"""Represents a realm in World of Warcraft.""" from __future__ import annotations __LICENSE__ = """ Copyright 2019 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apach...
python
# Copyright (c) 2018 - 2020 Institute for High Voltage Technology and Institute for High Voltage Equipment and Grids, Digitalization and Power Economics # RWTH Aachen University # Contact: Thomas Offergeld (t.offergeld@iaew.rwth-aachen.de) # # # This module is part of CIMPyORM. # # # CIMPyORM is licensed un...
python
import json import sewer class ExmpleDnsProvider(sewer.dns_providers.common.BaseDns): def __init__(self): self.dns_provider_name = 'example_dns_provider' def create_dns_record(self, domain_name, base64_of_acme_keyauthorization): pass def delete_dns_record(self, domain_name, base64_of_a...
python
r""" Backrefs for the 'regex' module. Add the ability to use the following backrefs with re: * \Q and \Q...\E - Escape/quote chars (search) * \c and \C...\E - Uppercase char or chars (replace) * \l and \L...\E - Lowercase char or chars (replace) Compiling ========= pattern = compile_search(r'somepattern'...
python
# Classes for rsinc module import subprocess import os from time import sleep THESAME, UPDATED, DELETED, CREATED = tuple(range(4)) NOMOVE, MOVED, CLONE, NOTHERE = tuple(range(4, 8)) class File: def __init__(self, name, uid, time, state, moved, is_clone, synced, ignore): self.name = name self.ui...
python
import json import csv import argparse import http.client import base64 fieldnames = ("TenantID","First Name","Last Name","Extension","Voice DID","Fax DID","Caller ID","ID for MS Exchange","Home Phone","Cell Phone","Fax Number", "E-mail","Alternate E-mail","User Name","Password","PIN","Pseudonym","User...
python
import os from itertools import product import re from numpy import append, array, bincount, diff, ma, sort #cumsum, nditer, roll, setdiff1d, where from numpy import product as np_prod seating_re = re.compile('[L\.]') workPath = os.path.expanduser("~/Documents/Code/Advent_of_code/2020") os.chdir(workPath) #with open...
python
import re import unittest from rexlex import Lexer from rexlex.lexer.itemclass import get_itemclass class TestableLexer(Lexer): """Test tuple state transitions including #pop.""" LOGLEVEL = None re_skip = re.compile('\s+') tokendefs = { 'root': [ ('Root', 'a', 'bar'), ...
python
from unityagents import UnityEnvironment from utils import dqn, get_env_spec from dqn_agents import Agent import os import argparse EXPS_ROOT_PATH = './data' parser=argparse.ArgumentParser(description="train a RL agent in Unity Banana Navigation Environment") parser.add_argument('-n', '--name', type=str, metavar='', ...
python
from django.urls import path from django.contrib.auth import views as auth_views from . import views app_name='todoapp' urlpatterns = [ path('',views.home, name='home'), path('index',views.lhome, name='lhome'), # Delete Paths path('<int:todo_id>/delete', views.delete, name='delete'), path('<in...
python
#!/usr/bin/env python3 # Transpose chroma matrix by nTransp semitones up (right rotation) where nTransp is 1st argument. # If two additional arguments are present, those are input and output file paths, respectively. # Otherwise, read/write on STDIN import sys, csv if __name__ == '__main__': ntransp = (int(sys.argv[...
python
from collections import defaultdict import networkx as nx import numpy as np import hashlib from .solver_utils import root_finder, get_edge_length def find_split( nodes, priors=None, considered=set(), fuzzy=False, probabilistic=False, minimum_allele_rep=1.0, ): # Tracks frequency of stat...
python
import matplotlib.pyplot as plt import matplotlib.patches as mpatch def DrawPlotOnPage(N, CanvasSize_W, CanvasSize_H, Lval, Tval, Wval, Hval, solNo): #print("plotter called") fig, ax = plt.subplots() rectangles = [] for x in range(N): myRect = mpatch.Rectangle((Lval[x], Tval[x]), Wval[x], Hv...
python
#!/usr/bin/env python3 # # This utility will generate the swift code from the c Fit SDK # You can download the Fit SDK from https://developer.garmin.com/fit and update your local copy using the diffsdk.py script # # in the python directory run ./fitsdkparser.py generate Profile.xlsx # # import re import argp...
python
from __future__ import absolute_import, unicode_literals import base64 import cgi import contextlib import datetime import decimal import json import time from mock import Mock, patch import pytest import six from six.moves import range, urllib import mixpanel class LogConsumer(object): def __init__(self): ...
python
_architecture_template = r'''#!/usr/bin/env bash EXPERIMENT_NAME="$(basename $(realpath $(pwd)/..))" SETUP_ID="$(basename $(pwd))" NAME="${EXPERIMENT_NAME}.${SETUP_ID}-mknet" USER_ID=${UID} docker rm -f $NAME #rm snapshots/* echo "Starting as user ${USER_ID}" CONTAINER='%(container)s' nvidia-docker run --rm \ -u...
python
import pathlib from pw_manager.utils import constants, utils from colorama import Fore, Style def require_valid_db(enter_confirmation=False): def decorator(func): def inner(*args, **kwargs): if constants.db_file is None: print(f"{Fore.RED}You need to select a database first!{...
python
import os import numpy as np import logging from app_globals import * from alad_support import * from r_support import matrix, cbind from forest_aad_detector import * from forest_aad_support import prepare_forest_aad_debug_args from results_support import write_sequential_results_to_csv from data_stream import * ""...
python
import requests class AppClient: def __init__(self, endpoint: str = 'http://localhost:5000'): self._endpoint = endpoint def get_index(self): return requests.get(self._endpoint).text
python
import rng import socket import pytest @pytest.fixture def index_test(): return rng.index() def test_index_content(index_test): hostname = socket.gethostname() assert "RNG running on {}\n".format(hostname) in index_test def test_rng_status(): statuscode = rng.rng(32).status_code assert statusc...
python
from PyCA.Core import * import PyCA.Common as common import PyCA.Display as display import numpy as np import matplotlib.pyplot as plt def PrimalDualTV(I0, \ DataFidC, \ TVC = 1.0, \ nIters = 5000, \ stepP = None, \ stepI = None, \ ...
python
# Jan28Report on General Accureacy ##################################################################################### # date = 'Jan-23-2020-22-N-noneSpark-R0-noOpt' # notes = 'noneSpark-R0-noOpt' # date = 'Jan-23-2020-21-N-UseSpark-R0-noOpt' # notes = 'UseSpark-R0-noOpt' # date = 'Jan-24-2020-2-N-UseSpark-R1-noOpt' ...
python
# noinspection PyShadowingBuiltins,PyUnusedLocal def sum(x, y): if not 0 <= x <= 100: raise ValueError('arg x must be between 0 and 100') if not 0 <= x <= 100: raise ValueError('arg y must be between 0 and 100') return x + y
python
""" Fabric tools for managing users """ from __future__ import with_statement from fabric.api import * def exists(name): """ Check if user exists """ with settings(hide('running', 'stdout', 'warnings'), warn_only=True): return sudo('getent passwd %(name)s' % locals()).succeeded def create(n...
python