text
stringlengths
2
999k
# Copyright 2021 AI Singapore # # 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...
#!/usr/bin/env python3 # Copyright (c) 2016-2019 The Eozi Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test processing of feefilter messages.""" from decimal import Decimal import time from test_framework.me...
"""Create a dummy database just to simulate regen.""" import pandas as pd import random from sqlalchemy import create_engine engine = create_engine( "postgresql://murabei:is_very_nice!@localhost/murabei") pd.read_sql("SELECT 1;", con=engine) ################### # Create database # var1 = ["murabei", "is", "the",...
# -*- coding: utf-8 -*- # from os import path, walk import rdflib from rdflib.namespace import Namespace, RDF, RDFS MF = Namespace('http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#') SHT = Namespace('http://www.w3.org/ns/shacl-test#') class SHTValidate(object): def __init__(self, node, sht_graph, result_...
#BEWARE: automatically generated code #This code was generated by /generate/__main__.py from opengl.gl.raw.bindings import * @accepts(t.enum, t.enum, t.enum, t.enum) @returns(t.void) @binds(dll) def blend_func_separate(sfactorrgb, dfactorrgb, sfactoralpha, dfactoralpha): ''' specify pixel arithmetic for RGB a...
#!/usr/bin/env python3 # Copyright (c) 2014-2020 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test descendant package tracking carve-out allowing one final transaction in an otherwise-full packa...
class CPF(object): INVALID_CPFS = ['00000000000', '11111111111', '22222222222', '33333333333', '44444444444', '55555555555', '66666666666', '77777777777', '88888888888', '99999999999'] def __init__(self, cpf): self.cpf = cpf def validate_size(self): cpf = self.cleaning...
"""An example of an evolutionary algorithm with a basic real-vectored solution representation, and that logs several diversity metrics from the population to its CSV output. We use a generational EA with Gaussian mutation of 2-D genomes to minimize the Langermann function. """ import os import sys from matplotlib imp...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.FileItem import FileItem from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.AlipayTradePageRefundModel import AlipayTradePageRefundModel class AlipayTradePageRefundRequest(object): def __init__(self, biz...
# -*- coding: utf-8 -*- ### Generates J and D factor table for Evans, Sanders & Geringer-Sameth (2016) import numpy as np import matplotlib.pyplot as plt import seaborn as sns import pandas as pd from scipy.special import gamma as Gamma from spherical_Jfactors import * ### A set of strings to convert pandas table name...
from functools import partial import numpy as _np from scipy.linalg import lstsq as _lstsq from scipy.linalg import cho_factor as _cho_factor from scipy.linalg import cho_solve as _cho_solve from scipy.sparse.linalg import LinearOperator from netket.stats import sum_inplace as _sum_inplace, mean as _mean from scipy.spa...
import torch from torch.autograd import Variable from torch.autograd import Function import numpy as np import scipy.linalg class MatrixSquareRoot(Function): """Square root of a positive definite matrix. NOTE: matrix square root is not differentiable for matrices with zero eigenvalues. """ @...
# Classification (U) """Program: elastic_class.py Description: Class definitions and methods for an Elasticsearch cluster, Elasticsearch cluster dump, Elasticsearch cluster repository, and Elasticsearch cluster status. Includes supporting functions for the classes. Functions: ...
import cv2 import numpy as np tmp_file_idx = 0 # 这个类每次进行预处理的时候都会重新声明,所以init每次预处理都会执行,随机数并不会被固定 class VideoTransform(): def __init__(self, size, flip_p=0.5, # 反转概率 mean=127, # 通道均值 std=1., horizontal_flip= False, # 随机水平翻转 vertica...
# pylint: disable=g-bad-file-header # pylint: disable=superfluous-parens # Copyright 2017 The Bazel 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:/...
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # This is all.gyp file for Android to prevent breakage in Android and other # platform; It will be churning a lot in the short term and eventually be mer...
from rest_framework import serializers from .models import Profile,Projects class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('user','profile_photo','bio') class ProjectsSerializer(serializers.ModelSerializer): class Meta: model = Proj...
#!/usr/bin/env python3 from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * from test_framework.script import * from test_framework.mininode import * from test_framework.crt import * from test_framework.address import * import time class CrowntiumManyValueRefundsFromSameTxT...
# Copyright 2019 The TensorFlow 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 applica...
import numpy as np def get_template_average(template, beam): """ Calculate the (beam-weighted) average of the lightcurve template <F>. template.shape => (t,) beam.shape => (x, y, t) output.shape => (x, y) where t is the number of time samples, (x, y) is the image dimension. """ retu...
import cv2 import tensorflow as tf import numpy as np from tensorflow.keras.preprocessing import image eye = {1:'Closed',0:'Open'} eyes_cascade = cv2.CascadeClassifier('haarcascade_eye.xml') face_cascade = cv2.CascadeClassifier('haarcascade_face.xml') try: model = tf.keras.models.load_model('eye.h5') except OSEr...
import pytest import logging from ocs_ci.ocs import constants from ocs_ci.ocs.resources import pod from ocs_ci.framework.testlib import ManageTest, tier2 log = logging.getLogger(__name__) @tier2 class TestCreateLargeSizedPVCWhileIOInProgress(ManageTest): """ Create large sized PVC while IO is in progress ...
#!/usr/bin/env python """ Classes in ELF files """ import os import sys import lib_uris import lib_elf import lib_util import lib_common from lib_properties import pc Usable = lib_util.UsableLinuxBinary def Main(): paramkey_max_depth = "Maximum depth" cgiEnv = lib_common.ScriptEnvironment( param...
from __future__ import print_function import sys import random import MusicTheory TSERhythmInfo = { '3/16' : {}, '3/8' : {}, '4/8' : {}, '5/8' : {}, '6/8' : {}, '7/8' : {}, '9/8' : {}, '11/8' : {}, '12/8' : {}, '13/8' : {}, ...
import time from DBUtils.PooledDB import PooledDB import pymysql from pymysql.cursors import DictCursor from datasets.data_utils.db.dbconfig import DBConfig """ urls:flag 0-爬虫已爬取到 1-可以下载 2-下载损坏 download_record:flag 0-已下载未处理 1-无损坏 2-无重复 -1-损坏或者重复图片 """ class ConnPool: __pool = None def __new__(cls, *args,...
# -*- coding: utf-8 -*- """DNACenterAPI tag API fixtures and tests. Copyright (c) 2019-2021 Cisco Systems. 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 l...
# a set of NLP functions that can be used for text processing # Created by Tony HAO, th2510@columbia.edu from nltk import word_tokenize from nltk import pos_tag import re # separate a phrase into words def word_splitting(phrase): words = word_tokenize(phrase) return words # POS tagging def word_pos_tagging(words...
# Copyright 2020 The StackStorm Authors. # Copyright 2019 Extreme Networks, 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 ...
from django.contrib.auth import get_user_model from rest_framework.permissions import BasePermission, SAFE_METHODS class IsOwnerOnly(BasePermission): # https://ssungkang.tistory.com/entry/Django-APIView%EC%97%90-permission-%EC%A7%80%EC%A0%95%ED%95%98%EA%B8%B0 # 작성자만 접근 def has_object_permission(self, reque...
import bpy from bpy.props import * from bpy.types import Node, NodeSocket from arm.logicnode.arm_nodes import * class GlobalObjectNode(Node, ArmLogicTreeNode): '''Global object node''' bl_idname = 'LNGlobalObjectNode' bl_label = 'Global Object' bl_icon = 'GAME' def init(self, context): ...
import random import math import numpy as np from collections import deque from game.helpers.point import Point from game.environment.action import Action from game.environment.tile import Tile from game.helpers.constants import Constants class Environment: snake = [] fruit = [] wall = [] snake_mov...
""" @name: syn_size_violoin.py @description: plot distribution of synapse sizes @author: Christopher Brittin @email: "cabrittin"+ <at>+ "gmail"+ "."+ "com" @date: 2020-03 """ import os import argparse from configparser import ConfigParser,ExtendedInterpolation import pandas as pd import seaborn as sns import matp...
#Sen Zhou 12.8.14 #define how to parse URLs like EE_Building/3F/ROOM318#near(0,1,2)&inside(3F), #(, ), &, |, are preserved key words #priority | < & < ~ #any kind of spaces, tabs or "\n" are not allowed in URL import sys, traceback, os sys.path.append(os.path.join(os.path.dirname(__file__), "./pyparsing")) from con...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import unittest from reportlab.lib.units import cm from reportlab.lib import pagesizes from reportlab.lib.styles import getSampleStyleSheet from reportlab.platypus import \ Frame, Paragraph, PageTemplate, BaseDocTemplate from reportlab...
import sqlite3 import requests import json from datetime import datetime import datetime import pandas as pd import sqlalchemy from sqlalchemy.orm import sessionmaker import auth # Transform def check_if_valid(df: pd.DataFrame) -> bool: # Check if dataframe is empty if df.empty: print('No songs downloa...
import urllib from vsmclient import base class License(base.Resource): """""" def __repr__(self): return "<License: %s>" % self.id def delete(self): """Delete this vsm.""" self.manager.delete(self) def update(self, **kwargs): """Update the display_name or display_des...
""" *String Lining* String lining graphically decorates a string with a line. """ from enum import Enum from .._geometra import StringGeometra __all__ = ["StringLining"] class StringLining( Enum, StringGeometra, ): Underline = "Underline" Overline = "Overline" LineThrough = "LineThroug...
from .fields import * from .middlewares import * __all__ = fields.__all__ + middlewares.__all__ __version__ = '0.0.4'
import GPy from util import data_validation from . import likelihood as lh import numpy as np from .sensormodel import SensorModel from ..sampling import sampling from util.others import mesh import scipy class GPcore(SensorModel): """ Base class for GP-based mappings. Each inherited class needs to impleme...
from datetime import timedelta from django import forms from django.utils.translation import ugettext_lazy as _ class PepExportForm(forms.Form): def clean(self): cleaned_data = super().clean() updated_at = cleaned_data.get('updated_at', None) if updated_at is None or updated_at.start is N...
# Crie um programa que leia a idade e o sexo de várias pessoas. A cada pessoa cadastrada, # o programa deverá perguntar se o usuário quer ou não continuar. No final, mostre: # A) quantas pessoas tem mais de 18 anos. # B) quantos homens foram cadastrados. # C) quantas mulheres tem menos de 20 anos. cores = {'limpa':'...
#!/usr/bin/env python3 # McDermott # March 2020 # first, make sure the macfp module directory is in your path # if not, uncomment the lines below and replace <path to macfp-db> # with the path (absolute or relative) to your macfp-db repository import sys # sys.path.append('<path to macfp-db>/macfp-db/Utilities/') sys...
# -*- coding: utf-8 -*- from .store import Store
#!/usr/bin/env python # # Copyright (C) 2009 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 ...
# -*- coding: utf-8 -*- # Copyright 2013 Google 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 require...
from __future__ import absolute_import, division, print_function from scitbx.array_family import flex from cctbx import miller from cctbx.development import random_structure from cctbx.sgtbx import space_group_info import boost_adaptbx.boost.python as bp asu_map_ext = bp.import_ext("cctbx_asymmetric_map_ext") from mmtb...
from pylab import plot, draw, pause from numpy import arange, sin, pi from time import time x = arange(0, 2 * pi, 0.01) tstart = time() line, = plot(x, sin(x)) for i in arange(1, 200): line.set_ydata(sin(x + i / 10.0)) draw() pause(0.001) fps_mpl = int(200 / (time() - tstart)) print('fps (mpl): %4d' % f...
# # @file TestSBMLDocument.py # @brief SBMLDocument unit tests # # @author Akiya Jouraku (Python conversion) # @author Ben Bornstein # # ====== WARNING ===== WARNING ===== WARNING ===== WARNING ===== WARNING ====== # # DO NOT EDIT THIS FILE. # # This file was generated automatically by converting the file loca...
from django.shortcuts import render import requests # Create your views here. from rest_framework.response import Response from rest_framework.views import APIView from .config import open_weather def get_from_service(request, service): city = request.GET['city'] api_url = service['api_url'] token = servi...
#!/usr/bin/env python # This software is Copyright (c) 2017, Dhiru Kholia <dhiru.kholia at gmail.com> # and it is hereby released under GPL v2 license. # # Major parts are borrowed from the "btcrecover" program which is, # Copyright (C) 2014-2016 Christopher Gurnee and under GPL v2. # # See https://github.com/gurnec/b...
# # PySNMP MIB module NBS-PART-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NBS-PART-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:07:38 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019,...
import base64 import hashlib import json import os import pathlib import requests import secrets import threading import urllib import webbrowser from time import sleep from werkzeug.serving import make_server import dotenv from flask import Flask, request # Load Settings from dotenv env_path = pathlib.Path('.') / ...
# # -*- coding: utf-8 -*- # # Copyright (c) 2019, reworq and contributors # # For license information, please see license.txt # from __future__ import unicode_literals # import frappe # from frappe.model.document import Document # import requests # import json # class IPRS(Document): # def validate(self): # self.c...
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2022, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #-------------------------------------------------------------------...
from rest_framework import viewsets, permissions,generics from registration.models import User from .serializers import UserSerializer # class UserViewSet(viewsets.ModelViewSet): # queryset = User.objects.all() # permission_classes = [permissions.AllowAny, ] # serializer_class = UserSerializer # # de...
# Copyright 2014-present PlatformIO <contact@platformio.org> # # 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 applicabl...
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)` tests.unit.config_test ~~~~~~~~~~~~~~~~~~~~~~ ''' # Import python libs import logging import os import shutil import tempfile from contextlib import contextmanager # Import Salt Testing libs from salttesting import Test...
from flask_restful import Resource, reqparse from models import db, ApiKeys from requests import get import datetime import secrets import config from decorators import restricted_api, admin_api import errors import logging logger = logging.getLogger("api") class ApiKey(Resource): @restricted_api def get(self):...
# Copyright (c) Microsoft. All rights reserved. # Licensed under the MIT license. See LICENSE file in the project root for # full license information. import gc import inspect import os import weakref import time import logging import importlib logger = logging.getLogger(__name__) def _run_garbage_collection(): ...
# Autogenerated from KST: please remove this line if doing any edits by hand! import unittest from nav_parent_vs_value_inst import NavParentVsValueInst class TestNavParentVsValueInst(unittest.TestCase): def test_nav_parent_vs_value_inst(self): with NavParentVsValueInst.from_file('src/term_strz.bin') as r...
""" Making a surface plot of a 3D statistical map ============================================= project a 3D statistical map onto a cortical mesh using :func:`nilearn.surface.vol_to_surf`. Display a surface plot of the projected map using :func:`nilearn.plotting.plot_surf_stat_map` and adding contours of regions of in...
""" Routines for filling missing data. """ import numpy as np from pandas._libs import algos, lib from pandas.compat._optional import import_optional_dependency from pandas.core.dtypes.cast import infer_dtype_from_array from pandas.core.dtypes.common import ( ensure_float64, is_datetime64_dtype, is_datet...
"""Global variables for pynetdicom.""" from typing import List, Optional, Union from pydicom.uid import UID # The default Maximum PDU Length (in bytes) # Must be 0 or greater than 7. # A value of 0 indicates unlimited maximum length DEFAULT_MAX_LENGTH: int = 16382 # DICOM Application Context Name - see Part 7, Ann...
# Generated by Django 3.2 on 2021-04-24 02:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('library', '0007_alter_book_image'), ] operations = [ migrations.AddField( model_name='book', name='times_borrowed', ...
import random a = ([[4,9],[8.5,10],[5,9],[8.5,9.5],[3,7],[4,9],[3,8],[7.5,8],[5,9],[0,6]]) b = ([[5,10],[4,4],[7,9],[2,8],[6,9.5],[8.5,10],[8,10],[0,7],[3,9],[0,3]]) c = ([[4,7],[6,8],[6,9],[6.5,9],[2,6],[6.5,9],[5.5,9],[9.5,9.5],[5,9],[4,9]]) def Monte_carlo (rango_calidad): variables=['dinero', 'ubicac...
from icalendar.cal import ( Calendar, Event, Todo, Journal, Timezone, TimezoneStandard, TimezoneDaylight, FreeBusy, Alarm, ComponentFactory, ) # Property Data Value Types from icalendar.prop import ( vBinary, vBoolean, vCalAddress, vDatetime, vDate, vDDDTy...
# This file is part of REANA. # Copyright (C) 2019 CERN. # # REANA is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """REANA Workflow Controller Kubernetes utils.""" import os from kubernetes import client from kubernetes.client.rest ...
import sqlite3 from fifobasic import FifoBasic class DbCommunication(object): def create_connection(self, db_name): """sets connection with given database file""" conn = sqlite3.connect(db_name) print("Utworzono połączenie z: ", db_name, "\n") return conn def check_if_tab...
r""" =============================================================================== Submodule -- throat_shape_factor =============================================================================== """ import scipy as _sp def compactness(geometry, throat_perimeter='throat.perimeter', throat_area='thr...
from django.test import TestCase from django.contrib.auth.models import User from rest_framework.authtoken.models import Token class ParticipantRegistrationTestCase(TestCase): def setUp(self) -> None: usr = User.objects.create_user(username = "12thMan", email = "twelve@testtamu.edu", password = "SomePassw...
""" Copyright (c) 2017, 2020 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ __version__ = "1.6.51"
import re import unittest import pkg_resources import ctds from .compat import PY27, StandardError_ class TestTds(unittest.TestCase): maxDiff = None def test_version(self): self.assertEqual( tuple(int(item) for item in ctds.__version__.split('.')), ctds.version_info ...
# # Copyright (C) 2007, 2008 Google Inc. # # Licensed under the Apache License 2.0; """Contains extensions to Atom objects used with Blogger.""" # __author__ = 'api.jscudder (Jeffrey Scudder)' import re import atom import gdata LABEL_SCHEME = 'http://www.blogger.com/atom/ns#' THR_NAMESPACE = 'http://purl.org/syn...
# Copyright (c) OpenMMLab. All rights reserved. import os.path as osp import mmcv import numpy as np import pycocotools.mask as maskUtils from mmdet.core import BitmapMasks, PolygonMasks from ..builder import PIPELINES try: from panopticapi.utils import rgb2id except ImportError: rgb2id = None @PIPELINES.r...
# -*- coding: utf-8-*- import logging import pkgutil import paths class Brain(object): def __init__(self, mic, profile): """ Instantiates a new Brain object, which cross-references user input with a list of modules. Note that the order of brain.modules matters, as the Brain will c...
import vcr from django.test import TestCase, override_settings from content.logic import SentimentCalculate, ParseContent from content.models import Article from content.tests.factories import ArticleFactory VCR_ROOT = "content/tests/fixtures/vcr" class SentimentCalculateTestCase(TestCase): @vcr.use_cassette( ...
#!/usr/bin/env python # Copyright (C) 2013 The Android Open Source Project # # 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 b...
# pylint: disable=missing-docstring from __future__ import absolute_import, division, print_function, unicode_literals import unittest import six from django.contrib.auth import get_user_model from django.contrib.auth.models import AnonymousUser, Group from guardian.shortcuts import assign_perm from guardian.models ...
### # Copyright (c) 2020, oddluck <oddluck@riseup.net> # 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 lis...
import collections import json import logging import sys import irc import regex as re import requests from pajbot.managers.schedule import ScheduleManager from pajbot.modules.ascii import AsciiProtectionModule log = logging.getLogger(__name__) class ActionParser: bot = None def parse(raw_data=None, data=...
########################################################################## # If not stated otherwise in this file or this component's Licenses.txt # file the following copyright and licenses apply: # # Copyright 2016 RDK Management # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use th...
from django.conf.urls import patterns, url urlpatterns = patterns( 'api.mon.base.views', # /mon/template - get url(r'^template/$', 'mon_template_list', name='api_mon_template_list'), # /mon/hostgroup - get url(r'^hostgroup/$', 'mon_hostgroup_list', name='api_mon_hostgroup_list'), # /mon/host...
import numpy as np WALL_LEN = 20.0 NUM_PATHS = 8.0 WALL_FROM_CENTER = 8.0 TARGET_DIST = 25.0 xml_block = '<body mocap=\"true\" pos=\"{x} {y} 1\" euler="0 0 {z_rot}\">\n\ \t<geom type=\"box\" size=\"{wall_len} 0.5 2\" group=\"1\" condim=\"3\" conaffinity=\"1\"/>\n\ </body>' increments = 2*np.pi / NUM_PATHS half_incre...
from pychecker2 import TestSupport from pychecker2 import OpChecks class OpTests(TestSupport.WarningTester): def testOperator(self): for op in ['--', '++']: self.warning('def f(x):\n' ' return %sx' % op, 2, OpChecks.OpCheck.operator, op) ...
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="geniuspy", version="0.0.2", author="Rafael Sánchez Sánchez", author_email="lletfrix@gmail.com", description="A Python wrapper around the Genius API", long_description=long_description,...
from keras.preprocessing import sequence from keras.models import Sequential from keras.layers import Dense, Dropout, Activation from keras.layers import Embedding from keras.layers import GRU from keras.layers import Conv1D, MaxPooling1D from keras.datasets import imdb from sklearn.datasets import fetch_20newsgroups i...
import os class Gmail: WAIT_FLAG = "email" SIGNIN = "/html/body/div/div[2]/div[1]/div/div[2]/div[1]/div/div[1]/a[1]" # EMAIL = "identifier" EMAIL = "#view_container > div > div > div.pwWryf.bxPAYd > div > div.WEQkZc > div > form input[name=identifier]" EMAIL_NEXT = "//*[@id='identifierNext']/span/s...
from django.contrib.auth.models import AbstractUser from django.db.models import CharField from django.urls import reverse from django.utils.translation import ugettext_lazy as _ class User(AbstractUser): """ User model """ # First Name and Last Name do not cover name patterns # around the globe. nam...
#from pymongo import MongoClient import pandas as pd import random from copy import deepcopy #import mysql.connector """ def connect_to_database(): global db mongo_name = "NAME" mongo_password = "PASSWORD" # Connect to the Mongo Database client = MongoClient() db = client.ghtorre...
from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier from sklearn.metrics import mean_squared_error from sklearn.base import BaseEstimator from abc import abstractmethod, ABCMeta import numpy as np from tqdm import tqdm from bolsonaro.models.utils import score_metric_mse, aggregation_regression, ...
""" Utility functions and constants related to writing a table of variable metadata. """ import pprint import numpy as np column_widths = { 'value': 20, 'resids': 20, 'units': 10, 'shape': 10, 'lower': 20, 'upper': 20, 'ref': 20, 'ref0': 20, 'res_ref': 20, } align = '' column_spaci...
import tempfile import os from PIL import Image from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse from rest_framework import status from rest_framework.test import APIClient from core.models import Ingredient, Recipe, Tag from recipe.serializers import ...
from dataclasses import dataclass class Syntax: pass class Term(Syntax): def reduce(self): return self def substitute(self, bindings=None): return self @dataclass(frozen=True) class Assignment(Syntax): name: str term: Term def friendly(self, aliases): if self in aliases:...
''' Created on Jun 21, 2018 @author: fangy5 ''' import argparse import moe import logging from os.path import join def create_parser(): parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description="cifar10") parser.add_argument( '--batch_siz...
import cv2 from imutils.video import WebcamVideoStream from imutils import resize import requests def detect(img, url='http://localhost:5000/detect?landmarks=on&gender=on'): _, img_encoded = cv2.imencode('.jpg', img) resp = requests.post(url, data=img_encoded.tostring()) return resp.json() camera = Webc...
from waffle.admin import FlagAdmin from apps.core.models import Flag from django.contrib import admin admin.site.register(Flag, FlagAdmin)
"""Functions that test the series_sum function.""" def test_one_sum_series_code_wars(): """Function that emulates test.assert_equals(series_sum(1), "1.00") from code wars.""" from sum_terms import series_sum assert series_sum(1) == '1.00' def test_two_sum_series_code_wars(): """Function that emu...
import pysmt.typing as types from pysmt.environment import Environment as PysmtEnv from pysmt.fnode import FNode from utils import symb_to_next def transition_system(env: PysmtEnv) -> (frozenset, FNode, FNode, FNode): assert isinstance(env, PysmtEnv) mgr = env.formula_manager d = mgr.Symbol("d", types.INT...
from collections import defaultdict from itertools import chain import logging from causeway.because_data import CausalityStandoffReader from causeway.tregex_based.tregex_stage import TRegexConnectiveModel from nlpypline.data.io import DirectoryReader from iaa import stringify_connective from nlpypline.util import pri...
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Eric Larson <larson.eric.d@gmail.com> # Oleh Kozynets <ok7mailbox@gmail.com> # Guillaume Favelier <guillaume.favelier@gmail.com> # jona-sassenhagen <jona.sassenhagen@gmail.com> # Joan Massich <mailsik@gmail.com> #...