content stringlengths 5 1.05M |
|---|
from ascii_art import AsciiImage
def convert_image(image, output, neighborhood=1, print_image=True):
ascii_image = AsciiImage(filename=image, neighborhood=neighborhood)
if print_image:
print(ascii_image)
ascii_image.save(output)
if __name__ == "__main__":
import argparse
ap = argparse.Ar... |
i = 0
t = int(input())
casos = []
while(i < t):
c = float(input())
casos.append(c)
i +=1
for i in range(0,len(casos)):
n = casos[i]
d = 0.0
while n > 1.00:
n /= 2
d +=1
print(int(d),"dias")
|
from unittest import TestCase
from mulearn.kernel import *
class TestLinearKernel(TestCase):
def test_compute(self):
k = LinearKernel()
self.assertEqual(k.compute([1, 0, 1], [2, 2, 2]), 4)
self.assertEqual(k.compute((1, 0, 2), (-1, 2, 5)), 9)
self.assertAlmostEqual(k.compute([1.2,... |
# -*- coding: utf-8 -*-
###############################################################################
# Author: Gérald Fenoy, gerald.fenoy@cartoworks.com
# Copyright (c) 2010-2014, Cartoworks Inc.
###############################################################################
# Permission is hereby granted, fr... |
import pickle
new_dir = '/home/cail/Documents/causal-infogan/'
old_dir = '/home/thanard/Downloads/'
filename = "imgs_skipped_1.pkl"
f = open(filename,"rb")
hs = pickle.load(f)
nhs = []
for h in hs:
k = ((h[0][0].replace(old_dir,new_dir),h[0][1]),(h[1][0].replace(old_dir, new_dir),h[1][1]))
nhs.append(k)
f.c... |
"""
Leakage Resilient Primitive (AN12304).
NOTE: This implementation is suitable only for use on PCD side (the device which reads/interacts with the NFC tag).
You shouldn't use this code on PICC (NFC tag/card) side and it shouldn't be ported to JavaCards or similar,
because in such case it may be not resistant to the ... |
# Code to handle DMD related operations
from speck_rem.holography import *
def main():
pass
class Mask(Image):
"""
Class to handle the pattern masks to be projected onto the DMD
"""
def __init__(self, width=1920, height=1080, pitch=7.6e-6):
self.width = width
self.height = height... |
# Copyright 2013-2021 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 import *
class PyFlitCore(Package):
"""Distribution-building parts of Flit."""
homepage = "https://g... |
#coding:utf-8
#
# id: bugs.core_5783
# title: execute statement ignores the text of the SQL-query after a comment of the form "-"
# decription:
# We concatenate query from several elements and use '
# ' delimiter only to split this query into lines.
# Als... |
import os
import numpy as np
import sys
from random import shuffle
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)
## Download data if necessary
DATA_DIR = os.path.join(BASE_DIR, 'data')
if not os.path.exists(DATA_DIR):
os.mkdir(DATA_DIR)
# Download ShapeNet point clouds
if not os.pa... |
"""Handler.py : Concatenate individual datsets into one dataset"""
import pandas as pd
df = pd.read_csv('app/data/events/geoConflicts.csv')
df2 = pd.read_csv('app/data/events/usEvents.csv')
df3 = pd.read_csv('app/data/events/GND.csv')
pre_merge = [df, df2, df3]
merged = pd.concat(pre_merge)
filename = "app/data/eve... |
import tools
import numpy as np
import pickle
import pdb
import os
import view
from sklearn.svm import SVC
from sklearn.metrics.pairwise import pairwise_kernels
from sklearn.svm.libsvm import decision_function
# CREATE RESULT FOLDER
if not os.path.exists("results"):
os.makedirs("results")
# READ DATA
print("... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -------------------------------------------------------------------... |
"""libdarknet module.
Low level module for interacting with ```libdarknet.so``` static library.
Every module should have a docstring at the very top of the file. The
module's docstring may extend over multiple lines. If your docstring does
extend over multiple lines, the closing three quotation marks must be on
... |
from typing import Union
from fastapi import Cookie, FastAPI
app = FastAPI()
@app.get("/items/")
async def read_items(ads_id: Union[str, None] = Cookie(default=None)):
return {"ads_id": ads_id}
|
import numpy as np
import pandas as pd
from mpfin import mpPandasObj
def getDailyVol(close, span0=100):
'''
Computes the daily volatility of price returns.
It takes a closing price series, applies a diff sample to sample
(assumes each sample is the closing price), computes an EWM with
`span0` sa... |
import requests
import json
import numpy as np
import matplotlib.pyplot as plt
if __name__ == "__main__":
x = np.linspace(0, 10, 5000)
y = np.sin(2*np.pi*59*x) + np.sin(2*np.pi*33*x)
url = 'http://localhost:5000/run_command'
data = json.dumps((x.tolist(), y.tolist()))
req = requests.put(url, dat... |
from board import *
FLAG = 11
BOMB = 12
LAKE = -1
class Piece:
def __init__(self, x, y, rank, team, count, knownStat = []):
self.X = x
self.Y = y
self.rank = rank # switche id to rank for better naming
self.count = count
self.team = te... |
import sys
import matplotlib
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.collections import PatchCollection
from niftynet.io.image_reader import ImageReader
from niftynet.engine.image_window_dataset import ImageWindowDataset
from nifty... |
import os
import configparser
from boto3.session import Session
from fastapi.responses import FileResponse
from fastapi import APIRouter,File, UploadFile,Request,Depends
from pydantic import BaseModel
import json
from sqlalchemy import and_
from pydantic.types import FilePath
from sqlalchemy.sql.elements import Null
f... |
import tkinter as tk
#--- functions ---
def on_click():
for number, var in enumerate(all_variables):
print('optionmenu:', number, '| selected:', var.get(), '| all:', data[number])
#--- main ---
data = ['a,b,c', 'x,y,z']
root = tk.Tk()
all_variables = []
for options in data:
options = options.split(',')
... |
# -*- coding: utf-8 -*-
from random import randint
from numpy.random import choice
from items.equipment_properties import *
from items.basic_item import *
from items.consumables.potions import endurance_potion, health_potion, mana_potion
drop_list = []
potion_list = [endurance_potion.endurance_potion_lis... |
import py
from pypy.config.makerestdoc import register_config_role
docdir = py.magic.autopath().dirpath()
pytest_plugins = "pytest_restdoc"
class PyPyDocPlugin:
def pytest_addoption(self, parser):
group = parser.addgroup("pypy-doc options")
group.addoption('--pypy-doctests', action="store_true",... |
import os, glob
import cv2, dlib
import numpy as np
from threading import Thread
from __init__ import raw_dir, raw_fids_dir, ref_dir, log_dir
from pca import PCA
from face import get_landmark, LandmarkIndex, facefrontal
srcdir = '%s/mp4' % raw_dir
dstdir = '%s/fids' % raw_dir
subdirs = os.listdir(dstdir)
su... |
from keras.models import Model
from keras.layers import *
from algorithms.keraswtacnn import KerasWTACNN
class KerasRandomInitCNN(KerasWTACNN):
def __init__(self, results_dir, config):
super(KerasRandomInitCNN, self).__init__(results_dir, config)
def build_sparsity(self):
inp = Input(shape=(s... |
from agstoolbox.core.ags.ags_editor import AgsEditor
class Release(AgsEditor):
"""a GitHub release object"""
url = None
id = None
tag = None
is_pre_release = False
text_details = None
published_at = None
published_at_timestamp = None
archive_name = None
archive_url = None
... |
# method overriding - 2
class Animal:
def animalSound(self):
print('Animal sound !!')
def animalType(self):
print('Carnivorous or Herbivorous or Omnivorous !!')
class Dog(Animal):
def animalSound(self):
super().animalSound()
print('Dog sound !!')
d = Dog()
d.animalSound... |
"""
LeetCode Problem: 332. Reconstruct Itinerary
Link: https://leetcode.com/problems/reconstruct-itinerary/
Language: Python
Written by: Mostofa Adib Shakib
Time Complexity: O(N)
Space Complexity: O(N)
"""
class Solution:
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
self.hashMap = defau... |
"""
Implements similar functionality as tf.train.Checkpoint and tf.train.CheckpointManager.
https://gist.github.com/kevinzakka/5d345421f7abefd5dbaf6a77f829e70a.
"""
import logging
import os
import signal
import numpy as np
import os.path as osp
import torch
from glob import glob
def mkdir(s):
"""Create a director... |
# Code is based on scikit-learns permutation importance.
import numpy as np
from joblib import Parallel
from sklearn.metrics import check_scoring
from sklearn.utils import Bunch
from sklearn.utils import check_random_state
from sklearn.utils import check_array
from sklearn.utils.fixes import delayed
from sklearn.inspe... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 9 22:57:58 2020
@author: ashokubuntu
"""
# Importing Packages
import pandas as pd
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
fro... |
from .launcher import gen_launch_element_tree
|
######################################################
#
# Generate Harmonics data
#
######################################################
import numpy as np
def generate(sineCoeffArray, sinePeriodsArray, cosineCoeffArray, cosinePeriodsArray, timeSteps, tStart = 0):
if (len(sineCoeffArray) != len(sinePerio... |
"""
This script analyzes the partition results
"""
import networkx as nx
import os
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import csv
import numpy as np
import genetic_partition_test as gp
import itertools
from networkx.drawing.nx_agraph import graphviz_layout
import matplotlib.image as ... |
a=[]
for r in range (5):
a.append(input("Enter a number : "))
print(a)
def QuickSort(a,p,r):
if p < r:
q = Partition (a,p,r)
QuickSort(a,p,q-1)
QuickSort(a,q+1,r)
def Partition(a,p,r):
x = a[r]
i = p-1
for j in range (p,r-1):
if a[j]<=x:
i=i+1
... |
#!/usr/bin/python3
# Copyright (c) 2018-2019 VMware, Inc. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Gather stats on a rocksdb dump. Prepare the dump files with:
#
# rocksdb-5.7.3/ldb --db=<rocksdb directory> \
# --path=<file in directory> \
# --hex dump > <dum... |
# -*- coding: utf-8 -*-
# dcf
# ---
# A Python library for generating discounted cashflows.
#
# Author: sonntagsgesicht, based on a fork of Deutsche Postbank [pbrisk]
# Version: 0.7, copyright Friday, 14 January 2022
# Website: https://github.com/sonntagsgesicht/dcf
# License: Apache License 2.0 (see LICENSE file... |
import cookielib
import requests
import logging
import os
import json
from .config import config, CONFIG_FOLDER
BASE_URL = 'https://leetcode.com'
LOGIN_URL = BASE_URL + '/accounts/login/'
API_URL = BASE_URL + '/api/problems/algorithms/'
COOKIE_PATH = os.path.join(CONFIG_FOLDER, 'cookies')
headers = {
'Accept': '... |
# 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... |
from unittest import TestCase
import mobile_codes
class TestCountries(TestCase):
def test_mcc(self):
countries = mobile_codes.mcc(u'302')
self.assertEqual(len(countries), 1)
self.assertEqual(countries[0].mcc, u'302')
def test_mcc_multiple_codes(self):
countries = mobile_code... |
# “价值 2 个亿”的 AI 代码
while True:
print('AI: 你好,我是价值 2 个亿 AI 智能聊天机器人! 有什么想问的的吗?')
message = input('我: ')
print('AI: ' + message.replace('吗','').replace('?','!')) |
s = """
.a.fy
def boom:
real x
subboom(x)
def subboom:
real inout x
x = 1 / 0
"""
from fython.test import *
shell('rm -rf a/ a.* b.*')
writer(s)
w = load('.a', force=1, release=0, verbose=0, run_main=1)
w.verbose()
try:
w.boom()
except Exception as e:
print(e)
assert 'sigfpe' in str(e)
|
from HSTB.kluster.__version__ import __version__
|
import json
import xml.etree.ElementTree as etree
from pathlib import Path
from pytiled_parser.common_types import OrderedPair, Size
from pytiled_parser.exception import UnknownFormat
from pytiled_parser.parsers.json.tileset import parse as parse_json_tileset
from pytiled_parser.parsers.tmx.layer import parse as parse... |
from copy import deepcopy
import numpy as np
import networkx as nx
def uniformWeights(G) -> dict:
"""
ユーザー間の影響力を一様分布で設定する.
各ユーザー間の影響力 = 各ユーザーの次数の逆数 とする.
"""
Ew = dict()
for u in G:
in_edges = G.in_edges([u], data=True)
dv = sum([edata['weight'] for v1, v2, edata in in_edges])
... |
"""Compound passes for rendering a shadowed scene...
The rendering passes here provide the bulk of the algorithm
for rendering shadowed scenes. You can follow the algorithm
starting at the OverallShadowPass, which manages 3 sets of
sub-passes:
ambient light passes (subPasses)
opaque-ambient-light pass
... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^register/', views.RegistrationFormView.as_view(), name='register'),
url(r'^orders/$', views.ProfileOrdersView.as_view(), name='orders'),
url(r'^orders/(?P<pk>\d+)/$', views.ProfileOrderDetailView.as_view(), name='order_detail'),
... |
import logging
import sedate
from datetime import timedelta
from itertools import groupby
from libres.context.core import ContextServicesMixin
from libres.db.models import Allocation, Reservation, ReservedSlot
from libres.modules import errors, events
from sqlalchemy import func, null
from sqlalchemy.orm import joined... |
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
for c in s:
if c in ['(', '{', '[']:
stack.append(c)
continue
elif c == ')':
if len(stack) > 0 and stack[... |
"""
Contains functions for computing thermal noise in conductive thin objects.
"""
__all__ = [
"compute_current_modes",
"noise_covar",
"noise_covar_dir",
"noise_var",
"visualize_current_modes",
]
import numpy as np
import trimesh
from .suhtools import SuhBasis
from .mesh_conductor import MeshCon... |
from .ascim import ASCIM
class ASCIMDraw:
"""Draw text and shapes on an ASCIM Image. Operations will be done in-place."""
def __init__(self, im):
"""Construct a ASCIMDraw object on a canvas.
:param im: ASCIM Image this ASCIMDraw object applies modifications to.
"""
... |
"""Contains the classes and functions for scraping a yahoo finance summary page."""
from collections import ChainMap
from typing import Dict, Iterable, List, Optional
from pandas import DataFrame
from pendulum.date import Date
from pydantic import BaseModel as Base
from pydantic import Field
from requests_html import... |
from nltk.util import bigrams
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
import string
import pandas as pd
import random
#from sentiments import SENTIMENTS
DATAFRAME_PATH = "../../dataset/dataframes/"
def preprocess(lyric: str) -> list:
lyric = lyric.lower()
lyric = lyric.r... |
from rest_framework.exceptions import ValidationError
class BaseElementSet(object):
'''
A `BaseElementSet` is a collection of unique `BaseElement` instances
(more likely the derived children classes) and is typically used as a
metadata data structure attached to some "real" data. For instance,
gi... |
from ass2 import create_graph
from random import random
import sys
import heapq
import time
class Vertex:
def __init__(self, idx, adj=None):
# adj is a [list of (vertex, weight) pairs]
self.adj = adj
self.cost = 1
self.prev = None
self.idx = idx
def __cmp__(self, other):
return cmp(self.cost, other.cost... |
import pytest
from scraper import nyc
PARSE_TRIP_ID_ARGNAMES = [
"trip_id",
"sub_division",
"effective_date",
"service_day",
"origin_time",
"trip_path",
"route_id",
"direction",
"path_identifier",
]
PARSE_TRIP_ID_PARAMS = [
(
"AFA19GEN-1037-Sunday-00_010600_1..S03R",
... |
import ffmpeg
import os
import subprocess
class ffmpeg_image_pipe:
encoders = {
'gif': {
'pix_fmt':'rgb8',
'codec':"gif",
'filter_complex': '[0:v]split[x][z];[z]palettegen[y];[x]fifo[x];[x][y]paletteuse'
},
'png': {
'pix_fmt':'rgba',
'codec':"png"
},
'vp8':{
'pix_fmt':'yuv422p',
'codec'... |
#!/usr/bin/env python3
"""Generate AST classes from grammar."""
import pkg_resources
from scoff.misc.textx import parse_textx_grammar, build_python_class_text
if __name__ == "__main__":
the_grammar = pkg_resources.resource_filename("sm", "state_machine.tx")
grammar_rules = parse_textx_grammar(the_grammar)
... |
#!/usr/bin/env python
from itertools import groupby
from operator import attrgetter,itemgetter
import sys
#----------------------------------------------
def printHelp():
s = '''
To Use: Add the Tracer Service to the cmsRun job you want to check for
stream stalls. Make sure to use the 'printTimstamps' option
... |
import pygame
class Brick:
def __init__(self, x, y,color,ID):
self.x = x
self.y = y
self.width = 32
self.height = 32
self.ID = ID
self.color = color
def render(self, window):
if self.ID == 'g':
img = pygame.image.load('Assets/Images/grass.bmp')
e... |
from django.urls import path
from . import views
from .custom_views import product_views, customer_views, order_views
urlpatterns = [
path('', views.index, name='index'),
path('products/', product_views.Products, name='products'),
path('products/<int:product_id>/', product_views.ProductDetails, name='produ... |
#!/usr/bin/env python3
from ..result import ExpectResult
from ..util.include import *
from ..util import py_exec, py_eval
def expect(vals, rules, peval="#", pexec="%", mode="", **kwargs):
if mode == peval:
return [run_expect("", rules, "eval", val=vals, **kwargs)]
if mode == pexec:
return [r... |
import errno
from pypy.interpreter.error import oefmt
from pypy.module.cpyext.api import cpython_api, CONST_STRING
from pypy.module.cpyext.pyobject import PyObject
from rpython.rlib import rdtoa
from rpython.rlib import rfloat
from rpython.rlib import rposix, jit
from rpython.rlib.rarithmetic import intmask
from rpytho... |
import random
import tkinter
import math
class Blackjack():
def __init__(self, master):
#Menu
glavniMenu = tkinter.Menu(master)
master.config(menu = glavniMenu)
menuBJ = tkinter.Menu(glavniMenu)
glavniMenu.add_cascade(label = 'Blackjack', menu=menuBJ)
menuBJ.add_cascade(label = 'New Game', command = ... |
import h5py
import os
import numpy as np
from sys import argv
from stereo_processing import align_audio, downsize
path = '/Volumes/seagate/legit_data/'
current_path = os.getcwd()+'/'
print "opening main file"
with h5py.File(current_path+argv[1], 'r') as main_data:
main_audio = main_data['audio'].value
main_depth = m... |
# Generated by Django 3.0.3 on 2020-09-02 20:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("dashboard", "0024_xengchannels_time"),
]
operations = [
migrations.AddField(
model_name="snaptoant",
name="node",
... |
import unittest
import copy
import os
from unittest.mock import patch
from mongoengine import connect, disconnect
from google.protobuf.json_format import MessageToDict
from google.protobuf.empty_pb2 import Empty
from spaceone.core.unittest.result import print_message
from spaceone.core.unittest.runner import RichTestR... |
#!/usr/bin/env python3
#
# Copyright 2013 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Unittest for serial_utils."""
import unittest
from unittest import mock
from cros.factory.test.utils import serial_utils
fr... |
from . import navigation, filters, filter_layout
|
import pytest
import sys
sys.path.append("..")
from utils import recover
def test_recovery():
privkey, chaincode = recover.restore_key_and_chaincode("backup.zip", "priv.pem", "Thefireblocks1!")
assert(privkey == 0x473d1820ca4bf7cf6b018a8520b1ec0849cb99bce4fff45c5598723f67b3bd52)
pub = recover.get_public_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# (C) 2014 Arulalan.T <arulalant@gmail.com>
#
# This file is part of 'open-tamil/txt2unicode' package examples
#
import sys
sys.path.append('../..')
from tamil.txt2unicode import tscii2unicode
tscii = """¾¢ÕÅûÙÅ÷
«ÕǢ ¾¢ÕìÌÈû """
uni = tscii2unicode(tscii)
f = open(... |
import acoustic_array
if __name__ == '__main__':
# Open the phase controller
pc = acoustic_array.Controller()
# The controller has 32 output banks (0-31), and 256 channels (0-255).
# Each pin on the output of the device controls 16 channels, i.e.
# FPGA pin 1: channels 0-15
# FPGA pin 2: c... |
#
# Copyright (c) 2017 Electronic Arts Inc. All Rights Reserved
#
from __future__ import print_function
from __future__ import absolute_import
from builtins import object
import json
import shutil
import os
import re
import time
import logging
import threading
from sys import platform
from .base import BaseJob
cla... |
#!/usr/bin/env pytest
###############################################################################
# $Id$
#
# Project: GDAL/OGR Test Suite
# Purpose: Test /vsioss
# Author: Even Rouault <even dot rouault at spatialys dot com>
#
###############################################################################
# Cop... |
from os import chdir
from pathlib import Path
from shutil import copy2 as copy
from subprocess import run
import pytest
@pytest.fixture
def fossil():
return "/home/osboxes/src/fossil-snapshot-20210429/fossil"
@pytest.fixture
def repo_path():
return "/home/osboxes/proj/pyphlogiston/pyphlogiston/repo"
@pyt... |
def quick_sort(array):
if len(array) < 2:
return array
pivot = array[0]
lower = [i for i in array[1:] if i <= pivot]
upper = [i for i in array[1:] if i > pivot]
return quick_sort(lower) + [pivot] + quick_sort(upper)
quick_sort([12, 31, 5, 3, 0, 43, 99, 78, 32, 9, 7]) |
# Generated by Django 3.1.7 on 2021-06-17 16:49
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('userapp', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='O... |
from django.conf.urls.defaults import *
urlpatterns = patterns('',
url(r'^$', 'privatebeta.views.invite', name='privatebeta_invite'),
url(r'^activate/(?P<code>\w+)/$', 'privatebeta.views.activate_invite',
{'redirect_to': '/register/'}, name='privatebeta_activate_invite'),
url(r'^sent/$', 'privatebe... |
import numpy as np
import tensorflow as tf
import random
import pickle
######################################## TF-IDF ############################################
from sklearn.feature_extraction.text import TfidfVectorizer
from collections import defaultdict
class TFIDF:
def __init__(self):
#load files
... |
from flask import Flask, make_response, request, abort, render_template
from Crypto.Cipher import AES
from Crypto import Random
from Crypto.Util import Padding
import base64
import hashlib
import json
import urllib
import random
app = Flask(__name__)
IV = Random.new().read(AES.block_size)
random.seed()
KEY = ''.joi... |
n=int(input())
academy_dict={}
for _ in range(n):
students=input()
grade=float(input())
if students not in academy_dict.keys():
academy_dict[students]=[]
academy_dict[students].append(grade)
for student,grades in academy_dict.items():
average_grades=sum(grades)/len(grades)
academy_dict[s... |
from unittest import TestCase
from memory_consumer import Consumer
class ConsumerTest(TestCase):
def test_simple(self):
consumer = Consumer(size=6, grow=3, hold=2)
expected_sizes = [2, 4, 6, 6, 6]
sizes = [len(consumer.data) for _ in consumer]
self.assertEqual(expected_sizes, si... |
""":mod:`rmon` --- redis monitor system
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
from flask import Flask
app = Flask(__name__, static_folder='assets', static_url_path='/assets')
app.config.from_envvar('RMON_SETTINGS')
from rmon.commons.views import mod as commonsModule
from rmon.clusters.views import mod as clust... |
import logging
import xml.etree.ElementTree as ET
from .baseplugin import AbstractClient
from pushno.messages import ProwlValidationMessage
# API endpoint base URL
BASE_URL = "https://api.prowlapp.com/publicapi"
# API endpoint to send messages
MESSAGE_URL = "{}/add".format(BASE_URL)
# API endpoint to validate the... |
import random
class Traveller:
"""Class which represent a travelling salesman
Author : Thomas Minier
"""
def __init__(self, id=None):
self.id = id
self.path = list()
self.nbChilds = 0
def __eq__(self, other):
if type(self) != type(other):
return False
... |
"""
файл функции, выполняющей команды в зависимости от времени
"""
from datetime import datetime
import pg_connect
import dataBase
import sqlite3
import args
"""
отдебажил функцию timer теперь выполнение, начисление очков и прочее работает корректно (upd я ошибался)
"""
def timer():
try:
... |
#!/usr/bin/env python3
# Dump Android Verified Boot Signature (c) B.Kerler 2017-2018
import hashlib
import struct
from binascii import hexlify,unhexlify
import sys
import argparse
from Crypto.Util.asn1 import DerSequence
from Crypto.PublicKey import RSA
from Library.libavb import *
version="v1.6"
def extract_hash(pub... |
import logging
import os
import unittest
from utils.users import UsersUtil
class UsersUtilTest(unittest.TestCase):
def setUp(self):
def _fake_fetch_actor(actor_url):
return {
'preferredUsername': 'cianlr',
'summary': 'cianlr is here'
}
os.... |
from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase
from wshop.models.fields import NullCharField
class NullCharFieldTest(TestCase):
def test_from_db_value_converts_null_to_string(self):
field = NullCharField()
self.assertEqual('', field.from_db_value(None, e... |
import logging
import threading
import time
from cachetools import LRUCache
from celery.events import EventReceiver
import tornado.gen
from tornado.ioloop import PeriodicCallback
from tornado.queues import Queue
logger = logging.getLogger(__name__)
class EventMonitor(threading.Thread):
max_events = 100
def... |
from os.path import join, dirname
from os import environ
from watson_developer_cloud import VisualRecognitionV3
visual_recognition = VisualRecognitionV3('2016-05-20', api_key='4a5dce0273f76cfc7fdebaec7d43f6828a512194')
def classify(url):
return visual_recognition.classify(images_url=url)
|
# -*- coding: utf-8-*-
import os
from robot import config, utils, logging
from watchdog.events import FileSystemEventHandler
logger = logging.getLogger(__name__)
class ConfigMonitor(FileSystemEventHandler):
def __init__(self, conversation):
FileSystemEventHandler.__init__(self)
self._conversation... |
import time
class HumanBrain(object):
def __init__(self):
self.minKeyPress = 10
self.maxKeyPress = 100
self.timeAwareDeviation = 0.3
def keyPress(self):
"""Send a human like keypress.
Keyword arguments:
keyCode -- the real key to be pressed (example Keycode.SE... |
float_1 = 0.25
float_2 = 40.0
product = float_1 * float_2
big_string = "The product was " + str(product) # float to string
|
import os
import time
import unittest
import twodlearn as tdl
import twodlearn.datasets.cifar10
from twodlearn.templates.supervised import (
LinearClassifier, MlpClassifier, AlexNetClassifier)
TESTS_PATH = os.path.dirname(os.path.abspath(__file__))
TMP_PATH = os.path.join(TESTS_PATH, 'cifar10_data/')
class Optim... |
import itertools
import numpy as np
from functools import partial
from pyquil import Program, api
from pyquil.paulis import PauliSum, PauliTerm, exponential_map, sZ
from pyquil.gates import *
from scipy.optimize import minimize
import pennylane as qml
from pennylane import numpy as np
np.set_printoptions(precision=3, s... |
import os
import glob
import pyopenms
toTest = set()
# pyopenms in the ignore list as it is represented twice in
# the pyopenms package
ignore = ["numpy", "np", "re", "os", "types", "sysinfo", "pyopenms"]
for clz_name, clz in pyopenms.__dict__.items():
if clz_name in ignore or clz_name.startswith("__"):
... |
# -*- coding: utf-8 -*-
#
# (c) 2017 Kilian Kluge
#
# 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 applica... |
'''
Detectors entry point.
'''
def get_bounding_boxes(frame, model):
'''
Run object detection algorithm and return a list of bounding boxes and other metadata.
'''
if model == 'yolo':
from detectors.yolo import get_bounding_boxes as gbb
elif model == 'haarcascade':
from detectors.ha... |
# Leo colorizer control file for actionscript mode.
# This file is in the public domain.
# Properties for actionscript mode.
properties = {
"commentEnd": "*/",
"commentStart": "/*",
"doubleBracketIndent": "false",
"indentCloseBrackets": "}",
"indentOpenBrackets": "{",
"indentPrevLine"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.