code
stringlengths
1
199k
from numpy import array, zeros, linspace, meshgrid, ndarray, diag from numpy import uint8, float64, int8, int0, float128, complex128 from numpy import exp, sqrt, cos, tan, arctan from numpy import minimum, maximum from numpy import ceil, floor from numpy import matrix as npmatrix from numpy.fft import fft, ifft from nu...
import numpy arr = numpy.array(list(map(float, input().split()))) x = float(input()) value = numpy.polyval(arr, x) print(value)
""" WSGI config for photoboard project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTIN...
import torch import torchvision.transforms as transforms import torch.utils.data as data import os import json import pickle import argparse from PIL import Image import numpy as np from utils import Vocabulary class CocoDataset(data.Dataset): def __init__(self, root, anns, vocab, mode='train',transform=None): ...
from collections import namedtuple import select StreamEvent = namedtuple( 'StreamEvent', [ 'fd', 'stream', 'data', 'direction', 'num_bytes', 'eof' ] ) class StreamWatcher(object): def __init__( self ): if _best_backend is None: raise Exception( "No poll/queue backend could be found for your OS." ) self.backend...
try: from setuptools import setup except ImportError: from distutils.core import setup config = { 'description':'End to end solution for bitcoin data gathering, backtesting, and live trading', 'author': 'ross palmer', 'url':'http://rosspalmer.github.io/bitQuant/', 'license':'MIT', 'version': '0.2.10', 'install_...
""" Module with the MCMC (``emcee``) sampling for NEGFC parameter estimation. """ __author__ = 'O. Wertz, Carlos Alberto Gomez Gonzalez, V. Christiaens' __all__ = ['mcmc_negfc_sampling', 'chain_zero_truncated', 'show_corner_plot', 'show_walk_plot', 'confidence'] import numpy ...
import pygame import math class Screen: ''' Se encarga de controlar lo que ve el jugador en la pantalla. Parameters ---------- size : List[int] Tamaño de la pantalla, ``[w, h]``. Notes ----- Primero se debe crear una instancia de este objeto, luego, en cada loop del juego uno...
import numpy as np class Site(object): """A class for general single site Use this class to create a single site object. The site comes with identity operator for a given dimension. To build specific site, additional operators need be add with add_operator method. """ def __init__(self, dim): ...
import datetime import json from brake.decorators import ratelimit from django.utils.decorators import method_decorator from django.utils.translation import get_language from django.conf import settings from django.core.urlresolvers import reverse_lazy from django.http import HttpResponseRedirect, HttpResponse from dja...
class DatabaseRouter(object): ''' These functions are called when Django accesses the database. Returns the name of the database to use depending on the app and model. Returning None means use default. ''' def db_for_read(self, model, **hints): return self.__db_for_read_and_write(model, ...
SIMPLE_SETTINGS = { 'OVERRIDE_BY_ENV': True } MY_VAR = u'Some Value'
import _plotly_utils.basevalidators class SizeValidator(_plotly_utils.basevalidators.NumberValidator): def __init__( self, plotly_name="size", parent_name="histogram.marker.colorbar.tickfont", **kwargs ): super(SizeValidator, self).__init__( plotly_name=plotly...
from load import load_dataset import numpy as np from threshold import learn_model, apply_model, accuracy features, labels = load_dataset('seeds') labels = (labels == 'Canadian') error = 0.0 for fold in range(10): training = np.ones(len(features), bool) # numpy magic to make an array with 10% of 0s starting at ...
import re from unidecode import unidecode import os, sys from hashlib import md5 as hasher import binascii import settings def gen_flattened_list(iterables): for item in iterables: if hasattr(item, '__iter__'): for i in item: yield i else: yield item def crc32...
import urllib2 url = "http://localhost:8888/test/test.txt" html = urllib2.urlopen(url).read() print html send_headers = { 'range':'bytes=10-' } req = urllib2.Request(url, headers=send_headers) html = urllib2.urlopen(req).read() print html
N = int(input()) B = [int(x) for x in input().split()] A = [10**5] * N for i, b in enumerate(B): A[i] = min(A[i], b) A[i+1] = min(A[i+1], b) print(sum(A))
'''coffeehandlers.py - Waqas Bhatti (wbhatti@astro.princeton.edu) - Jul 2014 This contains the URL handlers for the astroph-coffee web-server. ''' import os.path import logging import base64 import re LOGGER = logging.getLogger(__name__) from datetime import datetime, timedelta from pytz import utc, timezone import tor...
""" This file was generated with the customdashboard management command and contains the class for the main dashboard. To activate your index dashboard add the following to your settings.py:: GRAPPELLI_INDEX_DASHBOARD = 'version3.dashboard.CustomIndexDashboard' """ from django.utils.translation import ugettext_lazy...
"""Test event helpers.""" import unittest from datetime import datetime, timedelta from astral import Astral from homeassistant.bootstrap import setup_component import homeassistant.core as ha from homeassistant.const import MATCH_ALL from homeassistant.helpers.event import ( track_point_in_utc_time, track_poin...
""" .. moduleauthor:: Chris Dusold <DriveLink@chrisdusold.com> A module containing general purpose, cross instance hashing. This module intends to make storage and cache checking stable accross instances. """ from drivelink.hash._hasher import hash from drivelink.hash._hasher import frozen_hash from drivelink.hash._has...
from unittest import TestCase import pandas as pd import pandas.util.testing as tm import numpy as np import trtools.core.topper as topper import imp imp.reload(topper) arr = np.random.randn(10000) s = pd.Series(arr) df = tm.makeDataFrame() class TestTopper(TestCase): def __init__(self, *args, **kwargs): Te...
import sys def main(): with open(sys.argv[1]) as input_file: for line in input_file.readlines(): input_list = list(reversed(line.strip().split(' '))) index = int(input_list[0]) del input_list[0] print(input_list[index - 1]) if __name__ == '__main__': main(...
""" Summary: Container and main interface for accessing the Tuflow model and a class for containing the main tuflow model files (Tcf, Tgc, etc). There are several other classes in here that are used to determine the order of the files in the model and key words for reading in the files. Author: ...
from math import floor, log10 def round_(x, n): """Round a float, x, to n significant figures. Caution should be applied when performing this operation. Significant figures are an implication of precision; arbitrarily truncating floats mid-calculation is probably not Good Practice in almost all cases. Rounding of...
"""Test fee estimation code.""" from decimal import Decimal import random from test_framework.messages import CTransaction, CTxIn, CTxOut, COutPoint, ToHex, COIN from test_framework.script import CScript, OP_1, OP_DROP, OP_2, OP_HASH160, OP_EQUAL, hash160, OP_TRUE from test_framework.test_framework import DigiByteTestF...
import SocketServer import time HOST = '' PORT = 1234 ADDR = (HOST, PORT) class MyRequestHandler(SocketServer.StreamRequestHandler): def handle(self): print('...connected from: {}'.format(self.client_address)) self.wfile.write('[{}] {}'.format(time.ctime(), ...
from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRe...
from helper_sql import sqlExecute def insert(t): sqlExecute('''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)''', *t)
from . import adaptVor_driver from .adaptVor_driver import AdaptiveVoronoiDriver
import os import sys def main(): if len(sys.argv) != 2: print("Usage: Pass the file name for the source transcript txt file.") sys.exit(-1) file = sys.argv[1] out_file = os.path.expanduser( os.path.join( '~/Desktop', os.path.basename(file) ) ) ...
import json import os from typing import Any, Dict, Iterator, List from dataflow.core.utterance_tokenizer import UtteranceTokenizer from dataflow.multiwoz.create_programs import create_programs_for_trade_dialogue from dataflow.multiwoz.salience_model import DummySalienceModel, VanillaSalienceModel def load_test_trade_d...
""" The MIT License Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel 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 ri...
n, d = map(int, input().split()) A = list(map(int, input().split())) print(*(A[d:] + A[:d]))
from django import template from django.utils.encoding import smart_str from django.core.urlresolvers import reverse, NoReverseMatch from django.db.models import get_model from django.db.models.query import QuerySet register = template.Library() class GroupURLNode(template.Node): def __init__(self, view_name, group...
import unittest import unittest.mock as mock import dice import dice_config as dcfg import dice_exceptions as dexc class DiceInputVerificationTest(unittest.TestCase): def test_dice_roll_input_wod(self): examples = {'!r 5':[5, 10, None, 10, 8, 'wod', None], '!r 2000':[2000, 10, None, 10, ...
import tensorflow as tf import numpy as np from baselines.ppo2.model import Model class MicrobatchedModel(Model): """ Model that does training one microbatch at a time - when gradient computation on the entire minibatch causes some overflow """ def __init__(self, *, policy, ob_space, ac_space, nbatc...
import django from django.conf import settings if django.VERSION >= (1, 5): AUTH_USER_MODEL = settings.AUTH_USER_MODEL else: try: from django.contrib.auth.models import User AUTH_USER_MODEL = 'auth.User' except ImportError: raise ImportError(u"User model is not to be found.") try: ...
from PyQt4.QtGui import * import pypipe.formats import pypipe.basefile from pypipe.core import pipeline from widgets.combobox import ComboBox class AddFileDialog(QDialog): def __init__(self, parent=None): super(AddFileDialog, self).__init__(parent) self.formats_combo = ComboBox() self.filena...
import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bitcamp.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
from .lattice import default_optics_mode from .lattice import energy from .accelerator import default_vchamber_on from .accelerator import default_radiation_on from .accelerator import accelerator_data from .accelerator import create_accelerator from .families import get_family_data from .families import family_mapping...
from scapy.packet import Packet, bind_layers from scapy.fields import FieldLenField, BitEnumField, StrLenField, \ ShortField, ConditionalField, ByteEnumField, ByteField, StrNullField from scapy.layers.inet import TCP from scapy.error import Scapy_Exception class VariableFieldLenField(FieldLenField): def addfiel...
from setuptools import setup, find_packages setup( description='RESTful Nagios/Icinga Livestatus API', author='Christoph Oelmueller', url='https://github.com/zwopiR/lsapi', download_url='https://github.com/zwopiR/lsapi', author_email='christoph@oelmueller.info', version='0.1', install_requir...
from __future__ import unicode_literals from __future__ import absolute_import import json import logging import logging.config import os class AlpineObject(object): """ Base Class of Alpine API objects """ # # alpine alpine version string # _alpine_api_version = "v1" _min_alpine_version...
import os import glob import math import subprocess import re import sys import datetime import shutil from decimal import Decimal from astropy.io import fits from astropy import wcs from astropy import log log.setLevel('ERROR') from astropy import units as u import ccdproc import numpy as np def logme( str ): log.w...
import time def check_vertical(matrix): max_product = 0 for row in xrange(0, len(matrix)-3): for col in xrange(0, len(matrix)): product = matrix[row][col] * matrix[row+1][col] * matrix[row+2][col] * matrix[row+3][col] max_product = max(product, max_product) return max_product def check_horizontal(matrix): m...
from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Trac...
from django.conf.urls import url from dictionaries.items.views import DicItemsListView, DicItemsCreateView, \ DicItemsDetailView, DicItemsUpdateView, DicItemsDeleteView urlpatterns = [ url(r'^$', DicItemsListView.as_view(), name='items-list'), url(r'^add/$', DicItemsCreateView.as_view(), name='items-add'), ...
from flask.ext.sqlalchemy import SQLAlchemy from . import db class Role(db.Model): __tablename__='roles' id=db.Column(db.Integer,primary_key=True) name=db.Column(db.String(64),unique=True) users=db.relationship('User',backref='role') def __repr__(self): return '<Role>{}</Role>'.format(self.n...
SCHEDULE_NONE = None SCHEDULE_HOURLY = '0 * * * *' SCHEDULE_DAILY = '0 0 * * *' SCHEDULE_WEEKLY = '0 0 * * 0' SCHEDULE_MONTHLY = '0 0 1 * *' SCHEDULE_YEARLY = '0 0 1 1 *'
from django.conf.urls import patterns, include, url from django.contrib import admin import urls from apps.blog import views urlpatterns = patterns('', # Examples: # url(r'^$', 'gigsblog.views.home', name='home'), # url(r'^blog/', include('blog.urls')), # url(r'^admin/', include(admin.site.urls)), u...
from bs4 import BeautifulSoup as Soup import urls import re import proxy from datetime import * import time from time import mktime import functions def materials ( config ): url = "https://www.lectio.dk/lectio/%s/MaterialOverview.aspx?holdelement_id=%s" % ( str(config["school_id"]), str(config["team_element_id"]) ) ...
try: from setuptools import setup except ImportError: from distutils.core import setup setup( name='mozscape', version='0.1.1', description='Mozscape API Bindings for Python', author_email='dan@moz.com', url='http://github.com/seomoz/SEOmozAPISamples', py_modules=['mozscape'], licens...
import json import datetime import threading from base_plugin import * import base_plugin def send_message(recipient, message, mtype='chat'): ''' Send a message to recipient. :param recipient: The To field of your message. :param message: the message string to send. :para mtype: The message type to send, su...
def cheese_and_crackers(cheese_count,boxes_of_crackers): print "You have %d cheeses!" % cheese_count print "You have %d boxes of crackers!" % boxes_of_crackers print "Man that's enough for a party!" print "Get a blanket.\n" print "We can just give the function numbers directly:" cheese_and_crackers(20,3...
from babymaker import BabyMaker, EnumType, IntType, StringType, UUIDType, FieldType, DatetimeType, FloatType, EmbedType import unittest import string import sys from datetime import datetime, timedelta class TestMakeSomeBabies(unittest.TestCase): def test_make_one(self): fields = { "id": UUIDTyp...
import numpy as np class lemketableau: def __init__(self,M,q,maxIter = 100): n = len(q) self.T = np.hstack((np.eye(n),-M,-np.ones((n,1)),q.reshape((n,1)))) self.n = n self.wPos = np.arange(n) self.zPos = np.arange(n,2*n) self.W = 0 self.Z = 1 self.Y = ...
import xml.etree.ElementTree as ET import datetime import sys import openpyxl import re import dateutil def main(): print 'Number of arguments:', len(sys.argv), 'arguments.' #DEBUG print 'Argument List:', str(sys.argv) #DEBUG Payrate = raw_input("Enter your pay rate: ") #DEBUG sNumber = raw_input("Enter 900#: ") #D...
from PySide import QtCore, QtGui class MakinFrame(QtGui.QFrame): mousegeser = QtCore.Signal(int,int) def __init__(self,parent=None): super(MakinFrame,self).__init__(parent) self.setMouseTracking(True) def setMouseTracking(self, flag): def recursive_set(parent): for child in parent.findChildren(QtCore.QObjec...
from graphics_module.objects import * import numpy as np def make_pixels_array_basic(amount): return np.full(10,Pixel(), dtype=np.object) def make_pixels_array_config_based(config): if config.colorscheme == "b&w": c = Color() elif config.colorscheme == "light": c = Color(r=245,g=235,b=234,a=...
DOCUMENTATION = ''' --- module: zfs_permissions short_description: Manage zfs administrative permissions description: - Manages ZFS file system administrative permissions on Solaris and FreeBSD. See zfs(1M) for more information about the properties. version_added: "1.10" options: name: description: - File...
__author__ = 'olga' import numpy as np from prettyplotlib.colors import blue_red, blues_r, reds from prettyplotlib.utils import remove_chartjunk, maybe_get_fig_ax def pcolormesh(*args, **kwargs): """ Use for large datasets Non-traditional `pcolormesh` kwargs are: - xticklabels, which will put x tick lab...
""" To use this, create a settings.py file and make these variables: TOKEN=<oath token for github> ORG=<your org in github> DEST=<Path to download to> """ from github import Github from subprocess import call import os from settings import TOKEN, ORG, DEST def download(): """Quick and Dirty Download all repos function...
from distutils.core import setup, Extension setup( name = 'iMX233_GPIO', version = '0.1.0', author = 'Stefan Mavrodiev', author_email = 'support@olimex.com', url = 'https://www.olimex.com/', license = 'MIT', descripti...
from flask import Blueprint from flask import current_app from flask import request from flask import jsonify from flask import abort from flask import render_template from flask import redirect from flask import url_for from flask import flash from werkzeug.exceptions import NotFound from printus.web.models import Rep...
""" commswave ========= Takes device communications up and down according to a timefunction. Comms will be working whenever the timefunction returns non-zero. Configurable parameters:: { "timefunction" : A timefunction definition "threshold" : (optional) Comms will only work when the timefunction is...
from setuptools import setup, find_packages with open('requirements.txt') as reqs: inst_reqs = reqs.read().split('\n') setup( name='autobot', version='0.1.0', packages=find_packages(), author='Mikael Knutsson', author_email='mikael.knutsson@gmail.com', description='A bot framework made accor...
"""File related wrapper functions to streamline common use cases""" import manage as manage from manage import find_file, find_file_re, list_dir import operation as operation from operation import hash_file, read_file, slice_file, write_file
"""test_03b_subcmd_primer3.py Test primer3 subcommand for pdp script. These tests require primer3 v2+. This test suite is intended to be run from the repository root using: pytest -v (c) The James Hutton Institute 2017-2019 Author: Leighton Pritchard Contact: leighton.pritchard@hutton.ac.uk Leighton Pritchard, Informat...
import os def run(name='test1.py'): filename = os.getcwd() + name exec(compile(open(filename).read(), filename, 'exec'))
import base64 import copy import sys import time from webkitpy.layout_tests.port import DeviceFailure, Driver, DriverOutput, Port from webkitpy.layout_tests.port.base import VirtualTestSuite from webkitpy.layout_tests.models.test_configuration import TestConfiguration from webkitpy.layout_tests.models import test_run_r...
from jupyter_workflow.data import get_fremont_data import pandas as pd def test_fremont_data(): data = get_fremont_data() assert all(data.columns == ['West','East','Total']) assert isinstance(data.index,pd.DatetimeIndex)
def fail(): for t in [TypeA, TypeB]: x = TypeA() run_test(x) def OK1(seq): for _ in seq: do_something() print("Hi") def OK2(seq): i = 3 for x in seq: i += 1 return i def OK3(seq): for thing in seq: return "Not empty" return "empty" def OK4(n): ...
from __future__ import division import random import matrix from tile import Tile class Island(object): def __init__(self, width=300, height=300): self.radius = None self.shore_noise = None self.rect_shore = None self.shore_lines = None self.peak = None self.spokes = ...
from __future__ import absolute_import, unicode_literals from builtins import str import os import pytest import io from glob import glob from psd_tools import PSDImage from psd2svg import psd2svg FIXTURES = [ p for p in glob( os.path.join(os.path.dirname(__file__), 'fixtures', '*.psd')) ] @pytest.mark....
from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.core.poll...
import unittest from pyparsing import ParseException from tests.utils.grammar import get_record_grammar """ CWR Non-Roman Alphabet Agreement Party Name grammar tests. The following cases are tested: """ __author__ = 'Bernardo Martínez Garrido' __license__ = 'MIT' __status__ = 'Development' class TestNPAGrammar(unittest...
from collections import defaultdict import numpy class ThompsonAgent: def __init__(self, seed=None): self._succeeds = defaultdict(int) self._fails = defaultdict(int) self._np_random = numpy.random.RandomState(seed) def choose(self, arms, features=None): return max(arms, key=lambd...
"""Sensitive variant calling using VarDict. Defaults to using the faster, equally sensitive Java port: https://github.com/AstraZeneca-NGS/VarDictJava if 'vardict' or 'vardict-java' is specified in the configuration. To use the VarDict perl version: https://github.com/AstraZeneca-NGS/VarDict specify 'vardict-perl'. """ ...
"""add account id Revision ID: 3734300868bc Revises: 3772e5bcb34d Create Date: 2013-09-30 18:07:21.729288 """ revision = '3734300868bc' down_revision = '3772e5bcb34d' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column('account_profile', sa.Column('account_id', sa.Integer(11))) pass def ...
pkg_dnf = { 'collectd': {}, 'collectd-chrony': {}, 'collectd-curl': {}, 'collectd-curl_json': {}, 'collectd-curl_xml': {}, 'collectd-netlink': {}, 'rrdtool': {}, } if node.os == 'fedora' and node.os_version >= (26): pkg_dnf['collectd-disk'] = {} svc_systemd = { 'collectd': { ...
import tkinter as tk from time import sleep from playsound import playsound import config import fasttick from helpmessage import fasttick_help_message import misc from tickerwindow import TickerWindow class GUIfasttick(TickerWindow): def __init__(self, app): super().__init__(app) misc.delete_ancien...
import os import sys root_path = os.path.abspath("../../../") if root_path not in sys.path: sys.path.append(root_path) import numpy as np import tensorflow as tf from _Dist.NeuralNetworks.Base import Generator4d from _Dist.NeuralNetworks.h_RNN.RNN import Basic3d from _Dist.NeuralNetworks.NNUtil import Activations c...
import re import functools from slackbot.bot import respond_to from app.modules.shogi_input import ShogiInput, UserDifferentException, KomaCannotMoveException from app.modules.shogi_output import ShogiOutput from app.slack_utils.user import User from app.helper import channel_info, should_exist_shogi @respond_to('start...
import argparse import collections import os import re import torch from fairseq.file_io import PathManager def average_checkpoints(inputs): """Loads checkpoints from inputs and returns a model with averaged weights. Args: inputs: An iterable of string paths of checkpoints to load from. Returns: ...
from pygame.locals import * import pygame, string class ConfigError(KeyError): pass class Config: """ A utility for configuration """ def __init__(self, options, *look_for): assertions = [] for key in look_for: if key[0] in options.keys(): exec('self.'+key[0]+' = options[\''+key[0]+'...
from setuptools import setup setup( name = "mobileclick", description = "mobileclick provides baseline methods and utility scripts for the NTCIR-12 MobileClick-2 task", author = "Makoto P. Kato", author_email = "kato@dl.kuis.kyoto-u.ac.jp", license = "MIT License", url = ...
''' charlie.py ---class for controlling charlieplexed SparkFun 8x7 LED Array with the Raspberry Pi Relies upon RPi.GPIO written by Ben Croston The MIT License (MIT) Copyright (c) 2016 Amanda Cole Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation f...
import os import bisect import logging class RobotSignatures(object): """A repository of robot signatures. The repository is used for detecting web robots by matching their 'User-Agent' HTTP header. """ def __init__(self): """Constructor.""" self.m_robots = [] self.m_files = ...
from django.conf.urls import patterns, url from rai00base.raccordement import getModeleRaccordement, createRaccordement, deleteRaccordement, listRaccordement urlpatterns = patterns('', url('getModeleRaccordement/$', getModeleRaccordement), url('createRaccordement/$', createRaccordement), url('deleteRaccorde...
value_None = object() class FactoryException(Exception): pass class Factory: class Item: def __init__(self, factory, i): self.factory = factory self.i = i @property def value(self): return self.factory.value(self.i) @value.setter def va...
import pandas as pd from pandas import DataFrame df = pd.read_csv('sp500_ohlc.csv', index_col = 'Date', parse_dates=True) df['H-L'] = df.High - df.Low print df.head() df['100MA'] = pd.rolling_mean(df['Close'], 100) print df[200:210] df['Difference'] = df['Close'].diff() print df.head()
import numpy as np from nlpaug.augmenter.spectrogram import SpectrogramAugmenter from nlpaug.util import Action import nlpaug.model.spectrogram as nms class LoudnessAug(SpectrogramAugmenter): """ Augmenter that change loudness on mel spectrogram by random values. :param tuple zone: Default value is (0.2, 0....
""" HLS and Color Threshold ----------------------- You've now seen that various color thresholds can be applied to find the lane lines in images. Here we'll explore this a bit further and look at a couple examples to see why a color space like HLS can be more robust. """ import numpy as np import cv2 import matplotlib...
from __future__ import print_function from __future__ import unicode_literals import os import sys import time import argparse from datetime import datetime, timedelta, tzinfo from textwrap import dedent import json from random import choice import webbrowser import itertools import logging import threading from thread...
import cv2 import numpy as np import sys def reshapeImg(img, l, w, p): # reshape image to (l, w) and add/remove pixels as needed while len(img) % p != 0: img = np.append(img, 255) olds = img.size / p news = l*w if news < olds: img = img[:p*news] elif news > olds: img = np.concatenate( (img, np.zeros(p*(news...
import numpy import pandas import statsmodels.api as sm ''' In this exercise, we will perform some rudimentary practices similar to those of an actual data scientist. Part of a data scientist's job is to use her or his intuition and insight to write algorithms and heuristics. A data scientist also c...
""" Translator module that uses the Google Translate API. Adapted from Terry Yin's google-translate-python. Language detection added by Steven Loria. """ from __future__ import absolute_import import json import re import codecs from textblob.compat import PY2, request, urlencode from textblob.exceptions import Transla...
''' These classes specify the attributes that a view object can have when editing views ''' __author__ = 'William Emfinger' __copyright__ = 'Copyright 2016, ROSMOD' __credits__ = ['William Emfinger', 'Pranav Srinivas Kumar'] __license__ = 'GPL' __version__ = '0.4' __maintainer__ = 'William Emfinger' __email__ = 'emfing...
import vk import sys import json word = sys.argv[1] txt_file = open(word + '.txt', "w") html_file = open(word + '.html', "w") vkapi = vk.API(access_token='copy_token_here') result = vkapi.groups.search(q = word, offset = 0, count = 100) json_tree = result['items'] for item in json_tree: link = 'http://vk.com/club' ...