content
stringlengths
5
1.05M
"""Using a class as a decorator demo. Count the number of times a function is called. """ class CallCount: def __init__(self, function): self.f = function self.count = 0 def __call__(self, *args, **kwargs): self.count = 1 return self.f(*args, **kwargs) @property de...
# Copyright (c) Open-MMLab. All rights reserved. from mmcv.runner.hooks.hook import HOOKS, Hook @HOOKS.register_module() class AlternateTrainingHook(Hook): # def before_train_iter(self, runner): def before_train_epoch(self, runner): runner.model.module.neck.epoch_num = runner._epoch # if runner...
import os import logging from flask import Flask from slack import WebClient from slackeventsapi import SlackEventAdapter # Initialize a Flask app to host the events adapter app = Flask(__name__) # Create an events adapter and register it to an endpoint in the slack app for event injestion. slack_events_adapter = Slac...
import os import sys import glob import argparse import numpy as np from PIL import Image from Utility import * from keras.applications.vgg16 import VGG16, preprocess_input from keras.models import Model, load_model from keras.layers import Dense, GlobalAveragePooling2D, BatchNormalization from keras.preprocessing.im...
from __future__ import absolute_import from .base import Model from .base import DifferentiableModel class ModelWrapper(Model): """Base class for models that wrap other models. This base class can be used to implement model wrappers that turn models into new models, for example by preprocessing the ...
from jinja2 import Template import bot_logger import lang import models def help_user(msg): user = models.User(msg.author.name) if user.is_registered(): msg.reply(Template(lang.message_help + lang.message_footer).render( username=msg.author.name, address=user.address)) else: b...
#!/usr/bin/env python import sys import random import itertools import ast def nbackseq(n, length, words): """Generate n-back balanced sequences :param n: int How many characters (including the current one) to look back to assure no duplicates :param length: int The total length o...
sir = "mere pere droguri mofturi CamIoane" rime = {} for i in range(len(sir)): if (i == 0 or sir[i - 1] == " "): k = i if (sir[i] == " "): if (rime.get(sir[i - 2:i]) == None): rime[sir[i - 2:i]] = [sir[k:i]] else: rime[sir[i - 2:i]].append(sir[k:i]) ...
import os import sys import cherrypy import ConfigParser import urllib import urllib2 import simplejson as json import webtools import time import datetime import random import pprint from pyechonest import song as song_api, config config.TRACE_API_CALLS=True config.ECHO_NEST_API_KEY='EHY4JJEGIOFA1RCJP' import collec...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ppretredit.ui' # # Created: Mon Jan 11 21:22:20 2010 # by: PyQt4 UI code generator 4.6 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_TrainerEditDlg(object): def setupUi(self, Tra...
import datetime as dt import smtplib import random import pandas import os PLACEHOLDER = "[NAME]" MY_EMAIL = "my_email@gmail.com" MY_PASSWORD = "my_password" LETTER_TO_SEND = "" now = dt.datetime.now() is_day = now.day is_month = now.month data = pandas.read_csv("./birthdays.csv") birthdays = data.to_dict(orient="rec...
# coding=utf-8 import json from ibm_watson import LanguageTranslatorV3 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator authenticator = IAMAuthenticator('your_api_key') language_translator = LanguageTranslatorV3( version='2018-05-01', authenticator=authenticator) language_translator.set_service_u...
# TODO: support axis=k to create multiple factors for each row/col # TODO: knapsack (how to pass costs? must check broadcast/shape) class Logic(object): def __init__(self, variables): self._variables = variables # TODO: deal with negated def _construct(self, fg, variables): return [fg.crea...
import sys import os import numpy as np import shutil from common import PostProcess, update_metrics_in_report_json from common import read_limits, check_limits_and_add_to_report_json #from common import VirtualVehicleMakeMetrics as VVM def main(): print "in main....." sampleRate = 0.10 startAna...
# Algorithms > Warmup > Simple Array Sum # Calculate the sum of integers in an array. # # https://www.hackerrank.com/challenges/simple-array-sum/problem # # # Complete the simpleArraySum function below. # def simpleArraySum(ar): # # Write your code here. # return sum(ar) if __n...
from cached_property import cached_property from onegov.activity import Activity, Attendee, Booking, Occasion from onegov.feriennet import _ from onegov.feriennet import FeriennetApp from onegov.feriennet.collections import BillingCollection, MatchCollection from onegov.feriennet.exports.unlucky import UnluckyExport fr...
# -*- coding: utf-8 -*- """Configurations for slimming simple network. - Author: Curt-Park - Email: jwpark@jmarple.ai """ from config.train.cifar100 import simplenet, simplenet_finetune train_config = simplenet.config regularizer_params = { "REGULARIZER": "BnWeight", "REGULARIZER_PARAMS": dict(coeff=1e-5), ...
# hack to capture stdout to a string, to test it import re import os import subprocess import io import sys from contextlib import contextmanager import filecmp def test_rr_cases(): # now for various combinations of inputs output_file = 'test_output.csv' # test exact round robin case, but just once ...
from gpkit import Model, Variable, VectorVariable, SignomialsEnabled import numpy as np class MST(Model): def setup(self, N): edgeCost = VectorVariable([N, N], 'edgeCost') edgeMaxFlow = VectorVariable([N, N], 'edgeMaxFlow') ...
import pytest from auth import create_jwt_payload @pytest.mark.usefixtures("default_qr_code") def test_qr_exists(client, default_qr_code): code = default_qr_code["code"] graph_ql_query_string = f"""query CheckQrExistence {{ qrExists(qrCode: "{code}") }}""" data = {"query": grap...
import os import time import requests from flask import render_template, request, flash, redirect, url_for, abort from jinja2 import Markup from app import app, PLOTS_FOLDER, UPLOAD_FOLDER from functions import dir_listing, process_images @app.route('/') def home(): return render_template('home.html') @app.ro...
# Packages from sys import argv, exit from os.path import realpath, dirname from flask import Flask from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from flask_sqlalchemy import SQLAlchemy # Local from config import Config path = dirname(realpath(__file__)) secret = "%s/app/app.secre...
#! /usr/bin/env python from __future__ import print_function from builtins import str import sys import os from vmrunner import vmrunner import socket # Get an auto-created VM from the vmrunner vm = vmrunner.vms[0] def UDP_test(trigger_line): print("<Test.py> Performing UDP tests") HOST, PORT = "10.0.0.55", 4242...
#!/usr/bin/python3 spam = ['apples', 'bannanas', 'tofus', 'cats'] length = len(spam) item = 0 while item < length - 1: print(spam[item], end=' ') item = item + 1 print(' and ' + spam[item])
from SOC.models import Manna import numpy as np import pytest def test_boundary_shape(): sim = Manna(L=10) assert sim.values.shape == (12, 12) assert sim.L_with_boundary == 12 def test_run_abel(): sim = Manna(L=20) sim.run(5) def test_run_nonabel(): sim = Manna(L=20, abelian = False) sim....
# Copyright 2020 PerfKitBenchmarker Authors. 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. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
# Code adapted from https://github.com/araffin/learning-to-drive-in-5-minutes/ # Author: Sheelabhadra Dey import argparse import os import time from collections import OrderedDict from pprint import pprint import numpy as np import yaml from stable_baselines.common import set_global_seeds from stable_baselines.common....
# -*- coding: utf-8 -*- # MegEngine is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTI...
from glue.config import DictRegistry __all__ = ['viewer_registry', 'ViewerRegistry'] class ViewerRegistry(DictRegistry): """ Registry containing references to custom viewers. """ def __call__(self, name=None): def decorator(cls): self.add(name, cls) return cls ...
# -*- coding: utf-8 -*- ''' Code List Object =============== ''' from __future__ import annotations __all__ = ('CodeList',) from typing import Tuple from builder.commands.scode import SCode from builder.datatypes.builderexception import BuilderError from builder.utils import assertion from builder.utils.logger impo...
# import logging from xml.etree import ElementTree as ET import lxml.etree as LET from ckeditor.fields import RichTextField from acdh_tei_pyutils.tei import TeiReader from curator.models import Upload # Create your models here. from django.db import models from django.utils.timezone import now from .namespaces import ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings import django_fsm.db.fields.fsmfield class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
from pycket.interpreter import ( App, Begin, Begin0, BeginForSyntax, CaseLambda, Cell, CellRef, DefineValues, If, Lambda, Let, Letrec, LexicalVar, Module, ModuleVar, LinkletVar, Quote, QuoteSyntax, Require, SetBang, ToplevelVar, Va...
# -*- coding: UTF-8 -*- """ @CreateDate: 2021/07/25 @Author: Xingyan Liu @File: builder.py @Project: stagewiseNN """ import os import sys from pathlib import Path from typing import Sequence, Mapping, Optional, Union, Callable import logging import pandas as pd import numpy as np from scipy import sparse import scanpy ...
# A import performance test of standard classes, dataclasses, attrs, and cluegen import sys import time standard_template = ''' class C{n}: def __init__(self, a, b, c, d, e): self.a = a self.b = b self.c = c self.d = d self.e = e def __repr__(self): return f'C{...
from __future__ import print_function from __future__ import division from collections import defaultdict, OrderedDict from itertools import izip import numbers from time import time import itertools import math import scipy.sparse as sparse import sklearn from sklearn.base import BaseEstimator from sklearn.ensemble i...
# -*- encoding: utf-8 -*- text = u""" Mr. Speaker, Mr. President, distinguished Members of the Congress, honored guests, and fellow citizens: I come before you to report on the state of our Union, and I'm pleased to report that after 4 years of united effort, the American people have brought forth a nation renewed, s...
# # PySNMP MIB module HUAWEI-SEP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-SEP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:36:43 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2...
import unittest import unittest.mock import denonavr.__main__ as avr class TestDenonAVR(unittest.TestCase): def test_valid_input_source(self): self.assertTrue(avr._is_valid_input_source("DVD")) self.assertTrue(avr._is_valid_input_source("BD")) self.assertTrue(avr._is_valid_input_source("G...
from ...hek.defs.obje import * def get(): return obje_def # replace the model animations dependency with an open sauce one obje_attrs = dict(obje_attrs) obje_attrs[8] = dependency('animation_graph', valid_model_animations_yelo) obje_body = Struct('tagdata', obje_attrs ) obje_def = TagDef("o...
class Coordenadas(): def __init__(self, coordenadaX , coordenadaY): self.coordenadaX = coordenadaX self.coordenadaY = coordenadaY def valores(self): print("Los valores ingresados fueron:","(" , self.coordenadaX,",", self.coordenadaY ,")") def cuadrante(self): if...
import sys import unittest import os script_dir = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(1, os.path.abspath( os.path.join(script_dir, os.path.join('..', '..')))) import pake class SubpakeTest(unittest.TestCase): def file_helper_test_stub(self, ctx, silent): fp = pake.FileHelp...
import sys import re def main(): file = sys.stdin if file.isatty(): filename = input('Input file name: ') file = open(filename) rules = file.readlines() file.close() bags = parseRules(rules) shinyGoldBag = bags['shiny gold'] shinyGoldContainers = shinyGoldBag.findCont...
import copy import logging import os import typing import yaml from nbcollection.ci.constants import ENCODING, SCANNER_ARTIFACT_DEST_DIR from nbcollection.ci.generate_ci_environment.constants import NBCOLLECTION_BUILDER, CONFIG_TEMPLATE, JOB_TEMPLATE, \ PULL_REQUEST_TEMPLATE, NBCOLLECTION_WORKFLOW_NAME, PUBLIS...
""" protonate.py: Wrapper method for the reduce program: protonate (i.e., add hydrogens) a pdb using reduce and save to an output file. Pablo Gainza - LPDI STI EPFL 2019 Released under an Apache License 2.0 """ from subprocess import Popen, PIPE import os from ipdb import set_trace def protonate(in_...
import collections import logging from arekit.common.data.input.providers.opinions import OpinionProvider logger = logging.getLogger(__name__) class BaseRowProvider(object): """ Base provider for rows that suppose to be filled into BaseRowsStorage. """ # region protected methods def _provide_rows(...
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') requirements = [ 'pan-python', ] test_requirements = [ 'pan-pyt...
class Activation(object): def __init__(self): pass from deepend.activations.Softmax import Softmax from deepend.activations.LeakyReLU import LeakyReLU from deepend.activations.Linear import Linear from deepend.activations.TanH import TanH from deepend.activations.Sigmoid import Sigmoid from deepend.activations.ReLU...
"""Exemplo melhorias de Contraste.""" from PIL import Image, ImageEnhance im = Image.open('beijo.jpg') contrast = ImageEnhance.Contrast(im) contrast.enhance(1.2) contrast.show()
#!/usr/bin/python ############################ # Librairies import ############################ import os import checkUserInput ############################ # Functions ############################ def confirmation_address(address, what): confirmation = False if checkUserInput.question_and_verification("Confirmez...
# -*- python -*- import logging import unittest import electionfraud.testdata as eftd import electionfraud.redist as redist logging.basicConfig(level=logging.DEBUG) class RedistributorTest(unittest.TestCase): pass class TestIdentity(RedistributorTest): def setUp(self): self.rd = redist.Identity(ef...
#%% cell """ # Solving a New Keynesian model with Python This file is part of a computational appendix that accompanies the paper. > MATLAB, Python, Julia: What to Choose in Economics? > > Coleman, Lyon, Maliar, and Maliar (2017) In order to run the codes in this file you will need to install and configure a few Pyt...
arr = [1, 34, 3, 98, 9, 76, 45, 4] l = len(arr) digits =[] # # Uncomment and use either of the 2 digitconverter # def digitconverter(num): # # digit = [] # while num !=0: # digits.append(num%10) # num = num//10 # def digitconverter(num): # number = str(num) # for i in ra...
from rest_framework.serializers import ModelSerializer from rest_framework_gis.serializers import GeoFeatureModelSerializer from .models import IdentifiedBaseStation, Operator class IdentifiedBaseStationSerializer(GeoFeatureModelSerializer): class Meta: model = IdentifiedBaseStation geo_field = '...
#!/usr/bin/env python # -*- coding: utf-8 -*- import pathlib import pickle import yaml import numpy as np from librosa import load from tools import yaml_loader __author__ = 'Konstantinos Drossos -- Tampere University' __docformat__ = 'reStructuredText' __all__ = [ 'dump_pickle_file', 'load_pickle_file', 'read_t...
# Generated by Django 3.2.7 on 2021-09-17 12:44 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Course', '0001_initial'), ] operations = [ migrations.CreateModel( name='LearnGroup', fields=[ ('id'...
import gym import copy env = gym.make('LunarLander-v2') env.seed(111) # we cna fix the background for now env.action_space.np_random.seed(123) #fix random actions for now env.reset() for step in range(60): #input() env.render() #save info before action if step == 55: save_state = copy.copy(info)...
import asyncio import inspect import warnings import functools from typing import Callable, Generic, TypeVar, Type, Optional def deprecated(reason, stacklevel=2) -> Callable: """ This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the f...
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) import os from spack.package import * class HashTest3(Package): """Used to test package hashing """ homepa...
""" Yandex Transport Webdriver API. Continuous Monitoring tests. NOTE: These are designed to run indefinitely and check current YandexTransportAPI status. Tests are working with Live Data, with several random delays between them. They take a lot of time as a result. NOTE: Tests require running YandexTrans...
from __future__ import ( absolute_import, unicode_literals, ) import importlib import os import pytest @pytest.fixture(scope='module') def server_settings(server_class): """ Load the server_settings used by this service. """ if server_class.use_django: from django.conf import setting...
#! /usr/bin/env python3 from setuptools import find_packages from setuptools import setup def parse_requirements(filename): """Given a filename, strip empty lines and those beginning with #.""" with open(filename) as rfd: output = [] for line in rfd: line = line.strip() ...
import torch from allennlp.common.testing import AllenNlpTestCase from allennlp.common.params import Params from allennlp.training.learning_rate_schedulers import ( LearningRateScheduler, CombinedLearningRateScheduler, PolynomialDecay, ) from allennlp.training.optimizers import Optimizer class TestCombin...
#!/usr/bin/python3 for i in range(122, 96, -1): if i % 2 == 0: print("{:s}".format(chr(i)), end="") else: print("{:s}".format(chr(i-32)), end="")
# -*- coding: utf-8 -*- ## @package palette.main # # Main funcion. # @author tody # @date 2015/08/20 from palette.datasets.google_image import createDatasets from palette.results.single_image import signleImageResults from palette.results.multi_images import multiImagesResults if __name__ == '__main__'...
import torch import torch.nn as nn from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence class RNN(nn.Module): def __init__(self, config): """ type_rnn: RNN, GRU, LSTM 可选 """ super(RNN, self).__init__() # self.xxx = config.xxx self.input_size = c...
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config: SECRET_KEY = os.environ.get('SECRET_KEY') or '28#oN^^VfhcxV7x8H32yGOGIk2wLY%OFi!!V' ### email configs,https://pythonhosted.org/Flask-Mail/ ### MAIL_SERVER = os.environ.get('MAIL_SERVER') MAIL_PORT = int(os.environ.get('MA...
# 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 # distributed under t...
import os import sys sys.path.append( os.path.normpath( os.path.join(os.path.abspath(__file__), "..", "..", "..", "common") ) ) from env_indigo import * indigo = Indigo() indigo.setOption("ignore-stereochemistry-errors", True) indigo.setOption("molfile-saving-skip-date", True) def testSerializeIsoto...
import arrow import dateutil import requests COUNTRY_CODE = 'RO' def fetch_RO(): url = 'http://www.transelectrica.ro/sen-filter' data = {} for item in requests.get(url).json(): d = list(item.iteritems())[0] data[d[0]] = d[1] obj = { 'countryCode': COUNTRY_CODE, 'da...
from claf.config.factory.data_reader import DataReaderFactory from claf.config.factory.data_loader import DataLoaderFactory from claf.config.factory.model import ModelFactory from claf.config.factory.optimizer import OptimizerFactory from claf.config.factory.tokens import TokenMakersFactory __all__ = [ "DataRead...
import os import shutil from datetime import datetime from os.path import dirname, join import torch class Logger(): def __init__(self, para): self.para = para now = datetime.now() if 'time' not in vars(para) else para.time now = now.strftime("%Y_%m_%d_%H_%M_%S") mark = para.model...
############################################################################### # Exceptions ############################################################################### class UnexpectedCharacter(Exception): def __init__(self, char, idx, matcher): super().__init__( 'Expected {} at position ...
from ex112_1.utilidadescev import moeda, dados preco = dados.leiadinheiro('Digite o preço: ') moeda.resumo(preco, 90, 35)
#!/usr/bin/env python3 """ Filters for masking stationary or near stationary data based on vessel speed """ def mask_stationary(Sv, speed, threshold): """ Mask stationary or near stationary data based on vessel speed Args: Sv (float): 2D numpy array with Sv data to be masked (dB) spee...
# TemperatureConverter Tests import unittest from TemperatureConverter import TemperatureConverter from TemperatureErrors import * class KnownValues(unittest.TestCase): knownValues = ( (0, 32), (100, 212) ) temp_converter = TemperatureConverter() # test value conversions def testCtoF(self): ""...
# Reads float and prints BRL money conversion to JPY # In 2020/11/01 JP¥ 1.00 = R$ 0.060 :) brl = float(input('Por favor, digite quanto dinheiro você tem na carteira: R$ ')) jpy = brl / 0.060 print('Com R$ {:.2f} você pode comprar ¥ {:.2f}.'.format(brl, jpy))
def print_error(message): print("An error occured: " + message) def remove_white_chars(line): line = line.replace('\t', '') line = line.replace(' ', '') line = line.replace('\n', '') line = line.replace('\r', '') return line def remove_comments_and_empty_lines(text): new_text = '' fi...
import os import logging from dp4py_config.section import Section from dp4py_config.utils import bool_env from dp4py_sanic.config import CONFIG as SANIC_CONFIG from dp_conceptual_search.config.utils import read_git_sha def get_log_level(variable: str, default: str="INFO"): """ Returns the configured log le...
from federatedscope.tabular.model.quadratic import QuadraticModel __all__ = ['QuadraticModel']
string = """0: "HOW ResidentSleeper LONG ResidentSleeper CAN ResidentSleeper THIS ResidentSleeper GO ResidentSleeper ON ResidentSleeper" 1: "REPPIN LONDON ONTARIO 519 GANG" 2: "my eyes" 3: "CLULG" 4: "ResidentSleeper" 5: "mvp ward" 6: "4Head EU WATCHING NA 4Head STILL AWAKE 4Head NO JOB 4Head NO RESPONSIBILITIES 4Head ...
# Copyright 2015 Tesora Inc. # 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. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by a...
from reading import Maze, MazeReader class Node(object): """Nodes for evolving in graph.""" def __init__(self, maze, x, y, parent=None): """Initialize node. Keep maze, parent, and position.""" self.maze = maze self.x = x self.y = y self.parent = parent self.up = ...
import pyps from sys import argv if len(argv) == 1: # this source include a main() with a call to foo() ; but foo() isn't defined ! w=pyps.workspace("broker01.c") # We give a method to resolve missing module (here foo()) w.props.preprocessor_missing_file_handling="external_resolver" w.props.pre...
from typing import Any, Dict, Tuple from dateutil.parser import parse from great_expectations.execution_engine import PandasExecutionEngine from great_expectations.execution_engine.execution_engine import ( MetricDomainTypes, MetricPartialFunctionTypes, ) from great_expectations.expectations.metrics.map_metri...
from authlib.common.urls import quote, unquote def escape(s): return quote(s, safe=b'~') def unescape(s): return unquote(s)
import json from typing import Optional import pyrebase from .database import Database class FirebaseDatabase(Database): def __init__(self, serialised_config: str): super().__init__() self.config = json.loads(serialised_config) def add_document(self, doc_id: str, doc: dict) -> None: ...
from .s3 import *
#!/usr/bin/env python3 """ Get jobs from aCT. Returns: 1: No proxy found. 2: One of the elements in job list is not a range. 3: One of the elements in job list is not a valid ID. 5: tmp directory not configured. """ import argparse import sys import shutil import os import logging import act.client...
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="Turkish Topic Model", version="0.0.1", author="Ali ÇİMEN, Sevinç GÜLSEÇEN", author_email="cimenwd@gmailcom, gulsecen@istanbul.edu.tr", description="Türkçe metin ön işleme ve konu analizi k...
import pandas from sklearn.model_selection import train_test_split def add_series(X, y, name): """Converts list (y) to pd.Series with name (name) then adds it to a dataframe (X)""" X = X.copy() series = pandas.Series(data=y, name=name) X[name] = series return X def data_split(X): """Spl...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models import re class ResCompany(models.Model): _inherit = 'res.company' org_number = fields.Char(compute='_compute_org_number') @api.depends('vat') def _compute_org_num...
import numpy as np from ..functions import B_nu, dB_nu_dT from ..integrate import integrate_loglog from ..constants import sigma, k, c def test_b_nu(): nu = np.logspace(-20, 20., 10000) for T in [10, 100, 1000, 10000]: # Compute planck function b = B_nu(nu, T) # Check that the int...
"""Myia Pytorch frontend.""" from .pytorch import *
""" Dictionary Embedder Class """ import spacy from .base import BaseEmbedder class DictionaryEmbedder(BaseEmbedder): """Base Embedder class extended for implementing text embedders""" def __init__(self, spacy_pkg='en_vectors_web_lg', embedding_length=None): super(DictionaryEmbedder, self).__init__...
# -*- coding: utf-8 -*- """Tests for Terminal methods that account for sequences in strings""" # std imports import os import sys import struct import platform import itertools # 3rd party import six import pytest # local from .accessories import TestTerminal, as_subprocess from .conftest import IS_WINDOWS if platf...
def get_token(fi='dont.mess.with.me'): with open(fi, 'r') as f: return f.readline().strip() t = get_token()
import re from address_extractor import ( unit_type, zipcode, street_direction, street_type, cities, ) class InvalidAddressError(Exception): pass class Address(object): def __init__(self, tokens): self.tokens = tuple(self._clean_tokens(tokens[:11])) self.street_number_ind...
import os.path from newsplease.pipeline.pipelines.elements.extracted_information_storage import ExtractedInformationStorage class HtmlFileStorage(ExtractedInformationStorage): """ Handles storage of the file on the local system """ # Save the html and filename to the local storage folder def pro...
import json from decimal import Decimal import jwt from django.core import mail from mock import patch from nose.tools import eq_, ok_ from amo import CONTRIB_PENDING, CONTRIB_PURCHASE from amo.tests import TestCase from amo.urlresolvers import reverse from constants.payments import PROVIDER_BANGO from market.models...