content
stringlengths
0
894k
type
stringclasses
2 values
#!/usr/bin/env python3 # If imports fail, try installing scispacy and the model: # pip3 install scispacy # pip3 install https://s3-us-west-2.amazonaws.com/ai2-s2-scispacy/releases/v0.2.0/en_core_sci_md-0.2.0.tar.gz import sys import os import re import scispacy import spacy from sspostproc import refine_split DOC...
python
# -*- coding: utf-8 -*- """ Created on Mon Dec 14 18:17:10 2020 @author: Manuel Camargo """ import tests.read_log as rl import tests.analyzer_test as ats import tests.timeit_tests as tit import tests.timeline_split_tests as tst if __name__ == "__main__": ats.timeseries_test() ats.log_test() tit.execute_te...
python
#!/usr/bin/env python # -*- coding=utf-8 -*- ########################################################################### # Copyright (C) 2013-2017 by Caspar. All rights reserved. # File Name: fzcmeans.py # Author: Shankai Yan # E-mail: sk.yan@my.cityu.edu.hk # Created Time: 2017-01-23 12:52:12 #########################...
python
# Faça um programa que leia o nome completo de uma pessoa, mostrando em seguida o primeiro e o último nome separadamente. n = str(input('\nType your full name:\n>>> ')).strip().title() n1 = n.split() print('\nYour first name {} and your last name {}.\n'.format(n1[0], n1[-1]))
python
from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as ec from selenium.webdriver.support.ui import WebDriverWait from page_objects.login_page import LoginPage from tools.webdriver_factory import WebdriverFactory class TestLogin: def setup_method(self, method):...
python
class Config(object): DEBUG = False SQLALCHEMY_DATABASE_URI = '' SECRET_KEY = 'dbbc933946e04a729b17c0625b72e3db' MAIL_SERVER = 'smtp.gmail.com' MAIL_USERNAME = '' MAIL_PASSWORD = '' MAIL_PORT = 465 MAIL_USE_SSL = True MAIL_USE_TLS = False MAIL_SUPPRESS_SEND = False SQLALCHEM...
python
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Nicole Thomas <nicole@saltstack.com>` ''' # Import Python libs from __future__ import absolute_import # Import Salt Testing libs from salttesting import TestCase, skipIf from salttesting.helpers import ensure_in_syspath from salttesting.mock import ( NO_MOCK, ...
python
import os from distutils.version import StrictVersion from pathlib import Path from warnings import warn from ..utils.translations import trans try: from qtpy import API_NAME, QtCore except Exception as e: if 'No Qt bindings could be found' in str(e): raise type(e)( trans._( ...
python
__version__ = '0.1.1' from .tools import underline2hump, hump2underline, json_hump2underline
python
import pywikibot import redis from api.translation_v2.core import Translation from page_lister import get_pages_from_category from redis_wikicache import RedisPage, RedisSite if __name__ == '__main__': # print(translate_using_postgrest_json_dictionary('mat', '[[mine|Mine]]', 'en', 'mg')) # print(translate_usi...
python
keysDict = { 'YawLeftButton': 0x1E, # Key A 'YawRightButton': 0x20, # Key D 'PitchUpButton': 0xB5, # NUM / 'PitchDownButton': 0x37, # NUM * 'RollLeftButton': 0x4E, # NUM + 'RollRightButton': 0x9C, # NUM ENTER 'EnableFSD': 0x24, # Key J 'EngineBoost': 0x0F, # Key Tab 'Speed100': 0x47,...
python
import torch from .stft import STFT from librosa.filters import mel as librosa_mel_fn from .functional import dynamic_range_compression, dynamic_range_decompression import numpy as np class MelSTFT(torch.nn.Module): def __init__(self, filter_length=1024, hop_length=16 * 8, win_length=1024, n_mel_...
python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Created on 26/04/2016 Versão 1.0 @author: Ricieri (ELP) Python 3.4.4 """ """ Reviewed on 15/10/2020 Versão 1.0 rev.A - rounded printing values to 3 decimal places and displays '°C' instead of 'ºC'. @author: Marcelo (ELP) Python 3.8.6 """ """ Reviewed on 06/05/2021 Versão 1...
python
DEBUG = False BCRYPT_LEVEL = 12 # Configuration for the Flask-Bcrypt extension from settings.local_settings import *
python
import requests, json def activities(activity): # Get Activity ID switch = { 1: "755600276941176913", 2: "755827207812677713", 3: "773336526917861400", 4: "814288819477020702" } return switch.get(activity, "755600276941176913") print("--------------------------------") # He...
python
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # ...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Feb 14 09:31:37 2020 @author: natnem """ import math def countingSort(array, exp): n = len(array) out = [0]*n count = [0]*10 for i in range(n): index = (array[i]//exp) % 10 count[index] += 1 for i in range(1,10): ...
python
from django.shortcuts import redirect from rest_framework import permissions, viewsets from rest_framework.decorators import api_view, permission_classes from . import models from . import serializers from ..scraps.models import Scrap class ScrapBookViewSet(viewsets.ModelViewSet): queryset = models.ScrapBook.obj...
python
import numpy as np import os.path from keras.models import load_model, Model from keras.callbacks import ModelCheckpoint, EarlyStopping, CSVLogger from python_research.experiments.utils import ( TimeHistory ) from python_research.experiments.multiple_feature_learning.builders.keras_builders import ( bui...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from collections import Iterable, Iterator def g(): yield 1 yield 2 yield 3 print('Iterable? [1, 2, 3]:', isinstance([1, 2, 3], Iterable)) print('Iterable? \'abc\':', isinstance('abc', Iterable)) print('Iterable? 123:', isinstance(123, Iterable)) print('It...
python
from tkinter import ttk, Frame, Label, Entry, Button, LEFT, font from models.repositories.credentials_repository import CredentialsDatabase from settings import CREDENTIALS_DB, SALT import sys sys.path.append("..") from providers.password_encrypt_provider import PasswordEncryptProvider class PasswordPage(Frame): ...
python
import pygame from pygame.locals import * import random import sys from settings import * pygame.font.init() pygame.init() class Pad(pygame.sprite.Sprite): def __init__(self): super(Pad, self).__init__() self.width, self.height = 95,95 self.image = pygame.Surface((self.wid...
python
""" # Script: polyEvaluateTest.py # # Description: # Unit test for the polyEvaluate command. # ############################################################################## """ import maya.cmds as cmds import unittest class PolyEvalutateTest(unittest.TestCase): def testPolyEvaluate(self)...
python
#---------------------------------------------------------------------- # LinMoTube # by Jake Day # v1.2 # Basic GUI for YouTube on Linux Mobile #---------------------------------------------------------------------- import ctypes, os, requests, io, sys, subprocess, gi, json, threading from urllib.parse import urlpars...
python
""" @author: maffettone SVM models for classification and regression """ from sklearn.svm import SVC from sklearn.svm import SVR def gen_classifier(params): clf = SVC(probability=False, C=params['C'], gamma=params['gamma'] ) return clf def gen_regressor(params): ...
python
from .data_archive import * # noqa from .limit_monitor import * # noqa from .openmct import * # noqa
python
#!/usr/bin/python # -*- coding:utf-8 -*- # 遍历根资产的子域名 import sys import requests import threading import time,json,re from bs4 import BeautifulSoup class subdomain(object): def __init__(self,url): self.url = url self.set_dns = set() self.set_ip138 = set() self.set_crt = set() ...
python
from pkwscraper.lib.controller import Controller """ This example shows the invalid votes percentage in communes (gminy). It also shows how much of these votes where invalid because of putting voting mark next to 2 or more candidates. This is considered to be main indication of probability of elections falsification....
python
# coding=utf-8 # Copyright 2018 The Tensor2Tensor 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...
python
import os class GeneralConfig: # General validation_split = 0.2 seed = 42 verbose = True architecture_type = "PretrainedResNet50" # Data image extension image_extension = ".jpg" pip_packages = [ "tensorflow==2.2", "numpy", "pandas", "matplotlib", ...
python
from .GeometricRestriction import GeometricRestriction class SizingClusterAreas(GeometricRestriction): """The SizingClusterAreas object defines a sizing cluster areas geometric restriction. The SizingClusterAreas object is derived from the GeometricRestriction object. Notes ----- This object can...
python
import logging import logging.handlers from traceback import format_stack from brotab.inout import in_temp_dir def _init_logger(tag, filename: str): FORMAT = '%(asctime)-15s %(process)-5d %(levelname)-8s %(filename)s:%(lineno)d:%(funcName)s %(message)s' MAX_LOG_SIZE = 50 * 1024 * 1024 LOG_BACKUP_COUNT = ...
python
import cv2 import numpy as np from numpy.linalg import norm import os import json SZ = 20 PROVINCE_START = 1000 MAX_WIDTH = 2000 def point_limit(point): if point[0] < 0: point[0] = 0 if point[1] < 0: point[1] = 0 def deskew(img): m = cv2.moments(img) if abs(m['mu02']) < 1e-2: ...
python
""" Test method for Sub opcode """ from easier68k.simulator.m68k import M68K from easier68k.core.opcodes.cmpi import Cmpi from easier68k.core.models.assembly_parameter import AssemblyParameter from easier68k.core.enum.ea_mode import EAMode from easier68k.core.enum.register import Register from easier68k.core.enum.op_...
python
from typing import Mapping from collections import OrderedDict import copy from torch.utils.data import DataLoader from catalyst.core.callback import Callback, CallbackOrder from catalyst.core.runner import IRunner class PeriodicLoaderCallback(Callback): """Callback for runing loaders with specified period. ...
python
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler from google.appengine.runtime import apiproxy_errors from google.appengine.ext import ndb from models.rawmail import RawMail from models.post import Post from models.settings import Settings from models.userimage import UserImage from models.slug ...
python
"""Multiple Correspondence Analysis (MCA)""" import numpy as np import pandas as pd from sklearn import utils from . import ca from . import one_hot class MCA(ca.CA): def fit(self, X, y=None): utils.check_array(X, dtype=[str, np.number]) if not isinstance(X, pd.DataFrame): X = pd.D...
python
listOfWords = ['wordOne', 'wordTwo', 'wordThree', 'wordFour', 'wordFive'] listOfInts = [] for i in listOfWords: listOfInts.append(len(i)) print("List of words:" + str(listOfWords)) print("List of wordlength:" + str(listOfInts))
python
import asyncio import logging import os import random from aiohttp import WSServerHandshakeError, ClientConnectorError from cryptology import ClientWriterStub, Keys, run_client, exceptions from datetime import datetime from decimal import Context, ROUND_DOWN, Decimal from pathlib import Path from typing import Optiona...
python
#!/usr/bin/python #coding:utf-8 from bs4 import BeautifulSoup import requests url='http://www.moko.cc/mtb.html' r=requests.get(url, verify=False) content=r.content soup=BeautifulSoup(content,'lxml') modlist=soup.find_all('div','sub_show') link=[] for i in modlist: if i==modlist[-1] or i==modlist[0]: continu...
python
import pytest # run tests only if snappy is available snappy = pytest.importorskip("snappy") def test_snappy(): import snappy from snappy import (ProductIO, ProductUtils, ProgressMonitor, jpy)
python
from collections import Counter import nltk from nltk import * import numpy as np import xml.etree.ElementTree as ET import tmx trigram_measures = nltk.collocations.TrigramAssocMeasures() bigram_measures = nltk.collocations.BigramAssocMeasures() class CorpusUtil(object): __slots__ = 'tokenFrequencies', 'nGr...
python
from aiogram import types from aiogram.dispatcher import FSMContext from aiogram.dispatcher.filters import Text from misc import bot, dp, admin_ids from certificate import Certificate, get_all_certificates, set_all_certificates import logging from .menu import menu_keyboard from .states import AdminState, admin_keyboar...
python
n1 = float(input("Digite um número: ")) print("O sucessor de {} é {} e o seu antecessor é de {}" .format(n1,n1+1,n1-1))
python
# vim: tabstop=4 shiftwidth=4 softtabstop=4 """ [VRM DRIVER] VRM CLIENT. """ from cinder.openstack.common import log as logging from cinder.openstack.common.gettextutils import _ from cinder.volume.drivers.huawei.vrm.base_proxy import BaseProxy TASK_WAITING = 'waiting' TASK_RUNNING = 'running' TASK_SUCCESS = 'suc...
python
from collections import namedtuple from csv import QUOTE_ALL from unittest import TestCase import pytest from bonobo import CsvReader, CsvWriter from bonobo.constants import EMPTY from bonobo.util.testing import ( BufferingNodeExecutionContext, ConfigurableNodeTest, FilesystemTester, ReaderTest, WriterTest ) csv...
python
from textwrap import dedent import re from ansi2html import Ansi2HTMLConverter import mistune from jinja2 import Markup import pygments import pygments.lexers from pygments.lexer import RegexLexer, bygroups from pygments.token import Generic, Text, Comment import pygments.formatters.html ansi_convertor = Ansi2HTMLCo...
python
class Cell: pass class Fish(Cell): name = 'F' @staticmethod def update(neighbours): cnt = neighbours.count(Fish.name) if cnt == 2 or cnt == 3: return Fish() else: return Void() class Crayfish(Cell): name = 'C' @staticmethod def update(nei...
python
# flake8: noqa from __future__ import unicode_literals import sys import django from django.conf import settings # removed get_queryset <> get_query_set see, #29 #from django.db.models import Manager ## Monkey patch: # #try: # Manager.get_query_set = Manager.get_queryset #except AttributeError: # Manager.get_q...
python
name = 'lib_csv' title = 'lib_csv: functions to read and write csv files' version = '0.1.0' url = 'https://github.com/bitranox/lib_csv' author = 'Robert Nowotny' author_email = 'rnowotny1966@gmail.com' shell_command = 'lib_csv' def print_version() -> None: print('version: 0.1.0') def print_info() -> None: p...
python
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-09-12 19:12 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('logger', '0040_auto_20170912_1504'), ] operations = [ migrations.AlterField...
python
from fabric.api import run, quiet from braid import succeeds, cacheInEnvironment @cacheInEnvironment def distroName(): """ Get the name of the distro. """ with quiet(): lsb = run('/usr/bin/lsb_release --id --short', warn_only=True) if lsb.succeeded: return lsb.lower() ...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_acp-calendar ------------ Tests for `acp-calendar` models module. """ import datetime import os from unittest import mock from django.test import TestCase from django.test import override_settings from acp_calendar.initial_data import get_holiday_type_list, g...
python
load("//:plugin.bzl", "ProtoPluginInfo") ProtoCompileInfo = provider(fields = { "label": "label object", "plugins": "ProtoPluginInfo object", "descriptor": "descriptor set file", "outputs": "generated protoc outputs", "files": "final generated files", "protos": "generated protos (copies)", ...
python
import concurrent.futures import urllib.request import time URLS = ['http://www.foxnews.com/', 'http://www.cnn.com/', 'http://europe.wsj.com/', 'http://www.bbc.co.uk/', 'http://some-made-up-domain.com/', 'http://www.nytimes.com', 'http://www.facebook.com', 'http:...
python
#!/usr/local/uvcdat/bin/python # Functions to convert between representations of energy flux and # water flux (precipitation and evoporation) variables. # TODO: perhaps move the physical constants used here to atmconst.py. # These are: # - latent heat of vaporization (water) # - density (water...
python
from random import choice #============================================================================== """ Split a String in Balanced Strings Balanced strings are those that have an equal quantity of 'L' and 'R' characters. Given a balanced string s, split it in the maximum amount of balanced strings. Return the ...
python
# -*- coding:utf-8 -*- # author: donttouchkeyboard@gmail.com # software: PyCharm import openpyxl from style.default import ExcelFontStyle from core.base import TableCommon if __name__ == '__main__': """ 二级表头示例 """ wb = openpyxl.Workbook() ws = wb.active wb = TableCommon.excel_write_commo...
python
#!/usr/bin/env python # coding=utf8 ''' Created on Jul 7, 2012 @author: gf ''' import os import Util import ethtool def GetInfoString(): active_interfaces = ethtool.get_active_devices() all_interfaces = GetInterfaceList() for i in active_interfaces: if ethtool.get_flags('%s' % i) & ethtool.IFF_PO...
python
''' Created on Jan 24, 2013 @author: mdickson ''' import inworldz.maestro.uuid as genuuid import inworldz.util.user as user import inworldz.util.estate as estate import inworldz.util.properties as DefaultProperties import inworldz.maestro.MaestroStore as store from inworldz.maestro.ServiceBase import ServiceBase fro...
python
import math import textClasses def title_word_feature(title, processed_text): """ List of values from 0 to 1 rating the number title words that appear in the sentence""" title_word_feature_values = [] # Calculate the number of common words with the title that the sentence has word_intersection = [s...
python
""" """ import os import numpy as np import pandas as pd import xarray as xr from osgeo import gdal from src.utils.constants import ( REGIONS, LANDCOVER_MAP, LANDCOVER_PERIODS, LANDCOVER_PADDING ) if __name__ == "__main__": # Project's root os.chdir("../..") for region in REGIONS: ...
python
import fnmatch from functools import wraps def asgi_cors_decorator( allow_all=False, hosts=None, host_wildcards=None, callback=None ): hosts = hosts or [] host_wildcards = host_wildcards or [] # We need hosts and host_wildcards to be b"" hosts = set(h.encode("utf8") if isinstance(h, str) else h f...
python
from __future__ import division, print_function import numpy as np from scipy.constants import pi from numpy.fft import fftshift from scipy.fftpack import fft, ifft try: import accelerate jit = accelerate.numba.jit autojit = accelerate.numba.autojit complex128 = accelerate.numba.complex128 float64...
python
class Solution: def countConsistentStrings(self, allowed: str, words: List[str]) -> int: c = 0 allowed = set(allowed) for word in words: # word = set(word) for letter in word: if letter not in allowed: break else: ...
python
#!/usr/bin/python import sys, ctypes """ rdi contains argc rsi contains argv (in reverse) - Note rdi decrements """ def echo_args(): # See function 'echo_args' in echo.asm global rdi, rsi, rdx, stack stack.append(rdi) # "push" stack.append(rsi) # "push" ## Stack alignment?? rsp = index or ...
python
from abc import ABC, abstractmethod from zpy.api.reponse import Builder from zpy.api.stages import Decrypt from zpy.logger import g_log from zpy.api.errors import ErrorBuilder from flask import Flask from typing import Any from flask.wrappers import Request, Response from zpy.utils.Encryptor import AESEncryptor import ...
python
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch from maskrcnn_benchmark.modeling.box_coder import BoxCoder from maskrcnn_benchmark.structures.bounding_box import BoxList from maskrcnn_benchmark.structures.boxlist_ops import cat_boxlist from maskrcnn_benchmark.structures.boxlist_ops...
python
from __future__ import print_function import argparse import shutil import torch import torchvision import random import os import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms from torch.optim.lr_scheduler import StepLR from torch.utils.tensorbo...
python
""" These test cover Google searches """ import pytest from pages.result import GoogleResultPage from pages.search import GoogleSearchPage @pytest.mark.parametrize('phrase', ['nintendo', 'xbox', 'steam']) def test_basic_google_search(browser, phrase): search_page = GoogleSearchPage(browser) result_page = Goog...
python
from modern_greek_accentuation.accentuation import is_accented, where_is_accent, put_accent, count_syllables,\ put_accent_on_the_antepenultimate, put_accent_on_the_penultimate, remove_all_diacritics, put_accent_on_the_ultimate from modern_greek_accentuation.syllabify import modern_greek_syllabify from modern_gree...
python
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import os import warnings from builtins import str from typing import Any, Dict, Optional, Text from rasa.nlu.extractors.entity_synonyms import EntitySynonymMapper cl...
python
import numpy as np import torch import random from skimage import io, transform import torch.nn.functional as F from torchvision import transforms torch.manual_seed(17) random.seed(42) class Resize(object): """Rescale the image in a sample to a given size. Args: output_size (tuple or int): Desired ou...
python
import argparse # import paraview modules. from paraview.web import pv_wslink from paraview.web import protocols as pv_protocols from paraview import simple from wslink import server from enlil import EnlilDataset # ============================================================================= # Create custom PVServe...
python
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('all/', views.BlogList.as_view(), name='blog-list'), path('bloggers/',views.BlogAuthorList.as_view(), name='blogauthor-list'), path('bloggers/<int:pk>',views.BlogAuthorDetail.as_view(),name='bloga...
python
def main(): #fh, abs_path = mkstemp() antImages = 4000 first = 4 second = 4 newFileName = '%s_%s_bench_door_%s'%(first, second, antImages) with open(newFileName + '_local.txt','w') as new_file: with open('4_4_bench_door_4000_final.txt') as old_file: lines = old_file.readlin...
python
# Generated from Java9.g4 by ANTLR 4.8 from antlr4 import * if __name__ is not None and "." in __name__: from .Java9Parser import Java9Parser else: from Java9Parser import Java9Parser # This class defines a complete listener for a parse tree produced by Java9Parser. class Java9Listener(ParseTreeListener): ...
python
import argparse import pysam from ragtag_utilities.utilities import reverse_complement """ Like bedtools getfasta, but use the gff ID attribute as the FASTA header and always force strandedness. """ def main(): parser = argparse.ArgumentParser(description="Get fasta sequences from a GFF file") parser.add_...
python
"""Runs inference on clips much longer than 1s, by running a sliding window and aggregating predictions.""" from argparse import ArgumentParser from config_parser import get_config import torch import numpy as np import librosa from utils.misc import get_model from tqdm import tqdm import os import glob import json ...
python
import flask import json import inspect from .handle import Resource from .route import RouteFactory from .utils import Logger from .error import RequestError from .db import TinyBDDatabase class App(object): def __init__(self, base_route, db=None): self.base_route = base_route self.debug = True ...
python
# Copyright 2016 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
python
from django.test import TestCase from base.models import Comic, Character, Creator, Story from rest_framework.test import APIClient from rest_framework import status from django.urls import reverse class ComicTestCase(TestCase): """Test suite for the api views.""" def setUp(self): """Define the test ...
python
from collections import OrderedDict def contains_duplicate_extra_space(nums): seen = {} for i, val in enumerate(nums): if val in seen: return True else: seen[val] = i return False def contains_duplicate_2(nums, k): seen = dict() for i, val in enumerate(...
python
import math from kivy.properties import ObjectProperty, Clock, NumericProperty from cobiv.libs.magnet import Magnet from cobiv.modules.views.browser.eolitem import EOLItem class DraggableItem(Magnet): thumb = ObjectProperty(None, allownone=True) container = ObjectProperty(None) cell_size = NumericPropert...
python
"""Submodule that handles the generation of periodic table information.""" from __future__ import annotations import typing from .atomic_masses import ATOMIC_MASSES def atomic_symbols_to_mass(atoms: typing.Sequence[str]) -> list[float]: """Converts atomic symbols to their atomic masses in amu. Parameters ...
python
# # Copyright (C) 2009 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and ...
python
# -*- coding: utf-8 -*- """ Created on Wed Jul 27 10:55:34 2016 The plain vanila implementation of Recurrent Neural Network @author: yaric """ import time import datetime from random import uniform import numpy as np import scipy.io as sio class RNN(object): def __init__(self, n_features, n_outputs, n_neur...
python
from baiji.serialization import json from baiji.serialization.json import JSONDecoder class BlmathJSONDecoder(JSONDecoder): def __init__(self): super(BlmathJSONDecoder, self).__init__() self.register(self.decode_value) def decode_value(self, dct): from blmath.value import Value ...
python
class Solution: def nthUglyNumber(self, n): """ :type n: int :rtype: int """ if n < 1: return 0 ugly = [0]*n ugly[0] = 1 i2 = i3 = i5 = 0 nm_2, nm_3, nm_5 = 2, 3, 5 for i in range(1, n): ugly[i] = min(nm_2, nm_3,...
python
def slices(series, length): if length < 1 or length > len(series): raise ValueError("length too high") i = 0 result = [] while i+length <= len(series): result.append(series[i:i+length]) i+=1 return result
python
name = input("What is your name?\n") print ("Hello", name)
python
from keras.datasets import mnist import os from pandas import DataFrame from PIL import Image from autokeras.utils import ensure_dir ensure_dir('mnist/train') ensure_dir('mnist/test') (x_train, y_train), (x_test, y_test) = mnist.load_data() # x_train = x_train.reshape(x_train.shape + (1,)) # x_test = x_test.reshape(...
python
from django.http import HttpResponse # from django.shortcuts import render # Create your views here. def home(request): return HttpResponse('Olá Django')
python
import os import subprocess if os.environ.get("HEXA_FEATURE_FLAG_S3FS", "false") == "true": for bucket_name in os.environ.get("AWS_S3_BUCKET_NAMES", "").split(","): path_to_umount = os.path.join(f"/home/jovyan/s3-{bucket_name}") subprocess.run( [ "umount", ...
python
"""Returns compiled regex from regular expression.""" import re import pytest from mklists.returns import compile_regex # pylint: disable=anomalous-backslash-in-string # These are just tests... def test_compile_regex(): """Returns compiled regex from simple string.""" regex = "NOW" assert isinstance(co...
python
from __future__ import print_function, division import scipy #Import Require Libraries import matplotlib.pyplot as plt import cv2 import pandas from keras.applications.vgg16 import VGG16 from keras.models import Sequential from keras.layers import Dense,Dropout from keras.layers import LeakyReLU from kera...
python
# Copyright 2020 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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
python
# Copyright (c) 2019, Digi International, Inc. # # 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, pu...
python
#write a function to convert decimal number to binary, octal and Heaxdecimal equivalent n = input("Enter the Decimal") print("BINARY EQUIVALENT",bin(n)) print("OCTAL EQUIVALENT",oct(n)) print("HEXADECIMAL EQUIVALENT",hex(n))
python
from microbit import * import time while True: temp_c = pin1.read_analog() / 10.23 - 20 temp_f = int(temp_c * 9 / 5 + 32) display.scroll(temp_f) time.sleep(0.5)
python