content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
import re
class CCY:
BYN = "BYN"
RUB = "RUB"
USD = "USD"
EUR = "EUR"
@classmethod
def from_string(cls, s):
if s is None:
return cls.BYN
ccys = [
(r'r[u,r][r,b]?', cls.RUB),
(r'b[y,r]?n?', cls.BYN),
(r'usd?', cls.USD),
... | nilq/baby-python | python |
"""
================
Compute p-values
================
For the visualization, we used a comodulogram.
"""
from tensorpac import Pac
from tensorpac.signals import pac_signals_wavelet
import matplotlib.pyplot as plt
plt.style.use('seaborn-poster')
# First, we generate a dataset of signals artificially coupled between ... | nilq/baby-python | python |
import multiprocessing
def validate_chunks(n):
if n == 0:
raise AssertionError('The number of chunks cannot be 0 ')
elif n <= -2:
raise AssertionError('The number of chunks should be -1 or > 0')
def get_num_partitions(given_partitions, n):
if given_partitions == -1:
return multipro... | nilq/baby-python | python |
from typing import Union, List, Optional
from pyspark.sql.types import (
StructType,
StructField,
StringType,
ArrayType,
DataType,
TimestampType,
)
# This file is auto-generated by generate_schema so do not edit it manually
# noinspection PyPep8Naming
class MedicationAdministrationSchema:
... | nilq/baby-python | python |
from distutils.core import setup
from setuptools import find_packages
setup(
name='pyesapi',
version='0.2.1',
description='Python interface to Eclipse Scripting API',
author='Michael Folkerts, Varian Medical Systems',
author_email='Michael.Folkerts@varian.com',
license='MIT',
packages=find_... | nilq/baby-python | python |
from common import *
import collections
try:
import cupy
except:
cupy = None
# From http://pythonhosted.org/pythran/MANUAL.html
def arc_distance(theta_1, phi_1, theta_2, phi_2):
"""
Calculates the pairwise arc distance
between all points in vector a and b.
"""
temp = (np.sin((theta_2-thet... | nilq/baby-python | python |
from unittest import mock
import pytest
from nesta.packages.geographies.uk_geography_lookup import get_gss_codes
from nesta.packages.geographies.uk_geography_lookup import get_children
from nesta.packages.geographies.uk_geography_lookup import _get_children
SPARQL_QUERY = '''
PREFIX entity: <http://statistics.data.gov... | nilq/baby-python | python |
import unittest
import hcl2
from checkov.terraform.checks.resource.gcp.GoogleCloudSqlServerContainedDBAuthentication import check
from checkov.common.models.enums import CheckResult
class TestCloudSQLServerContainedDBAuthentication(unittest.TestCase):
def test_failure(self):
hcl_res = hcl2.loads(""" ... | nilq/baby-python | python |
import numpy as np
import pandas as pd
import pytest
from scipy import stats
from locan import LocData
from locan.analysis import BlinkStatistics
from locan.analysis.blinking import _blink_statistics, _DistributionFits
def test__blink_statistics_0():
# frame with on and off periods up to three frames and startin... | nilq/baby-python | python |
import unittest
import sys
from math import pi
sys.path.insert(0, "..")
from sections.sections import Wedge
import test_sections_generic as generic
class TestPhysicalProperties(generic.TestPhysicalProperties, unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.sectclass = Wedge
cl... | nilq/baby-python | python |
#!/usr/bin/env python3
# Usage raw_harness.py Y/N repTimes sourceFile arguments
# finally, will append a full function file
'''
original R file
#if has input, gen
args=c(args, argd, ...)
dataset = setup
'''
import sys,os
raw_haress_str = '''
rnorm <- runif
if(exists('setup')) {
if(length(bench_args) == 0... | nilq/baby-python | python |
# Import libraries
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import os
import scipy
# from scipy.sparse.construct import random
import scipy.stats
from scipy.stats import arcsine
from scipy.interpolate import interp1d
from astropy.io import fits
import astropy.units as u
# WebbPSF
import ... | nilq/baby-python | python |
import argparse
import contextlib
import collections
import grp
import hashlib
import logging
import io
import json
import os
import os.path
import platform
import pwd
import re
import shlex
import signal
import socket
import stat
import subprocess
import sys
import textwrap
import threading
import time
import uuid
fro... | nilq/baby-python | python |
#!/usr/bin/env python
###############################################################################
# $Id$
#
# Project: GDAL/OGR Test Suite
# Purpose: Test read/write functionality for USGSDEM driver.
# Author: Even Rouault <even dot rouault at mines dash paris dot org>
#
#########################################... | nilq/baby-python | python |
import tensorflow as tf
class GLU(tf.keras.layers.Layer):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def call(self, inputs, **kwargs):
channels = tf.shape(inputs)[-1]
nb_split_channels = channels // 2
x_1 = inputs[:, :, :, :nb_split_channels]
... | nilq/baby-python | python |
import aiohttp
import asyncio
import sys
import json
import argparse
async def upload_cast_info(session, addr, cast):
async with session.post(addr + "/wrk2-api/cast-info/write", json=cast) as resp:
return await resp.text()
async def upload_plot(session, addr, plot):
async with session.post(addr + "/wrk2-api/p... | nilq/baby-python | python |
"""Tests experiment modules."""
| nilq/baby-python | python |
import pytest
import json
from pytz import UnknownTimeZoneError
from tzlocal import get_localzone
from O365.connection import Connection, Protocol, MSGraphProtocol, MSOffice365Protocol, DEFAULT_SCOPES
TEST_SCOPES = ['Contacts.Read.Shared', 'Mail.Send.Shared', 'User.Read', 'Contacts.ReadWrite.Shared', 'Mail.ReadWrite... | nilq/baby-python | python |
import os
import dgl
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import networkx as nx
import numpy as np
from sklearn.model_selection import KFold
import digital_patient
from digital_patient.conformal.base import RegressorAdapter
from digital_patient.conformal.icp import IcpRegressor
f... | nilq/baby-python | python |
class Solution:
def minSumOfLengths(self, arr: List[int], target: int) -> int:
# need to know all subs
n = len(arr)
left = [math.inf] * n
seen = {0 : -1}
cur = 0
for i, val in enumerate(arr):
cur += val
if i > 0:
left[i] = left[... | nilq/baby-python | python |
# te18/leaderboard
# https://github.com/te18/leaderboard
from flask import Flask, render_template
app = Flask(__name__)
# error handlers
@app.errorhandler(400)
def error_400(e):
return render_template("errors/400.html"), 400
@app.errorhandler(404)
def error_404(e):
return render_template("errors/404.html"),... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""The Mozilla Firefox history event formatter."""
from __future__ import unicode_literals
from plaso.formatters import interface
from plaso.formatters import manager
from plaso.lib import errors
class FirefoxBookmarkAnnotationFormatter(interface.ConditionalEventFormatter):
"""The Firefox ... | nilq/baby-python | python |
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE
import os
import yaml
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
def getctype(typename):
flag = False
if "Const[" in typename:
flag = True
typename = typename[len("Const[") : -1]
array... | nilq/baby-python | python |
from enum import Enum
import random
class Color(Enum):
YELLOW = 0
RED = 1
BLUE = 2
GREEN = 3
NONE = -1
class Player(object):
def __init__(self, name, uid):
self.cards = []
self.name = name
self.id = uid
class Card(object):
def __init__(self, color):
self.id... | nilq/baby-python | python |
import os
from twisted.application import service
from twisted.python.filepath import FilePath
from buildslave.bot import BuildSlave
basedir = '.'
rotateLength = 10000000
maxRotatedFiles = 10
# if this is a relocatable tac file, get the directory containing the TAC
if basedir == '.':
import os.path
basedir =... | nilq/baby-python | python |
class LightCommand(object):
pass
| nilq/baby-python | python |
"""Package for all views."""
from .control import Control
from .dashboard import Dashboard
from .events import Events
from .live import Live
from .liveness import Ping, Ready
from .login import Login
from .logout import Logout
from .main import Main
from .resultat import Resultat, ResultatHeat
from .start import Start
... | nilq/baby-python | python |
"""MAGI Validators."""
| nilq/baby-python | python |
# Author: Nathan Trouvain at 16/08/2021 <nathan.trouvain@inria.fr>
# Licence: MIT License
# Copyright: Xavier Hinaut (2018) <xavier.hinaut@inria.fr>
from functools import partial
import numpy as np
from scipy import linalg
from .utils import (readout_forward, _initialize_readout,
_prepare_inputs_... | nilq/baby-python | python |
"""
This playbook checks for the presence of the Risk Response workbook and updates tasks or leaves generic notes. "Risk_notable_verdict" recommends this playbook as a second phase of the investigation. Additionally, this playbook can be used in ad-hoc investigations or incorporated into custom workbooks.
"""... | nilq/baby-python | python |
from learnware.feature.timeseries.ts_feature import *
import pandas as pd
import numpy as np
class TestTimeSeriesFeature:
def test_ts_feature_stationary_test(self):
df1 = pd.DataFrame(np.random.randint(0, 200, size=(100, 1)), columns=['x'])
df2 = pd.util.testing.makeTimeDataFrame(50)
df3 =... | nilq/baby-python | python |
"""
datos de entrada
A -->int -->a
B -->int -->b
C -->int -->c
D --> int --> d
datos de salida
"""
#entradas
a = int ( input ( "digite el valor de A:" ))
c = int ( input ( "digite el valor de B:" ))
b = int ( input ( "digite el valor de C:" ))
d = int ( input ( "digite el valor de D:" ))
#cajanegra
resu... | nilq/baby-python | python |
from kivy.logger import Logger
from kivy.clock import mainthread
from jnius import autoclass
from android.activity import bind as result_bind
Gso = autoclass("com.google.android.gms.auth.api.signin.GoogleSignInOptions")
GsoBuilder = autoclass(
"com.google.android.gms.auth.api.signin.GoogleSignInOptions$Builder"
)
... | nilq/baby-python | python |
import numpy as np; from random import choices
import matplotlib.pyplot as plt;
def Kroupa(N):
'''
Calculates N stellar masses drawing from a Kroupa IMF 0.08 < m < 130
Input >>> N = number of stars wanted
Output >>> masses = N-sized array of stellar masses
'''
# Create a... | nilq/baby-python | python |
import sys
from utils import write_exp_utils
import pandas as pd
from utils import misc_utils
import psycopg2
from psycopg2.extras import Json, DictCursor
def main(argv):
print(argv[1])
w = write_exp_utils.ExperimentConfig(argv[1], argv[2])
print("writing {} to database".format(argv[1]) )
w.write_to_db... | nilq/baby-python | python |
# Copyright 2019 The Johns Hopkins University Applied Physics Laboratory
#
# 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 ... | nilq/baby-python | python |
from __future__ import print_function
from timeit import default_timer as timer
import json
import datetime
print('Loading function')
def eratosthenes(n):
sieve = [ True for i in range(n+1) ]
def markOff(pv):
for i in range(pv+pv, n+1, pv):
sieve[i] = False
markOff(2)
for i in ... | nilq/baby-python | python |
"""
--- Day 1: The Tyranny of the Rocket Equation ---
https://adventofcode.com/2019/day/1
"""
class FuelCounterUpper:
"""Determines the amount of fuel required to launch"""
@classmethod
def calc_fuel_req(cls, mass: int) -> int:
"""calc fuel required for moving input mass
Don't fo... | nilq/baby-python | python |
from pyleap import *
bg = Rectangle(0, 0, window.width, window.height, color="white")
r = Rectangle(color=(125, 125, 0))
line1 = Line(100, 200, 300, 400, 15, 'pink')
tri = Triangle(200, 100, 300, 100, 250, 150, "green")
c2 = Circle(200, 200, 50, "#ffff00")
c = Circle(200, 200, 100, "red")
txt = Text('Hello, world')
c.... | nilq/baby-python | python |
# ======================================================================
# Timing is Everything
# Advent of Code 2016 Day 15 -- Eric Wastl -- https://adventofcode.com
#
# Python implementation by Dr. Dean Earl Wright III
# Tests from
# https://rosettacode.org/wiki/Chinese_remainder_theorem#Functional
# https://w... | nilq/baby-python | python |
import time
import random
import sqlite3
from parsers import OnePageParse
from parsers import SeparatedPageParser
from parsers import adultCollector
from history import History
conn = sqlite3.connect('killmepls.db')
c = conn.cursor()
for row in c.execute("SELECT MAX(hID) FROM stories"):
last_hID = r... | nilq/baby-python | python |
import math
import sys
import string
sys.path.append("../..")
from MolecularSystem import System
x = System(None)
y = System(None)
z = System(None)
x.load_pdb('1KAW.pdb')
y.load_pdb('1L1OA.pdb')
z.load_pdb('1L1OB.pdb')
for prot in [x,y,z]:
prot.ProteinList[0].fill_pseudo_sidechains(1)
prot.ProteinList[0].fill_n... | nilq/baby-python | python |
from ajenti.api import *
from ajenti.plugins.main.api import SectionPlugin
from ajenti.ui import on
from ajenti.ui.binder import Binder
from reconfigure.configs import ResolvConfig
from reconfigure.items.resolv import ItemData
@plugin
class Resolv (SectionPlugin):
def init(self):
self.title = _('Nameserv... | nilq/baby-python | python |
import pandas as pd
from pandas import ExcelWriter
counties_numbers_to_names = {
3: "Santa Clara",
4: "Alameda",
5: "Contra Costa",
2: "San Mateo",
8: "Sonoma",
1: "San Francisco",
6: "Solano",
9: "Marin",
7: "Napa"
}
counties_map = pd.read_csv("data/taz_geography.csv", index_col="zone").\
county.m... | nilq/baby-python | python |
#|=============================================================================
#|
#| FILE: ports.py [Python module source code]
#|
#| SYNOPSIS:
#|
#| The purpose of this module is simply to define
#| some easy-to-remember constants naming the port
#| numbers us... | nilq/baby-python | python |
from __future__ import annotations
import skia
from core.base import View, Rect
from views.enums import Alignment, Justify
class HBox(View):
def __init__(self):
super(HBox, self).__init__()
self._alignment = Alignment.BEGIN
self._justify = Justify.BEGIN
self._spacing = 0
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from gevent import monkey, event
monkey.patch_all()
import uuid
import unittest
import datetime
import requests_mock
from gevent.queue import Queue
from gevent.hub import LoopExit
from time import sleep
from mock import patch, MagicMock
from openprocurement.bot.identification.client import Do... | nilq/baby-python | python |
'''
该模块是控制流实例。
控制流语句如下:
if
while
for
break
continue
'''
def guessnumber():
'''猜数字游戏'''
number = 23
running = True
while running:
guess = int(input('猜整数:'))
if guess == number:
print('恭喜您,猜中啦!')
running = False
elif guess < number:
print('N... | nilq/baby-python | python |
import pytest
from ipypublish.filters_pandoc.utils import apply_filter
from ipypublish.filters_pandoc import prepare_labels
from ipypublish.filters_pandoc import format_label_elements
def test_math_span_latex():
in_json = {"blocks": [{"t": "Para", "c": [
{"t": "Span", "c": [
["a", ["labelled-... | nilq/baby-python | python |
from lxml import etree
import glob
class Plugin:
"""Class that defines a plugin with :
- his name
- his description
- his version
- his state..."""
def __init__(self, file, name, desc, version, state):
self.file = file
self.name = name
self.desc = desc
self.vers... | nilq/baby-python | python |
# type: ignore
import os
import signal
import sys
import time
def signal_handler(sig, frame):
print("You pressed Ctrl+C!")
time.sleep(1)
with open(
os.path.join(
os.path.dirname(os.path.dirname(__file__)),
"tests",
"signal_gracefully_terminated",
),
... | nilq/baby-python | python |
import LagInput
import os
def readInput(filename):
# INPUT: string filename
# OUTPUT: LagInput lagin
# This function reads from the input file and output the LagInput type lagin containing all the input values
os.chdir("../input")
fid = open(filename,"r")
for line in fid.readlines():
# Line Parsed... | nilq/baby-python | python |
import petsc4py
import sys
petsc4py.init(sys.argv)
from petsc4py import PETSc
import numpy as np
import MatrixOperations as MO
class BaseMyPC(object):
def setup(self, pc):
pass
def reset(self, pc):
pass
def apply(self, pc, x, y):
raise NotImplementedError
def applyT(self, pc, x, ... | nilq/baby-python | python |
"""$ fio distrib"""
import json
import logging
import click
import cligj
from fiona.fio import helpers, with_context_env
@click.command()
@cligj.use_rs_opt
@click.pass_context
@with_context_env
def distrib(ctx, use_rs):
"""Distribute features from a collection.
Print the features of GeoJSON objects read ... | nilq/baby-python | python |
#!/usr/bin/env python
import os
import base64
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from plant_disease_classification_api.models import ClassficationRequestItem
from plant_disease_classification_api.ml.plant_disease_classifier import (
PlantDiseaseClassifier,
)
app = FastAPI()
... | nilq/baby-python | python |
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from collections import Counter
import operator
import re
import os
import gc
import gensim
from gensim import corpora
from nltk.corpus import stopwords
import string
from copy import deepcopy
from sklearn.manifol... | nilq/baby-python | python |
from rest_framework.views import APIView
from rest_framework.response import Response
from . import signals
EVENTS = {
'Push Hook': signals.push_hook,
'Tag Push Hook': signals.tag_push_hook,
'Issue Hook': signals.issue_hook,
'Note Hook': signals.note_hook,
'Merge Request Hook': signals.merge_reques... | nilq/baby-python | python |
import FWCore.ParameterSet.Config as cms
from RecoMuon.TrackingTools.MuonServiceProxy_cff import *
muonSeedsAnalyzer = cms.EDAnalyzer("MuonSeedsAnalyzer",
MuonServiceProxy,
SeedCollection = cms.InputTag("ancientMuonSeed"),
... | nilq/baby-python | python |
import unittest
from monocliche.src.Card import Card
from monocliche.src.Deck import Deck
from monocliche.src.actions.DrawCardAction import DrawCardAction
class DrawCardActionTest(unittest.TestCase):
def test_execute(self):
cards = [Card('card1', '', None), Card('card2', '', None)]
deck = Deck(c... | nilq/baby-python | python |
from bitIO import *
from Element import Element
from PQHeap import PQHeap
import os
class Huffman:
"""
Huffman compression and decompression.
Authors:
- Kian Banke Larsen (kilar20)
- Silas Pockendahl (silch20)
"""
HEADER_SIZE = 1024
def _createHuffmanTree(freqs):
"""
... | nilq/baby-python | python |
# InfiniTag Copyright © 2020 AMOS-5
# Permission is hereby granted,
# free of charge, to any person obtaining a copy of this software and
# associated documentation files (the "Software"), to deal in the Software
# without restriction, including without limitation the rights to use, copy,
# modify, merge, publish, dist... | nilq/baby-python | python |
# Copyright 2019 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agre... | nilq/baby-python | python |
import telnetlib
import time
OK = 0
ERROR = 1
RESPONSE_DELAY_MS = 100
class AMXNMX(object):
def __init__(self, host, port=50002, response_delay_ms=RESPONSE_DELAY_MS):
self.conn = telnetlib.Telnet(host, port=port)
self.response_delay_sec = response_delay_ms / 1000.
self._initialize()
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Jayesh Kariya <jayeshk@saltstack.com>`
'''
# Import Python Libs
from __future__ import absolute_import
# Import Salt Testing Libs
from salttesting import TestCase, skipIf
from salttesting.mock import (
MagicMock,
patch,
NO_MOCK,
NO_MOCK_REASON
)
fro... | nilq/baby-python | python |
#!/usr/bin/env python
"""
A really simple module, just to demonstrate disutils
"""
def capitalize(infilename, outfilename):
"""
reads the contents of infilename, and writes it to outfilename, but with
every word capitalized
note: very primitive -- it will mess some files up!
this is called by th... | nilq/baby-python | python |
# -*- coding: utf-8 -*- #
"""*********************************************************************************************"""
# FileName [ utility/helper.py ]
# Synopsis [ helper functions ]
# Author [ Andy T. Liu (Andi611) ]
# Copyright [ Copyleft(c), Speech Lab, NTU, Taiwan ]
"""*************... | nilq/baby-python | python |
# module msysio.py
# Requires Python 2.2 or better.
"""Provide helpful routines for interactive IO on the MSYS console"""
# Output needs to be flushed to be seen. It is especially important
# when prompting for user input.
import sys
import os
__all__ = ['raw_input_', 'print_', 'is_msys']
# 2.x/3.x compatibility s... | nilq/baby-python | python |
#!/usr/bin/env python
import os
import sys
try:
here = __file__
except NameError:
# Python 2.2
here = sys.argv[0]
relative_paste = os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(here))), 'paste')
if os.path.exists(relative_paste):
sys.path.insert(0, os.path.dirname(relative_paste))... | nilq/baby-python | python |
from practicum import find_mcu_boards, McuBoard, PeriBoard
from flask import Flask, Response, jsonify, request
from flask_cors import CORS
import json
import threading
app = Flask(__name__)
CORS(app)
def ReadScore():
filename = "score.json"
with open(filename) as file:
data = json.load(file)
ret... | nilq/baby-python | python |
from python_kemptech_api import *
# Specify the LoadMaster connection credentials here:
loadmaster_ip = ""
username = ""
password = ""
lm = LoadMaster(loadmaster_ip, username, password)
# Specify the VS parameters:
vs_ip = ""
new_vs = ""
vs_port = ""
template_file = "template.txt"
# Create the VS
vs = lm.create_vir... | nilq/baby-python | python |
"""
Title: Mammogram Mass Detector
Author: David Sternheim
Description:
The purpose of this script is to take data regarding mass detected in a mammogram and use machine learning
models to predict if this mass is malignant or benign. The data is taken form UCI public data sets.
Bre... | nilq/baby-python | python |
import os
path = '/content/Multilingual_Text_to_Speech/checkpoints'
files = sorted(os.listdir(path)) | nilq/baby-python | python |
import numpy as np
import tensorflow as tf
tfkl = tf.keras.layers
def array2tensor(z, dtype=tf.float32):
"""Converts numpy arrays into tensorflow tensors.
Keyword arguments:
z -- numpy array
dtype -- data type of tensor entries (default float32)
"""
if len(np.shape(z)) == 1: # special case where input ... | nilq/baby-python | python |
# To run all the tests, run: python -m unittest in the terminal in the project directory.
from os.path import dirname, basename, isfile, join
import glob
# makes the modules easily loadable
modules = glob.glob(join(dirname(__file__), "*.py"))
__all__ = [basename(f)[:-3] for f in modules if isfile(f) and not f.endswit... | nilq/baby-python | python |
# -*- 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: ... | nilq/baby-python | 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... | nilq/baby-python | python |
from ptcaccount2.accounts import random_account
| nilq/baby-python | 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 ... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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,... | nilq/baby-python | python |
from mailbox import MMDF
from django_mail_admin.transports.generic import GenericFileMailbox
class MMDFTransport(GenericFileMailbox):
_variant = MMDF
| nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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 ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import flow
if __name__ == '__main__':
flow.initialize()
flow.app.run()
| nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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 é ... | nilq/baby-python | 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 =... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.